﻿/*!
* Ext JS Library 3.2.1
* Copyright(c) 2006-2010 Ext JS, Inc.
* licensing@extjs.com
* http://www.extjs.com/license
*/
// for old browsers
window.undefined = window.undefined;

/**
* @class Ext
* Ext core utilities and functions.
* @singleton
*/

Ext = {
	/**
	* The version of the framework
	* @type String
	*/
	version: '3.2.1',
	versionDetail: {
		major: 3,
		minor: 2,
		patch: 1
	}
};

/**
* Copies all the properties of config to obj.
* @param {Object} obj The receiver of the properties
* @param {Object} config The source of the properties
* @param {Object} defaults A different object that will also be applied for default values
* @return {Object} returns obj
* @member Ext apply
*/
Ext.apply = function (o, c, defaults) {
	// no "this" reference for friendly out of scope calls
	if (defaults) {
		Ext.apply(o, defaults);
	}
	if (o && c && typeof c == 'object') {
		for (var p in c) {
			o[p] = c[p];
		}
	}
	return o;
};

(function () {
	var idSeed = 0,
        toString = Object.prototype.toString,
        ua = navigator.userAgent.toLowerCase(),
        check = function (r) {
        	return r.test(ua);
        },
        DOC = document,
        isStrict = DOC.compatMode == "CSS1Compat",
        isOpera = check(/opera/),
        isChrome = check(/\bchrome\b/),
        isWebKit = check(/webkit/),
        isSafari = !isChrome && check(/safari/),
        isSafari2 = isSafari && check(/applewebkit\/4/), // unique to Safari 2
        isSafari3 = isSafari && check(/version\/3/),
        isSafari4 = isSafari && check(/version\/4/),
        isIE = !isOpera && check(/msie/),
        isIE7 = isIE && check(/msie 7/),
        isIE8 = isIE && check(/msie 8/),
        isIE6 = isIE && !isIE7 && !isIE8,
        isGecko = !isWebKit && check(/gecko/),
        isGecko2 = isGecko && check(/rv:1\.8/),
        isGecko3 = isGecko && check(/rv:1\.9/),
        isBorderBox = isIE && !isStrict,
        isWindows = check(/windows|win32/),
        isMac = check(/macintosh|mac os x/),
        isAir = check(/adobeair/),
        isLinux = check(/linux/),
        isSecure = /^https/i.test(window.location.protocol);

	// remove css image flicker
	if (isIE6) {
		try {
			DOC.execCommand("BackgroundImageCache", false, true);
		} catch (e) { }
	}

	Ext.apply(Ext, {
		/**
		* URL to a blank file used by Ext when in secure mode for iframe src and onReady src to prevent
		* the IE insecure content warning (<tt>'about:blank'</tt>, except for IE in secure mode, which is <tt>'javascript:""'</tt>).
		* @type String
		*/
		SSL_SECURE_URL: isSecure && isIE ? 'javascript:""' : 'about:blank',
		/**
		* True if the browser is in strict (standards-compliant) mode, as opposed to quirks mode
		* @type Boolean
		*/
		isStrict: isStrict,
		/**
		* True if the page is running over SSL
		* @type Boolean
		*/
		isSecure: isSecure,
		/**
		* True when the document is fully initialized and ready for action
		* @type Boolean
		*/
		isReady: false,

		/**
		* True if the {@link Ext.Fx} Class is available
		* @type Boolean
		* @property enableFx
		*/

		/**
		* True to automatically uncache orphaned Ext.Elements periodically (defaults to true)
		* @type Boolean
		*/
		enableGarbageCollector: true,

		/**
		* True to automatically purge event listeners during garbageCollection (defaults to false).
		* @type Boolean
		*/
		enableListenerCollection: false,

		/**
		* EXPERIMENTAL - True to cascade listener removal to child elements when an element is removed.
		* Currently not optimized for performance.
		* @type Boolean
		*/
		enableNestedListenerRemoval: false,

		/**
		* Indicates whether to use native browser parsing for JSON methods.
		* This option is ignored if the browser does not support native JSON methods.
		* <b>Note: Native JSON methods will not work with objects that have functions.
		* Also, property names must be quoted, otherwise the data will not parse.</b> (Defaults to false)
		* @type Boolean
		*/
		USE_NATIVE_JSON: false,

		/**
		* Copies all the properties of config to obj if they don't already exist.
		* @param {Object} obj The receiver of the properties
		* @param {Object} config The source of the properties
		* @return {Object} returns obj
		*/
		applyIf: function (o, c) {
			if (o) {
				for (var p in c) {
					if (!Ext.isDefined(o[p])) {
						o[p] = c[p];
					}
				}
			}
			return o;
		},

		/**
		* Generates unique ids. If the element already has an id, it is unchanged
		* @param {Mixed} el (optional) The element to generate an id for
		* @param {String} prefix (optional) Id prefix (defaults "ext-gen")
		* @return {String} The generated Id.
		*/
		id: function (el, prefix) {
			el = Ext.getDom(el, true) || {};
			if (!el.id) {
				el.id = (prefix || "ext-gen") + (++idSeed);
			}
			return el.id;
		},

		/**
		* <p>Extends one class to create a subclass and optionally overrides members with the passed literal. This method
		* also adds the function "override()" to the subclass that can be used to override members of the class.</p>
		* For example, to create a subclass of Ext GridPanel:
		* <pre><code>
		MyGridPanel = Ext.extend(Ext.grid.GridPanel, {
		constructor: function(config) {

		//      Create configuration for this Grid.
		var store = new Ext.data.Store({...});
		var colModel = new Ext.grid.ColumnModel({...});

		//      Create a new config object containing our computed properties
		//      *plus* whatever was in the config parameter.
		config = Ext.apply({
		store: store,
		colModel: colModel
		}, config);

		MyGridPanel.superclass.constructor.call(this, config);

		//      Your postprocessing here
		},

		yourMethod: function() {
		// etc.
		}
		});
		</code></pre>
		*
		* <p>This function also supports a 3-argument call in which the subclass's constructor is
		* passed as an argument. In this form, the parameters are as follows:</p>
		* <div class="mdetail-params"><ul>
		* <li><code>subclass</code> : Function <div class="sub-desc">The subclass constructor.</div></li>
		* <li><code>superclass</code> : Function <div class="sub-desc">The constructor of class being extended</div></li>
		* <li><code>overrides</code> : Object <div class="sub-desc">A literal with members which are copied into the subclass's
		* prototype, and are therefore shared among all instances of the new class.</div></li>
		* </ul></div>
		*
		* @param {Function} superclass The constructor of class being extended.
		* @param {Object} overrides <p>A literal with members which are copied into the subclass's
		* prototype, and are therefore shared between all instances of the new class.</p>
		* <p>This may contain a special member named <tt><b>constructor</b></tt>. This is used
		* to define the constructor of the new class, and is returned. If this property is
		* <i>not</i> specified, a constructor is generated and returned which just calls the
		* superclass's constructor passing on its parameters.</p>
		* <p><b>It is essential that you call the superclass constructor in any provided constructor. See example code.</b></p>
		* @return {Function} The subclass constructor from the <code>overrides</code> parameter, or a generated one if not provided.
		*/
		extend: function () {
			// inline overrides
			var io = function (o) {
				for (var m in o) {
					this[m] = o[m];
				}
			};
			var oc = Object.prototype.constructor;

			return function (sb, sp, overrides) {
				if (typeof sp == 'object') {
					overrides = sp;
					sp = sb;
					sb = overrides.constructor != oc ? overrides.constructor : function () { sp.apply(this, arguments); };
				}
				var F = function () { },
                    sbp,
                    spp = sp.prototype;

				F.prototype = spp;
				sbp = sb.prototype = new F();
				sbp.constructor = sb;
				sb.superclass = spp;
				if (spp.constructor == oc) {
					spp.constructor = sp;
				}
				sb.override = function (o) {
					Ext.override(sb, o);
				};
				sbp.superclass = sbp.supr = (function () {
					return spp;
				});
				sbp.override = io;
				Ext.override(sb, overrides);
				sb.extend = function (o) { return Ext.extend(sb, o); };
				return sb;
			};
		} (),

		/**
		* Adds a list of functions to the prototype of an existing class, overwriting any existing methods with the same name.
		* Usage:<pre><code>
		Ext.override(MyClass, {
		newMethod1: function(){
		// etc.
		},
		newMethod2: function(foo){
		// etc.
		}
		});
		</code></pre>
		* @param {Object} origclass The class to override
		* @param {Object} overrides The list of functions to add to origClass.  This should be specified as an object literal
		* containing one or more methods.
		* @method override
		*/
		override: function (origclass, overrides) {
			if (overrides) {
				var p = origclass.prototype;
				Ext.apply(p, overrides);
				if (Ext.isIE && overrides.hasOwnProperty('toString')) {
					p.toString = overrides.toString;
				}
			}
		},

		/**
		* Creates namespaces to be used for scoping variables and classes so that they are not global.
		* Specifying the last node of a namespace implicitly creates all other nodes. Usage:
		* <pre><code>
		Ext.namespace('Company', 'Company.data');
		Ext.namespace('Company.data'); // equivalent and preferable to above syntax
		Company.Widget = function() { ... }
		Company.data.CustomStore = function(config) { ... }
		</code></pre>
		* @param {String} namespace1
		* @param {String} namespace2
		* @param {String} etc
		* @return {Object} The namespace object. (If multiple arguments are passed, this will be the last namespace created)
		* @method namespace
		*/
		namespace: function () {
			var o, d;
			Ext.each(arguments, function (v) {
				d = v.split(".");
				o = window[d[0]] = window[d[0]] || {};
				Ext.each(d.slice(1), function (v2) {
					o = o[v2] = o[v2] || {};
				});
			});
			return o;
		},

		/**
		* 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.
		* @param {Object} o
		* @param {String} pre (optional) A prefix to add to the url encoded string
		* @return {String}
		*/
		urlEncode: function (o, pre) {
			var empty,
                buf = [],
                e = encodeURIComponent;

			Ext.iterate(o, function (key, item) {
				empty = Ext.isEmpty(item);
				Ext.each(empty ? key : item, function (val) {
					buf.push('&', e(key), '=', (!Ext.isEmpty(val) && (val != key || !empty)) ? (Ext.isDate(val) ? Ext.encode(val).replace(/"/g, '') : e(val)) : '');
				});
			});
			if (!pre) {
				buf.shift();
				pre = '';
			}
			return pre + buf.join('');
		},

		/**
		* Takes an encoded URL and and converts it to an object. Example: <pre><code>
		Ext.urlDecode("foo=1&bar=2"); // returns {foo: "1", bar: "2"}
		Ext.urlDecode("foo=1&bar=2&bar=3&bar=4", false); // returns {foo: "1", bar: ["2", "3", "4"]}
		</code></pre>
		* @param {String} string
		* @param {Boolean} overwrite (optional) Items of the same name will overwrite previous values instead of creating an an array (Defaults to false).
		* @return {Object} A literal with members
		*/
		urlDecode: function (string, overwrite) {
			if (Ext.isEmpty(string)) {
				return {};
			}
			var obj = {},
                pairs = string.split('&'),
                d = decodeURIComponent,
                name,
                value;
			Ext.each(pairs, function (pair) {
				pair = pair.split('=');
				name = d(pair[0]);
				value = d(pair[1]);
				obj[name] = overwrite || !obj[name] ? value :
                            [].concat(obj[name]).concat(value);
			});
			return obj;
		},

		/**
		* Appends content to the query string of a URL, handling logic for whether to place
		* a question mark or ampersand.
		* @param {String} url The URL to append to.
		* @param {String} s The content to append to the URL.
		* @return (String) The resulting URL
		*/
		urlAppend: function (url, s) {
			if (!Ext.isEmpty(s)) {
				return url + (url.indexOf('?') === -1 ? '?' : '&') + s;
			}
			return url;
		},

		/**
		* Converts any iterable (numeric indices and a length property) into a true array
		* Don't use this on strings. IE doesn't support "abc"[0] which this implementation depends on.
		* For strings, use this instead: "abc".match(/./g) => [a,b,c];
		* @param {Iterable} the iterable object to be turned into a true Array.
		* @return (Array) array
		*/
		toArray: function () {
			return isIE ?
                 function (a, i, j, res) {
                 	res = [];
                 	for (var x = 0, len = a.length; x < len; x++) {
                 		res.push(a[x]);
                 	}
                 	return res.slice(i || 0, j || res.length);
                 } :
                 function (a, i, j) {
                 	return Array.prototype.slice.call(a, i || 0, j || a.length);
                 }
		} (),

		isIterable: function (v) {
			//check for array or arguments
			if (Ext.isArray(v) || v.callee) {
				return true;
			}
			//check for node list type
			if (/NodeList|HTMLCollection/.test(toString.call(v))) {
				return true;
			}
			//NodeList has an item and length property
			//IXMLDOMNodeList has nextNode method, needs to be checked first.
			return ((typeof v.nextNode != 'undefined' || v.item) && Ext.isNumber(v.length));
		},

		/**
		* Iterates an array calling the supplied function.
		* @param {Array/NodeList/Mixed} array The array to be iterated. If this
		* argument is not really an array, the supplied function is called once.
		* @param {Function} fn The function to be called with each item. If the
		* supplied function returns false, iteration stops and this method returns
		* the current <code>index</code>. This function is called with
		* the following arguments:
		* <div class="mdetail-params"><ul>
		* <li><code>item</code> : <i>Mixed</i>
		* <div class="sub-desc">The item at the current <code>index</code>
		* in the passed <code>array</code></div></li>
		* <li><code>index</code> : <i>Number</i>
		* <div class="sub-desc">The current index within the array</div></li>
		* <li><code>allItems</code> : <i>Array</i>
		* <div class="sub-desc">The <code>array</code> passed as the first
		* argument to <code>Ext.each</code>.</div></li>
		* </ul></div>
		* @param {Object} scope The scope (<code>this</code> reference) in which the specified function is executed.
		* Defaults to the <code>item</code> at the current <code>index</code>
		* within the passed <code>array</code>.
		* @return See description for the fn parameter.
		*/
		each: function (array, fn, scope) {
			if (Ext.isEmpty(array, true)) {
				return;
			}
			if (!Ext.isIterable(array) || Ext.isPrimitive(array)) {
				array = [array];
			}
			for (var i = 0, len = array.length; i < len; i++) {
				if (fn.call(scope || array[i], array[i], i, array) === false) {
					return i;
				};
			}
		},

		/**
		* Iterates either the elements in an array, or each of the properties in an object.
		* <b>Note</b>: If you are only iterating arrays, it is better to call {@link #each}.
		* @param {Object/Array} object The object or array to be iterated
		* @param {Function} fn The function to be called for each iteration.
		* The iteration will stop if the supplied function returns false, or
		* all array elements / object properties have been covered. The signature
		* varies depending on the type of object being interated:
		* <div class="mdetail-params"><ul>
		* <li>Arrays : <tt>(Object item, Number index, Array allItems)</tt>
		* <div class="sub-desc">
		* When iterating an array, the supplied function is called with each item.</div></li>
		* <li>Objects : <tt>(String key, Object value, Object)</tt>
		* <div class="sub-desc">
		* When iterating an object, the supplied function is called with each key-value pair in
		* the object, and the iterated object</div></li>
		* </ul></div>
		* @param {Object} scope The scope (<code>this</code> reference) in which the specified function is executed. Defaults to
		* the <code>object</code> being iterated.
		*/
		iterate: function (obj, fn, scope) {
			if (Ext.isEmpty(obj)) {
				return;
			}
			if (Ext.isIterable(obj)) {
				Ext.each(obj, fn, scope);
				return;
			} else if (typeof obj == 'object') {
				for (var prop in obj) {
					if (obj.hasOwnProperty(prop)) {
						if (fn.call(scope || obj, prop, obj[prop], obj) === false) {
							return;
						};
					}
				}
			}
		},

		/**
		* Return the dom node for the passed String (id), dom node, or Ext.Element.
		* Optional 'strict' flag is needed for IE since it can return 'name' and
		* 'id' elements by using getElementById.
		* Here are some examples:
		* <pre><code>
		// gets dom node based on id
		var elDom = Ext.getDom('elId');
		// gets dom node based on the dom node
		var elDom1 = Ext.getDom(elDom);

		// If we don&#39;t know if we are working with an
		// Ext.Element or a dom node use Ext.getDom
		function(el){
		var dom = Ext.getDom(el);
		// do something with the dom node
		}
		* </code></pre>
		* <b>Note</b>: the dom node to be found actually needs to exist (be rendered, etc)
		* when this method is called to be successful.
		* @param {Mixed} el
		* @return HTMLElement
		*/
		getDom: function (el, strict) {
			if (!el || !DOC) {
				return null;
			}
			if (el.dom) {
				return el.dom;
			} else {
				if (typeof el == 'string') {
					var e = DOC.getElementById(el);
					// IE returns elements with the 'name' and 'id' attribute.
					// we do a strict check to return the element with only the id attribute
					if (e && isIE && strict) {
						if (el == e.getAttribute('id')) {
							return e;
						} else {
							return null;
						}
					}
					return e;
				} else {
					return el;
				}
			}
		},

		/**
		* Returns the current document body as an {@link Ext.Element}.
		* @return Ext.Element The document body
		*/
		getBody: function () {
			return Ext.get(DOC.body || DOC.documentElement);
		},

		/**
		* Removes a DOM node from the document.
		*/
		/**
		* <p>Removes this element from the document, removes all DOM event listeners, and deletes the cache reference.
		* All DOM event listeners are removed from this element. If {@link Ext#enableNestedListenerRemoval} is
		* <code>true</code>, then DOM event listeners are also removed from all child nodes. The body node
		* will be ignored if passed in.</p>
		* @param {HTMLElement} node The node to remove
		*/
		removeNode: isIE && !isIE8 ? function () {
			var d;
			return function (n) {
				if (n && n.tagName != 'BODY') {
					(Ext.enableNestedListenerRemoval) ? Ext.EventManager.purgeElement(n, true) : Ext.EventManager.removeAll(n);
					d = d || DOC.createElement('div');
					d.appendChild(n);
					d.innerHTML = '';
					delete Ext.elCache[n.id];
				}
			}
		} () : function (n) {
			if (n && n.parentNode && n.tagName != 'BODY') {
				(Ext.enableNestedListenerRemoval) ? Ext.EventManager.purgeElement(n, true) : Ext.EventManager.removeAll(n);
				n.parentNode.removeChild(n);
				delete Ext.elCache[n.id];
			}
		},

		/**
		* <p>Returns true if the passed value is empty.</p>
		* <p>The value is deemed to be empty if it is<div class="mdetail-params"><ul>
		* <li>null</li>
		* <li>undefined</li>
		* <li>an empty array</li>
		* <li>a zero length string (Unless the <tt>allowBlank</tt> parameter is <tt>true</tt>)</li>
		* </ul></div>
		* @param {Mixed} value The value to test
		* @param {Boolean} allowBlank (optional) true to allow empty strings (defaults to false)
		* @return {Boolean}
		*/
		isEmpty: function (v, allowBlank) {
			return v === null || v === undefined || ((Ext.isArray(v) && !v.length)) || (!allowBlank ? v === '' : false);
		},

		/**
		* Returns true if the passed value is a JavaScript array, otherwise false.
		* @param {Mixed} value The value to test
		* @return {Boolean}
		*/
		isArray: function (v) {
			return toString.apply(v) === '[object Array]';
		},

		/**
		* Returns true if the passed object is a JavaScript date object, otherwise false.
		* @param {Object} object The object to test
		* @return {Boolean}
		*/
		isDate: function (v) {
			return toString.apply(v) === '[object Date]';
		},

		/**
		* Returns true if the passed value is a JavaScript Object, otherwise false.
		* @param {Mixed} value The value to test
		* @return {Boolean}
		*/
		isObject: function (v) {
			return !!v && Object.prototype.toString.call(v) === '[object Object]';
		},

		/**
		* Returns true if the passed value is a JavaScript 'primitive', a string, number or boolean.
		* @param {Mixed} value The value to test
		* @return {Boolean}
		*/
		isPrimitive: function (v) {
			return Ext.isString(v) || Ext.isNumber(v) || Ext.isBoolean(v);
		},

		/**
		* Returns true if the passed value is a JavaScript Function, otherwise false.
		* @param {Mixed} value The value to test
		* @return {Boolean}
		*/
		isFunction: function (v) {
			return toString.apply(v) === '[object Function]';
		},

		/**
		* Returns true if the passed value is a number. Returns false for non-finite numbers.
		* @param {Mixed} value The value to test
		* @return {Boolean}
		*/
		isNumber: function (v) {
			return typeof v === 'number' && isFinite(v);
		},

		/**
		* Returns true if the passed value is a string.
		* @param {Mixed} value The value to test
		* @return {Boolean}
		*/
		isString: function (v) {
			return typeof v === 'string';
		},

		/**
		* Returns true if the passed value is a boolean.
		* @param {Mixed} value The value to test
		* @return {Boolean}
		*/
		isBoolean: function (v) {
			return typeof v === 'boolean';
		},

		/**
		* Returns true if the passed value is an HTMLElement
		* @param {Mixed} value The value to test
		* @return {Boolean}
		*/
		isElement: function (v) {
			return v ? !!v.tagName : false;
		},

		/**
		* Returns true if the passed value is not undefined.
		* @param {Mixed} value The value to test
		* @return {Boolean}
		*/
		isDefined: function (v) {
			return typeof v !== 'undefined';
		},

		/**
		* True if the detected browser is Opera.
		* @type Boolean
		*/
		isOpera: isOpera,
		/**
		* True if the detected browser uses WebKit.
		* @type Boolean
		*/
		isWebKit: isWebKit,
		/**
		* True if the detected browser is Chrome.
		* @type Boolean
		*/
		isChrome: isChrome,
		/**
		* True if the detected browser is Safari.
		* @type Boolean
		*/
		isSafari: isSafari,
		/**
		* True if the detected browser is Safari 3.x.
		* @type Boolean
		*/
		isSafari3: isSafari3,
		/**
		* True if the detected browser is Safari 4.x.
		* @type Boolean
		*/
		isSafari4: isSafari4,
		/**
		* True if the detected browser is Safari 2.x.
		* @type Boolean
		*/
		isSafari2: isSafari2,
		/**
		* True if the detected browser is Internet Explorer.
		* @type Boolean
		*/
		isIE: isIE,
		/**
		* True if the detected browser is Internet Explorer 6.x.
		* @type Boolean
		*/
		isIE6: isIE6,
		/**
		* True if the detected browser is Internet Explorer 7.x.
		* @type Boolean
		*/
		isIE7: isIE7,
		/**
		* True if the detected browser is Internet Explorer 8.x.
		* @type Boolean
		*/
		isIE8: isIE8,
		/**
		* True if the detected browser uses the Gecko layout engine (e.g. Mozilla, Firefox).
		* @type Boolean
		*/
		isGecko: isGecko,
		/**
		* True if the detected browser uses a pre-Gecko 1.9 layout engine (e.g. Firefox 2.x).
		* @type Boolean
		*/
		isGecko2: isGecko2,
		/**
		* True if the detected browser uses a Gecko 1.9+ layout engine (e.g. Firefox 3.x).
		* @type Boolean
		*/
		isGecko3: isGecko3,
		/**
		* True if the detected browser is Internet Explorer running in non-strict mode.
		* @type Boolean
		*/
		isBorderBox: isBorderBox,
		/**
		* True if the detected platform is Linux.
		* @type Boolean
		*/
		isLinux: isLinux,
		/**
		* True if the detected platform is Windows.
		* @type Boolean
		*/
		isWindows: isWindows,
		/**
		* True if the detected platform is Mac OS.
		* @type Boolean
		*/
		isMac: isMac,
		/**
		* True if the detected platform is Adobe Air.
		* @type Boolean
		*/
		isAir: isAir
	});

	/**
	* Creates namespaces to be used for scoping variables and classes so that they are not global.
	* Specifying the last node of a namespace implicitly creates all other nodes. Usage:
	* <pre><code>
	Ext.namespace('Company', 'Company.data');
	Ext.namespace('Company.data'); // equivalent and preferable to above syntax
	Company.Widget = function() { ... }
	Company.data.CustomStore = function(config) { ... }
	</code></pre>
	* @param {String} namespace1
	* @param {String} namespace2
	* @param {String} etc
	* @return {Object} The namespace object. (If multiple arguments are passed, this will be the last namespace created)
	* @method ns
	*/
	Ext.ns = Ext.namespace;
})();

Ext.ns("Ext.util", "Ext.lib", "Ext.data");

Ext.elCache = {};

/**
* @class Function
* These functions are available on every Function object (any JavaScript function).
*/
Ext.apply(Function.prototype, {
	/**
	* Creates an interceptor function. The passed function is called before the original one. If it returns false,
	* the original one is not called. The resulting function returns the results of the original function.
	* The passed function is called with the parameters of the original function. Example usage:
	* <pre><code>
	var sayHi = function(name){
	alert('Hi, ' + name);
	}

	sayHi('Fred'); // alerts "Hi, Fred"

	// create a new function that validates input without
	// directly modifying the original function:
	var sayHiToFriend = sayHi.createInterceptor(function(name){
	return name == 'Brian';
	});

	sayHiToFriend('Fred');  // no alert
	sayHiToFriend('Brian'); // alerts "Hi, Brian"
	</code></pre>
	* @param {Function} fcn The function to call before the original
	* @param {Object} scope (optional) The scope (<code><b>this</b></code> reference) in which the passed function is executed.
	* <b>If omitted, defaults to the scope in which the original function is called or the browser window.</b>
	* @return {Function} The new function
	*/
	createInterceptor: function (fcn, scope) {
		var method = this;
		return !Ext.isFunction(fcn) ?
                this :
                function () {
                	var me = this,
                        args = arguments;
                	fcn.target = me;
                	fcn.method = method;
                	return (fcn.apply(scope || me || window, args) !== false) ?
                            method.apply(me || window, args) :
                            null;
                };
	},

	/**
	* Creates a callback that passes arguments[0], arguments[1], arguments[2], ...
	* Call directly on any function. Example: <code>myFunction.createCallback(arg1, arg2)</code>
	* Will create a function that is bound to those 2 args. <b>If a specific scope is required in the
	* callback, use {@link #createDelegate} instead.</b> The function returned by createCallback always
	* executes in the window scope.
	* <p>This method is required when you want to pass arguments to a callback function.  If no arguments
	* are needed, you can simply pass a reference to the function as a callback (e.g., callback: myFn).
	* However, if you tried to pass a function with arguments (e.g., callback: myFn(arg1, arg2)) the function
	* would simply execute immediately when the code is parsed. Example usage:
	* <pre><code>
	var sayHi = function(name){
	alert('Hi, ' + name);
	}

	// clicking the button alerts "Hi, Fred"
	new Ext.Button({
	text: 'Say Hi',
	renderTo: Ext.getBody(),
	handler: sayHi.createCallback('Fred')
	});
	</code></pre>
	* @return {Function} The new function
	*/
	createCallback: function (/*args...*/) {
		// make args available, in function below
		var args = arguments,
            method = this;
		return function () {
			return method.apply(window, args);
		};
	},

	/**
	* Creates a delegate (callback) that sets the scope to obj.
	* Call directly on any function. Example: <code>this.myFunction.createDelegate(this, [arg1, arg2])</code>
	* Will create a function that is automatically scoped to obj so that the <tt>this</tt> variable inside the
	* callback points to obj. Example usage:
	* <pre><code>
	var sayHi = function(name){
	// Note this use of "this.text" here.  This function expects to
	// execute within a scope that contains a text property.  In this
	// example, the "this" variable is pointing to the btn object that
	// was passed in createDelegate below.
	alert('Hi, ' + name + '. You clicked the "' + this.text + '" button.');
	}

	var btn = new Ext.Button({
	text: 'Say Hi',
	renderTo: Ext.getBody()
	});

	// This callback will execute in the scope of the
	// button instance. Clicking the button alerts
	// "Hi, Fred. You clicked the "Say Hi" button."
	btn.on('click', sayHi.createDelegate(btn, ['Fred']));
	</code></pre>
	* @param {Object} scope (optional) The scope (<code><b>this</b></code> reference) in which the function is executed.
	* <b>If omitted, defaults to the browser window.</b>
	* @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
	* @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
	* if a number the args are inserted at the specified position
	* @return {Function} The new function
	*/
	createDelegate: function (obj, args, appendArgs) {
		var method = this;
		return function () {
			var callArgs = args || arguments;
			if (appendArgs === true) {
				callArgs = Array.prototype.slice.call(arguments, 0);
				callArgs = callArgs.concat(args);
			} else if (Ext.isNumber(appendArgs)) {
				callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first
				var applyArgs = [appendArgs, 0].concat(args); // create method call params
				Array.prototype.splice.apply(callArgs, applyArgs); // splice them in
			}
			return method.apply(obj || window, callArgs);
		};
	},

	/**
	* Calls this function after the number of millseconds specified, optionally in a specific scope. Example usage:
	* <pre><code>
	var sayHi = function(name){
	alert('Hi, ' + name);
	}

	// executes immediately:
	sayHi('Fred');

	// executes after 2 seconds:
	sayHi.defer(2000, this, ['Fred']);

	// this syntax is sometimes useful for deferring
	// execution of an anonymous function:
	(function(){
	alert('Anonymous');
	}).defer(100);
	</code></pre>
	* @param {Number} millis The number of milliseconds for the setTimeout call (if less than or equal to 0 the function is executed immediately)
	* @param {Object} scope (optional) The scope (<code><b>this</b></code> reference) in which the function is executed.
	* <b>If omitted, defaults to the browser window.</b>
	* @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
	* @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
	* if a number the args are inserted at the specified position
	* @return {Number} The timeout id that can be used with clearTimeout
	*/
	defer: function (millis, obj, args, appendArgs) {
		var fn = this.createDelegate(obj, args, appendArgs);
		if (millis > 0) {
			return setTimeout(fn, millis);
		}
		fn();
		return 0;
	}
});

/**
* @class String
* These functions are available on every String object.
*/
Ext.applyIf(String, {
	/**
	* Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens.  Each
	* token must be unique, and must increment in the format {0}, {1}, etc.  Example usage:
	* <pre><code>
	var cls = 'my-class', text = 'Some text';
	var s = String.format('&lt;div class="{0}">{1}&lt;/div>', cls, text);
	// s now contains the string: '&lt;div class="my-class">Some text&lt;/div>'
	* </code></pre>
	* @param {String} string The tokenized string to be formatted
	* @param {String} value1 The value to replace token {0}
	* @param {String} value2 Etc...
	* @return {String} The formatted string
	* @static
	*/
	format: function (format) {
		var args = Ext.toArray(arguments, 1);
		return format.replace(/\{(\d+)\}/g, function (m, i) {
			return args[i];
		});
	}
});

/**
* @class Array
*/
Ext.applyIf(Array.prototype, {
	/**
	* Checks whether or not the specified object exists in the array.
	* @param {Object} o The object to check for
	* @param {Number} from (Optional) The index at which to begin the search
	* @return {Number} The index of o in the array (or -1 if it is not found)
	*/
	indexOf: function (o, from) {
		var len = this.length;
		from = from || 0;
		from += (from < 0) ? len : 0;
		for (; from < len; ++from) {
			if (this[from] === o) {
				return from;
			}
		}
		return -1;
	},

	/**
	* Removes the specified object from the array.  If the object is not found nothing happens.
	* @param {Object} o The object to remove
	* @return {Array} this array
	*/
	remove: function (o) {
		var index = this.indexOf(o);
		if (index != -1) {
			this.splice(index, 1);
		}
		return this;
	}
});
/**
* @class Ext
*/

Ext.ns("Ext.grid", "Ext.list", "Ext.dd", "Ext.tree", "Ext.form", "Ext.menu",
       "Ext.state", "Ext.layout", "Ext.app", "Ext.ux", "Ext.chart", "Ext.direct");
/**
* Namespace alloted for extensions to the framework.
* @property ux
* @type Object
*/

Ext.apply(Ext, function () {
	var E = Ext,
        idSeed = 0,
        scrollWidth = null;

	return {
		/**
		* A reusable empty function
		* @property
		* @type Function
		*/
		emptyFn: function () { },

		/**
		* URL to a 1x1 transparent gif image used by Ext to create inline icons with CSS background images.
		* In older versions of IE, this defaults to "http://extjs.com/s.gif" and you should change this to a URL on your server.
		* For other browsers it uses an inline data URL.
		* @type String
		*/
		BLANK_IMAGE_URL: Ext.isIE6 || Ext.isIE7 || Ext.isAir ?
                            'http:/' + '/www.extjs.com/s.gif' :
                            'data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==',

		extendX: function (supr, fn) {
			return Ext.extend(supr, fn(supr.prototype));
		},

		/**
		* Returns the current HTML document object as an {@link Ext.Element}.
		* @return Ext.Element The document
		*/
		getDoc: function () {
			return Ext.get(document);
		},

		/**
		* Utility method for validating that a value is numeric, returning the specified default value if it is not.
		* @param {Mixed} value Should be a number, but any type will be handled appropriately
		* @param {Number} defaultValue The value to return if the original value is non-numeric
		* @return {Number} Value, if numeric, else defaultValue
		*/
		num: function (v, defaultValue) {
			v = Number(Ext.isEmpty(v) || Ext.isArray(v) || typeof v == 'boolean' || (typeof v == 'string' && v.trim().length == 0) ? NaN : v);
			return isNaN(v) ? defaultValue : v;
		},

		/**
		* <p>Utility method for returning a default value if the passed value is empty.</p>
		* <p>The value is deemed to be empty if it is<div class="mdetail-params"><ul>
		* <li>null</li>
		* <li>undefined</li>
		* <li>an empty array</li>
		* <li>a zero length string (Unless the <tt>allowBlank</tt> parameter is <tt>true</tt>)</li>
		* </ul></div>
		* @param {Mixed} value The value to test
		* @param {Mixed} defaultValue The value to return if the original value is empty
		* @param {Boolean} allowBlank (optional) true to allow zero length strings to qualify as non-empty (defaults to false)
		* @return {Mixed} value, if non-empty, else defaultValue
		*/
		value: function (v, defaultValue, allowBlank) {
			return Ext.isEmpty(v, allowBlank) ? defaultValue : v;
		},

		/**
		* Escapes the passed string for use in a regular expression
		* @param {String} str
		* @return {String}
		*/
		escapeRe: function (s) {
			return s.replace(/([-.*+?^${}()|[\]\/\\])/g, "\\$1");
		},

		sequence: function (o, name, fn, scope) {
			o[name] = o[name].createSequence(fn, scope);
		},

		/**
		* Applies event listeners to elements by selectors when the document is ready.
		* The event name is specified with an <tt>&#64;</tt> suffix.
		* <pre><code>
		Ext.addBehaviors({
		// add a listener for click on all anchors in element with id foo
		'#foo a&#64;click' : function(e, t){
		// do something
		},

		// add the same listener to multiple selectors (separated by comma BEFORE the &#64;)
		'#foo a, #bar span.some-class&#64;mouseover' : function(){
		// do something
		}
		});
		* </code></pre>
		* @param {Object} obj The list of behaviors to apply
		*/
		addBehaviors: function (o) {
			if (!Ext.isReady) {
				Ext.onReady(function () {
					Ext.addBehaviors(o);
				});
			} else {
				var cache = {}, // simple cache for applying multiple behaviors to same selector does query multiple times
                    parts,
                    b,
                    s;
				for (b in o) {
					if ((parts = b.split('@'))[1]) { // for Object prototype breakers
						s = parts[0];
						if (!cache[s]) {
							cache[s] = Ext.select(s);
						}
						cache[s].on(parts[1], o[b]);
					}
				}
				cache = null;
			}
		},

		/**
		* Utility method for getting the width of the browser scrollbar. This can differ depending on
		* operating system settings, such as the theme or font size.
		* @param {Boolean} force (optional) true to force a recalculation of the value.
		* @return {Number} The width of the scrollbar.
		*/
		getScrollBarWidth: function (force) {
			if (!Ext.isReady) {
				return 0;
			}

			if (force === true || scrollWidth === null) {
				// Append our div, do our calculation and then remove it
				var div = Ext.getBody().createChild('<div class="x-hide-offsets" style="width:100px;height:50px;overflow:hidden;"><div style="height:200px;"></div></div>'),
                    child = div.child('div', true);
				var w1 = child.offsetWidth;
				div.setStyle('overflow', (Ext.isWebKit || Ext.isGecko) ? 'auto' : 'scroll');
				var w2 = child.offsetWidth;
				div.remove();
				// Need to add 2 to ensure we leave enough space
				scrollWidth = w1 - w2 + 2;
			}
			return scrollWidth;
		},


		// deprecated
		combine: function () {
			var as = arguments, l = as.length, r = [];
			for (var i = 0; i < l; i++) {
				var a = as[i];
				if (Ext.isArray(a)) {
					r = r.concat(a);
				} else if (a.length !== undefined && !a.substr) {
					r = r.concat(Array.prototype.slice.call(a, 0));
				} else {
					r.push(a);
				}
			}
			return r;
		},

		/**
		* Copies a set of named properties fom the source object to the destination object.
		* <p>example:<pre><code>
		ImageComponent = Ext.extend(Ext.BoxComponent, {
		initComponent: function() {
		this.autoEl = { tag: 'img' };
		MyComponent.superclass.initComponent.apply(this, arguments);
		this.initialBox = Ext.copyTo({}, this.initialConfig, 'x,y,width,height');
		}
		});
		* </code></pre>
		* @param {Object} dest The destination object.
		* @param {Object} source The source object.
		* @param {Array/String} names Either an Array of property names, or a comma-delimited list
		* of property names to copy.
		* @return {Object} The modified object.
		*/
		copyTo: function (dest, source, names) {
			if (typeof names == 'string') {
				names = names.split(/[,;\s]/);
			}
			Ext.each(names, function (name) {
				if (source.hasOwnProperty(name)) {
					dest[name] = source[name];
				}
			}, this);
			return dest;
		},

		/**
		* Attempts to destroy any objects passed to it by removing all event listeners, removing them from the
		* DOM (if applicable) and calling their destroy functions (if available).  This method is primarily
		* intended for arguments of type {@link Ext.Element} and {@link Ext.Component}, but any subclass of
		* {@link Ext.util.Observable} can be passed in.  Any number of elements and/or components can be
		* passed into this function in a single call as separate arguments.
		* @param {Mixed} arg1 An {@link Ext.Element}, {@link Ext.Component}, or an Array of either of these to destroy
		* @param {Mixed} arg2 (optional)
		* @param {Mixed} etc... (optional)
		*/
		destroy: function () {
			Ext.each(arguments, function (arg) {
				if (arg) {
					if (Ext.isArray(arg)) {
						this.destroy.apply(this, arg);
					} else if (typeof arg.destroy == 'function') {
						arg.destroy();
					} else if (arg.dom) {
						arg.remove();
					}
				}
			}, this);
		},

		/**
		* Attempts to destroy and then remove a set of named properties of the passed object.
		* @param {Object} o The object (most likely a Component) who's properties you wish to destroy.
		* @param {Mixed} arg1 The name of the property to destroy and remove from the object.
		* @param {Mixed} etc... More property names to destroy and remove.
		*/
		destroyMembers: function (o, arg1, arg2, etc) {
			for (var i = 1, a = arguments, len = a.length; i < len; i++) {
				Ext.destroy(o[a[i]]);
				delete o[a[i]];
			}
		},

		/**
		* Creates a copy of the passed Array with falsy values removed.
		* @param {Array/NodeList} arr The Array from which to remove falsy values.
		* @return {Array} The new, compressed Array.
		*/
		clean: function (arr) {
			var ret = [];
			Ext.each(arr, function (v) {
				if (!!v) {
					ret.push(v);
				}
			});
			return ret;
		},

		/**
		* Creates a copy of the passed Array, filtered to contain only unique values.
		* @param {Array} arr The Array to filter
		* @return {Array} The new Array containing unique values.
		*/
		unique: function (arr) {
			var ret = [],
                collect = {};

			Ext.each(arr, function (v) {
				if (!collect[v]) {
					ret.push(v);
				}
				collect[v] = true;
			});
			return ret;
		},

		/**
		* Recursively flattens into 1-d Array. Injects Arrays inline.
		* @param {Array} arr The array to flatten
		* @return {Array} The new, flattened array.
		*/
		flatten: function (arr) {
			var worker = [];
			function rFlatten(a) {
				Ext.each(a, function (v) {
					if (Ext.isArray(v)) {
						rFlatten(v);
					} else {
						worker.push(v);
					}
				});
				return worker;
			}
			return rFlatten(arr);
		},

		/**
		* Returns the minimum value in the Array.
		* @param {Array|NodeList} arr The Array from which to select the minimum value.
		* @param {Function} comp (optional) a function to perform the comparision which determines minimization.
		*                   If omitted the "<" operator will be used. Note: gt = 1; eq = 0; lt = -1
		* @return {Object} The minimum value in the Array.
		*/
		min: function (arr, comp) {
			var ret = arr[0];
			comp = comp || function (a, b) { return a < b ? -1 : 1; };
			Ext.each(arr, function (v) {
				ret = comp(ret, v) == -1 ? ret : v;
			});
			return ret;
		},

		/**
		* Returns the maximum value in the Array
		* @param {Array|NodeList} arr The Array from which to select the maximum value.
		* @param {Function} comp (optional) a function to perform the comparision which determines maximization.
		*                   If omitted the ">" operator will be used. Note: gt = 1; eq = 0; lt = -1
		* @return {Object} The maximum value in the Array.
		*/
		max: function (arr, comp) {
			var ret = arr[0];
			comp = comp || function (a, b) { return a > b ? 1 : -1; };
			Ext.each(arr, function (v) {
				ret = comp(ret, v) == 1 ? ret : v;
			});
			return ret;
		},

		/**
		* Calculates the mean of the Array
		* @param {Array} arr The Array to calculate the mean value of.
		* @return {Number} The mean.
		*/
		mean: function (arr) {
			return arr.length > 0 ? Ext.sum(arr) / arr.length : undefined;
		},

		/**
		* Calculates the sum of the Array
		* @param {Array} arr The Array to calculate the sum value of.
		* @return {Number} The sum.
		*/
		sum: function (arr) {
			var ret = 0;
			Ext.each(arr, function (v) {
				ret += v;
			});
			return ret;
		},

		/**
		* Partitions the set into two sets: a true set and a false set.
		* Example:
		* Example2:
		* <pre><code>
		// Example 1:
		Ext.partition([true, false, true, true, false]); // [[true, true, true], [false, false]]

		// Example 2:
		Ext.partition(
		Ext.query("p"),
		function(val){
		return val.className == "class1"
		}
		);
		// true are those paragraph elements with a className of "class1",
		// false set are those that do not have that className.
		* </code></pre>
		* @param {Array|NodeList} arr The array to partition
		* @param {Function} truth (optional) a function to determine truth.  If this is omitted the element
		*                   itself must be able to be evaluated for its truthfulness.
		* @return {Array} [true<Array>,false<Array>]
		*/
		partition: function (arr, truth) {
			var ret = [[], []];
			Ext.each(arr, function (v, i, a) {
				ret[(truth && truth(v, i, a)) || (!truth && v) ? 0 : 1].push(v);
			});
			return ret;
		},

		/**
		* Invokes a method on each item in an Array.
		* <pre><code>
		// Example:
		Ext.invoke(Ext.query("p"), "getAttribute", "id");
		// [el1.getAttribute("id"), el2.getAttribute("id"), ..., elN.getAttribute("id")]
		* </code></pre>
		* @param {Array|NodeList} arr The Array of items to invoke the method on.
		* @param {String} methodName The method name to invoke.
		* @param {...*} args Arguments to send into the method invocation.
		* @return {Array} The results of invoking the method on each item in the array.
		*/
		invoke: function (arr, methodName) {
			var ret = [],
                args = Array.prototype.slice.call(arguments, 2);
			Ext.each(arr, function (v, i) {
				if (v && typeof v[methodName] == 'function') {
					ret.push(v[methodName].apply(v, args));
				} else {
					ret.push(undefined);
				}
			});
			return ret;
		},

		/**
		* Plucks the value of a property from each item in the Array
		* <pre><code>
		// Example:
		Ext.pluck(Ext.query("p"), "className"); // [el1.className, el2.className, ..., elN.className]
		* </code></pre>
		* @param {Array|NodeList} arr The Array of items to pluck the value from.
		* @param {String} prop The property name to pluck from each element.
		* @return {Array} The value from each item in the Array.
		*/
		pluck: function (arr, prop) {
			var ret = [];
			Ext.each(arr, function (v) {
				ret.push(v[prop]);
			});
			return ret;
		},

		/**
		* <p>Zips N sets together.</p>
		* <pre><code>
		// Example 1:
		Ext.zip([1,2,3],[4,5,6]); // [[1,4],[2,5],[3,6]]
		// Example 2:
		Ext.zip(
		[ "+", "-", "+"],
		[  12,  10,  22],
		[  43,  15,  96],
		function(a, b, c){
		return "$" + a + "" + b + "." + c
		}
		); // ["$+12.43", "$-10.15", "$+22.96"]
		* </code></pre>
		* @param {Arrays|NodeLists} arr This argument may be repeated. Array(s) to contribute values.
		* @param {Function} zipper (optional) The last item in the argument list. This will drive how the items are zipped together.
		* @return {Array} The zipped set.
		*/
		zip: function () {
			var parts = Ext.partition(arguments, function (val) { return typeof val != 'function'; }),
                arrs = parts[0],
                fn = parts[1][0],
                len = Ext.max(Ext.pluck(arrs, "length")),
                ret = [];

			for (var i = 0; i < len; i++) {
				ret[i] = [];
				if (fn) {
					ret[i] = fn.apply(fn, Ext.pluck(arrs, i));
				} else {
					for (var j = 0, aLen = arrs.length; j < aLen; j++) {
						ret[i].push(arrs[j][i]);
					}
				}
			}
			return ret;
		},

		/**
		* This is shorthand reference to {@link Ext.ComponentMgr#get}.
		* Looks up an existing {@link Ext.Component Component} by {@link Ext.Component#id id}
		* @param {String} id The component {@link Ext.Component#id id}
		* @return Ext.Component The Component, <tt>undefined</tt> if not found, or <tt>null</tt> if a
		* Class was found.
		*/
		getCmp: function (id) {
			return Ext.ComponentMgr.get(id);
		},

		/**
		* By default, Ext intelligently decides whether floating elements should be shimmed. If you are using flash,
		* you may want to set this to true.
		* @type Boolean
		*/
		useShims: E.isIE6 || (E.isMac && E.isGecko2),

		// inpired by a similar function in mootools library
		/**
		* Returns the type of object that is passed in. If the object passed in is null or undefined it
		* return false otherwise it returns one of the following values:<div class="mdetail-params"><ul>
		* <li><b>string</b>: If the object passed is a string</li>
		* <li><b>number</b>: If the object passed is a number</li>
		* <li><b>boolean</b>: If the object passed is a boolean value</li>
		* <li><b>date</b>: If the object passed is a Date object</li>
		* <li><b>function</b>: If the object passed is a function reference</li>
		* <li><b>object</b>: If the object passed is an object</li>
		* <li><b>array</b>: If the object passed is an array</li>
		* <li><b>regexp</b>: If the object passed is a regular expression</li>
		* <li><b>element</b>: If the object passed is a DOM Element</li>
		* <li><b>nodelist</b>: If the object passed is a DOM NodeList</li>
		* <li><b>textnode</b>: If the object passed is a DOM text node and contains something other than whitespace</li>
		* <li><b>whitespace</b>: If the object passed is a DOM text node and contains only whitespace</li>
		* </ul></div>
		* @param {Mixed} object
		* @return {String}
		*/
		type: function (o) {
			if (o === undefined || o === null) {
				return false;
			}
			if (o.htmlElement) {
				return 'element';
			}
			var t = typeof o;
			if (t == 'object' && o.nodeName) {
				switch (o.nodeType) {
					case 1: return 'element';
					case 3: return (/\S/).test(o.nodeValue) ? 'textnode' : 'whitespace';
				}
			}
			if (t == 'object' || t == 'function') {
				switch (o.constructor) {
					case Array: return 'array';
					case RegExp: return 'regexp';
					case Date: return 'date';
				}
				if (typeof o.length == 'number' && typeof o.item == 'function') {
					return 'nodelist';
				}
			}
			return t;
		},

		intercept: function (o, name, fn, scope) {
			o[name] = o[name].createInterceptor(fn, scope);
		},

		// internal
		callback: function (cb, scope, args, delay) {
			if (typeof cb == 'function') {
				if (delay) {
					cb.defer(delay, scope, args || []);
				} else {
					cb.apply(scope, args || []);
				}
			}
		}
	};
} ());

/**
* @class Function
* These functions are available on every Function object (any JavaScript function).
*/
Ext.apply(Function.prototype, {
	/**
	* Create a combined function call sequence of the original function + the passed function.
	* The resulting function returns the results of the original function.
	* The passed fcn is called with the parameters of the original function. Example usage:
	* <pre><code>
	var sayHi = function(name){
	alert('Hi, ' + name);
	}

	sayHi('Fred'); // alerts "Hi, Fred"

	var sayGoodbye = sayHi.createSequence(function(name){
	alert('Bye, ' + name);
	});

	sayGoodbye('Fred'); // both alerts show
	</code></pre>
	* @param {Function} fcn The function to sequence
	* @param {Object} scope (optional) The scope (<code><b>this</b></code> reference) in which the passed function is executed.
	* <b>If omitted, defaults to the scope in which the original function is called or the browser window.</b>
	* @return {Function} The new function
	*/
	createSequence: function (fcn, scope) {
		var method = this;
		return (typeof fcn != 'function') ?
                this :
                function () {
                	var retval = method.apply(this || window, arguments);
                	fcn.apply(scope || this || window, arguments);
                	return retval;
                };
	}
});


/**
* @class String
* These functions are available as static methods on the JavaScript String object.
*/
Ext.applyIf(String, {

	/**
	* Escapes the passed string for ' and \
	* @param {String} string The string to escape
	* @return {String} The escaped string
	* @static
	*/
	escape: function (string) {
		return string.replace(/('|\\)/g, "\\$1");
	},

	/**
	* Pads the left side of a string with a specified character.  This is especially useful
	* for normalizing number and date strings.  Example usage:
	* <pre><code>
	var s = String.leftPad('123', 5, '0');
	// s now contains the string: '00123'
	* </code></pre>
	* @param {String} string The original string
	* @param {Number} size The total length of the output string
	* @param {String} char (optional) The character with which to pad the original string (defaults to empty string " ")
	* @return {String} The padded string
	* @static
	*/
	leftPad: function (val, size, ch) {
		var result = String(val);
		if (!ch) {
			ch = " ";
		}
		while (result.length < size) {
			result = ch + result;
		}
		return result;
	}
});

/**
* Utility function that allows you to easily switch a string between two alternating values.  The passed value
* is compared to the current string, and if they are equal, the other value that was passed in is returned.  If
* they are already different, the first value passed in is returned.  Note that this method returns the new value
* but does not change the current string.
* <pre><code>
// alternate sort directions
sort = sort.toggle('ASC', 'DESC');

// instead of conditional logic:
sort = (sort == 'ASC' ? 'DESC' : 'ASC');
</code></pre>
* @param {String} value The value to compare to the current string
* @param {String} other The new value to use if the string already equals the first value passed in
* @return {String} The new value
*/
String.prototype.toggle = function (value, other) {
	return this == value ? other : value;
};

/**
* Trims whitespace from either end of a string, leaving spaces within the string intact.  Example:
* <pre><code>
var s = '  foo bar  ';
alert('-' + s + '-');         //alerts "- foo bar -"
alert('-' + s.trim() + '-');  //alerts "-foo bar-"
</code></pre>
* @return {String} The trimmed string
*/
String.prototype.trim = function () {
	var re = /^\s+|\s+$/g;
	return function () { return this.replace(re, ""); };
} ();

// here to prevent dependency on Date.js
/**
Returns the number of milliseconds between this date and date
@param {Date} date (optional) Defaults to now
@return {Number} The diff in milliseconds
@member Date getElapsed
*/
Date.prototype.getElapsed = function (date) {
	return Math.abs((date || new Date()).getTime() - this.getTime());
};


/**
* @class Number
*/
Ext.applyIf(Number.prototype, {
	/**
	* Checks whether or not the current number is within a desired range.  If the number is already within the
	* range it is returned, otherwise the min or max value is returned depending on which side of the range is
	* exceeded.  Note that this method returns the constrained value but does not change the current number.
	* @param {Number} min The minimum number in the range
	* @param {Number} max The maximum number in the range
	* @return {Number} The constrained value if outside the range, otherwise the current value
	*/
	constrain: function (min, max) {
		return Math.min(Math.max(this, min), max);
	}
});
/**
* @class Ext.util.TaskRunner
* Provides the ability to execute one or more arbitrary tasks in a multithreaded
* manner.  Generally, you can use the singleton {@link Ext.TaskMgr} instead, but
* if needed, you can create separate instances of TaskRunner.  Any number of
* separate tasks can be started at any time and will run independently of each
* other. Example usage:
* <pre><code>
// Start a simple clock task that updates a div once per second
var updateClock = function(){
Ext.fly('clock').update(new Date().format('g:i:s A'));
} 
var task = {
run: updateClock,
interval: 1000 //1 second
}
var runner = new Ext.util.TaskRunner();
runner.start(task);

// equivalent using TaskMgr
Ext.TaskMgr.start({
run: updateClock,
interval: 1000
});

* </code></pre>
* <p>See the {@link #start} method for details about how to configure a task object.</p>
* Also see {@link Ext.util.DelayedTask}. 
* 
* @constructor
* @param {Number} interval (optional) The minimum precision in milliseconds supported by this TaskRunner instance
* (defaults to 10)
*/
Ext.util.TaskRunner = function (interval) {
	interval = interval || 10;
	var tasks = [],
    	removeQueue = [],
    	id = 0,
    	running = false,

	// private
    	stopThread = function () {
    		running = false;
    		clearInterval(id);
    		id = 0;
    	},

	// private
    	startThread = function () {
    		if (!running) {
    			running = true;
    			id = setInterval(runTasks, interval);
    		}
    	},

	// private
    	removeTask = function (t) {
    		removeQueue.push(t);
    		if (t.onStop) {
    			t.onStop.apply(t.scope || t);
    		}
    	},

	// private
    	runTasks = function () {
    		var rqLen = removeQueue.length,
	    		now = new Date().getTime();

    		if (rqLen > 0) {
    			for (var i = 0; i < rqLen; i++) {
    				tasks.remove(removeQueue[i]);
    			}
    			removeQueue = [];
    			if (tasks.length < 1) {
    				stopThread();
    				return;
    			}
    		}
    		for (var i = 0, t, itime, rt, len = tasks.length; i < len; ++i) {
    			t = tasks[i];
    			itime = now - t.taskRunTime;
    			if (t.interval <= itime) {
    				rt = t.run.apply(t.scope || t, t.args || [++t.taskRunCount]);
    				t.taskRunTime = now;
    				if (rt === false || t.taskRunCount === t.repeat) {
    					removeTask(t);
    					return;
    				}
    			}
    			if (t.duration && t.duration <= (now - t.taskStartTime)) {
    				removeTask(t);
    			}
    		}
    	};

	/**
	* Starts a new task.
	* @method start
	* @param {Object} task <p>A config object that supports the following properties:<ul>
	* <li><code>run</code> : Function<div class="sub-desc"><p>The function to execute each time the task is invoked. The
	* function will be called at each interval and passed the <code>args</code> argument if specified, and the
	* current invocation count if not.</p>
	* <p>If a particular scope (<code>this</code> reference) is required, be sure to specify it using the <code>scope</code> argument.</p>
	* <p>Return <code>false</code> from this function to terminate the task.</p></div></li>
	* <li><code>interval</code> : Number<div class="sub-desc">The frequency in milliseconds with which the task
	* should be invoked.</div></li>
	* <li><code>args</code> : Array<div class="sub-desc">(optional) An array of arguments to be passed to the function
	* specified by <code>run</code>. If not specified, the current invocation count is passed.</div></li>
	* <li><code>scope</code> : Object<div class="sub-desc">(optional) The scope (<tt>this</tt> reference) in which to execute the
	* <code>run</code> function. Defaults to the task config object.</div></li>
	* <li><code>duration</code> : Number<div class="sub-desc">(optional) The length of time in milliseconds to invoke
	* the task before stopping automatically (defaults to indefinite).</div></li>
	* <li><code>repeat</code> : Number<div class="sub-desc">(optional) The number of times to invoke the task before
	* stopping automatically (defaults to indefinite).</div></li>
	* </ul></p>
	* <p>Before each invocation, Ext injects the property <code>taskRunCount</code> into the task object so
	* that calculations based on the repeat count can be performed.</p>
	* @return {Object} The task
	*/
	this.start = function (task) {
		tasks.push(task);
		task.taskStartTime = new Date().getTime();
		task.taskRunTime = 0;
		task.taskRunCount = 0;
		startThread();
		return task;
	};

	/**
	* Stops an existing running task.
	* @method stop
	* @param {Object} task The task to stop
	* @return {Object} The task
	*/
	this.stop = function (task) {
		removeTask(task);
		return task;
	};

	/**
	* Stops all tasks that are currently running.
	* @method stopAll
	*/
	this.stopAll = function () {
		stopThread();
		for (var i = 0, len = tasks.length; i < len; i++) {
			if (tasks[i].onStop) {
				tasks[i].onStop();
			}
		}
		tasks = [];
		removeQueue = [];
	};
};

/**
* @class Ext.TaskMgr
* @extends Ext.util.TaskRunner
* A static {@link Ext.util.TaskRunner} instance that can be used to start and stop arbitrary tasks.  See
* {@link Ext.util.TaskRunner} for supported methods and task config properties.
* <pre><code>
// Start a simple clock task that updates a div once per second
var task = {
run: function(){
Ext.fly('clock').update(new Date().format('g:i:s A'));
},
interval: 1000 //1 second
}
Ext.TaskMgr.start(task);
</code></pre>
* <p>See the {@link #start} method for details about how to configure a task object.</p>
* @singleton
*/
Ext.TaskMgr = new Ext.util.TaskRunner(); (function () {
	var libFlyweight;

	function fly(el) {
		if (!libFlyweight) {
			libFlyweight = new Ext.Element.Flyweight();
		}
		libFlyweight.dom = el;
		return libFlyweight;
	}

	(function () {
		var doc = document,
		isCSS1 = doc.compatMode == "CSS1Compat",
		MAX = Math.max,
        ROUND = Math.round,
		PARSEINT = parseInt;

		Ext.lib.Dom = {
			isAncestor: function (p, c) {
				var ret = false;

				p = Ext.getDom(p);
				c = Ext.getDom(c);
				if (p && c) {
					if (p.contains) {
						return p.contains(c);
					} else if (p.compareDocumentPosition) {
						return !!(p.compareDocumentPosition(c) & 16);
					} else {
						while (c = c.parentNode) {
							ret = c == p || ret;
						}
					}
				}
				return ret;
			},

			getViewWidth: function (full) {
				return full ? this.getDocumentWidth() : this.getViewportWidth();
			},

			getViewHeight: function (full) {
				return full ? this.getDocumentHeight() : this.getViewportHeight();
			},

			getDocumentHeight: function () {
				return MAX(!isCSS1 ? doc.body.scrollHeight : doc.documentElement.scrollHeight, this.getViewportHeight());
			},

			getDocumentWidth: function () {
				return MAX(!isCSS1 ? doc.body.scrollWidth : doc.documentElement.scrollWidth, this.getViewportWidth());
			},

			getViewportHeight: function () {
				return Ext.isIE ?
	        	   (Ext.isStrict ? doc.documentElement.clientHeight : doc.body.clientHeight) :
	        	   self.innerHeight;
			},

			getViewportWidth: function () {
				return !Ext.isStrict && !Ext.isOpera ? doc.body.clientWidth :
	        	   Ext.isIE ? doc.documentElement.clientWidth : self.innerWidth;
			},

			getY: function (el) {
				return this.getXY(el)[1];
			},

			getX: function (el) {
				return this.getXY(el)[0];
			},

			getXY: function (el) {
				var p,
            	pe,
            	b,
            	bt,
            	bl,
            	dbd,
            	x = 0,
            	y = 0,
            	scroll,
            	hasAbsolute,
            	bd = (doc.body || doc.documentElement),
            	ret = [0, 0];

				el = Ext.getDom(el);

				if (el != bd) {
					if (el.getBoundingClientRect) {
						b = el.getBoundingClientRect();
						scroll = fly(document).getScroll();
						ret = [ROUND(b.left + scroll.left), ROUND(b.top + scroll.top)];
					} else {
						p = el;
						hasAbsolute = fly(el).isStyle("position", "absolute");

						while (p) {
							pe = fly(p);
							x += p.offsetLeft;
							y += p.offsetTop;

							hasAbsolute = hasAbsolute || pe.isStyle("position", "absolute");

							if (Ext.isGecko) {
								y += bt = PARSEINT(pe.getStyle("borderTopWidth"), 10) || 0;
								x += bl = PARSEINT(pe.getStyle("borderLeftWidth"), 10) || 0;

								if (p != el && !pe.isStyle('overflow', 'visible')) {
									x += bl;
									y += bt;
								}
							}
							p = p.offsetParent;
						}

						if (Ext.isSafari && hasAbsolute) {
							x -= bd.offsetLeft;
							y -= bd.offsetTop;
						}

						if (Ext.isGecko && !hasAbsolute) {
							dbd = fly(bd);
							x += PARSEINT(dbd.getStyle("borderLeftWidth"), 10) || 0;
							y += PARSEINT(dbd.getStyle("borderTopWidth"), 10) || 0;
						}

						p = el.parentNode;
						while (p && p != bd) {
							if (!Ext.isOpera || (p.tagName != 'TR' && !fly(p).isStyle("display", "inline"))) {
								x -= p.scrollLeft;
								y -= p.scrollTop;
							}
							p = p.parentNode;
						}
						ret = [x, y];
					}
				}
				return ret
			},

			setXY: function (el, xy) {
				(el = Ext.fly(el, '_setXY')).position();

				var pts = el.translatePoints(xy),
            	style = el.dom.style,
            	pos;

				for (pos in pts) {
					if (!isNaN(pts[pos])) style[pos] = pts[pos] + "px"
				}
			},

			setX: function (el, x) {
				this.setXY(el, [x, false]);
			},

			setY: function (el, y) {
				this.setXY(el, [false, y]);
			}
		};
	})(); Ext.lib.Dom.getRegion = function (el) {
		return Ext.lib.Region.getRegion(el);
	}; Ext.lib.Event = function () {
		var loadComplete = false,
        unloadListeners = {},
        retryCount = 0,
        onAvailStack = [],
        _interval,
        locked = false,
        win = window,
        doc = document,

		// constants
        POLL_RETRYS = 200,
        POLL_INTERVAL = 20,
        EL = 0,
        TYPE = 0,
        FN = 1,
        WFN = 2,
        OBJ = 2,
        ADJ_SCOPE = 3,
        SCROLLLEFT = 'scrollLeft',
        SCROLLTOP = 'scrollTop',
        UNLOAD = 'unload',
        MOUSEOVER = 'mouseover',
        MOUSEOUT = 'mouseout',
		// private
        doAdd = function () {
        	var ret;
        	if (win.addEventListener) {
        		ret = function (el, eventName, fn, capture) {
        			if (eventName == 'mouseenter') {
        				fn = fn.createInterceptor(checkRelatedTarget);
        				el.addEventListener(MOUSEOVER, fn, (capture));
        			} else if (eventName == 'mouseleave') {
        				fn = fn.createInterceptor(checkRelatedTarget);
        				el.addEventListener(MOUSEOUT, fn, (capture));
        			} else {
        				el.addEventListener(eventName, fn, (capture));
        			}
        			return fn;
        		};
        	} else if (win.attachEvent) {
        		ret = function (el, eventName, fn, capture) {
        			el.attachEvent("on" + eventName, fn);
        			return fn;
        		};
        	} else {
        		ret = function () { };
        	}
        	return ret;
        } (),
		// private
        doRemove = function () {
        	var ret;
        	if (win.removeEventListener) {
        		ret = function (el, eventName, fn, capture) {
        			if (eventName == 'mouseenter') {
        				eventName = MOUSEOVER;
        			} else if (eventName == 'mouseleave') {
        				eventName = MOUSEOUT;
        			}
        			el.removeEventListener(eventName, fn, (capture));
        		};
        	} else if (win.detachEvent) {
        		ret = function (el, eventName, fn) {
        			el.detachEvent("on" + eventName, fn);
        		};
        	} else {
        		ret = function () { };
        	}
        	return ret;
        } ();

		function checkRelatedTarget(e) {
			return !elContains(e.currentTarget, pub.getRelatedTarget(e));
		}

		function elContains(parent, child) {
			if (parent && parent.firstChild) {
				while (child) {
					if (child === parent) {
						return true;
					}
					child = child.parentNode;
					if (child && (child.nodeType != 1)) {
						child = null;
					}
				}
			}
			return false;
		}

		// private
		function _tryPreloadAttach() {
			var ret = false,
            notAvail = [],
            element, i, v, override,
            tryAgain = !loadComplete || (retryCount > 0);

			if (!locked) {
				locked = true;

				for (i = 0; i < onAvailStack.length; ++i) {
					v = onAvailStack[i];
					if (v && (element = doc.getElementById(v.id))) {
						if (!v.checkReady || loadComplete || element.nextSibling || (doc && doc.body)) {
							override = v.override;
							element = override ? (override === true ? v.obj : override) : element;
							v.fn.call(element, v.obj);
							onAvailStack.remove(v);
							--i;
						} else {
							notAvail.push(v);
						}
					}
				}

				retryCount = (notAvail.length === 0) ? 0 : retryCount - 1;

				if (tryAgain) {
					startInterval();
				} else {
					clearInterval(_interval);
					_interval = null;
				}
				ret = !(locked = false);
			}
			return ret;
		}

		// private
		function startInterval() {
			if (!_interval) {
				var callback = function () {
					_tryPreloadAttach();
				};
				_interval = setInterval(callback, POLL_INTERVAL);
			}
		}

		// private
		function getScroll() {
			var dd = doc.documentElement,
            db = doc.body;
			if (dd && (dd[SCROLLTOP] || dd[SCROLLLEFT])) {
				return [dd[SCROLLLEFT], dd[SCROLLTOP]];
			} else if (db) {
				return [db[SCROLLLEFT], db[SCROLLTOP]];
			} else {
				return [0, 0];
			}
		}

		// private
		function getPageCoord(ev, xy) {
			ev = ev.browserEvent || ev;
			var coord = ev['page' + xy];
			if (!coord && coord !== 0) {
				coord = ev['client' + xy] || 0;

				if (Ext.isIE) {
					coord += getScroll()[xy == "X" ? 0 : 1];
				}
			}

			return coord;
		}

		var pub = {
			extAdapter: true,
			onAvailable: function (p_id, p_fn, p_obj, p_override) {
				onAvailStack.push({
					id: p_id,
					fn: p_fn,
					obj: p_obj,
					override: p_override,
					checkReady: false
				});

				retryCount = POLL_RETRYS;
				startInterval();
			},

			// This function should ALWAYS be called from Ext.EventManager
			addListener: function (el, eventName, fn) {
				el = Ext.getDom(el);
				if (el && fn) {
					if (eventName == UNLOAD) {
						if (unloadListeners[el.id] === undefined) {
							unloadListeners[el.id] = [];
						}
						unloadListeners[el.id].push([eventName, fn]);
						return fn;
					}
					return doAdd(el, eventName, fn, false);
				}
				return false;
			},

			// This function should ALWAYS be called from Ext.EventManager
			removeListener: function (el, eventName, fn) {
				el = Ext.getDom(el);
				var i, len, li, lis;
				if (el && fn) {
					if (eventName == UNLOAD) {
						if ((lis = unloadListeners[el.id]) !== undefined) {
							for (i = 0, len = lis.length; i < len; i++) {
								if ((li = lis[i]) && li[TYPE] == eventName && li[FN] == fn) {
									unloadListeners[el.id].splice(i, 1);
								}
							}
						}
						return;
					}
					doRemove(el, eventName, fn, false);
				}
			},

			getTarget: function (ev) {
				ev = ev.browserEvent || ev;
				return this.resolveTextNode(ev.target || ev.srcElement);
			},

			resolveTextNode: Ext.isGecko ? function (node) {
				if (!node) {
					return;
				}
				// work around firefox bug, https://bugzilla.mozilla.org/show_bug.cgi?id=101197
				var s = HTMLElement.prototype.toString.call(node);
				if (s == '[xpconnect wrapped native prototype]' || s == '[object XULElement]') {
					return;
				}
				return node.nodeType == 3 ? node.parentNode : node;
			} : function (node) {
				return node && node.nodeType == 3 ? node.parentNode : node;
			},

			getRelatedTarget: function (ev) {
				ev = ev.browserEvent || ev;
				return this.resolveTextNode(ev.relatedTarget ||
                    (ev.type == MOUSEOUT ? ev.toElement :
                     ev.type == MOUSEOVER ? ev.fromElement : null));
			},

			getPageX: function (ev) {
				return getPageCoord(ev, "X");
			},

			getPageY: function (ev) {
				return getPageCoord(ev, "Y");
			},


			getXY: function (ev) {
				return [this.getPageX(ev), this.getPageY(ev)];
			},

			stopEvent: function (ev) {
				this.stopPropagation(ev);
				this.preventDefault(ev);
			},

			stopPropagation: function (ev) {
				ev = ev.browserEvent || ev;
				if (ev.stopPropagation) {
					ev.stopPropagation();
				} else {
					ev.cancelBubble = true;
				}
			},

			preventDefault: function (ev) {
				ev = ev.browserEvent || ev;
				if (ev.preventDefault) {
					ev.preventDefault();
				} else {
					ev.returnValue = false;
				}
			},

			getEvent: function (e) {
				e = e || win.event;
				if (!e) {
					var c = this.getEvent.caller;
					while (c) {
						e = c.arguments[0];
						if (e && Event == e.constructor) {
							break;
						}
						c = c.caller;
					}
				}
				return e;
			},

			getCharCode: function (ev) {
				ev = ev.browserEvent || ev;
				return ev.charCode || ev.keyCode || 0;
			},

			//clearCache: function() {},
			// deprecated, call from EventManager
			getListeners: function (el, eventName) {
				Ext.EventManager.getListeners(el, eventName);
			},

			// deprecated, call from EventManager
			purgeElement: function (el, recurse, eventName) {
				Ext.EventManager.purgeElement(el, recurse, eventName);
			},

			_load: function (e) {
				loadComplete = true;
				var EU = Ext.lib.Event;
				if (Ext.isIE && e !== true) {
					// IE8 complains that _load is null or not an object
					// so lets remove self via arguments.callee
					doRemove(win, "load", arguments.callee);
				}
			},

			_unload: function (e) {
				var EU = Ext.lib.Event,
                i, j, l, v, ul, id, len, index, scope;


				for (id in unloadListeners) {
					ul = unloadListeners[id];
					for (i = 0, len = ul.length; i < len; i++) {
						v = ul[i];
						if (v) {
							try {
								scope = v[ADJ_SCOPE] ? (v[ADJ_SCOPE] === true ? v[OBJ] : v[ADJ_SCOPE]) : win;
								v[FN].call(scope, EU.getEvent(e), v[OBJ]);
							} catch (ex) { }
						}
					}
				};

				Ext.EventManager._unload();

				doRemove(win, UNLOAD, EU._unload);
			}
		};

		// Initialize stuff.
		pub.on = pub.addListener;
		pub.un = pub.removeListener;
		if (doc && doc.body) {
			pub._load(true);
		} else {
			doAdd(win, "load", pub._load);
		}
		doAdd(win, UNLOAD, pub._unload);
		_tryPreloadAttach();

		return pub;
	} ();
	/*
	* Portions of this file are based on pieces of Yahoo User Interface Library
	* Copyright (c) 2007, Yahoo! Inc. All rights reserved.
	* YUI licensed under the BSD License:
	* http://developer.yahoo.net/yui/license.txt
	*/
	Ext.lib.Ajax = function () {
		var activeX = ['MSXML2.XMLHTTP.3.0',
                   'MSXML2.XMLHTTP',
                   'Microsoft.XMLHTTP'],
        CONTENTTYPE = 'Content-Type';

		// private
		function setHeader(o) {
			var conn = o.conn,
            prop;

			function setTheHeaders(conn, headers) {
				for (prop in headers) {
					if (headers.hasOwnProperty(prop)) {
						conn.setRequestHeader(prop, headers[prop]);
					}
				}
			}

			if (pub.defaultHeaders) {
				setTheHeaders(conn, pub.defaultHeaders);
			}

			if (pub.headers) {
				setTheHeaders(conn, pub.headers);
				delete pub.headers;
			}
		}

		// private
		function createExceptionObject(tId, callbackArg, isAbort, isTimeout) {
			return {
				tId: tId,
				status: isAbort ? -1 : 0,
				statusText: isAbort ? 'transaction aborted' : 'communication failure',
				isAbort: isAbort,
				isTimeout: isTimeout,
				argument: callbackArg
			};
		}

		// private
		function initHeader(label, value) {
			(pub.headers = pub.headers || {})[label] = value;
		}

		// private
		function createResponseObject(o, callbackArg) {
			var headerObj = {},
            headerStr,
            conn = o.conn,
            t,
            s,
			// see: https://prototype.lighthouseapp.com/projects/8886/tickets/129-ie-mangles-http-response-status-code-204-to-1223
            isBrokenStatus = conn.status == 1223;

			try {
				headerStr = o.conn.getAllResponseHeaders();
				Ext.each(headerStr.replace(/\r\n/g, '\n').split('\n'), function (v) {
					t = v.indexOf(':');
					if (t >= 0) {
						s = v.substr(0, t).toLowerCase();
						if (v.charAt(t + 1) == ' ') {
							++t;
						}
						headerObj[s] = v.substr(t + 1);
					}
				});
			} catch (e) { }

			return {
				tId: o.tId,
				// Normalize the status and statusText when IE returns 1223, see the above link.
				status: isBrokenStatus ? 204 : conn.status,
				statusText: isBrokenStatus ? 'No Content' : conn.statusText,
				getResponseHeader: function (header) { return headerObj[header.toLowerCase()]; },
				getAllResponseHeaders: function () { return headerStr },
				responseText: conn.responseText,
				responseXML: conn.responseXML,
				argument: callbackArg
			};
		}

		// private
		function releaseObject(o) {
			if (o.tId) {
				pub.conn[o.tId] = null;
			}
			o.conn = null;
			o = null;
		}

		// private
		function handleTransactionResponse(o, callback, isAbort, isTimeout) {
			if (!callback) {
				releaseObject(o);
				return;
			}

			var httpStatus, responseObject;

			try {
				if (o.conn.status !== undefined && o.conn.status != 0) {
					httpStatus = o.conn.status;
				}
				else {
					httpStatus = 13030;
				}
			}
			catch (e) {
				httpStatus = 13030;
			}

			if ((httpStatus >= 200 && httpStatus < 300) || (Ext.isIE && httpStatus == 1223)) {
				responseObject = createResponseObject(o, callback.argument);
				if (callback.success) {
					if (!callback.scope) {
						callback.success(responseObject);
					}
					else {
						callback.success.apply(callback.scope, [responseObject]);
					}
				}
			}
			else {
				switch (httpStatus) {
					case 12002:
					case 12029:
					case 12030:
					case 12031:
					case 12152:
					case 13030:
						responseObject = createExceptionObject(o.tId, callback.argument, (isAbort ? isAbort : false), isTimeout);
						if (callback.failure) {
							if (!callback.scope) {
								callback.failure(responseObject);
							}
							else {
								callback.failure.apply(callback.scope, [responseObject]);
							}
						}
						break;
					default:
						responseObject = createResponseObject(o, callback.argument);
						if (callback.failure) {
							if (!callback.scope) {
								callback.failure(responseObject);
							}
							else {
								callback.failure.apply(callback.scope, [responseObject]);
							}
						}
				}
			}

			releaseObject(o);
			responseObject = null;
		}

		// private
		function handleReadyState(o, callback) {
			callback = callback || {};
			var conn = o.conn,
            tId = o.tId,
            poll = pub.poll,
            cbTimeout = callback.timeout || null;

			if (cbTimeout) {
				pub.conn[tId] = conn;
				pub.timeout[tId] = setTimeout(function () {
					pub.abort(o, callback, true);
				}, cbTimeout);
			}

			poll[tId] = setInterval(
            function () {
            	if (conn && conn.readyState == 4) {
            		clearInterval(poll[tId]);
            		poll[tId] = null;

            		if (cbTimeout) {
            			clearTimeout(pub.timeout[tId]);
            			pub.timeout[tId] = null;
            		}

            		handleTransactionResponse(o, callback);
            	}
            },
            pub.pollInterval);
		}

		// private
		function asyncRequest(method, uri, callback, postData) {
			var o = getConnectionObject() || null;

			if (o) {
				o.conn.open(method, uri, true);

				if (pub.useDefaultXhrHeader) {
					initHeader('X-Requested-With', pub.defaultXhrHeader);
				}

				if (postData && pub.useDefaultHeader && (!pub.headers || !pub.headers[CONTENTTYPE])) {
					initHeader(CONTENTTYPE, pub.defaultPostHeader);
				}

				if (pub.defaultHeaders || pub.headers) {
					setHeader(o);
				}

				handleReadyState(o, callback);
				o.conn.send(postData || null);
			}
			return o;
		}

		// private
		function getConnectionObject() {
			var o;

			try {
				if (o = createXhrObject(pub.transactionId)) {
					pub.transactionId++;
				}
			} catch (e) {
			} finally {
				return o;
			}
		}

		// private
		function createXhrObject(transactionId) {
			var http;

			try {
				http = new XMLHttpRequest();
			} catch (e) {
				for (var i = 0; i < activeX.length; ++i) {
					try {
						http = new ActiveXObject(activeX[i]);
						break;
					} catch (e) { }
				}
			} finally {
				return { conn: http, tId: transactionId };
			}
		}

		var pub = {
			request: function (method, uri, cb, data, options) {
				if (options) {
					var me = this,
                    xmlData = options.xmlData,
                    jsonData = options.jsonData,
                    hs;

					Ext.applyIf(me, options);

					if (xmlData || jsonData) {
						hs = me.headers;
						if (!hs || !hs[CONTENTTYPE]) {
							initHeader(CONTENTTYPE, xmlData ? 'text/xml' : 'application/json');
						}
						data = xmlData || (!Ext.isPrimitive(jsonData) ? Ext.encode(jsonData) : jsonData);
					}
				}
				return asyncRequest(method || options.method || "POST", uri, cb, data);
			},

			serializeForm: function (form) {
				var fElements = form.elements || (document.forms[form] || Ext.getDom(form)).elements,
                hasSubmit = false,
                encoder = encodeURIComponent,
                element,
                options,
                name,
                val,
                data = '',
                type;

				Ext.each(fElements, function (element) {
					name = element.name;
					type = element.type;

					if (!element.disabled && name) {
						if (/select-(one|multiple)/i.test(type)) {
							Ext.each(element.options, function (opt) {
								if (opt.selected) {
									data += String.format("{0}={1}&", encoder(name), encoder((opt.hasAttribute ? opt.hasAttribute('value') : opt.getAttribute('value') !== null) ? opt.value : opt.text));
								}
							});
						} else if (!/file|undefined|reset|button/i.test(type)) {
							if (!(/radio|checkbox/i.test(type) && !element.checked) && !(type == 'submit' && hasSubmit)) {

								data += encoder(name) + '=' + encoder(element.value) + '&';
								hasSubmit = /submit/i.test(type);
							}
						}
					}
				});
				return data.substr(0, data.length - 1);
			},

			useDefaultHeader: true,
			defaultPostHeader: 'application/x-www-form-urlencoded; charset=UTF-8',
			useDefaultXhrHeader: true,
			defaultXhrHeader: 'XMLHttpRequest',
			poll: {},
			timeout: {},
			conn: {},
			pollInterval: 50,
			transactionId: 0,

			//  This is never called - Is it worth exposing this?
			//          setProgId : function(id) {
			//              activeX.unshift(id);
			//          },

			//  This is never called - Is it worth exposing this?
			//          setDefaultPostHeader : function(b) {
			//              this.useDefaultHeader = b;
			//          },

			//  This is never called - Is it worth exposing this?
			//          setDefaultXhrHeader : function(b) {
			//              this.useDefaultXhrHeader = b;
			//          },

			//  This is never called - Is it worth exposing this?
			//          setPollingInterval : function(i) {
			//              if (typeof i == 'number' && isFinite(i)) {
			//                  this.pollInterval = i;
			//              }
			//          },

			//  This is never called - Is it worth exposing this?
			//          resetDefaultHeaders : function() {
			//              this.defaultHeaders = null;
			//          },

			abort: function (o, callback, isTimeout) {
				var me = this,
                tId = o.tId,
                isAbort = false;

				if (me.isCallInProgress(o)) {
					o.conn.abort();
					clearInterval(me.poll[tId]);
					me.poll[tId] = null;
					clearTimeout(pub.timeout[tId]);
					me.timeout[tId] = null;

					handleTransactionResponse(o, callback, (isAbort = true), isTimeout);
				}
				return isAbort;
			},

			isCallInProgress: function (o) {
				// if there is a connection and readyState is not 0 or 4
				return o.conn && !{ 0: true, 4: true}[o.conn.readyState];
			}
		};
		return pub;
	} (); Ext.lib.Region = function (t, r, b, l) {
		var me = this;
		me.top = t;
		me[1] = t;
		me.right = r;
		me.bottom = b;
		me.left = l;
		me[0] = l;
	};

	Ext.lib.Region.prototype = {
		contains: function (region) {
			var me = this;
			return (region.left >= me.left &&
                     region.right <= me.right &&
                     region.top >= me.top &&
                     region.bottom <= me.bottom);

		},

		getArea: function () {
			var me = this;
			return ((me.bottom - me.top) * (me.right - me.left));
		},

		intersect: function (region) {
			var me = this,
            	t = Math.max(me.top, region.top),
            	r = Math.min(me.right, region.right),
            	b = Math.min(me.bottom, region.bottom),
            	l = Math.max(me.left, region.left);

			if (b >= t && r >= l) {
				return new Ext.lib.Region(t, r, b, l);
			}
		},

		union: function (region) {
			var me = this,
            	t = Math.min(me.top, region.top),
            	r = Math.max(me.right, region.right),
            	b = Math.max(me.bottom, region.bottom),
            	l = Math.min(me.left, region.left);

			return new Ext.lib.Region(t, r, b, l);
		},

		constrainTo: function (r) {
			var me = this;
			me.top = me.top.constrain(r.top, r.bottom);
			me.bottom = me.bottom.constrain(r.top, r.bottom);
			me.left = me.left.constrain(r.left, r.right);
			me.right = me.right.constrain(r.left, r.right);
			return me;
		},

		adjust: function (t, l, b, r) {
			var me = this;
			me.top += t;
			me.left += l;
			me.right += r;
			me.bottom += b;
			return me;
		}
	};

	Ext.lib.Region.getRegion = function (el) {
		var p = Ext.lib.Dom.getXY(el),
        	t = p[1],
        	r = p[0] + el.offsetWidth,
        	b = p[1] + el.offsetHeight,
        	l = p[0];

		return new Ext.lib.Region(t, r, b, l);
	}; Ext.lib.Point = function (x, y) {
		if (Ext.isArray(x)) {
			y = x[1];
			x = x[0];
		}
		var me = this;
		me.x = me.right = me.left = me[0] = x;
		me.y = me.top = me.bottom = me[1] = y;
	};

	Ext.lib.Point.prototype = new Ext.lib.Region();
	(function () {
		var EXTLIB = Ext.lib,
        noNegatives = /width|height|opacity|padding/i,
        offsetAttribute = /^((width|height)|(top|left))$/,
        defaultUnit = /width|height|top$|bottom$|left$|right$/i,
        offsetUnit = /\d+(em|%|en|ex|pt|in|cm|mm|pc)$/i,
        isset = function (v) {
        	return typeof v !== 'undefined';
        },
        now = function () {
        	return new Date();
        };

		EXTLIB.Anim = {
			motion: function (el, args, duration, easing, cb, scope) {
				return this.run(el, args, duration, easing, cb, scope, Ext.lib.Motion);
			},

			run: function (el, args, duration, easing, cb, scope, type) {
				type = type || Ext.lib.AnimBase;
				if (typeof easing == "string") {
					easing = Ext.lib.Easing[easing];
				}
				var anim = new type(el, args, duration, easing);
				anim.animateX(function () {
					if (Ext.isFunction(cb)) {
						cb.call(scope);
					}
				});
				return anim;
			}
		};

		EXTLIB.AnimBase = function (el, attributes, duration, method) {
			if (el) {
				this.init(el, attributes, duration, method);
			}
		};

		EXTLIB.AnimBase.prototype = {
			doMethod: function (attr, start, end) {
				var me = this;
				return me.method(me.curFrame, start, end - start, me.totalFrames);
			},


			setAttr: function (attr, val, unit) {
				if (noNegatives.test(attr) && val < 0) {
					val = 0;
				}
				Ext.fly(this.el, '_anim').setStyle(attr, val + unit);
			},


			getAttr: function (attr) {
				var el = Ext.fly(this.el),
                val = el.getStyle(attr),
                a = offsetAttribute.exec(attr) || [];

				if (val !== 'auto' && !offsetUnit.test(val)) {
					return parseFloat(val);
				}

				return (!!(a[2]) || (el.getStyle('position') == 'absolute' && !!(a[3]))) ? el.dom['offset' + a[0].charAt(0).toUpperCase() + a[0].substr(1)] : 0;
			},


			getDefaultUnit: function (attr) {
				return defaultUnit.test(attr) ? 'px' : '';
			},

			animateX: function (callback, scope) {
				var me = this,
                f = function () {
                	me.onComplete.removeListener(f);
                	if (Ext.isFunction(callback)) {
                		callback.call(scope || me, me);
                	}
                };
				me.onComplete.addListener(f, me);
				me.animate();
			},


			setRunAttr: function (attr) {
				var me = this,
                a = this.attributes[attr],
                to = a.to,
                by = a.by,
                from = a.from,
                unit = a.unit,
                ra = (this.runAttrs[attr] = {}),
                end;

				if (!isset(to) && !isset(by)) {
					return false;
				}

				var start = isset(from) ? from : me.getAttr(attr);
				if (isset(to)) {
					end = to;
				} else if (isset(by)) {
					if (Ext.isArray(start)) {
						end = [];
						for (var i = 0, len = start.length; i < len; i++) {
							end[i] = start[i] + by[i];
						}
					} else {
						end = start + by;
					}
				}

				Ext.apply(ra, {
					start: start,
					end: end,
					unit: isset(unit) ? unit : me.getDefaultUnit(attr)
				});
			},


			init: function (el, attributes, duration, method) {
				var me = this,
                actualFrames = 0,
                mgr = EXTLIB.AnimMgr;

				Ext.apply(me, {
					isAnimated: false,
					startTime: null,
					el: Ext.getDom(el),
					attributes: attributes || {},
					duration: duration || 1,
					method: method || EXTLIB.Easing.easeNone,
					useSec: true,
					curFrame: 0,
					totalFrames: mgr.fps,
					runAttrs: {},
					animate: function () {
						var me = this,
                        d = me.duration;

						if (me.isAnimated) {
							return false;
						}

						me.curFrame = 0;
						me.totalFrames = me.useSec ? Math.ceil(mgr.fps * d) : d;
						mgr.registerElement(me);
					},

					stop: function (finish) {
						var me = this;

						if (finish) {
							me.curFrame = me.totalFrames;
							me._onTween.fire();
						}
						mgr.stop(me);
					}
				});

				var onStart = function () {
					var me = this,
                    attr;

					me.onStart.fire();
					me.runAttrs = {};
					for (attr in this.attributes) {
						this.setRunAttr(attr);
					}

					me.isAnimated = true;
					me.startTime = now();
					actualFrames = 0;
				};


				var onTween = function () {
					var me = this;

					me.onTween.fire({
						duration: now() - me.startTime,
						curFrame: me.curFrame
					});

					var ra = me.runAttrs;
					for (var attr in ra) {
						this.setAttr(attr, me.doMethod(attr, ra[attr].start, ra[attr].end), ra[attr].unit);
					}

					++actualFrames;
				};

				var onComplete = function () {
					var me = this,
                    actual = (now() - me.startTime) / 1000,
                    data = {
                    	duration: actual,
                    	frames: actualFrames,
                    	fps: actualFrames / actual
                    };

					me.isAnimated = false;
					actualFrames = 0;
					me.onComplete.fire(data);
				};

				me.onStart = new Ext.util.Event(me);
				me.onTween = new Ext.util.Event(me);
				me.onComplete = new Ext.util.Event(me);
				(me._onStart = new Ext.util.Event(me)).addListener(onStart);
				(me._onTween = new Ext.util.Event(me)).addListener(onTween);
				(me._onComplete = new Ext.util.Event(me)).addListener(onComplete);
			}
		};


		Ext.lib.AnimMgr = new function () {
			var me = this,
            thread = null,
            queue = [],
            tweenCount = 0;


			Ext.apply(me, {
				fps: 1000,
				delay: 1,
				registerElement: function (tween) {
					queue.push(tween);
					++tweenCount;
					tween._onStart.fire();
					me.start();
				},

				unRegister: function (tween, index) {
					tween._onComplete.fire();
					index = index || getIndex(tween);
					if (index != -1) {
						queue.splice(index, 1);
					}

					if (--tweenCount <= 0) {
						me.stop();
					}
				},

				start: function () {
					if (thread === null) {
						thread = setInterval(me.run, me.delay);
					}
				},

				stop: function (tween) {
					if (!tween) {
						clearInterval(thread);
						for (var i = 0, len = queue.length; i < len; ++i) {
							if (queue[0].isAnimated) {
								me.unRegister(queue[0], 0);
							}
						}

						queue = [];
						thread = null;
						tweenCount = 0;
					} else {
						me.unRegister(tween);
					}
				},

				run: function () {
					var tf, i, len, tween;
					for (i = 0, len = queue.length; i < len; i++) {
						tween = queue[i];
						if (tween && tween.isAnimated) {
							tf = tween.totalFrames;
							if (tween.curFrame < tf || tf === null) {
								++tween.curFrame;
								if (tween.useSec) {
									correctFrame(tween);
								}
								tween._onTween.fire();
							} else {
								me.stop(tween);
							}
						}
					}
				}
			});

			var getIndex = function (anim) {
				var i, len;
				for (i = 0, len = queue.length; i < len; i++) {
					if (queue[i] === anim) {
						return i;
					}
				}
				return -1;
			};

			var correctFrame = function (tween) {
				var frames = tween.totalFrames,
                frame = tween.curFrame,
                duration = tween.duration,
                expected = (frame * duration * 1000 / frames),
                elapsed = (now() - tween.startTime),
                tweak = 0;

				if (elapsed < duration * 1000) {
					tweak = Math.round((elapsed / expected - 1) * frame);
				} else {
					tweak = frames - (frame + 1);
				}
				if (tweak > 0 && isFinite(tweak)) {
					if (tween.curFrame + tweak >= frames) {
						tweak = frames - (frame + 1);
					}
					tween.curFrame += tweak;
				}
			};
		};

		EXTLIB.Bezier = new function () {

			this.getPosition = function (points, t) {
				var n = points.length,
                tmp = [],
                c = 1 - t,
                i,
                j;

				for (i = 0; i < n; ++i) {
					tmp[i] = [points[i][0], points[i][1]];
				}

				for (j = 1; j < n; ++j) {
					for (i = 0; i < n - j; ++i) {
						tmp[i][0] = c * tmp[i][0] + t * tmp[parseInt(i + 1, 10)][0];
						tmp[i][1] = c * tmp[i][1] + t * tmp[parseInt(i + 1, 10)][1];
					}
				}

				return [tmp[0][0], tmp[0][1]];

			};
		};


		EXTLIB.Easing = {
			easeNone: function (t, b, c, d) {
				return c * t / d + b;
			},


			easeIn: function (t, b, c, d) {
				return c * (t /= d) * t + b;
			},


			easeOut: function (t, b, c, d) {
				return -c * (t /= d) * (t - 2) + b;
			}
		};

		(function () {
			EXTLIB.Motion = function (el, attributes, duration, method) {
				if (el) {
					EXTLIB.Motion.superclass.constructor.call(this, el, attributes, duration, method);
				}
			};

			Ext.extend(EXTLIB.Motion, Ext.lib.AnimBase);

			var superclass = EXTLIB.Motion.superclass,
            proto = EXTLIB.Motion.prototype,
            pointsRe = /^points$/i;

			Ext.apply(EXTLIB.Motion.prototype, {
				setAttr: function (attr, val, unit) {
					var me = this,
                    setAttr = superclass.setAttr;

					if (pointsRe.test(attr)) {
						unit = unit || 'px';
						setAttr.call(me, 'left', val[0], unit);
						setAttr.call(me, 'top', val[1], unit);
					} else {
						setAttr.call(me, attr, val, unit);
					}
				},

				getAttr: function (attr) {
					var me = this,
                    getAttr = superclass.getAttr;

					return pointsRe.test(attr) ? [getAttr.call(me, 'left'), getAttr.call(me, 'top')] : getAttr.call(me, attr);
				},

				doMethod: function (attr, start, end) {
					var me = this;

					return pointsRe.test(attr)
                        ? EXTLIB.Bezier.getPosition(me.runAttrs[attr], me.method(me.curFrame, 0, 100, me.totalFrames) / 100)
                        : superclass.doMethod.call(me, attr, start, end);
				},

				setRunAttr: function (attr) {
					if (pointsRe.test(attr)) {

						var me = this,
                        el = this.el,
                        points = this.attributes.points,
                        control = points.control || [],
                        from = points.from,
                        to = points.to,
                        by = points.by,
                        DOM = EXTLIB.Dom,
                        start,
                        i,
                        end,
                        len,
                        ra;


						if (control.length > 0 && !Ext.isArray(control[0])) {
							control = [control];
						} else {
							/*
							var tmp = [];
							for (i = 0,len = control.length; i < len; ++i) {
							tmp[i] = control[i];
							}
							control = tmp;
							*/
						}

						Ext.fly(el, '_anim').position();
						DOM.setXY(el, isset(from) ? from : DOM.getXY(el));
						start = me.getAttr('points');


						if (isset(to)) {
							end = translateValues.call(me, to, start);
							for (i = 0, len = control.length; i < len; ++i) {
								control[i] = translateValues.call(me, control[i], start);
							}
						} else if (isset(by)) {
							end = [start[0] + by[0], start[1] + by[1]];

							for (i = 0, len = control.length; i < len; ++i) {
								control[i] = [start[0] + control[i][0], start[1] + control[i][1]];
							}
						}

						ra = this.runAttrs[attr] = [start];
						if (control.length > 0) {
							ra = ra.concat(control);
						}

						ra[ra.length] = end;
					} else {
						superclass.setRunAttr.call(this, attr);
					}
				}
			});

			var translateValues = function (val, start) {
				var pageXY = EXTLIB.Dom.getXY(this.el);
				return [val[0] - pageXY[0] + start[0], val[1] - pageXY[1] + start[1]];
			};
		})();
	})(); // Easing functions
	(function () {
		// shortcuts to aid compression
		var abs = Math.abs,
        pi = Math.PI,
        asin = Math.asin,
        pow = Math.pow,
        sin = Math.sin,
        EXTLIB = Ext.lib;

		Ext.apply(EXTLIB.Easing, {

			easeBoth: function (t, b, c, d) {
				return ((t /= d / 2) < 1) ? c / 2 * t * t + b : -c / 2 * ((--t) * (t - 2) - 1) + b;
			},

			easeInStrong: function (t, b, c, d) {
				return c * (t /= d) * t * t * t + b;
			},

			easeOutStrong: function (t, b, c, d) {
				return -c * ((t = t / d - 1) * t * t * t - 1) + b;
			},

			easeBothStrong: function (t, b, c, d) {
				return ((t /= d / 2) < 1) ? c / 2 * t * t * t * t + b : -c / 2 * ((t -= 2) * t * t * t - 2) + b;
			},

			elasticIn: function (t, b, c, d, a, p) {
				if (t == 0 || (t /= d) == 1) {
					return t == 0 ? b : b + c;
				}
				p = p || (d * .3);

				var s;
				if (a >= abs(c)) {
					s = p / (2 * pi) * asin(c / a);
				} else {
					a = c;
					s = p / 4;
				}

				return -(a * pow(2, 10 * (t -= 1)) * sin((t * d - s) * (2 * pi) / p)) + b;

			},

			elasticOut: function (t, b, c, d, a, p) {
				if (t == 0 || (t /= d) == 1) {
					return t == 0 ? b : b + c;
				}
				p = p || (d * .3);

				var s;
				if (a >= abs(c)) {
					s = p / (2 * pi) * asin(c / a);
				} else {
					a = c;
					s = p / 4;
				}

				return a * pow(2, -10 * t) * sin((t * d - s) * (2 * pi) / p) + c + b;
			},

			elasticBoth: function (t, b, c, d, a, p) {
				if (t == 0 || (t /= d / 2) == 2) {
					return t == 0 ? b : b + c;
				}

				p = p || (d * (.3 * 1.5));

				var s;
				if (a >= abs(c)) {
					s = p / (2 * pi) * asin(c / a);
				} else {
					a = c;
					s = p / 4;
				}

				return t < 1 ?
                    -.5 * (a * pow(2, 10 * (t -= 1)) * sin((t * d - s) * (2 * pi) / p)) + b :
                    a * pow(2, -10 * (t -= 1)) * sin((t * d - s) * (2 * pi) / p) * .5 + c + b;
			},

			backIn: function (t, b, c, d, s) {
				s = s || 1.70158;
				return c * (t /= d) * t * ((s + 1) * t - s) + b;
			},


			backOut: function (t, b, c, d, s) {
				if (!s) {
					s = 1.70158;
				}
				return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
			},


			backBoth: function (t, b, c, d, s) {
				s = s || 1.70158;

				return ((t /= d / 2) < 1) ?
                    c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b :
                    c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;
			},


			bounceIn: function (t, b, c, d) {
				return c - EXTLIB.Easing.bounceOut(d - t, 0, c, d) + b;
			},


			bounceOut: function (t, b, c, d) {
				if ((t /= d) < (1 / 2.75)) {
					return c * (7.5625 * t * t) + b;
				} else if (t < (2 / 2.75)) {
					return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b;
				} else if (t < (2.5 / 2.75)) {
					return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b;
				}
				return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b;
			},


			bounceBoth: function (t, b, c, d) {
				return (t < d / 2) ?
                    EXTLIB.Easing.bounceIn(t * 2, 0, c, d) * .5 + b :
                    EXTLIB.Easing.bounceOut(t * 2 - d, 0, c, d) * .5 + c * .5 + b;
			}
		});
	})();

	(function () {
		var EXTLIB = Ext.lib;
		// Color Animation
		EXTLIB.Anim.color = function (el, args, duration, easing, cb, scope) {
			return EXTLIB.Anim.run(el, args, duration, easing, cb, scope, EXTLIB.ColorAnim);
		}

		EXTLIB.ColorAnim = function (el, attributes, duration, method) {
			EXTLIB.ColorAnim.superclass.constructor.call(this, el, attributes, duration, method);
		};

		Ext.extend(EXTLIB.ColorAnim, EXTLIB.AnimBase);

		var superclass = EXTLIB.ColorAnim.superclass,
        colorRE = /color$/i,
        transparentRE = /^transparent|rgba\(0, 0, 0, 0\)$/,
        rgbRE = /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i,
        hexRE = /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i,
        hex3RE = /^#?([0-9A-F]{1})([0-9A-F]{1})([0-9A-F]{1})$/i,
        isset = function (v) {
        	return typeof v !== 'undefined';
        };

		// private
		function parseColor(s) {
			var pi = parseInt,
            base,
            out = null,
            c;

			if (s.length == 3) {
				return s;
			}

			Ext.each([hexRE, rgbRE, hex3RE], function (re, idx) {
				base = (idx % 2 == 0) ? 16 : 10;
				c = re.exec(s);
				if (c && c.length == 4) {
					out = [pi(c[1], base), pi(c[2], base), pi(c[3], base)];
					return false;
				}
			});
			return out;
		}

		Ext.apply(EXTLIB.ColorAnim.prototype, {
			getAttr: function (attr) {
				var me = this,
                el = me.el,
                val;
				if (colorRE.test(attr)) {
					while (el && transparentRE.test(val = Ext.fly(el).getStyle(attr))) {
						el = el.parentNode;
						val = "fff";
					}
				} else {
					val = superclass.getAttr.call(me, attr);
				}
				return val;
			},

			doMethod: function (attr, start, end) {
				var me = this,
                val,
                floor = Math.floor,
                i,
                len,
                v;

				if (colorRE.test(attr)) {
					val = [];
					end = end || [];

					for (i = 0, len = start.length; i < len; i++) {
						v = start[i];
						val[i] = superclass.doMethod.call(me, attr, v, end[i]);
					}
					val = 'rgb(' + floor(val[0]) + ',' + floor(val[1]) + ',' + floor(val[2]) + ')';
				} else {
					val = superclass.doMethod.call(me, attr, start, end);
				}
				return val;
			},

			setRunAttr: function (attr) {
				var me = this,
                a = me.attributes[attr],
                to = a.to,
                by = a.by,
                ra;

				superclass.setRunAttr.call(me, attr);
				ra = me.runAttrs[attr];
				if (colorRE.test(attr)) {
					var start = parseColor(ra.start),
                    end = parseColor(ra.end);

					if (!isset(to) && isset(by)) {
						end = parseColor(by);
						for (var i = 0, len = start.length; i < len; i++) {
							end[i] = start[i] + end[i];
						}
					}
					ra.start = start;
					ra.end = end;
				}
			}
		});
	})();


	(function () {
		// Scroll Animation
		var EXTLIB = Ext.lib;
		EXTLIB.Anim.scroll = function (el, args, duration, easing, cb, scope) {
			return EXTLIB.Anim.run(el, args, duration, easing, cb, scope, EXTLIB.Scroll);
		};

		EXTLIB.Scroll = function (el, attributes, duration, method) {
			if (el) {
				EXTLIB.Scroll.superclass.constructor.call(this, el, attributes, duration, method);
			}
		};

		Ext.extend(EXTLIB.Scroll, EXTLIB.ColorAnim);

		var superclass = EXTLIB.Scroll.superclass,
        SCROLL = 'scroll';

		Ext.apply(EXTLIB.Scroll.prototype, {

			doMethod: function (attr, start, end) {
				var val,
                me = this,
                curFrame = me.curFrame,
                totalFrames = me.totalFrames;

				if (attr == SCROLL) {
					val = [me.method(curFrame, start[0], end[0] - start[0], totalFrames),
                       me.method(curFrame, start[1], end[1] - start[1], totalFrames)];
				} else {
					val = superclass.doMethod.call(me, attr, start, end);
				}
				return val;
			},

			getAttr: function (attr) {
				var me = this;

				if (attr == SCROLL) {
					return [me.el.scrollLeft, me.el.scrollTop];
				} else {
					return superclass.getAttr.call(me, attr);
				}
			},

			setAttr: function (attr, val, unit) {
				var me = this;

				if (attr == SCROLL) {
					me.el.scrollLeft = val[0];
					me.el.scrollTop = val[1];
				} else {
					superclass.setAttr.call(me, attr, val, unit);
				}
			}
		});
	})();
	if (Ext.isIE) {
		function fnCleanUp() {
			var p = Function.prototype;
			delete p.createSequence;
			delete p.defer;
			delete p.createDelegate;
			delete p.createCallback;
			delete p.createInterceptor;

			window.detachEvent("onunload", fnCleanUp);
		}
		window.attachEvent("onunload", fnCleanUp);
	}
})();

/*!
* Ext JS Library 3.2.1
* Copyright(c) 2006-2010 Ext JS, Inc.
* licensing@extjs.com
* http://www.extjs.com/license
*/
/**
* @class Ext.DomHelper
* <p>The DomHelper class provides a layer of abstraction from DOM and transparently supports creating
* elements via DOM or using HTML fragments. It also has the ability to create HTML fragment templates
* from your DOM building code.</p>
*
* <p><b><u>DomHelper element specification object</u></b></p>
* <p>A specification object is used when creating elements. Attributes of this object
* are assumed to be element attributes, except for 4 special attributes:
* <div class="mdetail-params"><ul>
* <li><b><tt>tag</tt></b> : <div class="sub-desc">The tag name of the element</div></li>
* <li><b><tt>children</tt></b> : or <tt>cn</tt><div class="sub-desc">An array of the
* same kind of element definition objects to be created and appended. These can be nested
* as deep as you want.</div></li>
* <li><b><tt>cls</tt></b> : <div class="sub-desc">The class attribute of the element.
* This will end up being either the "class" attribute on a HTML fragment or className
* for a DOM node, depending on whether DomHelper is using fragments or DOM.</div></li>
* <li><b><tt>html</tt></b> : <div class="sub-desc">The innerHTML for the element</div></li>
* </ul></div></p>
*
* <p><b><u>Insertion methods</u></b></p>
* <p>Commonly used insertion methods:
* <div class="mdetail-params"><ul>
* <li><b><tt>{@link #append}</tt></b> : <div class="sub-desc"></div></li>
* <li><b><tt>{@link #insertBefore}</tt></b> : <div class="sub-desc"></div></li>
* <li><b><tt>{@link #insertAfter}</tt></b> : <div class="sub-desc"></div></li>
* <li><b><tt>{@link #overwrite}</tt></b> : <div class="sub-desc"></div></li>
* <li><b><tt>{@link #createTemplate}</tt></b> : <div class="sub-desc"></div></li>
* <li><b><tt>{@link #insertHtml}</tt></b> : <div class="sub-desc"></div></li>
* </ul></div></p>
*
* <p><b><u>Example</u></b></p>
* <p>This is an example, where an unordered list with 3 children items is appended to an existing
* element with id <tt>'my-div'</tt>:<br>
<pre><code>
var dh = Ext.DomHelper; // create shorthand alias
// specification object
var spec = {
id: 'my-ul',
tag: 'ul',
cls: 'my-list',
// append children after creating
children: [     // may also specify 'cn' instead of 'children'
{tag: 'li', id: 'item0', html: 'List Item 0'},
{tag: 'li', id: 'item1', html: 'List Item 1'},
{tag: 'li', id: 'item2', html: 'List Item 2'}
]
};
var list = dh.append(
'my-div', // the context element 'my-div' can either be the id or the actual node
spec      // the specification object
);
</code></pre></p>
* <p>Element creation specification parameters in this class may also be passed as an Array of
* specification objects. This can be used to insert multiple sibling nodes into an existing
* container very efficiently. For example, to add more list items to the example above:<pre><code>
dh.append('my-ul', [
{tag: 'li', id: 'item3', html: 'List Item 3'},
{tag: 'li', id: 'item4', html: 'List Item 4'}
]);
* </code></pre></p>
*
* <p><b><u>Templating</u></b></p>
* <p>The real power is in the built-in templating. Instead of creating or appending any elements,
* <tt>{@link #createTemplate}</tt> returns a Template object which can be used over and over to
* insert new elements. Revisiting the example above, we could utilize templating this time:
* <pre><code>
// create the node
var list = dh.append('my-div', {tag: 'ul', cls: 'my-list'});
// get template
var tpl = dh.createTemplate({tag: 'li', id: 'item{0}', html: 'List Item {0}'});

for(var i = 0; i < 5, i++){
tpl.append(list, [i]); // use template to append to the actual node
}
* </code></pre></p>
* <p>An example using a template:<pre><code>
var html = '<a id="{0}" href="{1}" class="nav">{2}</a>';

var tpl = new Ext.DomHelper.createTemplate(html);
tpl.append('blog-roll', ['link1', 'http://www.jackslocum.com/', "Jack&#39;s Site"]);
tpl.append('blog-roll', ['link2', 'http://www.dustindiaz.com/', "Dustin&#39;s Site"]);
* </code></pre></p>
*
* <p>The same example using named parameters:<pre><code>
var html = '<a id="{id}" href="{url}" class="nav">{text}</a>';

var tpl = new Ext.DomHelper.createTemplate(html);
tpl.append('blog-roll', {
id: 'link1',
url: 'http://www.jackslocum.com/',
text: "Jack&#39;s Site"
});
tpl.append('blog-roll', {
id: 'link2',
url: 'http://www.dustindiaz.com/',
text: "Dustin&#39;s Site"
});
* </code></pre></p>
*
* <p><b><u>Compiling Templates</u></b></p>
* <p>Templates are applied using regular expressions. The performance is great, but if
* you are adding a bunch of DOM elements using the same template, you can increase
* performance even further by {@link Ext.Template#compile "compiling"} the template.
* The way "{@link Ext.Template#compile compile()}" works is the template is parsed and
* broken up at the different variable points and a dynamic function is created and eval'ed.
* The generated function performs string concatenation of these parts and the passed
* variables instead of using regular expressions.
* <pre><code>
var html = '<a id="{id}" href="{url}" class="nav">{text}</a>';

var tpl = new Ext.DomHelper.createTemplate(html);
tpl.compile();

//... use template like normal
* </code></pre></p>
*
* <p><b><u>Performance Boost</u></b></p>
* <p>DomHelper will transparently create HTML fragments when it can. Using HTML fragments instead
* of DOM can significantly boost performance.</p>
* <p>Element creation specification parameters may also be strings. If {@link #useDom} is <tt>false</tt>,
* then the string is used as innerHTML. If {@link #useDom} is <tt>true</tt>, a string specification
* results in the creation of a text node. Usage:</p>
* <pre><code>
Ext.DomHelper.useDom = true; // force it to use DOM; reduces performance
* </code></pre>
* @singleton
*/
Ext.DomHelper = function () {
	var tempTableEl = null,
        emptyTags = /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i,
        tableRe = /^table|tbody|tr|td$/i,
        confRe = /tag|children|cn|html$/i,
        tableElRe = /td|tr|tbody/i,
        cssRe = /([a-z0-9-]+)\s*:\s*([^;\s]+(?:\s*[^;\s]+)*);?/gi,
        endRe = /end/i,
        pub,
	// kill repeat to save bytes
        afterbegin = 'afterbegin',
        afterend = 'afterend',
        beforebegin = 'beforebegin',
        beforeend = 'beforeend',
        ts = '<table>',
        te = '</table>',
        tbs = ts + '<tbody>',
        tbe = '</tbody>' + te,
        trs = tbs + '<tr>',
        tre = '</tr>' + tbe;

	// private
	function doInsert(el, o, returnElement, pos, sibling, append) {
		var newNode = pub.insertHtml(pos, Ext.getDom(el), createHtml(o));
		return returnElement ? Ext.get(newNode, true) : newNode;
	}

	// build as innerHTML where available
	function createHtml(o) {
		var b = '',
            attr,
            val,
            key,
            keyVal,
            cn;

		if (typeof o == "string") {
			b = o;
		} else if (Ext.isArray(o)) {
			for (var i = 0; i < o.length; i++) {
				if (o[i]) {
					b += createHtml(o[i]);
				}
			};
		} else {
			b += '<' + (o.tag = o.tag || 'div');
			for (attr in o) {
				val = o[attr];
				if (!confRe.test(attr)) {
					if (typeof val == "object") {
						b += ' ' + attr + '="';
						for (key in val) {
							b += key + ':' + val[key] + ';';
						};
						b += '"';
					} else {
						b += ' ' + ({ cls: 'class', htmlFor: 'for'}[attr] || attr) + '="' + val + '"';
					}
				}
			};
			// Now either just close the tag or try to add children and close the tag.
			if (emptyTags.test(o.tag)) {
				b += '/>';
			} else {
				b += '>';
				if ((cn = o.children || o.cn)) {
					b += createHtml(cn);
				} else if (o.html) {
					b += o.html;
				}
				b += '</' + o.tag + '>';
			}
		}
		return b;
	}

	function ieTable(depth, s, h, e) {
		tempTableEl.innerHTML = [s, h, e].join('');
		var i = -1,
            el = tempTableEl,
            ns;
		while (++i < depth) {
			el = el.firstChild;
		}
		//      If the result is multiple siblings, then encapsulate them into one fragment.
		if (ns = el.nextSibling) {
			var df = document.createDocumentFragment();
			while (el) {
				ns = el.nextSibling;
				df.appendChild(el);
				el = ns;
			}
			el = df;
		}
		return el;
	}

	/**
	* @ignore
	* Nasty code for IE's broken table implementation
	*/
	function insertIntoTable(tag, where, el, html) {
		var node,
            before;

		tempTableEl = tempTableEl || document.createElement('div');

		if (tag == 'td' && (where == afterbegin || where == beforeend) ||
           !tableElRe.test(tag) && (where == beforebegin || where == afterend)) {
			return;
		}
		before = where == beforebegin ? el :
                 where == afterend ? el.nextSibling :
                 where == afterbegin ? el.firstChild : null;

		if (where == beforebegin || where == afterend) {
			el = el.parentNode;
		}

		if (tag == 'td' || (tag == 'tr' && (where == beforeend || where == afterbegin))) {
			node = ieTable(4, trs, html, tre);
		} else if ((tag == 'tbody' && (where == beforeend || where == afterbegin)) ||
                   (tag == 'tr' && (where == beforebegin || where == afterend))) {
			node = ieTable(3, tbs, html, tbe);
		} else {
			node = ieTable(2, ts, html, te);
		}
		el.insertBefore(node, before);
		return node;
	}


	pub = {
		/**
		* Returns the markup for the passed Element(s) config.
		* @param {Object} o The DOM object spec (and children)
		* @return {String}
		*/
		markup: function (o) {
			return createHtml(o);
		},

		/**
		* Applies a style specification to an element.
		* @param {String/HTMLElement} el The element to apply styles to
		* @param {String/Object/Function} styles A style specification string e.g. 'width:100px', or object in the form {width:'100px'}, or
		* a function which returns such a specification.
		*/
		applyStyles: function (el, styles) {
			if (styles) {
				var i = 0,
                    len,
                    style,
                    matches;

				el = Ext.fly(el);
				if (typeof styles == "function") {
					styles = styles.call();
				}
				if (typeof styles == "string") {
					while ((matches = cssRe.exec(styles))) {
						el.setStyle(matches[1], matches[2]);
					}
				} else if (typeof styles == "object") {
					el.setStyle(styles);
				}
			}
		},

		/**
		* Inserts an HTML fragment into the DOM.
		* @param {String} where Where to insert the html in relation to el - beforeBegin, afterBegin, beforeEnd, afterEnd.
		* @param {HTMLElement} el The context element
		* @param {String} html The HTML fragment
		* @return {HTMLElement} The new node
		*/
		insertHtml: function (where, el, html) {
			var hash = {},
                hashVal,
                setStart,
                range,
                frag,
                rangeEl,
                rs;

			where = where.toLowerCase();
			// add these here because they are used in both branches of the condition.
			hash[beforebegin] = ['BeforeBegin', 'previousSibling'];
			hash[afterend] = ['AfterEnd', 'nextSibling'];

			if (el.insertAdjacentHTML) {
				if (tableRe.test(el.tagName) && (rs = insertIntoTable(el.tagName.toLowerCase(), where, el, html))) {
					return rs;
				}
				// add these two to the hash.
				hash[afterbegin] = ['AfterBegin', 'firstChild'];
				hash[beforeend] = ['BeforeEnd', 'lastChild'];
				if ((hashVal = hash[where])) {
					el.insertAdjacentHTML(hashVal[0], html);
					return el[hashVal[1]];
				}
			} else {
				range = el.ownerDocument.createRange();
				setStart = 'setStart' + (endRe.test(where) ? 'After' : 'Before');
				if (hash[where]) {
					range[setStart](el);
					frag = range.createContextualFragment(html);
					el.parentNode.insertBefore(frag, where == beforebegin ? el : el.nextSibling);
					return el[(where == beforebegin ? 'previous' : 'next') + 'Sibling'];
				} else {
					rangeEl = (where == afterbegin ? 'first' : 'last') + 'Child';
					if (el.firstChild) {
						range[setStart](el[rangeEl]);
						frag = range.createContextualFragment(html);
						if (where == afterbegin) {
							el.insertBefore(frag, el.firstChild);
						} else {
							el.appendChild(frag);
						}
					} else {
						el.innerHTML = html;
					}
					return el[rangeEl];
				}
			}
			throw 'Illegal insertion point -> "' + where + '"';
		},

		/**
		* Creates new DOM element(s) and inserts them before el.
		* @param {Mixed} el The context element
		* @param {Object/String} o The DOM object spec (and children) or raw HTML blob
		* @param {Boolean} returnElement (optional) true to return a Ext.Element
		* @return {HTMLElement/Ext.Element} The new node
		*/
		insertBefore: function (el, o, returnElement) {
			return doInsert(el, o, returnElement, beforebegin);
		},

		/**
		* Creates new DOM element(s) and inserts them after el.
		* @param {Mixed} el The context element
		* @param {Object} o The DOM object spec (and children)
		* @param {Boolean} returnElement (optional) true to return a Ext.Element
		* @return {HTMLElement/Ext.Element} The new node
		*/
		insertAfter: function (el, o, returnElement) {
			return doInsert(el, o, returnElement, afterend, 'nextSibling');
		},

		/**
		* Creates new DOM element(s) and inserts them as the first child of el.
		* @param {Mixed} el The context element
		* @param {Object/String} o The DOM object spec (and children) or raw HTML blob
		* @param {Boolean} returnElement (optional) true to return a Ext.Element
		* @return {HTMLElement/Ext.Element} The new node
		*/
		insertFirst: function (el, o, returnElement) {
			return doInsert(el, o, returnElement, afterbegin, 'firstChild');
		},

		/**
		* Creates new DOM element(s) and appends them to el.
		* @param {Mixed} el The context element
		* @param {Object/String} o The DOM object spec (and children) or raw HTML blob
		* @param {Boolean} returnElement (optional) true to return a Ext.Element
		* @return {HTMLElement/Ext.Element} The new node
		*/
		append: function (el, o, returnElement) {
			return doInsert(el, o, returnElement, beforeend, '', true);
		},

		/**
		* Creates new DOM element(s) and overwrites the contents of el with them.
		* @param {Mixed} el The context element
		* @param {Object/String} o The DOM object spec (and children) or raw HTML blob
		* @param {Boolean} returnElement (optional) true to return a Ext.Element
		* @return {HTMLElement/Ext.Element} The new node
		*/
		overwrite: function (el, o, returnElement) {
			el = Ext.getDom(el);
			el.innerHTML = createHtml(o);
			return returnElement ? Ext.get(el.firstChild) : el.firstChild;
		},

		createHtml: createHtml
	};
	return pub;
} ();
/**
* @class Ext.DomHelper
*/
Ext.apply(Ext.DomHelper,
function () {
	var pub,
        afterbegin = 'afterbegin',
        afterend = 'afterend',
        beforebegin = 'beforebegin',
        beforeend = 'beforeend',
        confRe = /tag|children|cn|html$/i;

	// private
	function doInsert(el, o, returnElement, pos, sibling, append) {
		el = Ext.getDom(el);
		var newNode;
		if (pub.useDom) {
			newNode = createDom(o, null);
			if (append) {
				el.appendChild(newNode);
			} else {
				(sibling == 'firstChild' ? el : el.parentNode).insertBefore(newNode, el[sibling] || el);
			}
		} else {
			newNode = Ext.DomHelper.insertHtml(pos, el, Ext.DomHelper.createHtml(o));
		}
		return returnElement ? Ext.get(newNode, true) : newNode;
	}

	// build as dom
	/** @ignore */
	function createDom(o, parentNode) {
		var el,
            doc = document,
            useSet,
            attr,
            val,
            cn;

		if (Ext.isArray(o)) {                       // Allow Arrays of siblings to be inserted
			el = doc.createDocumentFragment(); // in one shot using a DocumentFragment
			for (var i = 0, l = o.length; i < l; i++) {
				createDom(o[i], el);
			}
		} else if (typeof o == 'string') {         // Allow a string as a child spec.
			el = doc.createTextNode(o);
		} else {
			el = doc.createElement(o.tag || 'div');
			useSet = !!el.setAttribute; // In IE some elements don't have setAttribute
			for (var attr in o) {
				if (!confRe.test(attr)) {
					val = o[attr];
					if (attr == 'cls') {
						el.className = val;
					} else {
						if (useSet) {
							el.setAttribute(attr, val);
						} else {
							el[attr] = val;
						}
					}
				}
			}
			Ext.DomHelper.applyStyles(el, o.style);

			if ((cn = o.children || o.cn)) {
				createDom(cn, el);
			} else if (o.html) {
				el.innerHTML = o.html;
			}
		}
		if (parentNode) {
			parentNode.appendChild(el);
		}
		return el;
	}

	pub = {
		/**
		* Creates a new Ext.Template from the DOM object spec.
		* @param {Object} o The DOM object spec (and children)
		* @return {Ext.Template} The new template
		*/
		createTemplate: function (o) {
			var html = Ext.DomHelper.createHtml(o);
			return new Ext.Template(html);
		},

		/** True to force the use of DOM instead of html fragments @type Boolean */
		useDom: false,

		/**
		* Creates new DOM element(s) and inserts them before el.
		* @param {Mixed} el The context element
		* @param {Object/String} o The DOM object spec (and children) or raw HTML blob
		* @param {Boolean} returnElement (optional) true to return a Ext.Element
		* @return {HTMLElement/Ext.Element} The new node
		* @hide (repeat)
		*/
		insertBefore: function (el, o, returnElement) {
			return doInsert(el, o, returnElement, beforebegin);
		},

		/**
		* Creates new DOM element(s) and inserts them after el.
		* @param {Mixed} el The context element
		* @param {Object} o The DOM object spec (and children)
		* @param {Boolean} returnElement (optional) true to return a Ext.Element
		* @return {HTMLElement/Ext.Element} The new node
		* @hide (repeat)
		*/
		insertAfter: function (el, o, returnElement) {
			return doInsert(el, o, returnElement, afterend, 'nextSibling');
		},

		/**
		* Creates new DOM element(s) and inserts them as the first child of el.
		* @param {Mixed} el The context element
		* @param {Object/String} o The DOM object spec (and children) or raw HTML blob
		* @param {Boolean} returnElement (optional) true to return a Ext.Element
		* @return {HTMLElement/Ext.Element} The new node
		* @hide (repeat)
		*/
		insertFirst: function (el, o, returnElement) {
			return doInsert(el, o, returnElement, afterbegin, 'firstChild');
		},

		/**
		* Creates new DOM element(s) and appends them to el.
		* @param {Mixed} el The context element
		* @param {Object/String} o The DOM object spec (and children) or raw HTML blob
		* @param {Boolean} returnElement (optional) true to return a Ext.Element
		* @return {HTMLElement/Ext.Element} The new node
		* @hide (repeat)
		*/
		append: function (el, o, returnElement) {
			return doInsert(el, o, returnElement, beforeend, '', true);
		},

		/**
		* Creates new DOM element(s) without inserting them to the document.
		* @param {Object/String} o The DOM object spec (and children) or raw HTML blob
		* @return {HTMLElement} The new uninserted node
		*/
		createDom: createDom
	};
	return pub;
} ());
/**
* @class Ext.Template
* <p>Represents an HTML fragment template. Templates may be {@link #compile precompiled}
* for greater performance.</p>
* <p>For example usage {@link #Template see the constructor}.</p>
*
* @constructor
* An instance of this class may be created by passing to the constructor either
* a single argument, or multiple arguments:
* <div class="mdetail-params"><ul>
* <li><b>single argument</b> : String/Array
* <div class="sub-desc">
* The single argument may be either a String or an Array:<ul>
* <li><tt>String</tt> : </li><pre><code>
var t = new Ext.Template("&lt;div>Hello {0}.&lt;/div>");
t.{@link #append}('some-element', ['foo']);
* </code></pre>
* <li><tt>Array</tt> : </li>
* An Array will be combined with <code>join('')</code>.
<pre><code>
var t = new Ext.Template([
'&lt;div name="{id}"&gt;',
'&lt;span class="{cls}"&gt;{name:trim} {value:ellipsis(10)}&lt;/span&gt;',
'&lt;/div&gt;',
]);
t.{@link #compile}();
t.{@link #append}('some-element', {id: 'myid', cls: 'myclass', name: 'foo', value: 'bar'});
</code></pre>
* </ul></div></li>
* <li><b>multiple arguments</b> : String, Object, Array, ...
* <div class="sub-desc">
* Multiple arguments will be combined with <code>join('')</code>.
* <pre><code>
var t = new Ext.Template(
'&lt;div name="{id}"&gt;',
'&lt;span class="{cls}"&gt;{name} {value}&lt;/span&gt;',
'&lt;/div&gt;',
// a configuration object:
{
compiled: true,      // {@link #compile} immediately
disableFormats: true // See Notes below.
}
);
* </code></pre>
* <p><b>Notes</b>:</p>
* <div class="mdetail-params"><ul>
* <li>Formatting and <code>disableFormats</code> are not applicable for Ext Core.</li>
* <li>For a list of available format functions, see {@link Ext.util.Format}.</li>
* <li><code>disableFormats</code> reduces <code>{@link #apply}</code> time
* when no formatting is required.</li>
* </ul></div>
* </div></li>
* </ul></div>
* @param {Mixed} config
*/
Ext.Template = function (html) {
	var me = this,
        a = arguments,
        buf = [],
        v;

	if (Ext.isArray(html)) {
		html = html.join("");
	} else if (a.length > 1) {
		for (var i = 0, len = a.length; i < len; i++) {
			v = a[i];
			if (typeof v == 'object') {
				Ext.apply(me, v);
			} else {
				buf.push(v);
			}
		};
		html = buf.join('');
	}

	/**@private*/
	me.html = html;
	/**
	* @cfg {Boolean} compiled Specify <tt>true</tt> to compile the template
	* immediately (see <code>{@link #compile}</code>).
	* Defaults to <tt>false</tt>.
	*/
	if (me.compiled) {
		me.compile();
	}
};
Ext.Template.prototype = {
	/**
	* @cfg {RegExp} re The regular expression used to match template variables.
	* Defaults to:<pre><code>
	* re : /\{([\w-]+)\}/g                                     // for Ext Core
	* re : /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g      // for Ext JS
	* </code></pre>
	*/
	re: /\{([\w-]+)\}/g,
	/**
	* See <code>{@link #re}</code>.
	* @type RegExp
	* @property re
	*/

	/**
	* Returns an HTML fragment of this template with the specified <code>values</code> applied.
	* @param {Object/Array} values
	* The template values. Can be an array if the params are numeric (i.e. <code>{0}</code>)
	* or an object (i.e. <code>{foo: 'bar'}</code>).
	* @return {String} The HTML fragment
	*/
	applyTemplate: function (values) {
		var me = this;

		return me.compiled ?
                me.compiled(values) :
                me.html.replace(me.re, function (m, name) {
                	return values[name] !== undefined ? values[name] : "";
                });
	},

	/**
	* Sets the HTML used as the template and optionally compiles it.
	* @param {String} html
	* @param {Boolean} compile (optional) True to compile the template (defaults to undefined)
	* @return {Ext.Template} this
	*/
	set: function (html, compile) {
		var me = this;
		me.html = html;
		me.compiled = null;
		return compile ? me.compile() : me;
	},

	/**
	* Compiles the template into an internal function, eliminating the RegEx overhead.
	* @return {Ext.Template} this
	*/
	compile: function () {
		var me = this,
            sep = Ext.isGecko ? "+" : ",";

		function fn(m, name) {
			name = "values['" + name + "']";
			return "'" + sep + '(' + name + " == undefined ? '' : " + name + ')' + sep + "'";
		}

		eval("this.compiled = function(values){ return " + (Ext.isGecko ? "'" : "['") +
             me.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
             (Ext.isGecko ? "';};" : "'].join('');};"));
		return me;
	},

	/**
	* Applies the supplied values to the template and inserts the new node(s) as the first child of el.
	* @param {Mixed} el The context element
	* @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'})
	* @param {Boolean} returnElement (optional) true to return a Ext.Element (defaults to undefined)
	* @return {HTMLElement/Ext.Element} The new node or Element
	*/
	insertFirst: function (el, values, returnElement) {
		return this.doInsert('afterBegin', el, values, returnElement);
	},

	/**
	* Applies the supplied values to the template and inserts the new node(s) before el.
	* @param {Mixed} el The context element
	* @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'})
	* @param {Boolean} returnElement (optional) true to return a Ext.Element (defaults to undefined)
	* @return {HTMLElement/Ext.Element} The new node or Element
	*/
	insertBefore: function (el, values, returnElement) {
		return this.doInsert('beforeBegin', el, values, returnElement);
	},

	/**
	* Applies the supplied values to the template and inserts the new node(s) after el.
	* @param {Mixed} el The context element
	* @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'})
	* @param {Boolean} returnElement (optional) true to return a Ext.Element (defaults to undefined)
	* @return {HTMLElement/Ext.Element} The new node or Element
	*/
	insertAfter: function (el, values, returnElement) {
		return this.doInsert('afterEnd', el, values, returnElement);
	},

	/**
	* Applies the supplied <code>values</code> to the template and appends
	* the new node(s) to the specified <code>el</code>.
	* <p>For example usage {@link #Template see the constructor}.</p>
	* @param {Mixed} el The context element
	* @param {Object/Array} values
	* The template values. Can be an array if the params are numeric (i.e. <code>{0}</code>)
	* or an object (i.e. <code>{foo: 'bar'}</code>).
	* @param {Boolean} returnElement (optional) true to return an Ext.Element (defaults to undefined)
	* @return {HTMLElement/Ext.Element} The new node or Element
	*/
	append: function (el, values, returnElement) {
		return this.doInsert('beforeEnd', el, values, returnElement);
	},

	doInsert: function (where, el, values, returnEl) {
		el = Ext.getDom(el);
		var newNode = Ext.DomHelper.insertHtml(where, el, this.applyTemplate(values));
		return returnEl ? Ext.get(newNode, true) : newNode;
	},

	/**
	* Applies the supplied values to the template and overwrites the content of el with the new node(s).
	* @param {Mixed} el The context element
	* @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'})
	* @param {Boolean} returnElement (optional) true to return a Ext.Element (defaults to undefined)
	* @return {HTMLElement/Ext.Element} The new node or Element
	*/
	overwrite: function (el, values, returnElement) {
		el = Ext.getDom(el);
		el.innerHTML = this.applyTemplate(values);
		return returnElement ? Ext.get(el.firstChild, true) : el.firstChild;
	}
};
/**
* Alias for {@link #applyTemplate}
* Returns an HTML fragment of this template with the specified <code>values</code> applied.
* @param {Object/Array} values
* The template values. Can be an array if the params are numeric (i.e. <code>{0}</code>)
* or an object (i.e. <code>{foo: 'bar'}</code>).
* @return {String} The HTML fragment
* @member Ext.Template
* @method apply
*/
Ext.Template.prototype.apply = Ext.Template.prototype.applyTemplate;

/**
* Creates a template from the passed element's value (<i>display:none</i> textarea, preferred) or innerHTML.
* @param {String/HTMLElement} el A DOM element or its id
* @param {Object} config A configuration object
* @return {Ext.Template} The created template
* @static
*/
Ext.Template.from = function (el, config) {
	el = Ext.getDom(el);
	return new Ext.Template(el.value || el.innerHTML, config || '');
};
/**
* @class Ext.Template
*/
Ext.apply(Ext.Template.prototype, {
	/**
	* @cfg {Boolean} disableFormats Specify <tt>true</tt> to disable format
	* functions in the template. If the template does not contain
	* {@link Ext.util.Format format functions}, setting <code>disableFormats</code>
	* to true will reduce <code>{@link #apply}</code> time. Defaults to <tt>false</tt>.
	* <pre><code>
	var t = new Ext.Template(
	'&lt;div name="{id}"&gt;',
	'&lt;span class="{cls}"&gt;{name} {value}&lt;/span&gt;',
	'&lt;/div&gt;',
	{
	compiled: true,      // {@link #compile} immediately
	disableFormats: true // reduce <code>{@link #apply}</code> time since no formatting
	}
	);
	* </code></pre>
	* For a list of available format functions, see {@link Ext.util.Format}.
	*/
	disableFormats: false,
	/**
	* See <code>{@link #disableFormats}</code>.
	* @type Boolean
	* @property disableFormats
	*/

	/**
	* The regular expression used to match template variables
	* @type RegExp
	* @property
	* @hide repeat doc
	*/
	re: /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
	argsRe: /^\s*['"](.*)["']\s*$/,
	compileARe: /\\/g,
	compileBRe: /(\r\n|\n)/g,
	compileCRe: /'/g,

	/**
	* Returns an HTML fragment of this template with the specified values applied.
	* @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'})
	* @return {String} The HTML fragment
	* @hide repeat doc
	*/
	applyTemplate: function (values) {
		var me = this,
            useF = me.disableFormats !== true,
            fm = Ext.util.Format,
            tpl = me;

		if (me.compiled) {
			return me.compiled(values);
		}
		function fn(m, name, format, args) {
			if (format && useF) {
				if (format.substr(0, 5) == "this.") {
					return tpl.call(format.substr(5), values[name], values);
				} else {
					if (args) {
						// quoted values are required for strings in compiled templates,
						// but for non compiled we need to strip them
						// quoted reversed for jsmin
						var re = me.argsRe;
						args = args.split(',');
						for (var i = 0, len = args.length; i < len; i++) {
							args[i] = args[i].replace(re, "$1");
						}
						args = [values[name]].concat(args);
					} else {
						args = [values[name]];
					}
					return fm[format].apply(fm, args);
				}
			} else {
				return values[name] !== undefined ? values[name] : "";
			}
		}
		return me.html.replace(me.re, fn);
	},

	/**
	* Compiles the template into an internal function, eliminating the RegEx overhead.
	* @return {Ext.Template} this
	* @hide repeat doc
	*/
	compile: function () {
		var me = this,
            fm = Ext.util.Format,
            useF = me.disableFormats !== true,
            sep = Ext.isGecko ? "+" : ",",
            body;

		function fn(m, name, format, args) {
			if (format && useF) {
				args = args ? ',' + args : "";
				if (format.substr(0, 5) != "this.") {
					format = "fm." + format + '(';
				} else {
					format = 'this.call("' + format.substr(5) + '", ';
					args = ", values";
				}
			} else {
				args = ''; format = "(values['" + name + "'] == undefined ? '' : ";
			}
			return "'" + sep + format + "values['" + name + "']" + args + ")" + sep + "'";
		}

		// branched to use + in gecko and [].join() in others
		if (Ext.isGecko) {
			body = "this.compiled = function(values){ return '" +
                   me.html.replace(me.compileARe, '\\\\').replace(me.compileBRe, '\\n').replace(me.compileCRe, "\\'").replace(me.re, fn) +
                    "';};";
		} else {
			body = ["this.compiled = function(values){ return ['"];
			body.push(me.html.replace(me.compileARe, '\\\\').replace(me.compileBRe, '\\n').replace(me.compileCRe, "\\'").replace(me.re, fn));
			body.push("'].join('');};");
			body = body.join('');
		}
		eval(body);
		return me;
	},

	// private function used to call members
	call: function (fnName, value, allValues) {
		return this[fnName](value, allValues);
	}
});
Ext.Template.prototype.apply = Ext.Template.prototype.applyTemplate;
/*
* This is code is also distributed under MIT license for use
* with jQuery and prototype JavaScript libraries.
*/
/**
* @class Ext.DomQuery
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).
<p>
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>

<p>
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.
</p>
<h4>Element Selectors:</h4>
<ul class="list">
<li> <b>*</b> any element</li>
<li> <b>E</b> an element with the tag E</li>
<li> <b>E F</b> All descendent elements of E that have the tag F</li>
<li> <b>E > F</b> or <b>E/F</b> all direct children elements of E that have the tag F</li>
<li> <b>E + F</b> all elements with the tag F that are immediately preceded by an element with the tag E</li>
<li> <b>E ~ F</b> all elements with the tag F that are preceded by a sibling element with the tag E</li>
</ul>
<h4>Attribute Selectors:</h4>
<p>The use of &#64; and quotes are optional. For example, div[&#64;foo='bar'] is also a valid attribute selector.</p>
<ul class="list">
<li> <b>E[foo]</b> has an attribute "foo"</li>
<li> <b>E[foo=bar]</b> has an attribute "foo" that equals "bar"</li>
<li> <b>E[foo^=bar]</b> has an attribute "foo" that starts with "bar"</li>
<li> <b>E[foo$=bar]</b> has an attribute "foo" that ends with "bar"</li>
<li> <b>E[foo*=bar]</b> has an attribute "foo" that contains the substring "bar"</li>
<li> <b>E[foo%=2]</b> has an attribute "foo" that is evenly divisible by 2</li>
<li> <b>E[foo!=bar]</b> has an attribute "foo" that does not equal "bar"</li>
</ul>
<h4>Pseudo Classes:</h4>
<ul class="list">
<li> <b>E:first-child</b> E is the first child of its parent</li>
<li> <b>E:last-child</b> E is the last child of its parent</li>
<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>
<li> <b>E:nth-child(odd)</b> E is an odd child of its parent</li>
<li> <b>E:nth-child(even)</b> E is an even child of its parent</li>
<li> <b>E:only-child</b> E is the only child of its parent</li>
<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>
<li> <b>E:first</b> the first E in the resultset</li>
<li> <b>E:last</b> the last E in the resultset</li>
<li> <b>E:nth(<i>n</i>)</b> the <i>n</i>th E in the resultset (1 based)</li>
<li> <b>E:odd</b> shortcut for :nth-child(odd)</li>
<li> <b>E:even</b> shortcut for :nth-child(even)</li>
<li> <b>E:contains(foo)</b> E's innerHTML contains the substring "foo"</li>
<li> <b>E:nodeValue(foo)</b> E contains a textNode with a nodeValue that equals "foo"</li>
<li> <b>E:not(S)</b> an E element that does not match simple selector S</li>
<li> <b>E:has(S)</b> an E element that has a descendent that matches simple selector S</li>
<li> <b>E:next(S)</b> an E element whose next sibling matches simple selector S</li>
<li> <b>E:prev(S)</b> an E element whose previous sibling matches simple selector S</li>
<li> <b>E:any(S1|S2|S2)</b> an E element which matches any of the simple selectors S1, S2 or S3//\\</li>
</ul>
<h4>CSS Value Selectors:</h4>
<ul class="list">
<li> <b>E{display=none}</b> css value "display" that equals "none"</li>
<li> <b>E{display^=none}</b> css value "display" that starts with "none"</li>
<li> <b>E{display$=none}</b> css value "display" that ends with "none"</li>
<li> <b>E{display*=none}</b> css value "display" that contains the substring "none"</li>
<li> <b>E{display%=2}</b> css value "display" that is evenly divisible by 2</li>
<li> <b>E{display!=none}</b> css value "display" that does not equal "none"</li>
</ul>
* @singleton
*/
Ext.DomQuery = function () {
	var cache = {},
    	simpleCache = {},
    	valueCache = {},
    	nonSpace = /\S/,
    	trimRe = /^\s+|\s+$/g,
    	tplRe = /\{(\d+)\}/g,
    	modeRe = /^(\s?[\/>+~]\s?|\s|$)/,
    	tagTokenRe = /^(#)?([\w-\*]+)/,
    	nthRe = /(\d*)n\+?(\d*)/,
    	nthRe2 = /\D/,
	// This is for IE MSXML which does not support expandos.
	// IE runs the same speed using setAttribute, however FF slows way down
	// and Safari completely fails so they need to continue to use expandos.
	isIE = window.ActiveXObject ? true : false,
	key = 30803;

	// this eval is stop the compressor from
	// renaming the variable to something shorter
	eval("var batch = 30803;");

	// Retrieve the child node from a particular
	// parent at the specified index.
	function child(parent, index) {
		var i = 0,
            n = parent.firstChild;
		while (n) {
			if (n.nodeType == 1) {
				if (++i == index) {
					return n;
				}
			}
			n = n.nextSibling;
		}
		return null;
	}

	// retrieve the next element node
	function next(n) {
		while ((n = n.nextSibling) && n.nodeType != 1);
		return n;
	}

	// retrieve the previous element node 
	function prev(n) {
		while ((n = n.previousSibling) && n.nodeType != 1);
		return n;
	}

	// Mark each child node with a nodeIndex skipping and
	// removing empty text nodes.
	function children(parent) {
		var n = parent.firstChild,
	    nodeIndex = -1,
	    nextNode;
		while (n) {
			nextNode = n.nextSibling;
			// clean worthless empty nodes.
			if (n.nodeType == 3 && !nonSpace.test(n.nodeValue)) {
				parent.removeChild(n);
			} else {
				// add an expando nodeIndex
				n.nodeIndex = ++nodeIndex;
			}
			n = nextNode;
		}
		return this;
	}


	// nodeSet - array of nodes
	// cls - CSS Class
	function byClassName(nodeSet, cls) {
		if (!cls) {
			return nodeSet;
		}
		var result = [], ri = -1;
		for (var i = 0, ci; ci = nodeSet[i]; i++) {
			if ((' ' + ci.className + ' ').indexOf(cls) != -1) {
				result[++ri] = ci;
			}
		}
		return result;
	};

	function attrValue(n, attr) {
		// if its an array, use the first node.
		if (!n.tagName && typeof n.length != "undefined") {
			n = n[0];
		}
		if (!n) {
			return null;
		}

		if (attr == "for") {
			return n.htmlFor;
		}
		if (attr == "class" || attr == "className") {
			return n.className;
		}
		return n.getAttribute(attr) || n[attr];

	};


	// ns - nodes
	// mode - false, /, >, +, ~
	// tagName - defaults to "*"
	function getNodes(ns, mode, tagName) {
		var result = [], ri = -1, cs;
		if (!ns) {
			return result;
		}
		tagName = tagName || "*";
		// convert to array
		if (typeof ns.getElementsByTagName != "undefined") {
			ns = [ns];
		}

		// no mode specified, grab all elements by tagName
		// at any depth
		if (!mode) {
			for (var i = 0, ni; ni = ns[i]; i++) {
				cs = ni.getElementsByTagName(tagName);
				for (var j = 0, ci; ci = cs[j]; j++) {
					result[++ri] = ci;
				}
			}
			// Direct Child mode (/ or >)
			// E > F or E/F all direct children elements of E that have the tag 	
		} else if (mode == "/" || mode == ">") {
			var utag = tagName.toUpperCase();
			for (var i = 0, ni, cn; ni = ns[i]; i++) {
				cn = ni.childNodes;
				for (var j = 0, cj; cj = cn[j]; j++) {
					if (cj.nodeName == utag || cj.nodeName == tagName || tagName == '*') {
						result[++ri] = cj;
					}
				}
			}
			// Immediately Preceding mode (+)
			// E + F all elements with the tag F that are immediately preceded by an element with the tag E
		} else if (mode == "+") {
			var utag = tagName.toUpperCase();
			for (var i = 0, n; n = ns[i]; i++) {
				while ((n = n.nextSibling) && n.nodeType != 1);
				if (n && (n.nodeName == utag || n.nodeName == tagName || tagName == '*')) {
					result[++ri] = n;
				}
			}
			// Sibling mode (~)
			// E ~ F all elements with the tag F that are preceded by a sibling element with the tag E
		} else if (mode == "~") {
			var utag = tagName.toUpperCase();
			for (var i = 0, n; n = ns[i]; i++) {
				while ((n = n.nextSibling)) {
					if (n.nodeName == utag || n.nodeName == tagName || tagName == '*') {
						result[++ri] = n;
					}
				}
			}
		}
		return result;
	}

	function concat(a, b) {
		if (b.slice) {
			return a.concat(b);
		}
		for (var i = 0, l = b.length; i < l; i++) {
			a[a.length] = b[i];
		}
		return a;
	}

	function byTag(cs, tagName) {
		if (cs.tagName || cs == document) {
			cs = [cs];
		}
		if (!tagName) {
			return cs;
		}
		var result = [], ri = -1;
		tagName = tagName.toLowerCase();
		for (var i = 0, ci; ci = cs[i]; i++) {
			if (ci.nodeType == 1 && ci.tagName.toLowerCase() == tagName) {
				result[++ri] = ci;
			}
		}
		return result;
	}

	function byId(cs, id) {
		if (cs.tagName || cs == document) {
			cs = [cs];
		}
		if (!id) {
			return cs;
		}
		var result = [], ri = -1;
		for (var i = 0, ci; ci = cs[i]; i++) {
			if (ci && ci.id == id) {
				result[++ri] = ci;
				return result;
			}
		}
		return result;
	}

	// operators are =, !=, ^=, $=, *=, %=, |= and ~=
	// custom can be "{"
	function byAttribute(cs, attr, value, op, custom) {
		var result = [],
            ri = -1,
            useGetStyle = custom == "{",
            fn = Ext.DomQuery.operators[op],
            a,
            innerHTML;
		for (var i = 0, ci; ci = cs[i]; i++) {
			// skip non-element nodes.
			if (ci.nodeType != 1) {
				continue;
			}

			innerHTML = ci.innerHTML;
			// we only need to change the property names if we're dealing with html nodes, not XML
			if (innerHTML !== null && innerHTML !== undefined) {
				if (useGetStyle) {
					a = Ext.DomQuery.getStyle(ci, attr);
				} else if (attr == "class" || attr == "className") {
					a = ci.className;
				} else if (attr == "for") {
					a = ci.htmlFor;
				} else if (attr == "href") {
					// getAttribute href bug
					// http://www.glennjones.net/Post/809/getAttributehrefbug.htm
					a = ci.getAttribute("href", 2);
				} else {
					a = ci.getAttribute(attr);
				}
			} else {
				a = ci.getAttribute(attr);
			}
			if ((fn && fn(a, value)) || (!fn && a)) {
				result[++ri] = ci;
			}
		}
		return result;
	}

	function byPseudo(cs, name, value) {
		return Ext.DomQuery.pseudos[name](cs, value);
	}

	function nodupIEXml(cs) {
		var d = ++key,
            r;
		cs[0].setAttribute("_nodup", d);
		r = [cs[0]];
		for (var i = 1, len = cs.length; i < len; i++) {
			var c = cs[i];
			if (!c.getAttribute("_nodup") != d) {
				c.setAttribute("_nodup", d);
				r[r.length] = c;
			}
		}
		for (var i = 0, len = cs.length; i < len; i++) {
			cs[i].removeAttribute("_nodup");
		}
		return r;
	}

	function nodup(cs) {
		if (!cs) {
			return [];
		}
		var len = cs.length, c, i, r = cs, cj, ri = -1;
		if (!len || typeof cs.nodeType != "undefined" || len == 1) {
			return cs;
		}
		if (isIE && typeof cs[0].selectSingleNode != "undefined") {
			return nodupIEXml(cs);
		}
		var d = ++key;
		cs[0]._nodup = d;
		for (i = 1; c = cs[i]; i++) {
			if (c._nodup != d) {
				c._nodup = d;
			} else {
				r = [];
				for (var j = 0; j < i; j++) {
					r[++ri] = cs[j];
				}
				for (j = i + 1; cj = cs[j]; j++) {
					if (cj._nodup != d) {
						cj._nodup = d;
						r[++ri] = cj;
					}
				}
				return r;
			}
		}
		return r;
	}

	function quickDiffIEXml(c1, c2) {
		var d = ++key,
            r = [];
		for (var i = 0, len = c1.length; i < len; i++) {
			c1[i].setAttribute("_qdiff", d);
		}
		for (var i = 0, len = c2.length; i < len; i++) {
			if (c2[i].getAttribute("_qdiff") != d) {
				r[r.length] = c2[i];
			}
		}
		for (var i = 0, len = c1.length; i < len; i++) {
			c1[i].removeAttribute("_qdiff");
		}
		return r;
	}

	function quickDiff(c1, c2) {
		var len1 = c1.length,
        	d = ++key,
        	r = [];
		if (!len1) {
			return c2;
		}
		if (isIE && typeof c1[0].selectSingleNode != "undefined") {
			return quickDiffIEXml(c1, c2);
		}
		for (var i = 0; i < len1; i++) {
			c1[i]._qdiff = d;
		}
		for (var i = 0, len = c2.length; i < len; i++) {
			if (c2[i]._qdiff != d) {
				r[r.length] = c2[i];
			}
		}
		return r;
	}

	function quickId(ns, mode, root, id) {
		if (ns == root) {
			var d = root.ownerDocument || root;
			return d.getElementById(id);
		}
		ns = getNodes(ns, mode, "*");
		return byId(ns, id);
	}

	return {
		getStyle: function (el, name) {
			return Ext.fly(el).getStyle(name);
		},
		/**
		* Compiles a selector/xpath query into a reusable function. The returned function
		* takes one parameter "root" (optional), which is the context node from where the query should start.
		* @param {String} selector The selector/xpath query
		* @param {String} type (optional) Either "select" (the default) or "simple" for a simple selector match
		* @return {Function}
		*/
		compile: function (path, type) {
			type = type || "select";

			// setup fn preamble
			var fn = ["var f = function(root){\n var mode; ++batch; var n = root || document;\n"],
		mode,
		lastPath,
            	matchers = Ext.DomQuery.matchers,
            	matchersLn = matchers.length,
            	modeMatch,
			// accept leading mode switch
            	lmode = path.match(modeRe);

			if (lmode && lmode[1]) {
				fn[fn.length] = 'mode="' + lmode[1].replace(trimRe, "") + '";';
				path = path.replace(lmode[1], "");
			}

			// strip leading slashes
			while (path.substr(0, 1) == "/") {
				path = path.substr(1);
			}

			while (path && lastPath != path) {
				lastPath = path;
				var tokenMatch = path.match(tagTokenRe);
				if (type == "select") {
					if (tokenMatch) {
						// ID Selector
						if (tokenMatch[1] == "#") {
							fn[fn.length] = 'n = quickId(n, mode, root, "' + tokenMatch[2] + '");';
						} else {
							fn[fn.length] = 'n = getNodes(n, mode, "' + tokenMatch[2] + '");';
						}
						path = path.replace(tokenMatch[0], "");
					} else if (path.substr(0, 1) != '@') {
						fn[fn.length] = 'n = getNodes(n, mode, "*");';
					}
					// type of "simple"
				} else {
					if (tokenMatch) {
						if (tokenMatch[1] == "#") {
							fn[fn.length] = 'n = byId(n, "' + tokenMatch[2] + '");';
						} else {
							fn[fn.length] = 'n = byTag(n, "' + tokenMatch[2] + '");';
						}
						path = path.replace(tokenMatch[0], "");
					}
				}
				while (!(modeMatch = path.match(modeRe))) {
					var matched = false;
					for (var j = 0; j < matchersLn; j++) {
						var t = matchers[j];
						var m = path.match(t.re);
						if (m) {
							fn[fn.length] = t.select.replace(tplRe, function (x, i) {
								return m[i];
							});
							path = path.replace(m[0], "");
							matched = true;
							break;
						}
					}
					// prevent infinite loop on bad selector
					if (!matched) {
						throw 'Error parsing selector, parsing failed at "' + path + '"';
					}
				}
				if (modeMatch[1]) {
					fn[fn.length] = 'mode="' + modeMatch[1].replace(trimRe, "") + '";';
					path = path.replace(modeMatch[1], "");
				}
			}
			// close fn out
			fn[fn.length] = "return nodup(n);\n}";

			// eval fn and return it
			eval(fn.join(""));
			return f;
		},

		/**
		* Selects a group of elements.
		* @param {String} selector The selector/xpath query (can be a comma separated list of selectors)
		* @param {Node/String} root (optional) The start of the query (defaults to document).
		* @return {Array} An Array of DOM elements which match the selector. If there are
		* no matches, and empty Array is returned.
		*/
		jsSelect: function (path, root, type) {
			// set root to doc if not specified.
			root = root || document;

			if (typeof root == "string") {
				root = document.getElementById(root);
			}
			var paths = path.split(","),
            	results = [];

			// loop over each selector
			for (var i = 0, len = paths.length; i < len; i++) {
				var subPath = paths[i].replace(trimRe, "");
				// compile and place in cache
				if (!cache[subPath]) {
					cache[subPath] = Ext.DomQuery.compile(subPath);
					if (!cache[subPath]) {
						throw subPath + " is not a valid selector";
					}
				}
				var result = cache[subPath](root);
				if (result && result != document) {
					results = results.concat(result);
				}
			}

			// if there were multiple selectors, make sure dups
			// are eliminated
			if (paths.length > 1) {
				return nodup(results);
			}
			return results;
		},
		isXml: function (el) {
			var docEl = (el ? el.ownerDocument || el : 0).documentElement;
			return docEl ? docEl.nodeName !== "HTML" : false;
		},
		select: document.querySelectorAll ? function (path, root, type) {
			root = root || document;
			if (!Ext.DomQuery.isXml(root)) {
				try {
					var cs = root.querySelectorAll(path);
					return Ext.toArray(cs);
				}
				catch (ex) { }
			}
			return Ext.DomQuery.jsSelect.call(this, path, root, type);
		} : function (path, root, type) {
			return Ext.DomQuery.jsSelect.call(this, path, root, type);
		},

		/**
		* Selects a single element.
		* @param {String} selector The selector/xpath query
		* @param {Node} root (optional) The start of the query (defaults to document).
		* @return {Element} The DOM element which matched the selector.
		*/
		selectNode: function (path, root) {
			return Ext.DomQuery.select(path, root)[0];
		},

		/**
		* Selects the value of a node, optionally replacing null with the defaultValue.
		* @param {String} selector The selector/xpath query
		* @param {Node} root (optional) The start of the query (defaults to document).
		* @param {String} defaultValue
		* @return {String}
		*/
		selectValue: function (path, root, defaultValue) {
			path = path.replace(trimRe, "");
			if (!valueCache[path]) {
				valueCache[path] = Ext.DomQuery.compile(path, "select");
			}
			var n = valueCache[path](root), v;
			n = n[0] ? n[0] : n;

			// overcome a limitation of maximum textnode size
			// Rumored to potentially crash IE6 but has not been confirmed.
			// http://reference.sitepoint.com/javascript/Node/normalize
			// https://developer.mozilla.org/En/DOM/Node.normalize	    
			if (typeof n.normalize == 'function') n.normalize();

			v = (n && n.firstChild ? n.firstChild.nodeValue : null);
			return ((v === null || v === undefined || v === '') ? defaultValue : v);
		},

		/**
		* Selects the value of a node, parsing integers and floats. Returns the defaultValue, or 0 if none is specified.
		* @param {String} selector The selector/xpath query
		* @param {Node} root (optional) The start of the query (defaults to document).
		* @param {Number} defaultValue
		* @return {Number}
		*/
		selectNumber: function (path, root, defaultValue) {
			var v = Ext.DomQuery.selectValue(path, root, defaultValue || 0);
			return parseFloat(v);
		},

		/**
		* Returns true if the passed element(s) match the passed simple selector (e.g. div.some-class or span:first-child)
		* @param {String/HTMLElement/Array} el An element id, element or array of elements
		* @param {String} selector The simple selector to test
		* @return {Boolean}
		*/
		is: function (el, ss) {
			if (typeof el == "string") {
				el = document.getElementById(el);
			}
			var isArray = Ext.isArray(el),
            	result = Ext.DomQuery.filter(isArray ? el : [el], ss);
			return isArray ? (result.length == el.length) : (result.length > 0);
		},

		/**
		* Filters an array of elements to only include matches of a simple selector (e.g. div.some-class or span:first-child)
		* @param {Array} el An array of elements to filter
		* @param {String} selector The simple selector to test
		* @param {Boolean} nonMatches If true, it returns the elements that DON'T match
		* the selector instead of the ones that match
		* @return {Array} An Array of DOM elements which match the selector. If there are
		* no matches, and empty Array is returned.
		*/
		filter: function (els, ss, nonMatches) {
			ss = ss.replace(trimRe, "");
			if (!simpleCache[ss]) {
				simpleCache[ss] = Ext.DomQuery.compile(ss, "simple");
			}
			var result = simpleCache[ss](els);
			return nonMatches ? quickDiff(result, els) : result;
		},

		/**
		* Collection of matching regular expressions and code snippets.
		* Each capture group within () will be replace the {} in the select
		* statement as specified by their index.
		*/
		matchers: [{
			re: /^\.([\w-]+)/,
			select: 'n = byClassName(n, " {1} ");'
		}, {
			re: /^\:([\w-]+)(?:\(((?:[^\s>\/]*|.*?))\))?/,
			select: 'n = byPseudo(n, "{1}", "{2}");'
		}, {
			re: /^(?:([\[\{])(?:@)?([\w-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]\}])/,
			select: 'n = byAttribute(n, "{2}", "{4}", "{3}", "{1}");'
		}, {
			re: /^#([\w-]+)/,
			select: 'n = byId(n, "{1}");'
		}, {
			re: /^@([\w-]+)/,
			select: 'return {firstChild:{nodeValue:attrValue(n, "{1}")}};'
		}
        ],

		/**
		* Collection of operator comparison functions. The default operators are =, !=, ^=, $=, *=, %=, |= and ~=.
		* 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;.
		*/
		operators: {
			"=": function (a, v) {
				return a == v;
			},
			"!=": function (a, v) {
				return a != v;
			},
			"^=": function (a, v) {
				return a && a.substr(0, v.length) == v;
			},
			"$=": function (a, v) {
				return a && a.substr(a.length - v.length) == v;
			},
			"*=": function (a, v) {
				return a && a.indexOf(v) !== -1;
			},
			"%=": function (a, v) {
				return (a % v) == 0;
			},
			"|=": function (a, v) {
				return a && (a == v || a.substr(0, v.length + 1) == v + '-');
			},
			"~=": function (a, v) {
				return a && (' ' + a + ' ').indexOf(' ' + v + ' ') != -1;
			}
		},

		/**
		* <p>Object hash of "pseudo class" filter functions which are used when filtering selections. Each function is passed
		* two parameters:</p><div class="mdetail-params"><ul>
		* <li><b>c</b> : Array<div class="sub-desc">An Array of DOM elements to filter.</div></li>
		* <li><b>v</b> : String<div class="sub-desc">The argument (if any) supplied in the selector.</div></li>
		* </ul></div>
		* <p>A filter function returns an Array of DOM elements which conform to the pseudo class.</p>
		* <p>In addition to the provided pseudo classes listed above such as <code>first-child</code> and <code>nth-child</code>,
		* developers may add additional, custom psuedo class filters to select elements according to application-specific requirements.</p>
		* <p>For example, to filter <code>&lt;a></code> elements to only return links to <i>external</i> resources:</p>
		* <code><pre>
		Ext.DomQuery.pseudos.external = function(c, v){
		var r = [], ri = -1;
		for(var i = 0, ci; ci = c[i]; i++){
		//      Include in result set only if it's a link to an external resource
		if(ci.hostname != location.hostname){
		r[++ri] = ci;
		}
		}
		return r;
		};</pre></code>
		* Then external links could be gathered with the following statement:<code><pre>
		var externalLinks = Ext.select("a:external");
		</code></pre>
		*/
		pseudos: {
			"first-child": function (c) {
				var r = [], ri = -1, n;
				for (var i = 0, ci; ci = n = c[i]; i++) {
					while ((n = n.previousSibling) && n.nodeType != 1);
					if (!n) {
						r[++ri] = ci;
					}
				}
				return r;
			},

			"last-child": function (c) {
				var r = [], ri = -1, n;
				for (var i = 0, ci; ci = n = c[i]; i++) {
					while ((n = n.nextSibling) && n.nodeType != 1);
					if (!n) {
						r[++ri] = ci;
					}
				}
				return r;
			},

			"nth-child": function (c, a) {
				var r = [], ri = -1,
                	m = nthRe.exec(a == "even" && "2n" || a == "odd" && "2n+1" || !nthRe2.test(a) && "n+" + a || a),
                	f = (m[1] || 1) - 0, l = m[2] - 0;
				for (var i = 0, n; n = c[i]; i++) {
					var pn = n.parentNode;
					if (batch != pn._batch) {
						var j = 0;
						for (var cn = pn.firstChild; cn; cn = cn.nextSibling) {
							if (cn.nodeType == 1) {
								cn.nodeIndex = ++j;
							}
						}
						pn._batch = batch;
					}
					if (f == 1) {
						if (l == 0 || n.nodeIndex == l) {
							r[++ri] = n;
						}
					} else if ((n.nodeIndex + l) % f == 0) {
						r[++ri] = n;
					}
				}

				return r;
			},

			"only-child": function (c) {
				var r = [], ri = -1; ;
				for (var i = 0, ci; ci = c[i]; i++) {
					if (!prev(ci) && !next(ci)) {
						r[++ri] = ci;
					}
				}
				return r;
			},

			"empty": function (c) {
				var r = [], ri = -1;
				for (var i = 0, ci; ci = c[i]; i++) {
					var cns = ci.childNodes, j = 0, cn, empty = true;
					while (cn = cns[j]) {
						++j;
						if (cn.nodeType == 1 || cn.nodeType == 3) {
							empty = false;
							break;
						}
					}
					if (empty) {
						r[++ri] = ci;
					}
				}
				return r;
			},

			"contains": function (c, v) {
				var r = [], ri = -1;
				for (var i = 0, ci; ci = c[i]; i++) {
					if ((ci.textContent || ci.innerText || '').indexOf(v) != -1) {
						r[++ri] = ci;
					}
				}
				return r;
			},

			"nodeValue": function (c, v) {
				var r = [], ri = -1;
				for (var i = 0, ci; ci = c[i]; i++) {
					if (ci.firstChild && ci.firstChild.nodeValue == v) {
						r[++ri] = ci;
					}
				}
				return r;
			},

			"checked": function (c) {
				var r = [], ri = -1;
				for (var i = 0, ci; ci = c[i]; i++) {
					if (ci.checked == true) {
						r[++ri] = ci;
					}
				}
				return r;
			},

			"not": function (c, ss) {
				return Ext.DomQuery.filter(c, ss, true);
			},

			"any": function (c, selectors) {
				var ss = selectors.split('|'),
                	r = [], ri = -1, s;
				for (var i = 0, ci; ci = c[i]; i++) {
					for (var j = 0; s = ss[j]; j++) {
						if (Ext.DomQuery.is(ci, s)) {
							r[++ri] = ci;
							break;
						}
					}
				}
				return r;
			},

			"odd": function (c) {
				return this["nth-child"](c, "odd");
			},

			"even": function (c) {
				return this["nth-child"](c, "even");
			},

			"nth": function (c, a) {
				return c[a - 1] || [];
			},

			"first": function (c) {
				return c[0] || [];
			},

			"last": function (c) {
				return c[c.length - 1] || [];
			},

			"has": function (c, ss) {
				var s = Ext.DomQuery.select,
                	r = [], ri = -1;
				for (var i = 0, ci; ci = c[i]; i++) {
					if (s(ss, ci).length > 0) {
						r[++ri] = ci;
					}
				}
				return r;
			},

			"next": function (c, ss) {
				var is = Ext.DomQuery.is,
                	r = [], ri = -1;
				for (var i = 0, ci; ci = c[i]; i++) {
					var n = next(ci);
					if (n && is(n, ss)) {
						r[++ri] = ci;
					}
				}
				return r;
			},

			"prev": function (c, ss) {
				var is = Ext.DomQuery.is,
                	r = [], ri = -1;
				for (var i = 0, ci; ci = c[i]; i++) {
					var n = prev(ci);
					if (n && is(n, ss)) {
						r[++ri] = ci;
					}
				}
				return r;
			}
		}
	};
} ();

/**
* Selects an array of DOM nodes by CSS/XPath selector. Shorthand of {@link Ext.DomQuery#select}
* @param {String} path The selector/xpath query
* @param {Node} root (optional) The start of the query (defaults to document).
* @return {Array}
* @member Ext
* @method query
*/
Ext.query = Ext.DomQuery.select;
/**
* @class Ext.util.DelayedTask
* <p> The DelayedTask class provides a convenient way to "buffer" the execution of a method,
* performing setTimeout where a new timeout cancels the old timeout. When called, the
* task will wait the specified time period before executing. If durng that time period,
* the task is called again, the original call will be cancelled. This continues so that
* the function is only called a single time for each iteration.</p>
* <p>This method is especially useful for things like detecting whether a user has finished
* typing in a text field. An example would be performing validation on a keypress. You can
* use this class to buffer the keypress events for a certain number of milliseconds, and
* perform only if they stop for that amount of time.  Usage:</p><pre><code>
var task = new Ext.util.DelayedTask(function(){
alert(Ext.getDom('myInputField').value.length);
});
// Wait 500ms before calling our function. If the user presses another key 
// during that 500ms, it will be cancelled and we'll wait another 500ms.
Ext.get('myInputField').on('keypress', function(){
task.{@link #delay}(500); 
});
* </code></pre> 
* <p>Note that we are using a DelayedTask here to illustrate a point. The configuration
* option <tt>buffer</tt> for {@link Ext.util.Observable#addListener addListener/on} will
* also setup a delayed task for you to buffer events.</p> 
* @constructor The parameters to this constructor serve as defaults and are not required.
* @param {Function} fn (optional) The default function to call.
* @param {Object} scope The default scope (The <code><b>this</b></code> reference) in which the
* function is called. If not specified, <code>this</code> will refer to the browser window.
* @param {Array} args (optional) The default Array of arguments.
*/
Ext.util.DelayedTask = function (fn, scope, args) {
	var me = this,
    	id,
    	call = function () {
    		clearInterval(id);
    		id = null;
    		fn.apply(scope, args || []);
    	};

	/**
	* Cancels any pending timeout and queues a new one
	* @param {Number} delay The milliseconds to delay
	* @param {Function} newFn (optional) Overrides function passed to constructor
	* @param {Object} newScope (optional) Overrides scope passed to constructor. Remember that if no scope
	* is specified, <code>this</code> will refer to the browser window.
	* @param {Array} newArgs (optional) Overrides args passed to constructor
	*/
	me.delay = function (delay, newFn, newScope, newArgs) {
		me.cancel();
		fn = newFn || fn;
		scope = newScope || scope;
		args = newArgs || args;
		id = setInterval(call, delay);
	};

	/**
	* Cancel the last queued timeout
	*/
	me.cancel = function () {
		if (id) {
			clearInterval(id);
			id = null;
		}
	};
}; (function () {

	var EXTUTIL = Ext.util,
    EACH = Ext.each,
    TRUE = true,
    FALSE = false;
	/**
	* @class Ext.util.Observable
	* Base class that provides a common interface for publishing events. Subclasses are expected to
	* to have a property "events" with all the events defined, and, optionally, a property "listeners"
	* with configured listeners defined.<br>
	* For example:
	* <pre><code>
	Employee = Ext.extend(Ext.util.Observable, {
	constructor: function(config){
	this.name = config.name;
	this.addEvents({
	"fired" : true,
	"quit" : true
	});

	// Copy configured listeners into *this* object so that the base class&#39;s
	// constructor will add them.
	this.listeners = config.listeners;

	// Call our superclass constructor to complete construction process.
	Employee.superclass.constructor.call(this, config)
	}
	});
	</code></pre>
	* This could then be used like this:<pre><code>
	var newEmployee = new Employee({
	name: employeeName,
	listeners: {
	quit: function() {
	// By default, "this" will be the object that fired the event.
	alert(this.name + " has quit!");
	}
	}
	});
	</code></pre>
	*/
	EXTUTIL.Observable = function () {
		/**
		* @cfg {Object} listeners (optional) <p>A config object containing one or more event handlers to be added to this
		* object during initialization.  This should be a valid listeners config object as specified in the
		* {@link #addListener} example for attaching multiple handlers at once.</p>
		* <br><p><b><u>DOM events from ExtJs {@link Ext.Component Components}</u></b></p>
		* <br><p>While <i>some</i> ExtJs Component classes export selected DOM events (e.g. "click", "mouseover" etc), this
		* is usually only done when extra value can be added. For example the {@link Ext.DataView DataView}'s
		* <b><code>{@link Ext.DataView#click click}</code></b> event passing the node clicked on. To access DOM
		* events directly from a Component's HTMLElement, listeners must be added to the <i>{@link Ext.Component#getEl Element}</i> after the Component
		* has been rendered. A plugin can simplify this step:<pre><code>
		// Plugin is configured with a listeners config object.
		// The Component is appended to the argument list of all handler functions.
		Ext.DomObserver = Ext.extend(Object, {
		constructor: function(config) {
		this.listeners = config.listeners ? config.listeners : config;
		},

		// Component passes itself into plugin&#39;s init method
		init: function(c) {
		var p, l = this.listeners;
		for (p in l) {
		if (Ext.isFunction(l[p])) {
		l[p] = this.createHandler(l[p], c);
		} else {
		l[p].fn = this.createHandler(l[p].fn, c);
		}
		}

		// Add the listeners to the Element immediately following the render call
		c.render = c.render.{@link Function#createSequence createSequence}(function() {
		var e = c.getEl();
		if (e) {
		e.on(l);
		}
		});
		},

		createHandler: function(fn, c) {
		return function(e) {
		fn.call(this, e, c);
		};
		}
		});

		var combo = new Ext.form.ComboBox({

		// Collapse combo when its element is clicked on
		plugins: [ new Ext.DomObserver({
		click: function(evt, comp) {
		comp.collapse();
		}
		})],
		store: myStore,
		typeAhead: true,
		mode: 'local',
		triggerAction: 'all'
		});
		* </code></pre></p>
		*/
		var me = this, e = me.events;
		if (me.listeners) {
			me.on(me.listeners);
			delete me.listeners;
		}
		me.events = e || {};
	};

	EXTUTIL.Observable.prototype = {
		// private
		filterOptRe: /^(?:scope|delay|buffer|single)$/,

		/**
		* <p>Fires the specified event with the passed parameters (minus the event name).</p>
		* <p>An event may be set to bubble up an Observable parent hierarchy (See {@link Ext.Component#getBubbleTarget})
		* by calling {@link #enableBubble}.</p>
		* @param {String} eventName The name of the event to fire.
		* @param {Object...} args Variable number of parameters are passed to handlers.
		* @return {Boolean} returns false if any of the handlers return false otherwise it returns true.
		*/
		fireEvent: function () {
			var a = Array.prototype.slice.call(arguments, 0),
            ename = a[0].toLowerCase(),
            me = this,
            ret = TRUE,
            ce = me.events[ename],
            cc,
            q,
            c;
			if (me.eventsSuspended === TRUE) {
				if (q = me.eventQueue) {
					q.push(a);
				}
			}
			else if (typeof ce == 'object') {
				if (ce.bubble) {
					if (ce.fire.apply(ce, a.slice(1)) === FALSE) {
						return FALSE;
					}
					c = me.getBubbleTarget && me.getBubbleTarget();
					if (c && c.enableBubble) {
						cc = c.events[ename];
						if (!cc || typeof cc != 'object' || !cc.bubble) {
							c.enableBubble(ename);
						}
						return c.fireEvent.apply(c, a);
					}
				}
				else {
					a.shift();
					ret = ce.fire.apply(ce, a);
				}
			}
			return ret;
		},

		/**
		* Appends an event handler to this object.
		* @param {String}   eventName The name of the event to listen for.
		* @param {Function} handler The method the event invokes.
		* @param {Object}   scope (optional) The scope (<code><b>this</b></code> reference) in which the handler function is executed.
		* <b>If omitted, defaults to the object which fired the event.</b>
		* @param {Object}   options (optional) An object containing handler configuration.
		* properties. This may contain any of the following properties:<ul>
		* <li><b>scope</b> : Object<div class="sub-desc">The scope (<code><b>this</b></code> reference) in which the handler function is executed.
		* <b>If omitted, defaults to the object which fired the event.</b></div></li>
		* <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>
		* <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>
		* <li><b>buffer</b> : Number<div class="sub-desc">Causes the handler to be scheduled to run in an {@link Ext.util.DelayedTask} delayed
		* by the specified number of milliseconds. If the event fires again within that time, the original
		* handler is <em>not</em> invoked, but the new handler is scheduled in its place.</div></li>
		* <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>
		* if the event was bubbled up from a child Observable.</div></li>
		* </ul><br>
		* <p>
		* <b>Combining Options</b><br>
		* Using the options argument, it is possible to combine different types of listeners:<br>
		* <br>
		* A delayed, one-time listener.
		* <pre><code>
		myDataView.on('click', this.onClick, this, {
		single: true,
		delay: 100
		});</code></pre>
		* <p>
		* <b>Attaching multiple handlers in 1 call</b><br>
		* The method also allows for a single argument to be passed which is a config object containing properties
		* which specify multiple handlers.
		* <p>
		* <pre><code>
		myGridPanel.on({
		'click' : {
		fn: this.onClick,
		scope: this,
		delay: 100
		},
		'mouseover' : {
		fn: this.onMouseOver,
		scope: this
		},
		'mouseout' : {
		fn: this.onMouseOut,
		scope: this
		}
		});</code></pre>
		* <p>
		* Or a shorthand syntax:<br>
		* <pre><code>
		myGridPanel.on({
		'click' : this.onClick,
		'mouseover' : this.onMouseOver,
		'mouseout' : this.onMouseOut,
		scope: this
		});</code></pre>
		*/
		addListener: function (eventName, fn, scope, o) {
			var me = this,
            e,
            oe,
            isF,
        ce;
			if (typeof eventName == 'object') {
				o = eventName;
				for (e in o) {
					oe = o[e];
					if (!me.filterOptRe.test(e)) {
						me.addListener(e, oe.fn || oe, oe.scope || o.scope, oe.fn ? oe : o);
					}
				}
			} else {
				eventName = eventName.toLowerCase();
				ce = me.events[eventName] || TRUE;
				if (typeof ce == 'boolean') {
					me.events[eventName] = ce = new EXTUTIL.Event(me, eventName);
				}
				ce.addListener(fn, scope, typeof o == 'object' ? o : {});
			}
		},

		/**
		* Removes an event handler.
		* @param {String}   eventName The type of event the handler was associated with.
		* @param {Function} handler   The handler to remove. <b>This must be a reference to the function passed into the {@link #addListener} call.</b>
		* @param {Object}   scope     (optional) The scope originally specified for the handler.
		*/
		removeListener: function (eventName, fn, scope) {
			var ce = this.events[eventName.toLowerCase()];
			if (typeof ce == 'object') {
				ce.removeListener(fn, scope);
			}
		},

		/**
		* Removes all listeners for this object
		*/
		purgeListeners: function () {
			var events = this.events,
            evt,
            key;
			for (key in events) {
				evt = events[key];
				if (typeof evt == 'object') {
					evt.clearListeners();
				}
			}
		},

		/**
		* Adds the specified events to the list of events which this Observable may fire.
		* @param {Object|String} o Either an object with event names as properties with a value of <code>true</code>
		* or the first event name string if multiple event names are being passed as separate parameters.
		* @param {string} Optional. Event name if multiple event names are being passed as separate parameters.
		* Usage:<pre><code>
		this.addEvents('storeloaded', 'storecleared');
		</code></pre>
		*/
		addEvents: function (o) {
			var me = this;
			me.events = me.events || {};
			if (typeof o == 'string') {
				var a = arguments,
                i = a.length;
				while (i--) {
					me.events[a[i]] = me.events[a[i]] || TRUE;
				}
			} else {
				Ext.applyIf(me.events, o);
			}
		},

		/**
		* Checks to see if this object has any listeners for a specified event
		* @param {String} eventName The name of the event to check for
		* @return {Boolean} True if the event is being listened for, else false
		*/
		hasListener: function (eventName) {
			var e = this.events[eventName.toLowerCase()];
			return typeof e == 'object' && e.listeners.length > 0;
		},

		/**
		* Suspend the firing of all events. (see {@link #resumeEvents})
		* @param {Boolean} queueSuspended Pass as true to queue up suspended events to be fired
		* after the {@link #resumeEvents} call instead of discarding all suspended events;
		*/
		suspendEvents: function (queueSuspended) {
			this.eventsSuspended = TRUE;
			if (queueSuspended && !this.eventQueue) {
				this.eventQueue = [];
			}
		},

		/**
		* Resume firing events. (see {@link #suspendEvents})
		* If events were suspended using the <tt><b>queueSuspended</b></tt> parameter, then all
		* events fired during event suspension will be sent to any listeners now.
		*/
		resumeEvents: function () {
			var me = this,
            queued = me.eventQueue || [];
			me.eventsSuspended = FALSE;
			delete me.eventQueue;
			EACH(queued, function (e) {
				me.fireEvent.apply(me, e);
			});
		}
	};

	var OBSERVABLE = EXTUTIL.Observable.prototype;
	/**
	* Appends an event handler to this object (shorthand for {@link #addListener}.)
	* @param {String}   eventName     The type of event to listen for
	* @param {Function} handler       The method the event invokes
	* @param {Object}   scope         (optional) The scope (<code><b>this</b></code> reference) in which the handler function is executed.
	* <b>If omitted, defaults to the object which fired the event.</b>
	* @param {Object}   options       (optional) An object containing handler configuration.
	* @method
	*/
	OBSERVABLE.on = OBSERVABLE.addListener;
	/**
	* Removes an event handler (shorthand for {@link #removeListener}.)
	* @param {String}   eventName     The type of event the handler was associated with.
	* @param {Function} handler       The handler to remove. <b>This must be a reference to the function passed into the {@link #addListener} call.</b>
	* @param {Object}   scope         (optional) The scope originally specified for the handler.
	* @method
	*/
	OBSERVABLE.un = OBSERVABLE.removeListener;

	/**
	* Removes <b>all</b> added captures from the Observable.
	* @param {Observable} o The Observable to release
	* @static
	*/
	EXTUTIL.Observable.releaseCapture = function (o) {
		o.fireEvent = OBSERVABLE.fireEvent;
	};

	function createTargeted(h, o, scope) {
		return function () {
			if (o.target == arguments[0]) {
				h.apply(scope, Array.prototype.slice.call(arguments, 0));
			}
		};
	};

	function createBuffered(h, o, l, scope) {
		l.task = new EXTUTIL.DelayedTask();
		return function () {
			l.task.delay(o.buffer, h, scope, Array.prototype.slice.call(arguments, 0));
		};
	};

	function createSingle(h, e, fn, scope) {
		return function () {
			e.removeListener(fn, scope);
			return h.apply(scope, arguments);
		};
	};

	function createDelayed(h, o, l, scope) {
		return function () {
			var task = new EXTUTIL.DelayedTask();
			if (!l.tasks) {
				l.tasks = [];
			}
			l.tasks.push(task);
			task.delay(o.delay || 10, h, scope, Array.prototype.slice.call(arguments, 0));
		};
	};

	EXTUTIL.Event = function (obj, name) {
		this.name = name;
		this.obj = obj;
		this.listeners = [];
	};

	EXTUTIL.Event.prototype = {
		addListener: function (fn, scope, options) {
			var me = this,
            l;
			scope = scope || me.obj;
			if (!me.isListening(fn, scope)) {
				l = me.createListener(fn, scope, options);
				if (me.firing) { // if we are currently firing this event, don't disturb the listener loop
					me.listeners = me.listeners.slice(0);
				}
				me.listeners.push(l);
			}
		},

		createListener: function (fn, scope, o) {
			o = o || {}, scope = scope || this.obj;
			var l = {
				fn: fn,
				scope: scope,
				options: o
			}, h = fn;
			if (o.target) {
				h = createTargeted(h, o, scope);
			}
			if (o.delay) {
				h = createDelayed(h, o, l, scope);
			}
			if (o.single) {
				h = createSingle(h, this, fn, scope);
			}
			if (o.buffer) {
				h = createBuffered(h, o, l, scope);
			}
			l.fireFn = h;
			return l;
		},

		findListener: function (fn, scope) {
			var list = this.listeners,
            i = list.length,
            l;

			scope = scope || this.obj;
			while (i--) {
				l = list[i];
				if (l) {
					if (l.fn == fn && l.scope == scope) {
						return i;
					}
				}
			}
			return -1;
		},

		isListening: function (fn, scope) {
			return this.findListener(fn, scope) != -1;
		},

		removeListener: function (fn, scope) {
			var index,
            l,
            k,
            me = this,
            ret = FALSE;
			if ((index = me.findListener(fn, scope)) != -1) {
				if (me.firing) {
					me.listeners = me.listeners.slice(0);
				}
				l = me.listeners[index];
				if (l.task) {
					l.task.cancel();
					delete l.task;
				}
				k = l.tasks && l.tasks.length;
				if (k) {
					while (k--) {
						l.tasks[k].cancel();
					}
					delete l.tasks;
				}
				me.listeners.splice(index, 1);
				ret = TRUE;
			}
			return ret;
		},

		// Iterate to stop any buffered/delayed events
		clearListeners: function () {
			var me = this,
            l = me.listeners,
            i = l.length;
			while (i--) {
				me.removeListener(l[i].fn, l[i].scope);
			}
		},

		fire: function () {
			var me = this,
            listeners = me.listeners,
            len = listeners.length,
            i = 0,
            l;

			if (len > 0) {
				me.firing = TRUE;
				var args = Array.prototype.slice.call(arguments, 0);
				for (; i < len; i++) {
					l = listeners[i];
					if (l && l.fireFn.apply(l.scope || me.obj || window, args) === FALSE) {
						return (me.firing = FALSE);
					}
				}
			}
			me.firing = FALSE;
			return TRUE;
		}

	};
})();
/**
* @class Ext.util.Observable
*/
Ext.apply(Ext.util.Observable.prototype, function () {
	// this is considered experimental (along with beforeMethod, afterMethod, removeMethodListener?)
	// allows for easier interceptor and sequences, including cancelling and overwriting the return value of the call
	// private
	function getMethodEvent(method) {
		var e = (this.methodEvents = this.methodEvents ||
        {})[method], returnValue, v, cancel, obj = this;

		if (!e) {
			this.methodEvents[method] = e = {};
			e.originalFn = this[method];
			e.methodName = method;
			e.before = [];
			e.after = [];

			var makeCall = function (fn, scope, args) {
				if ((v = fn.apply(scope || obj, args)) !== undefined) {
					if (typeof v == 'object') {
						if (v.returnValue !== undefined) {
							returnValue = v.returnValue;
						} else {
							returnValue = v;
						}
						cancel = !!v.cancel;
					}
					else
						if (v === false) {
							cancel = true;
						}
						else {
							returnValue = v;
						}
				}
			};

			this[method] = function () {
				var args = Array.prototype.slice.call(arguments, 0),
                    b;
				returnValue = v = undefined;
				cancel = false;

				for (var i = 0, len = e.before.length; i < len; i++) {
					b = e.before[i];
					makeCall(b.fn, b.scope, args);
					if (cancel) {
						return returnValue;
					}
				}

				if ((v = e.originalFn.apply(obj, args)) !== undefined) {
					returnValue = v;
				}

				for (var i = 0, len = e.after.length; i < len; i++) {
					b = e.after[i];
					makeCall(b.fn, b.scope, args);
					if (cancel) {
						return returnValue;
					}
				}
				return returnValue;
			};
		}
		return e;
	}

	return {
		// these are considered experimental
		// allows for easier interceptor and sequences, including cancelling and overwriting the return value of the call
		// adds an 'interceptor' called before the original method
		beforeMethod: function (method, fn, scope) {
			getMethodEvent.call(this, method).before.push({
				fn: fn,
				scope: scope
			});
		},

		// adds a 'sequence' called after the original method
		afterMethod: function (method, fn, scope) {
			getMethodEvent.call(this, method).after.push({
				fn: fn,
				scope: scope
			});
		},

		removeMethodListener: function (method, fn, scope) {
			var e = this.getMethodEvent(method);
			for (var i = 0, len = e.before.length; i < len; i++) {
				if (e.before[i].fn == fn && e.before[i].scope == scope) {
					e.before.splice(i, 1);
					return;
				}
			}
			for (var i = 0, len = e.after.length; i < len; i++) {
				if (e.after[i].fn == fn && e.after[i].scope == scope) {
					e.after.splice(i, 1);
					return;
				}
			}
		},

		/**
		* Relays selected events from the specified Observable as if the events were fired by <tt><b>this</b></tt>.
		* @param {Object} o The Observable whose events this object is to relay.
		* @param {Array} events Array of event names to relay.
		*/
		relayEvents: function (o, events) {
			var me = this;
			function createHandler(ename) {
				return function () {
					return me.fireEvent.apply(me, [ename].concat(Array.prototype.slice.call(arguments, 0)));
				};
			}
			for (var i = 0, len = events.length; i < len; i++) {
				var ename = events[i];
				me.events[ename] = me.events[ename] || true;
				o.on(ename, createHandler(ename), me);
			}
		},

		/**
		* <p>Enables events fired by this Observable to bubble up an owner hierarchy by calling
		* <code>this.getBubbleTarget()</code> if present. There is no implementation in the Observable base class.</p>
		* <p>This is commonly used by Ext.Components to bubble events to owner Containers. See {@link Ext.Component.getBubbleTarget}. The default
		* implementation in Ext.Component returns the Component's immediate owner. But if a known target is required, this can be overridden to
		* access the required target more quickly.</p>
		* <p>Example:</p><pre><code>
		Ext.override(Ext.form.Field, {
		//  Add functionality to Field&#39;s initComponent to enable the change event to bubble
		initComponent : Ext.form.Field.prototype.initComponent.createSequence(function() {
		this.enableBubble('change');
		}),

		//  We know that we want Field&#39;s events to bubble directly to the FormPanel.
		getBubbleTarget : function() {
		if (!this.formPanel) {
		this.formPanel = this.findParentByType('form');
		}
		return this.formPanel;
		}
		});

		var myForm = new Ext.formPanel({
		title: 'User Details',
		items: [{
		...
		}],
		listeners: {
		change: function() {
		// Title goes red if form has been modified.
		myForm.header.setStyle('color', 'red');
		}
		}
		});
		</code></pre>
		* @param {String/Array} events The event name to bubble, or an Array of event names.
		*/
		enableBubble: function (events) {
			var me = this;
			if (!Ext.isEmpty(events)) {
				events = Ext.isArray(events) ? events : Array.prototype.slice.call(arguments, 0);
				for (var i = 0, len = events.length; i < len; i++) {
					var ename = events[i];
					ename = ename.toLowerCase();
					var ce = me.events[ename] || true;
					if (typeof ce == 'boolean') {
						ce = new Ext.util.Event(me, ename);
						me.events[ename] = ce;
					}
					ce.bubble = true;
				}
			}
		}
	};
} ());


/**
* Starts capture on the specified Observable. All events will be passed
* to the supplied function with the event name + standard signature of the event
* <b>before</b> the event is fired. If the supplied function returns false,
* the event will not fire.
* @param {Observable} o The Observable to capture events from.
* @param {Function} fn The function to call when an event is fired.
* @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to the Observable firing the event.
* @static
*/
Ext.util.Observable.capture = function (o, fn, scope) {
	o.fireEvent = o.fireEvent.createInterceptor(fn, scope);
};


/**
* Sets observability on the passed class constructor.<p>
* <p>This makes any event fired on any instance of the passed class also fire a single event through
* the <i>class</i> allowing for central handling of events on many instances at once.</p>
* <p>Usage:</p><pre><code>
Ext.util.Observable.observeClass(Ext.data.Connection);
Ext.data.Connection.on('beforerequest', function(con, options) {
console.log('Ajax request made to ' + options.url);
});</code></pre>
* @param {Function} c The class constructor to make observable.
* @param {Object} listeners An object containing a series of listeners to add. See {@link #addListener}.
* @static
*/
Ext.util.Observable.observeClass = function (c, listeners) {
	if (c) {
		if (!c.fireEvent) {
			Ext.apply(c, new Ext.util.Observable());
			Ext.util.Observable.capture(c.prototype, c.fireEvent, c);
		}
		if (typeof listeners == 'object') {
			c.on(listeners);
		}
		return c;
	}
};
/**
* @class Ext.EventManager
* Registers event handlers that want to receive a normalized EventObject instead of the standard browser event and provides
* several useful events directly.
* See {@link Ext.EventObject} for more details on normalized event objects.
* @singleton
*/

Ext.EventManager = function () {
	var docReadyEvent,
        docReadyProcId,
        docReadyState = false,
        DETECT_NATIVE = Ext.isGecko || Ext.isWebKit || Ext.isSafari,
        E = Ext.lib.Event,
        D = Ext.lib.Dom,
        DOC = document,
        WINDOW = window,
        DOMCONTENTLOADED = "DOMContentLoaded",
        COMPLETE = 'complete',
        propRe = /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/,
	/*
	* This cache is used to hold special js objects, the document and window, that don't have an id. We need to keep
	* a reference to them so we can look them up at a later point.
	*/
        specialElCache = [];

	function getId(el) {
		var id = false,
            i = 0,
            len = specialElCache.length,
            id = false,
            skip = false,
            o;
		if (el) {
			if (el.getElementById || el.navigator) {
				// look up the id
				for (; i < len; ++i) {
					o = specialElCache[i];
					if (o.el === el) {
						id = o.id;
						break;
					}
				}
				if (!id) {
					// for browsers that support it, ensure that give the el the same id
					id = Ext.id(el);
					specialElCache.push({
						id: id,
						el: el
					});
					skip = true;
				}
			} else {
				id = Ext.id(el);
			}
			if (!Ext.elCache[id]) {
				Ext.Element.addToCache(new Ext.Element(el), id);
				if (skip) {
					Ext.elCache[id].skipGC = true;
				}
			}
		}
		return id;
	};

	/// There is some jquery work around stuff here that isn't needed in Ext Core.
	function addListener(el, ename, fn, task, wrap, scope) {
		el = Ext.getDom(el);
		var id = getId(el),
            es = Ext.elCache[id].events,
            wfn;

		wfn = E.on(el, ename, wrap);
		es[ename] = es[ename] || [];

		/* 0 = Original Function,
		1 = Event Manager Wrapped Function,
		2 = Scope,
		3 = Adapter Wrapped Function,
		4 = Buffered Task
		*/
		es[ename].push([fn, wrap, scope, wfn, task]);

		// this is a workaround for jQuery and should somehow be removed from Ext Core in the future
		// without breaking ExtJS.

		// workaround for jQuery
		if (el.addEventListener && ename == "mousewheel") {
			var args = ["DOMMouseScroll", wrap, false];
			el.addEventListener.apply(el, args);
			Ext.EventManager.addListener(WINDOW, 'unload', function () {
				el.removeEventListener.apply(el, args);
			});
		}

		// fix stopped mousedowns on the document
		if (el == DOC && ename == "mousedown") {
			Ext.EventManager.stoppedMouseDownEvent.addListener(wrap);
		}
	};

	function doScrollChk() {
		/* Notes:
		'doScroll' will NOT work in a IFRAME/FRAMESET.
		The method succeeds but, a DOM query done immediately after -- FAILS.
		*/
		if (window != top) {
			return false;
		}

		try {
			DOC.documentElement.doScroll('left');
		} catch (e) {
			return false;
		}

		fireDocReady();
		return true;
	}
	/**
	* @return {Boolean} True if the document is in a 'complete' state (or was determined to
	* be true by other means). If false, the state is evaluated again until canceled.
	*/
	function checkReadyState(e) {

		if (Ext.isIE && doScrollChk()) {
			return true;
		}
		if (DOC.readyState == COMPLETE) {
			fireDocReady();
			return true;
		}
		docReadyState || (docReadyProcId = setTimeout(arguments.callee, 2));
		return false;
	}

	var styles;
	function checkStyleSheets(e) {
		styles || (styles = Ext.query('style, link[rel=stylesheet]'));
		if (styles.length == DOC.styleSheets.length) {
			fireDocReady();
			return true;
		}
		docReadyState || (docReadyProcId = setTimeout(arguments.callee, 2));
		return false;
	}

	function OperaDOMContentLoaded(e) {
		DOC.removeEventListener(DOMCONTENTLOADED, arguments.callee, false);
		checkStyleSheets();
	}

	function fireDocReady(e) {
		if (!docReadyState) {
			docReadyState = true; //only attempt listener removal once

			if (docReadyProcId) {
				clearTimeout(docReadyProcId);
			}
			if (DETECT_NATIVE) {
				DOC.removeEventListener(DOMCONTENTLOADED, fireDocReady, false);
			}
			if (Ext.isIE && checkReadyState.bindIE) {  //was this was actually set ??
				DOC.detachEvent('onreadystatechange', checkReadyState);
			}
			E.un(WINDOW, "load", arguments.callee);
		}
		if (docReadyEvent && !Ext.isReady) {
			Ext.isReady = true;
			docReadyEvent.fire();
			docReadyEvent.listeners = [];
		}

	};

	function initDocReady() {
		docReadyEvent || (docReadyEvent = new Ext.util.Event());
		if (DETECT_NATIVE) {
			DOC.addEventListener(DOMCONTENTLOADED, fireDocReady, false);
		}
		/*
		* Handle additional (exceptional) detection strategies here
		*/
		if (Ext.isIE) {
			//Use readystatechange as a backup AND primary detection mechanism for a FRAME/IFRAME
			//See if page is already loaded
			if (!checkReadyState()) {
				checkReadyState.bindIE = true;
				DOC.attachEvent('onreadystatechange', checkReadyState);
			}

		} else if (Ext.isOpera) {
			/* Notes:
			Opera needs special treatment needed here because CSS rules are NOT QUITE
			available after DOMContentLoaded is raised.
			*/

			//See if page is already loaded and all styleSheets are in place
			(DOC.readyState == COMPLETE && checkStyleSheets()) ||
                DOC.addEventListener(DOMCONTENTLOADED, OperaDOMContentLoaded, false);

		} else if (Ext.isWebKit) {
			//Fallback for older Webkits without DOMCONTENTLOADED support
			checkReadyState();
		}
		// no matter what, make sure it fires on load
		E.on(WINDOW, "load", fireDocReady);
	};

	function createTargeted(h, o) {
		return function () {
			var args = Ext.toArray(arguments);
			if (o.target == Ext.EventObject.setEvent(args[0]).target) {
				h.apply(this, args);
			}
		};
	};

	function createBuffered(h, o, task) {
		return function (e) {
			// create new event object impl so new events don't wipe out properties
			task.delay(o.buffer, h, null, [new Ext.EventObjectImpl(e)]);
		};
	};

	function createSingle(h, el, ename, fn, scope) {
		return function (e) {
			Ext.EventManager.removeListener(el, ename, fn, scope);
			h(e);
		};
	};

	function createDelayed(h, o, fn) {
		return function (e) {
			var task = new Ext.util.DelayedTask(h);
			if (!fn.tasks) {
				fn.tasks = [];
			}
			fn.tasks.push(task);
			task.delay(o.delay || 10, h, null, [new Ext.EventObjectImpl(e)]);
		};
	};

	function listen(element, ename, opt, fn, scope) {
		var o = (!opt || typeof opt == "boolean") ? {} : opt,
            el = Ext.getDom(element), task;

		fn = fn || o.fn;
		scope = scope || o.scope;

		if (!el) {
			throw "Error listening for \"" + ename + '\". Element "' + element + '" doesn\'t exist.';
		}
		function h(e) {
			// prevent errors while unload occurring
			if (!Ext) {// !window[xname]){  ==> can't we do this?
				return;
			}
			e = Ext.EventObject.setEvent(e);
			var t;
			if (o.delegate) {
				if (!(t = e.getTarget(o.delegate, el))) {
					return;
				}
			} else {
				t = e.target;
			}
			if (o.stopEvent) {
				e.stopEvent();
			}
			if (o.preventDefault) {
				e.preventDefault();
			}
			if (o.stopPropagation) {
				e.stopPropagation();
			}
			if (o.normalized) {
				e = e.browserEvent;
			}

			fn.call(scope || el, e, t, o);
		};
		if (o.target) {
			h = createTargeted(h, o);
		}
		if (o.delay) {
			h = createDelayed(h, o, fn);
		}
		if (o.single) {
			h = createSingle(h, el, ename, fn, scope);
		}
		if (o.buffer) {
			task = new Ext.util.DelayedTask(h);
			h = createBuffered(h, o, task);
		}

		addListener(el, ename, fn, task, h, scope);
		return h;
	};

	var pub = {
		/**
		* Appends an event handler to an element.  The shorthand version {@link #on} is equivalent.  Typically you will
		* use {@link Ext.Element#addListener} directly on an Element in favor of calling this version.
		* @param {String/HTMLElement} el The html element or id to assign the event handler to.
		* @param {String} eventName The name of the event to listen for.
		* @param {Function} handler The handler function the event invokes. This function is passed
		* the following parameters:<ul>
		* <li>evt : EventObject<div class="sub-desc">The {@link Ext.EventObject EventObject} describing the event.</div></li>
		* <li>t : Element<div class="sub-desc">The {@link Ext.Element Element} which was the target of the event.
		* Note that this may be filtered by using the <tt>delegate</tt> option.</div></li>
		* <li>o : Object<div class="sub-desc">The options object from the addListener call.</div></li>
		* </ul>
		* @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>.
		* @param {Object} options (optional) An object containing handler configuration properties.
		* This may contain any of the following properties:<ul>
		* <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>
		* <li>delegate : String<div class="sub-desc">A simple selector to filter the target or look for a descendant of the target</div></li>
		* <li>stopEvent : Boolean<div class="sub-desc">True to stop the event. That is stop propagation, and prevent the default action.</div></li>
		* <li>preventDefault : Boolean<div class="sub-desc">True to prevent the default action</div></li>
		* <li>stopPropagation : Boolean<div class="sub-desc">True to prevent event propagation</div></li>
		* <li>normalized : Boolean<div class="sub-desc">False to pass a browser event to the handler function instead of an Ext.EventObject</div></li>
		* <li>delay : Number<div class="sub-desc">The number of milliseconds to delay the invocation of the handler after te event fires.</div></li>
		* <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>
		* <li>buffer : Number<div class="sub-desc">Causes the handler to be scheduled to run in an {@link Ext.util.DelayedTask} delayed
		* by the specified number of milliseconds. If the event fires again within that time, the original
		* handler is <em>not</em> invoked, but the new handler is scheduled in its place.</div></li>
		* <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>
		* </ul><br>
		* <p>See {@link Ext.Element#addListener} for examples of how to use these options.</p>
		*/
		addListener: function (element, eventName, fn, scope, options) {
			if (typeof eventName == 'object') {
				var o = eventName, e, val;
				for (e in o) {
					val = o[e];
					if (!propRe.test(e)) {
						if (Ext.isFunction(val)) {
							// shared options
							listen(element, e, o, val, o.scope);
						} else {
							// individual options
							listen(element, e, val);
						}
					}
				}
			} else {
				listen(element, eventName, options, fn, scope);
			}
		},

		/**
		* Removes an event handler from an element.  The shorthand version {@link #un} is equivalent.  Typically
		* you will use {@link Ext.Element#removeListener} directly on an Element in favor of calling this version.
		* @param {String/HTMLElement} el The id or html element from which to remove the listener.
		* @param {String} eventName The name of the event.
		* @param {Function} fn The handler function to remove. <b>This must be a reference to the function passed into the {@link #addListener} call.</b>
		* @param {Object} scope If a scope (<b><code>this</code></b> reference) was specified when the listener was added,
		* then this must refer to the same object.
		*/
		removeListener: function (el, eventName, fn, scope) {
			el = Ext.getDom(el);
			var id = getId(el),
                f = el && (Ext.elCache[id].events)[eventName] || [],
                wrap, i, l, k, len, fnc;

			for (i = 0, len = f.length; i < len; i++) {

				/* 0 = Original Function,
				1 = Event Manager Wrapped Function,
				2 = Scope,
				3 = Adapter Wrapped Function,
				4 = Buffered Task
				*/
				if (Ext.isArray(fnc = f[i]) && fnc[0] == fn && (!scope || fnc[2] == scope)) {
					if (fnc[4]) {
						fnc[4].cancel();
					}
					k = fn.tasks && fn.tasks.length;
					if (k) {
						while (k--) {
							fn.tasks[k].cancel();
						}
						delete fn.tasks;
					}
					wrap = fnc[1];
					E.un(el, eventName, E.extAdapter ? fnc[3] : wrap);

					// jQuery workaround that should be removed from Ext Core
					if (wrap && el.addEventListener && eventName == "mousewheel") {
						el.removeEventListener("DOMMouseScroll", wrap, false);
					}

					// fix stopped mousedowns on the document
					if (wrap && el == DOC && eventName == "mousedown") {
						Ext.EventManager.stoppedMouseDownEvent.removeListener(wrap);
					}

					f.splice(i, 1);
					if (f.length === 0) {
						delete Ext.elCache[id].events[eventName];
					}
					for (k in Ext.elCache[id].events) {
						return false;
					}
					Ext.elCache[id].events = {};
					return false;
				}
			}
		},

		/**
		* Removes all event handers from an element.  Typically you will use {@link Ext.Element#removeAllListeners}
		* directly on an Element in favor of calling this version.
		* @param {String/HTMLElement} el The id or html element from which to remove all event handlers.
		*/
		removeAll: function (el) {
			el = Ext.getDom(el);
			var id = getId(el),
                ec = Ext.elCache[id] || {},
                es = ec.events || {},
                f, i, len, ename, fn, k, wrap;

			for (ename in es) {
				if (es.hasOwnProperty(ename)) {
					f = es[ename];
					/* 0 = Original Function,
					1 = Event Manager Wrapped Function,
					2 = Scope,
					3 = Adapter Wrapped Function,
					4 = Buffered Task
					*/
					for (i = 0, len = f.length; i < len; i++) {
						fn = f[i];
						if (fn[4]) {
							fn[4].cancel();
						}
						if (fn[0].tasks && (k = fn[0].tasks.length)) {
							while (k--) {
								fn[0].tasks[k].cancel();
							}
							delete fn.tasks;
						}
						wrap = fn[1];
						E.un(el, ename, E.extAdapter ? fn[3] : wrap);

						// jQuery workaround that should be removed from Ext Core
						if (el.addEventListener && wrap && ename == "mousewheel") {
							el.removeEventListener("DOMMouseScroll", wrap, false);
						}

						// fix stopped mousedowns on the document
						if (wrap && el == DOC && ename == "mousedown") {
							Ext.EventManager.stoppedMouseDownEvent.removeListener(wrap);
						}
					}
				}
			}
			if (Ext.elCache[id]) {
				Ext.elCache[id].events = {};
			}
		},

		getListeners: function (el, eventName) {
			el = Ext.getDom(el);
			var id = getId(el),
                ec = Ext.elCache[id] || {},
                es = ec.events || {},
                results = [];
			if (es && es[eventName]) {
				return es[eventName];
			} else {
				return null;
			}
		},

		purgeElement: function (el, recurse, eventName) {
			el = Ext.getDom(el);
			var id = getId(el),
                ec = Ext.elCache[id] || {},
                es = ec.events || {},
                i, f, len;
			if (eventName) {
				if (es && es.hasOwnProperty(eventName)) {
					f = es[eventName];
					for (i = 0, len = f.length; i < len; i++) {
						Ext.EventManager.removeListener(el, eventName, f[i][0]);
					}
				}
			} else {
				Ext.EventManager.removeAll(el);
			}
			if (recurse && el && el.childNodes) {
				for (i = 0, len = el.childNodes.length; i < len; i++) {
					Ext.EventManager.purgeElement(el.childNodes[i], recurse, eventName);
				}
			}
		},

		_unload: function () {
			var el;
			for (el in Ext.elCache) {
				Ext.EventManager.removeAll(el);
			}
			delete Ext.elCache;
			delete Ext.Element._flyweights;

			// Abort any outstanding Ajax requests
			var c,
                conn,
                tid,
                ajax = Ext.lib.Ajax;
			(typeof ajax.conn == 'object') ? conn = ajax.conn : conn = {};
			for (tid in conn) {
				c = conn[tid];
				if (c) {
					ajax.abort({ conn: c, tId: tid });
				}
			}
		},
		/**
		* Adds a listener to be notified when the document is ready (before onload and before images are loaded). Can be
		* accessed shorthanded as Ext.onReady().
		* @param {Function} fn The method the event invokes.
		* @param {Object} scope (optional) The scope (<code>this</code> reference) in which the handler function executes. Defaults to the browser window.
		* @param {boolean} options (optional) Options object as passed to {@link Ext.Element#addListener}. It is recommended that the options
		* <code>{single: true}</code> be used so that the handler is removed on first invocation.
		*/
		onDocumentReady: function (fn, scope, options) {
			if (Ext.isReady) { // if it already fired or document.body is present
				docReadyEvent || (docReadyEvent = new Ext.util.Event());
				docReadyEvent.addListener(fn, scope, options);
				docReadyEvent.fire();
				docReadyEvent.listeners = [];
			} else {
				if (!docReadyEvent) {
					initDocReady();
				}
				options = options || {};
				options.delay = options.delay || 1;
				docReadyEvent.addListener(fn, scope, options);
			}
		},

		/**
		* Forces a document ready state transition for the framework.  Used when Ext is loaded
		* into a DOM structure AFTER initial page load (Google API or other dynamic load scenario.
		* Any pending 'onDocumentReady' handlers will be fired (if not already handled).
		*/
		fireDocReady: fireDocReady
	};
	/**
	* Appends an event handler to an element.  Shorthand for {@link #addListener}.
	* @param {String/HTMLElement} el The html element or id to assign the event handler to
	* @param {String} eventName The name of the event to listen for.
	* @param {Function} handler The handler function the event invokes.
	* @param {Object} scope (optional) (<code>this</code> reference) in which the handler function executes. <b>Defaults to the Element</b>.
	* @param {Object} options (optional) An object containing standard {@link #addListener} options
	* @member Ext.EventManager
	* @method on
	*/
	pub.on = pub.addListener;
	/**
	* Removes an event handler from an element.  Shorthand for {@link #removeListener}.
	* @param {String/HTMLElement} el The id or html element from which to remove the listener.
	* @param {String} eventName The name of the event.
	* @param {Function} fn The handler function to remove. <b>This must be a reference to the function passed into the {@link #on} call.</b>
	* @param {Object} scope If a scope (<b><code>this</code></b> reference) was specified when the listener was added,
	* then this must refer to the same object.
	* @member Ext.EventManager
	* @method un
	*/
	pub.un = pub.removeListener;

	pub.stoppedMouseDownEvent = new Ext.util.Event();
	return pub;
} ();
/**
* Adds a listener to be notified when the document is ready (before onload and before images are loaded). Shorthand of {@link Ext.EventManager#onDocumentReady}.
* @param {Function} fn The method the event invokes.
* @param {Object} scope (optional) The scope (<code>this</code> reference) in which the handler function executes. Defaults to the browser window.
* @param {boolean} options (optional) Options object as passed to {@link Ext.Element#addListener}. It is recommended that the options
* <code>{single: true}</code> be used so that the handler is removed on first invocation.
* @member Ext
* @method onReady
*/
Ext.onReady = Ext.EventManager.onDocumentReady;


//Initialize doc classes
(function () {

	var initExtCss = function () {
		// find the body element
		var bd = document.body || document.getElementsByTagName('body')[0];
		if (!bd) { return false; }
		var cls = [' ',
                Ext.isIE ? "ext-ie " + (Ext.isIE6 ? 'ext-ie6' : (Ext.isIE7 ? 'ext-ie7' : 'ext-ie8'))
                : Ext.isGecko ? "ext-gecko " + (Ext.isGecko2 ? 'ext-gecko2' : 'ext-gecko3')
                : Ext.isOpera ? "ext-opera"
                : Ext.isWebKit ? "ext-webkit" : ""];

		if (Ext.isSafari) {
			cls.push("ext-safari " + (Ext.isSafari2 ? 'ext-safari2' : (Ext.isSafari3 ? 'ext-safari3' : 'ext-safari4')));
		} else if (Ext.isChrome) {
			cls.push("ext-chrome");
		}

		if (Ext.isMac) {
			cls.push("ext-mac");
		}
		if (Ext.isLinux) {
			cls.push("ext-linux");
		}

		if (Ext.isStrict || Ext.isBorderBox) { // add to the parent to allow for selectors like ".ext-strict .ext-ie"
			var p = bd.parentNode;
			if (p) {
				p.className += Ext.isStrict ? ' ext-strict' : ' ext-border-box';
			}
		}
		bd.className += cls.join(' ');
		return true;
	}

	if (!initExtCss()) {
		Ext.onReady(initExtCss);
	}
})();


/**
* @class Ext.EventObject
* Just as {@link Ext.Element} wraps around a native DOM node, Ext.EventObject
* wraps the browser's native event-object normalizing cross-browser differences,
* such as which mouse button is clicked, keys pressed, mechanisms to stop
* event-propagation along with a method to prevent default actions from taking place.
* <p>For example:</p>
* <pre><code>
function handleClick(e, t){ // e is not a standard event object, it is a Ext.EventObject
e.preventDefault();
var target = e.getTarget(); // same as t (the target HTMLElement)
...
}
var myDiv = {@link Ext#get Ext.get}("myDiv");  // get reference to an {@link Ext.Element}
myDiv.on(         // 'on' is shorthand for addListener
"click",      // perform an action on click of myDiv
handleClick   // reference to the action handler
);
// other methods to do the same:
Ext.EventManager.on("myDiv", 'click', handleClick);
Ext.EventManager.addListener("myDiv", 'click', handleClick);
</code></pre>
* @singleton
*/
Ext.EventObject = function () {
	var E = Ext.lib.Event,
	// safari keypress events for special keys return bad keycodes
        safariKeys = {
        	3: 13, // enter
        	63234: 37, // left
        	63235: 39, // right
        	63232: 38, // up
        	63233: 40, // down
        	63276: 33, // page up
        	63277: 34, // page down
        	63272: 46, // delete
        	63273: 36, // home
        	63275: 35  // end
        },
	// normalize button clicks
        btnMap = Ext.isIE ? { 1: 0, 4: 1, 2: 2} :
                (Ext.isWebKit ? { 1: 0, 2: 1, 3: 2} : { 0: 0, 1: 1, 2: 2 });

	Ext.EventObjectImpl = function (e) {
		if (e) {
			this.setEvent(e.browserEvent || e);
		}
	};

	Ext.EventObjectImpl.prototype = {
		/** @private */
		setEvent: function (e) {
			var me = this;
			if (e == me || (e && e.browserEvent)) { // already wrapped
				return e;
			}
			me.browserEvent = e;
			if (e) {
				// normalize buttons
				me.button = e.button ? btnMap[e.button] : (e.which ? e.which - 1 : -1);
				if (e.type == 'click' && me.button == -1) {
					me.button = 0;
				}
				me.type = e.type;
				me.shiftKey = e.shiftKey;
				// mac metaKey behaves like ctrlKey
				me.ctrlKey = e.ctrlKey || e.metaKey || false;
				me.altKey = e.altKey;
				// in getKey these will be normalized for the mac
				me.keyCode = e.keyCode;
				me.charCode = e.charCode;
				// cache the target for the delayed and or buffered events
				me.target = E.getTarget(e);
				// same for XY
				me.xy = E.getXY(e);
			} else {
				me.button = -1;
				me.shiftKey = false;
				me.ctrlKey = false;
				me.altKey = false;
				me.keyCode = 0;
				me.charCode = 0;
				me.target = null;
				me.xy = [0, 0];
			}
			return me;
		},

		/**
		* Stop the event (preventDefault and stopPropagation)
		*/
		stopEvent: function () {
			var me = this;
			if (me.browserEvent) {
				if (me.browserEvent.type == 'mousedown') {
					Ext.EventManager.stoppedMouseDownEvent.fire(me);
				}
				E.stopEvent(me.browserEvent);
			}
		},

		/**
		* Prevents the browsers default handling of the event.
		*/
		preventDefault: function () {
			if (this.browserEvent) {
				E.preventDefault(this.browserEvent);
			}
		},

		/**
		* Cancels bubbling of the event.
		*/
		stopPropagation: function () {
			var me = this;
			if (me.browserEvent) {
				if (me.browserEvent.type == 'mousedown') {
					Ext.EventManager.stoppedMouseDownEvent.fire(me);
				}
				E.stopPropagation(me.browserEvent);
			}
		},

		/**
		* Gets the character code for the event.
		* @return {Number}
		*/
		getCharCode: function () {
			return this.charCode || this.keyCode;
		},

		/**
		* Returns a normalized keyCode for the event.
		* @return {Number} The key code
		*/
		getKey: function () {
			return this.normalizeKey(this.keyCode || this.charCode)
		},

		// private
		normalizeKey: function (k) {
			return Ext.isSafari ? (safariKeys[k] || k) : k;
		},

		/**
		* Gets the x coordinate of the event.
		* @return {Number}
		*/
		getPageX: function () {
			return this.xy[0];
		},

		/**
		* Gets the y coordinate of the event.
		* @return {Number}
		*/
		getPageY: function () {
			return this.xy[1];
		},

		/**
		* Gets the page coordinates of the event.
		* @return {Array} The xy values like [x, y]
		*/
		getXY: function () {
			return this.xy;
		},

		/**
		* Gets the target for the event.
		* @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target
		* @param {Number/Mixed} maxDepth (optional) The max depth to
		search as a number or element (defaults to 10 || document.body)
		* @param {Boolean} returnEl (optional) True to return a Ext.Element object instead of DOM node
		* @return {HTMLelement}
		*/
		getTarget: function (selector, maxDepth, returnEl) {
			return selector ? Ext.fly(this.target).findParent(selector, maxDepth, returnEl) : (returnEl ? Ext.get(this.target) : this.target);
		},

		/**
		* Gets the related target.
		* @return {HTMLElement}
		*/
		getRelatedTarget: function () {
			return this.browserEvent ? E.getRelatedTarget(this.browserEvent) : null;
		},

		/**
		* Normalizes mouse wheel delta across browsers
		* @return {Number} The delta
		*/
		getWheelDelta: function () {
			var e = this.browserEvent;
			var delta = 0;
			if (e.wheelDelta) { /* IE/Opera. */
				delta = e.wheelDelta / 120;
			} else if (e.detail) { /* Mozilla case. */
				delta = -e.detail / 3;
			}
			return delta;
		},

		/**
		* 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.
		* Example usage:<pre><code>
		// Handle click on any child of an element
		Ext.getBody().on('click', function(e){
		if(e.within('some-el')){
		alert('Clicked on a child of some-el!');
		}
		});

		// Handle click directly on an element, ignoring clicks on child nodes
		Ext.getBody().on('click', function(e,t){
		if((t.id == 'some-el') && !e.within(t, true)){
		alert('Clicked directly on some-el!');
		}
		});
		</code></pre>
		* @param {Mixed} el The id, DOM element or Ext.Element to check
		* @param {Boolean} related (optional) true to test if the related target is within el instead of the target
		* @param {Boolean} allowEl {optional} true to also check if the passed element is the target or related target
		* @return {Boolean}
		*/
		within: function (el, related, allowEl) {
			if (el) {
				var t = this[related ? "getRelatedTarget" : "getTarget"]();
				return t && ((allowEl ? (t == Ext.getDom(el)) : false) || Ext.fly(el).contains(t));
			}
			return false;
		}
	};

	return new Ext.EventObjectImpl();
} ();
/**
* @class Ext.EventManager
*/
Ext.apply(Ext.EventManager, function () {
	var resizeEvent,
       resizeTask,
       textEvent,
       textSize,
       D = Ext.lib.Dom,
       propRe = /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/,
       curWidth = 0,
       curHeight = 0,
	// note 1: IE fires ONLY the keydown event on specialkey autorepeat
	// note 2: Safari < 3.1, Gecko (Mac/Linux) & Opera fire only the keypress event on specialkey autorepeat
	// (research done by @Jan Wolter at http://unixpapa.com/js/key.html)
       useKeydown = Ext.isWebKit ?
                   Ext.num(navigator.userAgent.match(/AppleWebKit\/(\d+)/)[1]) >= 525 :
                   !((Ext.isGecko && !Ext.isWindows) || Ext.isOpera);

	return {
		// private
		doResizeEvent: function () {
			var h = D.getViewHeight(),
               w = D.getViewWidth();

			//whacky problem in IE where the resize event will fire even though the w/h are the same.
			if (curHeight != h || curWidth != w) {
				resizeEvent.fire(curWidth = w, curHeight = h);
			}
		},

		/**
		* Adds a listener to be notified when the browser window is resized and provides resize event buffering (100 milliseconds),
		* passes new viewport width and height to handlers.
		* @param {Function} fn      The handler function the window resize event invokes.
		* @param {Object}   scope   The scope (<code>this</code> reference) in which the handler function executes. Defaults to the browser window.
		* @param {boolean}  options Options object as passed to {@link Ext.Element#addListener}
		*/
		onWindowResize: function (fn, scope, options) {
			if (!resizeEvent) {
				resizeEvent = new Ext.util.Event();
				resizeTask = new Ext.util.DelayedTask(this.doResizeEvent);
				Ext.EventManager.on(window, "resize", this.fireWindowResize, this);
			}
			resizeEvent.addListener(fn, scope, options);
		},

		// exposed only to allow manual firing
		fireWindowResize: function () {
			if (resizeEvent) {
				resizeTask.delay(100);
			}
		},

		/**
		* Adds a listener to be notified when the user changes the active text size. Handler gets called with 2 params, the old size and the new size.
		* @param {Function} fn      The function the event invokes.
		* @param {Object}   scope   The scope (<code>this</code> reference) in which the handler function executes. Defaults to the browser window.
		* @param {boolean}  options Options object as passed to {@link Ext.Element#addListener}
		*/
		onTextResize: function (fn, scope, options) {
			if (!textEvent) {
				textEvent = new Ext.util.Event();
				var textEl = new Ext.Element(document.createElement('div'));
				textEl.dom.className = 'x-text-resize';
				textEl.dom.innerHTML = 'X';
				textEl.appendTo(document.body);
				textSize = textEl.dom.offsetHeight;
				setInterval(function () {
					if (textEl.dom.offsetHeight != textSize) {
						textEvent.fire(textSize, textSize = textEl.dom.offsetHeight);
					}
				}, this.textResizeInterval);
			}
			textEvent.addListener(fn, scope, options);
		},

		/**
		* Removes the passed window resize listener.
		* @param {Function} fn        The method the event invokes
		* @param {Object}   scope    The scope of handler
		*/
		removeResizeListener: function (fn, scope) {
			if (resizeEvent) {
				resizeEvent.removeListener(fn, scope);
			}
		},

		// private
		fireResize: function () {
			if (resizeEvent) {
				resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
			}
		},

		/**
		* The frequency, in milliseconds, to check for text resize events (defaults to 50)
		*/
		textResizeInterval: 50,

		/**
		* Url used for onDocumentReady with using SSL (defaults to Ext.SSL_SECURE_URL)
		*/
		ieDeferSrc: false,

		// protected for use inside the framework
		// detects whether we should use keydown or keypress based on the browser.
		useKeydown: useKeydown
	};
} ());

Ext.EventManager.on = Ext.EventManager.addListener;


Ext.apply(Ext.EventObjectImpl.prototype, {
	/** Key constant @type Number */
	BACKSPACE: 8,
	/** Key constant @type Number */
	TAB: 9,
	/** Key constant @type Number */
	NUM_CENTER: 12,
	/** Key constant @type Number */
	ENTER: 13,
	/** Key constant @type Number */
	RETURN: 13,
	/** Key constant @type Number */
	SHIFT: 16,
	/** Key constant @type Number */
	CTRL: 17,
	CONTROL: 17, // legacy
	/** Key constant @type Number */
	ALT: 18,
	/** Key constant @type Number */
	PAUSE: 19,
	/** Key constant @type Number */
	CAPS_LOCK: 20,
	/** Key constant @type Number */
	ESC: 27,
	/** Key constant @type Number */
	SPACE: 32,
	/** Key constant @type Number */
	PAGE_UP: 33,
	PAGEUP: 33, // legacy
	/** Key constant @type Number */
	PAGE_DOWN: 34,
	PAGEDOWN: 34, // legacy
	/** Key constant @type Number */
	END: 35,
	/** Key constant @type Number */
	HOME: 36,
	/** Key constant @type Number */
	LEFT: 37,
	/** Key constant @type Number */
	UP: 38,
	/** Key constant @type Number */
	RIGHT: 39,
	/** Key constant @type Number */
	DOWN: 40,
	/** Key constant @type Number */
	PRINT_SCREEN: 44,
	/** Key constant @type Number */
	INSERT: 45,
	/** Key constant @type Number */
	DELETE: 46,
	/** Key constant @type Number */
	ZERO: 48,
	/** Key constant @type Number */
	ONE: 49,
	/** Key constant @type Number */
	TWO: 50,
	/** Key constant @type Number */
	THREE: 51,
	/** Key constant @type Number */
	FOUR: 52,
	/** Key constant @type Number */
	FIVE: 53,
	/** Key constant @type Number */
	SIX: 54,
	/** Key constant @type Number */
	SEVEN: 55,
	/** Key constant @type Number */
	EIGHT: 56,
	/** Key constant @type Number */
	NINE: 57,
	/** Key constant @type Number */
	A: 65,
	/** Key constant @type Number */
	B: 66,
	/** Key constant @type Number */
	C: 67,
	/** Key constant @type Number */
	D: 68,
	/** Key constant @type Number */
	E: 69,
	/** Key constant @type Number */
	F: 70,
	/** Key constant @type Number */
	G: 71,
	/** Key constant @type Number */
	H: 72,
	/** Key constant @type Number */
	I: 73,
	/** Key constant @type Number */
	J: 74,
	/** Key constant @type Number */
	K: 75,
	/** Key constant @type Number */
	L: 76,
	/** Key constant @type Number */
	M: 77,
	/** Key constant @type Number */
	N: 78,
	/** Key constant @type Number */
	O: 79,
	/** Key constant @type Number */
	P: 80,
	/** Key constant @type Number */
	Q: 81,
	/** Key constant @type Number */
	R: 82,
	/** Key constant @type Number */
	S: 83,
	/** Key constant @type Number */
	T: 84,
	/** Key constant @type Number */
	U: 85,
	/** Key constant @type Number */
	V: 86,
	/** Key constant @type Number */
	W: 87,
	/** Key constant @type Number */
	X: 88,
	/** Key constant @type Number */
	Y: 89,
	/** Key constant @type Number */
	Z: 90,
	/** Key constant @type Number */
	CONTEXT_MENU: 93,
	/** Key constant @type Number */
	NUM_ZERO: 96,
	/** Key constant @type Number */
	NUM_ONE: 97,
	/** Key constant @type Number */
	NUM_TWO: 98,
	/** Key constant @type Number */
	NUM_THREE: 99,
	/** Key constant @type Number */
	NUM_FOUR: 100,
	/** Key constant @type Number */
	NUM_FIVE: 101,
	/** Key constant @type Number */
	NUM_SIX: 102,
	/** Key constant @type Number */
	NUM_SEVEN: 103,
	/** Key constant @type Number */
	NUM_EIGHT: 104,
	/** Key constant @type Number */
	NUM_NINE: 105,
	/** Key constant @type Number */
	NUM_MULTIPLY: 106,
	/** Key constant @type Number */
	NUM_PLUS: 107,
	/** Key constant @type Number */
	NUM_MINUS: 109,
	/** Key constant @type Number */
	NUM_PERIOD: 110,
	/** Key constant @type Number */
	NUM_DIVISION: 111,
	/** Key constant @type Number */
	F1: 112,
	/** Key constant @type Number */
	F2: 113,
	/** Key constant @type Number */
	F3: 114,
	/** Key constant @type Number */
	F4: 115,
	/** Key constant @type Number */
	F5: 116,
	/** Key constant @type Number */
	F6: 117,
	/** Key constant @type Number */
	F7: 118,
	/** Key constant @type Number */
	F8: 119,
	/** Key constant @type Number */
	F9: 120,
	/** Key constant @type Number */
	F10: 121,
	/** Key constant @type Number */
	F11: 122,
	/** Key constant @type Number */
	F12: 123,

	/** @private */
	isNavKeyPress: function () {
		var me = this,
           k = this.normalizeKey(me.keyCode);
		return (k >= 33 && k <= 40) ||  // Page Up/Down, End, Home, Left, Up, Right, Down
       k == me.RETURN ||
       k == me.TAB ||
       k == me.ESC;
	},

	isSpecialKey: function () {
		var k = this.normalizeKey(this.keyCode);
		return (this.type == 'keypress' && this.ctrlKey) ||
       this.isNavKeyPress() ||
       (k == this.BACKSPACE) || // Backspace
       (k >= 16 && k <= 20) || // Shift, Ctrl, Alt, Pause, Caps Lock
       (k >= 44 && k <= 46);   // Print Screen, Insert, Delete
	},

	getPoint: function () {
		return new Ext.lib.Point(this.xy[0], this.xy[1]);
	},

	/**
	* Returns true if the control, meta, shift or alt key was pressed during this event.
	* @return {Boolean}
	*/
	hasModifier: function () {
		return ((this.ctrlKey || this.altKey) || this.shiftKey);
	}
}); /**
 * @class Ext.Element
 * <p>Encapsulates a DOM element, adding simple DOM manipulation facilities, normalizing for browser differences.</p>
 * <p>All instances of this class inherit the methods of {@link Ext.Fx} making visual effects easily available to all DOM elements.</p>
 * <p>Note that the events documented in this class are not Ext events, they encapsulate browser events. To
 * access the underlying browser event, see {@link Ext.EventObject#browserEvent}. Some older
 * browsers may not support the full range of events. Which events are supported is beyond the control of ExtJs.</p>
 * Usage:<br>
<pre><code>
// by id
var el = Ext.get("my-div");

// by DOM element reference
var el = Ext.get(myDivElement);
</code></pre>
 * <b>Animations</b><br />
 * <p>When an element is manipulated, by default there is no animation.</p>
 * <pre><code>
var el = Ext.get("my-div");

// no animation
el.setWidth(100);
 * </code></pre>
 * <p>Many of the functions for manipulating an element have an optional "animate" parameter.  This
 * parameter can be specified as boolean (<tt>true</tt>) for default animation effects.</p>
 * <pre><code>
// default animation
el.setWidth(100, true);
 * </code></pre>
 *
 * <p>To configure the effects, an object literal with animation options to use as the Element animation
 * configuration object can also be specified. Note that the supported Element animation configuration
 * options are a subset of the {@link Ext.Fx} animation options specific to Fx effects.  The supported
 * Element animation configuration options are:</p>
<pre>
Option    Default   Description
--------- --------  ---------------------------------------------
{@link Ext.Fx#duration duration}  .35       The duration of the animation in seconds
{@link Ext.Fx#easing easing}    easeOut   The easing method
{@link Ext.Fx#callback callback}  none      A function to execute when the anim completes
{@link Ext.Fx#scope scope}     this      The scope (this) of the callback function
</pre>
 *
 * <pre><code>
// Element animation options object
var opt = {
    {@link Ext.Fx#duration duration}: 1,
    {@link Ext.Fx#easing easing}: 'elasticIn',
    {@link Ext.Fx#callback callback}: this.foo,
    {@link Ext.Fx#scope scope}: this
};
// animation with some options set
el.setWidth(100, opt);
 * </code></pre>
 * <p>The Element animation object being used for the animation will be set on the options
 * object as "anim", which allows you to stop or manipulate the animation. Here is an example:</p>
 * <pre><code>
// using the "anim" property to get the Anim object
if(opt.anim.isAnimated()){
    opt.anim.stop();
}
 * </code></pre>
 * <p>Also see the <tt>{@link #animate}</tt> method for another animation technique.</p>
 * <p><b> Composite (Collections of) Elements</b></p>
 * <p>For working with collections of Elements, see {@link Ext.CompositeElement}</p>
 * @constructor Create a new Element directly.
 * @param {String/HTMLElement} element
 * @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).
 */
(function () {
	var DOC = document;

	Ext.Element = function (element, forceNew) {
		var dom = typeof element == "string" ?
              DOC.getElementById(element) : element,
        id;

		if (!dom) return null;

		id = dom.id;

		if (!forceNew && id && Ext.elCache[id]) { // element object already exists
			return Ext.elCache[id].el;
		}

		/**
		* The DOM element
		* @type HTMLElement
		*/
		this.dom = dom;

		/**
		* The DOM element ID
		* @type String
		*/
		this.id = id || Ext.id(dom);
	};

	var D = Ext.lib.Dom,
    DH = Ext.DomHelper,
    E = Ext.lib.Event,
    A = Ext.lib.Anim,
    El = Ext.Element,
    EC = Ext.elCache;

	El.prototype = {
		/**
		* Sets the passed attributes as attributes of this element (a style attribute can be a string, object or function)
		* @param {Object} o The object with the attributes
		* @param {Boolean} useSet (optional) false to override the default setAttribute to use expandos.
		* @return {Ext.Element} this
		*/
		set: function (o, useSet) {
			var el = this.dom,
            attr,
            val,
            useSet = (useSet !== false) && !!el.setAttribute;

			for (attr in o) {
				if (o.hasOwnProperty(attr)) {
					val = o[attr];
					if (attr == 'style') {
						DH.applyStyles(el, val);
					} else if (attr == 'cls') {
						el.className = val;
					} else if (useSet) {
						el.setAttribute(attr, val);
					} else {
						el[attr] = val;
					}
				}
			}
			return this;
		},

		//  Mouse events
		/**
		* @event click
		* Fires when a mouse click is detected within the element.
		* @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
		* @param {HtmlElement} t The target of the event.
		* @param {Object} o The options configuration passed to the {@link #addListener} call.
		*/
		/**
		* @event contextmenu
		* Fires when a right click is detected within the element.
		* @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
		* @param {HtmlElement} t The target of the event.
		* @param {Object} o The options configuration passed to the {@link #addListener} call.
		*/
		/**
		* @event dblclick
		* Fires when a mouse double click is detected within the element.
		* @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
		* @param {HtmlElement} t The target of the event.
		* @param {Object} o The options configuration passed to the {@link #addListener} call.
		*/
		/**
		* @event mousedown
		* Fires when a mousedown is detected within the element.
		* @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
		* @param {HtmlElement} t The target of the event.
		* @param {Object} o The options configuration passed to the {@link #addListener} call.
		*/
		/**
		* @event mouseup
		* Fires when a mouseup is detected within the element.
		* @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
		* @param {HtmlElement} t The target of the event.
		* @param {Object} o The options configuration passed to the {@link #addListener} call.
		*/
		/**
		* @event mouseover
		* Fires when a mouseover is detected within the element.
		* @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
		* @param {HtmlElement} t The target of the event.
		* @param {Object} o The options configuration passed to the {@link #addListener} call.
		*/
		/**
		* @event mousemove
		* Fires when a mousemove is detected with the element.
		* @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
		* @param {HtmlElement} t The target of the event.
		* @param {Object} o The options configuration passed to the {@link #addListener} call.
		*/
		/**
		* @event mouseout
		* Fires when a mouseout is detected with the element.
		* @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
		* @param {HtmlElement} t The target of the event.
		* @param {Object} o The options configuration passed to the {@link #addListener} call.
		*/
		/**
		* @event mouseenter
		* Fires when the mouse enters the element.
		* @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
		* @param {HtmlElement} t The target of the event.
		* @param {Object} o The options configuration passed to the {@link #addListener} call.
		*/
		/**
		* @event mouseleave
		* Fires when the mouse leaves the element.
		* @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
		* @param {HtmlElement} t The target of the event.
		* @param {Object} o The options configuration passed to the {@link #addListener} call.
		*/

		//  Keyboard events
		/**
		* @event keypress
		* Fires when a keypress is detected within the element.
		* @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
		* @param {HtmlElement} t The target of the event.
		* @param {Object} o The options configuration passed to the {@link #addListener} call.
		*/
		/**
		* @event keydown
		* Fires when a keydown is detected within the element.
		* @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
		* @param {HtmlElement} t The target of the event.
		* @param {Object} o The options configuration passed to the {@link #addListener} call.
		*/
		/**
		* @event keyup
		* Fires when a keyup is detected within the element.
		* @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
		* @param {HtmlElement} t The target of the event.
		* @param {Object} o The options configuration passed to the {@link #addListener} call.
		*/


		//  HTML frame/object events
		/**
		* @event load
		* Fires when the user agent finishes loading all content within the element. Only supported by window, frames, objects and images.
		* @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
		* @param {HtmlElement} t The target of the event.
		* @param {Object} o The options configuration passed to the {@link #addListener} call.
		*/
		/**
		* @event unload
		* 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.
		* @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
		* @param {HtmlElement} t The target of the event.
		* @param {Object} o The options configuration passed to the {@link #addListener} call.
		*/
		/**
		* @event abort
		* Fires when an object/image is stopped from loading before completely loaded.
		* @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
		* @param {HtmlElement} t The target of the event.
		* @param {Object} o The options configuration passed to the {@link #addListener} call.
		*/
		/**
		* @event error
		* Fires when an object/image/frame cannot be loaded properly.
		* @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
		* @param {HtmlElement} t The target of the event.
		* @param {Object} o The options configuration passed to the {@link #addListener} call.
		*/
		/**
		* @event resize
		* Fires when a document view is resized.
		* @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
		* @param {HtmlElement} t The target of the event.
		* @param {Object} o The options configuration passed to the {@link #addListener} call.
		*/
		/**
		* @event scroll
		* Fires when a document view is scrolled.
		* @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
		* @param {HtmlElement} t The target of the event.
		* @param {Object} o The options configuration passed to the {@link #addListener} call.
		*/

		//  Form events
		/**
		* @event select
		* Fires when a user selects some text in a text field, including input and textarea.
		* @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
		* @param {HtmlElement} t The target of the event.
		* @param {Object} o The options configuration passed to the {@link #addListener} call.
		*/
		/**
		* @event change
		* Fires when a control loses the input focus and its value has been modified since gaining focus.
		* @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
		* @param {HtmlElement} t The target of the event.
		* @param {Object} o The options configuration passed to the {@link #addListener} call.
		*/
		/**
		* @event submit
		* Fires when a form is submitted.
		* @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
		* @param {HtmlElement} t The target of the event.
		* @param {Object} o The options configuration passed to the {@link #addListener} call.
		*/
		/**
		* @event reset
		* Fires when a form is reset.
		* @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
		* @param {HtmlElement} t The target of the event.
		* @param {Object} o The options configuration passed to the {@link #addListener} call.
		*/
		/**
		* @event focus
		* Fires when an element receives focus either via the pointing device or by tab navigation.
		* @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
		* @param {HtmlElement} t The target of the event.
		* @param {Object} o The options configuration passed to the {@link #addListener} call.
		*/
		/**
		* @event blur
		* Fires when an element loses focus either via the pointing device or by tabbing navigation.
		* @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
		* @param {HtmlElement} t The target of the event.
		* @param {Object} o The options configuration passed to the {@link #addListener} call.
		*/

		//  User Interface events
		/**
		* @event DOMFocusIn
		* Where supported. Similar to HTML focus event, but can be applied to any focusable element.
		* @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
		* @param {HtmlElement} t The target of the event.
		* @param {Object} o The options configuration passed to the {@link #addListener} call.
		*/
		/**
		* @event DOMFocusOut
		* Where supported. Similar to HTML blur event, but can be applied to any focusable element.
		* @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
		* @param {HtmlElement} t The target of the event.
		* @param {Object} o The options configuration passed to the {@link #addListener} call.
		*/
		/**
		* @event DOMActivate
		* Where supported. Fires when an element is activated, for instance, through a mouse click or a keypress.
		* @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
		* @param {HtmlElement} t The target of the event.
		* @param {Object} o The options configuration passed to the {@link #addListener} call.
		*/

		//  DOM Mutation events
		/**
		* @event DOMSubtreeModified
		* Where supported. Fires when the subtree is modified.
		* @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
		* @param {HtmlElement} t The target of the event.
		* @param {Object} o The options configuration passed to the {@link #addListener} call.
		*/
		/**
		* @event DOMNodeInserted
		* Where supported. Fires when a node has been added as a child of another node.
		* @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
		* @param {HtmlElement} t The target of the event.
		* @param {Object} o The options configuration passed to the {@link #addListener} call.
		*/
		/**
		* @event DOMNodeRemoved
		* Where supported. Fires when a descendant node of the element is removed.
		* @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
		* @param {HtmlElement} t The target of the event.
		* @param {Object} o The options configuration passed to the {@link #addListener} call.
		*/
		/**
		* @event DOMNodeRemovedFromDocument
		* Where supported. Fires when a node is being removed from a document.
		* @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
		* @param {HtmlElement} t The target of the event.
		* @param {Object} o The options configuration passed to the {@link #addListener} call.
		*/
		/**
		* @event DOMNodeInsertedIntoDocument
		* Where supported. Fires when a node is being inserted into a document.
		* @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
		* @param {HtmlElement} t The target of the event.
		* @param {Object} o The options configuration passed to the {@link #addListener} call.
		*/
		/**
		* @event DOMAttrModified
		* Where supported. Fires when an attribute has been modified.
		* @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
		* @param {HtmlElement} t The target of the event.
		* @param {Object} o The options configuration passed to the {@link #addListener} call.
		*/
		/**
		* @event DOMCharacterDataModified
		* Where supported. Fires when the character data has been modified.
		* @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event.
		* @param {HtmlElement} t The target of the event.
		* @param {Object} o The options configuration passed to the {@link #addListener} call.
		*/

		/**
		* The default unit to append to CSS values where a unit isn't provided (defaults to px).
		* @type String
		*/
		defaultUnit: "px",

		/**
		* Returns true if this element matches the passed simple selector (e.g. div.some-class or span:first-child)
		* @param {String} selector The simple selector to test
		* @return {Boolean} True if this element matches the selector, else false
		*/
		is: function (simpleSelector) {
			return Ext.DomQuery.is(this.dom, simpleSelector);
		},

		/**
		* Tries to focus the element. Any exceptions are caught and ignored.
		* @param {Number} defer (optional) Milliseconds to defer the focus
		* @return {Ext.Element} this
		*/
		focus: function (defer, /* private */dom) {
			var me = this,
            dom = dom || me.dom;
			try {
				if (Number(defer)) {
					me.focus.defer(defer, null, [null, dom]);
				} else {
					dom.focus();
				}
			} catch (e) { }
			return me;
		},

		/**
		* Tries to blur the element. Any exceptions are caught and ignored.
		* @return {Ext.Element} this
		*/
		blur: function () {
			try {
				this.dom.blur();
			} catch (e) { }
			return this;
		},

		/**
		* Returns the value of the "value" attribute
		* @param {Boolean} asNumber true to parse the value as a number
		* @return {String/Number}
		*/
		getValue: function (asNumber) {
			var val = this.dom.value;
			return asNumber ? parseInt(val, 10) : val;
		},

		/**
		* Appends an event handler to this element.  The shorthand version {@link #on} is equivalent.
		* @param {String} eventName The name of event to handle.
		* @param {Function} fn The handler function the event invokes. This function is passed
		* the following parameters:<ul>
		* <li><b>evt</b> : EventObject<div class="sub-desc">The {@link Ext.EventObject EventObject} describing the event.</div></li>
		* <li><b>el</b> : HtmlElement<div class="sub-desc">The DOM element which was the target of the event.
		* Note that this may be filtered by using the <tt>delegate</tt> option.</div></li>
		* <li><b>o</b> : Object<div class="sub-desc">The options object from the addListener call.</div></li>
		* </ul>
		* @param {Object} scope (optional) The scope (<code><b>this</b></code> reference) in which the handler function is executed.
		* <b>If omitted, defaults to this Element.</b>.
		* @param {Object} options (optional) An object containing handler configuration properties.
		* This may contain any of the following properties:<ul>
		* <li><b>scope</b> Object : <div class="sub-desc">The scope (<code><b>this</b></code> reference) in which the handler function is executed.
		* <b>If omitted, defaults to this Element.</b></div></li>
		* <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>
		* <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>
		* <li><b>preventDefault</b> Boolean: <div class="sub-desc">True to prevent the default action</div></li>
		* <li><b>stopPropagation</b> Boolean: <div class="sub-desc">True to prevent event propagation</div></li>
		* <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>
		* <li><b>target</b> Ext.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>
		* <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>
		* <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>
		* <li><b>buffer</b> Number: <div class="sub-desc">Causes the handler to be scheduled to run in an {@link Ext.util.DelayedTask} delayed
		* by the specified number of milliseconds. If the event fires again within that time, the original
		* handler is <em>not</em> invoked, but the new handler is scheduled in its place.</div></li>
		* </ul><br>
		* <p>
		* <b>Combining Options</b><br>
		* In the following examples, the shorthand form {@link #on} is used rather than the more verbose
		* addListener.  The two are equivalent.  Using the options argument, it is possible to combine different
		* types of listeners:<br>
		* <br>
		* A delayed, one-time listener that auto stops the event and adds a custom argument (forumId) to the
		* options object. The options object is available as the third parameter in the handler function.<div style="margin: 5px 20px 20px;">
		* Code:<pre><code>
		el.on('click', this.onClick, this, {
		single: true,
		delay: 100,
		stopEvent : true,
		forumId: 4
		});</code></pre></p>
		* <p>
		* <b>Attaching multiple handlers in 1 call</b><br>
		* The method also allows for a single argument to be passed which is a config object containing properties
		* which specify multiple handlers.</p>
		* <p>
		* Code:<pre><code>
		el.on({
		'click' : {
		fn: this.onClick,
		scope: this,
		delay: 100
		},
		'mouseover' : {
		fn: this.onMouseOver,
		scope: this
		},
		'mouseout' : {
		fn: this.onMouseOut,
		scope: this
		}
		});</code></pre>
		* <p>
		* Or a shorthand syntax:<br>
		* Code:<pre><code></p>
		el.on({
		'click' : this.onClick,
		'mouseover' : this.onMouseOver,
		'mouseout' : this.onMouseOut,
		scope: this
		});
		* </code></pre></p>
		* <p><b>delegate</b></p>
		* <p>This is a configuration option that you can pass along when registering a handler for
		* an event to assist with event delegation. Event delegation is a technique that is used to
		* reduce memory consumption and prevent exposure to memory-leaks. By registering an event
		* for a container element as opposed to each element within a container. By setting this
		* configuration option to a simple selector, the target element will be filtered to look for
		* a descendant of the target.
		* For example:<pre><code>
		// using this markup:
		&lt;div id='elId'>
		&lt;p id='p1'>paragraph one&lt;/p>
		&lt;p id='p2' class='clickable'>paragraph two&lt;/p>
		&lt;p id='p3'>paragraph three&lt;/p>
		&lt;/div>
		// utilize event delegation to registering just one handler on the container element:
		el = Ext.get('elId');
		el.on(
		'click',
		function(e,t) {
		// handle click
		console.info(t.id); // 'p2'
		},
		this,
		{
		// filter the target element to be a descendant with the class 'clickable'
		delegate: '.clickable'
		}
		);
		* </code></pre></p>
		* @return {Ext.Element} this
		*/
		addListener: function (eventName, fn, scope, options) {
			Ext.EventManager.on(this.dom, eventName, fn, scope || this, options);
			return this;
		},

		/**
		* Removes an event handler from this element.  The shorthand version {@link #un} is equivalent.
		* <b>Note</b>: if a <i>scope</i> was explicitly specified when {@link #addListener adding} the
		* listener, the same scope must be specified here.
		* Example:
		* <pre><code>
		el.removeListener('click', this.handlerFn);
		// or
		el.un('click', this.handlerFn);
		</code></pre>
		* @param {String} eventName The name of the event from which to remove the handler.
		* @param {Function} fn The handler function to remove. <b>This must be a reference to the function passed into the {@link #addListener} call.</b>
		* @param {Object} scope If a scope (<b><code>this</code></b> reference) was specified when the listener was added,
		* then this must refer to the same object.
		* @return {Ext.Element} this
		*/
		removeListener: function (eventName, fn, scope) {
			Ext.EventManager.removeListener(this.dom, eventName, fn, scope || this);
			return this;
		},

		/**
		* Removes all previous added listeners from this element
		* @return {Ext.Element} this
		*/
		removeAllListeners: function () {
			Ext.EventManager.removeAll(this.dom);
			return this;
		},

		/**
		* Recursively removes all previous added listeners from this element and its children
		* @return {Ext.Element} this
		*/
		purgeAllListeners: function () {
			Ext.EventManager.purgeElement(this, true);
			return this;
		},
		/**
		* @private Test if size has a unit, otherwise appends the default
		*/
		addUnits: function (size) {
			if (size === "" || size == "auto" || size === undefined) {
				size = size || '';
			} else if (!isNaN(size) || !unitPattern.test(size)) {
				size = size + (this.defaultUnit || 'px');
			}
			return size;
		},

		/**
		* <p>Updates the <a href="http://developer.mozilla.org/en/DOM/element.innerHTML">innerHTML</a> of this Element
		* from a specified URL. Note that this is subject to the <a href="http://en.wikipedia.org/wiki/Same_origin_policy">Same Origin Policy</a></p>
		* <p>Updating innerHTML of an element will <b>not</b> execute embedded <tt>&lt;script></tt> elements. This is a browser restriction.</p>
		* @param {Mixed} options. Either a sring containing the URL from which to load the HTML, or an {@link Ext.Ajax#request} options object specifying
		* exactly how to request the HTML.
		* @return {Ext.Element} this
		*/
		load: function (url, params, cb) {
			Ext.Ajax.request(Ext.apply({
				params: params,
				url: url.url || url,
				callback: cb,
				el: this.dom,
				indicatorText: url.indicatorText || ''
			}, Ext.isObject(url) ? url : {}));
			return this;
		},

		/**
		* Tests various css rules/browsers to determine if this element uses a border box
		* @return {Boolean}
		*/
		isBorderBox: function () {
			return noBoxAdjust[(this.dom.tagName || "").toLowerCase()] || Ext.isBorderBox;
		},

		/**
		* <p>Removes this element's dom reference.  Note that event and cache removal is handled at {@link Ext#removeNode}</p>
		*/
		remove: function () {
			var me = this,
            dom = me.dom;

			if (dom) {
				delete me.dom;
				Ext.removeNode(dom);
			}
		},

		/**
		* Sets up event handlers to call the passed functions when the mouse is moved into and out of the Element.
		* @param {Function} overFn The function to call when the mouse enters the Element.
		* @param {Function} outFn The function to call when the mouse leaves the Element.
		* @param {Object} scope (optional) The scope (<code>this</code> reference) in which the functions are executed. Defaults to the Element's DOM element.
		* @param {Object} options (optional) Options for the listener. See {@link Ext.util.Observable#addListener the <tt>options</tt> parameter}.
		* @return {Ext.Element} this
		*/
		hover: function (overFn, outFn, scope, options) {
			var me = this;
			me.on('mouseenter', overFn, scope || me.dom, options);
			me.on('mouseleave', outFn, scope || me.dom, options);
			return me;
		},

		/**
		* Returns true if this element is an ancestor of the passed element
		* @param {HTMLElement/String} el The element to check
		* @return {Boolean} True if this element is an ancestor of el, else false
		*/
		contains: function (el) {
			return !el ? false : Ext.lib.Dom.isAncestor(this.dom, el.dom ? el.dom : el);
		},

		/**
		* Returns the value of a namespaced attribute from the element's underlying DOM node.
		* @param {String} namespace The namespace in which to look for the attribute
		* @param {String} name The attribute name
		* @return {String} The attribute value
		* @deprecated
		*/
		getAttributeNS: function (ns, name) {
			return this.getAttribute(name, ns);
		},

		/**
		* Returns the value of an attribute from the element's underlying DOM node.
		* @param {String} name The attribute name
		* @param {String} namespace (optional) The namespace in which to look for the attribute
		* @return {String} The attribute value
		*/
		getAttribute: Ext.isIE ? function (name, ns) {
			var d = this.dom,
            type = typeof d[ns + ":" + name];

			if (['undefined', 'unknown'].indexOf(type) == -1) {
				return d[ns + ":" + name];
			}
			return d[name];
		} : function (name, ns) {
			var d = this.dom;
			return d.getAttributeNS(ns, name) || d.getAttribute(ns + ":" + name) || d.getAttribute(name) || d[name];
		},

		/**
		* Update the innerHTML of this element
		* @param {String} html The new HTML
		* @return {Ext.Element} this
		*/
		update: function (html) {
			if (this.dom) {
				this.dom.innerHTML = html;
			}
			return this;
		}
	};

	var ep = El.prototype;

	El.addMethods = function (o) {
		Ext.apply(ep, o);
	};

	/**
	* Appends an event handler (shorthand for {@link #addListener}).
	* @param {String} eventName The name of event to handle.
	* @param {Function} fn The handler function the event invokes.
	* @param {Object} scope (optional) The scope (<code>this</code> reference) in which the handler function is executed.
	* @param {Object} options (optional) An object containing standard {@link #addListener} options
	* @member Ext.Element
	* @method on
	*/
	ep.on = ep.addListener;

	/**
	* Removes an event handler from this element (see {@link #removeListener} for additional notes).
	* @param {String} eventName The name of the event from which to remove the handler.
	* @param {Function} fn The handler function to remove. <b>This must be a reference to the function passed into the {@link #addListener} call.</b>
	* @param {Object} scope If a scope (<b><code>this</code></b> reference) was specified when the listener was added,
	* then this must refer to the same object.
	* @return {Ext.Element} this
	* @member Ext.Element
	* @method un
	*/
	ep.un = ep.removeListener;

	/**
	* true to automatically adjust width and height settings for box-model issues (default to true)
	*/
	ep.autoBoxAdjust = true;

	// private
	var unitPattern = /\d+(px|em|%|en|ex|pt|in|cm|mm|pc)$/i,
    docEl;

	/**
	* @private
	*/

	/**
	* Retrieves Ext.Element objects.
	* <p><b>This method does not retrieve {@link Ext.Component Component}s.</b> This method
	* retrieves Ext.Element objects which encapsulate DOM elements. To retrieve a Component by
	* its ID, use {@link Ext.ComponentMgr#get}.</p>
	* <p>Uses simple caching to consistently return the same object. Automatically fixes if an
	* object was recreated with the same id via AJAX or DOM.</p>
	* @param {Mixed} el The id of the node, a DOM Node or an existing Element.
	* @return {Element} The Element object (or null if no matching element was found)
	* @static
	* @member Ext.Element
	* @method get
	*/
	El.get = function (el) {
		var ex,
        elm,
        id;
		if (!el) { return null; }
		if (typeof el == "string") { // element id
			if (!(elm = DOC.getElementById(el))) {
				return null;
			}
			if (EC[el] && EC[el].el) {
				ex = EC[el].el;
				ex.dom = elm;
			} else {
				ex = El.addToCache(new El(elm));
			}
			return ex;
		} else if (el.tagName) { // dom element
			if (!(id = el.id)) {
				id = Ext.id(el);
			}
			if (EC[id] && EC[id].el) {
				ex = EC[id].el;
				ex.dom = el;
			} else {
				ex = El.addToCache(new El(el));
			}
			return ex;
		} else if (el instanceof El) {
			if (el != docEl) {
				// refresh dom element in case no longer valid,
				// catch case where it hasn't been appended

				// If an el instance is passed, don't pass to getElementById without some kind of id
				if (Ext.isIE && (el.id == undefined || el.id == '')) {
					el.dom = el.dom;
				} else {
					el.dom = DOC.getElementById(el.id) || el.dom;
				}
			}
			return el;
		} else if (el.isComposite) {
			return el;
		} else if (Ext.isArray(el)) {
			return El.select(el);
		} else if (el == DOC) {
			// create a bogus element object representing the document object
			if (!docEl) {
				var f = function () { };
				f.prototype = El.prototype;
				docEl = new f();
				docEl.dom = DOC;
			}
			return docEl;
		}
		return null;
	};

	El.addToCache = function (el, id) {
		id = id || el.id;
		EC[id] = {
			el: el,
			data: {},
			events: {}
		};
		return el;
	};

	// private method for getting and setting element data
	El.data = function (el, key, value) {
		el = El.get(el);
		if (!el) {
			return null;
		}
		var c = EC[el.id].data;
		if (arguments.length == 2) {
			return c[key];
		} else {
			return (c[key] = value);
		}
	};

	// private
	// Garbage collection - uncache elements/purge listeners on orphaned elements
	// so we don't hold a reference and cause the browser to retain them
	function garbageCollect() {
		if (!Ext.enableGarbageCollector) {
			clearInterval(El.collectorThreadId);
		} else {
			var eid,
            el,
            d,
            o;

			for (eid in EC) {
				o = EC[eid];
				if (o.skipGC) {
					continue;
				}
				el = o.el;
				d = el.dom;
				// -------------------------------------------------------
				// Determining what is garbage:
				// -------------------------------------------------------
				// !d
				// dom node is null, definitely garbage
				// -------------------------------------------------------
				// !d.parentNode
				// no parentNode == direct orphan, definitely garbage
				// -------------------------------------------------------
				// !d.offsetParent && !document.getElementById(eid)
				// display none elements have no offsetParent so we will
				// also try to look it up by it's id. However, check
				// offsetParent first so we don't do unneeded lookups.
				// This enables collection of elements that are not orphans
				// directly, but somewhere up the line they have an orphan
				// parent.
				// -------------------------------------------------------
				if (!d || !d.parentNode || (!d.offsetParent && !DOC.getElementById(eid))) {
					if (Ext.enableListenerCollection) {
						Ext.EventManager.removeAll(d);
					}
					delete EC[eid];
				}
			}
			// Cleanup IE Object leaks
			if (Ext.isIE) {
				var t = {};
				for (eid in EC) {
					t[eid] = EC[eid];
				}
				EC = Ext.elCache = t;
			}
		}
	}
	El.collectorThreadId = setInterval(garbageCollect, 30000);

	var flyFn = function () { };
	flyFn.prototype = El.prototype;

	// dom is optional
	El.Flyweight = function (dom) {
		this.dom = dom;
	};

	El.Flyweight.prototype = new flyFn();
	El.Flyweight.prototype.isFlyweight = true;
	El._flyweights = {};

	/**
	* <p>Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
	* the dom node can be overwritten by other code. Shorthand of {@link Ext.Element#fly}</p>
	* <p>Use this to make one-time references to DOM elements which are not going to be accessed again either by
	* application code, or by Ext's classes. If accessing an element which will be processed regularly, then {@link Ext#get}
	* will be more appropriate to take advantage of the caching provided by the Ext.Element class.</p>
	* @param {String/HTMLElement} el The dom node or id
	* @param {String} named (optional) Allows for creation of named reusable flyweights to prevent conflicts
	* (e.g. internally Ext uses "_global")
	* @return {Element} The shared Element object (or null if no matching element was found)
	* @member Ext.Element
	* @method fly
	*/
	El.fly = function (el, named) {
		var ret = null;
		named = named || '_global';

		if (el = Ext.getDom(el)) {
			(El._flyweights[named] = El._flyweights[named] || new El.Flyweight()).dom = el;
			ret = El._flyweights[named];
		}
		return ret;
	};

	/**
	* Retrieves Ext.Element objects.
	* <p><b>This method does not retrieve {@link Ext.Component Component}s.</b> This method
	* retrieves Ext.Element objects which encapsulate DOM elements. To retrieve a Component by
	* its ID, use {@link Ext.ComponentMgr#get}.</p>
	* <p>Uses simple caching to consistently return the same object. Automatically fixes if an
	* object was recreated with the same id via AJAX or DOM.</p>
	* Shorthand of {@link Ext.Element#get}
	* @param {Mixed} el The id of the node, a DOM Node or an existing Element.
	* @return {Element} The Element object (or null if no matching element was found)
	* @member Ext
	* @method get
	*/
	Ext.get = El.get;

	/**
	* <p>Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
	* the dom node can be overwritten by other code. Shorthand of {@link Ext.Element#fly}</p>
	* <p>Use this to make one-time references to DOM elements which are not going to be accessed again either by
	* application code, or by Ext's classes. If accessing an element which will be processed regularly, then {@link Ext#get}
	* will be more appropriate to take advantage of the caching provided by the Ext.Element class.</p>
	* @param {String/HTMLElement} el The dom node or id
	* @param {String} named (optional) Allows for creation of named reusable flyweights to prevent conflicts
	* (e.g. internally Ext uses "_global")
	* @return {Element} The shared Element object (or null if no matching element was found)
	* @member Ext
	* @method fly
	*/
	Ext.fly = El.fly;

	// speedy lookup for elements never to box adjust
	var noBoxAdjust = Ext.isStrict ? {
		select: 1
	} : {
		input: 1, select: 1, textarea: 1
	};
	if (Ext.isIE || Ext.isGecko) {
		noBoxAdjust['button'] = 1;
	}

})();
/**
* @class Ext.Element
*/
Ext.Element.addMethods({
	/**
	* Stops the specified event(s) from bubbling and optionally prevents the default action
	* @param {String/Array} eventName an event / array of events to stop from bubbling
	* @param {Boolean} preventDefault (optional) true to prevent the default action too
	* @return {Ext.Element} this
	*/
	swallowEvent: function (eventName, preventDefault) {
		var me = this;
		function fn(e) {
			e.stopPropagation();
			if (preventDefault) {
				e.preventDefault();
			}
		}
		if (Ext.isArray(eventName)) {
			Ext.each(eventName, function (e) {
				me.on(e, fn);
			});
			return me;
		}
		me.on(eventName, fn);
		return me;
	},

	/**
	* Create an event handler on this element such that when the event fires and is handled by this element,
	* it will be relayed to another object (i.e., fired again as if it originated from that object instead).
	* @param {String} eventName The type of event to relay
	* @param {Object} object Any object that extends {@link Ext.util.Observable} that will provide the context
	* for firing the relayed event
	*/
	relayEvent: function (eventName, observable) {
		this.on(eventName, function (e) {
			observable.fireEvent(eventName, e);
		});
	},

	/**
	* Removes worthless text nodes
	* @param {Boolean} forceReclean (optional) By default the element
	* keeps track if it has been cleaned already so
	* you can call this over and over. However, if you update the element and
	* need to force a reclean, you can pass true.
	*/
	clean: function (forceReclean) {
		var me = this,
            dom = me.dom,
            n = dom.firstChild,
            ni = -1;

		if (Ext.Element.data(dom, 'isCleaned') && forceReclean !== true) {
			return me;
		}

		while (n) {
			var nx = n.nextSibling;
			if (n.nodeType == 3 && !/\S/.test(n.nodeValue)) {
				dom.removeChild(n);
			} else {
				n.nodeIndex = ++ni;
			}
			n = nx;
		}
		Ext.Element.data(dom, 'isCleaned', true);
		return me;
	},

	/**
	* Direct access to the Updater {@link Ext.Updater#update} method. The method takes the same object
	* parameter as {@link Ext.Updater#update}
	* @return {Ext.Element} this
	*/
	load: function () {
		var um = this.getUpdater();
		um.update.apply(um, arguments);
		return this;
	},

	/**
	* Gets this element's {@link Ext.Updater Updater}
	* @return {Ext.Updater} The Updater
	*/
	getUpdater: function () {
		return this.updateManager || (this.updateManager = new Ext.Updater(this));
	},

	/**
	* Update the innerHTML of this element, optionally searching for and processing scripts
	* @param {String} html The new HTML
	* @param {Boolean} loadScripts (optional) True to look for and process scripts (defaults to false)
	* @param {Function} callback (optional) For async script loading you can be notified when the update completes
	* @return {Ext.Element} this
	*/
	update: function (html, loadScripts, callback) {
		if (!this.dom) {
			return this;
		}
		html = html || "";

		if (loadScripts !== true) {
			this.dom.innerHTML = html;
			if (typeof callback == 'function') {
				callback();
			}
			return this;
		}

		var id = Ext.id(),
            dom = this.dom;

		html += '<span id="' + id + '"></span>';

		Ext.lib.Event.onAvailable(id, function () {
			var DOC = document,
                hd = DOC.getElementsByTagName("head")[0],
                re = /(?:<script([^>]*)?>)((\n|\r|.)*?)(?:<\/script>)/ig,
                srcRe = /\ssrc=([\'\"])(.*?)\1/i,
                typeRe = /\stype=([\'\"])(.*?)\1/i,
                match,
                attrs,
                srcMatch,
                typeMatch,
                el,
                s;

			while ((match = re.exec(html))) {
				attrs = match[1];
				srcMatch = attrs ? attrs.match(srcRe) : false;
				if (srcMatch && srcMatch[2]) {
					s = DOC.createElement("script");
					s.src = srcMatch[2];
					typeMatch = attrs.match(typeRe);
					if (typeMatch && typeMatch[2]) {
						s.type = typeMatch[2];
					}
					hd.appendChild(s);
				} else if (match[2] && match[2].length > 0) {
					if (window.execScript) {
						window.execScript(match[2]);
					} else {
						window.eval(match[2]);
					}
				}
			}
			el = DOC.getElementById(id);
			if (el) { Ext.removeNode(el); }
			if (typeof callback == 'function') {
				callback();
			}
		});
		dom.innerHTML = html.replace(/(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig, "");
		return this;
	},

	// inherit docs, overridden so we can add removeAnchor
	removeAllListeners: function () {
		this.removeAnchor();
		Ext.EventManager.removeAll(this.dom);
		return this;
	},

	/**
	* Creates a proxy element of this element
	* @param {String/Object} config The class name of the proxy element or a DomHelper config object
	* @param {String/HTMLElement} renderTo (optional) The element or element id to render the proxy to (defaults to document.body)
	* @param {Boolean} matchBox (optional) True to align and size the proxy to this element now (defaults to false)
	* @return {Ext.Element} The new proxy element
	*/
	createProxy: function (config, renderTo, matchBox) {
		config = (typeof config == 'object') ? config : { tag: "div", cls: config };

		var me = this,
            proxy = renderTo ? Ext.DomHelper.append(renderTo, config, true) :
                               Ext.DomHelper.insertBefore(me.dom, config, true);

		if (matchBox && me.setBox && me.getBox) { // check to make sure Element.position.js is loaded
			proxy.setBox(me.getBox());
		}
		return proxy;
	}
});

Ext.Element.prototype.getUpdateManager = Ext.Element.prototype.getUpdater;
/**
* @class Ext.Element
*/
Ext.Element.addMethods({
	/**
	* Gets the x,y coordinates specified by the anchor position on the element.
	* @param {String} anchor (optional) The specified anchor position (defaults to "c").  See {@link #alignTo}
	* for details on supported anchor positions.
	* @param {Boolean} local (optional) True to get the local (element top/left-relative) anchor position instead
	* of page coordinates
	* @param {Object} size (optional) An object containing the size to use for calculating anchor position
	* {width: (target width), height: (target height)} (defaults to the element's current size)
	* @return {Array} [x, y] An array containing the element's x and y coordinates
	*/
	getAnchorXY: function (anchor, local, s) {
		//Passing a different size is useful for pre-calculating anchors,
		//especially for anchored animations that change the el size.
		anchor = (anchor || "tl").toLowerCase();
		s = s || {};

		var me = this,
        	vp = me.dom == document.body || me.dom == document,
        	w = s.width || vp ? Ext.lib.Dom.getViewWidth() : me.getWidth(),
        	h = s.height || vp ? Ext.lib.Dom.getViewHeight() : me.getHeight(),
        	xy,
        	r = Math.round,
        	o = me.getXY(),
        	scroll = me.getScroll(),
        	extraX = vp ? scroll.left : !local ? o[0] : 0,
        	extraY = vp ? scroll.top : !local ? o[1] : 0,
        	hash = {
        		c: [r(w * 0.5), r(h * 0.5)],
        		t: [r(w * 0.5), 0],
        		l: [0, r(h * 0.5)],
        		r: [w, r(h * 0.5)],
        		b: [r(w * 0.5), h],
        		tl: [0, 0],
        		bl: [0, h],
        		br: [w, h],
        		tr: [w, 0]
        	};

		xy = hash[anchor];
		return [xy[0] + extraX, xy[1] + extraY];
	},

	/**
	* Anchors an element to another element and realigns it when the window is resized.
	* @param {Mixed} element The element to align to.
	* @param {String} position The position to align to.
	* @param {Array} offsets (optional) Offset the positioning by [x, y]
	* @param {Boolean/Object} animate (optional) True for the default animation or a standard Element animation config object
	* @param {Boolean/Number} monitorScroll (optional) True to monitor body scroll and reposition. If this parameter
	* is a number, it is used as the buffer delay (defaults to 50ms).
	* @param {Function} callback The function to call after the animation finishes
	* @return {Ext.Element} this
	*/
	anchorTo: function (el, alignment, offsets, animate, monitorScroll, callback) {
		var me = this,
            dom = me.dom,
            scroll = !Ext.isEmpty(monitorScroll),
            action = function () {
            	Ext.fly(dom).alignTo(el, alignment, offsets, animate);
            	Ext.callback(callback, Ext.fly(dom));
            },
            anchor = this.getAnchor();

		// previous listener anchor, remove it
		this.removeAnchor();
		Ext.apply(anchor, {
			fn: action,
			scroll: scroll
		});

		Ext.EventManager.onWindowResize(action, null);

		if (scroll) {
			Ext.EventManager.on(window, 'scroll', action, null,
                { buffer: !isNaN(monitorScroll) ? monitorScroll : 50 });
		}
		action.call(me); // align immediately
		return me;
	},

	/**
	* Remove any anchor to this element. See {@link #anchorTo}.
	* @return {Ext.Element} this
	*/
	removeAnchor: function () {
		var me = this,
            anchor = this.getAnchor();

		if (anchor && anchor.fn) {
			Ext.EventManager.removeResizeListener(anchor.fn);
			if (anchor.scroll) {
				Ext.EventManager.un(window, 'scroll', anchor.fn);
			}
			delete anchor.fn;
		}
		return me;
	},

	// private
	getAnchor: function () {
		var data = Ext.Element.data,
            dom = this.dom;
		if (!dom) {
			return;
		}
		var anchor = data(dom, '_anchor');

		if (!anchor) {
			anchor = data(dom, '_anchor', {});
		}
		return anchor;
	},

	/**
	* Gets the x,y coordinates to align this element with another element. See {@link #alignTo} for more info on the
	* supported position values.
	* @param {Mixed} element The element to align to.
	* @param {String} position (optional, defaults to "tl-bl?") The position to align to.
	* @param {Array} offsets (optional) Offset the positioning by [x, y]
	* @return {Array} [x, y]
	*/
	getAlignToXY: function (el, p, o) {
		el = Ext.get(el);

		if (!el || !el.dom) {
			throw "Element.alignToXY with an element that doesn't exist";
		}

		o = o || [0, 0];
		p = (!p || p == "?" ? "tl-bl?" : (!/-/.test(p) && p !== "" ? "tl-" + p : p || "tl-bl")).toLowerCase();

		var me = this,
        	d = me.dom,
        	a1,
        	a2,
        	x,
        	y,
		//constrain the aligned el to viewport if necessary
        	w,
        	h,
        	r,
        	dw = Ext.lib.Dom.getViewWidth() - 10, // 10px of margin for ie
        	dh = Ext.lib.Dom.getViewHeight() - 10, // 10px of margin for ie
        	p1y,
        	p1x,
        	p2y,
        	p2x,
        	swapY,
        	swapX,
        	doc = document,
        	docElement = doc.documentElement,
        	docBody = doc.body,
        	scrollX = (docElement.scrollLeft || docBody.scrollLeft || 0) + 5,
        	scrollY = (docElement.scrollTop || docBody.scrollTop || 0) + 5,
        	c = false, //constrain to viewport
        	p1 = "",
        	p2 = "",
        	m = p.match(/^([a-z]+)-([a-z]+)(\?)?$/);

		if (!m) {
			throw "Element.alignTo with an invalid alignment " + p;
		}

		p1 = m[1];
		p2 = m[2];
		c = !!m[3];

		//Subtract the aligned el's internal xy from the target's offset xy
		//plus custom offset to get the aligned el's new offset xy
		a1 = me.getAnchorXY(p1, true);
		a2 = el.getAnchorXY(p2, false);

		x = a2[0] - a1[0] + o[0];
		y = a2[1] - a1[1] + o[1];

		if (c) {
			w = me.getWidth();
			h = me.getHeight();
			r = el.getRegion();
			//If we are at a viewport boundary and the aligned el is anchored on a target border that is
			//perpendicular to the vp border, allow the aligned el to slide on that border,
			//otherwise swap the aligned el to the opposite border of the target.
			p1y = p1.charAt(0);
			p1x = p1.charAt(p1.length - 1);
			p2y = p2.charAt(0);
			p2x = p2.charAt(p2.length - 1);
			swapY = ((p1y == "t" && p2y == "b") || (p1y == "b" && p2y == "t"));
			swapX = ((p1x == "r" && p2x == "l") || (p1x == "l" && p2x == "r"));


			if (x + w > dw + scrollX) {
				x = swapX ? r.left - w : dw + scrollX - w;
			}
			if (x < scrollX) {
				x = swapX ? r.right : scrollX;
			}
			if (y + h > dh + scrollY) {
				y = swapY ? r.top - h : dh + scrollY - h;
			}
			if (y < scrollY) {
				y = swapY ? r.bottom : scrollY;
			}
		}
		return [x, y];
	},

	/**
	* Aligns this element with another element relative to the specified anchor points. If the other element is the
	* document it aligns it to the viewport.
	* The position parameter is optional, and can be specified in any one of the following formats:
	* <ul>
	*   <li><b>Blank</b>: Defaults to aligning the element's top-left corner to the target's bottom-left corner ("tl-bl").</li>
	*   <li><b>One anchor (deprecated)</b>: The passed anchor position is used as the target element's anchor point.
	*       The element being aligned will position its top-left corner (tl) to that point.  <i>This method has been
	*       deprecated in favor of the newer two anchor syntax below</i>.</li>
	*   <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
	*       element's anchor point, and the second value is used as the target's anchor point.</li>
	* </ul>
	* In addition to the anchor points, the position parameter also supports the "?" character.  If "?" is passed at the end of
	* the position string, the element will attempt to align as specified, but the position will be adjusted to constrain to
	* the viewport if necessary.  Note that the element being aligned might be swapped to align to a different position than
	* that specified in order to enforce the viewport constraints.
	* Following are all of the supported anchor positions:
	<pre>
	Value  Description
	-----  -----------------------------
	tl     The top left corner (default)
	t      The center of the top edge
	tr     The top right corner
	l      The center of the left edge
	c      In the center of the element
	r      The center of the right edge
	bl     The bottom left corner
	b      The center of the bottom edge
	br     The bottom right corner
	</pre>
	Example Usage:
	<pre><code>
	// align el to other-el using the default positioning ("tl-bl", non-constrained)
	el.alignTo("other-el");

	// align the top left corner of el with the top right corner of other-el (constrained to viewport)
	el.alignTo("other-el", "tr?");

	// align the bottom right corner of el with the center left edge of other-el
	el.alignTo("other-el", "br-l?");

	// align the center of el with the bottom left corner of other-el and
	// adjust the x position by -6 pixels (and the y position by 0)
	el.alignTo("other-el", "c-bl", [-6, 0]);
	</code></pre>
	* @param {Mixed} element The element to align to.
	* @param {String} position (optional, defaults to "tl-bl?") The position to align to.
	* @param {Array} offsets (optional) Offset the positioning by [x, y]
	* @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
	* @return {Ext.Element} this
	*/
	alignTo: function (element, position, offsets, animate) {
		var me = this;
		return me.setXY(me.getAlignToXY(element, position, offsets),
          		        me.preanim && !!animate ? me.preanim(arguments, 3) : false);
	},

	// private ==>  used outside of core
	adjustForConstraints: function (xy, parent, offsets) {
		return this.getConstrainToXY(parent || document, false, offsets, xy) || xy;
	},

	// private ==>  used outside of core
	getConstrainToXY: function (el, local, offsets, proposedXY) {
		var os = { top: 0, left: 0, bottom: 0, right: 0 };

		return function (el, local, offsets, proposedXY) {
			el = Ext.get(el);
			offsets = offsets ? Ext.applyIf(offsets, os) : os;

			var vw, vh, vx = 0, vy = 0;
			if (el.dom == document.body || el.dom == document) {
				vw = Ext.lib.Dom.getViewWidth();
				vh = Ext.lib.Dom.getViewHeight();
			} else {
				vw = el.dom.clientWidth;
				vh = el.dom.clientHeight;
				if (!local) {
					var vxy = el.getXY();
					vx = vxy[0];
					vy = vxy[1];
				}
			}

			var s = el.getScroll();

			vx += offsets.left + s.left;
			vy += offsets.top + s.top;

			vw -= offsets.right;
			vh -= offsets.bottom;

			var vr = vx + vw;
			var vb = vy + vh;

			var xy = proposedXY || (!local ? this.getXY() : [this.getLeft(true), this.getTop(true)]);
			var x = xy[0], y = xy[1];
			var w = this.dom.offsetWidth, h = this.dom.offsetHeight;

			// only move it if it needs it
			var moved = false;

			// first validate right/bottom
			if ((x + w) > vr) {
				x = vr - w;
				moved = true;
			}
			if ((y + h) > vb) {
				y = vb - h;
				moved = true;
			}
			// then make sure top/left isn't negative
			if (x < vx) {
				x = vx;
				moved = true;
			}
			if (y < vy) {
				y = vy;
				moved = true;
			}
			return moved ? [x, y] : false;
		};
	} (),



	//         el = Ext.get(el);
	//         offsets = Ext.applyIf(offsets || {}, {top : 0, left : 0, bottom : 0, right : 0});

	//         var	me = this,
	//         	doc = document,
	//         	s = el.getScroll(),
	//         	vxy = el.getXY(),
	//         	vx = offsets.left + s.left, 
	//         	vy = offsets.top + s.top,            	
	//         	vw = -offsets.right, 
	//         	vh = -offsets.bottom, 
	//         	vr,
	//         	vb,
	//         	xy = proposedXY || (!local ? me.getXY() : [me.getLeft(true), me.getTop(true)]),
	//         	x = xy[0],
	//         	y = xy[1],
	//         	w = me.dom.offsetWidth, h = me.dom.offsetHeight,
	//         	moved = false; // only move it if it needs it
	//       
	//         	
	//         if(el.dom == doc.body || el.dom == doc){
	//             vw += Ext.lib.Dom.getViewWidth();
	//             vh += Ext.lib.Dom.getViewHeight();
	//         }else{
	//             vw += el.dom.clientWidth;
	//             vh += el.dom.clientHeight;
	//             if(!local){                    
	//                 vx += vxy[0];
	//                 vy += vxy[1];
	//             }
	//         }

	//         // first validate right/bottom
	//         if(x + w > vx + vw){
	//             x = vx + vw - w;
	//             moved = true;
	//         }
	//         if(y + h > vy + vh){
	//             y = vy + vh - h;
	//             moved = true;
	//         }
	//         // then make sure top/left isn't negative
	//         if(x < vx){
	//             x = vx;
	//             moved = true;
	//         }
	//         if(y < vy){
	//             y = vy;
	//             moved = true;
	//         }
	//         return moved ? [x, y] : false;
	//    },

	/**
	* Calculates the x, y to center this element on the screen
	* @return {Array} The x, y values [x, y]
	*/
	getCenterXY: function () {
		return this.getAlignToXY(document, 'c-c');
	},

	/**
	* Centers the Element in either the viewport, or another Element.
	* @param {Mixed} centerIn (optional) The element in which to center the element.
	*/
	center: function (centerIn) {
		return this.alignTo(centerIn || document, 'c-c');
	}
});
/**
* @class Ext.Element
*/
Ext.Element.addMethods(function () {
	var PARENTNODE = 'parentNode',
		NEXTSIBLING = 'nextSibling',
		PREVIOUSSIBLING = 'previousSibling',
		DQ = Ext.DomQuery,
		GET = Ext.get;

	return {
		/**
		* 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)
		* @param {String} selector The simple selector to test
		* @param {Number/Mixed} maxDepth (optional) The max depth to search as a number or element (defaults to 50 || document.body)
		* @param {Boolean} returnEl (optional) True to return a Ext.Element object instead of DOM node
		* @return {HTMLElement} The matching DOM node (or null if no match was found)
		*/
		findParent: function (simpleSelector, maxDepth, returnEl) {
			var p = this.dom,
	        	b = document.body,
	        	depth = 0,
	        	stopEl;
			if (Ext.isGecko && Object.prototype.toString.call(p) == '[object XULElement]') {
				return null;
			}
			maxDepth = maxDepth || 50;
			if (isNaN(maxDepth)) {
				stopEl = Ext.getDom(maxDepth);
				maxDepth = Number.MAX_VALUE;
			}
			while (p && p.nodeType == 1 && depth < maxDepth && p != b && p != stopEl) {
				if (DQ.is(p, simpleSelector)) {
					return returnEl ? GET(p) : p;
				}
				depth++;
				p = p.parentNode;
			}
			return null;
		},

		/**
		* Looks at parent nodes for a match of the passed simple selector (e.g. div.some-class or span:first-child)
		* @param {String} selector The simple selector to test
		* @param {Number/Mixed} maxDepth (optional) The max depth to
		search as a number or element (defaults to 10 || document.body)
		* @param {Boolean} returnEl (optional) True to return a Ext.Element object instead of DOM node
		* @return {HTMLElement} The matching DOM node (or null if no match was found)
		*/
		findParentNode: function (simpleSelector, maxDepth, returnEl) {
			var p = Ext.fly(this.dom.parentNode, '_internal');
			return p ? p.findParent(simpleSelector, maxDepth, returnEl) : null;
		},

		/**
		* Walks up the dom looking for a parent node that matches the passed simple selector (e.g. div.some-class or span:first-child).
		* This is a shortcut for findParentNode() that always returns an Ext.Element.
		* @param {String} selector The simple selector to test
		* @param {Number/Mixed} maxDepth (optional) The max depth to
		search as a number or element (defaults to 10 || document.body)
		* @return {Ext.Element} The matching DOM node (or null if no match was found)
		*/
		up: function (simpleSelector, maxDepth) {
			return this.findParentNode(simpleSelector, maxDepth, true);
		},

		/**
		* Creates a {@link Ext.CompositeElement} for child nodes based on the passed CSS selector (the selector should not contain an id).
		* @param {String} selector The CSS selector
		* @return {CompositeElement/CompositeElementLite} The composite element
		*/
		select: function (selector) {
			return Ext.Element.select(selector, this.dom);
		},

		/**
		* Selects child nodes based on the passed CSS selector (the selector should not contain an id).
		* @param {String} selector The CSS selector
		* @return {Array} An array of the matched nodes
		*/
		query: function (selector) {
			return DQ.select(selector, this.dom);
		},

		/**
		* Selects a single child at any depth below this element based on the passed CSS selector (the selector should not contain an id).
		* @param {String} selector The CSS selector
		* @param {Boolean} returnDom (optional) True to return the DOM node instead of Ext.Element (defaults to false)
		* @return {HTMLElement/Ext.Element} The child Ext.Element (or DOM node if returnDom = true)
		*/
		child: function (selector, returnDom) {
			var n = DQ.selectNode(selector, this.dom);
			return returnDom ? n : GET(n);
		},

		/**
		* Selects a single *direct* child based on the passed CSS selector (the selector should not contain an id).
		* @param {String} selector The CSS selector
		* @param {Boolean} returnDom (optional) True to return the DOM node instead of Ext.Element (defaults to false)
		* @return {HTMLElement/Ext.Element} The child Ext.Element (or DOM node if returnDom = true)
		*/
		down: function (selector, returnDom) {
			var n = DQ.selectNode(" > " + selector, this.dom);
			return returnDom ? n : GET(n);
		},

		/**
		* Gets the parent node for this element, optionally chaining up trying to match a selector
		* @param {String} selector (optional) Find a parent node that matches the passed simple selector
		* @param {Boolean} returnDom (optional) True to return a raw dom node instead of an Ext.Element
		* @return {Ext.Element/HTMLElement} The parent node or null
		*/
		parent: function (selector, returnDom) {
			return this.matchNode(PARENTNODE, PARENTNODE, selector, returnDom);
		},

		/**
		* Gets the next sibling, skipping text nodes
		* @param {String} selector (optional) Find the next sibling that matches the passed simple selector
		* @param {Boolean} returnDom (optional) True to return a raw dom node instead of an Ext.Element
		* @return {Ext.Element/HTMLElement} The next sibling or null
		*/
		next: function (selector, returnDom) {
			return this.matchNode(NEXTSIBLING, NEXTSIBLING, selector, returnDom);
		},

		/**
		* Gets the previous sibling, skipping text nodes
		* @param {String} selector (optional) Find the previous sibling that matches the passed simple selector
		* @param {Boolean} returnDom (optional) True to return a raw dom node instead of an Ext.Element
		* @return {Ext.Element/HTMLElement} The previous sibling or null
		*/
		prev: function (selector, returnDom) {
			return this.matchNode(PREVIOUSSIBLING, PREVIOUSSIBLING, selector, returnDom);
		},


		/**
		* Gets the first child, skipping text nodes
		* @param {String} selector (optional) Find the next sibling that matches the passed simple selector
		* @param {Boolean} returnDom (optional) True to return a raw dom node instead of an Ext.Element
		* @return {Ext.Element/HTMLElement} The first child or null
		*/
		first: function (selector, returnDom) {
			return this.matchNode(NEXTSIBLING, 'firstChild', selector, returnDom);
		},

		/**
		* Gets the last child, skipping text nodes
		* @param {String} selector (optional) Find the previous sibling that matches the passed simple selector
		* @param {Boolean} returnDom (optional) True to return a raw dom node instead of an Ext.Element
		* @return {Ext.Element/HTMLElement} The last child or null
		*/
		last: function (selector, returnDom) {
			return this.matchNode(PREVIOUSSIBLING, 'lastChild', selector, returnDom);
		},

		matchNode: function (dir, start, selector, returnDom) {
			var n = this.dom[start];
			while (n) {
				if (n.nodeType == 1 && (!selector || DQ.is(n, selector))) {
					return !returnDom ? GET(n) : n;
				}
				n = n[dir];
			}
			return null;
		}
	}
} ()); /**
 * @class Ext.Element
 */
Ext.Element.addMethods({
	/**
	* Creates a {@link Ext.CompositeElement} for child nodes based on the passed CSS selector (the selector should not contain an id).
	* @param {String} selector The CSS selector
	* @param {Boolean} unique (optional) True to create a unique Ext.Element for each child (defaults to false, which creates a single shared flyweight object)
	* @return {CompositeElement/CompositeElementLite} The composite element
	*/
	select: function (selector, unique) {
		return Ext.Element.select(selector, unique, this.dom);
	}
}); /**
 * @class Ext.Element
 */
Ext.Element.addMethods(
function () {
	var GETDOM = Ext.getDom,
		GET = Ext.get,
		DH = Ext.DomHelper;

	return {
		/**
		* Appends the passed element(s) to this element
		* @param {String/HTMLElement/Array/Element/CompositeElement} el
		* @return {Ext.Element} this
		*/
		appendChild: function (el) {
			return GET(el).appendTo(this);
		},

		/**
		* Appends this element to the passed element
		* @param {Mixed} el The new parent element
		* @return {Ext.Element} this
		*/
		appendTo: function (el) {
			GETDOM(el).appendChild(this.dom);
			return this;
		},

		/**
		* Inserts this element before the passed element in the DOM
		* @param {Mixed} el The element before which this element will be inserted
		* @return {Ext.Element} this
		*/
		insertBefore: function (el) {
			(el = GETDOM(el)).parentNode.insertBefore(this.dom, el);
			return this;
		},

		/**
		* Inserts this element after the passed element in the DOM
		* @param {Mixed} el The element to insert after
		* @return {Ext.Element} this
		*/
		insertAfter: function (el) {
			(el = GETDOM(el)).parentNode.insertBefore(this.dom, el.nextSibling);
			return this;
		},

		/**
		* Inserts (or creates) an element (or DomHelper config) as the first child of this element
		* @param {Mixed/Object} el The id or element to insert or a DomHelper config to create and insert
		* @return {Ext.Element} The new child
		*/
		insertFirst: function (el, returnDom) {
			el = el || {};
			if (el.nodeType || el.dom || typeof el == 'string') { // element
				el = GETDOM(el);
				this.dom.insertBefore(el, this.dom.firstChild);
				return !returnDom ? GET(el) : el;
			} else { // dh config
				return this.createChild(el, this.dom.firstChild, returnDom);
			}
		},

		/**
		* Replaces the passed element with this element
		* @param {Mixed} el The element to replace
		* @return {Ext.Element} this
		*/
		replace: function (el) {
			el = GET(el);
			this.insertBefore(el);
			el.remove();
			return this;
		},

		/**
		* Replaces this element with the passed element
		* @param {Mixed/Object} el The new element or a DomHelper config of an element to create
		* @return {Ext.Element} this
		*/
		replaceWith: function (el) {
			var me = this;

			if (el.nodeType || el.dom || typeof el == 'string') {
				el = GETDOM(el);
				me.dom.parentNode.insertBefore(el, me.dom);
			} else {
				el = DH.insertBefore(me.dom, el);
			}

			delete Ext.elCache[me.id];
			Ext.removeNode(me.dom);
			me.id = Ext.id(me.dom = el);
			Ext.Element.addToCache(me.isFlyweight ? new Ext.Element(me.dom) : me);
			return me;
		},

		/**
		* Creates the passed DomHelper config and appends it to this element or optionally inserts it before the passed child element.
		* @param {Object} config DomHelper element config object.  If no tag is specified (e.g., {tag:'input'}) then a div will be
		* automatically generated with the specified attributes.
		* @param {HTMLElement} insertBefore (optional) a child element of this element
		* @param {Boolean} returnDom (optional) true to return the dom node instead of creating an Element
		* @return {Ext.Element} The new child element
		*/
		createChild: function (config, insertBefore, returnDom) {
			config = config || { tag: 'div' };
			return insertBefore ?
		    	   DH.insertBefore(insertBefore, config, returnDom !== true) :
		    	   DH[!this.dom.firstChild ? 'overwrite' : 'append'](this.dom, config, returnDom !== true);
		},

		/**
		* Creates and wraps this element with another element
		* @param {Object} config (optional) DomHelper element config object for the wrapper element or null for an empty div
		* @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Ext.Element
		* @return {HTMLElement/Element} The newly created wrapper element
		*/
		wrap: function (config, returnDom) {
			var newEl = DH.insertBefore(this.dom, config || { tag: "div" }, !returnDom);
			newEl.dom ? newEl.dom.appendChild(this.dom) : newEl.appendChild(this.dom);
			return newEl;
		},

		/**
		* Inserts an html fragment into this element
		* @param {String} where Where to insert the html in relation to this element - beforeBegin, afterBegin, beforeEnd, afterEnd.
		* @param {String} html The HTML fragment
		* @param {Boolean} returnEl (optional) True to return an Ext.Element (defaults to false)
		* @return {HTMLElement/Ext.Element} The inserted node (or nearest related if more than 1 inserted)
		*/
		insertHtml: function (where, html, returnEl) {
			var el = DH.insertHtml(where, this.dom, html);
			return returnEl ? Ext.get(el) : el;
		}
	}
} ()); /**
 * @class Ext.Element
 */
Ext.apply(Ext.Element.prototype, function () {
	var GETDOM = Ext.getDom,
		GET = Ext.get,
		DH = Ext.DomHelper;

	return {
		/**
		* Inserts (or creates) the passed element (or DomHelper config) as a sibling of this element
		* @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.
		* @param {String} where (optional) 'before' or 'after' defaults to before
		* @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Ext.Element
		* @return {Ext.Element} The inserted Element. If an array is passed, the last inserted element is returned.
		*/
		insertSibling: function (el, where, returnDom) {
			var me = this,
	        	rt,
                isAfter = (where || 'before').toLowerCase() == 'after',
                insertEl;

			if (Ext.isArray(el)) {
				insertEl = me;
				Ext.each(el, function (e) {
					rt = Ext.fly(insertEl, '_internal').insertSibling(e, where, returnDom);
					if (isAfter) {
						insertEl = rt;
					}
				});
				return rt;
			}

			el = el || {};

			if (el.nodeType || el.dom) {
				rt = me.dom.parentNode.insertBefore(GETDOM(el), isAfter ? me.dom.nextSibling : me.dom);
				if (!returnDom) {
					rt = GET(rt);
				}
			} else {
				if (isAfter && !me.dom.nextSibling) {
					rt = DH.append(me.dom.parentNode, el, !returnDom);
				} else {
					rt = DH[isAfter ? 'insertAfter' : 'insertBefore'](me.dom, el, !returnDom);
				}
			}
			return rt;
		}
	};
} ()); /**
 * @class Ext.Element
 */
Ext.Element.addMethods(function () {
	// local style camelizing for speed
	var propCache = {},
        camelRe = /(-[a-z])/gi,
        classReCache = {},
        view = document.defaultView,
        propFloat = Ext.isIE ? 'styleFloat' : 'cssFloat',
        opacityRe = /alpha\(opacity=(.*)\)/i,
        trimRe = /^\s+|\s+$/g,
        spacesRe = /\s+/,
        wordsRe = /\w/g,
        EL = Ext.Element,
        PADDING = "padding",
        MARGIN = "margin",
        BORDER = "border",
        LEFT = "-left",
        RIGHT = "-right",
        TOP = "-top",
        BOTTOM = "-bottom",
        WIDTH = "-width",
        MATH = Math,
        HIDDEN = 'hidden',
        ISCLIPPED = 'isClipped',
        OVERFLOW = 'overflow',
        OVERFLOWX = 'overflow-x',
        OVERFLOWY = 'overflow-y',
        ORIGINALCLIP = 'originalClip',
	// special markup used throughout Ext when box wrapping elements
        borders = { l: BORDER + LEFT + WIDTH, r: BORDER + RIGHT + WIDTH, t: BORDER + TOP + WIDTH, b: BORDER + BOTTOM + WIDTH },
        paddings = { l: PADDING + LEFT, r: PADDING + RIGHT, t: PADDING + TOP, b: PADDING + BOTTOM },
        margins = { l: MARGIN + LEFT, r: MARGIN + RIGHT, t: MARGIN + TOP, b: MARGIN + BOTTOM },
        data = Ext.Element.data;


	// private
	function camelFn(m, a) {
		return a.charAt(1).toUpperCase();
	}

	function chkCache(prop) {
		return propCache[prop] || (propCache[prop] = prop == 'float' ? propFloat : prop.replace(camelRe, camelFn));
	}

	return {
		// private  ==> used by Fx
		adjustWidth: function (width) {
			var me = this;
			var isNum = (typeof width == "number");
			if (isNum && me.autoBoxAdjust && !me.isBorderBox()) {
				width -= (me.getBorderWidth("lr") + me.getPadding("lr"));
			}
			return (isNum && width < 0) ? 0 : width;
		},

		// private   ==> used by Fx
		adjustHeight: function (height) {
			var me = this;
			var isNum = (typeof height == "number");
			if (isNum && me.autoBoxAdjust && !me.isBorderBox()) {
				height -= (me.getBorderWidth("tb") + me.getPadding("tb"));
			}
			return (isNum && height < 0) ? 0 : height;
		},


		/**
		* Adds one or more CSS classes to the element. Duplicate classes are automatically filtered out.
		* @param {String/Array} className The CSS class to add, or an array of classes
		* @return {Ext.Element} this
		*/
		addClass: function (className) {
			var me = this,
                i,
                len,
                v,
                cls = [];
			// Separate case is for speed
			if (!Ext.isArray(className)) {
				if (typeof className == 'string' && !this.hasClass(className)) {
					me.dom.className += " " + className;
				}
			}
			else {
				for (i = 0, len = className.length; i < len; i++) {
					v = className[i];
					if (typeof v == 'string' && (' ' + me.dom.className + ' ').indexOf(' ' + v + ' ') == -1) {
						cls.push(v);
					}
				}
				if (cls.length) {
					me.dom.className += " " + cls.join(" ");
				}
			}
			return me;
		},

		/**
		* Removes one or more CSS classes from the element.
		* @param {String/Array} className The CSS class to remove, or an array of classes
		* @return {Ext.Element} this
		*/
		removeClass: function (className) {
			var me = this,
                i,
                idx,
                len,
                cls,
                elClasses;
			if (!Ext.isArray(className)) {
				className = [className];
			}
			if (me.dom && me.dom.className) {
				elClasses = me.dom.className.replace(trimRe, '').split(spacesRe);
				for (i = 0, len = className.length; i < len; i++) {
					cls = className[i];
					if (typeof cls == 'string') {
						cls = cls.replace(trimRe, '');
						idx = elClasses.indexOf(cls);
						if (idx != -1) {
							elClasses.splice(idx, 1);
						}
					}
				}
				me.dom.className = elClasses.join(" ");
			}
			return me;
		},

		/**
		* Adds one or more CSS classes to this element and removes the same class(es) from all siblings.
		* @param {String/Array} className The CSS class to add, or an array of classes
		* @return {Ext.Element} this
		*/
		radioClass: function (className) {
			var cn = this.dom.parentNode.childNodes,
                v,
                i,
                len;
			className = Ext.isArray(className) ? className : [className];
			for (i = 0, len = cn.length; i < len; i++) {
				v = cn[i];
				if (v && v.nodeType == 1) {
					Ext.fly(v, '_internal').removeClass(className);
				}
			};
			return this.addClass(className);
		},

		/**
		* Toggles the specified CSS class on this element (removes it if it already exists, otherwise adds it).
		* @param {String} className The CSS class to toggle
		* @return {Ext.Element} this
		*/
		toggleClass: function (className) {
			return this.hasClass(className) ? this.removeClass(className) : this.addClass(className);
		},

		/**
		* Checks if the specified CSS class exists on this element's DOM node.
		* @param {String} className The CSS class to check for
		* @return {Boolean} True if the class exists, else false
		*/
		hasClass: function (className) {
			return className && (' ' + this.dom.className + ' ').indexOf(' ' + className + ' ') != -1;
		},

		/**
		* Replaces a CSS class on the element with another.  If the old name does not exist, the new name will simply be added.
		* @param {String} oldClassName The CSS class to replace
		* @param {String} newClassName The replacement CSS class
		* @return {Ext.Element} this
		*/
		replaceClass: function (oldClassName, newClassName) {
			return this.removeClass(oldClassName).addClass(newClassName);
		},

		isStyle: function (style, val) {
			return this.getStyle(style) == val;
		},

		/**
		* Normalizes currentStyle and computedStyle.
		* @param {String} property The style property whose value is returned.
		* @return {String} The current value of the style property for this element.
		*/
		getStyle: function () {
			return view && view.getComputedStyle ?
                function (prop) {
                	var el = this.dom,
                        v,
                        cs,
                        out,
                        display,
                        wk = Ext.isWebKit,
                        display;

                	if (el == document) {
                		return null;
                	}
                	prop = chkCache(prop);
                	// Fix bug caused by this: https://bugs.webkit.org/show_bug.cgi?id=13343
                	if (wk && /marginRight/.test(prop)) {
                		display = this.getStyle('display');
                		el.style.display = 'inline-block';
                	}
                	out = (v = el.style[prop]) ? v :
                           (cs = view.getComputedStyle(el, "")) ? cs[prop] : null;

                	// Webkit returns rgb values for transparent.
                	if (wk) {
                		if (out == 'rgba(0, 0, 0, 0)') {
                			out = 'transparent';
                		} else if (display) {
                			el.style.display = display;
                		}
                	}
                	return out;
                } :
                function (prop) {
                	var el = this.dom,
                        m,
                        cs;

                	if (el == document) return null;
                	if (prop == 'opacity') {
                		if (el.style.filter.match) {
                			if (m = el.style.filter.match(opacityRe)) {
                				var fv = parseFloat(m[1]);
                				if (!isNaN(fv)) {
                					return fv ? fv / 100 : 0;
                				}
                			}
                		}
                		return 1;
                	}
                	prop = chkCache(prop);
                	return el.style[prop] || ((cs = el.currentStyle) ? cs[prop] : null);
                };
		} (),

		/**
		* Return the CSS color for the specified CSS attribute. rgb, 3 digit (like #fff) and valid values
		* are convert to standard 6 digit hex color.
		* @param {String} attr The css attribute
		* @param {String} defaultValue The default value to use when a valid color isn't found
		* @param {String} prefix (optional) defaults to #. Use an empty string when working with
		* color anims.
		*/
		getColor: function (attr, defaultValue, prefix) {
			var v = this.getStyle(attr),
                color = (typeof prefix != 'undefined') ? prefix : '#',
                h;

			if (!v || /transparent|inherit/.test(v)) {
				return defaultValue;
			}
			if (/^r/.test(v)) {
				Ext.each(v.slice(4, v.length - 1).split(','), function (s) {
					h = parseInt(s, 10);
					color += (h < 16 ? '0' : '') + h.toString(16);
				});
			} else {
				v = v.replace('#', '');
				color += v.length == 3 ? v.replace(/^(\w)(\w)(\w)$/, '$1$1$2$2$3$3') : v;
			}
			return (color.length > 5 ? color.toLowerCase() : defaultValue);
		},

		/**
		* Wrapper for setting style properties, also takes single object parameter of multiple styles.
		* @param {String/Object} property The style property to be set, or an object of multiple styles.
		* @param {String} value (optional) The value to apply to the given property, or null if an object was passed.
		* @return {Ext.Element} this
		*/
		setStyle: function (prop, value) {
			var tmp,
                style,
                camel;
			if (typeof prop != 'object') {
				tmp = {};
				tmp[prop] = value;
				prop = tmp;
			}
			for (style in prop) {
				value = prop[style];
				style == 'opacity' ?
                    this.setOpacity(value) :
                    this.dom.style[chkCache(style)] = value;
			}
			return this;
		},

		/**
		* Set the opacity of the element
		* @param {Float} opacity The new opacity. 0 = transparent, .5 = 50% visibile, 1 = fully visible, etc
		* @param {Boolean/Object} animate (optional) a standard Element animation config object or <tt>true</tt> for
		* the default animation (<tt>{duration: .35, easing: 'easeIn'}</tt>)
		* @return {Ext.Element} this
		*/
		setOpacity: function (opacity, animate) {
			var me = this,
                s = me.dom.style;

			if (!animate || !me.anim) {
				if (Ext.isIE) {
					var opac = opacity < 1 ? 'alpha(opacity=' + opacity * 100 + ')' : '',
                    val = s.filter.replace(opacityRe, '').replace(trimRe, '');

					s.zoom = 1;
					s.filter = val + (val.length > 0 ? ' ' : '') + opac;
				} else {
					s.opacity = opacity;
				}
			} else {
				me.anim({ opacity: { to: opacity} }, me.preanim(arguments, 1), null, .35, 'easeIn');
			}
			return me;
		},

		/**
		* Clears any opacity settings from this element. Required in some cases for IE.
		* @return {Ext.Element} this
		*/
		clearOpacity: function () {
			var style = this.dom.style;
			if (Ext.isIE) {
				if (!Ext.isEmpty(style.filter)) {
					style.filter = style.filter.replace(opacityRe, '').replace(trimRe, '');
				}
			} else {
				style.opacity = style['-moz-opacity'] = style['-khtml-opacity'] = '';
			}
			return this;
		},

		/**
		* Returns the offset height of the element
		* @param {Boolean} contentHeight (optional) true to get the height minus borders and padding
		* @return {Number} The element's height
		*/
		getHeight: function (contentHeight) {
			var me = this,
                dom = me.dom,
                hidden = Ext.isIE && me.isStyle('display', 'none'),
                h = MATH.max(dom.offsetHeight, hidden ? 0 : dom.clientHeight) || 0;

			h = !contentHeight ? h : h - me.getBorderWidth("tb") - me.getPadding("tb");
			return h < 0 ? 0 : h;
		},

		/**
		* Returns the offset width of the element
		* @param {Boolean} contentWidth (optional) true to get the width minus borders and padding
		* @return {Number} The element's width
		*/
		getWidth: function (contentWidth) {
			var me = this,
                dom = me.dom,
                hidden = Ext.isIE && me.isStyle('display', 'none'),
                w = MATH.max(dom.offsetWidth, hidden ? 0 : dom.clientWidth) || 0;
			w = !contentWidth ? w : w - me.getBorderWidth("lr") - me.getPadding("lr");
			return w < 0 ? 0 : w;
		},

		/**
		* Set the width of this Element.
		* @param {Mixed} width The new width. This may be one of:<div class="mdetail-params"><ul>
		* <li>A Number specifying the new width in this Element's {@link #defaultUnit}s (by default, pixels).</li>
		* <li>A String used to set the CSS width style. Animation may <b>not</b> be used.
		* </ul></div>
		* @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
		* @return {Ext.Element} this
		*/
		setWidth: function (width, animate) {
			var me = this;
			width = me.adjustWidth(width);
			!animate || !me.anim ?
                me.dom.style.width = me.addUnits(width) :
                me.anim({ width: { to: width} }, me.preanim(arguments, 1));
			return me;
		},

		/**
		* Set the height of this Element.
		* <pre><code>
		// change the height to 200px and animate with default configuration
		Ext.fly('elementId').setHeight(200, true);

		// change the height to 150px and animate with a custom configuration
		Ext.fly('elId').setHeight(150, {
		duration : .5, // animation will have a duration of .5 seconds
		// will change the content to "finished"
		callback: function(){ this.{@link #update}("finished"); }
		});
		* </code></pre>
		* @param {Mixed} height The new height. This may be one of:<div class="mdetail-params"><ul>
		* <li>A Number specifying the new height in this Element's {@link #defaultUnit}s (by default, pixels.)</li>
		* <li>A String used to set the CSS height style. Animation may <b>not</b> be used.</li>
		* </ul></div>
		* @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
		* @return {Ext.Element} this
		*/
		setHeight: function (height, animate) {
			var me = this;
			height = me.adjustHeight(height);
			!animate || !me.anim ?
                me.dom.style.height = me.addUnits(height) :
                me.anim({ height: { to: height} }, me.preanim(arguments, 1));
			return me;
		},

		/**
		* Gets the width of the border(s) for the specified side(s)
		* @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
		* passing <tt>'lr'</tt> would get the border <b><u>l</u></b>eft width + the border <b><u>r</u></b>ight width.
		* @return {Number} The width of the sides passed added together
		*/
		getBorderWidth: function (side) {
			return this.addStyles(side, borders);
		},

		/**
		* Gets the width of the padding(s) for the specified side(s)
		* @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
		* passing <tt>'lr'</tt> would get the padding <b><u>l</u></b>eft + the padding <b><u>r</u></b>ight.
		* @return {Number} The padding of the sides passed added together
		*/
		getPadding: function (side) {
			return this.addStyles(side, paddings);
		},

		/**
		*  Store the current overflow setting and clip overflow on the element - use <tt>{@link #unclip}</tt> to remove
		* @return {Ext.Element} this
		*/
		clip: function () {
			var me = this,
                dom = me.dom;

			if (!data(dom, ISCLIPPED)) {
				data(dom, ISCLIPPED, true);
				data(dom, ORIGINALCLIP, {
					o: me.getStyle(OVERFLOW),
					x: me.getStyle(OVERFLOWX),
					y: me.getStyle(OVERFLOWY)
				});
				me.setStyle(OVERFLOW, HIDDEN);
				me.setStyle(OVERFLOWX, HIDDEN);
				me.setStyle(OVERFLOWY, HIDDEN);
			}
			return me;
		},

		/**
		*  Return clipping (overflow) to original clipping before <tt>{@link #clip}</tt> was called
		* @return {Ext.Element} this
		*/
		unclip: function () {
			var me = this,
                dom = me.dom;

			if (data(dom, ISCLIPPED)) {
				data(dom, ISCLIPPED, false);
				var o = data(dom, ORIGINALCLIP);
				if (o.o) {
					me.setStyle(OVERFLOW, o.o);
				}
				if (o.x) {
					me.setStyle(OVERFLOWX, o.x);
				}
				if (o.y) {
					me.setStyle(OVERFLOWY, o.y);
				}
			}
			return me;
		},

		// private
		addStyles: function (sides, styles) {
			var ttlSize = 0,
                sidesArr = sides.match(wordsRe),
                side,
                size,
                i,
                len = sidesArr.length;
			for (i = 0; i < len; i++) {
				side = sidesArr[i];
				size = side && parseInt(this.getStyle(styles[side]), 10);
				if (size) {
					ttlSize += MATH.abs(size);
				}
			}
			return ttlSize;
		},

		margins: margins
	}
} ()
);
/**
* @class Ext.Element
*/

// special markup used throughout Ext when box wrapping elements
Ext.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>';

Ext.Element.addMethods(function () {
	var INTERNAL = "_internal",
        pxMatch = /(\d+\.?\d+)px/;
	return {
		/**
		* More flexible version of {@link #setStyle} for setting style properties.
		* @param {String/Object/Function} styles A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
		* a function which returns such a specification.
		* @return {Ext.Element} this
		*/
		applyStyles: function (style) {
			Ext.DomHelper.applyStyles(this.dom, style);
			return this;
		},

		/**
		* Returns an object with properties matching the styles requested.
		* For example, el.getStyles('color', 'font-size', 'width') might return
		* {'color': '#FFFFFF', 'font-size': '13px', 'width': '100px'}.
		* @param {String} style1 A style name
		* @param {String} style2 A style name
		* @param {String} etc.
		* @return {Object} The style object
		*/
		getStyles: function () {
			var ret = {};
			Ext.each(arguments, function (v) {
				ret[v] = this.getStyle(v);
			},
            this);
			return ret;
		},

		// private  ==> used by ext full
		setOverflow: function (v) {
			var dom = this.dom;
			if (v == 'auto' && Ext.isMac && Ext.isGecko2) { // work around stupid FF 2.0/Mac scroll bar bug
				dom.style.overflow = 'hidden';
				(function () { dom.style.overflow = 'auto'; }).defer(1);
			} else {
				dom.style.overflow = v;
			}
		},

		/**
		* <p>Wraps the specified element with a special 9 element markup/CSS block that renders by default as
		* a gray container with a gradient background, rounded corners and a 4-way shadow.</p>
		* <p>This special markup is used throughout Ext when box wrapping elements ({@link Ext.Button},
		* {@link Ext.Panel} when <tt>{@link Ext.Panel#frame frame=true}</tt>, {@link Ext.Window}).  The markup
		* is of this form:</p>
		* <pre><code>
		Ext.Element.boxMarkup =
		&#39;&lt;div class="{0}-tl">&lt;div class="{0}-tr">&lt;div class="{0}-tc">&lt;/div>&lt;/div>&lt;/div>
		&lt;div class="{0}-ml">&lt;div class="{0}-mr">&lt;div class="{0}-mc">&lt;/div>&lt;/div>&lt;/div>
		&lt;div class="{0}-bl">&lt;div class="{0}-br">&lt;div class="{0}-bc">&lt;/div>&lt;/div>&lt;/div>&#39;;
		* </code></pre>
		* <p>Example usage:</p>
		* <pre><code>
		// Basic box wrap
		Ext.get("foo").boxWrap();

		// You can also add a custom class and use CSS inheritance rules to customize the box look.
		// 'x-box-blue' is a built-in alternative -- look at the related CSS definitions as an example
		// for how to create a custom box wrap style.
		Ext.get("foo").boxWrap().addClass("x-box-blue");
		* </code></pre>
		* @param {String} class (optional) A base CSS class to apply to the containing wrapper element
		* (defaults to <tt>'x-box'</tt>). Note that there are a number of CSS rules that are dependent on
		* this name to make the overall effect work, so if you supply an alternate base class, make sure you
		* also supply all of the necessary rules.
		* @return {Ext.Element} The outermost wrapping element of the created box structure.
		*/
		boxWrap: function (cls) {
			cls = cls || 'x-box';
			var el = Ext.get(this.insertHtml("beforeBegin", "<div class='" + cls + "'>" + String.format(Ext.Element.boxMarkup, cls) + "</div>"));        //String.format('<div class="{0}">'+Ext.Element.boxMarkup+'</div>', cls)));
			Ext.DomQuery.selectNode('.' + cls + '-mc', el.dom).appendChild(this.dom);
			return el;
		},

		/**
		* Set the size of this Element. If animation is true, both width and height will be animated concurrently.
		* @param {Mixed} width The new width. This may be one of:<div class="mdetail-params"><ul>
		* <li>A Number specifying the new width in this Element's {@link #defaultUnit}s (by default, pixels).</li>
		* <li>A String used to set the CSS width style. Animation may <b>not</b> be used.
		* <li>A size object in the format <code>{width: widthValue, height: heightValue}</code>.</li>
		* </ul></div>
		* @param {Mixed} height The new height. This may be one of:<div class="mdetail-params"><ul>
		* <li>A Number specifying the new height in this Element's {@link #defaultUnit}s (by default, pixels).</li>
		* <li>A String used to set the CSS height style. Animation may <b>not</b> be used.</li>
		* </ul></div>
		* @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
		* @return {Ext.Element} this
		*/
		setSize: function (width, height, animate) {
			var me = this;
			if (typeof width == 'object') { // in case of object from getSize()
				height = width.height;
				width = width.width;
			}
			width = me.adjustWidth(width);
			height = me.adjustHeight(height);
			if (!animate || !me.anim) {
				me.dom.style.width = me.addUnits(width);
				me.dom.style.height = me.addUnits(height);
			} else {
				me.anim({ width: { to: width }, height: { to: height} }, me.preanim(arguments, 2));
			}
			return me;
		},

		/**
		* Returns either the offsetHeight or the height of this element based on CSS height adjusted by padding or borders
		* when needed to simulate offsetHeight when offsets aren't available. This may not work on display:none elements
		* if a height has not been set using CSS.
		* @return {Number}
		*/
		getComputedHeight: function () {
			var me = this,
                h = Math.max(me.dom.offsetHeight, me.dom.clientHeight);
			if (!h) {
				h = parseFloat(me.getStyle('height')) || 0;
				if (!me.isBorderBox()) {
					h += me.getFrameWidth('tb');
				}
			}
			return h;
		},

		/**
		* Returns either the offsetWidth or the width of this element based on CSS width adjusted by padding or borders
		* when needed to simulate offsetWidth when offsets aren't available. This may not work on display:none elements
		* if a width has not been set using CSS.
		* @return {Number}
		*/
		getComputedWidth: function () {
			var w = Math.max(this.dom.offsetWidth, this.dom.clientWidth);
			if (!w) {
				w = parseFloat(this.getStyle('width')) || 0;
				if (!this.isBorderBox()) {
					w += this.getFrameWidth('lr');
				}
			}
			return w;
		},

		/**
		* Returns the sum width of the padding and borders for the passed "sides". See getBorderWidth()
		for more information about the sides.
		* @param {String} sides
		* @return {Number}
		*/
		getFrameWidth: function (sides, onlyContentBox) {
			return onlyContentBox && this.isBorderBox() ? 0 : (this.getPadding(sides) + this.getBorderWidth(sides));
		},

		/**
		* Sets up event handlers to add and remove a css class when the mouse is over this element
		* @param {String} className
		* @return {Ext.Element} this
		*/
		addClassOnOver: function (className) {
			this.hover(
                function () {
                	Ext.fly(this, INTERNAL).addClass(className);
                },
                function () {
                	Ext.fly(this, INTERNAL).removeClass(className);
                }
            );
			return this;
		},

		/**
		* Sets up event handlers to add and remove a css class when this element has the focus
		* @param {String} className
		* @return {Ext.Element} this
		*/
		addClassOnFocus: function (className) {
			this.on("focus", function () {
				Ext.fly(this, INTERNAL).addClass(className);
			}, this.dom);
			this.on("blur", function () {
				Ext.fly(this, INTERNAL).removeClass(className);
			}, this.dom);
			return this;
		},

		/**
		* 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)
		* @param {String} className
		* @return {Ext.Element} this
		*/
		addClassOnClick: function (className) {
			var dom = this.dom;
			this.on("mousedown", function () {
				Ext.fly(dom, INTERNAL).addClass(className);
				var d = Ext.getDoc(),
                    fn = function () {
                    	Ext.fly(dom, INTERNAL).removeClass(className);
                    	d.removeListener("mouseup", fn);
                    };
				d.on("mouseup", fn);
			});
			return this;
		},

		/**
		* <p>Returns the dimensions of the element available to lay content out in.<p>
		* <p>If the element (or any ancestor element) has CSS style <code>display : none</code>, the dimensions will be zero.</p>
		* example:<pre><code>
		var vpSize = Ext.getBody().getViewSize();

		// all Windows created afterwards will have a default value of 90% height and 95% width
		Ext.Window.override({
		width: vpSize.width * 0.9,
		height: vpSize.height * 0.95
		});
		// To handle window resizing you would have to hook onto onWindowResize.
		* </code></pre>
		*
		* getViewSize utilizes clientHeight/clientWidth which excludes sizing of scrollbars.
		* To obtain the size including scrollbars, use getStyleSize
		*
		* Sizing of the document body is handled at the adapter level which handles special cases for IE and strict modes, etc.
		*/

		getViewSize: function () {
			var doc = document,
                d = this.dom,
                isDoc = (d == doc || d == doc.body);

			// If the body, use Ext.lib.Dom
			if (isDoc) {
				var extdom = Ext.lib.Dom;
				return {
					width: extdom.getViewWidth(),
					height: extdom.getViewHeight()
				};

				// Else use clientHeight/clientWidth
			} else {
				return {
					width: d.clientWidth,
					height: d.clientHeight
				}
			}
		},

		/**
		* <p>Returns the dimensions of the element available to lay content out in.<p>
		*
		* getStyleSize utilizes prefers style sizing if present, otherwise it chooses the larger of offsetHeight/clientHeight and offsetWidth/clientWidth.
		* To obtain the size excluding scrollbars, use getViewSize
		*
		* Sizing of the document body is handled at the adapter level which handles special cases for IE and strict modes, etc.
		*/

		getStyleSize: function () {
			var me = this,
                w, h,
                doc = document,
                d = this.dom,
                isDoc = (d == doc || d == doc.body),
                s = d.style;

			// If the body, use Ext.lib.Dom
			if (isDoc) {
				var extdom = Ext.lib.Dom;
				return {
					width: extdom.getViewWidth(),
					height: extdom.getViewHeight()
				}
			}
			// Use Styles if they are set
			if (s.width && s.width != 'auto') {
				w = parseFloat(s.width);
				if (me.isBorderBox()) {
					w -= me.getFrameWidth('lr');
				}
			}
			// Use Styles if they are set
			if (s.height && s.height != 'auto') {
				h = parseFloat(s.height);
				if (me.isBorderBox()) {
					h -= me.getFrameWidth('tb');
				}
			}
			// Use getWidth/getHeight if style not set.
			return { width: w || me.getWidth(true), height: h || me.getHeight(true) };
		},

		/**
		* Returns the size of the element.
		* @param {Boolean} contentSize (optional) true to get the width/size minus borders and padding
		* @return {Object} An object containing the element's size {width: (element width), height: (element height)}
		*/
		getSize: function (contentSize) {
			return { width: this.getWidth(contentSize), height: this.getHeight(contentSize) };
		},

		/**
		* Forces the browser to repaint this element
		* @return {Ext.Element} this
		*/
		repaint: function () {
			var dom = this.dom;
			this.addClass("x-repaint");
			setTimeout(function () {
				Ext.fly(dom).removeClass("x-repaint");
			}, 1);
			return this;
		},

		/**
		* Disables text selection for this element (normalized across browsers)
		* @return {Ext.Element} this
		*/
		unselectable: function () {
			this.dom.unselectable = "on";
			return this.swallowEvent("selectstart", true).
                        applyStyles("-moz-user-select:none;-khtml-user-select:none;").
                        addClass("x-unselectable");
		},

		/**
		* Returns an object with properties top, left, right and bottom representing the margins of this element unless sides is passed,
		* then it returns the calculated width of the sides (see getPadding)
		* @param {String} sides (optional) Any combination of l, r, t, b to get the sum of those sides
		* @return {Object/Number}
		*/
		getMargins: function (side) {
			var me = this,
                key,
                hash = { t: "top", l: "left", r: "right", b: "bottom" },
                o = {};

			if (!side) {
				for (key in me.margins) {
					o[hash[key]] = parseFloat(me.getStyle(me.margins[key])) || 0;
				}
				return o;
			} else {
				return me.addStyles.call(me, side, me.margins);
			}
		}
	};
} ());
/**
* @class Ext.Element
*/
(function () {
	var D = Ext.lib.Dom,
        LEFT = "left",
        RIGHT = "right",
        TOP = "top",
        BOTTOM = "bottom",
        POSITION = "position",
        STATIC = "static",
        RELATIVE = "relative",
        AUTO = "auto",
        ZINDEX = "z-index";

	Ext.Element.addMethods({
		/**
		* 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).
		* @return {Number} The X position of the element
		*/
		getX: function () {
			return D.getX(this.dom);
		},

		/**
		* 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).
		* @return {Number} The Y position of the element
		*/
		getY: function () {
			return D.getY(this.dom);
		},

		/**
		* 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).
		* @return {Array} The XY position of the element
		*/
		getXY: function () {
			return D.getXY(this.dom);
		},

		/**
		* 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.
		* @param {Mixed} element The element to get the offsets from.
		* @return {Array} The XY page offsets (e.g. [100, -200])
		*/
		getOffsetsTo: function (el) {
			var o = this.getXY(),
        	e = Ext.fly(el, '_internal').getXY();
			return [o[0] - e[0], o[1] - e[1]];
		},

		/**
		* 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).
		* @param {Number} The X position of the element
		* @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
		* @return {Ext.Element} this
		*/
		setX: function (x, animate) {
			return this.setXY([x, this.getY()], this.animTest(arguments, animate, 1));
		},

		/**
		* 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).
		* @param {Number} The Y position of the element
		* @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
		* @return {Ext.Element} this
		*/
		setY: function (y, animate) {
			return this.setXY([this.getX(), y], this.animTest(arguments, animate, 1));
		},

		/**
		* Sets the element's left position directly using CSS style (instead of {@link #setX}).
		* @param {String} left The left CSS property value
		* @return {Ext.Element} this
		*/
		setLeft: function (left) {
			this.setStyle(LEFT, this.addUnits(left));
			return this;
		},

		/**
		* Sets the element's top position directly using CSS style (instead of {@link #setY}).
		* @param {String} top The top CSS property value
		* @return {Ext.Element} this
		*/
		setTop: function (top) {
			this.setStyle(TOP, this.addUnits(top));
			return this;
		},

		/**
		* Sets the element's CSS right style.
		* @param {String} right The right CSS property value
		* @return {Ext.Element} this
		*/
		setRight: function (right) {
			this.setStyle(RIGHT, this.addUnits(right));
			return this;
		},

		/**
		* Sets the element's CSS bottom style.
		* @param {String} bottom The bottom CSS property value
		* @return {Ext.Element} this
		*/
		setBottom: function (bottom) {
			this.setStyle(BOTTOM, this.addUnits(bottom));
			return this;
		},

		/**
		* Sets the position of the element in page coordinates, regardless of how the element is positioned.
		* The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
		* @param {Array} pos Contains X & Y [x, y] values for new position (coordinates are page-based)
		* @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
		* @return {Ext.Element} this
		*/
		setXY: function (pos, animate) {
			var me = this;
			if (!animate || !me.anim) {
				D.setXY(me.dom, pos);
			} else {
				me.anim({ points: { to: pos} }, me.preanim(arguments, 1), 'motion');
			}
			return me;
		},

		/**
		* Sets the position of the element in page coordinates, regardless of how the element is positioned.
		* The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
		* @param {Number} x X value for new position (coordinates are page-based)
		* @param {Number} y Y value for new position (coordinates are page-based)
		* @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
		* @return {Ext.Element} this
		*/
		setLocation: function (x, y, animate) {
			return this.setXY([x, y], this.animTest(arguments, animate, 2));
		},

		/**
		* Sets the position of the element in page coordinates, regardless of how the element is positioned.
		* The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
		* @param {Number} x X value for new position (coordinates are page-based)
		* @param {Number} y Y value for new position (coordinates are page-based)
		* @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
		* @return {Ext.Element} this
		*/
		moveTo: function (x, y, animate) {
			return this.setXY([x, y], this.animTest(arguments, animate, 2));
		},

		/**
		* Gets the left X coordinate
		* @param {Boolean} local True to get the local css position instead of page coordinate
		* @return {Number}
		*/
		getLeft: function (local) {
			return !local ? this.getX() : parseInt(this.getStyle(LEFT), 10) || 0;
		},

		/**
		* Gets the right X coordinate of the element (element X position + element width)
		* @param {Boolean} local True to get the local css position instead of page coordinate
		* @return {Number}
		*/
		getRight: function (local) {
			var me = this;
			return !local ? me.getX() + me.getWidth() : (me.getLeft(true) + me.getWidth()) || 0;
		},

		/**
		* Gets the top Y coordinate
		* @param {Boolean} local True to get the local css position instead of page coordinate
		* @return {Number}
		*/
		getTop: function (local) {
			return !local ? this.getY() : parseInt(this.getStyle(TOP), 10) || 0;
		},

		/**
		* Gets the bottom Y coordinate of the element (element Y position + element height)
		* @param {Boolean} local True to get the local css position instead of page coordinate
		* @return {Number}
		*/
		getBottom: function (local) {
			var me = this;
			return !local ? me.getY() + me.getHeight() : (me.getTop(true) + me.getHeight()) || 0;
		},

		/**
		* Initializes positioning on this element. If a desired position is not passed, it will make the
		* the element positioned relative IF it is not already positioned.
		* @param {String} pos (optional) Positioning to use "relative", "absolute" or "fixed"
		* @param {Number} zIndex (optional) The zIndex to apply
		* @param {Number} x (optional) Set the page X position
		* @param {Number} y (optional) Set the page Y position
		*/
		position: function (pos, zIndex, x, y) {
			var me = this;

			if (!pos && me.isStyle(POSITION, STATIC)) {
				me.setStyle(POSITION, RELATIVE);
			} else if (pos) {
				me.setStyle(POSITION, pos);
			}
			if (zIndex) {
				me.setStyle(ZINDEX, zIndex);
			}
			if (x || y) me.setXY([x || false, y || false]);
		},

		/**
		* Clear positioning back to the default when the document was loaded
		* @param {String} value (optional) The value to use for the left,right,top,bottom, defaults to '' (empty string). You could use 'auto'.
		* @return {Ext.Element} this
		*/
		clearPositioning: function (value) {
			value = value || '';
			this.setStyle({
				left: value,
				right: value,
				top: value,
				bottom: value,
				"z-index": "",
				position: STATIC
			});
			return this;
		},

		/**
		* Gets an object with all CSS positioning properties. Useful along with setPostioning to get
		* snapshot before performing an update and then restoring the element.
		* @return {Object}
		*/
		getPositioning: function () {
			var l = this.getStyle(LEFT);
			var t = this.getStyle(TOP);
			return {
				"position": this.getStyle(POSITION),
				"left": l,
				"right": l ? "" : this.getStyle(RIGHT),
				"top": t,
				"bottom": t ? "" : this.getStyle(BOTTOM),
				"z-index": this.getStyle(ZINDEX)
			};
		},

		/**
		* Set positioning with an object returned by getPositioning().
		* @param {Object} posCfg
		* @return {Ext.Element} this
		*/
		setPositioning: function (pc) {
			var me = this,
	    	style = me.dom.style;

			me.setStyle(pc);

			if (pc.right == AUTO) {
				style.right = "";
			}
			if (pc.bottom == AUTO) {
				style.bottom = "";
			}

			return me;
		},

		/**
		* Translates the passed page coordinates into left/top css values for this element
		* @param {Number/Array} x The page x or an array containing [x, y]
		* @param {Number} y (optional) The page y, required if x is not an array
		* @return {Object} An object with left and top properties. e.g. {left: (value), top: (value)}
		*/
		translatePoints: function (x, y) {
			y = isNaN(x[1]) ? y : x[1];
			x = isNaN(x[0]) ? x : x[0];
			var me = this,
        	relative = me.isStyle(POSITION, RELATIVE),
        	o = me.getXY(),
        	l = parseInt(me.getStyle(LEFT), 10),
        	t = parseInt(me.getStyle(TOP), 10);

			l = !isNaN(l) ? l : (relative ? 0 : me.dom.offsetLeft);
			t = !isNaN(t) ? t : (relative ? 0 : me.dom.offsetTop);

			return { left: (x - o[0] + l), top: (y - o[1] + t) };
		},

		animTest: function (args, animate, i) {
			return !!animate && this.preanim ? this.preanim(args, i) : false;
		}
	});
})(); /**
 * @class Ext.Element
 */
Ext.Element.addMethods({
	/**
	* 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.
	* @param {Object} box The box to fill {x, y, width, height}
	* @param {Boolean} adjust (optional) Whether to adjust for box-model issues automatically
	* @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
	* @return {Ext.Element} this
	*/
	setBox: function (box, adjust, animate) {
		var me = this,
        	w = box.width,
        	h = box.height;
		if ((adjust && !me.autoBoxAdjust) && !me.isBorderBox()) {
			w -= (me.getBorderWidth("lr") + me.getPadding("lr"));
			h -= (me.getBorderWidth("tb") + me.getPadding("tb"));
		}
		me.setBounds(box.x, box.y, w, h, me.animTest.call(me, arguments, animate, 2));
		return me;
	},

	/**
	* Return an object defining the area of this Element which can be passed to {@link #setBox} to
	* set another Element's size/location to match this element.
	* @param {Boolean} contentBox (optional) If true a box for the content of the element is returned.
	* @param {Boolean} local (optional) If true the element's left and top are returned instead of page x/y.
	* @return {Object} box An object in the format<pre><code>
	{
	x: &lt;Element's X position>,
	y: &lt;Element's Y position>,
	width: &lt;Element's width>,
	height: &lt;Element's height>,
	bottom: &lt;Element's lower bound>,
	right: &lt;Element's rightmost bound>
	}
	</code></pre>
	* The returned object may also be addressed as an Array where index 0 contains the X position
	* and index 1 contains the Y position. So the result may also be used for {@link #setXY}
	*/
	getBox: function (contentBox, local) {
		var me = this,
        	xy,
        	left,
        	top,
        	getBorderWidth = me.getBorderWidth,
        	getPadding = me.getPadding,
        	l,
        	r,
        	t,
        	b;
		if (!local) {
			xy = me.getXY();
		} else {
			left = parseInt(me.getStyle("left"), 10) || 0;
			top = parseInt(me.getStyle("top"), 10) || 0;
			xy = [left, top];
		}
		var el = me.dom, w = el.offsetWidth, h = el.offsetHeight, bx;
		if (!contentBox) {
			bx = { x: xy[0], y: xy[1], 0: xy[0], 1: xy[1], width: w, height: h };
		} else {
			l = getBorderWidth.call(me, "l") + getPadding.call(me, "l");
			r = getBorderWidth.call(me, "r") + getPadding.call(me, "r");
			t = getBorderWidth.call(me, "t") + getPadding.call(me, "t");
			b = getBorderWidth.call(me, "b") + getPadding.call(me, "b");
			bx = { x: xy[0] + l, y: xy[1] + t, 0: xy[0] + l, 1: xy[1] + t, width: w - (l + r), height: h - (t + b) };
		}
		bx.right = bx.x + bx.width;
		bx.bottom = bx.y + bx.height;
		return bx;
	},

	/**
	* Move this element relative to its current position.
	* @param {String} direction Possible values are: "l" (or "left"), "r" (or "right"), "t" (or "top", or "up"), "b" (or "bottom", or "down").
	* @param {Number} distance How far to move the element in pixels
	* @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
	* @return {Ext.Element} this
	*/
	move: function (direction, distance, animate) {
		var me = this,
        	xy = me.getXY(),
        	x = xy[0],
        	y = xy[1],
        	left = [x - distance, y],
        	right = [x + distance, y],
        	top = [x, y - distance],
        	bottom = [x, y + distance],
	       	hash = {
	       		l: left,
	       		left: left,
	       		r: right,
	       		right: right,
	       		t: top,
	       		top: top,
	       		up: top,
	       		b: bottom,
	       		bottom: bottom,
	       		down: bottom
	       	};

		direction = direction.toLowerCase();
		me.moveTo(hash[direction][0], hash[direction][1], me.animTest.call(me, arguments, animate, 2));
	},

	/**
	* Quick set left and top adding default units
	* @param {String} left The left CSS property value
	* @param {String} top The top CSS property value
	* @return {Ext.Element} this
	*/
	setLeftTop: function (left, top) {
		var me = this,
	    	style = me.dom.style;
		style.left = me.addUnits(left);
		style.top = me.addUnits(top);
		return me;
	},

	/**
	* Returns the region of the given element.
	* The element must be part of the DOM tree to have a region (display:none or elements not appended return false).
	* @return {Region} A Ext.lib.Region containing "top, left, bottom, right" member data.
	*/
	getRegion: function () {
		return Ext.lib.Dom.getRegion(this.dom);
	},

	/**
	* Sets the element's position and size in one shot. If animation is true then width, height, x and y will be animated concurrently.
	* @param {Number} x X value for new position (coordinates are page-based)
	* @param {Number} y Y value for new position (coordinates are page-based)
	* @param {Mixed} width The new width. This may be one of:<div class="mdetail-params"><ul>
	* <li>A Number specifying the new width in this Element's {@link #defaultUnit}s (by default, pixels)</li>
	* <li>A String used to set the CSS width style. Animation may <b>not</b> be used.
	* </ul></div>
	* @param {Mixed} height The new height. This may be one of:<div class="mdetail-params"><ul>
	* <li>A Number specifying the new height in this Element's {@link #defaultUnit}s (by default, pixels)</li>
	* <li>A String used to set the CSS height style. Animation may <b>not</b> be used.</li>
	* </ul></div>
	* @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
	* @return {Ext.Element} this
	*/
	setBounds: function (x, y, width, height, animate) {
		var me = this;
		if (!animate || !me.anim) {
			me.setSize(width, height);
			me.setLocation(x, y);
		} else {
			me.anim({ points: { to: [x, y] },
				width: { to: me.adjustWidth(width) },
				height: { to: me.adjustHeight(height)}
			},
                     me.preanim(arguments, 4),
                     'motion');
		}
		return me;
	},

	/**
	* Sets the element's position and size the specified region. If animation is true then width, height, x and y will be animated concurrently.
	* @param {Ext.lib.Region} region The region to fill
	* @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
	* @return {Ext.Element} this
	*/
	setRegion: function (region, animate) {
		return this.setBounds(region.left, region.top, region.right - region.left, region.bottom - region.top, this.animTest.call(this, arguments, animate, 1));
	}
}); /**
 * @class Ext.Element
 */
Ext.Element.addMethods({
	/**
	* Returns true if this element is scrollable.
	* @return {Boolean}
	*/
	isScrollable: function () {
		var dom = this.dom;
		return dom.scrollHeight > dom.clientHeight || dom.scrollWidth > dom.clientWidth;
	},

	/**
	* 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().
	* @param {String} side Either "left" for scrollLeft values or "top" for scrollTop values.
	* @param {Number} value The new scroll value.
	* @return {Element} this
	*/
	scrollTo: function (side, value) {
		this.dom["scroll" + (/top/i.test(side) ? "Top" : "Left")] = value;
		return this;
	},

	/**
	* Returns the current scroll position of the element.
	* @return {Object} An object containing the scroll position in the format {left: (scrollLeft), top: (scrollTop)}
	*/
	getScroll: function () {
		var d = this.dom,
            doc = document,
            body = doc.body,
            docElement = doc.documentElement,
            l,
            t,
            ret;

		if (d == doc || d == body) {
			if (Ext.isIE && Ext.isStrict) {
				l = docElement.scrollLeft;
				t = docElement.scrollTop;
			} else {
				l = window.pageXOffset;
				t = window.pageYOffset;
			}
			ret = { left: l || (body ? body.scrollLeft : 0), top: t || (body ? body.scrollTop : 0) };
		} else {
			ret = { left: d.scrollLeft, top: d.scrollTop };
		}
		return ret;
	}
}); /**
 * @class Ext.Element
 */
Ext.Element.addMethods({
	/**
	* 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().
	* @param {String} side Either "left" for scrollLeft values or "top" for scrollTop values.
	* @param {Number} value The new scroll value
	* @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
	* @return {Element} this
	*/
	scrollTo: function (side, value, animate) {
		var top = /top/i.test(side), //check if we're scrolling top or left
        	me = this,
        	dom = me.dom,
            prop;
		if (!animate || !me.anim) {
			prop = 'scroll' + (top ? 'Top' : 'Left'), // just setting the value, so grab the direction
            dom[prop] = value;
		} else {
			prop = 'scroll' + (top ? 'Left' : 'Top'), // if scrolling top, we need to grab scrollLeft, if left, scrollTop
            me.anim({ scroll: { to: top ? [dom[prop], value] : [value, dom[prop]]} },
            		 me.preanim(arguments, 2), 'scroll');
		}
		return me;
	},

	/**
	* Scrolls this element into view within the passed container.
	* @param {Mixed} container (optional) The container element to scroll (defaults to document.body).  Should be a
	* string (id), dom node, or Ext.Element.
	* @param {Boolean} hscroll (optional) False to disable horizontal scroll (defaults to true)
	* @return {Ext.Element} this
	*/
	scrollIntoView: function (container, hscroll) {
		var c = Ext.getDom(container) || Ext.getBody().dom,
        	el = this.dom,
        	o = this.getOffsetsTo(c),
            l = o[0] + c.scrollLeft,
            t = o[1] + c.scrollTop,
            b = t + el.offsetHeight,
            r = l + el.offsetWidth,
        	ch = c.clientHeight,
        	ct = parseInt(c.scrollTop, 10),
        	cl = parseInt(c.scrollLeft, 10),
        	cb = ct + ch,
        	cr = cl + c.clientWidth;

		if (el.offsetHeight > ch || t < ct) {
			c.scrollTop = t;
		} else if (b > cb) {
			c.scrollTop = b - ch;
		}
		c.scrollTop = c.scrollTop; // corrects IE, other browsers will ignore

		if (hscroll !== false) {
			if (el.offsetWidth > c.clientWidth || l < cl) {
				c.scrollLeft = l;
			} else if (r > cr) {
				c.scrollLeft = r - c.clientWidth;
			}
			c.scrollLeft = c.scrollLeft;
		}
		return this;
	},

	// private
	scrollChildIntoView: function (child, hscroll) {
		Ext.fly(child, '_scrollChildIntoView').scrollIntoView(this, hscroll);
	},

	/**
	* Scrolls this element the specified direction. Does bounds checking to make sure the scroll is
	* within this element's scrollable range.
	* @param {String} direction Possible values are: "l" (or "left"), "r" (or "right"), "t" (or "top", or "up"), "b" (or "bottom", or "down").
	* @param {Number} distance How far to scroll the element in pixels
	* @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
	* @return {Boolean} Returns true if a scroll was triggered or false if the element
	* was scrolled as far as it could go.
	*/
	scroll: function (direction, distance, animate) {
		if (!this.isScrollable()) {
			return;
		}
		var el = this.dom,
            l = el.scrollLeft, t = el.scrollTop,
            w = el.scrollWidth, h = el.scrollHeight,
            cw = el.clientWidth, ch = el.clientHeight,
            scrolled = false, v,
            hash = {
            	l: Math.min(l + distance, w - cw),
            	r: v = Math.max(l - distance, 0),
            	t: Math.max(t - distance, 0),
            	b: Math.min(t + distance, h - ch)
            };
		hash.d = hash.b;
		hash.u = hash.t;

		direction = direction.substr(0, 1);
		if ((v = hash[direction]) > -1) {
			scrolled = true;
			this.scrollTo(direction == 'l' || direction == 'r' ? 'left' : 'top', v, this.preanim(arguments, 2));
		}
		return scrolled;
	}
}); /**
 * @class Ext.Element
 */
/**
* Visibility mode constant for use with {@link #setVisibilityMode}. Use visibility to hide element
* @static
* @type Number
*/
Ext.Element.VISIBILITY = 1;
/**
* Visibility mode constant for use with {@link #setVisibilityMode}. Use display to hide element
* @static
* @type Number
*/
Ext.Element.DISPLAY = 2;

Ext.Element.addMethods(function () {
	var VISIBILITY = "visibility",
        DISPLAY = "display",
        HIDDEN = "hidden",
        OFFSETS = "offsets",
        NONE = "none",
        ORIGINALDISPLAY = 'originalDisplay',
        VISMODE = 'visibilityMode',
        ELDISPLAY = Ext.Element.DISPLAY,
        data = Ext.Element.data,
        getDisplay = function (dom) {
        	var d = data(dom, ORIGINALDISPLAY);
        	if (d === undefined) {
        		data(dom, ORIGINALDISPLAY, d = '');
        	}
        	return d;
        },
        getVisMode = function (dom) {
        	var m = data(dom, VISMODE);
        	if (m === undefined) {
        		data(dom, VISMODE, m = 1);
        	}
        	return m;
        };

	return {
		/**
		* The element's default display mode  (defaults to "")
		* @type String
		*/
		originalDisplay: "",
		visibilityMode: 1,

		/**
		* Sets the element's visibility mode. When setVisible() is called it
		* will use this to determine whether to set the visibility or the display property.
		* @param {Number} visMode Ext.Element.VISIBILITY or Ext.Element.DISPLAY
		* @return {Ext.Element} this
		*/
		setVisibilityMode: function (visMode) {
			data(this.dom, VISMODE, visMode);
			return this;
		},

		/**
		* Perform custom animation on this element.
		* <div><ul class="mdetail-params">
		* <li><u>Animation Properties</u></li>
		*
		* <p>The Animation Control Object enables gradual transitions for any member of an
		* element's style object that takes a numeric value including but not limited to
		* these properties:</p><div><ul class="mdetail-params">
		* <li><tt>bottom, top, left, right</tt></li>
		* <li><tt>height, width</tt></li>
		* <li><tt>margin, padding</tt></li>
		* <li><tt>borderWidth</tt></li>
		* <li><tt>opacity</tt></li>
		* <li><tt>fontSize</tt></li>
		* <li><tt>lineHeight</tt></li>
		* </ul></div>
		*
		*
		* <li><u>Animation Property Attributes</u></li>
		*
		* <p>Each Animation Property is a config object with optional properties:</p>
		* <div><ul class="mdetail-params">
		* <li><tt>by</tt>*  : relative change - start at current value, change by this value</li>
		* <li><tt>from</tt> : ignore current value, start from this value</li>
		* <li><tt>to</tt>*  : start at current value, go to this value</li>
		* <li><tt>unit</tt> : any allowable unit specification</li>
		* <p>* do not specify both <tt>to</tt> and <tt>by</tt> for an animation property</p>
		* </ul></div>
		*
		* <li><u>Animation Types</u></li>
		*
		* <p>The supported animation types:</p><div><ul class="mdetail-params">
		* <li><tt>'run'</tt> : Default
		* <pre><code>
		var el = Ext.get('complexEl');
		el.animate(
		// animation control object
		{
		borderWidth: {to: 3, from: 0},
		opacity: {to: .3, from: 1},
		height: {to: 50, from: el.getHeight()},
		width: {to: 300, from: el.getWidth()},
		top  : {by: - 100, unit: 'px'},
		},
		0.35,      // animation duration
		null,      // callback
		'easeOut', // easing method
		'run'      // animation type ('run','color','motion','scroll')
		);
		* </code></pre>
		* </li>
		* <li><tt>'color'</tt>
		* <p>Animates transition of background, text, or border colors.</p>
		* <pre><code>
		el.animate(
		// animation control object
		{
		color: { to: '#06e' },
		backgroundColor: { to: '#e06' }
		},
		0.35,      // animation duration
		null,      // callback
		'easeOut', // easing method
		'color'    // animation type ('run','color','motion','scroll')
		);
		* </code></pre>
		* </li>
		*
		* <li><tt>'motion'</tt>
		* <p>Animates the motion of an element to/from specific points using optional bezier
		* way points during transit.</p>
		* <pre><code>
		el.animate(
		// animation control object
		{
		borderWidth: {to: 3, from: 0},
		opacity: {to: .3, from: 1},
		height: {to: 50, from: el.getHeight()},
		width: {to: 300, from: el.getWidth()},
		top  : {by: - 100, unit: 'px'},
		points: {
		to: [50, 100],  // go to this point
		control: [      // optional bezier way points
		[ 600, 800],
		[-100, 200]
		]
		}
		},
		3000,      // animation duration (milliseconds!)
		null,      // callback
		'easeOut', // easing method
		'motion'   // animation type ('run','color','motion','scroll')
		);
		* </code></pre>
		* </li>
		* <li><tt>'scroll'</tt>
		* <p>Animate horizontal or vertical scrolling of an overflowing page element.</p>
		* <pre><code>
		el.animate(
		// animation control object
		{
		scroll: {to: [400, 300]}
		},
		0.35,      // animation duration
		null,      // callback
		'easeOut', // easing method
		'scroll'   // animation type ('run','color','motion','scroll')
		);
		* </code></pre>
		* </li>
		* </ul></div>
		*
		* </ul></div>
		*
		* @param {Object} args The animation control args
		* @param {Float} duration (optional) How long the animation lasts in seconds (defaults to <tt>.35</tt>)
		* @param {Function} onComplete (optional) Function to call when animation completes
		* @param {String} easing (optional) {@link Ext.Fx#easing} method to use (defaults to <tt>'easeOut'</tt>)
		* @param {String} animType (optional) <tt>'run'</tt> is the default. Can also be <tt>'color'</tt>,
		* <tt>'motion'</tt>, or <tt>'scroll'</tt>
		* @return {Ext.Element} this
		*/
		animate: function (args, duration, onComplete, easing, animType) {
			this.anim(args, { duration: duration, callback: onComplete, easing: easing }, animType);
			return this;
		},

		/*
		* @private Internal animation call
		*/
		anim: function (args, opt, animType, defaultDur, defaultEase, cb) {
			animType = animType || 'run';
			opt = opt || {};
			var me = this,
                anim = Ext.lib.Anim[animType](
                    me.dom,
                    args,
                    (opt.duration || defaultDur) || .35,
                    (opt.easing || defaultEase) || 'easeOut',
                    function () {
                    	if (cb) cb.call(me);
                    	if (opt.callback) opt.callback.call(opt.scope || me, me, opt);
                    },
                    me
                );
			opt.anim = anim;
			return anim;
		},

		// private legacy anim prep
		preanim: function (a, i) {
			return !a[i] ? false : (typeof a[i] == 'object' ? a[i] : { duration: a[i + 1], callback: a[i + 2], easing: a[i + 3] });
		},

		/**
		* Checks whether the element is currently visible using both visibility and display properties.
		* @return {Boolean} True if the element is currently visible, else false
		*/
		isVisible: function () {
			return !this.isStyle(VISIBILITY, HIDDEN) && !this.isStyle(DISPLAY, NONE);
		},

		/**
		* Sets the visibility of the element (see details). If the visibilityMode is set to Element.DISPLAY, it will use
		* the display property to hide the element, otherwise it uses visibility. The default is to hide and show using the visibility property.
		* @param {Boolean} visible Whether the element is visible
		* @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
		* @return {Ext.Element} this
		*/
		setVisible: function (visible, animate) {
			var me = this, isDisplay, isVisible, isOffsets,
                dom = me.dom;

			// hideMode string override
			if (typeof animate == 'string') {
				isDisplay = animate == DISPLAY;
				isVisible = animate == VISIBILITY;
				isOffsets = animate == OFFSETS;
				animate = false;
			} else {
				isDisplay = getVisMode(this.dom) == ELDISPLAY;
				isVisible = !isDisplay;
			}

			if (!animate || !me.anim) {
				if (isDisplay) {
					me.setDisplayed(visible);
				} else if (isOffsets) {
					if (!visible) {
						me.hideModeStyles = {
							position: me.getStyle('position'),
							top: me.getStyle('top'),
							left: me.getStyle('left')
						};

						me.applyStyles({ position: 'absolute', top: '-10000px', left: '-10000px' });
					} else {
						me.applyStyles(me.hideModeStyles || { position: '', top: '', left: '' });
					}
				} else {
					me.fixDisplay();
					dom.style.visibility = visible ? "visible" : HIDDEN;
				}
			} else {
				// closure for composites
				if (visible) {
					me.setOpacity(.01);
					me.setVisible(true);
				}
				me.anim({ opacity: { to: (visible ? 1 : 0)} },
                        me.preanim(arguments, 1),
                        null,
                        .35,
                        'easeIn',
                        function () {
                        	if (!visible) {
                        		dom.style[isDisplay ? DISPLAY : VISIBILITY] = (isDisplay) ? NONE : HIDDEN;
                        		Ext.fly(dom).setOpacity(1);
                        	}
                        });
			}
			return me;
		},

		/**
		* Toggles the element's visibility or display, depending on visibility mode.
		* @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
		* @return {Ext.Element} this
		*/
		toggle: function (animate) {
			var me = this;
			me.setVisible(!me.isVisible(), me.preanim(arguments, 0));
			return me;
		},

		/**
		* Sets the CSS display property. Uses originalDisplay if the specified value is a boolean true.
		* @param {Mixed} value Boolean value to display the element using its default display, or a string to set the display directly.
		* @return {Ext.Element} this
		*/
		setDisplayed: function (value) {
			if (typeof value == "boolean") {
				value = value ? getDisplay(this.dom) : NONE;
			}
			this.setStyle(DISPLAY, value);
			return this;
		},

		// private
		fixDisplay: function () {
			var me = this;
			if (me.isStyle(DISPLAY, NONE)) {
				me.setStyle(VISIBILITY, HIDDEN);
				me.setStyle(DISPLAY, getDisplay(this.dom)); // first try reverting to default
				if (me.isStyle(DISPLAY, NONE)) { // if that fails, default to block
					me.setStyle(DISPLAY, "block");
				}
			}
		},

		/**
		* Hide this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
		* @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
		* @return {Ext.Element} this
		*/
		hide: function (animate) {
			// hideMode override
			if (typeof animate == 'string') {
				this.setVisible(false, animate);
				return this;
			}
			this.setVisible(false, this.preanim(arguments, 0));
			return this;
		},

		/**
		* Show this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
		* @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
		* @return {Ext.Element} this
		*/
		show: function (animate) {
			// hideMode override
			if (typeof animate == 'string') {
				this.setVisible(true, animate);
				return this;
			}
			this.setVisible(true, this.preanim(arguments, 0));
			return this;
		}
	};
} ());
/**
* @class Ext.Element
*/
Ext.Element.addMethods(
function () {
	var VISIBILITY = "visibility",
        DISPLAY = "display",
        HIDDEN = "hidden",
        NONE = "none",
	    XMASKED = "x-masked",
		XMASKEDRELATIVE = "x-masked-relative",
        data = Ext.Element.data;

	return {
		/**
		* Checks whether the element is currently visible using both visibility and display properties.
		* @param {Boolean} deep (optional) True to walk the dom and see if parent elements are hidden (defaults to false)
		* @return {Boolean} True if the element is currently visible, else false
		*/
		isVisible: function (deep) {
			var vis = !this.isStyle(VISIBILITY, HIDDEN) && !this.isStyle(DISPLAY, NONE),
	        	p = this.dom.parentNode;
			if (deep !== true || !vis) {
				return vis;
			}
			while (p && !/^body/i.test(p.tagName)) {
				if (!Ext.fly(p, '_isVisible').isVisible()) {
					return false;
				}
				p = p.parentNode;
			}
			return true;
		},

		/**
		* Returns true if display is not "none"
		* @return {Boolean}
		*/
		isDisplayed: function () {
			return !this.isStyle(DISPLAY, NONE);
		},

		/**
		* Convenience method for setVisibilityMode(Element.DISPLAY)
		* @param {String} display (optional) What to set display to when visible
		* @return {Ext.Element} this
		*/
		enableDisplayMode: function (display) {
			this.setVisibilityMode(Ext.Element.DISPLAY);
			if (!Ext.isEmpty(display)) {
				data(this.dom, 'originalDisplay', display);
			}
			return this;
		},

		/**
		* Puts a mask over this element to disable user interaction. Requires core.css.
		* This method can only be applied to elements which accept child nodes.
		* @param {String} msg (optional) A message to display in the mask
		* @param {String} msgCls (optional) A css class to apply to the msg element
		* @return {Element} The mask element
		*/
		mask: function (msg, msgCls) {
			var me = this,
		    	dom = me.dom,
		    	dh = Ext.DomHelper,
		    	EXTELMASKMSG = "ext-el-mask-msg",
                el,
                mask;

			if (!/^body/i.test(dom.tagName) && me.getStyle('position') == 'static') {
				me.addClass(XMASKEDRELATIVE);
			}
			if ((el = data(dom, 'maskMsg'))) {
				el.remove();
			}
			if ((el = data(dom, 'mask'))) {
				el.remove();
			}

			mask = dh.append(dom, { cls: "ext-el-mask" }, true);
			data(dom, 'mask', mask);

			me.addClass(XMASKED);
			mask.setDisplayed(true);
			if (typeof msg == 'string') {
				var mm = dh.append(dom, { cls: EXTELMASKMSG, cn: { tag: 'div'} }, true);
				data(dom, 'maskMsg', mm);
				mm.dom.className = msgCls ? EXTELMASKMSG + " " + msgCls : EXTELMASKMSG;
				mm.dom.firstChild.innerHTML = msg;
				mm.setDisplayed(true);
				mm.center(me);
			}
			if (Ext.isIE && !(Ext.isIE7 && Ext.isStrict) && me.getStyle('height') == 'auto') { // ie will not expand full height automatically
				mask.setSize(undefined, me.getHeight());
			}
			return mask;
		},

		/**
		* Removes a previously applied mask.
		*/
		unmask: function () {
			var me = this,
                dom = me.dom,
		    	mask = data(dom, 'mask'),
		    	maskMsg = data(dom, 'maskMsg');
			if (mask) {
				if (maskMsg) {
					maskMsg.remove();
					data(dom, 'maskMsg', undefined);
				}
				mask.remove();
				data(dom, 'mask', undefined);
			}
			me.removeClass([XMASKED, XMASKEDRELATIVE]);
		},

		/**
		* Returns true if this element is masked
		* @return {Boolean}
		*/
		isMasked: function () {
			var m = data(this.dom, 'mask');
			return m && m.isVisible();
		},

		/**
		* Creates an iframe shim for this element to keep selects and other windowed objects from
		* showing through.
		* @return {Ext.Element} The new shim element
		*/
		createShim: function () {
			var el = document.createElement('iframe'),
	        	shim;
			el.frameBorder = '0';
			el.className = 'ext-shim';
			el.src = Ext.SSL_SECURE_URL;
			shim = Ext.get(this.dom.parentNode.insertBefore(el, this.dom));
			shim.autoBoxAdjust = false;
			return shim;
		}
	};
} ()); /**
 * @class Ext.Element
 */
Ext.Element.addMethods({
	/**
	* Convenience method for constructing a KeyMap
	* @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:
	* <code>{key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}</code>
	* @param {Function} fn The function to call
	* @param {Object} scope (optional) The scope (<code>this</code> reference) in which the specified function is executed. Defaults to this Element.
	* @return {Ext.KeyMap} The KeyMap created
	*/
	addKeyListener: function (key, fn, scope) {
		var config;
		if (typeof key != 'object' || Ext.isArray(key)) {
			config = {
				key: key,
				fn: fn,
				scope: scope
			};
		} else {
			config = {
				key: key.key,
				shift: key.shift,
				ctrl: key.ctrl,
				alt: key.alt,
				fn: fn,
				scope: scope
			};
		}
		return new Ext.KeyMap(this, config);
	},

	/**
	* Creates a KeyMap for this element
	* @param {Object} config The KeyMap config. See {@link Ext.KeyMap} for more details
	* @return {Ext.KeyMap} The KeyMap created
	*/
	addKeyMap: function (config) {
		return new Ext.KeyMap(this, config);
	}
});
(function () {
	// contants
	var NULL = null,
        UNDEFINED = undefined,
        TRUE = true,
        FALSE = false,
        SETX = "setX",
        SETY = "setY",
        SETXY = "setXY",
        LEFT = "left",
        BOTTOM = "bottom",
        TOP = "top",
        RIGHT = "right",
        HEIGHT = "height",
        WIDTH = "width",
        POINTS = "points",
        HIDDEN = "hidden",
        ABSOLUTE = "absolute",
        VISIBLE = "visible",
        MOTION = "motion",
        POSITION = "position",
        EASEOUT = "easeOut",
	/*
	* Use a light flyweight here since we are using so many callbacks and are always assured a DOM element
	*/
        flyEl = new Ext.Element.Flyweight(),
        queues = {},
        getObject = function (o) {
        	return o || {};
        },
        fly = function (dom) {
        	flyEl.dom = dom;
        	flyEl.id = Ext.id(dom);
        	return flyEl;
        },
	/*
	* Queueing now stored outside of the element due to closure issues
	*/
        getQueue = function (id) {
        	if (!queues[id]) {
        		queues[id] = [];
        	}
        	return queues[id];
        },
        setQueue = function (id, value) {
        	queues[id] = value;
        };

	//Notifies Element that fx methods are available
	Ext.enableFx = TRUE;

	/**
	* @class Ext.Fx
	* <p>A class to provide basic animation and visual effects support.  <b>Note:</b> This class is automatically applied
	* to the {@link Ext.Element} interface when included, so all effects calls should be performed via {@link Ext.Element}.
	* Conversely, since the effects are not actually defined in {@link Ext.Element}, Ext.Fx <b>must</b> be
	* {@link Ext#enableFx included} in order for the Element effects to work.</p><br/>
	* 
	* <p><b><u>Method Chaining</u></b></p>
	* <p>It is important to note that although the Fx methods and many non-Fx Element methods support "method chaining" in that
	* they return the Element object itself as the method return value, it is not always possible to mix the two in a single
	* method chain.  The Fx methods use an internal effects queue so that each effect can be properly timed and sequenced.
	* Non-Fx methods, on the other hand, have no such internal queueing and will always execute immediately.  For this reason,
	* while it may be possible to mix certain Fx and non-Fx method calls in a single chain, it may not always provide the
	* expected results and should be done with care.  Also see <tt>{@link #callback}</tt>.</p><br/>
	*
	* <p><b><u>Anchor Options for Motion Effects</u></b></p>
	* <p>Motion effects support 8-way anchoring, meaning that you can choose one of 8 different anchor points on the Element
	* that will serve as either the start or end point of the animation.  Following are all of the supported anchor positions:</p>
	<pre>
	Value  Description
	-----  -----------------------------
	tl     The top left corner
	t      The center of the top edge
	tr     The top right corner
	l      The center of the left edge
	r      The center of the right edge
	bl     The bottom left corner
	b      The center of the bottom edge
	br     The bottom right corner
	</pre>
	* <b>Note</b>: some Fx methods accept specific custom config parameters.  The options shown in the Config Options
	* section below are common options that can be passed to any Fx method unless otherwise noted.</b>
	* 
	* @cfg {Function} callback A function called when the effect is finished.  Note that effects are queued internally by the
	* Fx class, so a callback is not required to specify another effect -- effects can simply be chained together
	* and called in sequence (see note for <b><u>Method Chaining</u></b> above), for example:<pre><code>
	* el.slideIn().highlight();
	* </code></pre>
	* The callback is intended for any additional code that should run once a particular effect has completed. The Element
	* being operated upon is passed as the first parameter.
	* 
	* @cfg {Object} scope The scope (<code>this</code> reference) in which the <tt>{@link #callback}</tt> function is executed. Defaults to the browser window.
	* 
	* @cfg {String} easing A valid Ext.lib.Easing value for the effect:</p><div class="mdetail-params"><ul>
	* <li><b><tt>backBoth</tt></b></li>
	* <li><b><tt>backIn</tt></b></li>
	* <li><b><tt>backOut</tt></b></li>
	* <li><b><tt>bounceBoth</tt></b></li>
	* <li><b><tt>bounceIn</tt></b></li>
	* <li><b><tt>bounceOut</tt></b></li>
	* <li><b><tt>easeBoth</tt></b></li>
	* <li><b><tt>easeBothStrong</tt></b></li>
	* <li><b><tt>easeIn</tt></b></li>
	* <li><b><tt>easeInStrong</tt></b></li>
	* <li><b><tt>easeNone</tt></b></li>
	* <li><b><tt>easeOut</tt></b></li>
	* <li><b><tt>easeOutStrong</tt></b></li>
	* <li><b><tt>elasticBoth</tt></b></li>
	* <li><b><tt>elasticIn</tt></b></li>
	* <li><b><tt>elasticOut</tt></b></li>
	* </ul></div>
	*
	* @cfg {String} afterCls A css class to apply after the effect
	* @cfg {Number} duration The length of time (in seconds) that the effect should last
	* 
	* @cfg {Number} endOpacity Only applicable for {@link #fadeIn} or {@link #fadeOut}, a number between
	* <tt>0</tt> and <tt>1</tt> inclusive to configure the ending opacity value.
	*  
	* @cfg {Boolean} remove Whether the Element should be removed from the DOM and destroyed after the effect finishes
	* @cfg {Boolean} useDisplay Whether to use the <i>display</i> CSS property instead of <i>visibility</i> when hiding Elements (only applies to 
	* effects that end with the element being visually hidden, ignored otherwise)
	* @cfg {String/Object/Function} afterStyle A style specification string, e.g. <tt>"width:100px"</tt>, or an object
	* in the form <tt>{width:"100px"}</tt>, or a function which returns such a specification that will be applied to the
	* Element after the effect finishes.
	* @cfg {Boolean} block Whether the effect should block other effects from queueing while it runs
	* @cfg {Boolean} concurrent Whether to allow subsequently-queued effects to run at the same time as the current effect, or to ensure that they run in sequence
	* @cfg {Boolean} stopFx Whether preceding effects should be stopped and removed before running current effect (only applies to non blocking effects)
	*/
	Ext.Fx = {

		// private - calls the function taking arguments from the argHash based on the key.  Returns the return value of the function.
		//           this is useful for replacing switch statements (for example).
		switchStatements: function (key, fn, argHash) {
			return fn.apply(this, argHash[key]);
		},

		/**
		* Slides the element into view.  An anchor point can be optionally passed to set the point of
		* origin for the slide effect.  This function automatically handles wrapping the element with
		* a fixed-size container if needed.  See the Fx class overview for valid anchor point options.
		* Usage:
		*<pre><code>
		// default: slide the element in from the top
		el.slideIn();

		// custom: slide the element in from the right with a 2-second duration
		el.slideIn('r', { duration: 2 });

		// common config options shown with default values
		el.slideIn('t', {
		easing: 'easeOut',
		duration: .5
		});
		</code></pre>
		* @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to top: 't')
		* @param {Object} options (optional) Object literal with any of the Fx config options
		* @return {Ext.Element} The Element
		*/
		slideIn: function (anchor, o) {
			o = getObject(o);
			var me = this,
            dom = me.dom,
            st = dom.style,
            xy,
            r,
            b,
            wrap,
            after,
            st,
            args,
            pt,
            bw,
            bh;

			anchor = anchor || "t";

			me.queueFx(o, function () {
				xy = fly(dom).getXY();
				// fix display to visibility
				fly(dom).fixDisplay();

				// restore values after effect
				r = fly(dom).getFxRestore();
				b = { x: xy[0], y: xy[1], 0: xy[0], 1: xy[1], width: dom.offsetWidth, height: dom.offsetHeight };
				b.right = b.x + b.width;
				b.bottom = b.y + b.height;

				// fixed size for slide
				fly(dom).setWidth(b.width).setHeight(b.height);

				// wrap if needed
				wrap = fly(dom).fxWrap(r.pos, o, HIDDEN);

				st.visibility = VISIBLE;
				st.position = ABSOLUTE;

				// clear out temp styles after slide and unwrap
				function after() {
					fly(dom).fxUnwrap(wrap, r.pos, o);
					st.width = r.width;
					st.height = r.height;
					fly(dom).afterFx(o);
				}

				// time to calculate the positions        
				pt = { to: [b.x, b.y] };
				bw = { to: b.width };
				bh = { to: b.height };

				function argCalc(wrap, style, ww, wh, sXY, sXYval, s1, s2, w, h, p) {
					var ret = {};
					fly(wrap).setWidth(ww).setHeight(wh);
					if (fly(wrap)[sXY]) {
						fly(wrap)[sXY](sXYval);
					}
					style[s1] = style[s2] = "0";
					if (w) {
						ret.width = w
					};
					if (h) {
						ret.height = h;
					}
					if (p) {
						ret.points = p;
					}
					return ret;
				};

				args = fly(dom).switchStatements(anchor.toLowerCase(), argCalc, {
					t: [wrap, st, b.width, 0, NULL, NULL, LEFT, BOTTOM, NULL, bh, NULL],
					l: [wrap, st, 0, b.height, NULL, NULL, RIGHT, TOP, bw, NULL, NULL],
					r: [wrap, st, b.width, b.height, SETX, b.right, LEFT, TOP, NULL, NULL, pt],
					b: [wrap, st, b.width, b.height, SETY, b.bottom, LEFT, TOP, NULL, bh, pt],
					tl: [wrap, st, 0, 0, NULL, NULL, RIGHT, BOTTOM, bw, bh, pt],
					bl: [wrap, st, 0, 0, SETY, b.y + b.height, RIGHT, TOP, bw, bh, pt],
					br: [wrap, st, 0, 0, SETXY, [b.right, b.bottom], LEFT, TOP, bw, bh, pt],
					tr: [wrap, st, 0, 0, SETX, b.x + b.width, LEFT, BOTTOM, bw, bh, pt]
				});

				st.visibility = VISIBLE;
				fly(wrap).show();

				arguments.callee.anim = fly(wrap).fxanim(args,
                o,
                MOTION,
                .5,
                EASEOUT,
                after);
			});
			return me;
		},

		/**
		* Slides the element out of view.  An anchor point can be optionally passed to set the end point
		* for the slide effect.  When the effect is completed, the element will be hidden (visibility = 
		* 'hidden') but block elements will still take up space in the document.  The element must be removed
		* from the DOM using the 'remove' config option if desired.  This function automatically handles 
		* wrapping the element with a fixed-size container if needed.  See the Fx class overview for valid anchor point options.
		* Usage:
		*<pre><code>
		// default: slide the element out to the top
		el.slideOut();

		// custom: slide the element out to the right with a 2-second duration
		el.slideOut('r', { duration: 2 });

		// common config options shown with default values
		el.slideOut('t', {
		easing: 'easeOut',
		duration: .5,
		remove: false,
		useDisplay: false
		});
		</code></pre>
		* @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to top: 't')
		* @param {Object} options (optional) Object literal with any of the Fx config options
		* @return {Ext.Element} The Element
		*/
		slideOut: function (anchor, o) {
			o = getObject(o);
			var me = this,
            dom = me.dom,
            st = dom.style,
            xy = me.getXY(),
            wrap,
            r,
            b,
            a,
            zero = { to: 0 };

			anchor = anchor || "t";

			me.queueFx(o, function () {

				// restore values after effect
				r = fly(dom).getFxRestore();
				b = { x: xy[0], y: xy[1], 0: xy[0], 1: xy[1], width: dom.offsetWidth, height: dom.offsetHeight };
				b.right = b.x + b.width;
				b.bottom = b.y + b.height;

				// fixed size for slide   
				fly(dom).setWidth(b.width).setHeight(b.height);

				// wrap if needed
				wrap = fly(dom).fxWrap(r.pos, o, VISIBLE);

				st.visibility = VISIBLE;
				st.position = ABSOLUTE;
				fly(wrap).setWidth(b.width).setHeight(b.height);

				function after() {
					o.useDisplay ? fly(dom).setDisplayed(FALSE) : fly(dom).hide();
					fly(dom).fxUnwrap(wrap, r.pos, o);
					st.width = r.width;
					st.height = r.height;
					fly(dom).afterFx(o);
				}

				function argCalc(style, s1, s2, p1, v1, p2, v2, p3, v3) {
					var ret = {};

					style[s1] = style[s2] = "0";
					ret[p1] = v1;
					if (p2) {
						ret[p2] = v2;
					}
					if (p3) {
						ret[p3] = v3;
					}

					return ret;
				};

				a = fly(dom).switchStatements(anchor.toLowerCase(), argCalc, {
					t: [st, LEFT, BOTTOM, HEIGHT, zero],
					l: [st, RIGHT, TOP, WIDTH, zero],
					r: [st, LEFT, TOP, WIDTH, zero, POINTS, { to: [b.right, b.y]}],
					b: [st, LEFT, TOP, HEIGHT, zero, POINTS, { to: [b.x, b.bottom]}],
					tl: [st, RIGHT, BOTTOM, WIDTH, zero, HEIGHT, zero],
					bl: [st, RIGHT, TOP, WIDTH, zero, HEIGHT, zero, POINTS, { to: [b.x, b.bottom]}],
					br: [st, LEFT, TOP, WIDTH, zero, HEIGHT, zero, POINTS, { to: [b.x + b.width, b.bottom]}],
					tr: [st, LEFT, BOTTOM, WIDTH, zero, HEIGHT, zero, POINTS, { to: [b.right, b.y]}]
				});

				arguments.callee.anim = fly(wrap).fxanim(a,
                o,
                MOTION,
                .5,
                EASEOUT,
                after);
			});
			return me;
		},

		/**
		* Fades the element out while slowly expanding it in all directions.  When the effect is completed, the 
		* element will be hidden (visibility = 'hidden') but block elements will still take up space in the document. 
		* The element must be removed from the DOM using the 'remove' config option if desired.
		* Usage:
		*<pre><code>
		// default
		el.puff();

		// common config options shown with default values
		el.puff({
		easing: 'easeOut',
		duration: .5,
		remove: false,
		useDisplay: false
		});
		</code></pre>
		* @param {Object} options (optional) Object literal with any of the Fx config options
		* @return {Ext.Element} The Element
		*/
		puff: function (o) {
			o = getObject(o);
			var me = this,
            dom = me.dom,
            st = dom.style,
            width,
            height,
            r;

			me.queueFx(o, function () {
				width = fly(dom).getWidth();
				height = fly(dom).getHeight();
				fly(dom).clearOpacity();
				fly(dom).show();

				// restore values after effect
				r = fly(dom).getFxRestore();

				function after() {
					o.useDisplay ? fly(dom).setDisplayed(FALSE) : fly(dom).hide();
					fly(dom).clearOpacity();
					fly(dom).setPositioning(r.pos);
					st.width = r.width;
					st.height = r.height;
					st.fontSize = '';
					fly(dom).afterFx(o);
				}

				arguments.callee.anim = fly(dom).fxanim({
					width: { to: fly(dom).adjustWidth(width * 2) },
					height: { to: fly(dom).adjustHeight(height * 2) },
					points: { by: [-width * .5, -height * .5] },
					opacity: { to: 0 },
					fontSize: { to: 200, unit: "%" }
				},
                o,
                MOTION,
                .5,
                EASEOUT,
                 after);
			});
			return me;
		},

		/**
		* Blinks the element as if it was clicked and then collapses on its center (similar to switching off a television).
		* When the effect is completed, the element will be hidden (visibility = 'hidden') but block elements will still 
		* take up space in the document. The element must be removed from the DOM using the 'remove' config option if desired.
		* Usage:
		*<pre><code>
		// default
		el.switchOff();

		// all config options shown with default values
		el.switchOff({
		easing: 'easeIn',
		duration: .3,
		remove: false,
		useDisplay: false
		});
		</code></pre>
		* @param {Object} options (optional) Object literal with any of the Fx config options
		* @return {Ext.Element} The Element
		*/
		switchOff: function (o) {
			o = getObject(o);
			var me = this,
            dom = me.dom,
            st = dom.style,
            r;

			me.queueFx(o, function () {
				fly(dom).clearOpacity();
				fly(dom).clip();

				// restore values after effect
				r = fly(dom).getFxRestore();

				function after() {
					o.useDisplay ? fly(dom).setDisplayed(FALSE) : fly(dom).hide();
					fly(dom).clearOpacity();
					fly(dom).setPositioning(r.pos);
					st.width = r.width;
					st.height = r.height;
					fly(dom).afterFx(o);
				};

				fly(dom).fxanim({ opacity: { to: 0.3} },
                NULL,
                NULL,
                .1,
                NULL,
                function () {
                	fly(dom).clearOpacity();
                	(function () {
                		fly(dom).fxanim({
                			height: { to: 1 },
                			points: { by: [0, fly(dom).getHeight() * .5] }
                		},
                            o,
                            MOTION,
                            0.3,
                            'easeIn',
                            after);
                	}).defer(100);
                });
			});
			return me;
		},

		/**
		* Highlights the Element by setting a color (applies to the background-color by default, but can be
		* changed using the "attr" config option) and then fading back to the original color. If no original
		* color is available, you should provide the "endColor" config option which will be cleared after the animation.
		* Usage:
		<pre><code>
		// default: highlight background to yellow
		el.highlight();

		// custom: highlight foreground text to blue for 2 seconds
		el.highlight("0000ff", { attr: 'color', duration: 2 });

		// common config options shown with default values
		el.highlight("ffff9c", {
		attr: "background-color", //can be any valid CSS property (attribute) that supports a color value
		endColor: (current color) or "ffffff",
		easing: 'easeIn',
		duration: 1
		});
		</code></pre>
		* @param {String} color (optional) The highlight color. Should be a 6 char hex color without the leading # (defaults to yellow: 'ffff9c')
		* @param {Object} options (optional) Object literal with any of the Fx config options
		* @return {Ext.Element} The Element
		*/
		highlight: function (color, o) {
			o = getObject(o);
			var me = this,
            dom = me.dom,
            attr = o.attr || "backgroundColor",
            a = {},
            restore;

			me.queueFx(o, function () {
				fly(dom).clearOpacity();
				fly(dom).show();

				function after() {
					dom.style[attr] = restore;
					fly(dom).afterFx(o);
				}
				restore = dom.style[attr];
				a[attr] = { from: color || "ffff9c", to: o.endColor || fly(dom).getColor(attr) || "ffffff" };
				arguments.callee.anim = fly(dom).fxanim(a,
                o,
                'color',
                1,
                'easeIn',
                after);
			});
			return me;
		},

		/**
		* Shows a ripple of exploding, attenuating borders to draw attention to an Element.
		* Usage:
		<pre><code>
		// default: a single light blue ripple
		el.frame();

		// custom: 3 red ripples lasting 3 seconds total
		el.frame("ff0000", 3, { duration: 3 });

		// common config options shown with default values
		el.frame("C3DAF9", 1, {
		duration: 1 //duration of each individual ripple.
		// Note: Easing is not configurable and will be ignored if included
		});
		</code></pre>
		* @param {String} color (optional) The color of the border.  Should be a 6 char hex color without the leading # (defaults to light blue: 'C3DAF9').
		* @param {Number} count (optional) The number of ripples to display (defaults to 1)
		* @param {Object} options (optional) Object literal with any of the Fx config options
		* @return {Ext.Element} The Element
		*/
		frame: function (color, count, o) {
			o = getObject(o);
			var me = this,
            dom = me.dom,
            proxy,
            active;

			me.queueFx(o, function () {
				color = color || '#C3DAF9';
				if (color.length == 6) {
					color = '#' + color;
				}
				count = count || 1;
				fly(dom).show();

				var xy = fly(dom).getXY(),
                b = { x: xy[0], y: xy[1], 0: xy[0], 1: xy[1], width: dom.offsetWidth, height: dom.offsetHeight },
                queue = function () {
                	proxy = fly(document.body || document.documentElement).createChild({
                		style: {
                			position: ABSOLUTE,
                			'z-index': 35000, // yee haw
                			border: '0px solid ' + color
                		}
                	});
                	return proxy.queueFx({}, animFn);
                };


				arguments.callee.anim = {
					isAnimated: true,
					stop: function () {
						count = 0;
						proxy.stopFx();
					}
				};

				function animFn() {
					var scale = Ext.isBorderBox ? 2 : 1;
					active = proxy.anim({
						top: { from: b.y, to: b.y - 20 },
						left: { from: b.x, to: b.x - 20 },
						borderWidth: { from: 0, to: 10 },
						opacity: { from: 1, to: 0 },
						height: { from: b.height, to: b.height + 20 * scale },
						width: { from: b.width, to: b.width + 20 * scale }
					}, {
						duration: o.duration || 1,
						callback: function () {
							proxy.remove();
							--count > 0 ? queue() : fly(dom).afterFx(o);
						}
					});
					arguments.callee.anim = {
						isAnimated: true,
						stop: function () {
							active.stop();
						}
					};
				};
				queue();
			});
			return me;
		},

		/**
		* Creates a pause before any subsequent queued effects begin.  If there are
		* no effects queued after the pause it will have no effect.
		* Usage:
		<pre><code>
		el.pause(1);
		</code></pre>
		* @param {Number} seconds The length of time to pause (in seconds)
		* @return {Ext.Element} The Element
		*/
		pause: function (seconds) {
			var dom = this.dom,
            t;

			this.queueFx({}, function () {
				t = setTimeout(function () {
					fly(dom).afterFx({});
				}, seconds * 1000);
				arguments.callee.anim = {
					isAnimated: true,
					stop: function () {
						clearTimeout(t);
						fly(dom).afterFx({});
					}
				};
			});
			return this;
		},

		/**
		* Fade an element in (from transparent to opaque).  The ending opacity can be specified
		* using the <tt>{@link #endOpacity}</tt> config option.
		* Usage:
		<pre><code>
		// default: fade in from opacity 0 to 100%
		el.fadeIn();

		// custom: fade in from opacity 0 to 75% over 2 seconds
		el.fadeIn({ endOpacity: .75, duration: 2});

		// common config options shown with default values
		el.fadeIn({
		endOpacity: 1, //can be any value between 0 and 1 (e.g. .5)
		easing: 'easeOut',
		duration: .5
		});
		</code></pre>
		* @param {Object} options (optional) Object literal with any of the Fx config options
		* @return {Ext.Element} The Element
		*/
		fadeIn: function (o) {
			o = getObject(o);
			var me = this,
            dom = me.dom,
            to = o.endOpacity || 1;

			me.queueFx(o, function () {
				fly(dom).setOpacity(0);
				fly(dom).fixDisplay();
				dom.style.visibility = VISIBLE;
				arguments.callee.anim = fly(dom).fxanim({ opacity: { to: to} },
                o, NULL, .5, EASEOUT, function () {
                	if (to == 1) {
                		fly(dom).clearOpacity();
                	}
                	fly(dom).afterFx(o);
                });
			});
			return me;
		},

		/**
		* Fade an element out (from opaque to transparent).  The ending opacity can be specified
		* using the <tt>{@link #endOpacity}</tt> config option.  Note that IE may require
		* <tt>{@link #useDisplay}:true</tt> in order to redisplay correctly.
		* Usage:
		<pre><code>
		// default: fade out from the element's current opacity to 0
		el.fadeOut();

		// custom: fade out from the element's current opacity to 25% over 2 seconds
		el.fadeOut({ endOpacity: .25, duration: 2});

		// common config options shown with default values
		el.fadeOut({
		endOpacity: 0, //can be any value between 0 and 1 (e.g. .5)
		easing: 'easeOut',
		duration: .5,
		remove: false,
		useDisplay: false
		});
		</code></pre>
		* @param {Object} options (optional) Object literal with any of the Fx config options
		* @return {Ext.Element} The Element
		*/
		fadeOut: function (o) {
			o = getObject(o);
			var me = this,
            dom = me.dom,
            style = dom.style,
            to = o.endOpacity || 0;

			me.queueFx(o, function () {
				arguments.callee.anim = fly(dom).fxanim({
					opacity: { to: to}
				},
                o,
                NULL,
                .5,
                EASEOUT,
                function () {
                	if (to == 0) {
                		Ext.Element.data(dom, 'visibilityMode') == Ext.Element.DISPLAY || o.useDisplay ?
                            style.display = "none" :
                            style.visibility = HIDDEN;

                		fly(dom).clearOpacity();
                	}
                	fly(dom).afterFx(o);
                });
			});
			return me;
		},

		/**
		* Animates the transition of an element's dimensions from a starting height/width
		* to an ending height/width.  This method is a convenience implementation of {@link shift}.
		* Usage:
		<pre><code>
		// change height and width to 100x100 pixels
		el.scale(100, 100);

		// common config options shown with default values.  The height and width will default to
		// the element&#39;s existing values if passed as null.
		el.scale(
		[element&#39;s width],
		[element&#39;s height], {
		easing: 'easeOut',
		duration: .35
		}
		);
		</code></pre>
		* @param {Number} width  The new width (pass undefined to keep the original width)
		* @param {Number} height  The new height (pass undefined to keep the original height)
		* @param {Object} options (optional) Object literal with any of the Fx config options
		* @return {Ext.Element} The Element
		*/
		scale: function (w, h, o) {
			this.shift(Ext.apply({}, o, {
				width: w,
				height: h
			}));
			return this;
		},

		/**
		* Animates the transition of any combination of an element's dimensions, xy position and/or opacity.
		* Any of these properties not specified in the config object will not be changed.  This effect 
		* requires that at least one new dimension, position or opacity setting must be passed in on
		* the config object in order for the function to have any effect.
		* Usage:
		<pre><code>
		// slide the element horizontally to x position 200 while changing the height and opacity
		el.shift({ x: 200, height: 50, opacity: .8 });

		// common config options shown with default values.
		el.shift({
		width: [element&#39;s width],
		height: [element&#39;s height],
		x: [element&#39;s x position],
		y: [element&#39;s y position],
		opacity: [element&#39;s opacity],
		easing: 'easeOut',
		duration: .35
		});
		</code></pre>
		* @param {Object} options  Object literal with any of the Fx config options
		* @return {Ext.Element} The Element
		*/
		shift: function (o) {
			o = getObject(o);
			var dom = this.dom,
            a = {};

			this.queueFx(o, function () {
				for (var prop in o) {
					if (o[prop] != UNDEFINED) {
						a[prop] = { to: o[prop] };
					}
				}

				a.width ? a.width.to = fly(dom).adjustWidth(o.width) : a;
				a.height ? a.height.to = fly(dom).adjustWidth(o.height) : a;

				if (a.x || a.y || a.xy) {
					a.points = a.xy ||
                           { to: [a.x ? a.x.to : fly(dom).getX(),
                                   a.y ? a.y.to : fly(dom).getY()]
                           };
				}

				arguments.callee.anim = fly(dom).fxanim(a,
                o,
                MOTION,
                .35,
                EASEOUT,
                function () {
                	fly(dom).afterFx(o);
                });
			});
			return this;
		},

		/**
		* Slides the element while fading it out of view.  An anchor point can be optionally passed to set the 
		* ending point of the effect.
		* Usage:
		*<pre><code>
		// default: slide the element downward while fading out
		el.ghost();

		// custom: slide the element out to the right with a 2-second duration
		el.ghost('r', { duration: 2 });

		// common config options shown with default values
		el.ghost('b', {
		easing: 'easeOut',
		duration: .5,
		remove: false,
		useDisplay: false
		});
		</code></pre>
		* @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to bottom: 'b')
		* @param {Object} options (optional) Object literal with any of the Fx config options
		* @return {Ext.Element} The Element
		*/
		ghost: function (anchor, o) {
			o = getObject(o);
			var me = this,
            dom = me.dom,
            st = dom.style,
            a = { opacity: { to: 0 }, points: {} },
            pt = a.points,
            r,
            w,
            h;

			anchor = anchor || "b";

			me.queueFx(o, function () {
				// restore values after effect
				r = fly(dom).getFxRestore();
				w = fly(dom).getWidth();
				h = fly(dom).getHeight();

				function after() {
					o.useDisplay ? fly(dom).setDisplayed(FALSE) : fly(dom).hide();
					fly(dom).clearOpacity();
					fly(dom).setPositioning(r.pos);
					st.width = r.width;
					st.height = r.height;
					fly(dom).afterFx(o);
				}

				pt.by = fly(dom).switchStatements(anchor.toLowerCase(), function (v1, v2) { return [v1, v2]; }, {
					t: [0, -h],
					l: [-w, 0],
					r: [w, 0],
					b: [0, h],
					tl: [-w, -h],
					bl: [-w, h],
					br: [w, h],
					tr: [w, -h]
				});

				arguments.callee.anim = fly(dom).fxanim(a,
                o,
                MOTION,
                .5,
                EASEOUT, after);
			});
			return me;
		},

		/**
		* Ensures that all effects queued after syncFx is called on the element are
		* run concurrently.  This is the opposite of {@link #sequenceFx}.
		* @return {Ext.Element} The Element
		*/
		syncFx: function () {
			var me = this;
			me.fxDefaults = Ext.apply(me.fxDefaults || {}, {
				block: FALSE,
				concurrent: TRUE,
				stopFx: FALSE
			});
			return me;
		},

		/**
		* Ensures that all effects queued after sequenceFx is called on the element are
		* run in sequence.  This is the opposite of {@link #syncFx}.
		* @return {Ext.Element} The Element
		*/
		sequenceFx: function () {
			var me = this;
			me.fxDefaults = Ext.apply(me.fxDefaults || {}, {
				block: FALSE,
				concurrent: FALSE,
				stopFx: FALSE
			});
			return me;
		},

		/* @private */
		nextFx: function () {
			var ef = getQueue(this.dom.id)[0];
			if (ef) {
				ef.call(this);
			}
		},

		/**
		* Returns true if the element has any effects actively running or queued, else returns false.
		* @return {Boolean} True if element has active effects, else false
		*/
		hasActiveFx: function () {
			return getQueue(this.dom.id)[0];
		},

		/**
		* Stops any running effects and clears the element's internal effects queue if it contains
		* any additional effects that haven't started yet.
		* @return {Ext.Element} The Element
		*/
		stopFx: function (finish) {
			var me = this,
            id = me.dom.id;
			if (me.hasActiveFx()) {
				var cur = getQueue(id)[0];
				if (cur && cur.anim) {
					if (cur.anim.isAnimated) {
						setQueue(id, [cur]); //clear
						cur.anim.stop(finish !== undefined ? finish : TRUE);
					} else {
						setQueue(id, []);
					}
				}
			}
			return me;
		},

		/* @private */
		beforeFx: function (o) {
			if (this.hasActiveFx() && !o.concurrent) {
				if (o.stopFx) {
					this.stopFx();
					return TRUE;
				}
				return FALSE;
			}
			return TRUE;
		},

		/**
		* Returns true if the element is currently blocking so that no other effect can be queued
		* until this effect is finished, else returns false if blocking is not set.  This is commonly
		* used to ensure that an effect initiated by a user action runs to completion prior to the
		* same effect being restarted (e.g., firing only one effect even if the user clicks several times).
		* @return {Boolean} True if blocking, else false
		*/
		hasFxBlock: function () {
			var q = getQueue(this.dom.id);
			return q && q[0] && q[0].block;
		},

		/* @private */
		queueFx: function (o, fn) {
			var me = fly(this.dom);
			if (!me.hasFxBlock()) {
				Ext.applyIf(o, me.fxDefaults);
				if (!o.concurrent) {
					var run = me.beforeFx(o);
					fn.block = o.block;
					getQueue(me.dom.id).push(fn);
					if (run) {
						me.nextFx();
					}
				} else {
					fn.call(me);
				}
			}
			return me;
		},

		/* @private */
		fxWrap: function (pos, o, vis) {
			var dom = this.dom,
            wrap,
            wrapXY;
			if (!o.wrap || !(wrap = Ext.getDom(o.wrap))) {
				if (o.fixPosition) {
					wrapXY = fly(dom).getXY();
				}
				var div = document.createElement("div");
				div.style.visibility = vis;
				wrap = dom.parentNode.insertBefore(div, dom);
				fly(wrap).setPositioning(pos);
				if (fly(wrap).isStyle(POSITION, "static")) {
					fly(wrap).position("relative");
				}
				fly(dom).clearPositioning('auto');
				fly(wrap).clip();
				wrap.appendChild(dom);
				if (wrapXY) {
					fly(wrap).setXY(wrapXY);
				}
			}
			return wrap;
		},

		/* @private */
		fxUnwrap: function (wrap, pos, o) {
			var dom = this.dom;
			fly(dom).clearPositioning();
			fly(dom).setPositioning(pos);
			if (!o.wrap) {
				var pn = fly(wrap).dom.parentNode;
				pn.insertBefore(dom, wrap);
				fly(wrap).remove();
			}
		},

		/* @private */
		getFxRestore: function () {
			var st = this.dom.style;
			return { pos: this.getPositioning(), width: st.width, height: st.height };
		},

		/* @private */
		afterFx: function (o) {
			var dom = this.dom,
            id = dom.id;
			if (o.afterStyle) {
				fly(dom).setStyle(o.afterStyle);
			}
			if (o.afterCls) {
				fly(dom).addClass(o.afterCls);
			}
			if (o.remove == TRUE) {
				fly(dom).remove();
			}
			if (o.callback) {
				o.callback.call(o.scope, fly(dom));
			}
			if (!o.concurrent) {
				getQueue(id).shift();
				fly(dom).nextFx();
			}
		},

		/* @private */
		fxanim: function (args, opt, animType, defaultDur, defaultEase, cb) {
			animType = animType || 'run';
			opt = opt || {};
			var anim = Ext.lib.Anim[animType](
                this.dom,
                args,
                (opt.duration || defaultDur) || .35,
                (opt.easing || defaultEase) || EASEOUT,
                cb,
                this
            );
			opt.anim = anim;
			return anim;
		}
	};

	// backwards compat
	Ext.Fx.resize = Ext.Fx.scale;

	//When included, Ext.Fx is automatically applied to Element so that all basic
	//effects are available directly via the Element API
	Ext.Element.addMethods(Ext.Fx);
})();
/**
* @class Ext.CompositeElementLite
* <p>This class encapsulates a <i>collection</i> of DOM elements, providing methods to filter
* members, or to perform collective actions upon the whole set.</p>
* <p>Although they are not listed, this class supports all of the methods of {@link Ext.Element} and
* {@link Ext.Fx}. The methods from these classes will be performed on all the elements in this collection.</p>
* Example:<pre><code>
var els = Ext.select("#some-el div.some-class");
// or select directly from an existing element
var el = Ext.get('some-el');
el.select('div.some-class');

els.setWidth(100); // all elements become 100 width
els.hide(true); // all elements fade out and hide
// or
els.setWidth(100).hide(true);
</code>
*/
Ext.CompositeElementLite = function (els, root) {
	/**
	* <p>The Array of DOM elements which this CompositeElement encapsulates. Read-only.</p>
	* <p>This will not <i>usually</i> be accessed in developers' code, but developers wishing
	* to augment the capabilities of the CompositeElementLite class may use it when adding
	* methods to the class.</p>
	* <p>For example to add the <code>nextAll</code> method to the class to <b>add</b> all
	* following siblings of selected elements, the code would be</p><code><pre>
	Ext.override(Ext.CompositeElementLite, {
	nextAll: function() {
	var els = this.elements, i, l = els.length, n, r = [], ri = -1;

	//      Loop through all elements in this Composite, accumulating
	//      an Array of all siblings.
	for (i = 0; i < l; i++) {
	for (n = els[i].nextSibling; n; n = n.nextSibling) {
	r[++ri] = n;
	}
	}

	//      Add all found siblings to this Composite
	return this.add(r);
	}
	});</pre></code>
	* @type Array
	* @property elements
	*/
	this.elements = [];
	this.add(els, root);
	this.el = new Ext.Element.Flyweight();
};

Ext.CompositeElementLite.prototype = {
	isComposite: true,

	// private
	getElement: function (el) {
		// Set the shared flyweight dom property to the current element
		var e = this.el;
		e.dom = el;
		e.id = el.id;
		return e;
	},

	// private
	transformElement: function (el) {
		return Ext.getDom(el);
	},

	/**
	* Returns the number of elements in this Composite.
	* @return Number
	*/
	getCount: function () {
		return this.elements.length;
	},
	/**
	* Adds elements to this Composite object.
	* @param {Mixed} els Either an Array of DOM elements to add, or another Composite object who's elements should be added.
	* @return {CompositeElement} This Composite object.
	*/
	add: function (els, root) {
		var me = this,
            elements = me.elements;
		if (!els) {
			return this;
		}
		if (typeof els == "string") {
			els = Ext.Element.selectorFunction(els, root);
		} else if (els.isComposite) {
			els = els.elements;
		} else if (!Ext.isIterable(els)) {
			els = [els];
		}

		for (var i = 0, len = els.length; i < len; ++i) {
			elements.push(me.transformElement(els[i]));
		}
		return me;
	},

	invoke: function (fn, args) {
		var me = this,
            els = me.elements,
            len = els.length,
            e,
            i;

		for (i = 0; i < len; i++) {
			e = els[i];
			if (e) {
				Ext.Element.prototype[fn].apply(me.getElement(e), args);
			}
		}
		return me;
	},
	/**
	* Returns a flyweight Element of the dom element object at the specified index
	* @param {Number} index
	* @return {Ext.Element}
	*/
	item: function (index) {
		var me = this,
            el = me.elements[index],
            out = null;

		if (el) {
			out = me.getElement(el);
		}
		return out;
	},

	// fixes scope with flyweight
	addListener: function (eventName, handler, scope, opt) {
		var els = this.elements,
            len = els.length,
            i, e;

		for (i = 0; i < len; i++) {
			e = els[i];
			if (e) {
				Ext.EventManager.on(e, eventName, handler, scope || e, opt);
			}
		}
		return this;
	},
	/**
	* <p>Calls the passed function for each element in this composite.</p>
	* @param {Function} fn The function to call. The function is passed the following parameters:<ul>
	* <li><b>el</b> : Element<div class="sub-desc">The current Element in the iteration.
	* <b>This is the flyweight (shared) Ext.Element instance, so if you require a
	* a reference to the dom node, use el.dom.</b></div></li>
	* <li><b>c</b> : Composite<div class="sub-desc">This Composite object.</div></li>
	* <li><b>idx</b> : Number<div class="sub-desc">The zero-based index in the iteration.</div></li>
	* </ul>
	* @param {Object} scope (optional) The scope (<i>this</i> reference) in which the function is executed. (defaults to the Element)
	* @return {CompositeElement} this
	*/
	each: function (fn, scope) {
		var me = this,
            els = me.elements,
            len = els.length,
            i, e;

		for (i = 0; i < len; i++) {
			e = els[i];
			if (e) {
				e = this.getElement(e);
				if (fn.call(scope || e, e, me, i) === false) {
					break;
				}
			}
		}
		return me;
	},

	/**
	* Clears this Composite and adds the elements passed.
	* @param {Mixed} els Either an array of DOM elements, or another Composite from which to fill this Composite.
	* @return {CompositeElement} this
	*/
	fill: function (els) {
		var me = this;
		me.elements = [];
		me.add(els);
		return me;
	},

	/**
	* Filters this composite to only elements that match the passed selector.
	* @param {String/Function} selector A string CSS selector or a comparison function.
	* The comparison function will be called with the following arguments:<ul>
	* <li><code>el</code> : Ext.Element<div class="sub-desc">The current DOM element.</div></li>
	* <li><code>index</code> : Number<div class="sub-desc">The current index within the collection.</div></li>
	* </ul>
	* @return {CompositeElement} this
	*/
	filter: function (selector) {
		var els = [],
            me = this,
            elements = me.elements,
            fn = Ext.isFunction(selector) ? selector
                : function (el) {
                	return el.is(selector);
                };


		me.each(function (el, self, i) {
			if (fn(el, i) !== false) {
				els[els.length] = me.transformElement(el);
			}
		});
		me.elements = els;
		return me;
	},

	/**
	* Find the index of the passed element within the composite collection.
	* @param el {Mixed} The id of an element, or an Ext.Element, or an HtmlElement to find within the composite collection.
	* @return Number The index of the passed Ext.Element in the composite collection, or -1 if not found.
	*/
	indexOf: function (el) {
		return this.elements.indexOf(this.transformElement(el));
	},

	/**
	* Replaces the specified element with the passed element.
	* @param {Mixed} el The id of an element, the Element itself, the index of the element in this composite
	* to replace.
	* @param {Mixed} replacement The id of an element or the Element itself.
	* @param {Boolean} domReplace (Optional) True to remove and replace the element in the document too.
	* @return {CompositeElement} this
	*/
	replaceElement: function (el, replacement, domReplace) {
		var index = !isNaN(el) ? el : this.indexOf(el),
            d;
		if (index > -1) {
			replacement = Ext.getDom(replacement);
			if (domReplace) {
				d = this.elements[index];
				d.parentNode.insertBefore(replacement, d);
				Ext.removeNode(d);
			}
			this.elements.splice(index, 1, replacement);
		}
		return this;
	},

	/**
	* Removes all elements.
	*/
	clear: function () {
		this.elements = [];
	}
};

Ext.CompositeElementLite.prototype.on = Ext.CompositeElementLite.prototype.addListener;

(function () {
	var fnName,
    ElProto = Ext.Element.prototype,
    CelProto = Ext.CompositeElementLite.prototype;

	for (fnName in ElProto) {
		if (Ext.isFunction(ElProto[fnName])) {
			(function (fnName) {
				CelProto[fnName] = CelProto[fnName] || function () {
					return this.invoke(fnName, arguments);
				};
			}).call(CelProto, fnName);

		}
	}
})();

if (Ext.DomQuery) {
	Ext.Element.selectorFunction = Ext.DomQuery.select;
}

/**
* Selects elements based on the passed CSS selector to enable {@link Ext.Element Element} methods
* to be applied to many related elements in one statement through the returned {@link Ext.CompositeElement CompositeElement} or
* {@link Ext.CompositeElementLite CompositeElementLite} object.
* @param {String/Array} selector The CSS selector or an array of elements
* @param {HTMLElement/String} root (optional) The root element of the query or id of the root
* @return {CompositeElementLite/CompositeElement}
* @member Ext.Element
* @method select
*/
Ext.Element.select = function (selector, root) {
	var els;
	if (typeof selector == "string") {
		els = Ext.Element.selectorFunction(selector, root);
	} else if (selector.length !== undefined) {
		els = selector;
	} else {
		throw "Invalid selector";
	}
	return new Ext.CompositeElementLite(els);
};
/**
* Selects elements based on the passed CSS selector to enable {@link Ext.Element Element} methods
* to be applied to many related elements in one statement through the returned {@link Ext.CompositeElement CompositeElement} or
* {@link Ext.CompositeElementLite CompositeElementLite} object.
* @param {String/Array} selector The CSS selector or an array of elements
* @param {HTMLElement/String} root (optional) The root element of the query or id of the root
* @return {CompositeElementLite/CompositeElement}
* @member Ext
* @method select
*/
Ext.select = Ext.Element.select;
/**
* @class Ext.CompositeElementLite
*/
Ext.apply(Ext.CompositeElementLite.prototype, {
	addElements: function (els, root) {
		if (!els) {
			return this;
		}
		if (typeof els == "string") {
			els = Ext.Element.selectorFunction(els, root);
		}
		var yels = this.elements;
		Ext.each(els, function (e) {
			yels.push(Ext.get(e));
		});
		return this;
	},

	/**
	* Returns the first Element
	* @return {Ext.Element}
	*/
	first: function () {
		return this.item(0);
	},

	/**
	* Returns the last Element
	* @return {Ext.Element}
	*/
	last: function () {
		return this.item(this.getCount() - 1);
	},

	/**
	* Returns true if this composite contains the passed element
	* @param el {Mixed} The id of an element, or an Ext.Element, or an HtmlElement to find within the composite collection.
	* @return Boolean
	*/
	contains: function (el) {
		return this.indexOf(el) != -1;
	},

	/**
	* Removes the specified element(s).
	* @param {Mixed} el The id of an element, the Element itself, the index of the element in this composite
	* or an array of any of those.
	* @param {Boolean} removeDom (optional) True to also remove the element from the document
	* @return {CompositeElement} this
	*/
	removeElement: function (keys, removeDom) {
		var me = this,
            els = this.elements,
            el;
		Ext.each(keys, function (val) {
			if ((el = (els[val] || els[val = me.indexOf(val)]))) {
				if (removeDom) {
					if (el.dom) {
						el.remove();
					} else {
						Ext.removeNode(el);
					}
				}
				els.splice(val, 1);
			}
		});
		return this;
	}
});
/**
* @class Ext.CompositeElement
* @extends Ext.CompositeElementLite
* <p>This class encapsulates a <i>collection</i> of DOM elements, providing methods to filter
* members, or to perform collective actions upon the whole set.</p>
* <p>Although they are not listed, this class supports all of the methods of {@link Ext.Element} and
* {@link Ext.Fx}. The methods from these classes will be performed on all the elements in this collection.</p>
* <p>All methods return <i>this</i> and can be chained.</p>
* Usage:
<pre><code>
var els = Ext.select("#some-el div.some-class", true);
// or select directly from an existing element
var el = Ext.get('some-el');
el.select('div.some-class', true);

els.setWidth(100); // all elements become 100 width
els.hide(true); // all elements fade out and hide
// or
els.setWidth(100).hide(true);
</code></pre>
*/
Ext.CompositeElement = Ext.extend(Ext.CompositeElementLite, {

	constructor: function (els, root) {
		this.elements = [];
		this.add(els, root);
	},

	// private
	getElement: function (el) {
		// In this case just return it, since we already have a reference to it
		return el;
	},

	// private
	transformElement: function (el) {
		return Ext.get(el);
	}

	/**
	* Adds elements to this composite.
	* @param {String/Array} els A string CSS selector, an array of elements or an element
	* @return {CompositeElement} this
	*/

	/**
	* Returns the Element object at the specified index
	* @param {Number} index
	* @return {Ext.Element}
	*/

	/**
	* Iterates each <code>element</code> in this <code>composite</code>
	* calling the supplied function using {@link Ext#each}.
	* @param {Function} fn The function to be called with each
	* <code>element</code>. If the supplied function returns <tt>false</tt>,
	* iteration stops. This function is called with the following arguments:
	* <div class="mdetail-params"><ul>
	* <li><code>element</code> : <i>Ext.Element</i><div class="sub-desc">The element at the current <code>index</code>
	* in the <code>composite</code></div></li>
	* <li><code>composite</code> : <i>Object</i> <div class="sub-desc">This composite.</div></li>
	* <li><code>index</code> : <i>Number</i> <div class="sub-desc">The current index within the <code>composite</code> </div></li>
	* </ul></div>
	* @param {Object} scope (optional) The scope (<code><this</code> reference) in which the specified function is executed.
	* Defaults to the <code>element</code> at the current <code>index</code>
	* within the composite.
	* @return {CompositeElement} this
	*/
});

/**
* Selects elements based on the passed CSS selector to enable {@link Ext.Element Element} methods
* to be applied to many related elements in one statement through the returned {@link Ext.CompositeElement CompositeElement} or
* {@link Ext.CompositeElementLite CompositeElementLite} object.
* @param {String/Array} selector The CSS selector or an array of elements
* @param {Boolean} unique (optional) true to create a unique Ext.Element for each element (defaults to a shared flyweight object)
* @param {HTMLElement/String} root (optional) The root element of the query or id of the root
* @return {CompositeElementLite/CompositeElement}
* @member Ext.Element
* @method select
*/
Ext.Element.select = function (selector, unique, root) {
	var els;
	if (typeof selector == "string") {
		els = Ext.Element.selectorFunction(selector, root);
	} else if (selector.length !== undefined) {
		els = selector;
	} else {
		throw "Invalid selector";
	}

	return (unique === true) ? new Ext.CompositeElement(els) : new Ext.CompositeElementLite(els);
};

/**
* Selects elements based on the passed CSS selector to enable {@link Ext.Element Element} methods
* to be applied to many related elements in one statement through the returned {@link Ext.CompositeElement CompositeElement} or
* {@link Ext.CompositeElementLite CompositeElementLite} object.
* @param {String/Array} selector The CSS selector or an array of elements
* @param {Boolean} unique (optional) true to create a unique Ext.Element for each element (defaults to a shared flyweight object)
* @param {HTMLElement/String} root (optional) The root element of the query or id of the root
* @return {CompositeElementLite/CompositeElement}
* @member Ext
* @method select
*/
Ext.select = Ext.Element.select; (function () {
	var BEFOREREQUEST = "beforerequest",
        REQUESTCOMPLETE = "requestcomplete",
        REQUESTEXCEPTION = "requestexception",
        UNDEFINED = undefined,
        LOAD = 'load',
        POST = 'POST',
        GET = 'GET',
        WINDOW = window;

	/**
	* @class Ext.data.Connection
	* @extends Ext.util.Observable
	* <p>The class encapsulates a connection to the page's originating domain, allowing requests to be made
	* either to a configured URL, or to a URL specified at request time.</p>
	* <p>Requests made by this class are asynchronous, and will return immediately. No data from
	* the server will be available to the statement immediately following the {@link #request} call.
	* To process returned data, use a
	* <a href="#request-option-success" ext:member="request-option-success" ext:cls="Ext.data.Connection">success callback</a>
	* in the request options object,
	* or an {@link #requestcomplete event listener}.</p>
	* <p><h3>File Uploads</h3><a href="#request-option-isUpload" ext:member="request-option-isUpload" ext:cls="Ext.data.Connection">File uploads</a> are not performed using normal "Ajax" techniques, that
	* is they are <b>not</b> performed using XMLHttpRequests. Instead the form is submitted in the standard
	* manner with the DOM <tt>&lt;form></tt> element temporarily modified to have its
	* <a href="http://www.w3.org/TR/REC-html40/present/frames.html#adef-target">target</a> set to refer
	* to a dynamically generated, hidden <tt>&lt;iframe></tt> which is inserted into the document
	* but removed after the return data has been gathered.</p>
	* <p>The server response is parsed by the browser to create the document for the IFRAME. If the
	* server is using JSON to send the return object, then the
	* <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17">Content-Type</a> header
	* must be set to "text/html" in order to tell the browser to insert the text unchanged into the document body.</p>
	* <p>Characters which are significant to an HTML parser must be sent as HTML entities, so encode
	* "&lt;" as "&amp;lt;", "&amp;" as "&amp;amp;" etc.</p>
	* <p>The response text is retrieved from the document, and a fake XMLHttpRequest object
	* is created containing a <tt>responseText</tt> property in order to conform to the
	* requirements of event handlers and callbacks.</p>
	* <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>
	* and some server technologies (notably JEE) may require some custom processing in order to
	* retrieve parameter names and parameter values from the packet content.</p>
	* @constructor
	* @param {Object} config a configuration object.
	*/
	Ext.data.Connection = function (config) {
		Ext.apply(this, config);
		this.addEvents(
		/**
		* @event beforerequest
		* Fires before a network request is made to retrieve a data object.
		* @param {Connection} conn This Connection object.
		* @param {Object} options The options config object passed to the {@link #request} method.
		*/
            BEFOREREQUEST,
		/**
		* @event requestcomplete
		* Fires if the request was successfully completed.
		* @param {Connection} conn This Connection object.
		* @param {Object} response The XHR object containing the response data.
		* See <a href="http://www.w3.org/TR/XMLHttpRequest/">The XMLHttpRequest Object</a>
		* for details.
		* @param {Object} options The options config object passed to the {@link #request} method.
		*/
            REQUESTCOMPLETE,
		/**
		* @event requestexception
		* Fires if an error HTTP status was returned from the server.
		* See <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html">HTTP Status Code Definitions</a>
		* for details of HTTP status codes.
		* @param {Connection} conn This Connection object.
		* @param {Object} response The XHR object containing the response data.
		* See <a href="http://www.w3.org/TR/XMLHttpRequest/">The XMLHttpRequest Object</a>
		* for details.
		* @param {Object} options The options config object passed to the {@link #request} method.
		*/
            REQUESTEXCEPTION
        );
		Ext.data.Connection.superclass.constructor.call(this);
	};

	Ext.extend(Ext.data.Connection, Ext.util.Observable, {
		/**
		* @cfg {String} url (Optional) <p>The default URL to be used for requests to the server. Defaults to undefined.</p>
		* <p>The <code>url</code> config may be a function which <i>returns</i> the URL to use for the Ajax request. The scope
		* (<code><b>this</b></code> reference) of the function is the <code>scope</code> option passed to the {@link #request} method.</p>
		*/
		/**
		* @cfg {Object} extraParams (Optional) An object containing properties which are used as
		* extra parameters to each request made by this object. (defaults to undefined)
		*/
		/**
		* @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
		*  to each request made by this object. (defaults to undefined)
		*/
		/**
		* @cfg {String} method (Optional) The default HTTP method to be used for requests.
		* (defaults to undefined; if not set, but {@link #request} params are present, POST will be used;
		* otherwise, GET will be used.)
		*/
		/**
		* @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
		*/
		timeout: 30000,
		/**
		* @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
		* @type Boolean
		*/
		autoAbort: false,

		/**
		* @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
		* @type Boolean
		*/
		disableCaching: true,

		/**
		* @cfg {String} disableCachingParam (Optional) Change the parameter which is sent went disabling caching
		* through a cache buster. Defaults to '_dc'
		* @type String
		*/
		disableCachingParam: '_dc',

		/**
		* <p>Sends an HTTP request to a remote server.</p>
		* <p><b>Important:</b> Ajax server requests are asynchronous, and this call will
		* return before the response has been received. Process any returned data
		* in a callback function.</p>
		* <pre><code>
		Ext.Ajax.request({
		url: 'ajax_demo/sample.json',
		success: function(response, opts) {
		var obj = Ext.decode(response.responseText);
		console.dir(obj);
		},
		failure: function(response, opts) {
		console.log('server-side failure with status code ' + response.status);
		}
		});
		* </code></pre>
		* <p>To execute a callback function in the correct scope, use the <tt>scope</tt> option.</p>
		* @param {Object} options An object which may contain the following properties:<ul>
		* <li><b>url</b> : String/Function (Optional)<div class="sub-desc">The URL to
		* which to send the request, or a function to call which returns a URL string. The scope of the
		* function is specified by the <tt>scope</tt> option. Defaults to the configured
		* <tt>{@link #url}</tt>.</div></li>
		* <li><b>params</b> : Object/String/Function (Optional)<div class="sub-desc">
		* An object containing properties which are used as parameters to the
		* request, a url encoded string or a function to call to get either. The scope of the function
		* is specified by the <tt>scope</tt> option.</div></li>
		* <li><b>method</b> : String (Optional)<div class="sub-desc">The HTTP method to use
		* for the request. Defaults to the configured method, or if no method was configured,
		* "GET" if no parameters are being sent, and "POST" if parameters are being sent.  Note that
		* the method name is case-sensitive and should be all caps.</div></li>
		* <li><b>callback</b> : Function (Optional)<div class="sub-desc">The
		* function to be called upon receipt of the HTTP response. The callback is
		* called regardless of success or failure and is passed the following
		* parameters:<ul>
		* <li><b>options</b> : Object<div class="sub-desc">The parameter to the request call.</div></li>
		* <li><b>success</b> : Boolean<div class="sub-desc">True if the request succeeded.</div></li>
		* <li><b>response</b> : Object<div class="sub-desc">The XMLHttpRequest object containing the response data.
		* See <a href="http://www.w3.org/TR/XMLHttpRequest/">http://www.w3.org/TR/XMLHttpRequest/</a> for details about
		* accessing elements of the response.</div></li>
		* </ul></div></li>
		* <li><a id="request-option-success"></a><b>success</b> : Function (Optional)<div class="sub-desc">The function
		* to be called upon success of the request. The callback is passed the following
		* parameters:<ul>
		* <li><b>response</b> : Object<div class="sub-desc">The XMLHttpRequest object containing the response data.</div></li>
		* <li><b>options</b> : Object<div class="sub-desc">The parameter to the request call.</div></li>
		* </ul></div></li>
		* <li><b>failure</b> : Function (Optional)<div class="sub-desc">The function
		* to be called upon failure of the request. The callback is passed the
		* following parameters:<ul>
		* <li><b>response</b> : Object<div class="sub-desc">The XMLHttpRequest object containing the response data.</div></li>
		* <li><b>options</b> : Object<div class="sub-desc">The parameter to the request call.</div></li>
		* </ul></div></li>
		* <li><b>scope</b> : Object (Optional)<div class="sub-desc">The scope in
		* which to execute the callbacks: The "this" object for the callback function. If the <tt>url</tt>, or <tt>params</tt> options were
		* specified as functions from which to draw values, then this also serves as the scope for those function calls.
		* Defaults to the browser window.</div></li>
		* <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>
		* <li><b>form</b> : Element/HTMLElement/String (Optional)<div class="sub-desc">The <tt>&lt;form&gt;</tt>
		* Element or the id of the <tt>&lt;form&gt;</tt> to pull parameters from.</div></li>
		* <li><a id="request-option-isUpload"></a><b>isUpload</b> : Boolean (Optional)<div class="sub-desc"><b>Only meaningful when used
		* with the <tt>form</tt> option</b>.
		* <p>True if the form object is a file upload (will be set automatically if the form was
		* configured with <b><tt>enctype</tt></b> "multipart/form-data").</p>
		* <p>File uploads are not performed using normal "Ajax" techniques, that is they are <b>not</b>
		* performed using XMLHttpRequests. Instead the form is submitted in the standard manner with the
		* DOM <tt>&lt;form></tt> element temporarily modified to have its
		* <a href="http://www.w3.org/TR/REC-html40/present/frames.html#adef-target">target</a> set to refer
		* to a dynamically generated, hidden <tt>&lt;iframe></tt> which is inserted into the document
		* but removed after the return data has been gathered.</p>
		* <p>The server response is parsed by the browser to create the document for the IFRAME. If the
		* server is using JSON to send the return object, then the
		* <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17">Content-Type</a> header
		* must be set to "text/html" in order to tell the browser to insert the text unchanged into the document body.</p>
		* <p>The response text is retrieved from the document, and a fake XMLHttpRequest object
		* is created containing a <tt>responseText</tt> property in order to conform to the
		* requirements of event handlers and callbacks.</p>
		* <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>
		* and some server technologies (notably JEE) may require some custom processing in order to
		* retrieve parameter names and parameter values from the packet content.</p>
		* </div></li>
		* <li><b>headers</b> : Object (Optional)<div class="sub-desc">Request
		* headers to set for the request.</div></li>
		* <li><b>xmlData</b> : Object (Optional)<div class="sub-desc">XML document
		* to use for the post. Note: This will be used instead of params for the post
		* data. Any params will be appended to the URL.</div></li>
		* <li><b>jsonData</b> : Object/String (Optional)<div class="sub-desc">JSON
		* data to use as the post. Note: This will be used instead of params for the post
		* data. Any params will be appended to the URL.</div></li>
		* <li><b>disableCaching</b> : Boolean (Optional)<div class="sub-desc">True
		* to add a unique cache-buster param to GET requests.</div></li>
		* </ul></p>
		* <p>The options object may also contain any other property which might be needed to perform
		* postprocessing in a callback because it is passed to callback functions.</p>
		* @return {Number} transactionId The id of the server transaction. This may be used
		* to cancel the request.
		*/
		request: function (o) {
			var me = this;
			if (me.fireEvent(BEFOREREQUEST, me, o)) {
				if (o.el) {
					if (!Ext.isEmpty(o.indicatorText)) {
						me.indicatorText = '<div class="loading-indicator">' + o.indicatorText + "</div>";
					}
					if (me.indicatorText) {
						Ext.getDom(o.el).innerHTML = me.indicatorText;
					}
					o.success = (Ext.isFunction(o.success) ? o.success : function () { }).createInterceptor(function (response) {
						Ext.getDom(o.el).innerHTML = response.responseText;
					});
				}

				var p = o.params,
                    url = o.url || me.url,
                    method,
                    cb = { success: me.handleResponse,
                    	failure: me.handleFailure,
                    	scope: me,
                    	argument: { options: o },
                    	timeout: o.timeout || me.timeout
                    },
                    form,
                    serForm;


				if (Ext.isFunction(p)) {
					p = p.call(o.scope || WINDOW, o);
				}

				p = Ext.urlEncode(me.extraParams, Ext.isObject(p) ? Ext.urlEncode(p) : p);

				if (Ext.isFunction(url)) {
					url = url.call(o.scope || WINDOW, o);
				}

				if ((form = Ext.getDom(o.form))) {
					url = url || form.action;
					if (o.isUpload || /multipart\/form-data/i.test(form.getAttribute("enctype"))) {
						return me.doFormUpload.call(me, o, p, url);
					}
					serForm = Ext.lib.Ajax.serializeForm(form);
					p = p ? (p + '&' + serForm) : serForm;
				}

				method = o.method || me.method || ((p || o.xmlData || o.jsonData) ? POST : GET);

				if (method === GET && (me.disableCaching && o.disableCaching !== false) || o.disableCaching === true) {
					var dcp = o.disableCachingParam || me.disableCachingParam;
					url = Ext.urlAppend(url, dcp + '=' + (new Date().getTime()));
				}

				o.headers = Ext.apply(o.headers || {}, me.defaultHeaders || {});

				if (o.autoAbort === true || me.autoAbort) {
					me.abort();
				}

				if ((method == GET || o.xmlData || o.jsonData) && p) {
					url = Ext.urlAppend(url, p);
					p = '';
				}
				return (me.transId = Ext.lib.Ajax.request(method, url, cb, p, o));
			} else {
				return o.callback ? o.callback.apply(o.scope, [o, UNDEFINED, UNDEFINED]) : null;
			}
		},

		/**
		* Determine whether this object has a request outstanding.
		* @param {Number} transactionId (Optional) defaults to the last transaction
		* @return {Boolean} True if there is an outstanding request.
		*/
		isLoading: function (transId) {
			return transId ? Ext.lib.Ajax.isCallInProgress(transId) : !!this.transId;
		},

		/**
		* Aborts any outstanding request.
		* @param {Number} transactionId (Optional) defaults to the last transaction
		*/
		abort: function (transId) {
			if (transId || this.isLoading()) {
				Ext.lib.Ajax.abort(transId || this.transId);
			}
		},

		// private
		handleResponse: function (response) {
			this.transId = false;
			var options = response.argument.options;
			response.argument = options ? options.argument : null;
			this.fireEvent(REQUESTCOMPLETE, this, response, options);
			if (options.success) {
				options.success.call(options.scope, response, options);
			}
			if (options.callback) {
				options.callback.call(options.scope, options, true, response);
			}
		},

		// private
		handleFailure: function (response, e) {
			this.transId = false;
			var options = response.argument.options;
			response.argument = options ? options.argument : null;
			this.fireEvent(REQUESTEXCEPTION, this, response, options, e);
			if (options.failure) {
				options.failure.call(options.scope, response, options);
			}
			if (options.callback) {
				options.callback.call(options.scope, options, false, response);
			}
		},

		// private
		doFormUpload: function (o, ps, url) {
			var id = Ext.id(),
                doc = document,
                frame = doc.createElement('iframe'),
                form = Ext.getDom(o.form),
                hiddens = [],
                hd,
                encoding = 'multipart/form-data',
                buf = {
                	target: form.target,
                	method: form.method,
                	encoding: form.encoding,
                	enctype: form.enctype,
                	action: form.action
                };

			/*
			* Originally this behaviour was modified for Opera 10 to apply the secure URL after
			* the frame had been added to the document. It seems this has since been corrected in
			* Opera so the behaviour has been reverted, the URL will be set before being added.
			*/
			Ext.fly(frame).set({
				id: id,
				name: id,
				cls: 'x-hidden',
				src: Ext.SSL_SECURE_URL
			});

			doc.body.appendChild(frame);

			// This is required so that IE doesn't pop the response up in a new window.
			if (Ext.isIE) {
				document.frames[id].name = id;
			}


			Ext.fly(form).set({
				target: id,
				method: POST,
				enctype: encoding,
				encoding: encoding,
				action: url || buf.action
			});

			// add dynamic params
			Ext.iterate(Ext.urlDecode(ps, false), function (k, v) {
				hd = doc.createElement('input');
				Ext.fly(hd).set({
					type: 'hidden',
					value: v,
					name: k
				});
				form.appendChild(hd);
				hiddens.push(hd);
			});

			function cb() {
				var me = this,
				// bogus response object
                    r = { responseText: '',
                    	responseXML: null,
                    	argument: o.argument
                    },
                    doc,
                    firstChild;

				try {
					doc = frame.contentWindow.document || frame.contentDocument || WINDOW.frames[id].document;
					if (doc) {
						if (doc.body) {
							if (/textarea/i.test((firstChild = doc.body.firstChild || {}).tagName)) { // json response wrapped in textarea
								r.responseText = firstChild.value;
							} else {
								r.responseText = doc.body.innerHTML;
							}
						}
						//in IE the document may still have a body even if returns XML.
						r.responseXML = doc.XMLDocument || doc;
					}
				}
				catch (e) { }

				Ext.EventManager.removeListener(frame, LOAD, cb, me);

				me.fireEvent(REQUESTCOMPLETE, me, r, o);

				function runCallback(fn, scope, args) {
					if (Ext.isFunction(fn)) {
						fn.apply(scope, args);
					}
				}

				runCallback(o.success, o.scope, [r, o]);
				runCallback(o.callback, o.scope, [o, true, r]);

				if (!me.debugUploads) {
					setTimeout(function () { Ext.removeNode(frame); }, 100);
				}
			}

			Ext.EventManager.on(frame, LOAD, cb, this);
			form.submit();

			Ext.fly(form).set(buf);
			Ext.each(hiddens, function (h) {
				Ext.removeNode(h);
			});
		}
	});
})();

/**
* @class Ext.Ajax
* @extends Ext.data.Connection
* <p>The global Ajax request class that provides a simple way to make Ajax requests
* with maximum flexibility.</p>
* <p>Since Ext.Ajax is a singleton, you can set common properties/events for it once
* and override them at the request function level only if necessary.</p>
* <p>Common <b>Properties</b> you may want to set are:<div class="mdetail-params"><ul>
* <li><b><tt>{@link #method}</tt></b><p class="sub-desc"></p></li>
* <li><b><tt>{@link #extraParams}</tt></b><p class="sub-desc"></p></li>
* <li><b><tt>{@link #url}</tt></b><p class="sub-desc"></p></li>
* </ul></div>
* <pre><code>
// Default headers to pass in every request
Ext.Ajax.defaultHeaders = {
'Powered-By': 'Ext'
};
* </code></pre>
* </p>
* <p>Common <b>Events</b> you may want to set are:<div class="mdetail-params"><ul>
* <li><b><tt>{@link Ext.data.Connection#beforerequest beforerequest}</tt></b><p class="sub-desc"></p></li>
* <li><b><tt>{@link Ext.data.Connection#requestcomplete requestcomplete}</tt></b><p class="sub-desc"></p></li>
* <li><b><tt>{@link Ext.data.Connection#requestexception requestexception}</tt></b><p class="sub-desc"></p></li>
* </ul></div>
* <pre><code>
// Example: show a spinner during all Ajax requests
Ext.Ajax.on('beforerequest', this.showSpinner, this);
Ext.Ajax.on('requestcomplete', this.hideSpinner, this);
Ext.Ajax.on('requestexception', this.hideSpinner, this);
* </code></pre>
* </p>
* <p>An example request:</p>
* <pre><code>
// Basic request
Ext.Ajax.{@link Ext.data.Connection#request request}({
url: 'foo.php',
success: someFn,
failure: otherFn,
headers: {
'my-header': 'foo'
},
params: { foo: 'bar' }
});

// Simple ajax form submission
Ext.Ajax.{@link Ext.data.Connection#request request}({
form: 'some-form',
params: 'foo=bar'
});
* </code></pre>
* </p>
* @singleton
*/
Ext.Ajax = new Ext.data.Connection({
	/**
	* @cfg {String} url @hide
	*/
	/**
	* @cfg {Object} extraParams @hide
	*/
	/**
	* @cfg {Object} defaultHeaders @hide
	*/
	/**
	* @cfg {String} method (Optional) @hide
	*/
	/**
	* @cfg {Number} timeout (Optional) @hide
	*/
	/**
	* @cfg {Boolean} autoAbort (Optional) @hide
	*/

	/**
	* @cfg {Boolean} disableCaching (Optional) @hide
	*/

	/**
	* @property  disableCaching
	* True to add a unique cache-buster param to GET requests. (defaults to true)
	* @type Boolean
	*/
	/**
	* @property  url
	* The default URL to be used for requests to the server. (defaults to undefined)
	* If the server receives all requests through one URL, setting this once is easier than
	* entering it on every request.
	* @type String
	*/
	/**
	* @property  extraParams
	* An object containing properties which are used as extra parameters to each request made
	* by this object (defaults to undefined). Session information and other data that you need
	* to pass with each request are commonly put here.
	* @type Object
	*/
	/**
	* @property  defaultHeaders
	* An object containing request headers which are added to each request made by this object
	* (defaults to undefined).
	* @type Object
	*/
	/**
	* @property  method
	* The default HTTP method to be used for requests. Note that this is case-sensitive and
	* should be all caps (defaults to undefined; if not set but params are present will use
	* <tt>"POST"</tt>, otherwise will use <tt>"GET"</tt>.)
	* @type String
	*/
	/**
	* @property  timeout
	* The timeout in milliseconds to be used for requests. (defaults to 30000)
	* @type Number
	*/

	/**
	* @property  autoAbort
	* Whether a new request should abort any pending requests. (defaults to false)
	* @type Boolean
	*/
	autoAbort: false,

	/**
	* Serialize the passed form into a url encoded string
	* @param {String/HTMLElement} form
	* @return {String}
	*/
	serializeForm: function (form) {
		return Ext.lib.Ajax.serializeForm(form);
	}
});
/**
* @class Ext.Updater
* @extends Ext.util.Observable
* Provides AJAX-style update capabilities for Element objects.  Updater can be used to {@link #update}
* an {@link Ext.Element} once, or you can use {@link #startAutoRefresh} to set up an auto-updating
* {@link Ext.Element Element} on a specific interval.<br><br>
* Usage:<br>
* <pre><code>
* var el = Ext.get("foo"); // Get Ext.Element object
* var mgr = el.getUpdater();
* mgr.update({
url: "http://myserver.com/index.php",
params: {
param1: "foo",
param2: "bar"
}
* });
* ...
* mgr.formUpdate("myFormId", "http://myserver.com/index.php");
* <br>
* // or directly (returns the same Updater instance)
* var mgr = new Ext.Updater("myElementId");
* mgr.startAutoRefresh(60, "http://myserver.com/index.php");
* mgr.on("update", myFcnNeedsToKnow);
* <br>
* // short handed call directly from the element object
* Ext.get("foo").load({
url: "bar.php",
scripts: true,
params: "param1=foo&amp;param2=bar",
text: "Loading Foo..."
* });
* </code></pre>
* @constructor
* Create new Updater directly.
* @param {Mixed} el The element to update
* @param {Boolean} forceNew (optional) By default the constructor checks to see if the passed element already
* has an Updater and if it does it returns the same instance. This will skip that check (useful for extending this class).
*/
Ext.UpdateManager = Ext.Updater = Ext.extend(Ext.util.Observable,
function () {
	var BEFOREUPDATE = "beforeupdate",
        UPDATE = "update",
        FAILURE = "failure";

	// private
	function processSuccess(response) {
		var me = this;
		me.transaction = null;
		if (response.argument.form && response.argument.reset) {
			try { // put in try/catch since some older FF releases had problems with this
				response.argument.form.reset();
			} catch (e) { }
		}
		if (me.loadScripts) {
			me.renderer.render(me.el, response, me,
               updateComplete.createDelegate(me, [response]));
		} else {
			me.renderer.render(me.el, response, me);
			updateComplete.call(me, response);
		}
	}

	// private
	function updateComplete(response, type, success) {
		this.fireEvent(type || UPDATE, this.el, response);
		if (Ext.isFunction(response.argument.callback)) {
			response.argument.callback.call(response.argument.scope, this.el, Ext.isEmpty(success) ? true : false, response, response.argument.options);
		}
	}

	// private
	function processFailure(response) {
		updateComplete.call(this, response, FAILURE, !!(this.transaction = null));
	}

	return {
		constructor: function (el, forceNew) {
			var me = this;
			el = Ext.get(el);
			if (!forceNew && el.updateManager) {
				return el.updateManager;
			}
			/**
			* The Element object
			* @type Ext.Element
			*/
			me.el = el;
			/**
			* Cached url to use for refreshes. Overwritten every time update() is called unless "discardUrl" param is set to true.
			* @type String
			*/
			me.defaultUrl = null;

			me.addEvents(
			/**
			* @event beforeupdate
			* Fired before an update is made, return false from your handler and the update is cancelled.
			* @param {Ext.Element} el
			* @param {String/Object/Function} url
			* @param {String/Object} params
			*/
                BEFOREUPDATE,
			/**
			* @event update
			* Fired after successful update is made.
			* @param {Ext.Element} el
			* @param {Object} oResponseObject The response Object
			*/
                UPDATE,
			/**
			* @event failure
			* Fired on update failure.
			* @param {Ext.Element} el
			* @param {Object} oResponseObject The response Object
			*/
                FAILURE
            );

			Ext.apply(me, Ext.Updater.defaults);
			/**
			* Blank page URL to use with SSL file uploads (defaults to {@link Ext.Updater.defaults#sslBlankUrl}).
			* @property sslBlankUrl
			* @type String
			*/
			/**
			* Whether to append unique parameter on get request to disable caching (defaults to {@link Ext.Updater.defaults#disableCaching}).
			* @property disableCaching
			* @type Boolean
			*/
			/**
			* Text for loading indicator (defaults to {@link Ext.Updater.defaults#indicatorText}).
			* @property indicatorText
			* @type String
			*/
			/**
			* Whether to show indicatorText when loading (defaults to {@link Ext.Updater.defaults#showLoadIndicator}).
			* @property showLoadIndicator
			* @type String
			*/
			/**
			* Timeout for requests or form posts in seconds (defaults to {@link Ext.Updater.defaults#timeout}).
			* @property timeout
			* @type Number
			*/
			/**
			* True to process scripts in the output (defaults to {@link Ext.Updater.defaults#loadScripts}).
			* @property loadScripts
			* @type Boolean
			*/

			/**
			* Transaction object of the current executing transaction, or null if there is no active transaction.
			*/
			me.transaction = null;
			/**
			* Delegate for refresh() prebound to "this", use myUpdater.refreshDelegate.createCallback(arg1, arg2) to bind arguments
			* @type Function
			*/
			me.refreshDelegate = me.refresh.createDelegate(me);
			/**
			* Delegate for update() prebound to "this", use myUpdater.updateDelegate.createCallback(arg1, arg2) to bind arguments
			* @type Function
			*/
			me.updateDelegate = me.update.createDelegate(me);
			/**
			* Delegate for formUpdate() prebound to "this", use myUpdater.formUpdateDelegate.createCallback(arg1, arg2) to bind arguments
			* @type Function
			*/
			me.formUpdateDelegate = (me.formUpdate || function () { }).createDelegate(me);

			/**
			* The renderer for this Updater (defaults to {@link Ext.Updater.BasicRenderer}).
			*/
			me.renderer = me.renderer || me.getDefaultRenderer();

			Ext.Updater.superclass.constructor.call(me);
		},

		/**
		* Sets the content renderer for this Updater. See {@link Ext.Updater.BasicRenderer#render} for more details.
		* @param {Object} renderer The object implementing the render() method
		*/
		setRenderer: function (renderer) {
			this.renderer = renderer;
		},

		/**
		* Returns the current content renderer for this Updater. See {@link Ext.Updater.BasicRenderer#render} for more details.
		* @return {Object}
		*/
		getRenderer: function () {
			return this.renderer;
		},

		/**
		* This is an overrideable method which returns a reference to a default
		* renderer class if none is specified when creating the Ext.Updater.
		* Defaults to {@link Ext.Updater.BasicRenderer}
		*/
		getDefaultRenderer: function () {
			return new Ext.Updater.BasicRenderer();
		},

		/**
		* Sets the default URL used for updates.
		* @param {String/Function} defaultUrl The url or a function to call to get the url
		*/
		setDefaultUrl: function (defaultUrl) {
			this.defaultUrl = defaultUrl;
		},

		/**
		* Get the Element this Updater is bound to
		* @return {Ext.Element} The element
		*/
		getEl: function () {
			return this.el;
		},

		/**
		* Performs an <b>asynchronous</b> request, updating this element with the response.
		* If params are specified it uses POST, otherwise it uses GET.<br><br>
		* <b>Note:</b> Due to the asynchronous nature of remote server requests, the Element
		* will not have been fully updated when the function returns. To post-process the returned
		* data, use the callback option, or an <b><code>update</code></b> event handler.
		* @param {Object} options A config object containing any of the following options:<ul>
		* <li>url : <b>String/Function</b><p class="sub-desc">The URL to request or a function which
		* <i>returns</i> the URL (defaults to the value of {@link Ext.Ajax#url} if not specified).</p></li>
		* <li>method : <b>String</b><p class="sub-desc">The HTTP method to
		* use. Defaults to POST if the <code>params</code> argument is present, otherwise GET.</p></li>
		* <li>params : <b>String/Object/Function</b><p class="sub-desc">The
		* parameters to pass to the server (defaults to none). These may be specified as a url-encoded
		* string, or as an object containing properties which represent parameters,
		* or as a function, which returns such an object.</p></li>
		* <li>scripts : <b>Boolean</b><p class="sub-desc">If <code>true</code>
		* any &lt;script&gt; tags embedded in the response text will be extracted
		* and executed (defaults to {@link Ext.Updater.defaults#loadScripts}). If this option is specified,
		* the callback will be called <i>after</i> the execution of the scripts.</p></li>
		* <li>callback : <b>Function</b><p class="sub-desc">A function to
		* be called when the response from the server arrives. The following
		* parameters are passed:<ul>
		* <li><b>el</b> : Ext.Element<p class="sub-desc">The Element being updated.</p></li>
		* <li><b>success</b> : Boolean<p class="sub-desc">True for success, false for failure.</p></li>
		* <li><b>response</b> : XMLHttpRequest<p class="sub-desc">The XMLHttpRequest which processed the update.</p></li>
		* <li><b>options</b> : Object<p class="sub-desc">The config object passed to the update call.</p></li></ul>
		* </p></li>
		* <li>scope : <b>Object</b><p class="sub-desc">The scope in which
		* to execute the callback (The callback's <code>this</code> reference.) If the
		* <code>params</code> argument is a function, this scope is used for that function also.</p></li>
		* <li>discardUrl : <b>Boolean</b><p class="sub-desc">By default, the URL of this request becomes
		* the default URL for this Updater object, and will be subsequently used in {@link #refresh}
		* calls.  To bypass this behavior, pass <code>discardUrl:true</code> (defaults to false).</p></li>
		* <li>timeout : <b>Number</b><p class="sub-desc">The number of seconds to wait for a response before
		* timing out (defaults to {@link Ext.Updater.defaults#timeout}).</p></li>
		* <li>text : <b>String</b><p class="sub-desc">The text to use as the innerHTML of the
		* {@link Ext.Updater.defaults#indicatorText} div (defaults to 'Loading...').  To replace the entire div, not
		* just the text, override {@link Ext.Updater.defaults#indicatorText} directly.</p></li>
		* <li>nocache : <b>Boolean</b><p class="sub-desc">Only needed for GET
		* requests, this option causes an extra, auto-generated parameter to be appended to the request
		* to defeat caching (defaults to {@link Ext.Updater.defaults#disableCaching}).</p></li></ul>
		* <p>
		* For example:
		<pre><code>
		um.update({
		url: "your-url.php",
		params: {param1: "foo", param2: "bar"}, // or a URL encoded string
		callback: yourFunction,
		scope: yourObject, //(optional scope)
		discardUrl: true,
		nocache: true,
		text: "Loading...",
		timeout: 60,
		scripts: false // Save time by avoiding RegExp execution.
		});
		</code></pre>
		*/
		update: function (url, params, callback, discardUrl) {
			var me = this,
                cfg,
                callerScope;

			if (me.fireEvent(BEFOREUPDATE, me.el, url, params) !== false) {
				if (Ext.isObject(url)) { // must be config object
					cfg = url;
					url = cfg.url;
					params = params || cfg.params;
					callback = callback || cfg.callback;
					discardUrl = discardUrl || cfg.discardUrl;
					callerScope = cfg.scope;
					if (!Ext.isEmpty(cfg.nocache)) { me.disableCaching = cfg.nocache; };
					if (!Ext.isEmpty(cfg.text)) { me.indicatorText = '<div class="loading-indicator">' + cfg.text + "</div>"; };
					if (!Ext.isEmpty(cfg.scripts)) { me.loadScripts = cfg.scripts; };
					if (!Ext.isEmpty(cfg.timeout)) { me.timeout = cfg.timeout; };
				}
				me.showLoading();

				if (!discardUrl) {
					me.defaultUrl = url;
				}
				if (Ext.isFunction(url)) {
					url = url.call(me);
				}

				var o = Ext.apply({}, {
					url: url,
					params: (Ext.isFunction(params) && callerScope) ? params.createDelegate(callerScope) : params,
					success: processSuccess,
					failure: processFailure,
					scope: me,
					callback: undefined,
					timeout: (me.timeout * 1000),
					disableCaching: me.disableCaching,
					argument: {
						"options": cfg,
						"url": url,
						"form": null,
						"callback": callback,
						"scope": callerScope || window,
						"params": params
					}
				}, cfg);

				me.transaction = Ext.Ajax.request(o);
			}
		},

		/**
		* <p>Performs an asynchronous form post, updating this element with the response. If the form has the attribute
		* enctype="<a href="http://www.faqs.org/rfcs/rfc2388.html">multipart/form-data</a>", it assumes it's a file upload.
		* Uses this.sslBlankUrl for SSL file uploads to prevent IE security warning.</p>
		* <p>File uploads are not performed using normal "Ajax" techniques, that is they are <b>not</b>
		* performed using XMLHttpRequests. Instead the form is submitted in the standard manner with the
		* DOM <code>&lt;form></code> element temporarily modified to have its
		* <a href="http://www.w3.org/TR/REC-html40/present/frames.html#adef-target">target</a> set to refer
		* to a dynamically generated, hidden <code>&lt;iframe></code> which is inserted into the document
		* but removed after the return data has been gathered.</p>
		* <p>Be aware that file upload packets, sent with the content type <a href="http://www.faqs.org/rfcs/rfc2388.html">multipart/form-data</a>
		* and some server technologies (notably JEE) may require some custom processing in order to
		* retrieve parameter names and parameter values from the packet content.</p>
		* @param {String/HTMLElement} form The form Id or form element
		* @param {String} url (optional) The url to pass the form to. If omitted the action attribute on the form will be used.
		* @param {Boolean} reset (optional) Whether to try to reset the form after the update
		* @param {Function} callback (optional) Callback when transaction is complete. The following
		* parameters are passed:<ul>
		* <li><b>el</b> : Ext.Element<p class="sub-desc">The Element being updated.</p></li>
		* <li><b>success</b> : Boolean<p class="sub-desc">True for success, false for failure.</p></li>
		* <li><b>response</b> : XMLHttpRequest<p class="sub-desc">The XMLHttpRequest which processed the update.</p></li></ul>
		*/
		formUpdate: function (form, url, reset, callback) {
			var me = this;
			if (me.fireEvent(BEFOREUPDATE, me.el, form, url) !== false) {
				if (Ext.isFunction(url)) {
					url = url.call(me);
				}
				form = Ext.getDom(form);
				me.transaction = Ext.Ajax.request({
					form: form,
					url: url,
					success: processSuccess,
					failure: processFailure,
					scope: me,
					timeout: (me.timeout * 1000),
					argument: {
						"url": url,
						"form": form,
						"callback": callback,
						"reset": reset
					}
				});
				me.showLoading.defer(1, me);
			}
		},

		/**
		* Set this element to auto refresh.  Can be canceled by calling {@link #stopAutoRefresh}.
		* @param {Number} interval How often to update (in seconds).
		* @param {String/Object/Function} url (optional) The url for this request, a config object in the same format
		* supported by {@link #load}, or a function to call to get the url (defaults to the last used url).  Note that while
		* the url used in a load call can be reused by this method, other load config options will not be reused and must be
		* sepcified as part of a config object passed as this paramter if needed.
		* @param {String/Object} params (optional) The parameters to pass as either a url encoded string
		* "&param1=1&param2=2" or as an object {param1: 1, param2: 2}
		* @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
		* @param {Boolean} refreshNow (optional) Whether to execute the refresh now, or wait the interval
		*/
		startAutoRefresh: function (interval, url, params, callback, refreshNow) {
			var me = this;
			if (refreshNow) {
				me.update(url || me.defaultUrl, params, callback, true);
			}
			if (me.autoRefreshProcId) {
				clearInterval(me.autoRefreshProcId);
			}
			me.autoRefreshProcId = setInterval(me.update.createDelegate(me, [url || me.defaultUrl, params, callback, true]), interval * 1000);
		},

		/**
		* Stop auto refresh on this element.
		*/
		stopAutoRefresh: function () {
			if (this.autoRefreshProcId) {
				clearInterval(this.autoRefreshProcId);
				delete this.autoRefreshProcId;
			}
		},

		/**
		* Returns true if the Updater is currently set to auto refresh its content (see {@link #startAutoRefresh}), otherwise false.
		*/
		isAutoRefreshing: function () {
			return !!this.autoRefreshProcId;
		},

		/**
		* Display the element's "loading" state. By default, the element is updated with {@link #indicatorText}. This
		* method may be overridden to perform a custom action while this Updater is actively updating its contents.
		*/
		showLoading: function () {
			if (this.showLoadIndicator) {
				this.el.dom.innerHTML = this.indicatorText;
			}
		},

		/**
		* Aborts the currently executing transaction, if any.
		*/
		abort: function () {
			if (this.transaction) {
				Ext.Ajax.abort(this.transaction);
			}
		},

		/**
		* Returns true if an update is in progress, otherwise false.
		* @return {Boolean}
		*/
		isUpdating: function () {
			return this.transaction ? Ext.Ajax.isLoading(this.transaction) : false;
		},

		/**
		* Refresh the element with the last used url or defaultUrl. If there is no url, it returns immediately
		* @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
		*/
		refresh: function (callback) {
			if (this.defaultUrl) {
				this.update(this.defaultUrl, null, callback, true);
			}
		}
	}
} ());

/**
* @class Ext.Updater.defaults
* The defaults collection enables customizing the default properties of Updater
*/
Ext.Updater.defaults = {
	/**
	* Timeout for requests or form posts in seconds (defaults to 30 seconds).
	* @type Number
	*/
	timeout: 30,
	/**
	* True to append a unique parameter to GET requests to disable caching (defaults to false).
	* @type Boolean
	*/
	disableCaching: false,
	/**
	* Whether or not to show {@link #indicatorText} during loading (defaults to true).
	* @type Boolean
	*/
	showLoadIndicator: true,
	/**
	* Text for loading indicator (defaults to '&lt;div class="loading-indicator"&gt;Loading...&lt;/div&gt;').
	* @type String
	*/
	indicatorText: '<div class="loading-indicator">Loading...</div>',
	/**
	* True to process scripts by default (defaults to false).
	* @type Boolean
	*/
	loadScripts: false,
	/**
	* Blank page URL to use with SSL file uploads (defaults to {@link Ext#SSL_SECURE_URL} if set, or "javascript:false").
	* @type String
	*/
	sslBlankUrl: Ext.SSL_SECURE_URL
};


/**
* Static convenience method. <b>This method is deprecated in favor of el.load({url:'foo.php', ...})</b>.
* Usage:
* <pre><code>Ext.Updater.updateElement("my-div", "stuff.php");</code></pre>
* @param {Mixed} el The element to update
* @param {String} url The url
* @param {String/Object} params (optional) Url encoded param string or an object of name/value pairs
* @param {Object} options (optional) A config object with any of the Updater properties you want to set - for
* example: {disableCaching:true, indicatorText: "Loading data..."}
* @static
* @deprecated
* @member Ext.Updater
*/
Ext.Updater.updateElement = function (el, url, params, options) {
	var um = Ext.get(el).getUpdater();
	Ext.apply(um, options);
	um.update(url, params, options ? options.callback : null);
};

/**
* @class Ext.Updater.BasicRenderer
* <p>This class is a base class implementing a simple render method which updates an element using results from an Ajax request.</p>
* <p>The BasicRenderer updates the element's innerHTML with the responseText. To perform a custom render (i.e. XML or JSON processing),
* create an object with a conforming {@link #render} method and pass it to setRenderer on the Updater.</p>
*/
Ext.Updater.BasicRenderer = function () { };

Ext.Updater.BasicRenderer.prototype = {
	/**
	* This method is called when an Ajax response is received, and an Element needs updating.
	* @param {Ext.Element} el The element being rendered
	* @param {Object} xhr The XMLHttpRequest object
	* @param {Updater} updateManager The calling update manager
	* @param {Function} callback A callback that will need to be called if loadScripts is true on the Updater
	*/
	render: function (el, response, updateManager, callback) {
		el.update(response.responseText, updateManager.loadScripts, callback);
	}
}; /**
 * @class Date
 *
 * The date parsing and formatting syntax contains a subset of
 * <a href="http://www.php.net/date">PHP's date() function</a>, and the formats that are
 * supported will provide results equivalent to their PHP versions.
 *
 * The following is a list of all currently supported formats:
 * <pre>
Format  Description                                                               Example returned values
------  -----------------------------------------------------------------------   -----------------------
  d     Day of the month, 2 digits with leading zeros                             01 to 31
  D     A short textual representation of the day of the week                     Mon to Sun
  j     Day of the month without leading zeros                                    1 to 31
  l     A full textual representation of the day of the week                      Sunday to Saturday
  N     ISO-8601 numeric representation of the day of the week                    1 (for Monday) through 7 (for Sunday)
  S     English ordinal suffix for the day of the month, 2 characters             st, nd, rd or th. Works well with j
  w     Numeric representation of the day of the week                             0 (for Sunday) to 6 (for Saturday)
  z     The day of the year (starting from 0)                                     0 to 364 (365 in leap years)
  W     ISO-8601 week number of year, weeks starting on Monday                    01 to 53
  F     A full textual representation of a month, such as January or March        January to December
  m     Numeric representation of a month, with leading zeros                     01 to 12
  M     A short textual representation of a month                                 Jan to Dec
  n     Numeric representation of a month, without leading zeros                  1 to 12
  t     Number of days in the given month                                         28 to 31
  L     Whether it's a leap year                                                  1 if it is a leap year, 0 otherwise.
  o     ISO-8601 year number (identical to (Y), but if the ISO week number (W)    Examples: 1998 or 2004
        belongs to the previous or next year, that year is used instead)
  Y     A full numeric representation of a year, 4 digits                         Examples: 1999 or 2003
  y     A two digit representation of a year                                      Examples: 99 or 03
  a     Lowercase Ante meridiem and Post meridiem                                 am or pm
  A     Uppercase Ante meridiem and Post meridiem                                 AM or PM
  g     12-hour format of an hour without leading zeros                           1 to 12
  G     24-hour format of an hour without leading zeros                           0 to 23
  h     12-hour format of an hour with leading zeros                              01 to 12
  H     24-hour format of an hour with leading zeros                              00 to 23
  i     Minutes, with leading zeros                                               00 to 59
  s     Seconds, with leading zeros                                               00 to 59
  u     Decimal fraction of a second                                              Examples:
        (minimum 1 digit, arbitrary number of digits allowed)                     001 (i.e. 0.001s) or
                                                                                  100 (i.e. 0.100s) or
                                                                                  999 (i.e. 0.999s) or
                                                                                  999876543210 (i.e. 0.999876543210s)
  O     Difference to Greenwich time (GMT) in hours and minutes                   Example: +1030
  P     Difference to Greenwich time (GMT) with colon between hours and minutes   Example: -08:00
  T     Timezone abbreviation of the machine running the code                     Examples: EST, MDT, PDT ...
  Z     Timezone offset in seconds (negative if west of UTC, positive if east)    -43200 to 50400
  c     ISO 8601 date
        Notes:                                                                    Examples:
        1) If unspecified, the month / day defaults to the current month / day,   1991 or
           the time defaults to midnight, while the timezone defaults to the      1992-10 or
           browser's timezone. If a time is specified, it must include both hours 1993-09-20 or
           and minutes. The "T" delimiter, seconds, milliseconds and timezone     1994-08-19T16:20+01:00 or
           are optional.                                                          1995-07-18T17:21:28-02:00 or
        2) The decimal fraction of a second, if specified, must contain at        1996-06-17T18:22:29.98765+03:00 or
           least 1 digit (there is no limit to the maximum number                 1997-05-16T19:23:30,12345-0400 or
           of digits allowed), and may be delimited by either a '.' or a ','      1998-04-15T20:24:31.2468Z or
        Refer to the examples on the right for the various levels of              1999-03-14T20:24:32Z or
        date-time granularity which are supported, or see                         2000-02-13T21:25:33
        http://www.w3.org/TR/NOTE-datetime for more info.                         2001-01-12 22:26:34
  U     Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)                1193432466 or -2138434463
  M$    Microsoft AJAX serialized dates                                           \/Date(1238606590509)\/ (i.e. UTC milliseconds since epoch) or
                                                                                  \/Date(1238606590509+0800)\/
</pre>
 *
 * Example usage (note that you must escape format specifiers with '\\' to render them as character literals):
 * <pre><code>
// Sample date:
// 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'

var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
document.write(dt.format('Y-m-d'));                           // 2007-01-10
document.write(dt.format('F j, Y, g:i a'));                   // January 10, 2007, 3:05 pm
document.write(dt.format('l, \\t\\he jS \\of F Y h:i:s A'));  // Wednesday, the 10th of January 2007 03:05:01 PM
</code></pre>
 *
 * Here are some standard date/time patterns that you might find helpful.  They
 * are not part of the source of Date.js, but to use them you can simply copy this
 * block of code into any script that is included after Date.js and they will also become
 * globally available on the Date object.  Feel free to add or remove patterns as needed in your code.
 * <pre><code>
Date.patterns = {
    ISO8601Long:"Y-m-d H:i:s",
    ISO8601Short:"Y-m-d",
    ShortDate: "n/j/Y",
    LongDate: "l, F d, Y",
    FullDateTime: "l, F d, Y g:i:s A",
    MonthDay: "F d",
    ShortTime: "g:i A",
    LongTime: "g:i:s A",
    SortableDateTime: "Y-m-d\\TH:i:s",
    UniversalSortableDateTime: "Y-m-d H:i:sO",
    YearMonth: "F, Y"
};
</code></pre>
 *
 * Example usage:
 * <pre><code>
var dt = new Date();
document.write(dt.format(Date.patterns.ShortDate));
</code></pre>
 * <p>Developer-written, custom formats may be used by supplying both a formatting and a parsing function
 * which perform to specialized requirements. The functions are stored in {@link #parseFunctions} and {@link #formatFunctions}.</p>
 */

/*
* Most of the date-formatting functions below are the excellent work of Baron Schwartz.
* (see http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/)
* They generate precompiled functions from format patterns instead of parsing and
* processing each pattern every time a date is formatted. These functions are available
* on every Date object.
*/

(function () {

	/**
	* Global flag which determines if strict date parsing should be used.
	* Strict date parsing will not roll-over invalid dates, which is the
	* default behaviour of javascript Date objects.
	* (see {@link #parseDate} for more information)
	* Defaults to <tt>false</tt>.
	* @static
	* @type Boolean
	*/
	Date.useStrict = false;


	// create private copy of Ext's String.format() method
	// - to remove unnecessary dependency
	// - to resolve namespace conflict with M$-Ajax's implementation
	function xf(format) {
		var args = Array.prototype.slice.call(arguments, 1);
		return format.replace(/\{(\d+)\}/g, function (m, i) {
			return args[i];
		});
	}


	// private
	Date.formatCodeToRegex = function (character, currentGroup) {
		// Note: currentGroup - position in regex result array (see notes for Date.parseCodes below)
		var p = Date.parseCodes[character];

		if (p) {
			p = typeof p == 'function' ? p() : p;
			Date.parseCodes[character] = p; // reassign function result to prevent repeated execution
		}

		return p ? Ext.applyIf({
			c: p.c ? xf(p.c, currentGroup || "{0}") : p.c
		}, p) : {
			g: 0,
			c: null,
			s: Ext.escapeRe(character) // treat unrecognised characters as literals
		}
	};

	// private shorthand for Date.formatCodeToRegex since we'll be using it fairly often
	var $f = Date.formatCodeToRegex;

	Ext.apply(Date, {
		/**
		* <p>An object hash in which each property is a date parsing function. The property name is the
		* format string which that function parses.</p>
		* <p>This object is automatically populated with date parsing functions as
		* date formats are requested for Ext standard formatting strings.</p>
		* <p>Custom parsing functions may be inserted into this object, keyed by a name which from then on
		* may be used as a format string to {@link #parseDate}.<p>
		* <p>Example:</p><pre><code>
		Date.parseFunctions['x-date-format'] = myDateParser;
		</code></pre>
		* <p>A parsing function should return a Date object, and is passed the following parameters:<div class="mdetail-params"><ul>
		* <li><code>date</code> : String<div class="sub-desc">The date string to parse.</div></li>
		* <li><code>strict</code> : Boolean<div class="sub-desc">True to validate date strings while parsing
		* (i.e. prevent javascript Date "rollover") (The default must be false).
		* Invalid date strings should return null when parsed.</div></li>
		* </ul></div></p>
		* <p>To enable Dates to also be <i>formatted</i> according to that format, a corresponding
		* formatting function must be placed into the {@link #formatFunctions} property.
		* @property parseFunctions
		* @static
		* @type Object
		*/
		parseFunctions: {
			"M$": function (input, strict) {
				// note: the timezone offset is ignored since the M$ Ajax server sends
				// a UTC milliseconds-since-Unix-epoch value (negative values are allowed)
				var re = new RegExp('\\/Date\\(([-+])?(\\d+)(?:[+-]\\d{4})?\\)\\/');
				var r = (input || '').match(re);
				return r ? new Date(((r[1] || '') + r[2]) * 1) : null;
			}
		},
		parseRegexes: [],

		/**
		* <p>An object hash in which each property is a date formatting function. The property name is the
		* format string which corresponds to the produced formatted date string.</p>
		* <p>This object is automatically populated with date formatting functions as
		* date formats are requested for Ext standard formatting strings.</p>
		* <p>Custom formatting functions may be inserted into this object, keyed by a name which from then on
		* may be used as a format string to {@link #format}. Example:</p><pre><code>
		Date.formatFunctions['x-date-format'] = myDateFormatter;
		</code></pre>
		* <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>
		* <li><code>date</code> : Date<div class="sub-desc">The Date to format.</div></li>
		* </ul></div></p>
		* <p>To enable date strings to also be <i>parsed</i> according to that format, a corresponding
		* parsing function must be placed into the {@link #parseFunctions} property.
		* @property formatFunctions
		* @static
		* @type Object
		*/
		formatFunctions: {
			"M$": function () {
				// UTC milliseconds since Unix epoch (M$-AJAX serialized date format (MRSF))
				return '\\/Date(' + this.getTime() + ')\\/';
			}
		},

		y2kYear: 50,

		/**
		* Date interval constant
		* @static
		* @type String
		*/
		MILLI: "ms",

		/**
		* Date interval constant
		* @static
		* @type String
		*/
		SECOND: "s",

		/**
		* Date interval constant
		* @static
		* @type String
		*/
		MINUTE: "mi",

		/** Date interval constant
		* @static
		* @type String
		*/
		HOUR: "h",

		/**
		* Date interval constant
		* @static
		* @type String
		*/
		DAY: "d",

		/**
		* Date interval constant
		* @static
		* @type String
		*/
		MONTH: "mo",

		/**
		* Date interval constant
		* @static
		* @type String
		*/
		YEAR: "y",

		/**
		* <p>An object hash containing default date values used during date parsing.</p>
		* <p>The following properties are available:<div class="mdetail-params"><ul>
		* <li><code>y</code> : Number<div class="sub-desc">The default year value. (defaults to undefined)</div></li>
		* <li><code>m</code> : Number<div class="sub-desc">The default 1-based month value. (defaults to undefined)</div></li>
		* <li><code>d</code> : Number<div class="sub-desc">The default day value. (defaults to undefined)</div></li>
		* <li><code>h</code> : Number<div class="sub-desc">The default hour value. (defaults to undefined)</div></li>
		* <li><code>i</code> : Number<div class="sub-desc">The default minute value. (defaults to undefined)</div></li>
		* <li><code>s</code> : Number<div class="sub-desc">The default second value. (defaults to undefined)</div></li>
		* <li><code>ms</code> : Number<div class="sub-desc">The default millisecond value. (defaults to undefined)</div></li>
		* </ul></div></p>
		* <p>Override these properties to customize the default date values used by the {@link #parseDate} method.</p>
		* <p><b>Note: In countries which experience Daylight Saving Time (i.e. DST), the <tt>h</tt>, <tt>i</tt>, <tt>s</tt>
		* and <tt>ms</tt> properties may coincide with the exact time in which DST takes effect.
		* It is the responsiblity of the developer to account for this.</b></p>
		* Example Usage:
		* <pre><code>
		// set default day value to the first day of the month
		Date.defaults.d = 1;

		// parse a February date string containing only year and month values.
		// setting the default day value to 1 prevents weird date rollover issues
		// when attempting to parse the following date string on, for example, March 31st 2009.
		Date.parseDate('2009-02', 'Y-m'); // returns a Date object representing February 1st 2009
		</code></pre>
		* @property defaults
		* @static
		* @type Object
		*/
		defaults: {},

		/**
		* An array of textual day names.
		* Override these values for international dates.
		* Example:
		* <pre><code>
		Date.dayNames = [
		'SundayInYourLang',
		'MondayInYourLang',
		...
		];
		</code></pre>
		* @type Array
		* @static
		*/
		dayNames: [
        "Sunday",
        "Monday",
        "Tuesday",
        "Wednesday",
        "Thursday",
        "Friday",
        "Saturday"
    ],

		/**
		* An array of textual month names.
		* Override these values for international dates.
		* Example:
		* <pre><code>
		Date.monthNames = [
		'JanInYourLang',
		'FebInYourLang',
		...
		];
		</code></pre>
		* @type Array
		* @static
		*/
		monthNames: [
        "January",
        "February",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December"
    ],

		/**
		* An object hash of zero-based javascript month numbers (with short month names as keys. note: keys are case-sensitive).
		* Override these values for international dates.
		* Example:
		* <pre><code>
		Date.monthNumbers = {
		'ShortJanNameInYourLang':0,
		'ShortFebNameInYourLang':1,
		...
		};
		</code></pre>
		* @type Object
		* @static
		*/
		monthNumbers: {
			Jan: 0,
			Feb: 1,
			Mar: 2,
			Apr: 3,
			May: 4,
			Jun: 5,
			Jul: 6,
			Aug: 7,
			Sep: 8,
			Oct: 9,
			Nov: 10,
			Dec: 11
		},

		/**
		* Get the short month name for the given month number.
		* Override this function for international dates.
		* @param {Number} month A zero-based javascript month number.
		* @return {String} The short month name.
		* @static
		*/
		getShortMonthName: function (month) {
			return Date.monthNames[month].substring(0, 3);
		},

		/**
		* Get the short day name for the given day number.
		* Override this function for international dates.
		* @param {Number} day A zero-based javascript day number.
		* @return {String} The short day name.
		* @static
		*/
		getShortDayName: function (day) {
			return Date.dayNames[day].substring(0, 3);
		},

		/**
		* Get the zero-based javascript month number for the given short/full month name.
		* Override this function for international dates.
		* @param {String} name The short/full month name.
		* @return {Number} The zero-based javascript month number.
		* @static
		*/
		getMonthNumber: function (name) {
			// handle camel casing for english month names (since the keys for the Date.monthNumbers hash are case sensitive)
			return Date.monthNumbers[name.substring(0, 1).toUpperCase() + name.substring(1, 3).toLowerCase()];
		},

		/**
		* The base format-code to formatting-function hashmap used by the {@link #format} method.
		* Formatting functions are strings (or functions which return strings) which
		* will return the appropriate value when evaluated in the context of the Date object
		* from which the {@link #format} method is called.
		* Add to / override these mappings for custom date formatting.
		* Note: Date.format() treats characters as literals if an appropriate mapping cannot be found.
		* Example:
		* <pre><code>
		Date.formatCodes.x = "String.leftPad(this.getDate(), 2, '0')";
		(new Date()).format("X"); // returns the current day of the month
		</code></pre>
		* @type Object
		* @static
		*/
		formatCodes: {
			d: "String.leftPad(this.getDate(), 2, '0')",
			D: "Date.getShortDayName(this.getDay())", // get localised short day name
			j: "this.getDate()",
			l: "Date.dayNames[this.getDay()]",
			N: "(this.getDay() ? this.getDay() : 7)",
			S: "this.getSuffix()",
			w: "this.getDay()",
			z: "this.getDayOfYear()",
			W: "String.leftPad(this.getWeekOfYear(), 2, '0')",
			F: "Date.monthNames[this.getMonth()]",
			m: "String.leftPad(this.getMonth() + 1, 2, '0')",
			M: "Date.getShortMonthName(this.getMonth())", // get localised short month name
			n: "(this.getMonth() + 1)",
			t: "this.getDaysInMonth()",
			L: "(this.isLeapYear() ? 1 : 0)",
			o: "(this.getFullYear() + (this.getWeekOfYear() == 1 && this.getMonth() > 0 ? +1 : (this.getWeekOfYear() >= 52 && this.getMonth() < 11 ? -1 : 0)))",
			Y: "this.getFullYear()",
			y: "('' + this.getFullYear()).substring(2, 4)",
			a: "(this.getHours() < 12 ? 'am' : 'pm')",
			A: "(this.getHours() < 12 ? 'AM' : 'PM')",
			g: "((this.getHours() % 12) ? this.getHours() % 12 : 12)",
			G: "this.getHours()",
			h: "String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0')",
			H: "String.leftPad(this.getHours(), 2, '0')",
			i: "String.leftPad(this.getMinutes(), 2, '0')",
			s: "String.leftPad(this.getSeconds(), 2, '0')",
			u: "String.leftPad(this.getMilliseconds(), 3, '0')",
			O: "this.getGMTOffset()",
			P: "this.getGMTOffset(true)",
			T: "this.getTimezone()",
			Z: "(this.getTimezoneOffset() * -60)",

			c: function () { // ISO-8601 -- GMT format
				for (var c = "Y-m-dTH:i:sP", code = [], i = 0, l = c.length; i < l; ++i) {
					var e = c.charAt(i);
					code.push(e == "T" ? "'T'" : Date.getFormatCode(e)); // treat T as a character literal
				}
				return code.join(" + ");
			},
			/*
			c: function() { // ISO-8601 -- UTC format
			return [
			"this.getUTCFullYear()", "'-'",
			"String.leftPad(this.getUTCMonth() + 1, 2, '0')", "'-'",
			"String.leftPad(this.getUTCDate(), 2, '0')",
			"'T'",
			"String.leftPad(this.getUTCHours(), 2, '0')", "':'",
			"String.leftPad(this.getUTCMinutes(), 2, '0')", "':'",
			"String.leftPad(this.getUTCSeconds(), 2, '0')",
			"'Z'"
			].join(" + ");
			},
			*/

			U: "Math.round(this.getTime() / 1000)"
		},

		/**
		* Checks if the passed Date parameters will cause a javascript Date "rollover".
		* @param {Number} year 4-digit year
		* @param {Number} month 1-based month-of-year
		* @param {Number} day Day of month
		* @param {Number} hour (optional) Hour
		* @param {Number} minute (optional) Minute
		* @param {Number} second (optional) Second
		* @param {Number} millisecond (optional) Millisecond
		* @return {Boolean} true if the passed parameters do not cause a Date "rollover", false otherwise.
		* @static
		*/
		isValid: function (y, m, d, h, i, s, ms) {
			// setup defaults
			h = h || 0;
			i = i || 0;
			s = s || 0;
			ms = ms || 0;

			var dt = new Date(y, m - 1, d, h, i, s, ms);

			return y == dt.getFullYear() &&
            m == dt.getMonth() + 1 &&
            d == dt.getDate() &&
            h == dt.getHours() &&
            i == dt.getMinutes() &&
            s == dt.getSeconds() &&
            ms == dt.getMilliseconds();
		},

		/**
		* Parses the passed string using the specified date format.
		* Note that this function expects normal calendar dates, meaning that months are 1-based (i.e. 1 = January).
		* The {@link #defaults} hash will be used for any date value (i.e. year, month, day, hour, minute, second or millisecond)
		* which cannot be found in the passed string. If a corresponding default date value has not been specified in the {@link #defaults} hash,
		* the current date's year, month, day or DST-adjusted zero-hour time value will be used instead.
		* Keep in mind that the input date string must precisely match the specified format string
		* in order for the parse operation to be successful (failed parse operations return a null value).
		* <p>Example:</p><pre><code>
		//dt = Fri May 25 2007 (current date)
		var dt = new Date();

		//dt = Thu May 25 2006 (today&#39;s month/day in 2006)
		dt = Date.parseDate("2006", "Y");

		//dt = Sun Jan 15 2006 (all date parts specified)
		dt = Date.parseDate("2006-01-15", "Y-m-d");

		//dt = Sun Jan 15 2006 15:20:01
		dt = Date.parseDate("2006-01-15 3:20:01 PM", "Y-m-d g:i:s A");

		// attempt to parse Sun Feb 29 2006 03:20:01 in strict mode
		dt = Date.parseDate("2006-02-29 03:20:01", "Y-m-d H:i:s", true); // returns null
		</code></pre>
		* @param {String} input The raw date string.
		* @param {String} format The expected date string format.
		* @param {Boolean} strict (optional) True to validate date strings while parsing (i.e. prevents javascript Date "rollover")
		(defaults to false). Invalid date strings will return null when parsed.
		* @return {Date} The parsed Date.
		* @static
		*/
		parseDate: function (input, format, strict) {
			var p = Date.parseFunctions;
			if (p[format] == null) {
				Date.createParser(format);
			}
			return p[format](input, Ext.isDefined(strict) ? strict : Date.useStrict);
		},

		// private
		getFormatCode: function (character) {
			var f = Date.formatCodes[character];

			if (f) {
				f = typeof f == 'function' ? f() : f;
				Date.formatCodes[character] = f; // reassign function result to prevent repeated execution
			}

			// note: unknown characters are treated as literals
			return f || ("'" + String.escape(character) + "'");
		},

		// private
		createFormat: function (format) {
			var code = [],
            special = false,
            ch = '';

			for (var i = 0; i < format.length; ++i) {
				ch = format.charAt(i);
				if (!special && ch == "\\") {
					special = true;
				} else if (special) {
					special = false;
					code.push("'" + String.escape(ch) + "'");
				} else {
					code.push(Date.getFormatCode(ch))
				}
			}
			Date.formatFunctions[format] = new Function("return " + code.join('+'));
		},

		// private
		createParser: function () {
			var code = [
            "var dt, y, m, d, h, i, s, ms, o, z, zz, u, v,",
                "def = Date.defaults,",
                "results = String(input).match(Date.parseRegexes[{0}]);", // either null, or an array of matched strings

            "if(results){",
                "{1}",

                "if(u != null){", // i.e. unix time is defined
                    "v = new Date(u * 1000);", // give top priority to UNIX time
                "}else{",
			// create Date object representing midnight of the current day;
			// this will provide us with our date defaults
			// (note: clearTime() handles Daylight Saving Time automatically)
                    "dt = (new Date()).clearTime();",

			// date calculations (note: these calculations create a dependency on Ext.num())
                    "y = Ext.num(y, Ext.num(def.y, dt.getFullYear()));",
                    "m = Ext.num(m, Ext.num(def.m - 1, dt.getMonth()));",
                    "d = Ext.num(d, Ext.num(def.d, dt.getDate()));",

			// time calculations (note: these calculations create a dependency on Ext.num())
                    "h  = Ext.num(h, Ext.num(def.h, dt.getHours()));",
                    "i  = Ext.num(i, Ext.num(def.i, dt.getMinutes()));",
                    "s  = Ext.num(s, Ext.num(def.s, dt.getSeconds()));",
                    "ms = Ext.num(ms, Ext.num(def.ms, dt.getMilliseconds()));",

                    "if(z >= 0 && y >= 0){",
			// both the year and zero-based day of year are defined and >= 0.
			// these 2 values alone provide sufficient info to create a full date object

			// create Date object representing January 1st for the given year
                        "v = new Date(y, 0, 1, h, i, s, ms);",

			// then add day of year, checking for Date "rollover" if necessary
                        "v = !strict? v : (strict === true && (z <= 364 || (v.isLeapYear() && z <= 365))? v.add(Date.DAY, z) : null);",
                    "}else if(strict === true && !Date.isValid(y, m + 1, d, h, i, s, ms)){", // check for Date "rollover"
                        "v = null;", // invalid date, so return null
                    "}else{",
			// plain old Date object
                        "v = new Date(y, m, d, h, i, s, ms);",
                    "}",
                "}",
            "}",

            "if(v){",
			// favour UTC offset over GMT offset
                "if(zz != null){",
			// reset to UTC, then add offset
                    "v = v.add(Date.SECOND, -v.getTimezoneOffset() * 60 - zz);",
                "}else if(o){",
			// reset to GMT, then add offset
                    "v = v.add(Date.MINUTE, -v.getTimezoneOffset() + (sn == '+'? -1 : 1) * (hr * 60 + mn));",
                "}",
            "}",

            "return v;"
        ].join('\n');

			return function (format) {
				var regexNum = Date.parseRegexes.length,
                currentGroup = 1,
                calc = [],
                regex = [],
                special = false,
                ch = "";

				for (var i = 0; i < format.length; ++i) {
					ch = format.charAt(i);
					if (!special && ch == "\\") {
						special = true;
					} else if (special) {
						special = false;
						regex.push(String.escape(ch));
					} else {
						var obj = $f(ch, currentGroup);
						currentGroup += obj.g;
						regex.push(obj.s);
						if (obj.g && obj.c) {
							calc.push(obj.c);
						}
					}
				}

				Date.parseRegexes[regexNum] = new RegExp("^" + regex.join('') + "$");
				Date.parseFunctions[format] = new Function("input", "strict", xf(code, regexNum, calc.join('')));
			}
		} (),

		// private
		parseCodes: {
			/*
			* Notes:
			* g = {Number} calculation group (0 or 1. only group 1 contributes to date calculations.)
			* c = {String} calculation method (required for group 1. null for group 0. {0} = currentGroup - position in regex result array)
			* s = {String} regex pattern. all matches are stored in results[], and are accessible by the calculation mapped to 'c'
			*/
			d: {
				g: 1,
				c: "d = parseInt(results[{0}], 10);\n",
				s: "(\\d{2})" // day of month with leading zeroes (01 - 31)
			},
			j: {
				g: 1,
				c: "d = parseInt(results[{0}], 10);\n",
				s: "(\\d{1,2})" // day of month without leading zeroes (1 - 31)
			},
			D: function () {
				for (var a = [], i = 0; i < 7; a.push(Date.getShortDayName(i)), ++i); // get localised short day names
				return {
					g: 0,
					c: null,
					s: "(?:" + a.join("|") + ")"
				}
			},
			l: function () {
				return {
					g: 0,
					c: null,
					s: "(?:" + Date.dayNames.join("|") + ")"
				}
			},
			N: {
				g: 0,
				c: null,
				s: "[1-7]" // ISO-8601 day number (1 (monday) - 7 (sunday))
			},
			S: {
				g: 0,
				c: null,
				s: "(?:st|nd|rd|th)"
			},
			w: {
				g: 0,
				c: null,
				s: "[0-6]" // javascript day number (0 (sunday) - 6 (saturday))
			},
			z: {
				g: 1,
				c: "z = parseInt(results[{0}], 10);\n",
				s: "(\\d{1,3})" // day of the year (0 - 364 (365 in leap years))
			},
			W: {
				g: 0,
				c: null,
				s: "(?:\\d{2})" // ISO-8601 week number (with leading zero)
			},
			F: function () {
				return {
					g: 1,
					c: "m = parseInt(Date.getMonthNumber(results[{0}]), 10);\n", // get localised month number
					s: "(" + Date.monthNames.join("|") + ")"
				}
			},
			M: function () {
				for (var a = [], i = 0; i < 12; a.push(Date.getShortMonthName(i)), ++i); // get localised short month names
				return Ext.applyIf({
					s: "(" + a.join("|") + ")"
				}, $f("F"));
			},
			m: {
				g: 1,
				c: "m = parseInt(results[{0}], 10) - 1;\n",
				s: "(\\d{2})" // month number with leading zeros (01 - 12)
			},
			n: {
				g: 1,
				c: "m = parseInt(results[{0}], 10) - 1;\n",
				s: "(\\d{1,2})" // month number without leading zeros (1 - 12)
			},
			t: {
				g: 0,
				c: null,
				s: "(?:\\d{2})" // no. of days in the month (28 - 31)
			},
			L: {
				g: 0,
				c: null,
				s: "(?:1|0)"
			},
			o: function () {
				return $f("Y");
			},
			Y: {
				g: 1,
				c: "y = parseInt(results[{0}], 10);\n",
				s: "(\\d{4})" // 4-digit year
			},
			y: {
				g: 1,
				c: "var ty = parseInt(results[{0}], 10);\n"
                + "y = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n", // 2-digit year
				s: "(\\d{1,2})"
			},
			a: {
				g: 1,
				c: "if (results[{0}] == 'am') {\n"
                + "if (!h || h == 12) { h = 0; }\n"
                + "} else { if (!h || h < 12) { h = (h || 0) + 12; }}",
				s: "(am|pm)"
			},
			A: {
				g: 1,
				c: "if (results[{0}] == 'AM') {\n"
                + "if (!h || h == 12) { h = 0; }\n"
                + "} else { if (!h || h < 12) { h = (h || 0) + 12; }}",
				s: "(AM|PM)"
			},
			g: function () {
				return $f("G");
			},
			G: {
				g: 1,
				c: "h = parseInt(results[{0}], 10);\n",
				s: "(\\d{1,2})" // 24-hr format of an hour without leading zeroes (0 - 23)
			},
			h: function () {
				return $f("H");
			},
			H: {
				g: 1,
				c: "h = parseInt(results[{0}], 10);\n",
				s: "(\\d{2})" //  24-hr format of an hour with leading zeroes (00 - 23)
			},
			i: {
				g: 1,
				c: "i = parseInt(results[{0}], 10);\n",
				s: "(\\d{2})" // minutes with leading zeros (00 - 59)
			},
			s: {
				g: 1,
				c: "s = parseInt(results[{0}], 10);\n",
				s: "(\\d{2})" // seconds with leading zeros (00 - 59)
			},
			u: {
				g: 1,
				c: "ms = results[{0}]; ms = parseInt(ms, 10)/Math.pow(10, ms.length - 3);\n",
				s: "(\\d+)" // decimal fraction of a second (minimum = 1 digit, maximum = unlimited)
			},
			O: {
				g: 1,
				c: [
                "o = results[{0}];",
                "var sn = o.substring(0,1),", // get + / - sign
                    "hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60),", // get hours (performs minutes-to-hour conversion also, just in case)
                    "mn = o.substring(3,5) % 60;", // get minutes
                "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))? (sn + String.leftPad(hr, 2, '0') + String.leftPad(mn, 2, '0')) : null;\n" // -12hrs <= GMT offset <= 14hrs
            ].join("\n"),
				s: "([+\-]\\d{4})" // GMT offset in hrs and mins
			},
			P: {
				g: 1,
				c: [
                "o = results[{0}];",
                "var sn = o.substring(0,1),", // get + / - sign
                    "hr = o.substring(1,3)*1 + Math.floor(o.substring(4,6) / 60),", // get hours (performs minutes-to-hour conversion also, just in case)
                    "mn = o.substring(4,6) % 60;", // get minutes
                "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))? (sn + String.leftPad(hr, 2, '0') + String.leftPad(mn, 2, '0')) : null;\n" // -12hrs <= GMT offset <= 14hrs
            ].join("\n"),
				s: "([+\-]\\d{2}:\\d{2})" // GMT offset in hrs and mins (with colon separator)
			},
			T: {
				g: 0,
				c: null,
				s: "[A-Z]{1,4}" // timezone abbrev. may be between 1 - 4 chars
			},
			Z: {
				g: 1,
				c: "zz = results[{0}] * 1;\n" // -43200 <= UTC offset <= 50400
                  + "zz = (-43200 <= zz && zz <= 50400)? zz : null;\n",
				s: "([+\-]?\\d{1,5})" // leading '+' sign is optional for UTC offset
			},
			c: function () {
				var calc = [],
                arr = [
                    $f("Y", 1), // year
                    $f("m", 2), // month
                    $f("d", 3), // day
                    $f("h", 4), // hour
                    $f("i", 5), // minute
                    $f("s", 6), // second
                    {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)
                    {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
                        "if(results[8]) {", // timezone specified
                            "if(results[8] == 'Z'){",
                                "zz = 0;", // UTC
                            "}else if (results[8].indexOf(':') > -1){",
                                $f("P", 8).c, // timezone offset with colon separator
                            "}else{",
                                $f("O", 8).c, // timezone offset without colon separator
                            "}",
                        "}"
                    ].join('\n')
                   }
                ];

				for (var i = 0, l = arr.length; i < l; ++i) {
					calc.push(arr[i].c);
				}

				return {
					g: 1,
					c: calc.join(""),
					s: [
                    arr[0].s, // year (required)
                    "(?:", "-", arr[1].s, // month (optional)
                        "(?:", "-", arr[2].s, // day (optional)
                            "(?:",
                                "(?:T| )?", // time delimiter -- either a "T" or a single blank space
                                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
                                "(?::", arr[5].s, ")?", // seconds (optional)
                                "(?:(?:\\.|,)(\\d+))?", // decimal fraction of a second (e.g. ",12345" or ".98765") (optional)
                                "(Z|(?:[-+]\\d{2}(?::)?\\d{2}))?", // "Z" (UTC) or "-0530" (UTC offset without colon delimiter) or "+08:00" (UTC offset with colon delimiter) (optional)
                            ")?",
                        ")?",
                    ")?"
                ].join("")
				}
			},
			U: {
				g: 1,
				c: "u = parseInt(results[{0}], 10);\n",
				s: "(-?\\d+)" // leading minus sign indicates seconds before UNIX epoch
			}
		}
	});

} ());

Ext.apply(Date.prototype, {
	// private
	dateFormat: function (format) {
		if (Date.formatFunctions[format] == null) {
			Date.createFormat(format);
		}
		return Date.formatFunctions[format].call(this);
	},

	/**
	* Get the timezone abbreviation of the current date (equivalent to the format specifier 'T').
	*
	* Note: The date string returned by the javascript Date object's toString() method varies
	* between browsers (e.g. FF vs IE) and system region settings (e.g. IE in Asia vs IE in America).
	* For a given date string e.g. "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)",
	* getTimezone() first tries to get the timezone abbreviation from between a pair of parentheses
	* (which may or may not be present), failing which it proceeds to get the timezone abbreviation
	* from the GMT offset portion of the date string.
	* @return {String} The abbreviated timezone name (e.g. 'CST', 'PDT', 'EDT', 'MPST' ...).
	*/
	getTimezone: function () {
		// the following list shows the differences between date strings from different browsers on a WinXP SP2 machine from an Asian locale:
		//
		// Opera  : "Thu, 25 Oct 2007 22:53:45 GMT+0800" -- shortest (weirdest) date string of the lot
		// 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)
		// FF     : "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)" -- value in parentheses always gives the correct timezone
		// IE     : "Thu Oct 25 22:54:35 UTC+0800 2007" -- (Asian system setting) look for 3-4 letter timezone abbrev
		// IE     : "Thu Oct 25 17:06:37 PDT 2007" -- (American system setting) look for 3-4 letter timezone abbrev
		//
		// this crazy regex attempts to guess the correct timezone abbreviation despite these differences.
		// step 1: (?:\((.*)\) -- find timezone in parentheses
		// 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
		// step 3: remove all non uppercase characters found in step 1 and 2
		return this.toString().replace(/^.* (?:\((.*)\)|([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?)$/, "$1$2").replace(/[^A-Z]/g, "");
	},

	/**
	* Get the offset from GMT of the current date (equivalent to the format specifier 'O').
	* @param {Boolean} colon (optional) true to separate the hours and minutes with a colon (defaults to false).
	* @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600').
	*/
	getGMTOffset: function (colon) {
		return (this.getTimezoneOffset() > 0 ? "-" : "+")
            + String.leftPad(Math.floor(Math.abs(this.getTimezoneOffset()) / 60), 2, "0")
            + (colon ? ":" : "")
            + String.leftPad(Math.abs(this.getTimezoneOffset() % 60), 2, "0");
	},

	/**
	* Get the numeric day number of the year, adjusted for leap year.
	* @return {Number} 0 to 364 (365 in leap years).
	*/
	getDayOfYear: function () {
		var num = 0,
            d = this.clone(),
            m = this.getMonth(),
            i;

		for (i = 0, d.setDate(1), d.setMonth(0); i < m; d.setMonth(++i)) {
			num += d.getDaysInMonth();
		}
		return num + this.getDate() - 1;
	},

	/**
	* Get the numeric ISO-8601 week number of the year.
	* (equivalent to the format specifier 'W', but without a leading zero).
	* @return {Number} 1 to 53
	*/
	getWeekOfYear: function () {
		// adapted from http://www.merlyn.demon.co.uk/weekcalc.htm
		var ms1d = 864e5, // milliseconds in a day
            ms7d = 7 * ms1d; // milliseconds in a week

		return function () { // return a closure so constants get calculated only once
			var DC3 = Date.UTC(this.getFullYear(), this.getMonth(), this.getDate() + 3) / ms1d, // an Absolute Day Number
                AWN = Math.floor(DC3 / 7), // an Absolute Week Number
                Wyr = new Date(AWN * ms7d).getUTCFullYear();

			return AWN - Math.floor(Date.UTC(Wyr, 0, 7) / ms7d) + 1;
		}
	} (),

	/**
	* Checks if the current date falls within a leap year.
	* @return {Boolean} True if the current date falls within a leap year, false otherwise.
	*/
	isLeapYear: function () {
		var year = this.getFullYear();
		return !!((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
	},

	/**
	* Get the first day of the current month, adjusted for leap year.  The returned value
	* is the numeric day index within the week (0-6) which can be used in conjunction with
	* the {@link #monthNames} array to retrieve the textual day name.
	* Example:
	* <pre><code>
	var dt = new Date('1/10/2007');
	document.write(Date.dayNames[dt.getFirstDayOfMonth()]); //output: 'Monday'
	</code></pre>
	* @return {Number} The day number (0-6).
	*/
	getFirstDayOfMonth: function () {
		var day = (this.getDay() - (this.getDate() - 1)) % 7;
		return (day < 0) ? (day + 7) : day;
	},

	/**
	* Get the last day of the current month, adjusted for leap year.  The returned value
	* is the numeric day index within the week (0-6) which can be used in conjunction with
	* the {@link #monthNames} array to retrieve the textual day name.
	* Example:
	* <pre><code>
	var dt = new Date('1/10/2007');
	document.write(Date.dayNames[dt.getLastDayOfMonth()]); //output: 'Wednesday'
	</code></pre>
	* @return {Number} The day number (0-6).
	*/
	getLastDayOfMonth: function () {
		return this.getLastDateOfMonth().getDay();
	},


	/**
	* Get the date of the first day of the month in which this date resides.
	* @return {Date}
	*/
	getFirstDateOfMonth: function () {
		return new Date(this.getFullYear(), this.getMonth(), 1);
	},

	/**
	* Get the date of the last day of the month in which this date resides.
	* @return {Date}
	*/
	getLastDateOfMonth: function () {
		return new Date(this.getFullYear(), this.getMonth(), this.getDaysInMonth());
	},

	/**
	* Get the number of days in the current month, adjusted for leap year.
	* @return {Number} The number of days in the month.
	*/
	getDaysInMonth: function () {
		var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

		return function () { // return a closure for efficiency
			var m = this.getMonth();

			return m == 1 && this.isLeapYear() ? 29 : daysInMonth[m];
		}
	} (),

	/**
	* Get the English ordinal suffix of the current day (equivalent to the format specifier 'S').
	* @return {String} 'st, 'nd', 'rd' or 'th'.
	*/
	getSuffix: function () {
		switch (this.getDate()) {
			case 1:
			case 21:
			case 31:
				return "st";
			case 2:
			case 22:
				return "nd";
			case 3:
			case 23:
				return "rd";
			default:
				return "th";
		}
	},

	/**
	* Creates and returns a new Date instance with the exact same date value as the called instance.
	* Dates are copied and passed by reference, so if a copied date variable is modified later, the original
	* variable will also be changed.  When the intention is to create a new variable that will not
	* modify the original instance, you should create a clone.
	*
	* Example of correctly cloning a date:
	* <pre><code>
	//wrong way:
	var orig = new Date('10/1/2006');
	var copy = orig;
	copy.setDate(5);
	document.write(orig);  //returns 'Thu Oct 05 2006'!

	//correct way:
	var orig = new Date('10/1/2006');
	var copy = orig.clone();
	copy.setDate(5);
	document.write(orig);  //returns 'Thu Oct 01 2006'
	</code></pre>
	* @return {Date} The new Date instance.
	*/
	clone: function () {
		return new Date(this.getTime());
	},

	/**
	* Checks if the current date is affected by Daylight Saving Time (DST).
	* @return {Boolean} True if the current date is affected by DST.
	*/
	isDST: function () {
		// adapted from http://extjs.com/forum/showthread.php?p=247172#post247172
		// courtesy of @geoffrey.mcgill
		return new Date(this.getFullYear(), 0, 1).getTimezoneOffset() != this.getTimezoneOffset();
	},

	/**
	* Attempts to clear all time information from this Date by setting the time to midnight of the same day,
	* automatically adjusting for Daylight Saving Time (DST) where applicable.
	* (note: DST timezone information for the browser's host operating system is assumed to be up-to-date)
	* @param {Boolean} clone true to create a clone of this date, clear the time and return it (defaults to false).
	* @return {Date} this or the clone.
	*/
	clearTime: function (clone) {
		if (clone) {
			return this.clone().clearTime();
		}

		// get current date before clearing time
		var d = this.getDate();

		// clear time
		this.setHours(0);
		this.setMinutes(0);
		this.setSeconds(0);
		this.setMilliseconds(0);

		if (this.getDate() != d) { // account for DST (i.e. day of month changed when setting hour = 0)
			// note: DST adjustments are assumed to occur in multiples of 1 hour (this is almost always the case)
			// refer to http://www.timeanddate.com/time/aboutdst.html for the (rare) exceptions to this rule

			// increment hour until cloned date == current date
			for (var hr = 1, c = this.add(Date.HOUR, hr); c.getDate() != d; hr++, c = this.add(Date.HOUR, hr));

			this.setDate(d);
			this.setHours(c.getHours());
		}

		return this;
	},

	/**
	* Provides a convenient method for performing basic date arithmetic. This method
	* does not modify the Date instance being called - it creates and returns
	* a new Date instance containing the resulting date value.
	*
	* Examples:
	* <pre><code>
	// Basic usage:
	var dt = new Date('10/29/2006').add(Date.DAY, 5);
	document.write(dt); //returns 'Fri Nov 03 2006 00:00:00'

	// Negative values will be subtracted:
	var dt2 = new Date('10/1/2006').add(Date.DAY, -5);
	document.write(dt2); //returns 'Tue Sep 26 2006 00:00:00'

	// You can even chain several calls together in one line:
	var dt3 = new Date('10/1/2006').add(Date.DAY, 5).add(Date.HOUR, 8).add(Date.MINUTE, -30);
	document.write(dt3); //returns 'Fri Oct 06 2006 07:30:00'
	</code></pre>
	*
	* @param {String} interval A valid date interval enum value.
	* @param {Number} value The amount to add to the current date.
	* @return {Date} The new Date instance.
	*/
	add: function (interval, value) {
		var d = this.clone();
		if (!interval || value === 0) return d;

		switch (interval.toLowerCase()) {
			case Date.MILLI:
				d.setMilliseconds(this.getMilliseconds() + value);
				break;
			case Date.SECOND:
				d.setSeconds(this.getSeconds() + value);
				break;
			case Date.MINUTE:
				d.setMinutes(this.getMinutes() + value);
				break;
			case Date.HOUR:
				d.setHours(this.getHours() + value);
				break;
			case Date.DAY:
				d.setDate(this.getDate() + value);
				break;
			case Date.MONTH:
				var day = this.getDate();
				if (day > 28) {
					day = Math.min(day, this.getFirstDateOfMonth().add('mo', value).getLastDateOfMonth().getDate());
				}
				d.setDate(day);
				d.setMonth(this.getMonth() + value);
				break;
			case Date.YEAR:
				d.setFullYear(this.getFullYear() + value);
				break;
		}
		return d;
	},

	/**
	* Checks if this date falls on or between the given start and end dates.
	* @param {Date} start Start date
	* @param {Date} end End date
	* @return {Boolean} true if this date falls on or between the given start and end dates.
	*/
	between: function (start, end) {
		var t = this.getTime();
		return start.getTime() <= t && t <= end.getTime();
	}
});


/**
* Formats a date given the supplied format string.
* @param {String} format The format string.
* @return {String} The formatted date.
* @method format
*/
Date.prototype.format = Date.prototype.dateFormat;


// private
if (Ext.isSafari && (navigator.userAgent.match(/WebKit\/(\d+)/)[1] || NaN) < 420) {
	Ext.apply(Date.prototype, {
		_xMonth: Date.prototype.setMonth,
		_xDate: Date.prototype.setDate,

		// Bug in Safari 1.3, 2.0 (WebKit build < 420)
		// Date.setMonth does not work consistently if iMonth is not 0-11
		setMonth: function (num) {
			if (num <= -1) {
				var n = Math.ceil(-num),
                    back_year = Math.ceil(n / 12),
                    month = (n % 12) ? 12 - n % 12 : 0;

				this.setFullYear(this.getFullYear() - back_year);

				return this._xMonth(month);
			} else {
				return this._xMonth(num);
			}
		},

		// Bug in setDate() method (resolved in WebKit build 419.3, so to be safe we target Webkit builds < 420)
		// The parameter for Date.setDate() is converted to a signed byte integer in Safari
		// http://brianary.blogspot.com/2006/03/safari-date-bug.html
		setDate: function (d) {
			// use setTime() to workaround setDate() bug
			// subtract current day of month in milliseconds, then add desired day of month in milliseconds
			return this.setTime(this.getTime() - (this.getDate() - d) * 864e5);
		}
	});
}



/* Some basic Date tests... (requires Firebug)

Date.parseDate('', 'c'); // call Date.parseDate() once to force computation of regex string so we can console.log() it
console.log('Insane Regex for "c" format: %o', Date.parseCodes.c.s); // view the insane regex for the "c" format specifier

// standard tests
console.group('Standard Date.parseDate() Tests');
console.log('Date.parseDate("2009-01-05T11:38:56", "c")               = %o', Date.parseDate("2009-01-05T11:38:56", "c")); // assumes browser's timezone setting
console.log('Date.parseDate("2009-02-04T12:37:55.001000", "c")        = %o', Date.parseDate("2009-02-04T12:37:55.001000", "c")); // assumes browser's timezone setting
console.log('Date.parseDate("2009-03-03T13:36:54,101000Z", "c")       = %o', Date.parseDate("2009-03-03T13:36:54,101000Z", "c")); // UTC
console.log('Date.parseDate("2009-04-02T14:35:53.901000-0530", "c")   = %o', Date.parseDate("2009-04-02T14:35:53.901000-0530", "c")); // GMT-0530
console.log('Date.parseDate("2009-05-01T15:34:52,9876000+08:00", "c") = %o', Date.parseDate("2009-05-01T15:34:52,987600+08:00", "c")); // GMT+08:00
console.groupEnd();

// ISO-8601 format as specified in http://www.w3.org/TR/NOTE-datetime
// -- accepts ALL 6 levels of date-time granularity
console.group('ISO-8601 Granularity Test (see http://www.w3.org/TR/NOTE-datetime)');
console.log('Date.parseDate("1997", "c")                              = %o', Date.parseDate("1997", "c")); // YYYY (e.g. 1997)
console.log('Date.parseDate("1997-07", "c")                           = %o', Date.parseDate("1997-07", "c")); // YYYY-MM (e.g. 1997-07)
console.log('Date.parseDate("1997-07-16", "c")                        = %o', Date.parseDate("1997-07-16", "c")); // YYYY-MM-DD (e.g. 1997-07-16)
console.log('Date.parseDate("1997-07-16T19:20+01:00", "c")            = %o', Date.parseDate("1997-07-16T19:20+01:00", "c")); // YYYY-MM-DDThh:mmTZD (e.g. 1997-07-16T19:20+01:00)
console.log('Date.parseDate("1997-07-16T19:20:30+01:00", "c")         = %o', Date.parseDate("1997-07-16T19:20:30+01:00", "c")); // YYYY-MM-DDThh:mm:ssTZD (e.g. 1997-07-16T19:20:30+01:00)
console.log('Date.parseDate("1997-07-16T19:20:30.45+01:00", "c")      = %o', Date.parseDate("1997-07-16T19:20:30.45+01:00", "c")); // YYYY-MM-DDThh:mm:ss.sTZD (e.g. 1997-07-16T19:20:30.45+01:00)
console.log('Date.parseDate("1997-07-16 19:20:30.45+01:00", "c")      = %o', Date.parseDate("1997-07-16 19:20:30.45+01:00", "c")); // YYYY-MM-DD hh:mm:ss.sTZD (e.g. 1997-07-16T19:20:30.45+01:00)
console.log('Date.parseDate("1997-13-16T19:20:30.45+01:00", "c", true)= %o', Date.parseDate("1997-13-16T19:20:30.45+01:00", "c", true)); // strict date parsing with invalid month value
console.groupEnd();

//*/
/**
* @class Ext.util.MixedCollection
* @extends Ext.util.Observable
* A Collection class that maintains both numeric indexes and keys and exposes events.
* @constructor
* @param {Boolean} allowFunctions Specify <tt>true</tt> if the {@link #addAll}
* function should add function references to the collection. Defaults to
* <tt>false</tt>.
* @param {Function} keyFn A function that can accept an item of the type(s) stored in this MixedCollection
* and return the key value for that item.  This is used when available to look up the key on items that
* were passed without an explicit key parameter to a MixedCollection method.  Passing this parameter is
* equivalent to providing an implementation for the {@link #getKey} method.
*/
Ext.util.MixedCollection = function (allowFunctions, keyFn) {
	this.items = [];
	this.map = {};
	this.keys = [];
	this.length = 0;
	this.addEvents(
	/**
	* @event clear
	* Fires when the collection is cleared.
	*/
        'clear',
	/**
	* @event add
	* Fires when an item is added to the collection.
	* @param {Number} index The index at which the item was added.
	* @param {Object} o The item added.
	* @param {String} key The key associated with the added item.
	*/
        'add',
	/**
	* @event replace
	* Fires when an item is replaced in the collection.
	* @param {String} key he key associated with the new added.
	* @param {Object} old The item being replaced.
	* @param {Object} new The new item.
	*/
        'replace',
	/**
	* @event remove
	* Fires when an item is removed from the collection.
	* @param {Object} o The item being removed.
	* @param {String} key (optional) The key associated with the removed item.
	*/
        'remove',
        'sort'
    );
	this.allowFunctions = allowFunctions === true;
	if (keyFn) {
		this.getKey = keyFn;
	}
	Ext.util.MixedCollection.superclass.constructor.call(this);
};

Ext.extend(Ext.util.MixedCollection, Ext.util.Observable, {

	/**
	* @cfg {Boolean} allowFunctions Specify <tt>true</tt> if the {@link #addAll}
	* function should add function references to the collection. Defaults to
	* <tt>false</tt>.
	*/
	allowFunctions: false,

	/**
	* Adds an item to the collection. Fires the {@link #add} event when complete.
	* @param {String} key <p>The key to associate with the item, or the new item.</p>
	* <p>If a {@link #getKey} implementation was specified for this MixedCollection,
	* or if the key of the stored items is in a property called <tt><b>id</b></tt>,
	* the MixedCollection will be able to <i>derive</i> the key for the new item.
	* In this case just pass the new item in this parameter.</p>
	* @param {Object} o The item to add.
	* @return {Object} The item added.
	*/
	add: function (key, o) {
		if (arguments.length == 1) {
			o = arguments[0];
			key = this.getKey(o);
		}
		if (typeof key != 'undefined' && key !== null) {
			var old = this.map[key];
			if (typeof old != 'undefined') {
				return this.replace(key, o);
			}
			this.map[key] = o;
		}
		this.length++;
		this.items.push(o);
		this.keys.push(key);
		this.fireEvent('add', this.length - 1, o, key);
		return o;
	},

	/**
	* MixedCollection has a generic way to fetch keys if you implement getKey.  The default implementation
	* simply returns <b><code>item.id</code></b> but you can provide your own implementation
	* to return a different value as in the following examples:<pre><code>
	// normal way
	var mc = new Ext.util.MixedCollection();
	mc.add(someEl.dom.id, someEl);
	mc.add(otherEl.dom.id, otherEl);
	//and so on

	// using getKey
	var mc = new Ext.util.MixedCollection();
	mc.getKey = function(el){
	return el.dom.id;
	};
	mc.add(someEl);
	mc.add(otherEl);

	// or via the constructor
	var mc = new Ext.util.MixedCollection(false, function(el){
	return el.dom.id;
	});
	mc.add(someEl);
	mc.add(otherEl);
	* </code></pre>
	* @param {Object} item The item for which to find the key.
	* @return {Object} The key for the passed item.
	*/
	getKey: function (o) {
		return o.id;
	},

	/**
	* Replaces an item in the collection. Fires the {@link #replace} event when complete.
	* @param {String} key <p>The key associated with the item to replace, or the replacement item.</p>
	* <p>If you supplied a {@link #getKey} implementation for this MixedCollection, or if the key
	* of your stored items is in a property called <tt><b>id</b></tt>, then the MixedCollection
	* will be able to <i>derive</i> the key of the replacement item. If you want to replace an item
	* with one having the same key value, then just pass the replacement item in this parameter.</p>
	* @param o {Object} o (optional) If the first parameter passed was a key, the item to associate
	* with that key.
	* @return {Object}  The new item.
	*/
	replace: function (key, o) {
		if (arguments.length == 1) {
			o = arguments[0];
			key = this.getKey(o);
		}
		var old = this.map[key];
		if (typeof key == 'undefined' || key === null || typeof old == 'undefined') {
			return this.add(key, o);
		}
		var index = this.indexOfKey(key);
		this.items[index] = o;
		this.map[key] = o;
		this.fireEvent('replace', key, old, o);
		return o;
	},

	/**
	* Adds all elements of an Array or an Object to the collection.
	* @param {Object/Array} objs An Object containing properties which will be added
	* to the collection, or an Array of values, each of which are added to the collection.
	* Functions references will be added to the collection if <code>{@link #allowFunctions}</code>
	* has been set to <tt>true</tt>.
	*/
	addAll: function (objs) {
		if (arguments.length > 1 || Ext.isArray(objs)) {
			var args = arguments.length > 1 ? arguments : objs;
			for (var i = 0, len = args.length; i < len; i++) {
				this.add(args[i]);
			}
		} else {
			for (var key in objs) {
				if (this.allowFunctions || typeof objs[key] != 'function') {
					this.add(key, objs[key]);
				}
			}
		}
	},

	/**
	* Executes the specified function once for every item in the collection, passing the following arguments:
	* <div class="mdetail-params"><ul>
	* <li><b>item</b> : Mixed<p class="sub-desc">The collection item</p></li>
	* <li><b>index</b> : Number<p class="sub-desc">The item's index</p></li>
	* <li><b>length</b> : Number<p class="sub-desc">The total number of items in the collection</p></li>
	* </ul></div>
	* The function should return a boolean value. Returning false from the function will stop the iteration.
	* @param {Function} fn The function to execute for each item.
	* @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to the current item in the iteration.
	*/
	each: function (fn, scope) {
		var items = [].concat(this.items); // each safe for removal
		for (var i = 0, len = items.length; i < len; i++) {
			if (fn.call(scope || items[i], items[i], i, len) === false) {
				break;
			}
		}
	},

	/**
	* Executes the specified function once for every key in the collection, passing each
	* key, and its associated item as the first two parameters.
	* @param {Function} fn The function to execute for each item.
	* @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to the browser window.
	*/
	eachKey: function (fn, scope) {
		for (var i = 0, len = this.keys.length; i < len; i++) {
			fn.call(scope || window, this.keys[i], this.items[i], i, len);
		}
	},

	/**
	* Returns the first item in the collection which elicits a true return value from the
	* passed selection function.
	* @param {Function} fn The selection function to execute for each item.
	* @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to the browser window.
	* @return {Object} The first item in the collection which returned true from the selection function.
	*/
	find: function (fn, scope) {
		for (var i = 0, len = this.items.length; i < len; i++) {
			if (fn.call(scope || window, this.items[i], this.keys[i])) {
				return this.items[i];
			}
		}
		return null;
	},

	/**
	* Inserts an item at the specified index in the collection. Fires the {@link #add} event when complete.
	* @param {Number} index The index to insert the item at.
	* @param {String} key The key to associate with the new item, or the item itself.
	* @param {Object} o (optional) If the second parameter was a key, the new item.
	* @return {Object} The item inserted.
	*/
	insert: function (index, key, o) {
		if (arguments.length == 2) {
			o = arguments[1];
			key = this.getKey(o);
		}
		if (this.containsKey(key)) {
			this.suspendEvents();
			this.removeKey(key);
			this.resumeEvents();
		}
		if (index >= this.length) {
			return this.add(key, o);
		}
		this.length++;
		this.items.splice(index, 0, o);
		if (typeof key != 'undefined' && key !== null) {
			this.map[key] = o;
		}
		this.keys.splice(index, 0, key);
		this.fireEvent('add', index, o, key);
		return o;
	},

	/**
	* Remove an item from the collection.
	* @param {Object} o The item to remove.
	* @return {Object} The item removed or false if no item was removed.
	*/
	remove: function (o) {
		return this.removeAt(this.indexOf(o));
	},

	/**
	* Remove an item from a specified index in the collection. Fires the {@link #remove} event when complete.
	* @param {Number} index The index within the collection of the item to remove.
	* @return {Object} The item removed or false if no item was removed.
	*/
	removeAt: function (index) {
		if (index < this.length && index >= 0) {
			this.length--;
			var o = this.items[index];
			this.items.splice(index, 1);
			var key = this.keys[index];
			if (typeof key != 'undefined') {
				delete this.map[key];
			}
			this.keys.splice(index, 1);
			this.fireEvent('remove', o, key);
			return o;
		}
		return false;
	},

	/**
	* Removed an item associated with the passed key fom the collection.
	* @param {String} key The key of the item to remove.
	* @return {Object} The item removed or false if no item was removed.
	*/
	removeKey: function (key) {
		return this.removeAt(this.indexOfKey(key));
	},

	/**
	* Returns the number of items in the collection.
	* @return {Number} the number of items in the collection.
	*/
	getCount: function () {
		return this.length;
	},

	/**
	* Returns index within the collection of the passed Object.
	* @param {Object} o The item to find the index of.
	* @return {Number} index of the item. Returns -1 if not found.
	*/
	indexOf: function (o) {
		return this.items.indexOf(o);
	},

	/**
	* Returns index within the collection of the passed key.
	* @param {String} key The key to find the index of.
	* @return {Number} index of the key.
	*/
	indexOfKey: function (key) {
		return this.keys.indexOf(key);
	},

	/**
	* Returns the item associated with the passed key OR index.
	* Key has priority over index.  This is the equivalent
	* of calling {@link #key} first, then if nothing matched calling {@link #itemAt}.
	* @param {String/Number} key The key or index of the item.
	* @return {Object} If the item is found, returns the item.  If the item was not found, returns <tt>undefined</tt>.
	* If an item was found, but is a Class, returns <tt>null</tt>.
	*/
	item: function (key) {
		var mk = this.map[key],
            item = mk !== undefined ? mk : (typeof key == 'number') ? this.items[key] : undefined;
		return typeof item != 'function' || this.allowFunctions ? item : null; // for prototype!
	},

	/**
	* Returns the item at the specified index.
	* @param {Number} index The index of the item.
	* @return {Object} The item at the specified index.
	*/
	itemAt: function (index) {
		return this.items[index];
	},

	/**
	* Returns the item associated with the passed key.
	* @param {String/Number} key The key of the item.
	* @return {Object} The item associated with the passed key.
	*/
	key: function (key) {
		return this.map[key];
	},

	/**
	* Returns true if the collection contains the passed Object as an item.
	* @param {Object} o  The Object to look for in the collection.
	* @return {Boolean} True if the collection contains the Object as an item.
	*/
	contains: function (o) {
		return this.indexOf(o) != -1;
	},

	/**
	* Returns true if the collection contains the passed Object as a key.
	* @param {String} key The key to look for in the collection.
	* @return {Boolean} True if the collection contains the Object as a key.
	*/
	containsKey: function (key) {
		return typeof this.map[key] != 'undefined';
	},

	/**
	* Removes all items from the collection.  Fires the {@link #clear} event when complete.
	*/
	clear: function () {
		this.length = 0;
		this.items = [];
		this.keys = [];
		this.map = {};
		this.fireEvent('clear');
	},

	/**
	* Returns the first item in the collection.
	* @return {Object} the first item in the collection..
	*/
	first: function () {
		return this.items[0];
	},

	/**
	* Returns the last item in the collection.
	* @return {Object} the last item in the collection..
	*/
	last: function () {
		return this.items[this.length - 1];
	},

	/**
	* @private
	* Performs the actual sorting based on a direction and a sorting function. Internally,
	* this creates a temporary array of all items in the MixedCollection, sorts it and then writes
	* the sorted array data back into this.items and this.keys
	* @param {String} property Property to sort by ('key', 'value', or 'index')
	* @param {String} dir (optional) Direction to sort 'ASC' or 'DESC'. Defaults to 'ASC'.
	* @param {Function} fn (optional) Comparison function that defines the sort order.
	* Defaults to sorting by numeric value.
	*/
	_sort: function (property, dir, fn) {
		var i, len,
            dsc = String(dir).toUpperCase() == 'DESC' ? -1 : 1,

		//this is a temporary array used to apply the sorting function
            c = [],
            keys = this.keys,
            items = this.items;

		//default to a simple sorter function if one is not provided
		fn = fn || function (a, b) {
			return a - b;
		};

		//copy all the items into a temporary array, which we will sort
		for (i = 0, len = items.length; i < len; i++) {
			c[c.length] = {
				key: keys[i],
				value: items[i],
				index: i
			};
		}

		//sort the temporary array
		c.sort(function (a, b) {
			var v = fn(a[property], b[property]) * dsc;
			if (v === 0) {
				v = (a.index < b.index ? -1 : 1);
			}
			return v;
		});

		//copy the temporary array back into the main this.items and this.keys objects
		for (i = 0, len = c.length; i < len; i++) {
			items[i] = c[i].value;
			keys[i] = c[i].key;
		}

		this.fireEvent('sort', this);
	},

	/**
	* Sorts this collection by <b>item</b> value with the passed comparison function.
	* @param {String} direction (optional) 'ASC' or 'DESC'. Defaults to 'ASC'.
	* @param {Function} fn (optional) Comparison function that defines the sort order.
	* Defaults to sorting by numeric value.
	*/
	sort: function (dir, fn) {
		this._sort('value', dir, fn);
	},

	/**
	* Reorders each of the items based on a mapping from old index to new index. Internally this
	* just translates into a sort. The 'sort' event is fired whenever reordering has occured.
	* @param {Object} mapping Mapping from old item index to new item index
	*/
	reorder: function (mapping) {
		this.suspendEvents();

		var items = this.items,
            index = 0,
            length = items.length,
            order = [],
            remaining = [];

		//object of {oldPosition: newPosition} reversed to {newPosition: oldPosition}
		for (oldIndex in mapping) {
			order[mapping[oldIndex]] = items[oldIndex];
		}

		for (index = 0; index < length; index++) {
			if (mapping[index] == undefined) {
				remaining.push(items[index]);
			}
		}

		for (index = 0; index < length; index++) {
			if (order[index] == undefined) {
				order[index] = remaining.shift();
			}
		}

		this.clear();
		this.addAll(order);

		this.resumeEvents();
		this.fireEvent('sort', this);
	},

	/**
	* Sorts this collection by <b>key</b>s.
	* @param {String} direction (optional) 'ASC' or 'DESC'. Defaults to 'ASC'.
	* @param {Function} fn (optional) Comparison function that defines the sort order.
	* Defaults to sorting by case insensitive string.
	*/
	keySort: function (dir, fn) {
		this._sort('key', dir, fn || function (a, b) {
			var v1 = String(a).toUpperCase(), v2 = String(b).toUpperCase();
			return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
		});
	},

	/**
	* Returns a range of items in this collection
	* @param {Number} startIndex (optional) The starting index. Defaults to 0.
	* @param {Number} endIndex (optional) The ending index. Defaults to the last item.
	* @return {Array} An array of items
	*/
	getRange: function (start, end) {
		var items = this.items;
		if (items.length < 1) {
			return [];
		}
		start = start || 0;
		end = Math.min(typeof end == 'undefined' ? this.length - 1 : end, this.length - 1);
		var i, r = [];
		if (start <= end) {
			for (i = start; i <= end; i++) {
				r[r.length] = items[i];
			}
		} else {
			for (i = start; i >= end; i--) {
				r[r.length] = items[i];
			}
		}
		return r;
	},

	/**
	* Filter the <i>objects</i> in this collection by a specific property.
	* Returns a new collection that has been filtered.
	* @param {String} property A property on your objects
	* @param {String/RegExp} value Either string that the property values
	* should start with or a RegExp to test against the property
	* @param {Boolean} anyMatch (optional) True to match any part of the string, not just the beginning
	* @param {Boolean} caseSensitive (optional) True for case sensitive comparison (defaults to False).
	* @return {MixedCollection} The new filtered collection
	*/
	filter: function (property, value, anyMatch, caseSensitive) {
		if (Ext.isEmpty(value, false)) {
			return this.clone();
		}
		value = this.createValueMatcher(value, anyMatch, caseSensitive);
		return this.filterBy(function (o) {
			return o && value.test(o[property]);
		});
	},

	/**
	* Filter by a function. Returns a <i>new</i> collection that has been filtered.
	* The passed function will be called with each object in the collection.
	* If the function returns true, the value is included otherwise it is filtered.
	* @param {Function} fn The function to be called, it will receive the args o (the object), k (the key)
	* @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this MixedCollection.
	* @return {MixedCollection} The new filtered collection
	*/
	filterBy: function (fn, scope) {
		var r = new Ext.util.MixedCollection();
		r.getKey = this.getKey;
		var k = this.keys, it = this.items;
		for (var i = 0, len = it.length; i < len; i++) {
			if (fn.call(scope || this, it[i], k[i])) {
				r.add(k[i], it[i]);
			}
		}
		return r;
	},

	/**
	* Finds the index of the first matching object in this collection by a specific property/value.
	* @param {String} property The name of a property on your objects.
	* @param {String/RegExp} value A string that the property values
	* should start with or a RegExp to test against the property.
	* @param {Number} start (optional) The index to start searching at (defaults to 0).
	* @param {Boolean} anyMatch (optional) True to match any part of the string, not just the beginning.
	* @param {Boolean} caseSensitive (optional) True for case sensitive comparison.
	* @return {Number} The matched index or -1
	*/
	findIndex: function (property, value, start, anyMatch, caseSensitive) {
		if (Ext.isEmpty(value, false)) {
			return -1;
		}
		value = this.createValueMatcher(value, anyMatch, caseSensitive);
		return this.findIndexBy(function (o) {
			return o && value.test(o[property]);
		}, null, start);
	},

	/**
	* Find the index of the first matching object in this collection by a function.
	* If the function returns <i>true</i> it is considered a match.
	* @param {Function} fn The function to be called, it will receive the args o (the object), k (the key).
	* @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this MixedCollection.
	* @param {Number} start (optional) The index to start searching at (defaults to 0).
	* @return {Number} The matched index or -1
	*/
	findIndexBy: function (fn, scope, start) {
		var k = this.keys, it = this.items;
		for (var i = (start || 0), len = it.length; i < len; i++) {
			if (fn.call(scope || this, it[i], k[i])) {
				return i;
			}
		}
		return -1;
	},

	/**
	* Returns a regular expression based on the given value and matching options. This is used internally for finding and filtering,
	* and by Ext.data.Store#filter
	* @private
	* @param {String} value The value to create the regex for. This is escaped using Ext.escapeRe
	* @param {Boolean} anyMatch True to allow any match - no regex start/end line anchors will be added. Defaults to false
	* @param {Boolean} caseSensitive True to make the regex case sensitive (adds 'i' switch to regex). Defaults to false.
	* @param {Boolean} exactMatch True to force exact match (^ and $ characters added to the regex). Defaults to false. Ignored if anyMatch is true.
	*/
	createValueMatcher: function (value, anyMatch, caseSensitive, exactMatch) {
		if (!value.exec) { // not a regex
			var er = Ext.escapeRe;
			value = String(value);

			if (anyMatch === true) {
				value = er(value);
			} else {
				value = '^' + er(value);
				if (exactMatch === true) {
					value += '$';
				}
			}
			value = new RegExp(value, caseSensitive ? '' : 'i');
		}
		return value;
	},

	/**
	* Creates a shallow copy of this collection
	* @return {MixedCollection}
	*/
	clone: function () {
		var r = new Ext.util.MixedCollection();
		var k = this.keys, it = this.items;
		for (var i = 0, len = it.length; i < len; i++) {
			r.add(k[i], it[i]);
		}
		r.getKey = this.getKey;
		return r;
	}
});
/**
* This method calls {@link #item item()}.
* Returns the item associated with the passed key OR index. Key has priority
* over index.  This is the equivalent of calling {@link #key} first, then if
* nothing matched calling {@link #itemAt}.
* @param {String/Number} key The key or index of the item.
* @return {Object} If the item is found, returns the item.  If the item was
* not found, returns <tt>undefined</tt>. If an item was found, but is a Class,
* returns <tt>null</tt>.
*/
Ext.util.MixedCollection.prototype.get = Ext.util.MixedCollection.prototype.item;
/**
* @class Ext.util.JSON
* Modified version of Douglas Crockford"s json.js that doesn"t
* mess with the Object prototype
* http://www.json.org/js.html
* @singleton
*/
Ext.util.JSON = new (function () {
	var useHasOwn = !!{}.hasOwnProperty,
        isNative = function () {
        	var useNative = null;

        	return function () {
        		if (useNative === null) {
        			useNative = Ext.USE_NATIVE_JSON && window.JSON && JSON.toString() == '[object JSON]';
        		}

        		return useNative;
        	};
        } (),
        pad = function (n) {
        	return n < 10 ? "0" + n : n;
        },
        doDecode = function (json) {
        	return eval("(" + json + ')');
        },
        doEncode = function (o) {
        	if (!Ext.isDefined(o) || o === null) {
        		return "null";
        	} else if (Ext.isArray(o)) {
        		return encodeArray(o);
        	} else if (Ext.isDate(o)) {
        		return Ext.util.JSON.encodeDate(o);
        	} else if (Ext.isString(o)) {
        		return encodeString(o);
        	} else if (typeof o == "number") {
        		//don't use isNumber here, since finite checks happen inside isNumber
        		return isFinite(o) ? String(o) : "null";
        	} else if (Ext.isBoolean(o)) {
        		return String(o);
        	} else {
        		var a = ["{"], b, i, v;
        		for (i in o) {
        			// don't encode DOM objects
        			if (!o.getElementsByTagName) {
        				if (!useHasOwn || o.hasOwnProperty(i)) {
        					v = o[i];
        					switch (typeof v) {
        						case "undefined":
        						case "function":
        						case "unknown":
        							break;
        						default:
        							if (b) {
        								a.push(',');
        							}
        							a.push(doEncode(i), ":",
                                        v === null ? "null" : doEncode(v));
        							b = true;
        					}
        				}
        			}
        		}
        		a.push("}");
        		return a.join("");
        	}
        },
        m = {
        	"\b": '\\b',
        	"\t": '\\t',
        	"\n": '\\n',
        	"\f": '\\f',
        	"\r": '\\r',
        	'"': '\\"',
        	"\\": '\\\\'
        },
        encodeString = function (s) {
        	if (/["\\\x00-\x1f]/.test(s)) {
        		return '"' + s.replace(/([\x00-\x1f\\"])/g, function (a, b) {
        			var c = m[b];
        			if (c) {
        				return c;
        			}
        			c = b.charCodeAt();
        			return "\\u00" +
                        Math.floor(c / 16).toString(16) +
                        (c % 16).toString(16);
        		}) + '"';
        	}
        	return '"' + s + '"';
        },
        encodeArray = function (o) {
        	var a = ["["], b, i, l = o.length, v;
        	for (i = 0; i < l; i += 1) {
        		v = o[i];
        		switch (typeof v) {
        			case "undefined":
        			case "function":
        			case "unknown":
        				break;
        			default:
        				if (b) {
        					a.push(',');
        				}
        				a.push(v === null ? "null" : Ext.util.JSON.encode(v));
        				b = true;
        		}
        	}
        	a.push("]");
        	return a.join("");
        };

	/**
	* <p>Encodes a Date. This returns the actual string which is inserted into the JSON string as the literal expression.
	* <b>The returned value includes enclosing double quotation marks.</b></p>
	* <p>The default return format is "yyyy-mm-ddThh:mm:ss".</p>
	* <p>To override this:</p><pre><code>
	Ext.util.JSON.encodeDate = function(d) {
	return d.format('"Y-m-d"');
	};
	</code></pre>
	* @param {Date} d The Date to encode
	* @return {String} The string literal to use in a JSON string.
	*/
	this.encodeDate = function (o) {
		return '"' + o.getFullYear() + "-" +
                pad(o.getMonth() + 1) + "-" +
                pad(o.getDate()) + "T" +
                pad(o.getHours()) + ":" +
                pad(o.getMinutes()) + ":" +
                pad(o.getSeconds()) + '"';
	};

	/**
	* Encodes an Object, Array or other value
	* @param {Mixed} o The variable to encode
	* @return {String} The JSON string
	*/
	this.encode = function () {
		var ec;
		return function (o) {
			if (!ec) {
				// setup encoding function on first access
				ec = isNative() ? JSON.stringify : doEncode;
			}
			return ec(o);
		};
	} ();


	/**
	* Decodes (parses) a JSON string to an object. If the JSON is invalid, this function throws a SyntaxError unless the safe option is set.
	* @param {String} json The JSON string
	* @return {Object} The resulting object
	*/
	this.decode = function () {
		var dc;
		return function (json) {
			if (!dc) {
				// setup decoding function on first access
				dc = isNative() ? JSON.parse : doDecode;
			}
			return dc(json);
		};
	} ();

})();
/**
* Shorthand for {@link Ext.util.JSON#encode}
* @param {Mixed} o The variable to encode
* @return {String} The JSON string
* @member Ext
* @method encode
*/
Ext.encode = Ext.util.JSON.encode;
/**
* Shorthand for {@link Ext.util.JSON#decode}
* @param {String} json The JSON string
* @param {Boolean} safe (optional) Whether to return null or throw an exception if the JSON is invalid.
* @return {Object} The resulting object
* @member Ext
* @method decode
*/
Ext.decode = Ext.util.JSON.decode;
/**
* @class Ext.util.Format
* Reusable data formatting functions
* @singleton
*/
Ext.util.Format = function () {
	var trimRe = /^\s+|\s+$/g,
        stripTagsRE = /<\/?[^>]+>/gi,
        stripScriptsRe = /(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig,
        nl2brRe = /\r?\n/g;

	return {
		/**
		* Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length
		* @param {String} value The string to truncate
		* @param {Number} length The maximum length to allow before truncating
		* @param {Boolean} word True to try to find a common work break
		* @return {String} The converted text
		*/
		ellipsis: function (value, len, word) {
			if (value && value.length > len) {
				if (word) {
					var vs = value.substr(0, len - 2),
                        index = Math.max(vs.lastIndexOf(' '), vs.lastIndexOf('.'), vs.lastIndexOf('!'), vs.lastIndexOf('?'));
					if (index == -1 || index < (len - 15)) {
						return value.substr(0, len - 3) + "...";
					} else {
						return vs.substr(0, index) + "...";
					}
				} else {
					return value.substr(0, len - 3) + "...";
				}
			}
			return value;
		},

		/**
		* Checks a reference and converts it to empty string if it is undefined
		* @param {Mixed} value Reference to check
		* @return {Mixed} Empty string if converted, otherwise the original value
		*/
		undef: function (value) {
			return value !== undefined ? value : "";
		},

		/**
		* Checks a reference and converts it to the default value if it's empty
		* @param {Mixed} value Reference to check
		* @param {String} defaultValue The value to insert of it's undefined (defaults to "")
		* @return {String}
		*/
		defaultValue: function (value, defaultValue) {
			return value !== undefined && value !== '' ? value : defaultValue;
		},

		/**
		* Convert certain characters (&, <, >, and ') to their HTML character equivalents for literal display in web pages.
		* @param {String} value The string to encode
		* @return {String} The encoded text
		*/
		htmlEncode: function (value) {
			return !value ? value : String(value).replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/"/g, "&quot;");
		},

		/**
		* Convert certain characters (&, <, >, and ') from their HTML character equivalents.
		* @param {String} value The string to decode
		* @return {String} The decoded text
		*/
		htmlDecode: function (value) {
			return !value ? value : String(value).replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/&quot;/g, '"').replace(/&amp;/g, "&");
		},

		/**
		* Trims any whitespace from either side of a string
		* @param {String} value The text to trim
		* @return {String} The trimmed text
		*/
		trim: function (value) {
			return String(value).replace(trimRe, "");
		},

		/**
		* Returns a substring from within an original string
		* @param {String} value The original text
		* @param {Number} start The start index of the substring
		* @param {Number} length The length of the substring
		* @return {String} The substring
		*/
		substr: function (value, start, length) {
			return String(value).substr(start, length);
		},

		/**
		* Converts a string to all lower case letters
		* @param {String} value The text to convert
		* @return {String} The converted text
		*/
		lowercase: function (value) {
			return String(value).toLowerCase();
		},

		/**
		* Converts a string to all upper case letters
		* @param {String} value The text to convert
		* @return {String} The converted text
		*/
		uppercase: function (value) {
			return String(value).toUpperCase();
		},

		/**
		* Converts the first character only of a string to upper case
		* @param {String} value The text to convert
		* @return {String} The converted text
		*/
		capitalize: function (value) {
			return !value ? value : value.charAt(0).toUpperCase() + value.substr(1).toLowerCase();
		},

		// private
		call: function (value, fn) {
			if (arguments.length > 2) {
				var args = Array.prototype.slice.call(arguments, 2);
				args.unshift(value);
				return eval(fn).apply(window, args);
			} else {
				return eval(fn).call(window, value);
			}
		},

		/**
		* Format a number as US currency
		* @param {Number/String} value The numeric value to format
		* @return {String} The formatted currency string
		*/
		usMoney: function (v) {
			v = (Math.round((v - 0) * 100)) / 100;
			v = (v == Math.floor(v)) ? v + ".00" : ((v * 10 == Math.floor(v * 10)) ? v + "0" : v);
			v = String(v);
			var ps = v.split('.'),
                whole = ps[0],
                sub = ps[1] ? '.' + ps[1] : '.00',
                r = /(\d+)(\d{3})/;
			while (r.test(whole)) {
				whole = whole.replace(r, '$1' + ',' + '$2');
			}
			v = whole + sub;
			if (v.charAt(0) == '-') {
				return '-$' + v.substr(1);
			}
			return "$" + v;
		},

		/**
		* Parse a value into a formatted date using the specified format pattern.
		* @param {String/Date} value The value to format (Strings must conform to the format expected by the javascript Date object's <a href="http://www.w3schools.com/jsref/jsref_parse.asp">parse()</a> method)
		* @param {String} format (optional) Any valid date format string (defaults to 'm/d/Y')
		* @return {String} The formatted date string
		*/
		date: function (v, format) {
			if (!v) {
				return "";
			}
			if (!Ext.isDate(v)) {
				v = new Date(Date.parse(v));
			}
			return v.dateFormat(format || "m/d/Y");
		},

		/**
		* Returns a date rendering function that can be reused to apply a date format multiple times efficiently
		* @param {String} format Any valid date format string
		* @return {Function} The date formatting function
		*/
		dateRenderer: function (format) {
			return function (v) {
				return Ext.util.Format.date(v, format);
			};
		},

		/**
		* Strips all HTML tags
		* @param {Mixed} value The text from which to strip tags
		* @return {String} The stripped text
		*/
		stripTags: function (v) {
			return !v ? v : String(v).replace(stripTagsRE, "");
		},

		/**
		* Strips all script tags
		* @param {Mixed} value The text from which to strip script tags
		* @return {String} The stripped text
		*/
		stripScripts: function (v) {
			return !v ? v : String(v).replace(stripScriptsRe, "");
		},

		/**
		* Simple format for a file size (xxx bytes, xxx KB, xxx MB)
		* @param {Number/String} size The numeric value to format
		* @return {String} The formatted file size
		*/
		fileSize: function (size) {
			if (size < 1024) {
				return size + " bytes";
			} else if (size < 1048576) {
				return (Math.round(((size * 10) / 1024)) / 10) + " KB";
			} else {
				return (Math.round(((size * 10) / 1048576)) / 10) + " MB";
			}
		},

		/**
		* It does simple math for use in a template, for example:<pre><code>
		* var tpl = new Ext.Template('{value} * 10 = {value:math("* 10")}');
		* </code></pre>
		* @return {Function} A function that operates on the passed value.
		*/
		math: function () {
			var fns = {};
			return function (v, a) {
				if (!fns[a]) {
					fns[a] = new Function('v', 'return v ' + a + ';');
				}
				return fns[a](v);
			}
		} (),

		/**
		* Rounds the passed number to the required decimal precision.
		* @param {Number/String} value The numeric value to round.
		* @param {Number} precision The number of decimal places to which to round the first parameter's value.
		* @return {Number} The rounded value.
		*/
		round: function (value, precision) {
			var result = Number(value);
			if (typeof precision == 'number') {
				precision = Math.pow(10, precision);
				result = Math.round(value * precision) / precision;
			}
			return result;
		},

		/**
		* Formats the number according to the format string.
		* <div style="margin-left:40px">examples (123456.789):
		* <div style="margin-left:10px">
		* 0 - (123456) show only digits, no precision<br>
		* 0.00 - (123456.78) show only digits, 2 precision<br>
		* 0.0000 - (123456.7890) show only digits, 4 precision<br>
		* 0,000 - (123,456) show comma and digits, no precision<br>
		* 0,000.00 - (123,456.78) show comma and digits, 2 precision<br>
		* 0,0.00 - (123,456.78) shortcut method, show comma and digits, 2 precision<br>
		* To reverse the grouping (,) and decimal (.) for international numbers, add /i to the end.
		* For example: 0.000,00/i
		* </div></div>
		* @param {Number} v The number to format.
		* @param {String} format The way you would like to format this text.
		* @return {String} The formatted number.
		*/
		number: function (v, format) {
			if (!format) {
				return v;
			}
			v = Ext.num(v, NaN);
			if (isNaN(v)) {
				return '';
			}
			var comma = ',',
                dec = '.',
                i18n = false,
                neg = v < 0;

			v = Math.abs(v);
			if (format.substr(format.length - 2) == '/i') {
				format = format.substr(0, format.length - 2);
				i18n = true;
				comma = '.';
				dec = ',';
			}

			var hasComma = format.indexOf(comma) != -1,
                psplit = (i18n ? format.replace(/[^\d\,]/g, '') : format.replace(/[^\d\.]/g, '')).split(dec);

			if (1 < psplit.length) {
				v = v.toFixed(psplit[1].length);
			} else if (2 < psplit.length) {
				throw ('NumberFormatException: invalid format, formats should have no more than 1 period: ' + format);
			} else {
				v = v.toFixed(0);
			}

			var fnum = v.toString();

			psplit = fnum.split('.');

			if (hasComma) {
				var cnum = psplit[0], parr = [], j = cnum.length, m = Math.floor(j / 3), n = cnum.length % 3 || 3;

				for (var i = 0; i < j; i += n) {
					if (i != 0) {
						n = 3;
					}
					parr[parr.length] = cnum.substr(i, n);
					m -= 1;
				}
				fnum = parr.join(comma);
				if (psplit[1]) {
					fnum += dec + psplit[1];
				}
			} else {
				if (psplit[1]) {
					fnum = psplit[0] + dec + psplit[1];
				}
			}

			return (neg ? '-' : '') + format.replace(/[\d,?\.?]+/, fnum);
		},

		/**
		* Returns a number rendering function that can be reused to apply a number format multiple times efficiently
		* @param {String} format Any valid number format string for {@link #number}
		* @return {Function} The number formatting function
		*/
		numberRenderer: function (format) {
			return function (v) {
				return Ext.util.Format.number(v, format);
			};
		},

		/**
		* Selectively do a plural form of a word based on a numeric value. For example, in a template,
		* {commentCount:plural("Comment")}  would result in "1 Comment" if commentCount was 1 or would be "x Comments"
		* if the value is 0 or greater than 1.
		* @param {Number} value The value to compare against
		* @param {String} singular The singular form of the word
		* @param {String} plural (optional) The plural form of the word (defaults to the singular with an "s")
		*/
		plural: function (v, s, p) {
			return v + ' ' + (v == 1 ? s : (p ? p : s + 's'));
		},

		/**
		* Converts newline characters to the HTML tag &lt;br/>
		* @param {String} The string value to format.
		* @return {String} The string with embedded &lt;br/> tags in place of newlines.
		*/
		nl2br: function (v) {
			return Ext.isEmpty(v) ? '' : v.replace(nl2brRe, '<br/>');
		}
	}
} ();
/**
* @class Ext.XTemplate
* @extends Ext.Template
* <p>A template class that supports advanced functionality like:<div class="mdetail-params"><ul>
* <li>Autofilling arrays using templates and sub-templates</li>
* <li>Conditional processing with basic comparison operators</li>
* <li>Basic math function support</li>
* <li>Execute arbitrary inline code with special built-in template variables</li>
* <li>Custom member functions</li>
* <li>Many special tags and built-in operators that aren't defined as part of
* the API, but are supported in the templates that can be created</li>
* </ul></div></p>
* <p>XTemplate provides the templating mechanism built into:<div class="mdetail-params"><ul>
* <li>{@link Ext.DataView}</li>
* <li>{@link Ext.ListView}</li>
* <li>{@link Ext.form.ComboBox}</li>
* <li>{@link Ext.grid.TemplateColumn}</li>
* <li>{@link Ext.grid.GroupingView}</li>
* <li>{@link Ext.menu.Item}</li>
* <li>{@link Ext.layout.MenuLayout}</li>
* <li>{@link Ext.ColorPalette}</li>
* </ul></div></p>
*
* <p>For example usage {@link #XTemplate see the constructor}.</p>
*
* @constructor
* The {@link Ext.Template#Template Ext.Template constructor} describes
* the acceptable parameters to pass to the constructor. The following
* examples demonstrate all of the supported features.</p>
*
* <div class="mdetail-params"><ul>
*
* <li><b><u>Sample Data</u></b>
* <div class="sub-desc">
* <p>This is the data object used for reference in each code example:</p>
* <pre><code>
var data = {
name: 'Jack Slocum',
title: 'Lead Developer',
company: 'Ext JS, LLC',
email: 'jack@extjs.com',
address: '4 Red Bulls Drive',
city: 'Cleveland',
state: 'Ohio',
zip: '44102',
drinks: ['Red Bull', 'Coffee', 'Water'],
kids: [{
name: 'Sara Grace',
age:3
},{
name: 'Zachary',
age:2
},{
name: 'John James',
age:0
}]
};
* </code></pre>
* </div>
* </li>
*
*
* <li><b><u>Auto filling of arrays</u></b>
* <div class="sub-desc">
* <p>The <b><tt>tpl</tt></b> tag and the <b><tt>for</tt></b> operator are used
* to process the provided data object:
* <ul>
* <li>If the value specified in <tt>for</tt> is an array, it will auto-fill,
* repeating the template block inside the <tt>tpl</tt> tag for each item in the
* array.</li>
* <li>If <tt>for="."</tt> is specified, the data object provided is examined.</li>
* <li>While processing an array, the special variable <tt>{#}</tt>
* will provide the current array index + 1 (starts at 1, not 0).</li>
* </ul>
* </p>
* <pre><code>
&lt;tpl <b>for</b>=".">...&lt;/tpl>       // loop through array at root node
&lt;tpl <b>for</b>="foo">...&lt;/tpl>     // loop through array at foo node
&lt;tpl <b>for</b>="foo.bar">...&lt;/tpl> // loop through array at foo.bar node
* </code></pre>
* Using the sample data above:
* <pre><code>
var tpl = new Ext.XTemplate(
'&lt;p>Kids: ',
'&lt;tpl <b>for</b>=".">',       // process the data.kids node
'&lt;p>{#}. {name}&lt;/p>',  // use current array index to autonumber
'&lt;/tpl>&lt;/p>'
);
tpl.overwrite(panel.body, data.kids); // pass the kids property of the data object
* </code></pre>
* <p>An example illustrating how the <b><tt>for</tt></b> property can be leveraged
* to access specified members of the provided data object to populate the template:</p>
* <pre><code>
var tpl = new Ext.XTemplate(
'&lt;p>Name: {name}&lt;/p>',
'&lt;p>Title: {title}&lt;/p>',
'&lt;p>Company: {company}&lt;/p>',
'&lt;p>Kids: ',
'&lt;tpl <b>for="kids"</b>>',     // interrogate the kids property within the data
'&lt;p>{name}&lt;/p>',
'&lt;/tpl>&lt;/p>'
);
tpl.overwrite(panel.body, data);  // pass the root node of the data object
* </code></pre>
* <p>Flat arrays that contain values (and not objects) can be auto-rendered
* using the special <b><tt>{.}</tt></b> variable inside a loop.  This variable
* will represent the value of the array at the current index:</p>
* <pre><code>
var tpl = new Ext.XTemplate(
'&lt;p>{name}\&#39;s favorite beverages:&lt;/p>',
'&lt;tpl for="drinks">',
'&lt;div> - {.}&lt;/div>',
'&lt;/tpl>'
);
tpl.overwrite(panel.body, data);
* </code></pre>
* <p>When processing a sub-template, for example while looping through a child array,
* you can access the parent object's members via the <b><tt>parent</tt></b> object:</p>
* <pre><code>
var tpl = new Ext.XTemplate(
'&lt;p>Name: {name}&lt;/p>',
'&lt;p>Kids: ',
'&lt;tpl for="kids">',
'&lt;tpl if="age > 1">',
'&lt;p>{name}&lt;/p>',
'&lt;p>Dad: {<b>parent</b>.name}&lt;/p>',
'&lt;/tpl>',
'&lt;/tpl>&lt;/p>'
);
tpl.overwrite(panel.body, data);
* </code></pre>
* </div>
* </li>
*
*
* <li><b><u>Conditional processing with basic comparison operators</u></b>
* <div class="sub-desc">
* <p>The <b><tt>tpl</tt></b> tag and the <b><tt>if</tt></b> operator are used
* to provide conditional checks for deciding whether or not to render specific
* parts of the template. Notes:<div class="sub-desc"><ul>
* <li>Double quotes must be encoded if used within the conditional</li>
* <li>There is no <tt>else</tt> operator &mdash; if needed, two opposite
* <tt>if</tt> statements should be used.</li>
* </ul></div>
* <pre><code>
&lt;tpl if="age &gt; 1 &amp;&amp; age &lt; 10">Child&lt;/tpl>
&lt;tpl if="age >= 10 && age < 18">Teenager&lt;/tpl>
&lt;tpl <b>if</b>="this.isGirl(name)">...&lt;/tpl>
&lt;tpl <b>if</b>="id==\'download\'">...&lt;/tpl>
&lt;tpl <b>if</b>="needsIcon">&lt;img src="{icon}" class="{iconCls}"/>&lt;/tpl>
// no good:
&lt;tpl if="name == "Jack"">Hello&lt;/tpl>
// encode &#34; if it is part of the condition, e.g.
&lt;tpl if="name == &#38;quot;Jack&#38;quot;">Hello&lt;/tpl>
* </code></pre>
* Using the sample data above:
* <pre><code>
var tpl = new Ext.XTemplate(
'&lt;p>Name: {name}&lt;/p>',
'&lt;p>Kids: ',
'&lt;tpl for="kids">',
'&lt;tpl if="age > 1">',
'&lt;p>{name}&lt;/p>',
'&lt;/tpl>',
'&lt;/tpl>&lt;/p>'
);
tpl.overwrite(panel.body, data);
* </code></pre>
* </div>
* </li>
*
*
* <li><b><u>Basic math support</u></b>
* <div class="sub-desc">
* <p>The following basic math operators may be applied directly on numeric
* data values:</p><pre>
* + - * /
* </pre>
* For example:
* <pre><code>
var tpl = new Ext.XTemplate(
'&lt;p>Name: {name}&lt;/p>',
'&lt;p>Kids: ',
'&lt;tpl for="kids">',
'&lt;tpl if="age &amp;gt; 1">',  // <-- Note that the &gt; is encoded
'&lt;p>{#}: {name}&lt;/p>',  // <-- Auto-number each item
'&lt;p>In 5 Years: {age+5}&lt;/p>',  // <-- Basic math
'&lt;p>Dad: {parent.name}&lt;/p>',
'&lt;/tpl>',
'&lt;/tpl>&lt;/p>'
);
tpl.overwrite(panel.body, data);
</code></pre>
* </div>
* </li>
*
*
* <li><b><u>Execute arbitrary inline code with special built-in template variables</u></b>
* <div class="sub-desc">
* <p>Anything between <code>{[ ... ]}</code> is considered code to be executed
* in the scope of the template. There are some special variables available in that code:
* <ul>
* <li><b><tt>values</tt></b>: The values in the current scope. If you are using
* scope changing sub-templates, you can change what <tt>values</tt> is.</li>
* <li><b><tt>parent</tt></b>: The scope (values) of the ancestor template.</li>
* <li><b><tt>xindex</tt></b>: If you are in a looping template, the index of the
* loop you are in (1-based).</li>
* <li><b><tt>xcount</tt></b>: If you are in a looping template, the total length
* of the array you are looping.</li>
* <li><b><tt>fm</tt></b>: An alias for <tt>Ext.util.Format</tt>.</li>
* </ul>
* This example demonstrates basic row striping using an inline code block and the
* <tt>xindex</tt> variable:</p>
* <pre><code>
var tpl = new Ext.XTemplate(
'&lt;p>Name: {name}&lt;/p>',
'&lt;p>Company: {[values.company.toUpperCase() + ", " + values.title]}&lt;/p>',
'&lt;p>Kids: ',
'&lt;tpl for="kids">',
'&lt;div class="{[xindex % 2 === 0 ? "even" : "odd"]}">',
'{name}',
'&lt;/div>',
'&lt;/tpl>&lt;/p>'
);
tpl.overwrite(panel.body, data);
* </code></pre>
* </div>
* </li>
*
* <li><b><u>Template member functions</u></b>
* <div class="sub-desc">
* <p>One or more member functions can be specified in a configuration
* object passed into the XTemplate constructor for more complex processing:</p>
* <pre><code>
var tpl = new Ext.XTemplate(
'&lt;p>Name: {name}&lt;/p>',
'&lt;p>Kids: ',
'&lt;tpl for="kids">',
'&lt;tpl if="this.isGirl(name)">',
'&lt;p>Girl: {name} - {age}&lt;/p>',
'&lt;/tpl>',
// use opposite if statement to simulate 'else' processing:
'&lt;tpl if="this.isGirl(name) == false">',
'&lt;p>Boy: {name} - {age}&lt;/p>',
'&lt;/tpl>',
'&lt;tpl if="this.isBaby(age)">',
'&lt;p>{name} is a baby!&lt;/p>',
'&lt;/tpl>',
'&lt;/tpl>&lt;/p>',
{
// XTemplate configuration:
compiled: true,
disableFormats: true,
// member functions:
isGirl: function(name){
return name == 'Sara Grace';
},
isBaby: function(age){
return age < 1;
}
}
);
tpl.overwrite(panel.body, data);
* </code></pre>
* </div>
* </li>
*
* </ul></div>
*
* @param {Mixed} config
*/
Ext.XTemplate = function () {
	Ext.XTemplate.superclass.constructor.apply(this, arguments);

	var me = this,
        s = me.html,
        re = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
        nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
        ifRe = /^<tpl\b[^>]*?if="(.*?)"/,
        execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
        m,
        id = 0,
        tpls = [],
        VALUES = 'values',
        PARENT = 'parent',
        XINDEX = 'xindex',
        XCOUNT = 'xcount',
        RETURN = 'return ',
        WITHVALUES = 'with(values){ ';

	s = ['<tpl>', s, '</tpl>'].join('');

	while ((m = s.match(re))) {
		var m2 = m[0].match(nameRe),
            m3 = m[0].match(ifRe),
            m4 = m[0].match(execRe),
            exp = null,
            fn = null,
            exec = null,
            name = m2 && m2[1] ? m2[1] : '';

		if (m3) {
			exp = m3 && m3[1] ? m3[1] : null;
			if (exp) {
				fn = new Function(VALUES, PARENT, XINDEX, XCOUNT, WITHVALUES + RETURN + (Ext.util.Format.htmlDecode(exp)) + '; }');
			}
		}
		if (m4) {
			exp = m4 && m4[1] ? m4[1] : null;
			if (exp) {
				exec = new Function(VALUES, PARENT, XINDEX, XCOUNT, WITHVALUES + (Ext.util.Format.htmlDecode(exp)) + '; }');
			}
		}
		if (name) {
			switch (name) {
				case '.': name = new Function(VALUES, PARENT, WITHVALUES + RETURN + VALUES + '; }'); break;
				case '..': name = new Function(VALUES, PARENT, WITHVALUES + RETURN + PARENT + '; }'); break;
				default: name = new Function(VALUES, PARENT, WITHVALUES + RETURN + name + '; }');
			}
		}
		tpls.push({
			id: id,
			target: name,
			exec: exec,
			test: fn,
			body: m[1] || ''
		});
		s = s.replace(m[0], '{xtpl' + id + '}');
		++id;
	}
	for (var i = tpls.length - 1; i >= 0; --i) {
		me.compileTpl(tpls[i]);
	}
	me.master = tpls[tpls.length - 1];
	me.tpls = tpls;
};
Ext.extend(Ext.XTemplate, Ext.Template, {
	// private
	re: /\{([\w-\.\#]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?(\s?[\+\-\*\\]\s?[\d\.\+\-\*\\\(\)]+)?\}/g,
	// private
	codeRe: /\{\[((?:\\\]|.|\n)*?)\]\}/g,

	// private
	applySubTemplate: function (id, values, parent, xindex, xcount) {
		var me = this,
            len,
            t = me.tpls[id],
            vs,
            buf = [];
		if ((t.test && !t.test.call(me, values, parent, xindex, xcount)) ||
            (t.exec && t.exec.call(me, values, parent, xindex, xcount))) {
			return '';
		}
		vs = t.target ? t.target.call(me, values, parent) : values;
		len = vs.length;
		parent = t.target ? values : parent;
		if (t.target && Ext.isArray(vs)) {
			for (var i = 0, len = vs.length; i < len; i++) {
				buf[buf.length] = t.compiled.call(me, vs[i], parent, i + 1, len);
			}
			return buf.join('');
		}
		return t.compiled.call(me, vs, parent, xindex, xcount);
	},

	// private
	compileTpl: function (tpl) {
		var fm = Ext.util.Format,
            useF = this.disableFormats !== true,
            sep = Ext.isGecko ? "+" : ",",
            body;

		function fn(m, name, format, args, math) {
			if (name.substr(0, 4) == 'xtpl') {
				return "'" + sep + 'this.applySubTemplate(' + name.substr(4) + ', values, parent, xindex, xcount)' + sep + "'";
			}
			var v;
			if (name === '.') {
				v = 'values';
			} else if (name === '#') {
				v = 'xindex';
			} else if (name.indexOf('.') != -1) {
				v = name;
			} else {
				v = "values['" + name + "']";
			}
			if (math) {
				v = '(' + v + math + ')';
			}
			if (format && useF) {
				args = args ? ',' + args : "";
				if (format.substr(0, 5) != "this.") {
					format = "fm." + format + '(';
				} else {
					format = 'this.call("' + format.substr(5) + '", ';
					args = ", values";
				}
			} else {
				args = ''; format = "(" + v + " === undefined ? '' : ";
			}
			return "'" + sep + format + v + args + ")" + sep + "'";
		}

		function codeFn(m, code) {
			// Single quotes get escaped when the template is compiled, however we want to undo this when running code.
			return "'" + sep + '(' + code.replace(/\\'/g, "'") + ')' + sep + "'";
		}

		// branched to use + in gecko and [].join() in others
		if (Ext.isGecko) {
			body = "tpl.compiled = function(values, parent, xindex, xcount){ return '" +
                   tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn).replace(this.codeRe, codeFn) +
                    "';};";
		} else {
			body = ["tpl.compiled = function(values, parent, xindex, xcount){ return ['"];
			body.push(tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn).replace(this.codeRe, codeFn));
			body.push("'].join('');};");
			body = body.join('');
		}
		eval(body);
		return this;
	},

	/**
	* Returns an HTML fragment of this template with the specified values applied.
	* @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'})
	* @return {String} The HTML fragment
	*/
	applyTemplate: function (values) {
		return this.master.compiled.call(this, values, {}, 1, 1);
	},

	/**
	* Compile the template to a function for optimized performance.  Recommended if the template will be used frequently.
	* @return {Function} The compiled function
	*/
	compile: function () { return this; }

	/**
	* @property re
	* @hide
	*/
	/**
	* @property disableFormats
	* @hide
	*/
	/**
	* @method set
	* @hide
	*/

});
/**
* Alias for {@link #applyTemplate}
* Returns an HTML fragment of this template with the specified values applied.
* @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'})
* @return {String} The HTML fragment
* @member Ext.XTemplate
* @method apply
*/
Ext.XTemplate.prototype.apply = Ext.XTemplate.prototype.applyTemplate;

/**
* Creates a template from the passed element's value (<i>display:none</i> textarea, preferred) or innerHTML.
* @param {String/HTMLElement} el A DOM element or its id
* @return {Ext.Template} The created template
* @static
*/
Ext.XTemplate.from = function (el) {
	el = Ext.getDom(el);
	return new Ext.XTemplate(el.value || el.innerHTML);
};
/**
* @class Ext.util.CSS
* Utility class for manipulating CSS rules
* @singleton
*/
Ext.util.CSS = function () {
	var rules = null;
	var doc = document;

	var camelRe = /(-[a-z])/gi;
	var camelFn = function (m, a) { return a.charAt(1).toUpperCase(); };

	return {
		/**
		* Creates a stylesheet from a text blob of rules.
		* These rules will be wrapped in a STYLE tag and appended to the HEAD of the document.
		* @param {String} cssText The text containing the css rules
		* @param {String} id An id to add to the stylesheet for later removal
		* @return {StyleSheet}
		*/
		createStyleSheet: function (cssText, id) {
			var ss;
			var head = doc.getElementsByTagName("head")[0];
			var rules = doc.createElement("style");
			rules.setAttribute("type", "text/css");
			if (id) {
				rules.setAttribute("id", id);
			}
			if (Ext.isIE) {
				head.appendChild(rules);
				ss = rules.styleSheet;
				ss.cssText = cssText;
			} else {
				try {
					rules.appendChild(doc.createTextNode(cssText));
				} catch (e) {
					rules.cssText = cssText;
				}
				head.appendChild(rules);
				ss = rules.styleSheet ? rules.styleSheet : (rules.sheet || doc.styleSheets[doc.styleSheets.length - 1]);
			}
			this.cacheStyleSheet(ss);
			return ss;
		},

		/**
		* Removes a style or link tag by id
		* @param {String} id The id of the tag
		*/
		removeStyleSheet: function (id) {
			var existing = doc.getElementById(id);
			if (existing) {
				existing.parentNode.removeChild(existing);
			}
		},

		/**
		* Dynamically swaps an existing stylesheet reference for a new one
		* @param {String} id The id of an existing link tag to remove
		* @param {String} url The href of the new stylesheet to include
		*/
		swapStyleSheet: function (id, url) {
			this.removeStyleSheet(id);
			var ss = doc.createElement("link");
			ss.setAttribute("rel", "stylesheet");
			ss.setAttribute("type", "text/css");
			ss.setAttribute("id", id);
			ss.setAttribute("href", url);
			doc.getElementsByTagName("head")[0].appendChild(ss);
		},

		/**
		* Refresh the rule cache if you have dynamically added stylesheets
		* @return {Object} An object (hash) of rules indexed by selector
		*/
		refreshCache: function () {
			return this.getRules(true);
		},

		// private
		cacheStyleSheet: function (ss) {
			if (!rules) {
				rules = {};
			}
			try {// try catch for cross domain access issue
				var ssRules = ss.cssRules || ss.rules;
				for (var j = ssRules.length - 1; j >= 0; --j) {
					rules[ssRules[j].selectorText.toLowerCase()] = ssRules[j];
				}
			} catch (e) { }
		},

		/**
		* Gets all css rules for the document
		* @param {Boolean} refreshCache true to refresh the internal cache
		* @return {Object} An object (hash) of rules indexed by selector
		*/
		getRules: function (refreshCache) {
			if (rules === null || refreshCache) {
				rules = {};
				var ds = doc.styleSheets;
				for (var i = 0, len = ds.length; i < len; i++) {
					try {
						this.cacheStyleSheet(ds[i]);
					} catch (e) { }
				}
			}
			return rules;
		},

		/**
		* Gets an an individual CSS rule by selector(s)
		* @param {String/Array} selector The CSS selector or an array of selectors to try. The first selector that is found is returned.
		* @param {Boolean} refreshCache true to refresh the internal cache if you have recently updated any rules or added styles dynamically
		* @return {CSSRule} The CSS rule or null if one is not found
		*/
		getRule: function (selector, refreshCache) {
			var rs = this.getRules(refreshCache);
			if (!Ext.isArray(selector)) {
				return rs[selector.toLowerCase()];
			}
			for (var i = 0; i < selector.length; i++) {
				if (rs[selector[i]]) {
					return rs[selector[i].toLowerCase()];
				}
			}
			return null;
		},


		/**
		* Updates a rule property
		* @param {String/Array} selector If it's an array it tries each selector until it finds one. Stops immediately once one is found.
		* @param {String} property The css property
		* @param {String} value The new value for the property
		* @return {Boolean} true If a rule was found and updated
		*/
		updateRule: function (selector, property, value) {
			if (!Ext.isArray(selector)) {
				var rule = this.getRule(selector);
				if (rule) {
					rule.style[property.replace(camelRe, camelFn)] = value;
					return true;
				}
			} else {
				for (var i = 0; i < selector.length; i++) {
					if (this.updateRule(selector[i], property, value)) {
						return true;
					}
				}
			}
			return false;
		}
	};
} (); /**
 @class Ext.util.ClickRepeater
 @extends Ext.util.Observable

 A wrapper class which can be applied to any element. Fires a "click" event while the
 mouse is pressed. The interval between firings may be specified in the config but
 defaults to 20 milliseconds.

 Optionally, a CSS class may be applied to the element during the time it is pressed.

 @cfg {Mixed} el The element to act as a button.
 @cfg {Number} delay The initial delay before the repeating event begins firing.
 Similar to an autorepeat key delay.
 @cfg {Number} interval The interval between firings of the "click" event. Default 20 ms.
 @cfg {String} pressClass A CSS class name to be applied to the element while pressed.
 @cfg {Boolean} accelerate True if autorepeating should start slowly and accelerate.
           "interval" and "delay" are ignored.
 @cfg {Boolean} preventDefault True to prevent the default click event
 @cfg {Boolean} stopDefault True to stop the default click event

 @history
    2007-02-02 jvs Original code contributed by Nige "Animal" White
    2007-02-02 jvs Renamed to ClickRepeater
    2007-02-03 jvs Modifications for FF Mac and Safari

 @constructor
 @param {Mixed} el The element to listen on
 @param {Object} config
 */
Ext.util.ClickRepeater = function (el, config) {
	this.el = Ext.get(el);
	this.el.unselectable();

	Ext.apply(this, config);

	this.addEvents(
	/**
	* @event mousedown
	* Fires when the mouse button is depressed.
	* @param {Ext.util.ClickRepeater} this
	*/
        "mousedown",
	/**
	* @event click
	* Fires on a specified interval during the time the element is pressed.
	* @param {Ext.util.ClickRepeater} this
	*/
        "click",
	/**
	* @event mouseup
	* Fires when the mouse key is released.
	* @param {Ext.util.ClickRepeater} this
	*/
        "mouseup"
    );

	if (!this.disabled) {
		this.disabled = true;
		this.enable();
	}

	// allow inline handler
	if (this.handler) {
		this.on("click", this.handler, this.scope || this);
	}

	Ext.util.ClickRepeater.superclass.constructor.call(this);
};

Ext.extend(Ext.util.ClickRepeater, Ext.util.Observable, {
	interval: 20,
	delay: 250,
	preventDefault: true,
	stopDefault: false,
	timer: 0,

	/**
	* Enables the repeater and allows events to fire.
	*/
	enable: function () {
		if (this.disabled) {
			this.el.on('mousedown', this.handleMouseDown, this);
			if (Ext.isIE) {
				this.el.on('dblclick', this.handleDblClick, this);
			}
			if (this.preventDefault || this.stopDefault) {
				this.el.on('click', this.eventOptions, this);
			}
		}
		this.disabled = false;
	},

	/**
	* Disables the repeater and stops events from firing.
	*/
	disable: function (/* private */force) {
		if (force || !this.disabled) {
			clearTimeout(this.timer);
			if (this.pressClass) {
				this.el.removeClass(this.pressClass);
			}
			Ext.getDoc().un('mouseup', this.handleMouseUp, this);
			this.el.removeAllListeners();
		}
		this.disabled = true;
	},

	/**
	* Convenience function for setting disabled/enabled by boolean.
	* @param {Boolean} disabled
	*/
	setDisabled: function (disabled) {
		this[disabled ? 'disable' : 'enable']();
	},

	eventOptions: function (e) {
		if (this.preventDefault) {
			e.preventDefault();
		}
		if (this.stopDefault) {
			e.stopEvent();
		}
	},

	// private
	destroy: function () {
		this.disable(true);
		Ext.destroy(this.el);
		this.purgeListeners();
	},

	handleDblClick: function () {
		clearTimeout(this.timer);
		this.el.blur();

		this.fireEvent("mousedown", this);
		this.fireEvent("click", this);
	},

	// private
	handleMouseDown: function () {
		clearTimeout(this.timer);
		this.el.blur();
		if (this.pressClass) {
			this.el.addClass(this.pressClass);
		}
		this.mousedownTime = new Date();

		Ext.getDoc().on("mouseup", this.handleMouseUp, this);
		this.el.on("mouseout", this.handleMouseOut, this);

		this.fireEvent("mousedown", this);
		this.fireEvent("click", this);

		// Do not honor delay or interval if acceleration wanted.
		if (this.accelerate) {
			this.delay = 400;
		}
		this.timer = this.click.defer(this.delay || this.interval, this);
	},

	// private
	click: function () {
		this.fireEvent("click", this);
		this.timer = this.click.defer(this.accelerate ?
            this.easeOutExpo(this.mousedownTime.getElapsed(),
                400,
                -390,
                12000) :
            this.interval, this);
	},

	easeOutExpo: function (t, b, c, d) {
		return (t == d) ? b + c : c * (-Math.pow(2, -10 * t / d) + 1) + b;
	},

	// private
	handleMouseOut: function () {
		clearTimeout(this.timer);
		if (this.pressClass) {
			this.el.removeClass(this.pressClass);
		}
		this.el.on("mouseover", this.handleMouseReturn, this);
	},

	// private
	handleMouseReturn: function () {
		this.el.un("mouseover", this.handleMouseReturn, this);
		if (this.pressClass) {
			this.el.addClass(this.pressClass);
		}
		this.click();
	},

	// private
	handleMouseUp: function () {
		clearTimeout(this.timer);
		this.el.un("mouseover", this.handleMouseReturn, this);
		this.el.un("mouseout", this.handleMouseOut, this);
		Ext.getDoc().un("mouseup", this.handleMouseUp, this);
		this.el.removeClass(this.pressClass);
		this.fireEvent("mouseup", this);
	}
}); /**
 * @class Ext.KeyNav
 * <p>Provides a convenient wrapper for normalized keyboard navigation.  KeyNav allows you to bind
 * navigation keys to function calls that will get called when the keys are pressed, providing an easy
 * way to implement custom navigation schemes for any UI component.</p>
 * <p>The following are all of the possible keys that can be implemented: enter, left, right, up, down, tab, esc,
 * pageUp, pageDown, del, home, end.  Usage:</p>
 <pre><code>
var nav = new Ext.KeyNav("my-element", {
    "left" : function(e){
        this.moveLeft(e.ctrlKey);
    },
    "right" : function(e){
        this.moveRight(e.ctrlKey);
    },
    "enter" : function(e){
        this.save();
    },
    scope : this
});
</code></pre>
 * @constructor
 * @param {Mixed} el The element to bind to
 * @param {Object} config The config
 */
Ext.KeyNav = function (el, config) {
	this.el = Ext.get(el);
	Ext.apply(this, config);
	if (!this.disabled) {
		this.disabled = true;
		this.enable();
	}
};

Ext.KeyNav.prototype = {
	/**
	* @cfg {Boolean} disabled
	* True to disable this KeyNav instance (defaults to false)
	*/
	disabled: false,
	/**
	* @cfg {String} defaultEventAction
	* The method to call on the {@link Ext.EventObject} after this KeyNav intercepts a key.  Valid values are
	* {@link Ext.EventObject#stopEvent}, {@link Ext.EventObject#preventDefault} and
	* {@link Ext.EventObject#stopPropagation} (defaults to 'stopEvent')
	*/
	defaultEventAction: "stopEvent",
	/**
	* @cfg {Boolean} forceKeyDown
	* Handle the keydown event instead of keypress (defaults to false).  KeyNav automatically does this for IE since
	* IE does not propagate special keys on keypress, but setting this to true will force other browsers to also
	* handle keydown instead of keypress.
	*/
	forceKeyDown: false,

	// private
	relay: function (e) {
		var k = e.getKey();
		var h = this.keyToHandler[k];
		if (h && this[h]) {
			if (this.doRelay(e, this[h], h) !== true) {
				e[this.defaultEventAction]();
			}
		}
	},

	// private
	doRelay: function (e, h, hname) {
		return h.call(this.scope || this, e);
	},

	// possible handlers
	enter: false,
	left: false,
	right: false,
	up: false,
	down: false,
	tab: false,
	esc: false,
	pageUp: false,
	pageDown: false,
	del: false,
	home: false,
	end: false,

	// quick lookup hash
	keyToHandler: {
		37: "left",
		39: "right",
		38: "up",
		40: "down",
		33: "pageUp",
		34: "pageDown",
		46: "del",
		36: "home",
		35: "end",
		13: "enter",
		27: "esc",
		9: "tab"
	},

	stopKeyUp: function (e) {
		var k = e.getKey();

		if (k >= 37 && k <= 40) {
			// *** bugfix - safari 2.x fires 2 keyup events on cursor keys
			// *** (note: this bugfix sacrifices the "keyup" event originating from keyNav elements in Safari 2)
			e.stopEvent();
		}
	},

	/**
	* Destroy this KeyNav (this is the same as calling disable).
	*/
	destroy: function () {
		this.disable();
	},

	/**
	* Enable this KeyNav
	*/
	enable: function () {
		if (this.disabled) {
			if (Ext.isSafari2) {
				// call stopKeyUp() on "keyup" event
				this.el.on('keyup', this.stopKeyUp, this);
			}

			this.el.on(this.isKeydown() ? 'keydown' : 'keypress', this.relay, this);
			this.disabled = false;
		}
	},

	/**
	* Disable this KeyNav
	*/
	disable: function () {
		if (!this.disabled) {
			if (Ext.isSafari2) {
				// remove "keyup" event handler
				this.el.un('keyup', this.stopKeyUp, this);
			}

			this.el.un(this.isKeydown() ? 'keydown' : 'keypress', this.relay, this);
			this.disabled = true;
		}
	},

	/**
	* Convenience function for setting disabled/enabled by boolean.
	* @param {Boolean} disabled
	*/
	setDisabled: function (disabled) {
		this[disabled ? "disable" : "enable"]();
	},

	// private
	isKeydown: function () {
		return this.forceKeyDown || Ext.EventManager.useKeydown;
	}
};
/**
* @class Ext.KeyMap
* Handles mapping keys to actions for an element. One key map can be used for multiple actions.
* The constructor accepts the same config object as defined by {@link #addBinding}.
* If you bind a callback function to a KeyMap, anytime the KeyMap handles an expected key
* combination it will call the function with this signature (if the match is a multi-key
* combination the callback will still be called only once): (String key, Ext.EventObject e)
* A KeyMap can also handle a string representation of keys.<br />
* Usage:
<pre><code>
// map one key by key code
var map = new Ext.KeyMap("my-element", {
key: 13, // or Ext.EventObject.ENTER
fn: myHandler,
scope: myObject
});

// map multiple keys to one action by string
var map = new Ext.KeyMap("my-element", {
key: "a\r\n\t",
fn: myHandler,
scope: myObject
});

// map multiple keys to multiple actions by strings and array of codes
var map = new Ext.KeyMap("my-element", [
{
key: [10,13],
fn: function(){ alert("Return was pressed"); }
}, {
key: "abc",
fn: function(){ alert('a, b or c was pressed'); }
}, {
key: "\t",
ctrl:true,
shift:true,
fn: function(){ alert('Control + shift + tab was pressed.'); }
}
]);
</code></pre>
* <b>Note: A KeyMap starts enabled</b>
* @constructor
* @param {Mixed} el The element to bind to
* @param {Object} config The config (see {@link #addBinding})
* @param {String} eventName (optional) The event to bind to (defaults to "keydown")
*/
Ext.KeyMap = function (el, config, eventName) {
	this.el = Ext.get(el);
	this.eventName = eventName || "keydown";
	this.bindings = [];
	if (config) {
		this.addBinding(config);
	}
	this.enable();
};

Ext.KeyMap.prototype = {
	/**
	* True to stop the event from bubbling and prevent the default browser action if the
	* key was handled by the KeyMap (defaults to false)
	* @type Boolean
	*/
	stopEvent: false,

	/**
	* Add a new binding to this KeyMap. The following config object properties are supported:
	* <pre>
	Property    Type             Description
	----------  ---------------  ----------------------------------------------------------------------
	key         String/Array     A single keycode or an array of keycodes to handle
	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)
	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)
	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)
	handler     Function         The function to call when KeyMap finds the expected key combination
	fn          Function         Alias of handler (for backwards-compatibility)
	scope       Object           The scope of the callback function
	stopEvent   Boolean          True to stop the event from bubbling and prevent the default browser action if the key was handled by the KeyMap (defaults to false)
	</pre>
	*
	* Usage:
	* <pre><code>
	// Create a KeyMap
	var map = new Ext.KeyMap(document, {
	key: Ext.EventObject.ENTER,
	fn: handleKey,
	scope: this
	});

	//Add a new binding to the existing KeyMap later
	map.addBinding({
	key: 'abc',
	shift: true,
	fn: handleKey,
	scope: this
	});
	</code></pre>
	* @param {Object/Array} config A single KeyMap config or an array of configs
	*/
	addBinding: function (config) {
		if (Ext.isArray(config)) {
			Ext.each(config, function (c) {
				this.addBinding(c);
			}, this);
			return;
		}
		var keyCode = config.key,
            fn = config.fn || config.handler,
            scope = config.scope;

		if (config.stopEvent) {
			this.stopEvent = config.stopEvent;
		}

		if (typeof keyCode == "string") {
			var ks = [];
			var keyString = keyCode.toUpperCase();
			for (var j = 0, len = keyString.length; j < len; j++) {
				ks.push(keyString.charCodeAt(j));
			}
			keyCode = ks;
		}
		var keyArray = Ext.isArray(keyCode);

		var handler = function (e) {
			if (this.checkModifiers(config, e)) {
				var k = e.getKey();
				if (keyArray) {
					for (var i = 0, len = keyCode.length; i < len; i++) {
						if (keyCode[i] == k) {
							if (this.stopEvent) {
								e.stopEvent();
							}
							fn.call(scope || window, k, e);
							return;
						}
					}
				} else {
					if (k == keyCode) {
						if (this.stopEvent) {
							e.stopEvent();
						}
						fn.call(scope || window, k, e);
					}
				}
			}
		};
		this.bindings.push(handler);
	},

	// private
	checkModifiers: function (config, e) {
		var val, key, keys = ['shift', 'ctrl', 'alt'];
		for (var i = 0, len = keys.length; i < len; ++i) {
			key = keys[i];
			val = config[key];
			if (!(val === undefined || (val === e[key + 'Key']))) {
				return false;
			}
		}
		return true;
	},

	/**
	* Shorthand for adding a single key listener
	* @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the
	* following options:
	* {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
	* @param {Function} fn The function to call
	* @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to the browser window.
	*/
	on: function (key, fn, scope) {
		var keyCode, shift, ctrl, alt;
		if (typeof key == "object" && !Ext.isArray(key)) {
			keyCode = key.key;
			shift = key.shift;
			ctrl = key.ctrl;
			alt = key.alt;
		} else {
			keyCode = key;
		}
		this.addBinding({
			key: keyCode,
			shift: shift,
			ctrl: ctrl,
			alt: alt,
			fn: fn,
			scope: scope
		});
	},

	// private
	handleKeyDown: function (e) {
		if (this.enabled) { //just in case
			var b = this.bindings;
			for (var i = 0, len = b.length; i < len; i++) {
				b[i].call(this, e);
			}
		}
	},

	/**
	* Returns true if this KeyMap is enabled
	* @return {Boolean}
	*/
	isEnabled: function () {
		return this.enabled;
	},

	/**
	* Enables this KeyMap
	*/
	enable: function () {
		if (!this.enabled) {
			this.el.on(this.eventName, this.handleKeyDown, this);
			this.enabled = true;
		}
	},

	/**
	* Disable this KeyMap
	*/
	disable: function () {
		if (this.enabled) {
			this.el.removeListener(this.eventName, this.handleKeyDown, this);
			this.enabled = false;
		}
	},

	/**
	* Convenience function for setting disabled/enabled by boolean.
	* @param {Boolean} disabled
	*/
	setDisabled: function (disabled) {
		this[disabled ? "disable" : "enable"]();
	}
}; /**
 * @class Ext.util.TextMetrics
 * Provides precise pixel measurements for blocks of text so that you can determine exactly how high and
 * wide, in pixels, a given block of text will be. Note that when measuring text, it should be plain text and
 * should not contain any HTML, otherwise it may not be measured correctly.
 * @singleton
 */
Ext.util.TextMetrics = function () {
	var shared;
	return {
		/**
		* Measures the size of the specified text
		* @param {String/HTMLElement} el The element, dom node or id from which to copy existing CSS styles
		* that can affect the size of the rendered text
		* @param {String} text The text to measure
		* @param {Number} fixedWidth (optional) If the text will be multiline, you have to set a fixed width
		* in order to accurately measure the text height
		* @return {Object} An object containing the text's size {width: (width), height: (height)}
		*/
		measure: function (el, text, fixedWidth) {
			if (!shared) {
				shared = Ext.util.TextMetrics.Instance(el, fixedWidth);
			}
			shared.bind(el);
			shared.setFixedWidth(fixedWidth || 'auto');
			return shared.getSize(text);
		},

		/**
		* Return a unique TextMetrics instance that can be bound directly to an element and reused.  This reduces
		* the overhead of multiple calls to initialize the style properties on each measurement.
		* @param {String/HTMLElement} el The element, dom node or id that the instance will be bound to
		* @param {Number} fixedWidth (optional) If the text will be multiline, you have to set a fixed width
		* in order to accurately measure the text height
		* @return {Ext.util.TextMetrics.Instance} instance The new instance
		*/
		createInstance: function (el, fixedWidth) {
			return Ext.util.TextMetrics.Instance(el, fixedWidth);
		}
	};
} ();

Ext.util.TextMetrics.Instance = function (bindTo, fixedWidth) {
	var ml = new Ext.Element(document.createElement('div'));
	document.body.appendChild(ml.dom);
	ml.position('absolute');
	ml.setLeftTop(-1000, -1000);
	ml.hide();

	if (fixedWidth) {
		ml.setWidth(fixedWidth);
	}

	var instance = {
		/**
		* <p><b>Only available on the instance returned from {@link #createInstance}, <u>not</u> on the singleton.</b></p>
		* Returns the size of the specified text based on the internal element's style and width properties
		* @param {String} text The text to measure
		* @return {Object} An object containing the text's size {width: (width), height: (height)}
		*/
		getSize: function (text) {
			ml.update(text);
			var s = ml.getSize();
			ml.update('');
			return s;
		},

		/**
		* <p><b>Only available on the instance returned from {@link #createInstance}, <u>not</u> on the singleton.</b></p>
		* Binds this TextMetrics instance to an element from which to copy existing CSS styles
		* that can affect the size of the rendered text
		* @param {String/HTMLElement} el The element, dom node or id
		*/
		bind: function (el) {
			ml.setStyle(
                Ext.fly(el).getStyles('font-size', 'font-style', 'font-weight', 'font-family', 'line-height', 'text-transform', 'letter-spacing')
            );
		},

		/**
		* <p><b>Only available on the instance returned from {@link #createInstance}, <u>not</u> on the singleton.</b></p>
		* Sets a fixed width on the internal measurement element.  If the text will be multiline, you have
		* to set a fixed width in order to accurately measure the text height.
		* @param {Number} width The width to set on the element
		*/
		setFixedWidth: function (width) {
			ml.setWidth(width);
		},

		/**
		* <p><b>Only available on the instance returned from {@link #createInstance}, <u>not</u> on the singleton.</b></p>
		* Returns the measured width of the specified text
		* @param {String} text The text to measure
		* @return {Number} width The width in pixels
		*/
		getWidth: function (text) {
			ml.dom.style.width = 'auto';
			return this.getSize(text).width;
		},

		/**
		* <p><b>Only available on the instance returned from {@link #createInstance}, <u>not</u> on the singleton.</b></p>
		* Returns the measured height of the specified text.  For multiline text, be sure to call
		* {@link #setFixedWidth} if necessary.
		* @param {String} text The text to measure
		* @return {Number} height The height in pixels
		*/
		getHeight: function (text) {
			return this.getSize(text).height;
		}
	};

	instance.bind(bindTo);

	return instance;
};

Ext.Element.addMethods({
	/**
	* Returns the width in pixels of the passed text, or the width of the text in this Element.
	* @param {String} text The text to measure. Defaults to the innerHTML of the element.
	* @param {Number} min (Optional) The minumum value to return.
	* @param {Number} max (Optional) The maximum value to return.
	* @return {Number} The text width in pixels.
	* @member Ext.Element getTextWidth
	*/
	getTextWidth: function (text, min, max) {
		return (Ext.util.TextMetrics.measure(this.dom, Ext.value(text, this.dom.innerHTML, true)).width).constrain(min || 0, max || 1000000);
	}
});
/**
* @class Ext.util.Cookies
* Utility class for managing and interacting with cookies.
* @singleton
*/
Ext.util.Cookies = {
	/**
	* Create a cookie with the specified name and value. Additional settings
	* for the cookie may be optionally specified (for example: expiration,
	* access restriction, SSL).
	* @param {String} name The name of the cookie to set. 
	* @param {Mixed} value The value to set for the cookie.
	* @param {Object} expires (Optional) Specify an expiration date the
	* cookie is to persist until.  Note that the specified Date object will
	* be converted to Greenwich Mean Time (GMT). 
	* @param {String} path (Optional) Setting a path on the cookie restricts
	* access to pages that match that path. Defaults to all pages (<tt>'/'</tt>). 
	* @param {String} domain (Optional) Setting a domain restricts access to
	* pages on a given domain (typically used to allow cookie access across
	* subdomains). For example, "extjs.com" will create a cookie that can be
	* accessed from any subdomain of extjs.com, including www.extjs.com,
	* support.extjs.com, etc.
	* @param {Boolean} secure (Optional) Specify true to indicate that the cookie
	* should only be accessible via SSL on a page using the HTTPS protocol.
	* Defaults to <tt>false</tt>. Note that this will only work if the page
	* calling this code uses the HTTPS protocol, otherwise the cookie will be
	* created with default options.
	*/
	set: function (name, value) {
		var argv = arguments;
		var argc = arguments.length;
		var expires = (argc > 2) ? argv[2] : null;
		var path = (argc > 3) ? argv[3] : '/';
		var domain = (argc > 4) ? argv[4] : null;
		var secure = (argc > 5) ? argv[5] : false;
		document.cookie = name + "=" + escape(value) + ((expires === null) ? "" : ("; expires=" + expires.toGMTString())) + ((path === null) ? "" : ("; path=" + path)) + ((domain === null) ? "" : ("; domain=" + domain)) + ((secure === true) ? "; secure" : "");
	},

	/**
	* Retrieves cookies that are accessible by the current page. If a cookie
	* does not exist, <code>get()</code> returns <tt>null</tt>.  The following
	* example retrieves the cookie called "valid" and stores the String value
	* in the variable <tt>validStatus</tt>.
	* <pre><code>
	* var validStatus = Ext.util.Cookies.get("valid");
	* </code></pre>
	* @param {String} name The name of the cookie to get
	* @return {Mixed} Returns the cookie value for the specified name;
	* null if the cookie name does not exist.
	*/
	get: function (name) {
		var arg = name + "=";
		var alen = arg.length;
		var clen = document.cookie.length;
		var i = 0;
		var j = 0;
		while (i < clen) {
			j = i + alen;
			if (document.cookie.substring(i, j) == arg) {
				return Ext.util.Cookies.getCookieVal(j);
			}
			i = document.cookie.indexOf(" ", i) + 1;
			if (i === 0) {
				break;
			}
		}
		return null;
	},

	/**
	* Removes a cookie with the provided name from the browser
	* if found by setting its expiration date to sometime in the past. 
	* @param {String} name The name of the cookie to remove
	*/
	clear: function (name) {
		if (Ext.util.Cookies.get(name)) {
			document.cookie = name + "=" + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
		}
	},
	/**
	* @private
	*/
	getCookieVal: function (offset) {
		var endstr = document.cookie.indexOf(";", offset);
		if (endstr == -1) {
			endstr = document.cookie.length;
		}
		return unescape(document.cookie.substring(offset, endstr));
	}
}; /**
 * Framework-wide error-handler.  Developers can override this method to provide
 * custom exception-handling.  Framework errors will often extend from the base
 * Ext.Error class.
 * @param {Object/Error} e The thrown exception object.
 */
Ext.handleError = function (e) {
	throw e;
};

/**
* @class Ext.Error
* @extends Error
* <p>A base error class. Future implementations are intended to provide more
* robust error handling throughout the framework (<b>in the debug build only</b>)
* to check for common errors and problems. The messages issued by this class
* will aid error checking. Error checks will be automatically removed in the
* production build so that performance is not negatively impacted.</p>
* <p>Some sample messages currently implemented:</p><pre>
"DataProxy attempted to execute an API-action but found an undefined
url / function. Please review your Proxy url/api-configuration."
* </pre><pre>
"Could not locate your "root" property in your server response.
Please review your JsonReader config to ensure the config-property
"root" matches the property your server-response.  See the JsonReader
docs for additional assistance."
* </pre>
* <p>An example of the code used for generating error messages:</p><pre><code>
try {
generateError({
foo: 'bar'
});
}
catch (e) {
console.error(e);
}
function generateError(data) {
throw new Ext.Error('foo-error', data);
}
* </code></pre>
* @param {String} message
*/
Ext.Error = function (message) {
	// Try to read the message from Ext.Error.lang
	this.message = (this.lang[message]) ? this.lang[message] : message;
};

Ext.Error.prototype = new Error();
Ext.apply(Ext.Error.prototype, {
	// protected.  Extensions place their error-strings here.
	lang: {},

	name: 'Ext.Error',
	/**
	* getName
	* @return {String}
	*/
	getName: function () {
		return this.name;
	},
	/**
	* getMessage
	* @return {String}
	*/
	getMessage: function () {
		return this.message;
	},
	/**
	* toJson
	* @return {String}
	*/
	toJson: function () {
		return Ext.encode(this);
	}
});
/**
* @class Ext.ComponentMgr
* <p>Provides a registry of all Components (instances of {@link Ext.Component} or any subclass
* thereof) on a page so that they can be easily accessed by {@link Ext.Component component}
* {@link Ext.Component#id id} (see {@link #get}, or the convenience method {@link Ext#getCmp Ext.getCmp}).</p>
* <p>This object also provides a registry of available Component <i>classes</i>
* indexed by a mnemonic code known as the Component's {@link Ext.Component#xtype xtype}.
* The <code>{@link Ext.Component#xtype xtype}</code> provides a way to avoid instantiating child Components
* when creating a full, nested config object for a complete Ext page.</p>
* <p>A child Component may be specified simply as a <i>config object</i>
* as long as the correct <code>{@link Ext.Component#xtype xtype}</code> is specified so that if and when the Component
* needs rendering, the correct type can be looked up for lazy instantiation.</p>
* <p>For a list of all available <code>{@link Ext.Component#xtype xtypes}</code>, see {@link Ext.Component}.</p>
* @singleton
*/
Ext.ComponentMgr = function () {
	var all = new Ext.util.MixedCollection();
	var types = {};
	var ptypes = {};

	return {
		/**
		* Registers a component.
		* @param {Ext.Component} c The component
		*/
		register: function (c) {
			all.add(c);
		},

		/**
		* Unregisters a component.
		* @param {Ext.Component} c The component
		*/
		unregister: function (c) {
			all.remove(c);
		},

		/**
		* Returns a component by {@link Ext.Component#id id}.
		* For additional details see {@link Ext.util.MixedCollection#get}.
		* @param {String} id The component {@link Ext.Component#id id}
		* @return Ext.Component The Component, <code>undefined</code> if not found, or <code>null</code> if a
		* Class was found.
		*/
		get: function (id) {
			return all.get(id);
		},

		/**
		* Registers a function that will be called when a Component with the specified id is added to ComponentMgr. This will happen on instantiation.
		* @param {String} id The component {@link Ext.Component#id id}
		* @param {Function} fn The callback function
		* @param {Object} scope The scope (<code>this</code> reference) in which the callback is executed. Defaults to the Component.
		*/
		onAvailable: function (id, fn, scope) {
			all.on("add", function (index, o) {
				if (o.id == id) {
					fn.call(scope || o, o);
					all.un("add", fn, scope);
				}
			});
		},

		/**
		* The MixedCollection used internally for the component cache. An example usage may be subscribing to
		* events on the MixedCollection to monitor addition or removal.  Read-only.
		* @type {MixedCollection}
		*/
		all: all,

		/**
		* The xtypes that have been registered with the component manager.
		* @type {Object}
		*/
		types: types,

		/**
		* The ptypes that have been registered with the component manager.
		* @type {Object}
		*/
		ptypes: ptypes,

		/**
		* Checks if a Component type is registered.
		* @param {Ext.Component} xtype The mnemonic string by which the Component class may be looked up
		* @return {Boolean} Whether the type is registered.
		*/
		isRegistered: function (xtype) {
			return types[xtype] !== undefined;
		},

		/**
		* Checks if a Plugin type is registered.
		* @param {Ext.Component} ptype The mnemonic string by which the Plugin class may be looked up
		* @return {Boolean} Whether the type is registered.
		*/
		isPluginRegistered: function (ptype) {
			return ptypes[ptype] !== undefined;
		},

		/**
		* <p>Registers a new Component constructor, keyed by a new
		* {@link Ext.Component#xtype}.</p>
		* <p>Use this method (or its alias {@link Ext#reg Ext.reg}) to register new
		* subclasses of {@link Ext.Component} so that lazy instantiation may be used when specifying
		* child Components.
		* see {@link Ext.Container#items}</p>
		* @param {String} xtype The mnemonic string by which the Component class may be looked up.
		* @param {Constructor} cls The new Component class.
		*/
		registerType: function (xtype, cls) {
			types[xtype] = cls;
			cls.xtype = xtype;
		},

		/**
		* Creates a new Component from the specified config object using the
		* config object's {@link Ext.component#xtype xtype} to determine the class to instantiate.
		* @param {Object} config A configuration object for the Component you wish to create.
		* @param {Constructor} defaultType The constructor to provide the default Component type if
		* the config object does not contain a <code>xtype</code>. (Optional if the config contains a <code>xtype</code>).
		* @return {Ext.Component} The newly instantiated Component.
		*/
		create: function (config, defaultType) {
			return config.render ? config : new types[config.xtype || defaultType](config);
		},

		/**
		* <p>Registers a new Plugin constructor, keyed by a new
		* {@link Ext.Component#ptype}.</p>
		* <p>Use this method (or its alias {@link Ext#preg Ext.preg}) to register new
		* plugins for {@link Ext.Component}s so that lazy instantiation may be used when specifying
		* Plugins.</p>
		* @param {String} ptype The mnemonic string by which the Plugin class may be looked up.
		* @param {Constructor} cls The new Plugin class.
		*/
		registerPlugin: function (ptype, cls) {
			ptypes[ptype] = cls;
			cls.ptype = ptype;
		},

		/**
		* Creates a new Plugin from the specified config object using the
		* config object's {@link Ext.component#ptype ptype} to determine the class to instantiate.
		* @param {Object} config A configuration object for the Plugin you wish to create.
		* @param {Constructor} defaultType The constructor to provide the default Plugin type if
		* the config object does not contain a <code>ptype</code>. (Optional if the config contains a <code>ptype</code>).
		* @return {Ext.Component} The newly instantiated Plugin.
		*/
		createPlugin: function (config, defaultType) {
			var PluginCls = ptypes[config.ptype || defaultType];
			if (PluginCls.init) {
				return PluginCls;
			} else {
				return new PluginCls(config);
			}
		}
	};
} ();

/**
* Shorthand for {@link Ext.ComponentMgr#registerType}
* @param {String} xtype The {@link Ext.component#xtype mnemonic string} by which the Component class
* may be looked up.
* @param {Constructor} cls The new Component class.
* @member Ext
* @method reg
*/
Ext.reg = Ext.ComponentMgr.registerType; // this will be called a lot internally, shorthand to keep the bytes down
/**
* Shorthand for {@link Ext.ComponentMgr#registerPlugin}
* @param {String} ptype The {@link Ext.component#ptype mnemonic string} by which the Plugin class
* may be looked up.
* @param {Constructor} cls The new Plugin class.
* @member Ext
* @method preg
*/
Ext.preg = Ext.ComponentMgr.registerPlugin;
/**
* Shorthand for {@link Ext.ComponentMgr#create}
* Creates a new Component from the specified config object using the
* config object's {@link Ext.component#xtype xtype} to determine the class to instantiate.
* @param {Object} config A configuration object for the Component you wish to create.
* @param {Constructor} defaultType The constructor to provide the default Component type if
* the config object does not contain a <code>xtype</code>. (Optional if the config contains a <code>xtype</code>).
* @return {Ext.Component} The newly instantiated Component.
* @member Ext
* @method create
*/
Ext.create = Ext.ComponentMgr.create; /**
 * @class Ext.Component
 * @extends Ext.util.Observable
 * <p>Base class for all Ext components.  All subclasses of Component may participate in the automated
 * Ext component lifecycle of creation, rendering and destruction which is provided by the {@link Ext.Container Container} class.
 * Components may be added to a Container through the {@link Ext.Container#items items} config option at the time the Container is created,
 * or they may be added dynamically via the {@link Ext.Container#add add} method.</p>
 * <p>The Component base class has built-in support for basic hide/show and enable/disable behavior.</p>
 * <p>All Components are registered with the {@link Ext.ComponentMgr} on construction so that they can be referenced at any time via
 * {@link Ext#getCmp}, passing the {@link #id}.</p>
 * <p>All user-developed visual widgets that are required to participate in automated lifecycle and size management should subclass Component (or
 * {@link Ext.BoxComponent} if managed box model handling is required, ie height and width management).</p>
 * <p>See the <a href="http://extjs.com/learn/Tutorial:Creating_new_UI_controls">Creating new UI controls</a> tutorial for details on how
 * and to either extend or augment ExtJs base classes to create custom Components.</p>
 * <p>Every component has a specific xtype, which is its Ext-specific type name, along with methods for checking the
 * xtype like {@link #getXType} and {@link #isXType}. This is the list of all valid xtypes:</p>
 * <pre>
xtype            Class
-------------    ------------------
box              {@link Ext.BoxComponent}
button           {@link Ext.Button}
buttongroup      {@link Ext.ButtonGroup}
colorpalette     {@link Ext.ColorPalette}
component        {@link Ext.Component}
container        {@link Ext.Container}
cycle            {@link Ext.CycleButton}
dataview         {@link Ext.DataView}
datepicker       {@link Ext.DatePicker}
editor           {@link Ext.Editor}
editorgrid       {@link Ext.grid.EditorGridPanel}
flash            {@link Ext.FlashComponent}
grid             {@link Ext.grid.GridPanel}
listview         {@link Ext.ListView}
panel            {@link Ext.Panel}
progress         {@link Ext.ProgressBar}
propertygrid     {@link Ext.grid.PropertyGrid}
slider           {@link Ext.Slider}
spacer           {@link Ext.Spacer}
splitbutton      {@link Ext.SplitButton}
tabpanel         {@link Ext.TabPanel}
treepanel        {@link Ext.tree.TreePanel}
viewport         {@link Ext.ViewPort}
window           {@link Ext.Window}

Toolbar components
---------------------------------------
paging           {@link Ext.PagingToolbar}
toolbar          {@link Ext.Toolbar}
tbbutton         {@link Ext.Toolbar.Button}        (deprecated; use button)
tbfill           {@link Ext.Toolbar.Fill}
tbitem           {@link Ext.Toolbar.Item}
tbseparator      {@link Ext.Toolbar.Separator}
tbspacer         {@link Ext.Toolbar.Spacer}
tbsplit          {@link Ext.Toolbar.SplitButton}   (deprecated; use splitbutton)
tbtext           {@link Ext.Toolbar.TextItem}

Menu components
---------------------------------------
menu             {@link Ext.menu.Menu}
colormenu        {@link Ext.menu.ColorMenu}
datemenu         {@link Ext.menu.DateMenu}
menubaseitem     {@link Ext.menu.BaseItem}
menucheckitem    {@link Ext.menu.CheckItem}
menuitem         {@link Ext.menu.Item}
menuseparator    {@link Ext.menu.Separator}
menutextitem     {@link Ext.menu.TextItem}

Form components
---------------------------------------
form             {@link Ext.form.FormPanel}
checkbox         {@link Ext.form.Checkbox}
checkboxgroup    {@link Ext.form.CheckboxGroup}
combo            {@link Ext.form.ComboBox}
datefield        {@link Ext.form.DateField}
displayfield     {@link Ext.form.DisplayField}
field            {@link Ext.form.Field}
fieldset         {@link Ext.form.FieldSet}
hidden           {@link Ext.form.Hidden}
htmleditor       {@link Ext.form.HtmlEditor}
label            {@link Ext.form.Label}
numberfield      {@link Ext.form.NumberField}
radio            {@link Ext.form.Radio}
radiogroup       {@link Ext.form.RadioGroup}
textarea         {@link Ext.form.TextArea}
textfield        {@link Ext.form.TextField}
timefield        {@link Ext.form.TimeField}
trigger          {@link Ext.form.TriggerField}

Chart components
---------------------------------------
chart            {@link Ext.chart.Chart}
barchart         {@link Ext.chart.BarChart}
cartesianchart   {@link Ext.chart.CartesianChart}
columnchart      {@link Ext.chart.ColumnChart}
linechart        {@link Ext.chart.LineChart}
piechart         {@link Ext.chart.PieChart}

Store xtypes
---------------------------------------
arraystore       {@link Ext.data.ArrayStore}
directstore      {@link Ext.data.DirectStore}
groupingstore    {@link Ext.data.GroupingStore}
jsonstore        {@link Ext.data.JsonStore}
simplestore      {@link Ext.data.SimpleStore}      (deprecated; use arraystore)
store            {@link Ext.data.Store}
xmlstore         {@link Ext.data.XmlStore}
</pre>
 * @constructor
 * @param {Ext.Element/String/Object} config The configuration options may be specified as either:
 * <div class="mdetail-params"><ul>
 * <li><b>an element</b> :
 * <p class="sub-desc">it is set as the internal element and its id used as the component id</p></li>
 * <li><b>a string</b> :
 * <p class="sub-desc">it is assumed to be the id of an existing element and is used as the component id</p></li>
 * <li><b>anything else</b> :
 * <p class="sub-desc">it is assumed to be a standard config object and is applied to the component</p></li>
 * </ul></div>
 */
Ext.Component = function (config) {
	config = config || {};
	if (config.initialConfig) {
		if (config.isAction) {           // actions
			this.baseAction = config;
		}
		config = config.initialConfig; // component cloning / action set up
	} else if (config.tagName || config.dom || Ext.isString(config)) { // element object
		config = { applyTo: config, id: config.id || config };
	}

	/**
	* This Component's initial configuration specification. Read-only.
	* @type Object
	* @property initialConfig
	*/
	this.initialConfig = config;

	Ext.apply(this, config);
	this.addEvents(
	/**
	* @event added
	* Fires when a component is added to an Ext.Container
	* @param {Ext.Component} this
	* @param {Ext.Container} ownerCt Container which holds the component
	* @param {number} index Position at which the component was added
	*/
        'added',
	/**
	* @event disable
	* Fires after the component is disabled.
	* @param {Ext.Component} this
	*/
        'disable',
	/**
	* @event enable
	* Fires after the component is enabled.
	* @param {Ext.Component} this
	*/
        'enable',
	/**
	* @event beforeshow
	* Fires before the component is shown by calling the {@link #show} method.
	* Return false from an event handler to stop the show.
	* @param {Ext.Component} this
	*/
        'beforeshow',
	/**
	* @event show
	* Fires after the component is shown when calling the {@link #show} method.
	* @param {Ext.Component} this
	*/
        'show',
	/**
	* @event beforehide
	* Fires before the component is hidden by calling the {@link #hide} method.
	* Return false from an event handler to stop the hide.
	* @param {Ext.Component} this
	*/
        'beforehide',
	/**
	* @event hide
	* Fires after the component is hidden.
	* Fires after the component is hidden when calling the {@link #hide} method.
	* @param {Ext.Component} this
	*/
        'hide',
	/**
	* @event removed
	* Fires when a component is removed from an Ext.Container
	* @param {Ext.Component} this
	* @param {Ext.Container} ownerCt Container which holds the component
	*/
        'removed',
	/**
	* @event beforerender
	* Fires before the component is {@link #rendered}. Return false from an
	* event handler to stop the {@link #render}.
	* @param {Ext.Component} this
	*/
        'beforerender',
	/**
	* @event render
	* Fires after the component markup is {@link #rendered}.
	* @param {Ext.Component} this
	*/
        'render',
	/**
	* @event afterrender
	* <p>Fires after the component rendering is finished.</p>
	* <p>The afterrender event is fired after this Component has been {@link #rendered}, been postprocesed
	* by any afterRender method defined for the Component, and, if {@link #stateful}, after state
	* has been restored.</p>
	* @param {Ext.Component} this
	*/
        'afterrender',
	/**
	* @event beforedestroy
	* Fires before the component is {@link #destroy}ed. Return false from an event handler to stop the {@link #destroy}.
	* @param {Ext.Component} this
	*/
        'beforedestroy',
	/**
	* @event destroy
	* Fires after the component is {@link #destroy}ed.
	* @param {Ext.Component} this
	*/
        'destroy',
	/**
	* @event beforestaterestore
	* Fires before the state of the component is restored. Return false from an event handler to stop the restore.
	* @param {Ext.Component} this
	* @param {Object} state The hash of state values returned from the StateProvider. If this
	* event is not vetoed, then the state object is passed to <b><tt>applyState</tt></b>. By default,
	* that simply copies property values into this Component. The method maybe overriden to
	* provide custom state restoration.
	*/
        'beforestaterestore',
	/**
	* @event staterestore
	* Fires after the state of the component is restored.
	* @param {Ext.Component} this
	* @param {Object} state The hash of state values returned from the StateProvider. This is passed
	* to <b><tt>applyState</tt></b>. By default, that simply copies property values into this
	* Component. The method maybe overriden to provide custom state restoration.
	*/
        'staterestore',
	/**
	* @event beforestatesave
	* Fires before the state of the component is saved to the configured state provider. Return false to stop the save.
	* @param {Ext.Component} this
	* @param {Object} state The hash of state values. This is determined by calling
	* <b><tt>getState()</tt></b> on the Component. This method must be provided by the
	* developer to return whetever representation of state is required, by default, Ext.Component
	* has a null implementation.
	*/
        'beforestatesave',
	/**
	* @event statesave
	* Fires after the state of the component is saved to the configured state provider.
	* @param {Ext.Component} this
	* @param {Object} state The hash of state values. This is determined by calling
	* <b><tt>getState()</tt></b> on the Component. This method must be provided by the
	* developer to return whetever representation of state is required, by default, Ext.Component
	* has a null implementation.
	*/
        'statesave'
    );
	this.getId();
	Ext.ComponentMgr.register(this);
	Ext.Component.superclass.constructor.call(this);

	if (this.baseAction) {
		this.baseAction.addComponent(this);
	}

	this.initComponent();

	if (this.plugins) {
		if (Ext.isArray(this.plugins)) {
			for (var i = 0, len = this.plugins.length; i < len; i++) {
				this.plugins[i] = this.initPlugin(this.plugins[i]);
			}
		} else {
			this.plugins = this.initPlugin(this.plugins);
		}
	}

	if (this.stateful !== false) {
		this.initState();
	}

	if (this.applyTo) {
		this.applyToMarkup(this.applyTo);
		delete this.applyTo;
	} else if (this.renderTo) {
		this.render(this.renderTo);
		delete this.renderTo;
	}
};

// private
Ext.Component.AUTO_ID = 1000;

Ext.extend(Ext.Component, Ext.util.Observable, {
	// Configs below are used for all Components when rendered by FormLayout.
	/**
	* @cfg {String} fieldLabel <p>The label text to display next to this Component (defaults to '').</p>
	* <br><p><b>Note</b>: this config is only used when this Component is rendered by a Container which
	* has been configured to use the <b>{@link Ext.layout.FormLayout FormLayout}</b> layout manager (e.g.
	* {@link Ext.form.FormPanel} or specifying <tt>layout:'form'</tt>).</p><br>
	* <p>Also see <tt>{@link #hideLabel}</tt> and
	* {@link Ext.layout.FormLayout}.{@link Ext.layout.FormLayout#fieldTpl fieldTpl}.</p>
	* Example use:<pre><code>
	new Ext.FormPanel({
	height: 100,
	renderTo: Ext.getBody(),
	items: [{
	xtype: 'textfield',
	fieldLabel: 'Name'
	}]
	});
	</code></pre>
	*/
	/**
	* @cfg {String} labelStyle <p>A CSS style specification string to apply directly to this field's
	* label.  Defaults to the container's labelStyle value if set (e.g.,
	* <tt>{@link Ext.layout.FormLayout#labelStyle}</tt> , or '').</p>
	* <br><p><b>Note</b>: see the note for <code>{@link #clearCls}</code>.</p><br>
	* <p>Also see <code>{@link #hideLabel}</code> and
	* <code>{@link Ext.layout.FormLayout}.{@link Ext.layout.FormLayout#fieldTpl fieldTpl}.</code></p>
	* Example use:<pre><code>
	new Ext.FormPanel({
	height: 100,
	renderTo: Ext.getBody(),
	items: [{
	xtype: 'textfield',
	fieldLabel: 'Name',
	labelStyle: 'font-weight:bold;'
	}]
	});
	</code></pre>
	*/
	/**
	* @cfg {String} labelSeparator <p>The separator to display after the text of each
	* <tt>{@link #fieldLabel}</tt>.  This property may be configured at various levels.
	* The order of precedence is:
	* <div class="mdetail-params"><ul>
	* <li>field / component level</li>
	* <li>container level</li>
	* <li>{@link Ext.layout.FormLayout#labelSeparator layout level} (defaults to colon <tt>':'</tt>)</li>
	* </ul></div>
	* To display no separator for this field's label specify empty string ''.</p>
	* <br><p><b>Note</b>: see the note for <tt>{@link #clearCls}</tt>.</p><br>
	* <p>Also see <tt>{@link #hideLabel}</tt> and
	* {@link Ext.layout.FormLayout}.{@link Ext.layout.FormLayout#fieldTpl fieldTpl}.</p>
	* Example use:<pre><code>
	new Ext.FormPanel({
	height: 100,
	renderTo: Ext.getBody(),
	layoutConfig: {
	labelSeparator: '~'   // layout config has lowest priority (defaults to ':')
	},
	{@link Ext.layout.FormLayout#labelSeparator labelSeparator}: '>>',     // config at container level
	items: [{
	xtype: 'textfield',
	fieldLabel: 'Field 1',
	labelSeparator: '...' // field/component level config supersedes others
	},{
	xtype: 'textfield',
	fieldLabel: 'Field 2' // labelSeparator will be '='
	}]
	});
	</code></pre>
	*/
	/**
	* @cfg {Boolean} hideLabel <p><tt>true</tt> to completely hide the label element
	* ({@link #fieldLabel label} and {@link #labelSeparator separator}). Defaults to <tt>false</tt>.
	* By default, even if you do not specify a <tt>{@link #fieldLabel}</tt> the space will still be
	* reserved so that the field will line up with other fields that do have labels.
	* Setting this to <tt>true</tt> will cause the field to not reserve that space.</p>
	* <br><p><b>Note</b>: see the note for <tt>{@link #clearCls}</tt>.</p><br>
	* Example use:<pre><code>
	new Ext.FormPanel({
	height: 100,
	renderTo: Ext.getBody(),
	items: [{
	xtype: 'textfield'
	hideLabel: true
	}]
	});
	</code></pre>
	*/
	/**
	* @cfg {String} clearCls <p>The CSS class used to to apply to the special clearing div rendered
	* directly after each form field wrapper to provide field clearing (defaults to
	* <tt>'x-form-clear-left'</tt>).</p>
	* <br><p><b>Note</b>: this config is only used when this Component is rendered by a Container
	* which has been configured to use the <b>{@link Ext.layout.FormLayout FormLayout}</b> layout
	* manager (e.g. {@link Ext.form.FormPanel} or specifying <tt>layout:'form'</tt>) and either a
	* <tt>{@link #fieldLabel}</tt> is specified or <tt>isFormField=true</tt> is specified.</p><br>
	* <p>See {@link Ext.layout.FormLayout}.{@link Ext.layout.FormLayout#fieldTpl fieldTpl} also.</p>
	*/
	/**
	* @cfg {String} itemCls
	* <p><b>Note</b>: this config is only used when this Component is rendered by a Container which
	* has been configured to use the <b>{@link Ext.layout.FormLayout FormLayout}</b> layout manager (e.g.
	* {@link Ext.form.FormPanel} or specifying <tt>layout:'form'</tt>).</p><br>
	* <p>An additional CSS class to apply to the div wrapping the form item
	* element of this field.  If supplied, <tt>itemCls</tt> at the <b>field</b> level will override
	* the default <tt>itemCls</tt> supplied at the <b>container</b> level. The value specified for
	* <tt>itemCls</tt> will be added to the default class (<tt>'x-form-item'</tt>).</p>
	* <p>Since it is applied to the item wrapper (see
	* {@link Ext.layout.FormLayout}.{@link Ext.layout.FormLayout#fieldTpl fieldTpl}), it allows
	* you to write standard CSS rules that can apply to the field, the label (if specified), or
	* any other element within the markup for the field.</p>
	* <br><p><b>Note</b>: see the note for <tt>{@link #fieldLabel}</tt>.</p><br>
	* Example use:<pre><code>
	// Apply a style to the field&#39;s label:
	&lt;style>
	.required .x-form-item-label {font-weight:bold;color:red;}
	&lt;/style>

	new Ext.FormPanel({
	height: 100,
	renderTo: Ext.getBody(),
	items: [{
	xtype: 'textfield',
	fieldLabel: 'Name',
	itemCls: 'required' //this label will be styled
	},{
	xtype: 'textfield',
	fieldLabel: 'Favorite Color'
	}]
	});
	</code></pre>
	*/

	/**
	* @cfg {String} id
	* <p>The <b>unique</b> id of this component (defaults to an {@link #getId auto-assigned id}).
	* You should assign an id if you need to be able to access the component later and you do
	* not have an object reference available (e.g., using {@link Ext}.{@link Ext#getCmp getCmp}).</p>
	* <p>Note that this id will also be used as the element id for the containing HTML element
	* that is rendered to the page for this component. This allows you to write id-based CSS
	* rules to style the specific instance of this component uniquely, and also to select
	* sub-elements using this component's id as the parent.</p>
	* <p><b>Note</b>: to avoid complications imposed by a unique <tt>id</tt> also see
	* <code>{@link #itemId}</code> and <code>{@link #ref}</code>.</p>
	* <p><b>Note</b>: to access the container of an item see <code>{@link #ownerCt}</code>.</p>
	*/
	/**
	* @cfg {String} itemId
	* <p>An <tt>itemId</tt> can be used as an alternative way to get a reference to a component
	* when no object reference is available.  Instead of using an <code>{@link #id}</code> with
	* {@link Ext}.{@link Ext#getCmp getCmp}, use <code>itemId</code> with
	* {@link Ext.Container}.{@link Ext.Container#getComponent getComponent} which will retrieve
	* <code>itemId</code>'s or <tt>{@link #id}</tt>'s. Since <code>itemId</code>'s are an index to the
	* container's internal MixedCollection, the <code>itemId</code> is scoped locally to the container --
	* avoiding potential conflicts with {@link Ext.ComponentMgr} which requires a <b>unique</b>
	* <code>{@link #id}</code>.</p>
	* <pre><code>
	var c = new Ext.Panel({ //
	{@link Ext.BoxComponent#height height}: 300,
	{@link #renderTo}: document.body,
	{@link Ext.Container#layout layout}: 'auto',
	{@link Ext.Container#items items}: [
	{
	itemId: 'p1',
	{@link Ext.Panel#title title}: 'Panel 1',
	{@link Ext.BoxComponent#height height}: 150
	},
	{
	itemId: 'p2',
	{@link Ext.Panel#title title}: 'Panel 2',
	{@link Ext.BoxComponent#height height}: 150
	}
	]
	})
	p1 = c.{@link Ext.Container#getComponent getComponent}('p1'); // not the same as {@link Ext#getCmp Ext.getCmp()}
	p2 = p1.{@link #ownerCt}.{@link Ext.Container#getComponent getComponent}('p2'); // reference via a sibling
	* </code></pre>
	* <p>Also see <tt>{@link #id}</tt> and <code>{@link #ref}</code>.</p>
	* <p><b>Note</b>: to access the container of an item see <tt>{@link #ownerCt}</tt>.</p>
	*/
	/**
	* @cfg {String} xtype
	* The registered <tt>xtype</tt> to create. This config option is not used when passing
	* a config object into a constructor. This config option is used only when
	* lazy instantiation is being used, and a child item of a Container is being
	* specified not as a fully instantiated Component, but as a <i>Component config
	* object</i>. The <tt>xtype</tt> will be looked up at render time up to determine what
	* type of child Component to create.<br><br>
	* The predefined xtypes are listed {@link Ext.Component here}.
	* <br><br>
	* If you subclass Components to create your own Components, you may register
	* them using {@link Ext.ComponentMgr#registerType} in order to be able to
	* take advantage of lazy instantiation and rendering.
	*/
	/**
	* @cfg {String} ptype
	* The registered <tt>ptype</tt> to create. This config option is not used when passing
	* a config object into a constructor. This config option is used only when
	* lazy instantiation is being used, and a Plugin is being
	* specified not as a fully instantiated Component, but as a <i>Component config
	* object</i>. The <tt>ptype</tt> will be looked up at render time up to determine what
	* type of Plugin to create.<br><br>
	* If you create your own Plugins, you may register them using
	* {@link Ext.ComponentMgr#registerPlugin} in order to be able to
	* take advantage of lazy instantiation and rendering.
	*/
	/**
	* @cfg {String} cls
	* An optional extra CSS class that will be added to this component's Element (defaults to '').  This can be
	* useful for adding customized styles to the component or any of its children using standard CSS rules.
	*/
	/**
	* @cfg {String} overCls
	* An optional extra CSS class that will be added to this component's Element when the mouse moves
	* over the Element, and removed when the mouse moves out. (defaults to '').  This can be
	* useful for adding customized 'active' or 'hover' styles to the component or any of its children using standard CSS rules.
	*/
	/**
	* @cfg {String} style
	* A custom style specification to be applied to this component's Element.  Should be a valid argument to
	* {@link Ext.Element#applyStyles}.
	* <pre><code>
	new Ext.Panel({
	title: 'Some Title',
	renderTo: Ext.getBody(),
	width: 400, height: 300,
	layout: 'form',
	items: [{
	xtype: 'textarea',
	style: {
	width: '95%',
	marginBottom: '10px'
	}
	},
	new Ext.Button({
	text: 'Send',
	minWidth: '100',
	style: {
	marginBottom: '10px'
	}
	})
	]
	});
	* </code></pre>
	*/
	/**
	* @cfg {String} ctCls
	* <p>An optional extra CSS class that will be added to this component's container. This can be useful for
	* adding customized styles to the container or any of its children using standard CSS rules.  See
	* {@link Ext.layout.ContainerLayout}.{@link Ext.layout.ContainerLayout#extraCls extraCls} also.</p>
	* <p><b>Note</b>: <tt>ctCls</tt> defaults to <tt>''</tt> except for the following class
	* which assigns a value by default:
	* <div class="mdetail-params"><ul>
	* <li>{@link Ext.layout.Box Box Layout} : <tt>'x-box-layout-ct'</tt></li>
	* </ul></div>
	* To configure the above Class with an extra CSS class append to the default.  For example,
	* for BoxLayout (Hbox and Vbox):<pre><code>
	* ctCls: 'x-box-layout-ct custom-class'
	* </code></pre>
	* </p>
	*/
	/**
	* @cfg {Boolean} disabled
	* Render this component disabled (default is false).
	*/
	disabled: false,
	/**
	* @cfg {Boolean} hidden
	* Render this component hidden (default is false). If <tt>true</tt>, the
	* {@link #hide} method will be called internally.
	*/
	hidden: false,
	/**
	* @cfg {Object/Array} plugins
	* An object or array of objects that will provide custom functionality for this component.  The only
	* requirement for a valid plugin is that it contain an init method that accepts a reference of type Ext.Component.
	* When a component is created, if any plugins are available, the component will call the init method on each
	* plugin, passing a reference to itself.  Each plugin can then call methods or respond to events on the
	* component as needed to provide its functionality.
	*/
	/**
	* @cfg {Mixed} applyTo
	* <p>Specify the id of the element, a DOM element or an existing Element corresponding to a DIV
	* that is already present in the document that specifies some structural markup for this
	* component.</p><div><ul>
	* <li><b>Description</b> : <ul>
	* <div class="sub-desc">When <tt>applyTo</tt> is used, constituent parts of the component can also be specified
	* by id or CSS class name within the main element, and the component being created may attempt
	* to create its subcomponents from that markup if applicable.</div>
	* </ul></li>
	* <li><b>Notes</b> : <ul>
	* <div class="sub-desc">When using this config, a call to render() is not required.</div>
	* <div class="sub-desc">If applyTo is specified, any value passed for {@link #renderTo} will be ignored and the target
	* element's parent node will automatically be used as the component's container.</div>
	* </ul></li>
	* </ul></div>
	*/
	/**
	* @cfg {Mixed} renderTo
	* <p>Specify the id of the element, a DOM element or an existing Element that this component
	* will be rendered into.</p><div><ul>
	* <li><b>Notes</b> : <ul>
	* <div class="sub-desc">Do <u>not</u> use this option if the Component is to be a child item of
	* a {@link Ext.Container Container}. It is the responsibility of the
	* {@link Ext.Container Container}'s {@link Ext.Container#layout layout manager}
	* to render and manage its child items.</div>
	* <div class="sub-desc">When using this config, a call to render() is not required.</div>
	* </ul></li>
	* </ul></div>
	* <p>See <tt>{@link #render}</tt> also.</p>
	*/
	/**
	* @cfg {Boolean} stateful
	* <p>A flag which causes the Component to attempt to restore the state of
	* internal properties from a saved state on startup. The component must have
	* either a <code>{@link #stateId}</code> or <code>{@link #id}</code> assigned
	* for state to be managed. Auto-generated ids are not guaranteed to be stable
	* across page loads and cannot be relied upon to save and restore the same
	* state for a component.<p>
	* <p>For state saving to work, the state manager's provider must have been
	* set to an implementation of {@link Ext.state.Provider} which overrides the
	* {@link Ext.state.Provider#set set} and {@link Ext.state.Provider#get get}
	* methods to save and recall name/value pairs. A built-in implementation,
	* {@link Ext.state.CookieProvider} is available.</p>
	* <p>To set the state provider for the current page:</p>
	* <pre><code>
	Ext.state.Manager.setProvider(new Ext.state.CookieProvider({
	expires: new Date(new Date().getTime()+(1000*60*60*24*7)), //7 days from now
	}));
	* </code></pre>
	* <p>A stateful Component attempts to save state when one of the events
	* listed in the <code>{@link #stateEvents}</code> configuration fires.</p>
	* <p>To save state, a stateful Component first serializes its state by
	* calling <b><code>getState</code></b>. By default, this function does
	* nothing. The developer must provide an implementation which returns an
	* object hash which represents the Component's restorable state.</p>
	* <p>The value yielded by getState is passed to {@link Ext.state.Manager#set}
	* which uses the configured {@link Ext.state.Provider} to save the object
	* keyed by the Component's <code>{@link stateId}</code>, or, if that is not
	* specified, its <code>{@link #id}</code>.</p>
	* <p>During construction, a stateful Component attempts to <i>restore</i>
	* its state by calling {@link Ext.state.Manager#get} passing the
	* <code>{@link #stateId}</code>, or, if that is not specified, the
	* <code>{@link #id}</code>.</p>
	* <p>The resulting object is passed to <b><code>applyState</code></b>.
	* The default implementation of <code>applyState</code> simply copies
	* properties into the object, but a developer may override this to support
	* more behaviour.</p>
	* <p>You can perform extra processing on state save and restore by attaching
	* handlers to the {@link #beforestaterestore}, {@link #staterestore},
	* {@link #beforestatesave} and {@link #statesave} events.</p>
	*/
	/**
	* @cfg {String} stateId
	* The unique id for this component to use for state management purposes
	* (defaults to the component id if one was set, otherwise null if the
	* component is using a generated id).
	* <p>See <code>{@link #stateful}</code> for an explanation of saving and
	* restoring Component state.</p>
	*/
	/**
	* @cfg {Array} stateEvents
	* <p>An array of events that, when fired, should trigger this component to
	* save its state (defaults to none). <code>stateEvents</code> may be any type
	* of event supported by this component, including browser or custom events
	* (e.g., <tt>['click', 'customerchange']</tt>).</p>
	* <p>See <code>{@link #stateful}</code> for an explanation of saving and
	* restoring Component state.</p>
	*/
	/**
	* @cfg {Mixed} autoEl
	* <p>A tag name or {@link Ext.DomHelper DomHelper} spec used to create the {@link #getEl Element} which will
	* encapsulate this Component.</p>
	* <p>You do not normally need to specify this. For the base classes {@link Ext.Component}, {@link Ext.BoxComponent},
	* and {@link Ext.Container}, this defaults to <b><tt>'div'</tt></b>. The more complex Ext classes use a more complex
	* DOM structure created by their own onRender methods.</p>
	* <p>This is intended to allow the developer to create application-specific utility Components encapsulated by
	* different DOM elements. Example usage:</p><pre><code>
	{
	xtype: 'box',
	autoEl: {
	tag: 'img',
	src: 'http://www.example.com/example.jpg'
	}
	}, {
	xtype: 'box',
	autoEl: {
	tag: 'blockquote',
	html: 'autoEl is cool!'
	}
	}, {
	xtype: 'container',
	autoEl: 'ul',
	cls: 'ux-unordered-list',
	items: {
	xtype: 'box',
	autoEl: 'li',
	html: 'First list item'
	}
	}
	</code></pre>
	*/
	autoEl: 'div',

	/**
	* @cfg {String} disabledClass
	* CSS class added to the component when it is disabled (defaults to 'x-item-disabled').
	*/
	disabledClass: 'x-item-disabled',
	/**
	* @cfg {Boolean} allowDomMove
	* Whether the component can move the Dom node when rendering (defaults to true).
	*/
	allowDomMove: true,
	/**
	* @cfg {Boolean} autoShow
	* True if the component should check for hidden classes (e.g. 'x-hidden' or 'x-hide-display') and remove
	* them on render (defaults to false).
	*/
	autoShow: false,
	/**
	* @cfg {String} hideMode
	* <p>How this component should be hidden. Supported values are <tt>'visibility'</tt>
	* (css visibility), <tt>'offsets'</tt> (negative offset position) and <tt>'display'</tt>
	* (css display).</p>
	* <br><p><b>Note</b>: the default of <tt>'display'</tt> is generally preferred
	* since items are automatically laid out when they are first shown (no sizing
	* is done while hidden).</p>
	*/
	hideMode: 'display',
	/**
	* @cfg {Boolean} hideParent
	* True to hide and show the component's container when hide/show is called on the component, false to hide
	* and show the component itself (defaults to false).  For example, this can be used as a shortcut for a hide
	* button on a window by setting hide:true on the button when adding it to its parent container.
	*/
	hideParent: false,
	/**
	* <p>The {@link Ext.Element} which encapsulates this Component. Read-only.</p>
	* <p>This will <i>usually</i> be a &lt;DIV> element created by the class's onRender method, but
	* that may be overridden using the <code>{@link #autoEl}</code> config.</p>
	* <br><p><b>Note</b>: this element will not be available until this Component has been rendered.</p><br>
	* <p>To add listeners for <b>DOM events</b> to this Component (as opposed to listeners
	* for this Component's own Observable events), see the {@link Ext.util.Observable#listeners listeners}
	* config for a suggestion, or use a render listener directly:</p><pre><code>
	new Ext.Panel({
	title: 'The Clickable Panel',
	listeners: {
	render: function(p) {
	// Append the Panel to the click handler&#39;s argument list.
	p.getEl().on('click', handlePanelClick.createDelegate(null, [p], true));
	},
	single: true  // Remove the listener after first invocation
	}
	});
	</code></pre>
	* <p>See also <tt>{@link #getEl getEl}</p>
	* @type Ext.Element
	* @property el
	*/
	/**
	* This Component's owner {@link Ext.Container Container} (defaults to undefined, and is set automatically when
	* this Component is added to a Container).  Read-only.
	* <p><b>Note</b>: to access items within the Container see <tt>{@link #itemId}</tt>.</p>
	* @type Ext.Container
	* @property ownerCt
	*/
	/**
	* True if this component is hidden. Read-only.
	* @type Boolean
	* @property hidden
	*/
	/**
	* True if this component is disabled. Read-only.
	* @type Boolean
	* @property disabled
	*/
	/**
	* True if this component has been rendered. Read-only.
	* @type Boolean
	* @property rendered
	*/
	rendered: false,

	/**
	* @cfg {String} contentEl
	* <p>Optional. Specify an existing HTML element, or the <code>id</code> of an existing HTML element to use as the content
	* for this component.</p>
	* <ul>
	* <li><b>Description</b> :
	* <div class="sub-desc">This config option is used to take an existing HTML element and place it in the layout element
	* 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>
	* <li><b>Notes</b> :
	* <div class="sub-desc">The specified HTML element is appended to the layout element of the component <i>after any configured
	* {@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>
	* <div class="sub-desc">The specified HTML element used will not participate in any <code><b>{@link Ext.Container#layout layout}</b></code>
	* scheme that the Component may use. It is just HTML. Layouts operate on child <code><b>{@link Ext.Container#items items}</b></code>.</div>
	* <div class="sub-desc">Add either the <code>x-hidden</code> or the <code>x-hide-display</code> CSS class to
	* prevent a brief flicker of the content before it is rendered to the panel.</div></li>
	* </ul>
	*/
	/**
	* @cfg {String/Object} html
	* An HTML fragment, or a {@link Ext.DomHelper DomHelper} specification to use as the layout element
	* content (defaults to ''). The HTML content is added after the component is rendered,
	* so the document will not contain this HTML at the time the {@link #render} event is fired.
	* This content is inserted into the body <i>before</i> any configured {@link #contentEl} is appended.
	*/

	/**
	* @cfg {Mixed} tpl
	* An <bold>{@link Ext.Template}</bold>, <bold>{@link Ext.XTemplate}</bold>
	* or an array of strings to form an Ext.XTemplate.
	* Used in conjunction with the <code>{@link #data}</code> and
	* <code>{@link #tplWriteMode}</code> configurations.
	*/

	/**
	* @cfg {String} tplWriteMode The Ext.(X)Template method to use when
	* updating the content area of the Component. Defaults to <tt>'overwrite'</tt>
	* (see <code>{@link Ext.XTemplate#overwrite}</code>).
	*/
	tplWriteMode: 'overwrite',

	/**
	* @cfg {Mixed} data
	* The initial set of data to apply to the <code>{@link #tpl}</code> to
	* update the content area of the Component.
	*/

	/**
	* @cfg {Array} bubbleEvents
	* <p>An array of events that, when fired, should be bubbled to any parent container.
	* See {@link Ext.util.Observable#enableBubble}.
	* Defaults to <tt>[]</tt>.
	*/
	bubbleEvents: [],


	// private
	ctype: 'Ext.Component',

	// private
	actionMode: 'el',

	// private
	getActionEl: function () {
		return this[this.actionMode];
	},

	initPlugin: function (p) {
		if (p.ptype && !Ext.isFunction(p.init)) {
			p = Ext.ComponentMgr.createPlugin(p);
		} else if (Ext.isString(p)) {
			p = Ext.ComponentMgr.createPlugin({
				ptype: p
			});
		}
		p.init(this);
		return p;
	},

	/* // protected
	* Function to be implemented by Component subclasses to be part of standard component initialization flow (it is empty by default).
	* <pre><code>
	// Traditional constructor:
	Ext.Foo = function(config){
	// call superclass constructor:
	Ext.Foo.superclass.constructor.call(this, config);

	this.addEvents({
	// add events
	});
	};
	Ext.extend(Ext.Foo, Ext.Bar, {
	// class body
	}

	// initComponent replaces the constructor:
	Ext.Foo = Ext.extend(Ext.Bar, {
	initComponent : function(){
	// call superclass initComponent
	Ext.Container.superclass.initComponent.call(this);

	this.addEvents({
	// add events
	});
	}
	}
	</code></pre>
	*/
	initComponent: function () {
		/*
		* this is double processing, however it allows people to be able to do
		* Ext.apply(this, {
		*     listeners: {
		*         //here
		*     }
		* });
		* MyClass.superclass.initComponent.call(this);
		*/
		if (this.listeners) {
			this.on(this.listeners);
			delete this.listeners;
		}
		this.enableBubble(this.bubbleEvents);
	},

	/**
	* <p>Render this Component into the passed HTML element.</p>
	* <p><b>If you are using a {@link Ext.Container Container} object to house this Component, then
	* do not use the render method.</b></p>
	* <p>A Container's child Components are rendered by that Container's
	* {@link Ext.Container#layout layout} manager when the Container is first rendered.</p>
	* <p>Certain layout managers allow dynamic addition of child components. Those that do
	* include {@link Ext.layout.CardLayout}, {@link Ext.layout.AnchorLayout},
	* {@link Ext.layout.FormLayout}, {@link Ext.layout.TableLayout}.</p>
	* <p>If the Container is already rendered when a new child Component is added, you may need to call
	* the Container's {@link Ext.Container#doLayout doLayout} to refresh the view which causes any
	* unrendered child Components to be rendered. This is required so that you can add multiple
	* child components if needed while only refreshing the layout once.</p>
	* <p>When creating complex UIs, it is important to remember that sizing and positioning
	* of child items is the responsibility of the Container's {@link Ext.Container#layout layout} manager.
	* If you expect child items to be sized in response to user interactions, you must
	* configure the Container with a layout manager which creates and manages the type of layout you
	* have in mind.</p>
	* <p><b>Omitting the Container's {@link Ext.Container#layout layout} config means that a basic
	* layout manager is used which does nothing but render child components sequentially into the
	* Container. No sizing or positioning will be performed in this situation.</b></p>
	* @param {Element/HTMLElement/String} container (optional) The element this Component should be
	* rendered into. If it is being created from existing markup, this should be omitted.
	* @param {String/Number} position (optional) The element ID or DOM node index within the container <b>before</b>
	* which this component will be inserted (defaults to appending to the end of the container)
	*/
	render: function (container, position) {
		if (!this.rendered && this.fireEvent('beforerender', this) !== false) {
			if (!container && this.el) {
				this.el = Ext.get(this.el);
				container = this.el.dom.parentNode;
				this.allowDomMove = false;
			}
			this.container = Ext.get(container);
			if (this.ctCls) {
				this.container.addClass(this.ctCls);
			}
			this.rendered = true;
			if (position !== undefined) {
				if (Ext.isNumber(position)) {
					position = this.container.dom.childNodes[position];
				} else {
					position = Ext.getDom(position);
				}
			}
			this.onRender(this.container, position || null);
			if (this.autoShow) {
				this.el.removeClass(['x-hidden', 'x-hide-' + this.hideMode]);
			}
			if (this.cls) {
				this.el.addClass(this.cls);
				delete this.cls;
			}
			if (this.style) {
				this.el.applyStyles(this.style);
				delete this.style;
			}
			if (this.overCls) {
				this.el.addClassOnOver(this.overCls);
			}
			this.fireEvent('render', this);


			// Populate content of the component with html, contentEl or
			// a tpl.
			var contentTarget = this.getContentTarget();
			if (this.html) {
				contentTarget.update(Ext.DomHelper.markup(this.html));
				delete this.html;
			}
			if (this.contentEl) {
				var ce = Ext.getDom(this.contentEl);
				Ext.fly(ce).removeClass(['x-hidden', 'x-hide-display']);
				contentTarget.appendChild(ce);
			}
			if (this.tpl) {
				if (!this.tpl.compile) {
					this.tpl = new Ext.XTemplate(this.tpl);
				}
				if (this.data) {
					this.tpl[this.tplWriteMode](contentTarget, this.data);
					delete this.data;
				}
			}
			this.afterRender(this.container);


			if (this.hidden) {
				// call this so we don't fire initial hide events.
				this.doHide();
			}
			if (this.disabled) {
				// pass silent so the event doesn't fire the first time.
				this.disable(true);
			}

			if (this.stateful !== false) {
				this.initStateEvents();
			}
			this.fireEvent('afterrender', this);
		}
		return this;
	},


	/**
	* Update the content area of a component.
	* @param {Mixed} htmlOrData
	* If this component has been configured with a template via the tpl config
	* then it will use this argument as data to populate the template.
	* If this component was not configured with a template, the components
	* content area will be updated via Ext.Element update
	* @param {Boolean} loadScripts
	* (optional) Only legitimate when using the html configuration. Defaults to false
	* @param {Function} callback
	* (optional) Only legitimate when using the html configuration. Callback to execute when scripts have finished loading
	*/
	update: function (htmlOrData, loadScripts, cb) {
		var contentTarget = this.getContentTarget();
		if (this.tpl && typeof htmlOrData !== "string") {
			this.tpl[this.tplWriteMode](contentTarget, htmlOrData || {});
		} else {
			var html = Ext.isObject(htmlOrData) ? Ext.DomHelper.markup(htmlOrData) : htmlOrData;
			contentTarget.update(html, loadScripts, cb);
		}
	},


	/**
	* @private
	* Method to manage awareness of when components are added to their
	* respective Container, firing an added event.
	* References are established at add time rather than at render time.
	* @param {Ext.Container} container Container which holds the component
	* @param {number} pos Position at which the component was added
	*/
	onAdded: function (container, pos) {
		this.ownerCt = container;
		this.initRef();
		this.fireEvent('added', this, container, pos);
	},

	/**
	* @private
	* Method to manage awareness of when components are removed from their
	* respective Container, firing an removed event. References are properly
	* cleaned up after removing a component from its owning container.
	*/
	onRemoved: function () {
		this.removeRef();
		this.fireEvent('removed', this, this.ownerCt);
		delete this.ownerCt;
	},

	/**
	* @private
	* Method to establish a reference to a component.
	*/
	initRef: function () {
		/**
		* @cfg {String} ref
		* <p>A path specification, relative to the Component's <code>{@link #ownerCt}</code>
		* specifying into which ancestor Container to place a named reference to this Component.</p>
		* <p>The ancestor axis can be traversed by using '/' characters in the path.
		* For example, to put a reference to a Toolbar Button into <i>the Panel which owns the Toolbar</i>:</p><pre><code>
		var myGrid = new Ext.grid.EditorGridPanel({
		title: 'My EditorGridPanel',
		store: myStore,
		colModel: myColModel,
		tbar: [{
		text: 'Save',
		handler: saveChanges,
		disabled: true,
		ref: '../saveButton'
		}],
		listeners: {
		afteredit: function() {
		//          The button reference is in the GridPanel
		myGrid.saveButton.enable();
		}
		}
		});
		</code></pre>
		* <p>In the code above, if the <code>ref</code> had been <code>'saveButton'</code>
		* the reference would have been placed into the Toolbar. Each '/' in the <code>ref</code>
		* moves up one level from the Component's <code>{@link #ownerCt}</code>.</p>
		* <p>Also see the <code>{@link #added}</code> and <code>{@link #removed}</code> events.</p>
		*/
		if (this.ref && !this.refOwner) {
			var levels = this.ref.split('/'),
                last = levels.length,
                i = 0,
                t = this;

			while (t && i < last) {
				t = t.ownerCt;
				++i;
			}
			if (t) {
				t[this.refName = levels[--i]] = this;
				/**
				* @type Ext.Container
				* @property refOwner
				* The ancestor Container into which the {@link #ref} reference was inserted if this Component
				* is a child of a Container, and has been configured with a <code>ref</code>.
				*/
				this.refOwner = t;
			}
		}
	},

	removeRef: function () {
		if (this.refOwner && this.refName) {
			delete this.refOwner[this.refName];
			delete this.refOwner;
		}
	},

	// private
	initState: function () {
		if (Ext.state.Manager) {
			var id = this.getStateId();
			if (id) {
				var state = Ext.state.Manager.get(id);
				if (state) {
					if (this.fireEvent('beforestaterestore', this, state) !== false) {
						this.applyState(Ext.apply({}, state));
						this.fireEvent('staterestore', this, state);
					}
				}
			}
		}
	},

	// private
	getStateId: function () {
		return this.stateId || ((/^(ext-comp-|ext-gen)/).test(String(this.id)) ? null : this.id);
	},

	// private
	initStateEvents: function () {
		if (this.stateEvents) {
			for (var i = 0, e; e = this.stateEvents[i]; i++) {
				this.on(e, this.saveState, this, { delay: 100 });
			}
		}
	},

	// private
	applyState: function (state) {
		if (state) {
			Ext.apply(this, state);
		}
	},

	// private
	getState: function () {
		return null;
	},

	// private
	saveState: function () {
		if (Ext.state.Manager && this.stateful !== false) {
			var id = this.getStateId();
			if (id) {
				var state = this.getState();
				if (this.fireEvent('beforestatesave', this, state) !== false) {
					Ext.state.Manager.set(id, state);
					this.fireEvent('statesave', this, state);
				}
			}
		}
	},

	/**
	* Apply this component to existing markup that is valid. With this function, no call to render() is required.
	* @param {String/HTMLElement} el
	*/
	applyToMarkup: function (el) {
		this.allowDomMove = false;
		this.el = Ext.get(el);
		this.render(this.el.dom.parentNode);
	},

	/**
	* Adds a CSS class to the component's underlying element.
	* @param {string} cls The CSS class name to add
	* @return {Ext.Component} this
	*/
	addClass: function (cls) {
		if (this.el) {
			this.el.addClass(cls);
		} else {
			this.cls = this.cls ? this.cls + ' ' + cls : cls;
		}
		return this;
	},

	/**
	* Removes a CSS class from the component's underlying element.
	* @param {string} cls The CSS class name to remove
	* @return {Ext.Component} this
	*/
	removeClass: function (cls) {
		if (this.el) {
			this.el.removeClass(cls);
		} else if (this.cls) {
			this.cls = this.cls.split(' ').remove(cls).join(' ');
		}
		return this;
	},

	// private
	// default function is not really useful
	onRender: function (ct, position) {
		if (!this.el && this.autoEl) {
			if (Ext.isString(this.autoEl)) {
				this.el = document.createElement(this.autoEl);
			} else {
				var div = document.createElement('div');
				Ext.DomHelper.overwrite(div, this.autoEl);
				this.el = div.firstChild;
			}
			if (!this.el.id) {
				this.el.id = this.getId();
			}
		}
		if (this.el) {
			this.el = Ext.get(this.el);
			if (this.allowDomMove !== false) {
				ct.dom.insertBefore(this.el.dom, position);
				if (div) {
					Ext.removeNode(div);
					div = null;
				}
			}
		}
	},

	// private
	getAutoCreate: function () {
		var cfg = Ext.isObject(this.autoCreate) ?
                      this.autoCreate : Ext.apply({}, this.defaultAutoCreate);
		if (this.id && !cfg.id) {
			cfg.id = this.id;
		}
		return cfg;
	},

	// private
	afterRender: Ext.emptyFn,

	/**
	* Destroys this component by purging any event listeners, removing the component's element from the DOM,
	* removing the component from its {@link Ext.Container} (if applicable) and unregistering it from
	* {@link Ext.ComponentMgr}.  Destruction is generally handled automatically by the framework and this method
	* should usually not need to be called directly.
	*
	*/
	destroy: function () {
		if (!this.isDestroyed) {
			if (this.fireEvent('beforedestroy', this) !== false) {
				this.destroying = true;
				this.beforeDestroy();
				if (this.ownerCt && this.ownerCt.remove) {
					this.ownerCt.remove(this, false);
				}
				if (this.rendered) {
					this.el.remove();
					if (this.actionMode == 'container' || this.removeMode == 'container') {
						this.container.remove();
					}
				}
				// Stop any buffered tasks
				if (this.focusTask && this.focusTask.cancel) {
					this.focusTask.cancel();
				}
				this.onDestroy();
				Ext.ComponentMgr.unregister(this);
				this.fireEvent('destroy', this);
				this.purgeListeners();
				this.destroying = false;
				this.isDestroyed = true;
			}
		}
	},

	deleteMembers: function () {
		var args = arguments;
		for (var i = 0, len = args.length; i < len; ++i) {
			delete this[args[i]];
		}
	},

	// private
	beforeDestroy: Ext.emptyFn,

	// private
	onDestroy: Ext.emptyFn,

	/**
	* <p>Returns the {@link Ext.Element} which encapsulates this Component.</p>
	* <p>This will <i>usually</i> be a &lt;DIV> element created by the class's onRender method, but
	* that may be overridden using the {@link #autoEl} config.</p>
	* <br><p><b>Note</b>: this element will not be available until this Component has been rendered.</p><br>
	* <p>To add listeners for <b>DOM events</b> to this Component (as opposed to listeners
	* for this Component's own Observable events), see the {@link #listeners} config for a suggestion,
	* or use a render listener directly:</p><pre><code>
	new Ext.Panel({
	title: 'The Clickable Panel',
	listeners: {
	render: function(p) {
	// Append the Panel to the click handler&#39;s argument list.
	p.getEl().on('click', handlePanelClick.createDelegate(null, [p], true));
	},
	single: true  // Remove the listener after first invocation
	}
	});
	</code></pre>
	* @return {Ext.Element} The Element which encapsulates this Component.
	*/
	getEl: function () {
		return this.el;
	},

	// private
	getContentTarget: function () {
		return this.el;
	},

	/**
	* Returns the <code>id</code> of this component or automatically generates and
	* returns an <code>id</code> if an <code>id</code> is not defined yet:<pre><code>
	* 'ext-comp-' + (++Ext.Component.AUTO_ID)
	* </code></pre>
	* @return {String} id
	*/
	getId: function () {
		return this.id || (this.id = 'ext-comp-' + (++Ext.Component.AUTO_ID));
	},

	/**
	* Returns the <code>{@link #itemId}</code> of this component.  If an
	* <code>{@link #itemId}</code> was not assigned through configuration the
	* <code>id</code> is returned using <code>{@link #getId}</code>.
	* @return {String}
	*/
	getItemId: function () {
		return this.itemId || this.getId();
	},

	/**
	* Try to focus this component.
	* @param {Boolean} selectText (optional) If applicable, true to also select the text in this component
	* @param {Boolean/Number} delay (optional) Delay the focus this number of milliseconds (true for 10 milliseconds)
	* @return {Ext.Component} this
	*/
	focus: function (selectText, delay) {
		if (delay) {
			this.focusTask = new Ext.util.DelayedTask(this.focus, this, [selectText, false]);
			this.focusTask.delay(Ext.isNumber(delay) ? delay : 10);
			return;
		}
		if (this.rendered && !this.isDestroyed) {
			this.el.focus();
			if (selectText === true) {
				this.el.dom.select();
			}
		}
		return this;
	},

	// private
	blur: function () {
		if (this.rendered) {
			this.el.blur();
		}
		return this;
	},

	/**
	* Disable this component and fire the 'disable' event.
	* @return {Ext.Component} this
	*/
	disable: function (/* private */silent) {
		if (this.rendered) {
			this.onDisable();
		}
		this.disabled = true;
		if (silent !== true) {
			this.fireEvent('disable', this);
		}
		return this;
	},

	// private
	onDisable: function () {
		this.getActionEl().addClass(this.disabledClass);
		this.el.dom.disabled = true;
	},

	/**
	* Enable this component and fire the 'enable' event.
	* @return {Ext.Component} this
	*/
	enable: function () {
		if (this.rendered) {
			this.onEnable();
		}
		this.disabled = false;
		this.fireEvent('enable', this);
		return this;
	},

	// private
	onEnable: function () {
		this.getActionEl().removeClass(this.disabledClass);
		this.el.dom.disabled = false;
	},

	/**
	* Convenience function for setting disabled/enabled by boolean.
	* @param {Boolean} disabled
	* @return {Ext.Component} this
	*/
	setDisabled: function (disabled) {
		return this[disabled ? 'disable' : 'enable']();
	},

	/**
	* Show this component.  Listen to the '{@link #beforeshow}' event and return
	* <tt>false</tt> to cancel showing the component.  Fires the '{@link #show}'
	* event after showing the component.
	* @return {Ext.Component} this
	*/
	show: function () {
		if (this.fireEvent('beforeshow', this) !== false) {
			this.hidden = false;
			if (this.autoRender) {
				this.render(Ext.isBoolean(this.autoRender) ? Ext.getBody() : this.autoRender);
			}
			if (this.rendered) {
				this.onShow();
			}
			this.fireEvent('show', this);
		}
		return this;
	},

	// private
	onShow: function () {
		this.getVisibilityEl().removeClass('x-hide-' + this.hideMode);
	},

	/**
	* Hide this component.  Listen to the '{@link #beforehide}' event and return
	* <tt>false</tt> to cancel hiding the component.  Fires the '{@link #hide}'
	* event after hiding the component. Note this method is called internally if
	* the component is configured to be <code>{@link #hidden}</code>.
	* @return {Ext.Component} this
	*/
	hide: function () {
		if (this.fireEvent('beforehide', this) !== false) {
			this.doHide();
			this.fireEvent('hide', this);
		}
		return this;
	},

	// private
	doHide: function () {
		this.hidden = true;
		if (this.rendered) {
			this.onHide();
		}
	},

	// private
	onHide: function () {
		this.getVisibilityEl().addClass('x-hide-' + this.hideMode);
	},

	// private
	getVisibilityEl: function () {
		return this.hideParent ? this.container : this.getActionEl();
	},

	/**
	* Convenience function to hide or show this component by boolean.
	* @param {Boolean} visible True to show, false to hide
	* @return {Ext.Component} this
	*/
	setVisible: function (visible) {
		return this[visible ? 'show' : 'hide']();
	},

	/**
	* Returns true if this component is visible.
	* @return {Boolean} True if this component is visible, false otherwise.
	*/
	isVisible: function () {
		return this.rendered && this.getVisibilityEl().isVisible();
	},

	/**
	* Clone the current component using the original config values passed into this instance by default.
	* @param {Object} overrides A new config containing any properties to override in the cloned version.
	* An id property can be passed on this object, otherwise one will be generated to avoid duplicates.
	* @return {Ext.Component} clone The cloned copy of this component
	*/
	cloneConfig: function (overrides) {
		overrides = overrides || {};
		var id = overrides.id || Ext.id();
		var cfg = Ext.applyIf(overrides, this.initialConfig);
		cfg.id = id; // prevent dup id
		return new this.constructor(cfg);
	},

	/**
	* Gets the xtype for this component as registered with {@link Ext.ComponentMgr}. For a list of all
	* available xtypes, see the {@link Ext.Component} header. Example usage:
	* <pre><code>
	var t = new Ext.form.TextField();
	alert(t.getXType());  // alerts 'textfield'
	</code></pre>
	* @return {String} The xtype
	*/
	getXType: function () {
		return this.constructor.xtype;
	},

	/**
	* <p>Tests whether or not this Component is of a specific xtype. This can test whether this Component is descended
	* from the xtype (default) or whether it is directly of the xtype specified (shallow = true).</p>
	* <p><b>If using your own subclasses, be aware that a Component must register its own xtype
	* to participate in determination of inherited xtypes.</b></p>
	* <p>For a list of all available xtypes, see the {@link Ext.Component} header.</p>
	* <p>Example usage:</p>
	* <pre><code>
	var t = new Ext.form.TextField();
	var isText = t.isXType('textfield');        // true
	var isBoxSubclass = t.isXType('box');       // true, descended from BoxComponent
	var isBoxInstance = t.isXType('box', true); // false, not a direct BoxComponent instance
	</code></pre>
	* @param {String} xtype The xtype to check for this Component
	* @param {Boolean} shallow (optional) False to check whether this Component is descended from the xtype (this is
	* the default), or true to check whether this Component is directly of the specified xtype.
	* @return {Boolean} True if this component descends from the specified xtype, false otherwise.
	*/
	isXType: function (xtype, shallow) {
		//assume a string by default
		if (Ext.isFunction(xtype)) {
			xtype = xtype.xtype; //handle being passed the class, e.g. Ext.Component
		} else if (Ext.isObject(xtype)) {
			xtype = xtype.constructor.xtype; //handle being passed an instance
		}

		return !shallow ? ('/' + this.getXTypes() + '/').indexOf('/' + xtype + '/') != -1 : this.constructor.xtype == xtype;
	},

	/**
	* <p>Returns this Component's xtype hierarchy as a slash-delimited string. For a list of all
	* available xtypes, see the {@link Ext.Component} header.</p>
	* <p><b>If using your own subclasses, be aware that a Component must register its own xtype
	* to participate in determination of inherited xtypes.</b></p>
	* <p>Example usage:</p>
	* <pre><code>
	var t = new Ext.form.TextField();
	alert(t.getXTypes());  // alerts 'component/box/field/textfield'
	</code></pre>
	* @return {String} The xtype hierarchy string
	*/
	getXTypes: function () {
		var tc = this.constructor;
		if (!tc.xtypes) {
			var c = [], sc = this;
			while (sc && sc.constructor.xtype) {
				c.unshift(sc.constructor.xtype);
				sc = sc.constructor.superclass;
			}
			tc.xtypeChain = c;
			tc.xtypes = c.join('/');
		}
		return tc.xtypes;
	},

	/**
	* Find a container above this component at any level by a custom function. If the passed function returns
	* true, the container will be returned.
	* @param {Function} fn The custom function to call with the arguments (container, this component).
	* @return {Ext.Container} The first Container for which the custom function returns true
	*/
	findParentBy: function (fn) {
		for (var p = this.ownerCt; (p != null) && !fn(p, this); p = p.ownerCt);
		return p || null;
	},

	/**
	* Find a container above this component at any level by xtype or class
	* @param {String/Class} xtype The xtype string for a component, or the class of the component directly
	* @return {Ext.Container} The first Container which matches the given xtype or class
	*/
	findParentByType: function (xtype) {
		return Ext.isFunction(xtype) ?
            this.findParentBy(function (p) {
            	return p.constructor === xtype;
            }) :
            this.findParentBy(function (p) {
            	return p.constructor.xtype === xtype;
            });
	},

	// protected
	getPositionEl: function () {
		return this.positionEl || this.el;
	},

	// private
	purgeListeners: function () {
		Ext.Component.superclass.purgeListeners.call(this);
		if (this.mons) {
			this.on('beforedestroy', this.clearMons, this, { single: true });
		}
	},

	// private
	clearMons: function () {
		Ext.each(this.mons, function (m) {
			m.item.un(m.ename, m.fn, m.scope);
		}, this);
		this.mons = [];
	},

	// private
	createMons: function () {
		if (!this.mons) {
			this.mons = [];
			this.on('beforedestroy', this.clearMons, this, { single: true });
		}
	},

	/**
	* <p>Adds listeners to any Observable object (or Elements) which are automatically removed when this Component
	* is destroyed. Usage:</p><code><pre>
	myGridPanel.mon(myGridPanel.getSelectionModel(), 'selectionchange', handleSelectionChange, null, {buffer: 50});
	</pre></code>
	* <p>or:</p><code><pre>
	myGridPanel.mon(myGridPanel.getSelectionModel(), {
	selectionchange: handleSelectionChange,
	buffer: 50
	});
	</pre></code>
	* @param {Observable|Element} item The item to which to add a listener/listeners.
	* @param {Object|String} ename The event name, or an object containing event name properties.
	* @param {Function} fn Optional. If the <code>ename</code> parameter was an event name, this
	* is the handler function.
	* @param {Object} scope Optional. If the <code>ename</code> parameter was an event name, this
	* is the scope (<code>this</code> reference) in which the handler function is executed.
	* @param {Object} opt Optional. If the <code>ename</code> parameter was an event name, this
	* is the {@link Ext.util.Observable#addListener addListener} options.
	*/
	mon: function (item, ename, fn, scope, opt) {
		this.createMons();
		if (Ext.isObject(ename)) {
			var propRe = /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/;

			var o = ename;
			for (var e in o) {
				if (propRe.test(e)) {
					continue;
				}
				if (Ext.isFunction(o[e])) {
					// shared options
					this.mons.push({
						item: item, ename: e, fn: o[e], scope: o.scope
					});
					item.on(e, o[e], o.scope, o);
				} else {
					// individual options
					this.mons.push({
						item: item, ename: e, fn: o[e], scope: o.scope
					});
					item.on(e, o[e]);
				}
			}
			return;
		}

		this.mons.push({
			item: item, ename: ename, fn: fn, scope: scope
		});
		item.on(ename, fn, scope, opt);
	},

	/**
	* Removes listeners that were added by the {@link #mon} method.
	* @param {Observable|Element} item The item from which to remove a listener/listeners.
	* @param {Object|String} ename The event name, or an object containing event name properties.
	* @param {Function} fn Optional. If the <code>ename</code> parameter was an event name, this
	* is the handler function.
	* @param {Object} scope Optional. If the <code>ename</code> parameter was an event name, this
	* is the scope (<code>this</code> reference) in which the handler function is executed.
	*/
	mun: function (item, ename, fn, scope) {
		var found, mon;
		this.createMons();
		for (var i = 0, len = this.mons.length; i < len; ++i) {
			mon = this.mons[i];
			if (item === mon.item && ename == mon.ename && fn === mon.fn && scope === mon.scope) {
				this.mons.splice(i, 1);
				item.un(ename, fn, scope);
				found = true;
				break;
			}
		}
		return found;
	},

	/**
	* Returns the next component in the owning container
	* @return Ext.Component
	*/
	nextSibling: function () {
		if (this.ownerCt) {
			var index = this.ownerCt.items.indexOf(this);
			if (index != -1 && index + 1 < this.ownerCt.items.getCount()) {
				return this.ownerCt.items.itemAt(index + 1);
			}
		}
		return null;
	},

	/**
	* Returns the previous component in the owning container
	* @return Ext.Component
	*/
	previousSibling: function () {
		if (this.ownerCt) {
			var index = this.ownerCt.items.indexOf(this);
			if (index > 0) {
				return this.ownerCt.items.itemAt(index - 1);
			}
		}
		return null;
	},

	/**
	* Provides the link for Observable's fireEvent method to bubble up the ownership hierarchy.
	* @return {Ext.Container} the Container which owns this Component.
	*/
	getBubbleTarget: function () {
		return this.ownerCt;
	}
});

Ext.reg('component', Ext.Component); /**
 * @class Ext.Action
 * <p>An Action is a piece of reusable functionality that can be abstracted out of any particular component so that it
 * can be usefully shared among multiple components.  Actions let you share handlers, configuration options and UI
 * updates across any components that support the Action interface (primarily {@link Ext.Toolbar}, {@link Ext.Button}
 * and {@link Ext.menu.Menu} components).</p>
 * <p>Aside from supporting the config object interface, any component that needs to use Actions must also support
 * the following method list, as these will be called as needed by the Action class: setText(string), setIconCls(string),
 * setDisabled(boolean), setVisible(boolean) and setHandler(function).</p>
 * Example usage:<br>
 * <pre><code>
// Define the shared action.  Each component below will have the same
// display text and icon, and will display the same message on click.
var action = new Ext.Action({
    {@link #text}: 'Do something',
    {@link #handler}: function(){
        Ext.Msg.alert('Click', 'You did something.');
    },
    {@link #iconCls}: 'do-something',
    {@link #itemId}: 'myAction'
});

var panel = new Ext.Panel({
    title: 'Actions',
    width: 500,
    height: 300,
    tbar: [
        // Add the action directly to a toolbar as a menu button
        action,
        {
            text: 'Action Menu',
            // Add the action to a menu as a text item
            menu: [action]
        }
    ],
    items: [
        // Add the action to the panel body as a standard button
        new Ext.Button(action)
    ],
    renderTo: Ext.getBody()
});

// Change the text for all components using the action
action.setText('Something else');

// Reference an action through a container using the itemId
var btn = panel.getComponent('myAction');
var aRef = btn.baseAction;
aRef.setText('New text');
</code></pre>
 * @constructor
 * @param {Object} config The configuration options
 */
Ext.Action = Ext.extend(Object, {
	/**
	* @cfg {String} text The text to set for all components using this action (defaults to '').
	*/
	/**
	* @cfg {String} iconCls
	* The CSS class selector that specifies a background image to be used as the header icon for
	* all components using this action (defaults to '').
	* <p>An example of specifying a custom icon class would be something like:
	* </p><pre><code>
	// specify the property in the config for the class:
	...
	iconCls: 'do-something'

	// css class that specifies background image to be used as the icon image:
	.do-something { background-image: url(../images/my-icon.gif) 0 6px no-repeat !important; }
	</code></pre>
	*/
	/**
	* @cfg {Boolean} disabled True to disable all components using this action, false to enable them (defaults to false).
	*/
	/**
	* @cfg {Boolean} hidden True to hide all components using this action, false to show them (defaults to false).
	*/
	/**
	* @cfg {Function} handler The function that will be invoked by each component tied to this action
	* when the component's primary event is triggered (defaults to undefined).
	*/
	/**
	* @cfg {String} itemId
	* See {@link Ext.Component}.{@link Ext.Component#itemId itemId}.
	*/
	/**
	* @cfg {Object} scope The scope (<tt><b>this</b></tt> reference) in which the
	* <code>{@link #handler}</code> is executed. Defaults to this Button.
	*/

	constructor: function (config) {
		this.initialConfig = config;
		this.itemId = config.itemId = (config.itemId || config.id || Ext.id());
		this.items = [];
	},

	// private
	isAction: true,

	/**
	* Sets the text to be displayed by all components using this action.
	* @param {String} text The text to display
	*/
	setText: function (text) {
		this.initialConfig.text = text;
		this.callEach('setText', [text]);
	},

	/**
	* Gets the text currently displayed by all components using this action.
	*/
	getText: function () {
		return this.initialConfig.text;
	},

	/**
	* Sets the icon CSS class for all components using this action.  The class should supply
	* a background image that will be used as the icon image.
	* @param {String} cls The CSS class supplying the icon image
	*/
	setIconClass: function (cls) {
		this.initialConfig.iconCls = cls;
		this.callEach('setIconClass', [cls]);
	},

	/**
	* Gets the icon CSS class currently used by all components using this action.
	*/
	getIconClass: function () {
		return this.initialConfig.iconCls;
	},

	/**
	* Sets the disabled state of all components using this action.  Shortcut method
	* for {@link #enable} and {@link #disable}.
	* @param {Boolean} disabled True to disable the component, false to enable it
	*/
	setDisabled: function (v) {
		this.initialConfig.disabled = v;
		this.callEach('setDisabled', [v]);
	},

	/**
	* Enables all components using this action.
	*/
	enable: function () {
		this.setDisabled(false);
	},

	/**
	* Disables all components using this action.
	*/
	disable: function () {
		this.setDisabled(true);
	},

	/**
	* Returns true if the components using this action are currently disabled, else returns false.  
	*/
	isDisabled: function () {
		return this.initialConfig.disabled;
	},

	/**
	* Sets the hidden state of all components using this action.  Shortcut method
	* for <code>{@link #hide}</code> and <code>{@link #show}</code>.
	* @param {Boolean} hidden True to hide the component, false to show it
	*/
	setHidden: function (v) {
		this.initialConfig.hidden = v;
		this.callEach('setVisible', [!v]);
	},

	/**
	* Shows all components using this action.
	*/
	show: function () {
		this.setHidden(false);
	},

	/**
	* Hides all components using this action.
	*/
	hide: function () {
		this.setHidden(true);
	},

	/**
	* Returns true if the components using this action are currently hidden, else returns false.  
	*/
	isHidden: function () {
		return this.initialConfig.hidden;
	},

	/**
	* Sets the function that will be called by each Component using this action when its primary event is triggered.
	* @param {Function} fn The function that will be invoked by the action's components.  The function
	* will be called with no arguments.
	* @param {Object} scope The scope (<code>this</code> reference) in which the function is executed. Defaults to the Component firing the event.
	*/
	setHandler: function (fn, scope) {
		this.initialConfig.handler = fn;
		this.initialConfig.scope = scope;
		this.callEach('setHandler', [fn, scope]);
	},

	/**
	* Executes the specified function once for each Component currently tied to this action.  The function passed
	* in should accept a single argument that will be an object that supports the basic Action config/method interface.
	* @param {Function} fn The function to execute for each component
	* @param {Object} scope The scope (<code>this</code> reference) in which the function is executed.  Defaults to the Component.
	*/
	each: function (fn, scope) {
		Ext.each(this.items, fn, scope);
	},

	// private
	callEach: function (fnName, args) {
		var cs = this.items;
		for (var i = 0, len = cs.length; i < len; i++) {
			cs[i][fnName].apply(cs[i], args);
		}
	},

	// private
	addComponent: function (comp) {
		this.items.push(comp);
		comp.on('destroy', this.removeComponent, this);
	},

	// private
	removeComponent: function (comp) {
		this.items.remove(comp);
	},

	/**
	* Executes this action manually using the handler function specified in the original config object
	* or the handler function set with <code>{@link #setHandler}</code>.  Any arguments passed to this
	* function will be passed on to the handler function.
	* @param {Mixed} arg1 (optional) Variable number of arguments passed to the handler function
	* @param {Mixed} arg2 (optional)
	* @param {Mixed} etc... (optional)
	*/
	execute: function () {
		this.initialConfig.handler.apply(this.initialConfig.scope || window, arguments);
	}
});
/**
* @class Ext.Layer
* @extends Ext.Element
* An extended {@link Ext.Element} object that supports a shadow and shim, constrain to viewport and
* automatic maintaining of shadow/shim positions.
* @cfg {Boolean} shim False to disable the iframe shim in browsers which need one (defaults to true)
* @cfg {String/Boolean} shadow True to automatically create an {@link Ext.Shadow}, or a string indicating the
* shadow's display {@link Ext.Shadow#mode}. False to disable the shadow. (defaults to false)
* @cfg {Object} dh DomHelper object config to create element with (defaults to {tag: 'div', cls: 'x-layer'}).
* @cfg {Boolean} constrain False to disable constrain to viewport (defaults to true)
* @cfg {String} cls CSS class to add to the element
* @cfg {Number} zindex Starting z-index (defaults to 11000)
* @cfg {Number} shadowOffset Number of pixels to offset the shadow (defaults to 4)
* @cfg {Boolean} useDisplay
* Defaults to use css offsets to hide the Layer. Specify <tt>true</tt>
* to use css style <tt>'display:none;'</tt> to hide the Layer.
* @constructor
* @param {Object} config An object with config options.
* @param {String/HTMLElement} existingEl (optional) Uses an existing DOM element. If the element is not found it creates it.
*/
(function () {
	Ext.Layer = function (config, existingEl) {
		config = config || {};
		var dh = Ext.DomHelper;
		var cp = config.parentEl, pel = cp ? Ext.getDom(cp) : document.body;
		if (existingEl) {
			this.dom = Ext.getDom(existingEl);
		}
		if (!this.dom) {
			var o = config.dh || { tag: 'div', cls: 'x-layer' };
			this.dom = dh.append(pel, o);
		}
		if (config.cls) {
			this.addClass(config.cls);
		}
		this.constrain = config.constrain !== false;
		this.setVisibilityMode(Ext.Element.VISIBILITY);
		if (config.id) {
			this.id = this.dom.id = config.id;
		} else {
			this.id = Ext.id(this.dom);
		}
		this.zindex = config.zindex || this.getZIndex();
		this.position('absolute', this.zindex);
		if (config.shadow) {
			this.shadowOffset = config.shadowOffset || 4;
			this.shadow = new Ext.Shadow({
				offset: this.shadowOffset,
				mode: config.shadow
			});
		} else {
			this.shadowOffset = 0;
		}
		this.useShim = config.shim !== false && Ext.useShims;
		this.useDisplay = config.useDisplay;
		this.hide();
	};

	var supr = Ext.Element.prototype;

	// shims are shared among layer to keep from having 100 iframes
	var shims = [];

	Ext.extend(Ext.Layer, Ext.Element, {

		getZIndex: function () {
			return this.zindex || parseInt((this.getShim() || this).getStyle('z-index'), 10) || 11000;
		},

		getShim: function () {
			if (!this.useShim) {
				return null;
			}
			if (this.shim) {
				return this.shim;
			}
			var shim = shims.shift();
			if (!shim) {
				shim = this.createShim();
				shim.enableDisplayMode('block');
				shim.dom.style.display = 'none';
				shim.dom.style.visibility = 'visible';
			}
			var pn = this.dom.parentNode;
			if (shim.dom.parentNode != pn) {
				pn.insertBefore(shim.dom, this.dom);
			}
			shim.setStyle('z-index', this.getZIndex() - 2);
			this.shim = shim;
			return shim;
		},

		hideShim: function () {
			if (this.shim) {
				this.shim.setDisplayed(false);
				shims.push(this.shim);
				delete this.shim;
			}
		},

		disableShadow: function () {
			if (this.shadow) {
				this.shadowDisabled = true;
				this.shadow.hide();
				this.lastShadowOffset = this.shadowOffset;
				this.shadowOffset = 0;
			}
		},

		enableShadow: function (show) {
			if (this.shadow) {
				this.shadowDisabled = false;
				this.shadowOffset = this.lastShadowOffset;
				delete this.lastShadowOffset;
				if (show) {
					this.sync(true);
				}
			}
		},

		// private
		// this code can execute repeatedly in milliseconds (i.e. during a drag) so
		// code size was sacrificed for effeciency (e.g. no getBox/setBox, no XY calls)
		sync: function (doShow) {
			var shadow = this.shadow;
			if (!this.updating && this.isVisible() && (shadow || this.useShim)) {
				var shim = this.getShim(),
                w = this.getWidth(),
                h = this.getHeight(),
                l = this.getLeft(true),
                t = this.getTop(true);

				if (shadow && !this.shadowDisabled) {
					if (doShow && !shadow.isVisible()) {
						shadow.show(this);
					} else {
						shadow.realign(l, t, w, h);
					}
					if (shim) {
						if (doShow) {
							shim.show();
						}
						// fit the shim behind the shadow, so it is shimmed too
						var shadowAdj = shadow.el.getXY(), shimStyle = shim.dom.style,
                        shadowSize = shadow.el.getSize();
						shimStyle.left = (shadowAdj[0]) + 'px';
						shimStyle.top = (shadowAdj[1]) + 'px';
						shimStyle.width = (shadowSize.width) + 'px';
						shimStyle.height = (shadowSize.height) + 'px';
					}
				} else if (shim) {
					if (doShow) {
						shim.show();
					}
					shim.setSize(w, h);
					shim.setLeftTop(l, t);
				}
			}
		},

		// private
		destroy: function () {
			this.hideShim();
			if (this.shadow) {
				this.shadow.hide();
			}
			this.removeAllListeners();
			Ext.removeNode(this.dom);
			delete this.dom;
		},

		remove: function () {
			this.destroy();
		},

		// private
		beginUpdate: function () {
			this.updating = true;
		},

		// private
		endUpdate: function () {
			this.updating = false;
			this.sync(true);
		},

		// private
		hideUnders: function (negOffset) {
			if (this.shadow) {
				this.shadow.hide();
			}
			this.hideShim();
		},

		// private
		constrainXY: function () {
			if (this.constrain) {
				var vw = Ext.lib.Dom.getViewWidth(),
                vh = Ext.lib.Dom.getViewHeight();
				var s = Ext.getDoc().getScroll();

				var xy = this.getXY();
				var x = xy[0], y = xy[1];
				var so = this.shadowOffset;
				var w = this.dom.offsetWidth + so, h = this.dom.offsetHeight + so;
				// only move it if it needs it
				var moved = false;
				// first validate right/bottom
				if ((x + w) > vw + s.left) {
					x = vw - w - so;
					moved = true;
				}
				if ((y + h) > vh + s.top) {
					y = vh - h - so;
					moved = true;
				}
				// then make sure top/left isn't negative
				if (x < s.left) {
					x = s.left;
					moved = true;
				}
				if (y < s.top) {
					y = s.top;
					moved = true;
				}
				if (moved) {
					if (this.avoidY) {
						var ay = this.avoidY;
						if (y <= ay && (y + h) >= ay) {
							y = ay - h - 5;
						}
					}
					xy = [x, y];
					this.storeXY(xy);
					supr.setXY.call(this, xy);
					this.sync();
				}
			}
			return this;
		},

		isVisible: function () {
			return this.visible;
		},

		// private
		showAction: function () {
			this.visible = true; // track visibility to prevent getStyle calls
			if (this.useDisplay === true) {
				this.setDisplayed('');
			} else if (this.lastXY) {
				supr.setXY.call(this, this.lastXY);
			} else if (this.lastLT) {
				supr.setLeftTop.call(this, this.lastLT[0], this.lastLT[1]);
			}
		},

		// private
		hideAction: function () {
			this.visible = false;
			if (this.useDisplay === true) {
				this.setDisplayed(false);
			} else {
				this.setLeftTop(-10000, -10000);
			}
		},

		// overridden Element method
		setVisible: function (v, a, d, c, e) {
			if (v) {
				this.showAction();
			}
			if (a && v) {
				var cb = function () {
					this.sync(true);
					if (c) {
						c();
					}
				} .createDelegate(this);
				supr.setVisible.call(this, true, true, d, cb, e);
			} else {
				if (!v) {
					this.hideUnders(true);
				}
				var cb = c;
				if (a) {
					cb = function () {
						this.hideAction();
						if (c) {
							c();
						}
					} .createDelegate(this);
				}
				supr.setVisible.call(this, v, a, d, cb, e);
				if (v) {
					this.sync(true);
				} else if (!a) {
					this.hideAction();
				}
			}
			return this;
		},

		storeXY: function (xy) {
			delete this.lastLT;
			this.lastXY = xy;
		},

		storeLeftTop: function (left, top) {
			delete this.lastXY;
			this.lastLT = [left, top];
		},

		// private
		beforeFx: function () {
			this.beforeAction();
			return Ext.Layer.superclass.beforeFx.apply(this, arguments);
		},

		// private
		afterFx: function () {
			Ext.Layer.superclass.afterFx.apply(this, arguments);
			this.sync(this.isVisible());
		},

		// private
		beforeAction: function () {
			if (!this.updating && this.shadow) {
				this.shadow.hide();
			}
		},

		// overridden Element method
		setLeft: function (left) {
			this.storeLeftTop(left, this.getTop(true));
			supr.setLeft.apply(this, arguments);
			this.sync();
			return this;
		},

		setTop: function (top) {
			this.storeLeftTop(this.getLeft(true), top);
			supr.setTop.apply(this, arguments);
			this.sync();
			return this;
		},

		setLeftTop: function (left, top) {
			this.storeLeftTop(left, top);
			supr.setLeftTop.apply(this, arguments);
			this.sync();
			return this;
		},

		setXY: function (xy, a, d, c, e) {
			this.fixDisplay();
			this.beforeAction();
			this.storeXY(xy);
			var cb = this.createCB(c);
			supr.setXY.call(this, xy, a, d, cb, e);
			if (!a) {
				cb();
			}
			return this;
		},

		// private
		createCB: function (c) {
			var el = this;
			return function () {
				el.constrainXY();
				el.sync(true);
				if (c) {
					c();
				}
			};
		},

		// overridden Element method
		setX: function (x, a, d, c, e) {
			this.setXY([x, this.getY()], a, d, c, e);
			return this;
		},

		// overridden Element method
		setY: function (y, a, d, c, e) {
			this.setXY([this.getX(), y], a, d, c, e);
			return this;
		},

		// overridden Element method
		setSize: function (w, h, a, d, c, e) {
			this.beforeAction();
			var cb = this.createCB(c);
			supr.setSize.call(this, w, h, a, d, cb, e);
			if (!a) {
				cb();
			}
			return this;
		},

		// overridden Element method
		setWidth: function (w, a, d, c, e) {
			this.beforeAction();
			var cb = this.createCB(c);
			supr.setWidth.call(this, w, a, d, cb, e);
			if (!a) {
				cb();
			}
			return this;
		},

		// overridden Element method
		setHeight: function (h, a, d, c, e) {
			this.beforeAction();
			var cb = this.createCB(c);
			supr.setHeight.call(this, h, a, d, cb, e);
			if (!a) {
				cb();
			}
			return this;
		},

		// overridden Element method
		setBounds: function (x, y, w, h, a, d, c, e) {
			this.beforeAction();
			var cb = this.createCB(c);
			if (!a) {
				this.storeXY([x, y]);
				supr.setXY.call(this, [x, y]);
				supr.setSize.call(this, w, h, a, d, cb, e);
				cb();
			} else {
				supr.setBounds.call(this, x, y, w, h, a, d, cb, e);
			}
			return this;
		},

		/**
		* Sets the z-index of this layer and adjusts any shadow and shim z-indexes. The layer z-index is automatically
		* incremented by two more than the value passed in so that it always shows above any shadow or shim (the shadow
		* element, if any, will be assigned z-index + 1, and the shim element, if any, will be assigned the unmodified z-index).
		* @param {Number} zindex The new z-index to set
		* @return {this} The Layer
		*/
		setZIndex: function (zindex) {
			this.zindex = zindex;
			this.setStyle('z-index', zindex + 2);
			if (this.shadow) {
				this.shadow.setZIndex(zindex + 1);
			}
			if (this.shim) {
				this.shim.setStyle('z-index', zindex);
			}
			return this;
		}
	});
})();
/**
* @class Ext.Shadow
* Simple class that can provide a shadow effect for any element.  Note that the element MUST be absolutely positioned,
* and the shadow does not provide any shimming.  This should be used only in simple cases -- for more advanced
* functionality that can also provide the same shadow effect, see the {@link Ext.Layer} class.
* @constructor
* Create a new Shadow
* @param {Object} config The config object
*/
Ext.Shadow = function (config) {
	Ext.apply(this, config);
	if (typeof this.mode != "string") {
		this.mode = this.defaultMode;
	}
	var o = this.offset, a = { h: 0 };
	var rad = Math.floor(this.offset / 2);
	switch (this.mode.toLowerCase()) { // all this hideous nonsense calculates the various offsets for shadows
		case "drop":
			a.w = 0;
			a.l = a.t = o;
			a.t -= 1;
			if (Ext.isIE) {
				a.l -= this.offset + rad;
				a.t -= this.offset + rad;
				a.w -= rad;
				a.h -= rad;
				a.t += 1;
			}
			break;
		case "sides":
			a.w = (o * 2);
			a.l = -o;
			a.t = o - 1;
			if (Ext.isIE) {
				a.l -= (this.offset - rad);
				a.t -= this.offset + rad;
				a.l += 1;
				a.w -= (this.offset - rad) * 2;
				a.w -= rad + 1;
				a.h -= 1;
			}
			break;
		case "frame":
			a.w = a.h = (o * 2);
			a.l = a.t = -o;
			a.t += 1;
			a.h -= 2;
			if (Ext.isIE) {
				a.l -= (this.offset - rad);
				a.t -= (this.offset - rad);
				a.l += 1;
				a.w -= (this.offset + rad + 1);
				a.h -= (this.offset + rad);
				a.h += 1;
			}
			break;
	};

	this.adjusts = a;
};

Ext.Shadow.prototype = {
	/**
	* @cfg {String} mode
	* The shadow display mode.  Supports the following options:<div class="mdetail-params"><ul>
	* <li><b><tt>sides</tt></b> : Shadow displays on both sides and bottom only</li>
	* <li><b><tt>frame</tt></b> : Shadow displays equally on all four sides</li>
	* <li><b><tt>drop</tt></b> : Traditional bottom-right drop shadow</li>
	* </ul></div>
	*/
	/**
	* @cfg {String} offset
	* The number of pixels to offset the shadow from the element (defaults to <tt>4</tt>)
	*/
	offset: 4,

	// private
	defaultMode: "drop",

	/**
	* Displays the shadow under the target element
	* @param {Mixed} targetEl The id or element under which the shadow should display
	*/
	show: function (target) {
		target = Ext.get(target);
		if (!this.el) {
			this.el = Ext.Shadow.Pool.pull();
			if (this.el.dom.nextSibling != target.dom) {
				this.el.insertBefore(target);
			}
		}
		this.el.setStyle("z-index", this.zIndex || parseInt(target.getStyle("z-index"), 10) - 1);
		if (Ext.isIE) {
			this.el.dom.style.filter = "progid:DXImageTransform.Microsoft.alpha(opacity=50) progid:DXImageTransform.Microsoft.Blur(pixelradius=" + (this.offset) + ")";
		}
		this.realign(
            target.getLeft(true),
            target.getTop(true),
            target.getWidth(),
            target.getHeight()
        );
		this.el.dom.style.display = "block";
	},

	/**
	* Returns true if the shadow is visible, else false
	*/
	isVisible: function () {
		return this.el ? true : false;
	},

	/**
	* Direct alignment when values are already available. Show must be called at least once before
	* calling this method to ensure it is initialized.
	* @param {Number} left The target element left position
	* @param {Number} top The target element top position
	* @param {Number} width The target element width
	* @param {Number} height The target element height
	*/
	realign: function (l, t, w, h) {
		if (!this.el) {
			return;
		}
		var a = this.adjusts, d = this.el.dom, s = d.style;
		var iea = 0;
		s.left = (l + a.l) + "px";
		s.top = (t + a.t) + "px";
		var sw = (w + a.w), sh = (h + a.h), sws = sw + "px", shs = sh + "px";
		if (s.width != sws || s.height != shs) {
			s.width = sws;
			s.height = shs;
			if (!Ext.isIE) {
				var cn = d.childNodes;
				var sww = Math.max(0, (sw - 12)) + "px";
				cn[0].childNodes[1].style.width = sww;
				cn[1].childNodes[1].style.width = sww;
				cn[2].childNodes[1].style.width = sww;
				cn[1].style.height = Math.max(0, (sh - 12)) + "px";
			}
		}
	},

	/**
	* Hides this shadow
	*/
	hide: function () {
		if (this.el) {
			this.el.dom.style.display = "none";
			Ext.Shadow.Pool.push(this.el);
			delete this.el;
		}
	},

	/**
	* Adjust the z-index of this shadow
	* @param {Number} zindex The new z-index
	*/
	setZIndex: function (z) {
		this.zIndex = z;
		if (this.el) {
			this.el.setStyle("z-index", z);
		}
	}
};

// Private utility class that manages the internal Shadow cache
Ext.Shadow.Pool = function () {
	var p = [];
	var markup = Ext.isIE ?
                 '<div class="x-ie-shadow"></div>' :
                 '<div class="x-shadow"><div class="xst"><div class="xstl"></div><div class="xstc"></div><div class="xstr"></div></div><div class="xsc"><div class="xsml"></div><div class="xsmc"></div><div class="xsmr"></div></div><div class="xsb"><div class="xsbl"></div><div class="xsbc"></div><div class="xsbr"></div></div></div>';
	return {
		pull: function () {
			var sh = p.shift();
			if (!sh) {
				sh = Ext.get(Ext.DomHelper.insertHtml("beforeBegin", document.body.firstChild, markup));
				sh.autoBoxAdjust = false;
			}
			return sh;
		},

		push: function (sh) {
			p.push(sh);
		}
	};
} (); /**
 * @class Ext.BoxComponent
 * @extends Ext.Component
 * <p>Base class for any {@link Ext.Component Component} that is to be sized as a box, using width and height.</p>
 * <p>BoxComponent provides automatic box model adjustments for sizing and positioning and will work correctly
 * within the Component rendering model.</p>
 * <p>A BoxComponent may be created as a custom Component which encapsulates any HTML element, either a pre-existing
 * element, or one that is created to your specifications at render time. Usually, to participate in layouts,
 * a Component will need to be a <b>Box</b>Component in order to have its width and height managed.</p>
 * <p>To use a pre-existing element as a BoxComponent, configure it so that you preset the <b>el</b> property to the
 * element to reference:<pre><code>
var pageHeader = new Ext.BoxComponent({
    el: 'my-header-div'
});</code></pre>
 * This may then be {@link Ext.Container#add added} to a {@link Ext.Container Container} as a child item.</p>
 * <p>To create a BoxComponent based around a HTML element to be created at render time, use the
 * {@link Ext.Component#autoEl autoEl} config option which takes the form of a
 * {@link Ext.DomHelper DomHelper} specification:<pre><code>
var myImage = new Ext.BoxComponent({
    autoEl: {
        tag: 'img',
        src: '/images/my-image.jpg'
    }
});</code></pre></p>
 * @constructor
 * @param {Ext.Element/String/Object} config The configuration options.
 * @xtype box
 */
Ext.BoxComponent = Ext.extend(Ext.Component, {

	// Configs below are used for all Components when rendered by BoxLayout.
	/**
	* @cfg {Number} flex
	* <p><b>Note</b>: this config is only used when this Component is rendered
	* by a Container which has been configured to use a <b>{@link Ext.layout.BoxLayout BoxLayout}.</b>
	* Each child Component with a <code>flex</code> property will be flexed either vertically (by a VBoxLayout)
	* or horizontally (by an HBoxLayout) according to the item's <b>relative</b> <code>flex</code> value
	* compared to the sum of all Components with <code>flex</flex> value specified. Any child items that have
	* either a <code>flex = 0</code> or <code>flex = undefined</code> will not be 'flexed' (the initial size will not be changed).
	*/
	// Configs below are used for all Components when rendered by AnchorLayout.
	/**
	* @cfg {String} anchor <p><b>Note</b>: this config is only used when this Component is rendered
	* by a Container which has been configured to use an <b>{@link Ext.layout.AnchorLayout AnchorLayout} (or subclass thereof).</b>
	* based layout manager, for example:<div class="mdetail-params"><ul>
	* <li>{@link Ext.form.FormPanel}</li>
	* <li>specifying <code>layout: 'anchor' // or 'form', or 'absolute'</code></li>
	* </ul></div></p>
	* <p>See {@link Ext.layout.AnchorLayout}.{@link Ext.layout.AnchorLayout#anchor anchor} also.</p>
	*/
	// tabTip config is used when a BoxComponent is a child of a TabPanel
	/**
	* @cfg {String} tabTip
	* <p><b>Note</b>: this config is only used when this BoxComponent is a child item of a TabPanel.</p>
	* A string to be used as innerHTML (html tags are accepted) to show in a tooltip when mousing over
	* the associated tab selector element. {@link Ext.QuickTips}.init()
	* must be called in order for the tips to render.
	*/
	// Configs below are used for all Components when rendered by BorderLayout.
	/**
	* @cfg {String} region <p><b>Note</b>: this config is only used when this BoxComponent is rendered
	* by a Container which has been configured to use the <b>{@link Ext.layout.BorderLayout BorderLayout}</b>
	* layout manager (e.g. specifying <tt>layout:'border'</tt>).</p><br>
	* <p>See {@link Ext.layout.BorderLayout} also.</p>
	*/
	// margins config is used when a BoxComponent is rendered by BorderLayout or BoxLayout.
	/**
	* @cfg {Object} margins <p><b>Note</b>: this config is only used when this BoxComponent is rendered
	* by a Container which has been configured to use the <b>{@link Ext.layout.BorderLayout BorderLayout}</b>
	* or one of the two <b>{@link Ext.layout.BoxLayout BoxLayout} subclasses.</b></p>
	* <p>An object containing margins to apply to this BoxComponent in the
	* format:</p><pre><code>
	{
	top: (top margin),
	right: (right margin),
	bottom: (bottom margin),
	left: (left margin)
	}</code></pre>
	* <p>May also be a string containing space-separated, numeric margin values. The order of the
	* sides associated with each value matches the way CSS processes margin values:</p>
	* <p><div class="mdetail-params"><ul>
	* <li>If there is only one value, it applies to all sides.</li>
	* <li>If there are two values, the top and bottom borders are set to the first value and the
	* right and left are set to the second.</li>
	* <li>If there are three values, the top is set to the first value, the left and right are set
	* to the second, and the bottom is set to the third.</li>
	* <li>If there are four values, they apply to the top, right, bottom, and left, respectively.</li>
	* </ul></div></p>
	* <p>Defaults to:</p><pre><code>
	* {top:0, right:0, bottom:0, left:0}
	* </code></pre>
	*/
	/**
	* @cfg {Number} x
	* The local x (left) coordinate for this component if contained within a positioning container.
	*/
	/**
	* @cfg {Number} y
	* The local y (top) coordinate for this component if contained within a positioning container.
	*/
	/**
	* @cfg {Number} pageX
	* The page level x coordinate for this component if contained within a positioning container.
	*/
	/**
	* @cfg {Number} pageY
	* The page level y coordinate for this component if contained within a positioning container.
	*/
	/**
	* @cfg {Number} height
	* The height of this component in pixels (defaults to auto).
	* <b>Note</b> to express this dimension as a percentage or offset see {@link Ext.Component#anchor}.
	*/
	/**
	* @cfg {Number} width
	* The width of this component in pixels (defaults to auto).
	* <b>Note</b> to express this dimension as a percentage or offset see {@link Ext.Component#anchor}.
	*/
	/**
	* @cfg {Number} boxMinHeight
	* <p>The minimum value in pixels which this BoxComponent will set its height to.</p>
	* <p><b>Warning:</b> This will override any size management applied by layout managers.</p>
	*/
	/**
	* @cfg {Number} boxMinWidth
	* <p>The minimum value in pixels which this BoxComponent will set its width to.</p>
	* <p><b>Warning:</b> This will override any size management applied by layout managers.</p>
	*/
	/**
	* @cfg {Number} boxMaxHeight
	* <p>The maximum value in pixels which this BoxComponent will set its height to.</p>
	* <p><b>Warning:</b> This will override any size management applied by layout managers.</p>
	*/
	/**
	* @cfg {Number} boxMaxWidth
	* <p>The maximum value in pixels which this BoxComponent will set its width to.</p>
	* <p><b>Warning:</b> This will override any size management applied by layout managers.</p>
	*/
	/**
	* @cfg {Boolean} autoHeight
	* <p>True to use height:'auto', false to use fixed height (or allow it to be managed by its parent
	* Container's {@link Ext.Container#layout layout manager}. Defaults to false.</p>
	* <p><b>Note</b>: Although many components inherit this config option, not all will
	* function as expected with a height of 'auto'. Setting autoHeight:true means that the
	* browser will manage height based on the element's contents, and that Ext will not manage it at all.</p>
	* <p>If the <i>browser</i> is managing the height, be aware that resizes performed by the browser in response
	* to changes within the structure of the Component cannot be detected. Therefore changes to the height might
	* result in elements needing to be synchronized with the new height. Example:</p><pre><code>
	var w = new Ext.Window({
	title: 'Window',
	width: 600,
	autoHeight: true,
	items: {
	title: 'Collapse Me',
	height: 400,
	collapsible: true,
	border: false,
	listeners: {
	beforecollapse: function() {
	w.el.shadow.hide();
	},
	beforeexpand: function() {
	w.el.shadow.hide();
	},
	collapse: function() {
	w.syncShadow();
	},
	expand: function() {
	w.syncShadow();
	}
	}
	}
	}).show();
	</code></pre>
	*/
	/**
	* @cfg {Boolean} autoWidth
	* <p>True to use width:'auto', false to use fixed width (or allow it to be managed by its parent
	* Container's {@link Ext.Container#layout layout manager}. Defaults to false.</p>
	* <p><b>Note</b>: Although many components  inherit this config option, not all will
	* function as expected with a width of 'auto'. Setting autoWidth:true means that the
	* browser will manage width based on the element's contents, and that Ext will not manage it at all.</p>
	* <p>If the <i>browser</i> is managing the width, be aware that resizes performed by the browser in response
	* to changes within the structure of the Component cannot be detected. Therefore changes to the width might
	* result in elements needing to be synchronized with the new width. For example, where the target element is:</p><pre><code>
	&lt;div id='grid-container' style='margin-left:25%;width:50%'>&lt;/div>
	</code></pre>
	* A Panel rendered into that target element must listen for browser window resize in order to relay its
	* child items when the browser changes its width:<pre><code>
	var myPanel = new Ext.Panel({
	renderTo: 'grid-container',
	monitorResize: true, // relay on browser resize
	title: 'Panel',
	height: 400,
	autoWidth: true,
	layout: 'hbox',
	layoutConfig: {
	align: 'stretch'
	},
	defaults: {
	flex: 1
	},
	items: [{
	title: 'Box 1',
	}, {
	title: 'Box 2'
	}, {
	title: 'Box 3'
	}],
	});
	</code></pre>
	*/
	/**
	* @cfg {Boolean} autoScroll
	* <code>true</code> to use overflow:'auto' on the components layout element and show scroll bars automatically when
	* necessary, <code>false</code> to clip any overflowing content (defaults to <code>false</code>).
	*/

	/* // private internal config
	* {Boolean} deferHeight
	* True to defer height calculations to an external component, false to allow this component to set its own
	* height (defaults to false).
	*/

	// private
	initComponent: function () {
		Ext.BoxComponent.superclass.initComponent.call(this);
		this.addEvents(
		/**
		* @event resize
		* Fires after the component is resized.
		* @param {Ext.Component} this
		* @param {Number} adjWidth The box-adjusted width that was set
		* @param {Number} adjHeight The box-adjusted height that was set
		* @param {Number} rawWidth The width that was originally specified
		* @param {Number} rawHeight The height that was originally specified
		*/
            'resize',
		/**
		* @event move
		* Fires after the component is moved.
		* @param {Ext.Component} this
		* @param {Number} x The new x position
		* @param {Number} y The new y position
		*/
            'move'
        );
	},

	// private, set in afterRender to signify that the component has been rendered
	boxReady: false,
	// private, used to defer height settings to subclasses
	deferHeight: false,

	/**
	* Sets the width and height of this BoxComponent. This method fires the {@link #resize} event. This method can accept
	* either width and height as separate arguments, or you can pass a size object like <code>{width:10, height:20}</code>.
	* @param {Mixed} width The new width to set. This may be one of:<div class="mdetail-params"><ul>
	* <li>A Number specifying the new width in the {@link #getEl Element}'s {@link Ext.Element#defaultUnit}s (by default, pixels).</li>
	* <li>A String used to set the CSS width style.</li>
	* <li>A size object in the format <code>{width: widthValue, height: heightValue}</code>.</li>
	* <li><code>undefined</code> to leave the width unchanged.</li>
	* </ul></div>
	* @param {Mixed} height The new height to set (not required if a size object is passed as the first arg).
	* This may be one of:<div class="mdetail-params"><ul>
	* <li>A Number specifying the new height in the {@link #getEl Element}'s {@link Ext.Element#defaultUnit}s (by default, pixels).</li>
	* <li>A String used to set the CSS height style. Animation may <b>not</b> be used.</li>
	* <li><code>undefined</code> to leave the height unchanged.</li>
	* </ul></div>
	* @return {Ext.BoxComponent} this
	*/
	setSize: function (w, h) {

		// support for standard size objects
		if (typeof w == 'object') {
			h = w.height;
			w = w.width;
		}
		if (Ext.isDefined(w) && Ext.isDefined(this.boxMinWidth) && (w < this.boxMinWidth)) {
			w = this.boxMinWidth;
		}
		if (Ext.isDefined(h) && Ext.isDefined(this.boxMinHeight) && (h < this.boxMinHeight)) {
			h = this.boxMinHeight;
		}
		if (Ext.isDefined(w) && Ext.isDefined(this.boxMaxWidth) && (w > this.boxMaxWidth)) {
			w = this.boxMaxWidth;
		}
		if (Ext.isDefined(h) && Ext.isDefined(this.boxMaxHeight) && (h > this.boxMaxHeight)) {
			h = this.boxMaxHeight;
		}
		// not rendered
		if (!this.boxReady) {
			this.width = w;
			this.height = h;
			return this;
		}

		// prevent recalcs when not needed
		if (this.cacheSizes !== false && this.lastSize && this.lastSize.width == w && this.lastSize.height == h) {
			return this;
		}
		this.lastSize = { width: w, height: h };
		var adj = this.adjustSize(w, h),
            aw = adj.width,
            ah = adj.height,
            rz;
		if (aw !== undefined || ah !== undefined) { // this code is nasty but performs better with floaters
			rz = this.getResizeEl();
			if (!this.deferHeight && aw !== undefined && ah !== undefined) {
				rz.setSize(aw, ah);
			} else if (!this.deferHeight && ah !== undefined) {
				rz.setHeight(ah);
			} else if (aw !== undefined) {
				rz.setWidth(aw);
			}
			this.onResize(aw, ah, w, h);
			this.fireEvent('resize', this, aw, ah, w, h);
		}
		return this;
	},

	/**
	* Sets the width of the component.  This method fires the {@link #resize} event.
	* @param {Mixed} width The new width to set. This may be one of:<div class="mdetail-params"><ul>
	* <li>A Number specifying the new width in the {@link #getEl Element}'s {@link Ext.Element#defaultUnit defaultUnit}s (by default, pixels).</li>
	* <li>A String used to set the CSS width style.</li>
	* </ul></div>
	* @return {Ext.BoxComponent} this
	*/
	setWidth: function (width) {
		return this.setSize(width);
	},

	/**
	* Sets the height of the component.  This method fires the {@link #resize} event.
	* @param {Mixed} height The new height to set. This may be one of:<div class="mdetail-params"><ul>
	* <li>A Number specifying the new height in the {@link #getEl Element}'s {@link Ext.Element#defaultUnit defaultUnit}s (by default, pixels).</li>
	* <li>A String used to set the CSS height style.</li>
	* <li><i>undefined</i> to leave the height unchanged.</li>
	* </ul></div>
	* @return {Ext.BoxComponent} this
	*/
	setHeight: function (height) {
		return this.setSize(undefined, height);
	},

	/**
	* Gets the current size of the component's underlying element.
	* @return {Object} An object containing the element's size {width: (element width), height: (element height)}
	*/
	getSize: function () {
		return this.getResizeEl().getSize();
	},

	/**
	* Gets the current width of the component's underlying element.
	* @return {Number}
	*/
	getWidth: function () {
		return this.getResizeEl().getWidth();
	},

	/**
	* Gets the current height of the component's underlying element.
	* @return {Number}
	*/
	getHeight: function () {
		return this.getResizeEl().getHeight();
	},

	/**
	* Gets the current size of the component's underlying element, including space taken by its margins.
	* @return {Object} An object containing the element's size {width: (element width + left/right margins), height: (element height + top/bottom margins)}
	*/
	getOuterSize: function () {
		var el = this.getResizeEl();
		return { width: el.getWidth() + el.getMargins('lr'),
			height: el.getHeight() + el.getMargins('tb')
		};
	},

	/**
	* Gets the current XY position of the component's underlying element.
	* @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
	* @return {Array} The XY position of the element (e.g., [100, 200])
	*/
	getPosition: function (local) {
		var el = this.getPositionEl();
		if (local === true) {
			return [el.getLeft(true), el.getTop(true)];
		}
		return this.xy || el.getXY();
	},

	/**
	* Gets the current box measurements of the component's underlying element.
	* @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
	* @return {Object} box An object in the format {x, y, width, height}
	*/
	getBox: function (local) {
		var pos = this.getPosition(local);
		var s = this.getSize();
		s.x = pos[0];
		s.y = pos[1];
		return s;
	},

	/**
	* Sets the current box measurements of the component's underlying element.
	* @param {Object} box An object in the format {x, y, width, height}
	* @return {Ext.BoxComponent} this
	*/
	updateBox: function (box) {
		this.setSize(box.width, box.height);
		this.setPagePosition(box.x, box.y);
		return this;
	},

	/**
	* <p>Returns the outermost Element of this Component which defines the Components overall size.</p>
	* <p><i>Usually</i> this will return the same Element as <code>{@link #getEl}</code>,
	* but in some cases, a Component may have some more wrapping Elements around its main
	* active Element.</p>
	* <p>An example is a ComboBox. It is encased in a <i>wrapping</i> Element which
	* contains both the <code>&lt;input></code> Element (which is what would be returned
	* by its <code>{@link #getEl}</code> method, <i>and</i> the trigger button Element.
	* This Element is returned as the <code>resizeEl</code>.
	* @return {Ext.Element} The Element which is to be resized by size managing layouts.
	*/
	getResizeEl: function () {
		return this.resizeEl || this.el;
	},

	/**
	* Sets the overflow on the content element of the component.
	* @param {Boolean} scroll True to allow the Component to auto scroll.
	* @return {Ext.BoxComponent} this
	*/
	setAutoScroll: function (scroll) {
		if (this.rendered) {
			this.getContentTarget().setOverflow(scroll ? 'auto' : '');
		}
		this.autoScroll = scroll;
		return this;
	},

	/**
	* Sets the left and top of the component.  To set the page XY position instead, use {@link #setPagePosition}.
	* This method fires the {@link #move} event.
	* @param {Number} left The new left
	* @param {Number} top The new top
	* @return {Ext.BoxComponent} this
	*/
	setPosition: function (x, y) {
		if (x && typeof x[1] == 'number') {
			y = x[1];
			x = x[0];
		}
		this.x = x;
		this.y = y;
		if (!this.boxReady) {
			return this;
		}
		var adj = this.adjustPosition(x, y);
		var ax = adj.x, ay = adj.y;

		var el = this.getPositionEl();
		if (ax !== undefined || ay !== undefined) {
			if (ax !== undefined && ay !== undefined) {
				el.setLeftTop(ax, ay);
			} else if (ax !== undefined) {
				el.setLeft(ax);
			} else if (ay !== undefined) {
				el.setTop(ay);
			}
			this.onPosition(ax, ay);
			this.fireEvent('move', this, ax, ay);
		}
		return this;
	},

	/**
	* Sets the page XY position of the component.  To set the left and top instead, use {@link #setPosition}.
	* This method fires the {@link #move} event.
	* @param {Number} x The new x position
	* @param {Number} y The new y position
	* @return {Ext.BoxComponent} this
	*/
	setPagePosition: function (x, y) {
		if (x && typeof x[1] == 'number') {
			y = x[1];
			x = x[0];
		}
		this.pageX = x;
		this.pageY = y;
		if (!this.boxReady) {
			return;
		}
		if (x === undefined || y === undefined) { // cannot translate undefined points
			return;
		}
		var p = this.getPositionEl().translatePoints(x, y);
		this.setPosition(p.left, p.top);
		return this;
	},

	// private
	afterRender: function () {
		Ext.BoxComponent.superclass.afterRender.call(this);
		if (this.resizeEl) {
			this.resizeEl = Ext.get(this.resizeEl);
		}
		if (this.positionEl) {
			this.positionEl = Ext.get(this.positionEl);
		}
		this.boxReady = true;
		Ext.isDefined(this.autoScroll) && this.setAutoScroll(this.autoScroll);
		this.setSize(this.width, this.height);
		if (this.x || this.y) {
			this.setPosition(this.x, this.y);
		} else if (this.pageX || this.pageY) {
			this.setPagePosition(this.pageX, this.pageY);
		}
	},

	/**
	* Force the component's size to recalculate based on the underlying element's current height and width.
	* @return {Ext.BoxComponent} this
	*/
	syncSize: function () {
		delete this.lastSize;
		this.setSize(this.autoWidth ? undefined : this.getResizeEl().getWidth(), this.autoHeight ? undefined : this.getResizeEl().getHeight());
		return this;
	},

	/* // protected
	* Called after the component is resized, this method is empty by default but can be implemented by any
	* subclass that needs to perform custom logic after a resize occurs.
	* @param {Number} adjWidth The box-adjusted width that was set
	* @param {Number} adjHeight The box-adjusted height that was set
	* @param {Number} rawWidth The width that was originally specified
	* @param {Number} rawHeight The height that was originally specified
	*/
	onResize: function (adjWidth, adjHeight, rawWidth, rawHeight) {
	},

	/* // protected
	* Called after the component is moved, this method is empty by default but can be implemented by any
	* subclass that needs to perform custom logic after a move occurs.
	* @param {Number} x The new x position
	* @param {Number} y The new y position
	*/
	onPosition: function (x, y) {

	},

	// private
	adjustSize: function (w, h) {
		if (this.autoWidth) {
			w = 'auto';
		}
		if (this.autoHeight) {
			h = 'auto';
		}
		return { width: w, height: h };
	},

	// private
	adjustPosition: function (x, y) {
		return { x: x, y: y };
	}
});
Ext.reg('box', Ext.BoxComponent);


/**
* @class Ext.Spacer
* @extends Ext.BoxComponent
* <p>Used to provide a sizable space in a layout.</p>
* @constructor
* @param {Object} config
*/
Ext.Spacer = Ext.extend(Ext.BoxComponent, {
	autoEl: 'div'
});
Ext.reg('spacer', Ext.Spacer); /**
 * @class Ext.SplitBar
 * @extends Ext.util.Observable
 * Creates draggable splitter bar functionality from two elements (element to be dragged and element to be resized).
 * <br><br>
 * Usage:
 * <pre><code>
var split = new Ext.SplitBar("elementToDrag", "elementToSize",
                   Ext.SplitBar.HORIZONTAL, Ext.SplitBar.LEFT);
split.setAdapter(new Ext.SplitBar.AbsoluteLayoutAdapter("container"));
split.minSize = 100;
split.maxSize = 600;
split.animate = true;
split.on('moved', splitterMoved);
</code></pre>
 * @constructor
 * Create a new SplitBar
 * @param {Mixed} dragElement The element to be dragged and act as the SplitBar.
 * @param {Mixed} resizingElement The element to be resized based on where the SplitBar element is dragged
 * @param {Number} orientation (optional) Either Ext.SplitBar.HORIZONTAL or Ext.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
 * @param {Number} placement (optional) Either Ext.SplitBar.LEFT or Ext.SplitBar.RIGHT for horizontal or
                        Ext.SplitBar.TOP or Ext.SplitBar.BOTTOM for vertical. (By default, this is determined automatically by the initial
                        position of the SplitBar).
 */
Ext.SplitBar = function (dragElement, resizingElement, orientation, placement, existingProxy) {

	/** @private */
	this.el = Ext.get(dragElement, true);
	this.el.dom.unselectable = "on";
	/** @private */
	this.resizingEl = Ext.get(resizingElement, true);

	/**
	* @private
	* The orientation of the split. Either Ext.SplitBar.HORIZONTAL or Ext.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
	* Note: If this is changed after creating the SplitBar, the placement property must be manually updated
	* @type Number
	*/
	this.orientation = orientation || Ext.SplitBar.HORIZONTAL;

	/**
	* The increment, in pixels by which to move this SplitBar. When <i>undefined</i>, the SplitBar moves smoothly.
	* @type Number
	* @property tickSize
	*/
	/**
	* The minimum size of the resizing element. (Defaults to 0)
	* @type Number
	*/
	this.minSize = 0;

	/**
	* The maximum size of the resizing element. (Defaults to 2000)
	* @type Number
	*/
	this.maxSize = 2000;

	/**
	* Whether to animate the transition to the new size
	* @type Boolean
	*/
	this.animate = false;

	/**
	* Whether to create a transparent shim that overlays the page when dragging, enables dragging across iframes.
	* @type Boolean
	*/
	this.useShim = false;

	/** @private */
	this.shim = null;

	if (!existingProxy) {
		/** @private */
		this.proxy = Ext.SplitBar.createProxy(this.orientation);
	} else {
		this.proxy = Ext.get(existingProxy).dom;
	}
	/** @private */
	this.dd = new Ext.dd.DDProxy(this.el.dom.id, "XSplitBars", { dragElId: this.proxy.id });

	/** @private */
	this.dd.b4StartDrag = this.onStartProxyDrag.createDelegate(this);

	/** @private */
	this.dd.endDrag = this.onEndProxyDrag.createDelegate(this);

	/** @private */
	this.dragSpecs = {};

	/**
	* @private The adapter to use to positon and resize elements
	*/
	this.adapter = new Ext.SplitBar.BasicLayoutAdapter();
	this.adapter.init(this);

	if (this.orientation == Ext.SplitBar.HORIZONTAL) {
		/** @private */
		this.placement = placement || (this.el.getX() > this.resizingEl.getX() ? Ext.SplitBar.LEFT : Ext.SplitBar.RIGHT);
		this.el.addClass("x-splitbar-h");
	} else {
		/** @private */
		this.placement = placement || (this.el.getY() > this.resizingEl.getY() ? Ext.SplitBar.TOP : Ext.SplitBar.BOTTOM);
		this.el.addClass("x-splitbar-v");
	}

	this.addEvents(
	/**
	* @event resize
	* Fires when the splitter is moved (alias for {@link #moved})
	* @param {Ext.SplitBar} this
	* @param {Number} newSize the new width or height
	*/
        "resize",
	/**
	* @event moved
	* Fires when the splitter is moved
	* @param {Ext.SplitBar} this
	* @param {Number} newSize the new width or height
	*/
        "moved",
	/**
	* @event beforeresize
	* Fires before the splitter is dragged
	* @param {Ext.SplitBar} this
	*/
        "beforeresize",

        "beforeapply"
    );

	Ext.SplitBar.superclass.constructor.call(this);
};

Ext.extend(Ext.SplitBar, Ext.util.Observable, {
	onStartProxyDrag: function (x, y) {
		this.fireEvent("beforeresize", this);
		this.overlay = Ext.DomHelper.append(document.body, { cls: "x-drag-overlay", html: "&#160;" }, true);
		this.overlay.unselectable();
		this.overlay.setSize(Ext.lib.Dom.getViewWidth(true), Ext.lib.Dom.getViewHeight(true));
		this.overlay.show();
		Ext.get(this.proxy).setDisplayed("block");
		var size = this.adapter.getElementSize(this);
		this.activeMinSize = this.getMinimumSize();
		this.activeMaxSize = this.getMaximumSize();
		var c1 = size - this.activeMinSize;
		var c2 = Math.max(this.activeMaxSize - size, 0);
		if (this.orientation == Ext.SplitBar.HORIZONTAL) {
			this.dd.resetConstraints();
			this.dd.setXConstraint(
                this.placement == Ext.SplitBar.LEFT ? c1 : c2,
                this.placement == Ext.SplitBar.LEFT ? c2 : c1,
                this.tickSize
            );
			this.dd.setYConstraint(0, 0);
		} else {
			this.dd.resetConstraints();
			this.dd.setXConstraint(0, 0);
			this.dd.setYConstraint(
                this.placement == Ext.SplitBar.TOP ? c1 : c2,
                this.placement == Ext.SplitBar.TOP ? c2 : c1,
                this.tickSize
            );
		}
		this.dragSpecs.startSize = size;
		this.dragSpecs.startPoint = [x, y];
		Ext.dd.DDProxy.prototype.b4StartDrag.call(this.dd, x, y);
	},

	/**
	* @private Called after the drag operation by the DDProxy
	*/
	onEndProxyDrag: function (e) {
		Ext.get(this.proxy).setDisplayed(false);
		var endPoint = Ext.lib.Event.getXY(e);
		if (this.overlay) {
			Ext.destroy(this.overlay);
			delete this.overlay;
		}
		var newSize;
		if (this.orientation == Ext.SplitBar.HORIZONTAL) {
			newSize = this.dragSpecs.startSize +
                (this.placement == Ext.SplitBar.LEFT ?
                    endPoint[0] - this.dragSpecs.startPoint[0] :
                    this.dragSpecs.startPoint[0] - endPoint[0]
                );
		} else {
			newSize = this.dragSpecs.startSize +
                (this.placement == Ext.SplitBar.TOP ?
                    endPoint[1] - this.dragSpecs.startPoint[1] :
                    this.dragSpecs.startPoint[1] - endPoint[1]
                );
		}
		newSize = Math.min(Math.max(newSize, this.activeMinSize), this.activeMaxSize);
		if (newSize != this.dragSpecs.startSize) {
			if (this.fireEvent('beforeapply', this, newSize) !== false) {
				this.adapter.setElementSize(this, newSize);
				this.fireEvent("moved", this, newSize);
				this.fireEvent("resize", this, newSize);
			}
		}
	},

	/**
	* Get the adapter this SplitBar uses
	* @return The adapter object
	*/
	getAdapter: function () {
		return this.adapter;
	},

	/**
	* Set the adapter this SplitBar uses
	* @param {Object} adapter A SplitBar adapter object
	*/
	setAdapter: function (adapter) {
		this.adapter = adapter;
		this.adapter.init(this);
	},

	/**
	* Gets the minimum size for the resizing element
	* @return {Number} The minimum size
	*/
	getMinimumSize: function () {
		return this.minSize;
	},

	/**
	* Sets the minimum size for the resizing element
	* @param {Number} minSize The minimum size
	*/
	setMinimumSize: function (minSize) {
		this.minSize = minSize;
	},

	/**
	* Gets the maximum size for the resizing element
	* @return {Number} The maximum size
	*/
	getMaximumSize: function () {
		return this.maxSize;
	},

	/**
	* Sets the maximum size for the resizing element
	* @param {Number} maxSize The maximum size
	*/
	setMaximumSize: function (maxSize) {
		this.maxSize = maxSize;
	},

	/**
	* Sets the initialize size for the resizing element
	* @param {Number} size The initial size
	*/
	setCurrentSize: function (size) {
		var oldAnimate = this.animate;
		this.animate = false;
		this.adapter.setElementSize(this, size);
		this.animate = oldAnimate;
	},

	/**
	* Destroy this splitbar.
	* @param {Boolean} removeEl True to remove the element
	*/
	destroy: function (removeEl) {
		Ext.destroy(this.shim, Ext.get(this.proxy));
		this.dd.unreg();
		if (removeEl) {
			this.el.remove();
		}
		this.purgeListeners();
	}
});

/**
* @private static Create our own proxy element element. So it will be the same same size on all browsers, we won't use borders. Instead we use a background color.
*/
Ext.SplitBar.createProxy = function (dir) {
	var proxy = new Ext.Element(document.createElement("div"));
	document.body.appendChild(proxy.dom);
	proxy.unselectable();
	var cls = 'x-splitbar-proxy';
	proxy.addClass(cls + ' ' + (dir == Ext.SplitBar.HORIZONTAL ? cls + '-h' : cls + '-v'));
	return proxy.dom;
};

/**
* @class Ext.SplitBar.BasicLayoutAdapter
* Default Adapter. It assumes the splitter and resizing element are not positioned
* elements and only gets/sets the width of the element. Generally used for table based layouts.
*/
Ext.SplitBar.BasicLayoutAdapter = function () {
};

Ext.SplitBar.BasicLayoutAdapter.prototype = {
	// do nothing for now
	init: function (s) {

	},
	/**
	* Called before drag operations to get the current size of the resizing element.
	* @param {Ext.SplitBar} s The SplitBar using this adapter
	*/
	getElementSize: function (s) {
		if (s.orientation == Ext.SplitBar.HORIZONTAL) {
			return s.resizingEl.getWidth();
		} else {
			return s.resizingEl.getHeight();
		}
	},

	/**
	* Called after drag operations to set the size of the resizing element.
	* @param {Ext.SplitBar} s The SplitBar using this adapter
	* @param {Number} newSize The new size to set
	* @param {Function} onComplete A function to be invoked when resizing is complete
	*/
	setElementSize: function (s, newSize, onComplete) {
		if (s.orientation == Ext.SplitBar.HORIZONTAL) {
			if (!s.animate) {
				s.resizingEl.setWidth(newSize);
				if (onComplete) {
					onComplete(s, newSize);
				}
			} else {
				s.resizingEl.setWidth(newSize, true, .1, onComplete, 'easeOut');
			}
		} else {

			if (!s.animate) {
				s.resizingEl.setHeight(newSize);
				if (onComplete) {
					onComplete(s, newSize);
				}
			} else {
				s.resizingEl.setHeight(newSize, true, .1, onComplete, 'easeOut');
			}
		}
	}
};

/**
*@class Ext.SplitBar.AbsoluteLayoutAdapter
* @extends Ext.SplitBar.BasicLayoutAdapter
* Adapter that  moves the splitter element to align with the resized sizing element.
* Used with an absolute positioned SplitBar.
* @param {Mixed} container The container that wraps around the absolute positioned content. If it's
* document.body, make sure you assign an id to the body element.
*/
Ext.SplitBar.AbsoluteLayoutAdapter = function (container) {
	this.basic = new Ext.SplitBar.BasicLayoutAdapter();
	this.container = Ext.get(container);
};

Ext.SplitBar.AbsoluteLayoutAdapter.prototype = {
	init: function (s) {
		this.basic.init(s);
	},

	getElementSize: function (s) {
		return this.basic.getElementSize(s);
	},

	setElementSize: function (s, newSize, onComplete) {
		this.basic.setElementSize(s, newSize, this.moveSplitter.createDelegate(this, [s]));
	},

	moveSplitter: function (s) {
		var yes = Ext.SplitBar;
		switch (s.placement) {
			case yes.LEFT:
				s.el.setX(s.resizingEl.getRight());
				break;
			case yes.RIGHT:
				s.el.setStyle("right", (this.container.getWidth() - s.resizingEl.getLeft()) + "px");
				break;
			case yes.TOP:
				s.el.setY(s.resizingEl.getBottom());
				break;
			case yes.BOTTOM:
				s.el.setY(s.resizingEl.getTop() - s.el.getHeight());
				break;
		}
	}
};

/**
* Orientation constant - Create a vertical SplitBar
* @static
* @type Number
*/
Ext.SplitBar.VERTICAL = 1;

/**
* Orientation constant - Create a horizontal SplitBar
* @static
* @type Number
*/
Ext.SplitBar.HORIZONTAL = 2;

/**
* Placement constant - The resizing element is to the left of the splitter element
* @static
* @type Number
*/
Ext.SplitBar.LEFT = 1;

/**
* Placement constant - The resizing element is to the right of the splitter element
* @static
* @type Number
*/
Ext.SplitBar.RIGHT = 2;

/**
* Placement constant - The resizing element is positioned above the splitter element
* @static
* @type Number
*/
Ext.SplitBar.TOP = 3;

/**
* Placement constant - The resizing element is positioned under splitter element
* @static
* @type Number
*/
Ext.SplitBar.BOTTOM = 4;
/**
* @class Ext.Container
* @extends Ext.BoxComponent
* <p>Base class for any {@link Ext.BoxComponent} that may contain other Components. Containers handle the
* basic behavior of containing items, namely adding, inserting and removing items.</p>
*
* <p>The most commonly used Container classes are {@link Ext.Panel}, {@link Ext.Window} and {@link Ext.TabPanel}.
* If you do not need the capabilities offered by the aforementioned classes you can create a lightweight
* Container to be encapsulated by an HTML element to your specifications by using the
* <code><b>{@link Ext.Component#autoEl autoEl}</b></code> config option. This is a useful technique when creating
* embedded {@link Ext.layout.ColumnLayout column} layouts inside {@link Ext.form.FormPanel FormPanels}
* for example.</p>
*
* <p>The code below illustrates both how to explicitly create a Container, and how to implicitly
* create one using the <b><code>'container'</code></b> xtype:<pre><code>
// explicitly create a Container
var embeddedColumns = new Ext.Container({
autoEl: 'div',  // This is the default
layout: 'column',
defaults: {
// implicitly create Container by specifying xtype
xtype: 'container',
autoEl: 'div', // This is the default.
layout: 'form',
columnWidth: 0.5,
style: {
padding: '10px'
}
},
//  The two items below will be Ext.Containers, each encapsulated by a &lt;DIV> element.
items: [{
items: {
xtype: 'datefield',
name: 'startDate',
fieldLabel: 'Start date'
}
}, {
items: {
xtype: 'datefield',
name: 'endDate',
fieldLabel: 'End date'
}
}]
});</code></pre></p>
*
* <p><u><b>Layout</b></u></p>
* <p>Container classes delegate the rendering of child Components to a layout
* manager class which must be configured into the Container using the
* <code><b>{@link #layout}</b></code> configuration property.</p>
* <p>When either specifying child <code>{@link #items}</code> of a Container,
* or dynamically {@link #add adding} Components to a Container, remember to
* consider how you wish the Container to arrange those child elements, and
* whether those child elements need to be sized using one of Ext's built-in
* <b><code>{@link #layout}</code></b> schemes. By default, Containers use the
* {@link Ext.layout.ContainerLayout ContainerLayout} scheme which only
* renders child components, appending them one after the other inside the
* Container, and <b>does not apply any sizing</b> at all.</p>
* <p>A common mistake is when a developer neglects to specify a
* <b><code>{@link #layout}</code></b> (e.g. widgets like GridPanels or
* TreePanels are added to Containers for which no <code><b>{@link #layout}</b></code>
* has been specified). If a Container is left to use the default
* {@link Ext.layout.ContainerLayout ContainerLayout} scheme, none of its
* child components will be resized, or changed in any way when the Container
* is resized.</p>
* <p>Certain layout managers allow dynamic addition of child components.
* Those that do include {@link Ext.layout.CardLayout},
* {@link Ext.layout.AnchorLayout}, {@link Ext.layout.FormLayout}, and
* {@link Ext.layout.TableLayout}. For example:<pre><code>
//  Create the GridPanel.
var myNewGrid = new Ext.grid.GridPanel({
store: myStore,
columns: myColumnModel,
title: 'Results', // the title becomes the title of the tab
});

myTabPanel.add(myNewGrid); // {@link Ext.TabPanel} implicitly uses {@link Ext.layout.CardLayout CardLayout}
myTabPanel.{@link Ext.TabPanel#setActiveTab setActiveTab}(myNewGrid);
* </code></pre></p>
* <p>The example above adds a newly created GridPanel to a TabPanel. Note that
* a TabPanel uses {@link Ext.layout.CardLayout} as its layout manager which
* means all its child items are sized to {@link Ext.layout.FitLayout fit}
* exactly into its client area.
* <p><b><u>Overnesting is a common problem</u></b>.
* An example of overnesting occurs when a GridPanel is added to a TabPanel
* by wrapping the GridPanel <i>inside</i> a wrapping Panel (that has no
* <code><b>{@link #layout}</b></code> specified) and then add that wrapping Panel
* to the TabPanel. The point to realize is that a GridPanel <b>is</b> a
* Component which can be added directly to a Container. If the wrapping Panel
* has no <code><b>{@link #layout}</b></code> configuration, then the overnested
* GridPanel will not be sized as expected.<p>
*
* <p><u><b>Adding via remote configuration</b></u></p>
*
* <p>A server side script can be used to add Components which are generated dynamically on the server.
* An example of adding a GridPanel to a TabPanel where the GridPanel is generated by the server
* based on certain parameters:
* </p><pre><code>
// execute an Ajax request to invoke server side script:
Ext.Ajax.request({
url: 'gen-invoice-grid.php',
// send additional parameters to instruct server script
params: {
startDate: Ext.getCmp('start-date').getValue(),
endDate: Ext.getCmp('end-date').getValue()
},
// process the response object to add it to the TabPanel:
success: function(xhr) {
var newComponent = eval(xhr.responseText); // see discussion below
myTabPanel.add(newComponent); // add the component to the TabPanel
myTabPanel.setActiveTab(newComponent);
},
failure: function() {
Ext.Msg.alert("Grid create failed", "Server communication failure");
}
});
</code></pre>
* <p>The server script needs to return an executable Javascript statement which, when processed
* using <code>eval()</code>, will return either a config object with an {@link Ext.Component#xtype xtype},
* or an instantiated Component. The server might return this for example:</p><pre><code>
(function() {
function formatDate(value){
return value ? value.dateFormat('M d, Y') : '';
};

var store = new Ext.data.Store({
url: 'get-invoice-data.php',
baseParams: {
startDate: '01/01/2008',
endDate: '01/31/2008'
},
reader: new Ext.data.JsonReader({
record: 'transaction',
idProperty: 'id',
totalRecords: 'total'
}, [
'customer',
'invNo',
{name: 'date', type: 'date', dateFormat: 'm/d/Y'},
{name: 'value', type: 'float'}
])
});

var grid = new Ext.grid.GridPanel({
title: 'Invoice Report',
bbar: new Ext.PagingToolbar(store),
store: store,
columns: [
{header: "Customer", width: 250, dataIndex: 'customer', sortable: true},
{header: "Invoice Number", width: 120, dataIndex: 'invNo', sortable: true},
{header: "Invoice Date", width: 100, dataIndex: 'date', renderer: formatDate, sortable: true},
{header: "Value", width: 120, dataIndex: 'value', renderer: 'usMoney', sortable: true}
],
});
store.load();
return grid;  // return instantiated component
})();
</code></pre>
* <p>When the above code fragment is passed through the <code>eval</code> function in the success handler
* of the Ajax request, the code is executed by the Javascript processor, and the anonymous function
* runs, and returns the instantiated grid component.</p>
* <p>Note: since the code above is <i>generated</i> by a server script, the <code>baseParams</code> for
* the Store, the metadata to allow generation of the Record layout, and the ColumnModel
* can all be generated into the code since these are all known on the server.</p>
*
* @xtype container
*/
Ext.Container = Ext.extend(Ext.BoxComponent, {
	/**
	* @cfg {Boolean} monitorResize
	* True to automatically monitor window resize events to handle anything that is sensitive to the current size
	* of the viewport.  This value is typically managed by the chosen <code>{@link #layout}</code> and should not need
	* to be set manually.
	*/
	/**
	* @cfg {String/Object} layout
	* <p><b>*Important</b>: In order for child items to be correctly sized and
	* positioned, typically a layout manager <b>must</b> be specified through
	* the <code>layout</code> configuration option.</p>
	* <br><p>The sizing and positioning of child {@link items} is the responsibility of
	* the Container's layout manager which creates and manages the type of layout
	* you have in mind.  For example:</p><pre><code>
	new Ext.Window({
	width:300, height: 300,
	layout: 'fit', // explicitly set layout manager: override the default (layout:'auto')
	items: [{
	title: 'Panel inside a Window'
	}]
	}).show();
	* </code></pre>
	* <p>If the {@link #layout} configuration is not explicitly specified for
	* a general purpose container (e.g. Container or Panel) the
	* {@link Ext.layout.ContainerLayout default layout manager} will be used
	* which does nothing but render child components sequentially into the
	* Container (no sizing or positioning will be performed in this situation).
	* Some container classes implicitly specify a default layout
	* (e.g. FormPanel specifies <code>layout:'form'</code>). Other specific
	* purpose classes internally specify/manage their internal layout (e.g.
	* GridPanel, TabPanel, TreePanel, Toolbar, Menu, etc.).</p>
	* <br><p><b><code>layout</code></b> may be specified as either as an Object or
	* as a String:</p><div><ul class="mdetail-params">
	*
	* <li><u>Specify as an Object</u></li>
	* <div><ul class="mdetail-params">
	* <li>Example usage:</li>
	<pre><code>
	layout: {
	type: 'vbox',
	padding: '5',
	align: 'left'
	}
	</code></pre>
	*
	* <li><code><b>type</b></code></li>
	* <br/><p>The layout type to be used for this container.  If not specified,
	* a default {@link Ext.layout.ContainerLayout} will be created and used.</p>
	* <br/><p>Valid layout <code>type</code> values are:</p>
	* <div class="sub-desc"><ul class="mdetail-params">
	* <li><code><b>{@link Ext.layout.AbsoluteLayout absolute}</b></code></li>
	* <li><code><b>{@link Ext.layout.AccordionLayout accordion}</b></code></li>
	* <li><code><b>{@link Ext.layout.AnchorLayout anchor}</b></code></li>
	* <li><code><b>{@link Ext.layout.ContainerLayout auto}</b></code> &nbsp;&nbsp;&nbsp; <b>Default</b></li>
	* <li><code><b>{@link Ext.layout.BorderLayout border}</b></code></li>
	* <li><code><b>{@link Ext.layout.CardLayout card}</b></code></li>
	* <li><code><b>{@link Ext.layout.ColumnLayout column}</b></code></li>
	* <li><code><b>{@link Ext.layout.FitLayout fit}</b></code></li>
	* <li><code><b>{@link Ext.layout.FormLayout form}</b></code></li>
	* <li><code><b>{@link Ext.layout.HBoxLayout hbox}</b></code></li>
	* <li><code><b>{@link Ext.layout.MenuLayout menu}</b></code></li>
	* <li><code><b>{@link Ext.layout.TableLayout table}</b></code></li>
	* <li><code><b>{@link Ext.layout.ToolbarLayout toolbar}</b></code></li>
	* <li><code><b>{@link Ext.layout.VBoxLayout vbox}</b></code></li>
	* </ul></div>
	*
	* <li>Layout specific configuration properties</li>
	* <br/><p>Additional layout specific configuration properties may also be
	* specified. For complete details regarding the valid config options for
	* each layout type, see the layout class corresponding to the <code>type</code>
	* specified.</p>
	*
	* </ul></div>
	*
	* <li><u>Specify as a String</u></li>
	* <div><ul class="mdetail-params">
	* <li>Example usage:</li>
	<pre><code>
	layout: 'vbox',
	layoutConfig: {
	padding: '5',
	align: 'left'
	}
	</code></pre>
	* <li><code><b>layout</b></code></li>
	* <br/><p>The layout <code>type</code> to be used for this container (see list
	* of valid layout type values above).</p><br/>
	* <li><code><b>{@link #layoutConfig}</b></code></li>
	* <br/><p>Additional layout specific configuration properties. For complete
	* details regarding the valid config options for each layout type, see the
	* layout class corresponding to the <code>layout</code> specified.</p>
	* </ul></div></ul></div>
	*/
	/**
	* @cfg {Object} layoutConfig
	* This is a config object containing properties specific to the chosen
	* <b><code>{@link #layout}</code></b> if <b><code>{@link #layout}</code></b>
	* has been specified as a <i>string</i>.</p>
	*/
	/**
	* @cfg {Boolean/Number} bufferResize
	* When set to true (50 milliseconds) or a number of milliseconds, the layout assigned for this container will buffer
	* the frequency it calculates and does a re-layout of components. This is useful for heavy containers or containers
	* with a large quantity of sub-components for which frequent layout calls would be expensive. Defaults to <code>50</code>.
	*/
	bufferResize: 50,

	/**
	* @cfg {String/Number} activeItem
	* A string component id or the numeric index of the component that should be initially activated within the
	* container's layout on render.  For example, activeItem: 'item-1' or activeItem: 0 (index 0 = the first
	* item in the container's collection).  activeItem only applies to layout styles that can display
	* items one at a time (like {@link Ext.layout.AccordionLayout}, {@link Ext.layout.CardLayout} and
	* {@link Ext.layout.FitLayout}).  Related to {@link Ext.layout.ContainerLayout#activeItem}.
	*/
	/**
	* @cfg {Object/Array} items
	* <pre><b>** IMPORTANT</b>: be sure to <b>{@link #layout specify a <code>layout</code>} if needed ! **</b></pre>
	* <p>A single item, or an array of child Components to be added to this container,
	* for example:</p>
	* <pre><code>
	// specifying a single item
	items: {...},
	layout: 'fit',    // specify a layout!

	// specifying multiple items
	items: [{...}, {...}],
	layout: 'anchor', // specify a layout!
	* </code></pre>
	* <p>Each item may be:</p>
	* <div><ul class="mdetail-params">
	* <li>any type of object based on {@link Ext.Component}</li>
	* <li>a fully instanciated object or</li>
	* <li>an object literal that:</li>
	* <div><ul class="mdetail-params">
	* <li>has a specified <code>{@link Ext.Component#xtype xtype}</code></li>
	* <li>the {@link Ext.Component#xtype} specified is associated with the Component
	* desired and should be chosen from one of the available xtypes as listed
	* in {@link Ext.Component}.</li>
	* <li>If an <code>{@link Ext.Component#xtype xtype}</code> is not explicitly
	* specified, the {@link #defaultType} for that Container is used.</li>
	* <li>will be "lazily instanciated", avoiding the overhead of constructing a fully
	* instanciated Component object</li>
	* </ul></div></ul></div>
	* <p><b>Notes</b>:</p>
	* <div><ul class="mdetail-params">
	* <li>Ext uses lazy rendering. Child Components will only be rendered
	* should it become necessary. Items are automatically laid out when they are first
	* shown (no sizing is done while hidden), or in response to a {@link #doLayout} call.</li>
	* <li>Do not specify <code>{@link Ext.Panel#contentEl contentEl}</code>/
	* <code>{@link Ext.Panel#html html}</code> with <code>items</code>.</li>
	* </ul></div>
	*/
	/**
	* @cfg {Object|Function} defaults
	* <p>This option is a means of applying default settings to all added items whether added through the {@link #items}
	* config or via the {@link #add} or {@link #insert} methods.</p>
	* <p>If an added item is a config object, and <b>not</b> an instantiated Component, then the default properties are
	* unconditionally applied. If the added item <b>is</b> an instantiated Component, then the default properties are
	* applied conditionally so as not to override existing properties in the item.</p>
	* <p>If the defaults option is specified as a function, then the function will be called using this Container as the
	* scope (<code>this</code> reference) and passing the added item as the first parameter. Any resulting object
	* from that call is then applied to the item as default properties.</p>
	* <p>For example, to automatically apply padding to the body of each of a set of
	* contained {@link Ext.Panel} items, you could pass: <code>defaults: {bodyStyle:'padding:15px'}</code>.</p>
	* <p>Usage:</p><pre><code>
	defaults: {               // defaults are applied to items, not the container
	autoScroll:true
	},
	items: [
	{
	xtype: 'panel',   // defaults <b>do not</b> have precedence over
	id: 'panel1',     // options in config objects, so the defaults
	autoScroll: false // will not be applied here, panel1 will be autoScroll:false
	},
	new Ext.Panel({       // defaults <b>do</b> have precedence over options
	id: 'panel2',     // options in components, so the defaults
	autoScroll: false // will be applied here, panel2 will be autoScroll:true.
	})
	]
	* </code></pre>
	*/


	/** @cfg {Boolean} autoDestroy
	* If true the container will automatically destroy any contained component that is removed from it, else
	* destruction must be handled manually (defaults to true).
	*/
	autoDestroy: true,

	/** @cfg {Boolean} forceLayout
	* If true the container will force a layout initially even if hidden or collapsed. This option
	* is useful for forcing forms to render in collapsed or hidden containers. (defaults to false).
	*/
	forceLayout: false,

	/** @cfg {Boolean} hideBorders
	* True to hide the borders of each contained component, false to defer to the component's existing
	* border settings (defaults to false).
	*/
	/** @cfg {String} defaultType
	* <p>The default {@link Ext.Component xtype} of child Components to create in this Container when
	* a child item is specified as a raw configuration object, rather than as an instantiated Component.</p>
	* <p>Defaults to <code>'panel'</code>, except {@link Ext.menu.Menu} which defaults to <code>'menuitem'</code>,
	* and {@link Ext.Toolbar} and {@link Ext.ButtonGroup} which default to <code>'button'</code>.</p>
	*/
	defaultType: 'panel',

	/** @cfg {String} resizeEvent
	* The event to listen to for resizing in layouts. Defaults to <code>'resize'</code>.
	*/
	resizeEvent: 'resize',

	/**
	* @cfg {Array} bubbleEvents
	* <p>An array of events that, when fired, should be bubbled to any parent container.
	* See {@link Ext.util.Observable#enableBubble}.
	* Defaults to <code>['add', 'remove']</code>.
	*/
	bubbleEvents: ['add', 'remove'],

	// private
	initComponent: function () {
		Ext.Container.superclass.initComponent.call(this);

		this.addEvents(
		/**
		* @event afterlayout
		* Fires when the components in this container are arranged by the associated layout manager.
		* @param {Ext.Container} this
		* @param {ContainerLayout} layout The ContainerLayout implementation for this container
		*/
            'afterlayout',
		/**
		* @event beforeadd
		* Fires before any {@link Ext.Component} is added or inserted into the container.
		* A handler can return false to cancel the add.
		* @param {Ext.Container} this
		* @param {Ext.Component} component The component being added
		* @param {Number} index The index at which the component will be added to the container's items collection
		*/
            'beforeadd',
		/**
		* @event beforeremove
		* Fires before any {@link Ext.Component} is removed from the container.  A handler can return
		* false to cancel the remove.
		* @param {Ext.Container} this
		* @param {Ext.Component} component The component being removed
		*/
            'beforeremove',
		/**
		* @event add
		* @bubbles
		* Fires after any {@link Ext.Component} is added or inserted into the container.
		* @param {Ext.Container} this
		* @param {Ext.Component} component The component that was added
		* @param {Number} index The index at which the component was added to the container's items collection
		*/
            'add',
		/**
		* @event remove
		* @bubbles
		* Fires after any {@link Ext.Component} is removed from the container.
		* @param {Ext.Container} this
		* @param {Ext.Component} component The component that was removed
		*/
            'remove'
        );

		/**
		* The collection of components in this container as a {@link Ext.util.MixedCollection}
		* @type MixedCollection
		* @property items
		*/
		var items = this.items;
		if (items) {
			delete this.items;
			this.add(items);
		}
	},

	// private
	initItems: function () {
		if (!this.items) {
			this.items = new Ext.util.MixedCollection(false, this.getComponentId);
			this.getLayout(); // initialize the layout
		}
	},

	// private
	setLayout: function (layout) {
		if (this.layout && this.layout != layout) {
			this.layout.setContainer(null);
		}
		this.layout = layout;
		this.initItems();
		layout.setContainer(this);
	},

	afterRender: function () {
		// Render this Container, this should be done before setLayout is called which
		// will hook onResize
		Ext.Container.superclass.afterRender.call(this);
		if (!this.layout) {
			this.layout = 'auto';
		}
		if (Ext.isObject(this.layout) && !this.layout.layout) {
			this.layoutConfig = this.layout;
			this.layout = this.layoutConfig.type;
		}
		if (Ext.isString(this.layout)) {
			this.layout = new Ext.Container.LAYOUTS[this.layout.toLowerCase()](this.layoutConfig);
		}
		this.setLayout(this.layout);

		// If a CardLayout, the active item set
		if (this.activeItem !== undefined) {
			var item = this.activeItem;
			delete this.activeItem;
			this.layout.setActiveItem(item);
		}

		// If we have no ownerCt, render and size all children
		if (!this.ownerCt) {
			this.doLayout(false, true);
		}

		// This is a manually configured flag set by users in conjunction with renderTo.
		// Not to be confused with the flag by the same name used in Layouts.
		if (this.monitorResize === true) {
			Ext.EventManager.onWindowResize(this.doLayout, this, [false]);
		}
	},

	/**
	* <p>Returns the Element to be used to contain the child Components of this Container.</p>
	* <p>An implementation is provided which returns the Container's {@link #getEl Element}, but
	* if there is a more complex structure to a Container, this may be overridden to return
	* the element into which the {@link #layout layout} renders child Components.</p>
	* @return {Ext.Element} The Element to render child Components into.
	*/
	getLayoutTarget: function () {
		return this.el;
	},

	// private - used as the key lookup function for the items collection
	getComponentId: function (comp) {
		return comp.getItemId();
	},

	/**
	* <p>Adds {@link Ext.Component Component}(s) to this Container.</p>
	* <br><p><b>Description</b></u> :
	* <div><ul class="mdetail-params">
	* <li>Fires the {@link #beforeadd} event before adding</li>
	* <li>The Container's {@link #defaults default config values} will be applied
	* accordingly (see <code>{@link #defaults}</code> for details).</li>
	* <li>Fires the {@link #add} event after the component has been added.</li>
	* </ul></div>
	* <br><p><b>Notes</b></u> :
	* <div><ul class="mdetail-params">
	* <li>If the Container is <i>already rendered</i> when <code>add</code>
	* is called, you may need to call {@link #doLayout} to refresh the view which causes
	* any unrendered child Components to be rendered. This is required so that you can
	* <code>add</code> multiple child components if needed while only refreshing the layout
	* once. For example:<pre><code>
	var tb = new {@link Ext.Toolbar}();
	tb.render(document.body);  // toolbar is rendered
	tb.add({text:'Button 1'}); // add multiple items ({@link #defaultType} for {@link Ext.Toolbar Toolbar} is 'button')
	tb.add({text:'Button 2'});
	tb.{@link #doLayout}();             // refresh the layout
	* </code></pre></li>
	* <li><i>Warning:</i> Containers directly managed by the BorderLayout layout manager
	* may not be removed or added.  See the Notes for {@link Ext.layout.BorderLayout BorderLayout}
	* for more details.</li>
	* </ul></div>
	* @param {...Object/Array} component
	* <p>Either one or more Components to add or an Array of Components to add.  See
	* <code>{@link #items}</code> for additional information.</p>
	* @return {Ext.Component/Array} The Components that were added.
	*/
	add: function (comp) {
		this.initItems();
		var args = arguments.length > 1;
		if (args || Ext.isArray(comp)) {
			var result = [];
			Ext.each(args ? arguments : comp, function (c) {
				result.push(this.add(c));
			}, this);
			return result;
		}
		var c = this.lookupComponent(this.applyDefaults(comp));
		var index = this.items.length;
		if (this.fireEvent('beforeadd', this, c, index) !== false && this.onBeforeAdd(c) !== false) {
			this.items.add(c);
			// *onAdded
			c.onAdded(this, index);
			this.onAdd(c);
			this.fireEvent('add', this, c, index);
		}
		return c;
	},

	onAdd: function (c) {
		// Empty template method
	},

	// private
	onAdded: function (container, pos) {
		//overridden here so we can cascade down, not worth creating a template method.
		this.ownerCt = container;
		this.initRef();
		//initialize references for child items
		this.cascade(function (c) {
			c.initRef();
		});
		this.fireEvent('added', this, container, pos);
	},

	/**
	* Inserts a Component into this Container at a specified index. Fires the
	* {@link #beforeadd} event before inserting, then fires the {@link #add} event after the
	* Component has been inserted.
	* @param {Number} index The index at which the Component will be inserted
	* into the Container's items collection
	* @param {Ext.Component} component The child Component to insert.<br><br>
	* Ext uses lazy rendering, and will only render the inserted Component should
	* it become necessary.<br><br>
	* A Component config object may be passed in order to avoid the overhead of
	* constructing a real Component object if lazy rendering might mean that the
	* inserted Component will not be rendered immediately. To take advantage of
	* this 'lazy instantiation', set the {@link Ext.Component#xtype} config
	* property to the registered type of the Component wanted.<br><br>
	* For a list of all available xtypes, see {@link Ext.Component}.
	* @return {Ext.Component} component The Component (or config object) that was
	* inserted with the Container's default config values applied.
	*/
	insert: function (index, comp) {
		this.initItems();
		var a = arguments, len = a.length;
		if (len > 2) {
			var result = [];
			for (var i = len - 1; i >= 1; --i) {
				result.push(this.insert(index, a[i]));
			}
			return result;
		}
		var c = this.lookupComponent(this.applyDefaults(comp));
		index = Math.min(index, this.items.length);
		if (this.fireEvent('beforeadd', this, c, index) !== false && this.onBeforeAdd(c) !== false) {
			if (c.ownerCt == this) {
				this.items.remove(c);
			}
			this.items.insert(index, c);
			c.onAdded(this, index);
			this.onAdd(c);
			this.fireEvent('add', this, c, index);
		}
		return c;
	},

	// private
	applyDefaults: function (c) {
		var d = this.defaults;
		if (d) {
			if (Ext.isFunction(d)) {
				d = d.call(this, c);
			}
			if (Ext.isString(c)) {
				c = Ext.ComponentMgr.get(c);
				Ext.apply(c, d);
			} else if (!c.events) {
				Ext.applyIf(c, d);
			} else {
				Ext.apply(c, d);
			}
		}
		return c;
	},

	// private
	onBeforeAdd: function (item) {
		if (item.ownerCt) {
			item.ownerCt.remove(item, false);
		}
		if (this.hideBorders === true) {
			item.border = (item.border === true);
		}
	},

	/**
	* Removes a component from this container.  Fires the {@link #beforeremove} event before removing, then fires
	* the {@link #remove} event after the component has been removed.
	* @param {Component/String} component The component reference or id to remove.
	* @param {Boolean} autoDestroy (optional) True to automatically invoke the removed Component's {@link Ext.Component#destroy} function.
	* Defaults to the value of this Container's {@link #autoDestroy} config.
	* @return {Ext.Component} component The Component that was removed.
	*/
	remove: function (comp, autoDestroy) {
		this.initItems();
		var c = this.getComponent(comp);
		if (c && this.fireEvent('beforeremove', this, c) !== false) {
			this.doRemove(c, autoDestroy);
			this.fireEvent('remove', this, c);
		}
		return c;
	},

	onRemove: function (c) {
		// Empty template method
	},

	// private
	doRemove: function (c, autoDestroy) {
		var l = this.layout,
            hasLayout = l && this.rendered;

		if (hasLayout) {
			l.onRemove(c);
		}
		this.items.remove(c);
		c.onRemoved();
		this.onRemove(c);
		if (autoDestroy === true || (autoDestroy !== false && this.autoDestroy)) {
			c.destroy();
		}
		if (hasLayout) {
			l.afterRemove(c);
		}
	},

	/**
	* Removes all components from this container.
	* @param {Boolean} autoDestroy (optional) True to automatically invoke the removed Component's {@link Ext.Component#destroy} function.
	* Defaults to the value of this Container's {@link #autoDestroy} config.
	* @return {Array} Array of the destroyed components
	*/
	removeAll: function (autoDestroy) {
		this.initItems();
		var item, rem = [], items = [];
		this.items.each(function (i) {
			rem.push(i);
		});
		for (var i = 0, len = rem.length; i < len; ++i) {
			item = rem[i];
			this.remove(item, autoDestroy);
			if (item.ownerCt !== this) {
				items.push(item);
			}
		}
		return items;
	},

	/**
	* Examines this container's <code>{@link #items}</code> <b>property</b>
	* and gets a direct child component of this container.
	* @param {String/Number} comp This parameter may be any of the following:
	* <div><ul class="mdetail-params">
	* <li>a <b><code>String</code></b> : representing the <code>{@link Ext.Component#itemId itemId}</code>
	* or <code>{@link Ext.Component#id id}</code> of the child component </li>
	* <li>a <b><code>Number</code></b> : representing the position of the child component
	* within the <code>{@link #items}</code> <b>property</b></li>
	* </ul></div>
	* <p>For additional information see {@link Ext.util.MixedCollection#get}.
	* @return Ext.Component The component (if found).
	*/
	getComponent: function (comp) {
		if (Ext.isObject(comp)) {
			comp = comp.getItemId();
		}
		return this.items.get(comp);
	},

	// private
	lookupComponent: function (comp) {
		if (Ext.isString(comp)) {
			return Ext.ComponentMgr.get(comp);
		} else if (!comp.events) {
			return this.createComponent(comp);
		}
		return comp;
	},

	// private
	createComponent: function (config, defaultType) {
		if (config.render) {
			return config;
		}
		// add in ownerCt at creation time but then immediately
		// remove so that onBeforeAdd can handle it
		var c = Ext.create(Ext.apply({
			ownerCt: this
		}, config), defaultType || this.defaultType);
		delete c.initialConfig.ownerCt;
		delete c.ownerCt;
		return c;
	},

	/**
	* @private
	* We can only lay out if there is a view area in which to layout.
	* display:none on the layout target, *or any of its parent elements* will mean it has no view area.
	*/
	canLayout: function () {
		var el = this.getVisibilityEl();
		return el && el.dom && !el.isStyle("display", "none");
	},

	/**
	* Force this container's layout to be recalculated. A call to this function is required after adding a new component
	* to an already rendered container, or possibly after changing sizing/position properties of child components.
	* @param {Boolean} shallow (optional) True to only calc the layout of this component, and let child components auto
	* calc layouts as required (defaults to false, which calls doLayout recursively for each subcontainer)
	* @param {Boolean} force (optional) True to force a layout to occur, even if the item is hidden.
	* @return {Ext.Container} this
	*/

	doLayout: function (shallow, force) {
		var rendered = this.rendered,
            forceLayout = force || this.forceLayout;

		if (this.collapsed || !this.canLayout()) {
			this.deferLayout = this.deferLayout || !shallow;
			if (!forceLayout) {
				return;
			}
			shallow = shallow && !this.deferLayout;
		} else {
			delete this.deferLayout;
		}
		if (rendered && this.layout) {
			this.layout.layout();
		}
		if (shallow !== true && this.items) {
			var cs = this.items.items;
			for (var i = 0, len = cs.length; i < len; i++) {
				var c = cs[i];
				if (c.doLayout) {
					c.doLayout(false, forceLayout);
				}
			}
		}
		if (rendered) {
			this.onLayout(shallow, forceLayout);
		}
		// Initial layout completed
		this.hasLayout = true;
		delete this.forceLayout;
	},

	onLayout: Ext.emptyFn,

	// private
	shouldBufferLayout: function () {
		/*
		* Returns true if the container should buffer a layout.
		* This is true only if the container has previously been laid out
		* and has a parent container that is pending a layout.
		*/
		var hl = this.hasLayout;
		if (this.ownerCt) {
			// Only ever buffer if we've laid out the first time and we have one pending.
			return hl ? !this.hasLayoutPending() : false;
		}
		// Never buffer initial layout
		return hl;
	},

	// private
	hasLayoutPending: function () {
		// Traverse hierarchy to see if any parent container has a pending layout.
		var pending = false;
		this.ownerCt.bubble(function (c) {
			if (c.layoutPending) {
				pending = true;
				return false;
			}
		});
		return pending;
	},

	onShow: function () {
		// removes css classes that were added to hide
		Ext.Container.superclass.onShow.call(this);
		// If we were sized during the time we were hidden, layout.
		if (Ext.isDefined(this.deferLayout)) {
			delete this.deferLayout;
			this.doLayout(true);
		}
	},

	/**
	* Returns the layout currently in use by the container.  If the container does not currently have a layout
	* set, a default {@link Ext.layout.ContainerLayout} will be created and set as the container's layout.
	* @return {ContainerLayout} layout The container's layout
	*/
	getLayout: function () {
		if (!this.layout) {
			var layout = new Ext.layout.AutoLayout(this.layoutConfig);
			this.setLayout(layout);
		}
		return this.layout;
	},

	// private
	beforeDestroy: function () {
		var c;
		if (this.items) {
			while (c = this.items.first()) {
				this.doRemove(c, true);
			}
		}
		if (this.monitorResize) {
			Ext.EventManager.removeResizeListener(this.doLayout, this);
		}
		Ext.destroy(this.layout);
		Ext.Container.superclass.beforeDestroy.call(this);
	},

	/**
	* Bubbles up the component/container heirarchy, calling the specified function with each component. The scope (<i>this</i>) of
	* function call will be the scope provided or the current component. The arguments to the function
	* will be the args provided or the current component. If the function returns false at any point,
	* the bubble is stopped.
	* @param {Function} fn The function to call
	* @param {Object} scope (optional) The scope of the function (defaults to current node)
	* @param {Array} args (optional) The args to call the function with (default to passing the current component)
	* @return {Ext.Container} this
	*/
	bubble: function (fn, scope, args) {
		var p = this;
		while (p) {
			if (fn.apply(scope || p, args || [p]) === false) {
				break;
			}
			p = p.ownerCt;
		}
		return this;
	},

	/**
	* Cascades down the component/container heirarchy from this component (called first), calling the specified function with
	* each component. The scope (<i>this</i>) of
	* function call will be the scope provided or the current component. The arguments to the function
	* will be the args provided or the current component. If the function returns false at any point,
	* the cascade is stopped on that branch.
	* @param {Function} fn The function to call
	* @param {Object} scope (optional) The scope of the function (defaults to current component)
	* @param {Array} args (optional) The args to call the function with (defaults to passing the current component)
	* @return {Ext.Container} this
	*/
	cascade: function (fn, scope, args) {
		if (fn.apply(scope || this, args || [this]) !== false) {
			if (this.items) {
				var cs = this.items.items;
				for (var i = 0, len = cs.length; i < len; i++) {
					if (cs[i].cascade) {
						cs[i].cascade(fn, scope, args);
					} else {
						fn.apply(scope || cs[i], args || [cs[i]]);
					}
				}
			}
		}
		return this;
	},

	/**
	* Find a component under this container at any level by id
	* @param {String} id
	* @return Ext.Component
	*/
	findById: function (id) {
		var m, ct = this;
		this.cascade(function (c) {
			if (ct != c && c.id === id) {
				m = c;
				return false;
			}
		});
		return m || null;
	},

	/**
	* Find a component under this container at any level by xtype or class
	* @param {String/Class} xtype The xtype string for a component, or the class of the component directly
	* @param {Boolean} shallow (optional) False to check whether this Component is descended from the xtype (this is
	* the default), or true to check whether this Component is directly of the specified xtype.
	* @return {Array} Array of Ext.Components
	*/
	findByType: function (xtype, shallow) {
		return this.findBy(function (c) {
			return c.isXType(xtype, shallow);
		});
	},

	/**
	* Find a component under this container at any level by property
	* @param {String} prop
	* @param {String} value
	* @return {Array} Array of Ext.Components
	*/
	find: function (prop, value) {
		return this.findBy(function (c) {
			return c[prop] === value;
		});
	},

	/**
	* Find a component under this container at any level by a custom function. If the passed function returns
	* true, the component will be included in the results. The passed function is called with the arguments (component, this container).
	* @param {Function} fn The function to call
	* @param {Object} scope (optional)
	* @return {Array} Array of Ext.Components
	*/
	findBy: function (fn, scope) {
		var m = [], ct = this;
		this.cascade(function (c) {
			if (ct != c && fn.call(scope || c, c, ct) === true) {
				m.push(c);
			}
		});
		return m;
	},

	/**
	* Get a component contained by this container (alias for items.get(key))
	* @param {String/Number} key The index or id of the component
	* @return {Ext.Component} Ext.Component
	*/
	get: function (key) {
		return this.items.get(key);
	}
});

Ext.Container.LAYOUTS = {};
Ext.reg('container', Ext.Container);
/**
* @class Ext.layout.ContainerLayout
* <p>This class is intended to be extended or created via the <tt><b>{@link Ext.Container#layout layout}</b></tt>
* configuration property.  See <tt><b>{@link Ext.Container#layout}</b></tt> for additional details.</p>
*/
Ext.layout.ContainerLayout = Ext.extend(Object, {
	/**
	* @cfg {String} extraCls
	* <p>An optional extra CSS class that will be added to the container. This can be useful for adding
	* customized styles to the container or any of its children using standard CSS rules. See
	* {@link Ext.Component}.{@link Ext.Component#ctCls ctCls} also.</p>
	* <p><b>Note</b>: <tt>extraCls</tt> defaults to <tt>''</tt> except for the following classes
	* which assign a value by default:
	* <div class="mdetail-params"><ul>
	* <li>{@link Ext.layout.AbsoluteLayout Absolute Layout} : <tt>'x-abs-layout-item'</tt></li>
	* <li>{@link Ext.layout.Box Box Layout} : <tt>'x-box-item'</tt></li>
	* <li>{@link Ext.layout.ColumnLayout Column Layout} : <tt>'x-column'</tt></li>
	* </ul></div>
	* To configure the above Classes with an extra CSS class append to the default.  For example,
	* for ColumnLayout:<pre><code>
	* extraCls: 'x-column custom-class'
	* </code></pre>
	* </p>
	*/
	/**
	* @cfg {Boolean} renderHidden
	* True to hide each contained item on render (defaults to false).
	*/

	/**
	* A reference to the {@link Ext.Component} that is active.  For example, <pre><code>
	* if(myPanel.layout.activeItem.id == 'item-1') { ... }
	* </code></pre>
	* <tt>activeItem</tt> only applies to layout styles that can display items one at a time
	* (like {@link Ext.layout.AccordionLayout}, {@link Ext.layout.CardLayout}
	* and {@link Ext.layout.FitLayout}).  Read-only.  Related to {@link Ext.Container#activeItem}.
	* @type {Ext.Component}
	* @property activeItem
	*/

	// private
	monitorResize: false,
	// private
	activeItem: null,

	constructor: function (config) {
		this.id = Ext.id(null, 'ext-layout-');
		Ext.apply(this, config);
	},

	type: 'container',

	/* Workaround for how IE measures autoWidth elements.  It prefers bottom-up measurements
	whereas other browser prefer top-down.  We will hide all target child elements before we measure and
	put them back to get an accurate measurement.
	*/
	IEMeasureHack: function (target, viewFlag) {
		var tChildren = target.dom.childNodes, tLen = tChildren.length, c, d = [], e, i, ret;
		for (i = 0; i < tLen; i++) {
			c = tChildren[i];
			e = Ext.get(c);
			if (e) {
				d[i] = e.getStyle('display');
				e.setStyle({ display: 'none' });
			}
		}
		ret = target ? target.getViewSize(viewFlag) : {};
		for (i = 0; i < tLen; i++) {
			c = tChildren[i];
			e = Ext.get(c);
			if (e) {
				e.setStyle({ display: d[i] });
			}
		}
		return ret;
	},

	// Placeholder for the derived layouts
	getLayoutTargetSize: Ext.EmptyFn,

	// private
	layout: function () {
		var ct = this.container, target = ct.getLayoutTarget();
		if (!(this.hasLayout || Ext.isEmpty(this.targetCls))) {
			target.addClass(this.targetCls);
		}
		this.onLayout(ct, target);
		ct.fireEvent('afterlayout', ct, this);
	},

	// private
	onLayout: function (ct, target) {
		this.renderAll(ct, target);
	},

	// private
	isValidParent: function (c, target) {
		return target && c.getPositionEl().dom.parentNode == (target.dom || target);
	},

	// private
	renderAll: function (ct, target) {
		var items = ct.items.items, i, c, len = items.length;
		for (i = 0; i < len; i++) {
			c = items[i];
			if (c && (!c.rendered || !this.isValidParent(c, target))) {
				this.renderItem(c, i, target);
			}
		}
	},

	/**
	* @private
	* Renders the given Component into the target Element. If the Component is already rendered,
	* it is moved to the provided target instead.
	* @param {Ext.Component} c The Component to render
	* @param {Number} position The position within the target to render the item to
	* @param {Ext.Element} target The target Element
	*/
	renderItem: function (c, position, target) {
		if (c) {
			if (!c.rendered) {
				c.render(target, position);
				this.configureItem(c, position);
			} else if (!this.isValidParent(c, target)) {
				if (Ext.isNumber(position)) {
					position = target.dom.childNodes[position];
				}

				target.dom.insertBefore(c.getPositionEl().dom, position || null);
				c.container = target;
				this.configureItem(c, position);
			}
		}
	},

	// private.
	// Get all rendered items to lay out.
	getRenderedItems: function (ct) {
		var t = ct.getLayoutTarget(), cti = ct.items.items, len = cti.length, i, c, items = [];
		for (i = 0; i < len; i++) {
			if ((c = cti[i]).rendered && this.isValidParent(c, t)) {
				items.push(c);
			}
		};
		return items;
	},

	/**
	* @private
	* Applies extraCls and hides the item if renderHidden is true
	*/
	configureItem: function (c, position) {
		if (this.extraCls) {
			var t = c.getPositionEl ? c.getPositionEl() : c;
			t.addClass(this.extraCls);
		}

		// If we are forcing a layout, do so *before* we hide so elements have height/width
		if (c.doLayout && this.forceLayout) {
			c.doLayout();
		}
		if (this.renderHidden && c != this.activeItem) {
			c.hide();
		}
	},

	onRemove: function (c) {
		if (this.activeItem == c) {
			delete this.activeItem;
		}
		if (c.rendered && this.extraCls) {
			var t = c.getPositionEl ? c.getPositionEl() : c;
			t.removeClass(this.extraCls);
		}
	},

	afterRemove: function (c) {
		if (c.removeRestore) {
			c.removeMode = 'container';
			delete c.removeRestore;
		}
	},

	// private
	onResize: function () {
		var ct = this.container,
            b;
		if (ct.collapsed) {
			return;
		}
		if (b = ct.bufferResize && ct.shouldBufferLayout()) {
			if (!this.resizeTask) {
				this.resizeTask = new Ext.util.DelayedTask(this.runLayout, this);
				this.resizeBuffer = Ext.isNumber(b) ? b : 50;
			}
			ct.layoutPending = true;
			this.resizeTask.delay(this.resizeBuffer);
		} else {
			this.runLayout();
		}
	},

	runLayout: function () {
		var ct = this.container;
		this.layout();
		ct.onLayout();
		delete ct.layoutPending;
	},

	// private
	setContainer: function (ct) {
		/**
		* This monitorResize flag will be renamed soon as to avoid confusion
		* with the Container version which hooks onWindowResize to doLayout
		*
		* monitorResize flag in this context attaches the resize event between
		* a container and it's layout
		*/
		if (this.monitorResize && ct != this.container) {
			var old = this.container;
			if (old) {
				old.un(old.resizeEvent, this.onResize, this);
			}
			if (ct) {
				ct.on(ct.resizeEvent, this.onResize, this);
			}
		}
		this.container = ct;
	},

	/**
	* Parses a number or string representing margin sizes into an object. Supports CSS-style margin declarations
	* (e.g. 10, "10", "10 10", "10 10 10" and "10 10 10 10" are all valid options and would return the same result)
	* @param {Number|String} v The encoded margins
	* @return {Object} An object with margin sizes for top, right, bottom and left
	*/
	parseMargins: function (v) {
		if (Ext.isNumber(v)) {
			v = v.toString();
		}
		var ms = v.split(' '),
            len = ms.length;

		if (len == 1) {
			ms[1] = ms[2] = ms[3] = ms[0];
		} else if (len == 2) {
			ms[2] = ms[0];
			ms[3] = ms[1];
		} else if (len == 3) {
			ms[3] = ms[1];
		}

		return {
			top: parseInt(ms[0], 10) || 0,
			right: parseInt(ms[1], 10) || 0,
			bottom: parseInt(ms[2], 10) || 0,
			left: parseInt(ms[3], 10) || 0
		};
	},

	/**
	* The {@link Ext.Template Ext.Template} used by Field rendering layout classes (such as
	* {@link Ext.layout.FormLayout}) to create the DOM structure of a fully wrapped,
	* labeled and styled form Field. A default Template is supplied, but this may be
	* overriden to create custom field structures. The template processes values returned from
	* {@link Ext.layout.FormLayout#getTemplateArgs}.
	* @property fieldTpl
	* @type Ext.Template
	*/
	fieldTpl: (function () {
		var t = new Ext.Template(
            '<div class="x-form-item {itemCls}" tabIndex="-1">',
                '<label for="{id}" style="{labelStyle}" class="x-form-item-label">{label}{labelSeparator}</label>',
                '<div class="x-form-element" id="x-form-el-{id}" style="{elementStyle}">',
                '</div><div class="{clearCls}"></div>',
            '</div>'
        );
		t.disableFormats = true;
		return t.compile();
	})(),

	/*
	* Destroys this layout. This is a template method that is empty by default, but should be implemented
	* by subclasses that require explicit destruction to purge event handlers or remove DOM nodes.
	* @protected
	*/
	destroy: function () {
		// Stop any buffered layout tasks
		if (this.resizeTask && this.resizeTask.cancel) {
			this.resizeTask.cancel();
		}
		if (!Ext.isEmpty(this.targetCls)) {
			var target = this.container.getLayoutTarget();
			if (target) {
				target.removeClass(this.targetCls);
			}
		}
	}
}); /**
 * @class Ext.layout.AutoLayout
 * <p>The AutoLayout is the default layout manager delegated by {@link Ext.Container} to
 * render any child Components when no <tt>{@link Ext.Container#layout layout}</tt> is configured into
 * a {@link Ext.Container Container}.</tt>.  AutoLayout provides only a passthrough of any layout calls
 * to any child containers.</p>
 */
Ext.layout.AutoLayout = Ext.extend(Ext.layout.ContainerLayout, {
	type: 'auto',

	monitorResize: true,

	onLayout: function (ct, target) {
		Ext.layout.AutoLayout.superclass.onLayout.call(this, ct, target);
		var cs = this.getRenderedItems(ct), len = cs.length, i, c;
		for (i = 0; i < len; i++) {
			c = cs[i];
			if (c.doLayout) {
				// Shallow layout children
				c.doLayout(true);
			}
		}
	}
});

Ext.Container.LAYOUTS['auto'] = Ext.layout.AutoLayout;
/**
* @class Ext.layout.FitLayout
* @extends Ext.layout.ContainerLayout
* <p>This is a base class for layouts that contain <b>a single item</b> that automatically expands to fill the layout's
* container.  This class is intended to be extended or created via the <tt>layout:'fit'</tt> {@link Ext.Container#layout}
* config, and should generally not need to be created directly via the new keyword.</p>
* <p>FitLayout does not have any direct config options (other than inherited ones).  To fit a panel to a container
* using FitLayout, simply set layout:'fit' on the container and add a single panel to it.  If the container has
* multiple panels, only the first one will be displayed.  Example usage:</p>
* <pre><code>
var p = new Ext.Panel({
title: 'Fit Layout',
layout:'fit',
items: {
title: 'Inner Panel',
html: '&lt;p&gt;This is the inner panel content&lt;/p&gt;',
border: false
}
});
</code></pre>
*/
Ext.layout.FitLayout = Ext.extend(Ext.layout.ContainerLayout, {
	// private
	monitorResize: true,

	type: 'fit',

	getLayoutTargetSize: function () {
		var target = this.container.getLayoutTarget();
		if (!target) {
			return {};
		}
		// Style Sized (scrollbars not included)
		return target.getStyleSize();
	},

	// private
	onLayout: function (ct, target) {
		Ext.layout.FitLayout.superclass.onLayout.call(this, ct, target);
		if (!ct.collapsed) {
			this.setItemSize(this.activeItem || ct.items.itemAt(0), this.getLayoutTargetSize());
		}
	},

	// private
	setItemSize: function (item, size) {
		if (item && size.height > 0) { // display none?
			item.setSize(size);
		}
	}
});
Ext.Container.LAYOUTS['fit'] = Ext.layout.FitLayout; /**
 * @class Ext.layout.CardLayout
 * @extends Ext.layout.FitLayout
 * <p>This layout manages multiple child Components, each fitted to the Container, where only a single child Component can be
 * visible at any given time.  This layout style is most commonly used for wizards, tab implementations, etc.
 * This class is intended to be extended or created via the layout:'card' {@link Ext.Container#layout} config,
 * and should generally not need to be created directly via the new keyword.</p>
 * <p>The CardLayout's focal method is {@link #setActiveItem}.  Since only one panel is displayed at a time,
 * the only way to move from one Component to the next is by calling setActiveItem, passing the id or index of
 * the next panel to display.  The layout itself does not provide a user interface for handling this navigation,
 * so that functionality must be provided by the developer.</p>
 * <p>In the following example, a simplistic wizard setup is demonstrated.  A button bar is added
 * to the footer of the containing panel to provide navigation buttons.  The buttons will be handled by a
 * common navigation routine -- for this example, the implementation of that routine has been ommitted since
 * it can be any type of custom logic.  Note that other uses of a CardLayout (like a tab control) would require a
 * completely different implementation.  For serious implementations, a better approach would be to extend
 * CardLayout to provide the custom functionality needed.  Example usage:</p>
 * <pre><code>
var navHandler = function(direction){
    // This routine could contain business logic required to manage the navigation steps.
    // It would call setActiveItem as needed, manage navigation button state, handle any
    // branching logic that might be required, handle alternate actions like cancellation
    // or finalization, etc.  A complete wizard implementation could get pretty
    // sophisticated depending on the complexity required, and should probably be
    // done as a subclass of CardLayout in a real-world implementation.
};

var card = new Ext.Panel({
    title: 'Example Wizard',
    layout:'card',
    activeItem: 0, // make sure the active item is set on the container config!
    bodyStyle: 'padding:15px',
    defaults: {
        // applied to each contained panel
        border:false
    },
    // just an example of one possible navigation scheme, using buttons
    bbar: [
        {
            id: 'move-prev',
            text: 'Back',
            handler: navHandler.createDelegate(this, [-1]),
            disabled: true
        },
        '->', // greedy spacer so that the buttons are aligned to each side
        {
            id: 'move-next',
            text: 'Next',
            handler: navHandler.createDelegate(this, [1])
        }
    ],
    // the panels (or "cards") within the layout
    items: [{
        id: 'card-0',
        html: '&lt;h1&gt;Welcome to the Wizard!&lt;/h1&gt;&lt;p&gt;Step 1 of 3&lt;/p&gt;'
    },{
        id: 'card-1',
        html: '&lt;p&gt;Step 2 of 3&lt;/p&gt;'
    },{
        id: 'card-2',
        html: '&lt;h1&gt;Congratulations!&lt;/h1&gt;&lt;p&gt;Step 3 of 3 - Complete&lt;/p&gt;'
    }]
});
</code></pre>
 */
Ext.layout.CardLayout = Ext.extend(Ext.layout.FitLayout, {
	/**
	* @cfg {Boolean} deferredRender
	* True to render each contained item at the time it becomes active, false to render all contained items
	* as soon as the layout is rendered (defaults to false).  If there is a significant amount of content or
	* a lot of heavy controls being rendered into panels that are not displayed by default, setting this to
	* true might improve performance.
	*/
	deferredRender: false,

	/**
	* @cfg {Boolean} layoutOnCardChange
	* True to force a layout of the active item when the active card is changed. Defaults to false.
	*/
	layoutOnCardChange: false,

	/**
	* @cfg {Boolean} renderHidden @hide
	*/
	// private
	renderHidden: true,

	type: 'card',

	/**
	* Sets the active (visible) item in the layout.
	* @param {String/Number} item The string component id or numeric index of the item to activate
	*/
	setActiveItem: function (item) {
		var ai = this.activeItem,
            ct = this.container;
		item = ct.getComponent(item);

		// Is this a valid, different card?
		if (item && ai != item) {

			// Changing cards, hide the current one
			if (ai) {
				ai.hide();
				if (ai.hidden !== true) {
					return false;
				}
				ai.fireEvent('deactivate', ai);
			}

			var layout = item.doLayout && (this.layoutOnCardChange || !item.rendered);

			// Change activeItem reference
			this.activeItem = item;

			// The container is about to get a recursive layout, remove any deferLayout reference
			// because it will trigger a redundant layout.
			delete item.deferLayout;

			// Show the new component
			item.show();

			this.layout();

			if (layout) {
				item.doLayout();
			}
			item.fireEvent('activate', item);
		}
	},

	// private
	renderAll: function (ct, target) {
		if (this.deferredRender) {
			this.renderItem(this.activeItem, undefined, target);
		} else {
			Ext.layout.CardLayout.superclass.renderAll.call(this, ct, target);
		}
	}
});
Ext.Container.LAYOUTS['card'] = Ext.layout.CardLayout;
/**
* @class Ext.layout.AnchorLayout
* @extends Ext.layout.ContainerLayout
* <p>This is a layout that enables anchoring of contained elements relative to the container's dimensions.
* If the container is resized, all anchored items are automatically rerendered according to their
* <b><tt>{@link #anchor}</tt></b> rules.</p>
* <p>This class is intended to be extended or created via the layout:'anchor' {@link Ext.Container#layout}
* config, and should generally not need to be created directly via the new keyword.</p>
* <p>AnchorLayout does not have any direct config options (other than inherited ones). By default,
* AnchorLayout will calculate anchor measurements based on the size of the container itself. However, the
* container using the AnchorLayout can supply an anchoring-specific config property of <b>anchorSize</b>.
* If anchorSize is specifed, the layout will use it as a virtual container for the purposes of calculating
* anchor measurements based on it instead, allowing the container to be sized independently of the anchoring
* logic if necessary.  For example:</p>
* <pre><code>
var viewport = new Ext.Viewport({
layout:'anchor',
anchorSize: {width:800, height:600},
items:[{
title:'Item 1',
html:'Content 1',
width:800,
anchor:'right 20%'
},{
title:'Item 2',
html:'Content 2',
width:300,
anchor:'50% 30%'
},{
title:'Item 3',
html:'Content 3',
width:600,
anchor:'-100 50%'
}]
});
* </code></pre>
*/
Ext.layout.AnchorLayout = Ext.extend(Ext.layout.ContainerLayout, {
	/**
	* @cfg {String} anchor
	* <p>This configuation option is to be applied to <b>child <tt>items</tt></b> of a container managed by
	* this layout (ie. configured with <tt>layout:'anchor'</tt>).</p><br/>
	*
	* <p>This value is what tells the layout how an item should be anchored to the container. <tt>items</tt>
	* added to an AnchorLayout accept an anchoring-specific config property of <b>anchor</b> which is a string
	* containing two values: the horizontal anchor value and the vertical anchor value (for example, '100% 50%').
	* The following types of anchor values are supported:<div class="mdetail-params"><ul>
	*
	* <li><b>Percentage</b> : Any value between 1 and 100, expressed as a percentage.<div class="sub-desc">
	* The first anchor is the percentage width that the item should take up within the container, and the
	* second is the percentage height.  For example:<pre><code>
	// two values specified
	anchor: '100% 50%' // render item complete width of the container and
	// 1/2 height of the container
	// one value specified
	anchor: '100%'     // the width value; the height will default to auto
	* </code></pre></div></li>
	*
	* <li><b>Offsets</b> : Any positive or negative integer value.<div class="sub-desc">
	* This is a raw adjustment where the first anchor is the offset from the right edge of the container,
	* and the second is the offset from the bottom edge. For example:<pre><code>
	// two values specified
	anchor: '-50 -100' // render item the complete width of the container
	// minus 50 pixels and
	// the complete height minus 100 pixels.
	// one value specified
	anchor: '-50'      // anchor value is assumed to be the right offset value
	// bottom offset will default to 0
	* </code></pre></div></li>
	*
	* <li><b>Sides</b> : Valid values are <tt>'right'</tt> (or <tt>'r'</tt>) and <tt>'bottom'</tt>
	* (or <tt>'b'</tt>).<div class="sub-desc">
	* Either the container must have a fixed size or an anchorSize config value defined at render time in
	* order for these to have any effect.</div></li>
	*
	* <li><b>Mixed</b> : <div class="sub-desc">
	* Anchor values can also be mixed as needed.  For example, to render the width offset from the container
	* right edge by 50 pixels and 75% of the container's height use:
	* <pre><code>
	anchor: '-50 75%'
	* </code></pre></div></li>
	*
	*
	* </ul></div>
	*/

	// private
	monitorResize: true,

	type: 'anchor',

	/**
	* @cfg {String} defaultAnchor
	*
	* default anchor for all child container items applied if no anchor or specific width is set on the child item.  Defaults to '100%'.
	*
	*/
	defaultAnchor: '100%',

	parseAnchorRE: /^(r|right|b|bottom)$/i,

	getLayoutTargetSize: function () {
		var target = this.container.getLayoutTarget();
		if (!target) {
			return {};
		}
		// Style Sized (scrollbars not included)
		return target.getStyleSize();
	},

	// private
	onLayout: function (ct, target) {
		Ext.layout.AnchorLayout.superclass.onLayout.call(this, ct, target);
		var size = this.getLayoutTargetSize();

		var w = size.width, h = size.height;

		if (w < 20 && h < 20) {
			return;
		}

		// find the container anchoring size
		var aw, ah;
		if (ct.anchorSize) {
			if (typeof ct.anchorSize == 'number') {
				aw = ct.anchorSize;
			} else {
				aw = ct.anchorSize.width;
				ah = ct.anchorSize.height;
			}
		} else {
			aw = ct.initialConfig.width;
			ah = ct.initialConfig.height;
		}

		var cs = this.getRenderedItems(ct), len = cs.length, i, c, a, cw, ch, el, vs, boxes = [];
		for (i = 0; i < len; i++) {
			c = cs[i];
			el = c.getPositionEl();

			// If a child container item has no anchor and no specific width, set the child to the default anchor size
			if (!c.anchor && c.items && !Ext.isNumber(c.width) && !(Ext.isIE6 && Ext.isStrict)) {
				c.anchor = this.defaultAnchor;
			}

			if (c.anchor) {
				a = c.anchorSpec;
				if (!a) { // cache all anchor values
					vs = c.anchor.split(' ');
					c.anchorSpec = a = {
						right: this.parseAnchor(vs[0], c.initialConfig.width, aw),
						bottom: this.parseAnchor(vs[1], c.initialConfig.height, ah)
					};
				}
				cw = a.right ? this.adjustWidthAnchor(a.right(w) - el.getMargins('lr'), c) : undefined;
				ch = a.bottom ? this.adjustHeightAnchor(a.bottom(h) - el.getMargins('tb'), c) : undefined;

				if (cw || ch) {
					boxes.push({
						comp: c,
						width: cw || undefined,
						height: ch || undefined
					});
				}
			}
		}
		for (i = 0, len = boxes.length; i < len; i++) {
			c = boxes[i];
			c.comp.setSize(c.width, c.height);
		}
	},

	// private
	parseAnchor: function (a, start, cstart) {
		if (a && a != 'none') {
			var last;
			// standard anchor
			if (this.parseAnchorRE.test(a)) {
				var diff = cstart - start;
				return function (v) {
					if (v !== last) {
						last = v;
						return v - diff;
					}
				}
				// percentage
			} else if (a.indexOf('%') != -1) {
				var ratio = parseFloat(a.replace('%', '')) * .01;
				return function (v) {
					if (v !== last) {
						last = v;
						return Math.floor(v * ratio);
					}
				}
				// simple offset adjustment
			} else {
				a = parseInt(a, 10);
				if (!isNaN(a)) {
					return function (v) {
						if (v !== last) {
							last = v;
							return v + a;
						}
					}
				}
			}
		}
		return false;
	},

	// private
	adjustWidthAnchor: function (value, comp) {
		return value;
	},

	// private
	adjustHeightAnchor: function (value, comp) {
		return value;
	}

	/**
	* @property activeItem
	* @hide
	*/
});
Ext.Container.LAYOUTS['anchor'] = Ext.layout.AnchorLayout;
/**
* @class Ext.layout.ColumnLayout
* @extends Ext.layout.ContainerLayout
* <p>This is the layout style of choice for creating structural layouts in a multi-column format where the width of
* each column can be specified as a percentage or fixed width, but the height is allowed to vary based on the content.
* This class is intended to be extended or created via the layout:'column' {@link Ext.Container#layout} config,
* and should generally not need to be created directly via the new keyword.</p>
* <p>ColumnLayout does not have any direct config options (other than inherited ones), but it does support a
* specific config property of <b><tt>columnWidth</tt></b> that can be included in the config of any panel added to it.  The
* layout will use the columnWidth (if present) or width of each panel during layout to determine how to size each panel.
* If width or columnWidth is not specified for a given panel, its width will default to the panel's width (or auto).</p>
* <p>The width property is always evaluated as pixels, and must be a number greater than or equal to 1.
* The columnWidth property is always evaluated as a percentage, and must be a decimal value greater than 0 and
* less than 1 (e.g., .25).</p>
* <p>The basic rules for specifying column widths are pretty simple.  The logic makes two passes through the
* set of contained panels.  During the first layout pass, all panels that either have a fixed width or none
* specified (auto) are skipped, but their widths are subtracted from the overall container width.  During the second
* pass, all panels with columnWidths are assigned pixel widths in proportion to their percentages based on
* the total <b>remaining</b> container width.  In other words, percentage width panels are designed to fill the space
* left over by all the fixed-width and/or auto-width panels.  Because of this, while you can specify any number of columns
* with different percentages, the columnWidths must always add up to 1 (or 100%) when added together, otherwise your
* layout may not render as expected.  Example usage:</p>
* <pre><code>
// All columns are percentages -- they must add up to 1
var p = new Ext.Panel({
title: 'Column Layout - Percentage Only',
layout:'column',
items: [{
title: 'Column 1',
columnWidth: .25
},{
title: 'Column 2',
columnWidth: .6
},{
title: 'Column 3',
columnWidth: .15
}]
});

// Mix of width and columnWidth -- all columnWidth values must add up
// to 1. The first column will take up exactly 120px, and the last two
// columns will fill the remaining container width.
var p = new Ext.Panel({
title: 'Column Layout - Mixed',
layout:'column',
items: [{
title: 'Column 1',
width: 120
},{
title: 'Column 2',
columnWidth: .8
},{
title: 'Column 3',
columnWidth: .2
}]
});
</code></pre>
*/
Ext.layout.ColumnLayout = Ext.extend(Ext.layout.ContainerLayout, {
	// private
	monitorResize: true,

	type: 'column',

	extraCls: 'x-column',

	scrollOffset: 0,

	// private

	targetCls: 'x-column-layout-ct',

	isValidParent: function (c, target) {
		return this.innerCt && c.getPositionEl().dom.parentNode == this.innerCt.dom;
	},

	getLayoutTargetSize: function () {
		var target = this.container.getLayoutTarget(), ret;
		if (target) {
			ret = target.getViewSize();

			// IE in strict mode will return a width of 0 on the 1st pass of getViewSize.
			// Use getStyleSize to verify the 0 width, the adjustment pass will then work properly
			// with getViewSize
			if (Ext.isIE && Ext.isStrict && ret.width == 0) {
				ret = target.getStyleSize();
			}

			ret.width -= target.getPadding('lr');
			ret.height -= target.getPadding('tb');
		}
		return ret;
	},

	renderAll: function (ct, target) {
		if (!this.innerCt) {
			// the innerCt prevents wrapping and shuffling while
			// the container is resizing
			this.innerCt = target.createChild({ cls: 'x-column-inner' });
			this.innerCt.createChild({ cls: 'x-clear' });
		}
		Ext.layout.ColumnLayout.superclass.renderAll.call(this, ct, this.innerCt);
	},

	// private
	onLayout: function (ct, target) {
		var cs = ct.items.items,
            len = cs.length,
            c,
            i,
            m,
            margins = [];

		this.renderAll(ct, target);

		var size = this.getLayoutTargetSize();

		if (size.width < 1 && size.height < 1) { // display none?
			return;
		}

		var w = size.width - this.scrollOffset,
            h = size.height,
            pw = w;

		this.innerCt.setWidth(w);

		// some columns can be percentages while others are fixed
		// so we need to make 2 passes

		for (i = 0; i < len; i++) {
			c = cs[i];
			m = c.getPositionEl().getMargins('lr');
			margins[i] = m;
			if (!c.columnWidth) {
				pw -= (c.getWidth() + m);
			}
		}

		pw = pw < 0 ? 0 : pw;

		for (i = 0; i < len; i++) {
			c = cs[i];
			m = margins[i];
			if (c.columnWidth) {
				c.setSize(Math.floor(c.columnWidth * pw) - m);
			}
		}

		// Browsers differ as to when they account for scrollbars.  We need to re-measure to see if the scrollbar
		// spaces were accounted for properly.  If not, re-layout.
		if (Ext.isIE) {
			if (i = target.getStyle('overflow') && i != 'hidden' && !this.adjustmentPass) {
				var ts = this.getLayoutTargetSize();
				if (ts.width != size.width) {
					this.adjustmentPass = true;
					this.onLayout(ct, target);
				}
			}
		}
		delete this.adjustmentPass;
	}

	/**
	* @property activeItem
	* @hide
	*/
});

Ext.Container.LAYOUTS['column'] = Ext.layout.ColumnLayout;
/**
* @class Ext.layout.BorderLayout
* @extends Ext.layout.ContainerLayout
* <p>This is a multi-pane, application-oriented UI layout style that supports multiple
* nested panels, automatic {@link Ext.layout.BorderLayout.Region#split split} bars between
* {@link Ext.layout.BorderLayout.Region#BorderLayout.Region regions} and built-in
* {@link Ext.layout.BorderLayout.Region#collapsible expanding and collapsing} of regions.</p>
* <p>This class is intended to be extended or created via the <tt>layout:'border'</tt>
* {@link Ext.Container#layout} config, and should generally not need to be created directly
* via the new keyword.</p>
* <p>BorderLayout does not have any direct config options (other than inherited ones).
* All configuration options available for customizing the BorderLayout are at the
* {@link Ext.layout.BorderLayout.Region} and {@link Ext.layout.BorderLayout.SplitRegion}
* levels.</p>
* <p>Example usage:</p>
* <pre><code>
var myBorderPanel = new Ext.Panel({
{@link Ext.Component#renderTo renderTo}: document.body,
{@link Ext.BoxComponent#width width}: 700,
{@link Ext.BoxComponent#height height}: 500,
{@link Ext.Panel#title title}: 'Border Layout',
{@link Ext.Container#layout layout}: 'border',
{@link Ext.Container#items items}: [{
{@link Ext.Panel#title title}: 'South Region is resizable',
{@link Ext.layout.BorderLayout.Region#BorderLayout.Region region}: 'south',     // position for region
{@link Ext.BoxComponent#height height}: 100,
{@link Ext.layout.BorderLayout.Region#split split}: true,         // enable resizing
{@link Ext.SplitBar#minSize minSize}: 75,         // defaults to {@link Ext.layout.BorderLayout.Region#minHeight 50}
{@link Ext.SplitBar#maxSize maxSize}: 150,
{@link Ext.layout.BorderLayout.Region#margins margins}: '0 5 5 5'
},{
// xtype: 'panel' implied by default
{@link Ext.Panel#title title}: 'West Region is collapsible',
{@link Ext.layout.BorderLayout.Region#BorderLayout.Region region}:'west',
{@link Ext.layout.BorderLayout.Region#margins margins}: '5 0 0 5',
{@link Ext.BoxComponent#width width}: 200,
{@link Ext.layout.BorderLayout.Region#collapsible collapsible}: true,   // make collapsible
{@link Ext.layout.BorderLayout.Region#cmargins cmargins}: '5 5 0 5', // adjust top margin when collapsed
{@link Ext.Component#id id}: 'west-region-container',
{@link Ext.Container#layout layout}: 'fit',
{@link Ext.Panel#unstyled unstyled}: true
},{
{@link Ext.Panel#title title}: 'Center Region',
{@link Ext.layout.BorderLayout.Region#BorderLayout.Region region}: 'center',     // center region is required, no width/height specified
{@link Ext.Component#xtype xtype}: 'container',
{@link Ext.Container#layout layout}: 'fit',
{@link Ext.layout.BorderLayout.Region#margins margins}: '5 5 0 0'
}]
});
</code></pre>
* <p><b><u>Notes</u></b>:</p><div class="mdetail-params"><ul>
* <li>Any container using the BorderLayout <b>must</b> have a child item with <tt>region:'center'</tt>.
* The child item in the center region will always be resized to fill the remaining space not used by
* the other regions in the layout.</li>
* <li>Any child items with a region of <tt>west</tt> or <tt>east</tt> must have <tt>width</tt> defined
* (an integer representing the number of pixels that the region should take up).</li>
* <li>Any child items with a region of <tt>north</tt> or <tt>south</tt> must have <tt>height</tt> defined.</li>
* <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
* Components within a BorderLayout, have them wrapped by an additional Container which is directly
* managed by the BorderLayout.  If the region is to be collapsible, the Container used directly
* by the BorderLayout manager should be a Panel.  In the following example a Container (an Ext.Panel)
* is added to the west region:
* <div style="margin-left:16px"><pre><code>
wrc = {@link Ext#getCmp Ext.getCmp}('west-region-container');
wrc.{@link Ext.Panel#removeAll removeAll}();
wrc.{@link Ext.Container#add add}({
title: 'Added Panel',
html: 'Some content'
});
wrc.{@link Ext.Container#doLayout doLayout}();
* </code></pre></div>
* </li>
* <li> To reference a {@link Ext.layout.BorderLayout.Region Region}:
* <div style="margin-left:16px"><pre><code>
wr = myBorderPanel.layout.west;
* </code></pre></div>
* </li>
* </ul></div>
*/
Ext.layout.BorderLayout = Ext.extend(Ext.layout.ContainerLayout, {
	// private
	monitorResize: true,
	// private
	rendered: false,

	type: 'border',

	targetCls: 'x-border-layout-ct',

	getLayoutTargetSize: function () {
		var target = this.container.getLayoutTarget();
		return target ? target.getViewSize() : {};
	},

	// private
	onLayout: function (ct, target) {
		var collapsed, i, c, pos, items = ct.items.items, len = items.length;
		if (!this.rendered) {
			collapsed = [];
			for (i = 0; i < len; i++) {
				c = items[i];
				pos = c.region;
				if (c.collapsed) {
					collapsed.push(c);
				}
				c.collapsed = false;
				if (!c.rendered) {
					c.render(target, i);
					c.getPositionEl().addClass('x-border-panel');
				}
				this[pos] = pos != 'center' && c.split ?
                    new Ext.layout.BorderLayout.SplitRegion(this, c.initialConfig, pos) :
                    new Ext.layout.BorderLayout.Region(this, c.initialConfig, pos);
				this[pos].render(target, c);
			}
			this.rendered = true;
		}

		var size = this.getLayoutTargetSize();
		if (size.width < 20 || size.height < 20) { // display none?
			if (collapsed) {
				this.restoreCollapsed = collapsed;
			}
			return;
		} else if (this.restoreCollapsed) {
			collapsed = this.restoreCollapsed;
			delete this.restoreCollapsed;
		}

		var w = size.width, h = size.height,
            centerW = w, centerH = h, centerY = 0, centerX = 0,
            n = this.north, s = this.south, west = this.west, e = this.east, c = this.center,
            b, m, totalWidth, totalHeight;
		if (!c && Ext.layout.BorderLayout.WARN !== false) {
			throw 'No center region defined in BorderLayout ' + ct.id;
		}

		if (n && n.isVisible()) {
			b = n.getSize();
			m = n.getMargins();
			b.width = w - (m.left + m.right);
			b.x = m.left;
			b.y = m.top;
			centerY = b.height + b.y + m.bottom;
			centerH -= centerY;
			n.applyLayout(b);
		}
		if (s && s.isVisible()) {
			b = s.getSize();
			m = s.getMargins();
			b.width = w - (m.left + m.right);
			b.x = m.left;
			totalHeight = (b.height + m.top + m.bottom);
			b.y = h - totalHeight + m.top;
			centerH -= totalHeight;
			s.applyLayout(b);
		}
		if (west && west.isVisible()) {
			b = west.getSize();
			m = west.getMargins();
			b.height = centerH - (m.top + m.bottom);
			b.x = m.left;
			b.y = centerY + m.top;
			totalWidth = (b.width + m.left + m.right);
			centerX += totalWidth;
			centerW -= totalWidth;
			west.applyLayout(b);
		}
		if (e && e.isVisible()) {
			b = e.getSize();
			m = e.getMargins();
			b.height = centerH - (m.top + m.bottom);
			totalWidth = (b.width + m.left + m.right);
			b.x = w - totalWidth + m.left;
			b.y = centerY + m.top;
			centerW -= totalWidth;
			e.applyLayout(b);
		}
		if (c) {
			m = c.getMargins();
			var centerBox = {
				x: centerX + m.left,
				y: centerY + m.top,
				width: centerW - (m.left + m.right),
				height: centerH - (m.top + m.bottom)
			};
			c.applyLayout(centerBox);
		}
		if (collapsed) {
			for (i = 0, len = collapsed.length; i < len; i++) {
				collapsed[i].collapse(false);
			}
		}
		if (Ext.isIE && Ext.isStrict) { // workaround IE strict repainting issue
			target.repaint();
		}
		// Putting a border layout into an overflowed container is NOT correct and will make a second layout pass necessary.
		if (i = target.getStyle('overflow') && i != 'hidden' && !this.adjustmentPass) {
			var ts = this.getLayoutTargetSize();
			if (ts.width != size.width || ts.height != size.height) {
				this.adjustmentPass = true;
				this.onLayout(ct, target);
			}
		}
		delete this.adjustmentPass;
	},

	destroy: function () {
		var r = ['north', 'south', 'east', 'west'], i, region;
		for (i = 0; i < r.length; i++) {
			region = this[r[i]];
			if (region) {
				if (region.destroy) {
					region.destroy();
				} else if (region.split) {
					region.split.destroy(true);
				}
			}
		}
		Ext.layout.BorderLayout.superclass.destroy.call(this);
	}

	/**
	* @property activeItem
	* @hide
	*/
});

/**
* @class Ext.layout.BorderLayout.Region
* <p>This is a region of a {@link Ext.layout.BorderLayout BorderLayout} that acts as a subcontainer
* within the layout.  Each region has its own {@link Ext.layout.ContainerLayout layout} that is
* independent of other regions and the containing BorderLayout, and can be any of the
* {@link Ext.layout.ContainerLayout valid Ext layout types}.</p>
* <p>Region size is managed automatically and cannot be changed by the user -- for
* {@link #split resizable regions}, see {@link Ext.layout.BorderLayout.SplitRegion}.</p>
* @constructor
* Create a new Region.
* @param {Layout} layout The {@link Ext.layout.BorderLayout BorderLayout} instance that is managing this Region.
* @param {Object} config The configuration options
* @param {String} position The region position.  Valid values are: <tt>north</tt>, <tt>south</tt>,
* <tt>east</tt>, <tt>west</tt> and <tt>center</tt>.  Every {@link Ext.layout.BorderLayout BorderLayout}
* <b>must have a center region</b> for the primary content -- all other regions are optional.
*/
Ext.layout.BorderLayout.Region = function (layout, config, pos) {
	Ext.apply(this, config);
	this.layout = layout;
	this.position = pos;
	this.state = {};
	if (typeof this.margins == 'string') {
		this.margins = this.layout.parseMargins(this.margins);
	}
	this.margins = Ext.applyIf(this.margins || {}, this.defaultMargins);
	if (this.collapsible) {
		if (typeof this.cmargins == 'string') {
			this.cmargins = this.layout.parseMargins(this.cmargins);
		}
		if (this.collapseMode == 'mini' && !this.cmargins) {
			this.cmargins = { left: 0, top: 0, right: 0, bottom: 0 };
		} else {
			this.cmargins = Ext.applyIf(this.cmargins || {},
                pos == 'north' || pos == 'south' ? this.defaultNSCMargins : this.defaultEWCMargins);
		}
	}
};

Ext.layout.BorderLayout.Region.prototype = {
	/**
	* @cfg {Boolean} animFloat
	* When a collapsed region's bar is clicked, the region's panel will be displayed as a floated
	* panel that will close again once the user mouses out of that panel (or clicks out if
	* <tt>{@link #autoHide} = false</tt>).  Setting <tt>{@link #animFloat} = false</tt> will
	* prevent the open and close of these floated panels from being animated (defaults to <tt>true</tt>).
	*/
	/**
	* @cfg {Boolean} autoHide
	* When a collapsed region's bar is clicked, the region's panel will be displayed as a floated
	* panel.  If <tt>autoHide = true</tt>, the panel will automatically hide after the user mouses
	* out of the panel.  If <tt>autoHide = false</tt>, the panel will continue to display until the
	* user clicks outside of the panel (defaults to <tt>true</tt>).
	*/
	/**
	* @cfg {String} collapseMode
	* <tt>collapseMode</tt> supports two configuration values:<div class="mdetail-params"><ul>
	* <li><b><tt>undefined</tt></b> (default)<div class="sub-desc">By default, {@link #collapsible}
	* regions are collapsed by clicking the expand/collapse tool button that renders into the region's
	* title bar.</div></li>
	* <li><b><tt>'mini'</tt></b><div class="sub-desc">Optionally, when <tt>collapseMode</tt> is set to
	* <tt>'mini'</tt> the region's split bar will also display a small collapse button in the center of
	* the bar. In <tt>'mini'</tt> mode the region will collapse to a thinner bar than in normal mode.
	* </div></li>
	* </ul></div></p>
	* <p><b>Note</b>: if a collapsible region does not have a title bar, then set <tt>collapseMode =
	* 'mini'</tt> and <tt>{@link #split} = true</tt> in order for the region to be {@link #collapsible}
	* by the user as the expand/collapse tool button (that would go in the title bar) will not be rendered.</p>
	* <p>See also <tt>{@link #cmargins}</tt>.</p>
	*/
	/**
	* @cfg {Object} margins
	* An object containing margins to apply to the region when in the expanded state in the
	* format:<pre><code>
	{
	top: (top margin),
	right: (right margin),
	bottom: (bottom margin),
	left: (left margin)
	}</code></pre>
	* <p>May also be a string containing space-separated, numeric margin values. The order of the
	* sides associated with each value matches the way CSS processes margin values:</p>
	* <p><div class="mdetail-params"><ul>
	* <li>If there is only one value, it applies to all sides.</li>
	* <li>If there are two values, the top and bottom borders are set to the first value and the
	* right and left are set to the second.</li>
	* <li>If there are three values, the top is set to the first value, the left and right are set
	* to the second, and the bottom is set to the third.</li>
	* <li>If there are four values, they apply to the top, right, bottom, and left, respectively.</li>
	* </ul></div></p>
	* <p>Defaults to:</p><pre><code>
	* {top:0, right:0, bottom:0, left:0}
	* </code></pre>
	*/
	/**
	* @cfg {Object} cmargins
	* An object containing margins to apply to the region when in the collapsed state in the
	* format:<pre><code>
	{
	top: (top margin),
	right: (right margin),
	bottom: (bottom margin),
	left: (left margin)
	}</code></pre>
	* <p>May also be a string containing space-separated, numeric margin values. The order of the
	* sides associated with each value matches the way CSS processes margin values.</p>
	* <p><ul>
	* <li>If there is only one value, it applies to all sides.</li>
	* <li>If there are two values, the top and bottom borders are set to the first value and the
	* right and left are set to the second.</li>
	* <li>If there are three values, the top is set to the first value, the left and right are set
	* to the second, and the bottom is set to the third.</li>
	* <li>If there are four values, they apply to the top, right, bottom, and left, respectively.</li>
	* </ul></p>
	*/
	/**
	* @cfg {Boolean} collapsible
	* <p><tt>true</tt> to allow the user to collapse this region (defaults to <tt>false</tt>).  If
	* <tt>true</tt>, an expand/collapse tool button will automatically be rendered into the title
	* bar of the region, otherwise the button will not be shown.</p>
	* <p><b>Note</b>: that a title bar is required to display the collapse/expand toggle button -- if
	* no <tt>title</tt> is specified for the region's panel, the region will only be collapsible if
	* <tt>{@link #collapseMode} = 'mini'</tt> and <tt>{@link #split} = true</tt>.
	*/
	collapsible: false,
	/**
	* @cfg {Boolean} split
	* <p><tt>true</tt> to create a {@link Ext.layout.BorderLayout.SplitRegion SplitRegion} and
	* display a 5px wide {@link Ext.SplitBar} between this region and its neighbor, allowing the user to
	* resize the regions dynamically.  Defaults to <tt>false</tt> creating a
	* {@link Ext.layout.BorderLayout.Region Region}.</p><br>
	* <p><b>Notes</b>:</p><div class="mdetail-params"><ul>
	* <li>this configuration option is ignored if <tt>region='center'</tt></li>
	* <li>when <tt>split == true</tt>, it is common to specify a
	* <tt>{@link Ext.SplitBar#minSize minSize}</tt> and <tt>{@link Ext.SplitBar#maxSize maxSize}</tt>
	* for the {@link Ext.BoxComponent BoxComponent} representing the region. These are not native
	* configs of {@link Ext.BoxComponent BoxComponent}, and are used only by this class.</li>
	* <li>if <tt>{@link #collapseMode} = 'mini'</tt> requires <tt>split = true</tt> to reserve space
	* for the collapse tool</tt></li>
	* </ul></div>
	*/
	split: false,
	/**
	* @cfg {Boolean} floatable
	* <tt>true</tt> to allow clicking a collapsed region's bar to display the region's panel floated
	* above the layout, <tt>false</tt> to force the user to fully expand a collapsed region by
	* clicking the expand button to see it again (defaults to <tt>true</tt>).
	*/
	floatable: true,
	/**
	* @cfg {Number} minWidth
	* <p>The minimum allowable width in pixels for this region (defaults to <tt>50</tt>).
	* <tt>maxWidth</tt> may also be specified.</p><br>
	* <p><b>Note</b>: setting the <tt>{@link Ext.SplitBar#minSize minSize}</tt> /
	* <tt>{@link Ext.SplitBar#maxSize maxSize}</tt> supersedes any specified
	* <tt>minWidth</tt> / <tt>maxWidth</tt>.</p>
	*/
	minWidth: 50,
	/**
	* @cfg {Number} minHeight
	* The minimum allowable height in pixels for this region (defaults to <tt>50</tt>)
	* <tt>maxHeight</tt> may also be specified.</p><br>
	* <p><b>Note</b>: setting the <tt>{@link Ext.SplitBar#minSize minSize}</tt> /
	* <tt>{@link Ext.SplitBar#maxSize maxSize}</tt> supersedes any specified
	* <tt>minHeight</tt> / <tt>maxHeight</tt>.</p>
	*/
	minHeight: 50,

	// private
	defaultMargins: { left: 0, top: 0, right: 0, bottom: 0 },
	// private
	defaultNSCMargins: { left: 5, top: 5, right: 5, bottom: 5 },
	// private
	defaultEWCMargins: { left: 5, top: 0, right: 5, bottom: 0 },
	floatingZIndex: 100,

	/**
	* True if this region is collapsed. Read-only.
	* @type Boolean
	* @property
	*/
	isCollapsed: false,

	/**
	* This region's panel.  Read-only.
	* @type Ext.Panel
	* @property panel
	*/
	/**
	* This region's layout.  Read-only.
	* @type Layout
	* @property layout
	*/
	/**
	* This region's layout position (north, south, east, west or center).  Read-only.
	* @type String
	* @property position
	*/

	// private
	render: function (ct, p) {
		this.panel = p;
		p.el.enableDisplayMode();
		this.targetEl = ct;
		this.el = p.el;

		var gs = p.getState, ps = this.position;
		p.getState = function () {
			return Ext.apply(gs.call(p) || {}, this.state);
		} .createDelegate(this);

		if (ps != 'center') {
			p.allowQueuedExpand = false;
			p.on({
				beforecollapse: this.beforeCollapse,
				collapse: this.onCollapse,
				beforeexpand: this.beforeExpand,
				expand: this.onExpand,
				hide: this.onHide,
				show: this.onShow,
				scope: this
			});
			if (this.collapsible || this.floatable) {
				p.collapseEl = 'el';
				p.slideAnchor = this.getSlideAnchor();
			}
			if (p.tools && p.tools.toggle) {
				p.tools.toggle.addClass('x-tool-collapse-' + ps);
				p.tools.toggle.addClassOnOver('x-tool-collapse-' + ps + '-over');
			}
		}
	},

	// private
	getCollapsedEl: function () {
		if (!this.collapsedEl) {
			if (!this.toolTemplate) {
				var tt = new Ext.Template(
                     '<div class="x-tool x-tool-{id}">&#160;</div>'
                );
				tt.disableFormats = true;
				tt.compile();
				Ext.layout.BorderLayout.Region.prototype.toolTemplate = tt;
			}
			this.collapsedEl = this.targetEl.createChild({
				cls: "x-layout-collapsed x-layout-collapsed-" + this.position,
				id: this.panel.id + '-xcollapsed'
			});
			this.collapsedEl.enableDisplayMode('block');

			if (this.collapseMode == 'mini') {
				this.collapsedEl.addClass('x-layout-cmini-' + this.position);
				this.miniCollapsedEl = this.collapsedEl.createChild({
					cls: "x-layout-mini x-layout-mini-" + this.position, html: "&#160;"
				});
				this.miniCollapsedEl.addClassOnOver('x-layout-mini-over');
				this.collapsedEl.addClassOnOver("x-layout-collapsed-over");
				this.collapsedEl.on('click', this.onExpandClick, this, { stopEvent: true });
			} else {
				if (this.collapsible !== false && !this.hideCollapseTool) {
					var t = this.toolTemplate.append(
                            this.collapsedEl.dom,
                            { id: 'expand-' + this.position }, true);
					t.addClassOnOver('x-tool-expand-' + this.position + '-over');
					t.on('click', this.onExpandClick, this, { stopEvent: true });
				}
				if (this.floatable !== false || this.titleCollapse) {
					this.collapsedEl.addClassOnOver("x-layout-collapsed-over");
					this.collapsedEl.on("click", this[this.floatable ? 'collapseClick' : 'onExpandClick'], this);
				}
			}
		}
		return this.collapsedEl;
	},

	// private
	onExpandClick: function (e) {
		if (this.isSlid) {
			this.panel.expand(false);
		} else {
			this.panel.expand();
		}
	},

	// private
	onCollapseClick: function (e) {
		this.panel.collapse();
	},

	// private
	beforeCollapse: function (p, animate) {
		this.lastAnim = animate;
		if (this.splitEl) {
			this.splitEl.hide();
		}
		this.getCollapsedEl().show();
		var el = this.panel.getEl();
		this.originalZIndex = el.getStyle('z-index');
		el.setStyle('z-index', 100);
		this.isCollapsed = true;
		this.layout.layout();
	},

	// private
	onCollapse: function (animate) {
		this.panel.el.setStyle('z-index', 1);
		if (this.lastAnim === false || this.panel.animCollapse === false) {
			this.getCollapsedEl().dom.style.visibility = 'visible';
		} else {
			this.getCollapsedEl().slideIn(this.panel.slideAnchor, { duration: .2 });
		}
		this.state.collapsed = true;
		this.panel.saveState();
	},

	// private
	beforeExpand: function (animate) {
		if (this.isSlid) {
			this.afterSlideIn();
		}
		var c = this.getCollapsedEl();
		this.el.show();
		if (this.position == 'east' || this.position == 'west') {
			this.panel.setSize(undefined, c.getHeight());
		} else {
			this.panel.setSize(c.getWidth(), undefined);
		}
		c.hide();
		c.dom.style.visibility = 'hidden';
		this.panel.el.setStyle('z-index', this.floatingZIndex);
	},

	// private
	onExpand: function () {
		this.isCollapsed = false;
		if (this.splitEl) {
			this.splitEl.show();
		}
		this.layout.layout();
		this.panel.el.setStyle('z-index', this.originalZIndex);
		this.state.collapsed = false;
		this.panel.saveState();
	},

	// private
	collapseClick: function (e) {
		if (this.isSlid) {
			e.stopPropagation();
			this.slideIn();
		} else {
			e.stopPropagation();
			this.slideOut();
		}
	},

	// private
	onHide: function () {
		if (this.isCollapsed) {
			this.getCollapsedEl().hide();
		} else if (this.splitEl) {
			this.splitEl.hide();
		}
	},

	// private
	onShow: function () {
		if (this.isCollapsed) {
			this.getCollapsedEl().show();
		} else if (this.splitEl) {
			this.splitEl.show();
		}
	},

	/**
	* True if this region is currently visible, else false.
	* @return {Boolean}
	*/
	isVisible: function () {
		return !this.panel.hidden;
	},

	/**
	* Returns the current margins for this region.  If the region is collapsed, the
	* {@link #cmargins} (collapsed margins) value will be returned, otherwise the
	* {@link #margins} value will be returned.
	* @return {Object} An object containing the element's margins: <tt>{left: (left
	* margin), top: (top margin), right: (right margin), bottom: (bottom margin)}</tt>
	*/
	getMargins: function () {
		return this.isCollapsed && this.cmargins ? this.cmargins : this.margins;
	},

	/**
	* Returns the current size of this region.  If the region is collapsed, the size of the
	* collapsedEl will be returned, otherwise the size of the region's panel will be returned.
	* @return {Object} An object containing the element's size: <tt>{width: (element width),
	* height: (element height)}</tt>
	*/
	getSize: function () {
		return this.isCollapsed ? this.getCollapsedEl().getSize() : this.panel.getSize();
	},

	/**
	* Sets the specified panel as the container element for this region.
	* @param {Ext.Panel} panel The new panel
	*/
	setPanel: function (panel) {
		this.panel = panel;
	},

	/**
	* Returns the minimum allowable width for this region.
	* @return {Number} The minimum width
	*/
	getMinWidth: function () {
		return this.minWidth;
	},

	/**
	* Returns the minimum allowable height for this region.
	* @return {Number} The minimum height
	*/
	getMinHeight: function () {
		return this.minHeight;
	},

	// private
	applyLayoutCollapsed: function (box) {
		var ce = this.getCollapsedEl();
		ce.setLeftTop(box.x, box.y);
		ce.setSize(box.width, box.height);
	},

	// private
	applyLayout: function (box) {
		if (this.isCollapsed) {
			this.applyLayoutCollapsed(box);
		} else {
			this.panel.setPosition(box.x, box.y);
			this.panel.setSize(box.width, box.height);
		}
	},

	// private
	beforeSlide: function () {
		this.panel.beforeEffect();
	},

	// private
	afterSlide: function () {
		this.panel.afterEffect();
	},

	// private
	initAutoHide: function () {
		if (this.autoHide !== false) {
			if (!this.autoHideHd) {
				this.autoHideSlideTask = new Ext.util.DelayedTask(this.slideIn, this);
				this.autoHideHd = {
					"mouseout": function (e) {
						if (!e.within(this.el, true)) {
							this.autoHideSlideTask.delay(500);
						}
					},
					"mouseover": function (e) {
						this.autoHideSlideTask.cancel();
					},
					scope: this
				};
			}
			this.el.on(this.autoHideHd);
			this.collapsedEl.on(this.autoHideHd);
		}
	},

	// private
	clearAutoHide: function () {
		if (this.autoHide !== false) {
			this.el.un("mouseout", this.autoHideHd.mouseout);
			this.el.un("mouseover", this.autoHideHd.mouseover);
			this.collapsedEl.un("mouseout", this.autoHideHd.mouseout);
			this.collapsedEl.un("mouseover", this.autoHideHd.mouseover);
		}
	},

	// private
	clearMonitor: function () {
		Ext.getDoc().un("click", this.slideInIf, this);
	},

	/**
	* If this Region is {@link #floatable}, this method slides this Region into full visibility <i>over the top
	* of the center Region</i> where it floats until either {@link #slideIn} is called, or other regions of the layout
	* are clicked, or the mouse exits the Region.
	*/
	slideOut: function () {
		if (this.isSlid || this.el.hasActiveFx()) {
			return;
		}
		this.isSlid = true;
		var ts = this.panel.tools, dh, pc;
		if (ts && ts.toggle) {
			ts.toggle.hide();
		}
		this.el.show();

		// Temporarily clear the collapsed flag so we can onResize the panel on the slide
		pc = this.panel.collapsed;
		this.panel.collapsed = false;

		if (this.position == 'east' || this.position == 'west') {
			// Temporarily clear the deferHeight flag so we can size the height on the slide
			dh = this.panel.deferHeight;
			this.panel.deferHeight = false;

			this.panel.setSize(undefined, this.collapsedEl.getHeight());

			// Put the deferHeight flag back after setSize
			this.panel.deferHeight = dh;
		} else {
			this.panel.setSize(this.collapsedEl.getWidth(), undefined);
		}

		// Put the collapsed flag back after onResize
		this.panel.collapsed = pc;

		this.restoreLT = [this.el.dom.style.left, this.el.dom.style.top];
		this.el.alignTo(this.collapsedEl, this.getCollapseAnchor());
		this.el.setStyle("z-index", this.floatingZIndex + 2);
		this.panel.el.replaceClass('x-panel-collapsed', 'x-panel-floating');
		if (this.animFloat !== false) {
			this.beforeSlide();
			this.el.slideIn(this.getSlideAnchor(), {
				callback: function () {
					this.afterSlide();
					this.initAutoHide();
					Ext.getDoc().on("click", this.slideInIf, this);
				},
				scope: this,
				block: true
			});
		} else {
			this.initAutoHide();
			Ext.getDoc().on("click", this.slideInIf, this);
		}
	},

	// private
	afterSlideIn: function () {
		this.clearAutoHide();
		this.isSlid = false;
		this.clearMonitor();
		this.el.setStyle("z-index", "");
		this.panel.el.replaceClass('x-panel-floating', 'x-panel-collapsed');
		this.el.dom.style.left = this.restoreLT[0];
		this.el.dom.style.top = this.restoreLT[1];

		var ts = this.panel.tools;
		if (ts && ts.toggle) {
			ts.toggle.show();
		}
	},

	/**
	* If this Region is {@link #floatable}, and this Region has been slid into floating visibility, then this method slides
	* this region back into its collapsed state.
	*/
	slideIn: function (cb) {
		if (!this.isSlid || this.el.hasActiveFx()) {
			Ext.callback(cb);
			return;
		}
		this.isSlid = false;
		if (this.animFloat !== false) {
			this.beforeSlide();
			this.el.slideOut(this.getSlideAnchor(), {
				callback: function () {
					this.el.hide();
					this.afterSlide();
					this.afterSlideIn();
					Ext.callback(cb);
				},
				scope: this,
				block: true
			});
		} else {
			this.el.hide();
			this.afterSlideIn();
		}
	},

	// private
	slideInIf: function (e) {
		if (!e.within(this.el)) {
			this.slideIn();
		}
	},

	// private
	anchors: {
		"west": "left",
		"east": "right",
		"north": "top",
		"south": "bottom"
	},

	// private
	sanchors: {
		"west": "l",
		"east": "r",
		"north": "t",
		"south": "b"
	},

	// private
	canchors: {
		"west": "tl-tr",
		"east": "tr-tl",
		"north": "tl-bl",
		"south": "bl-tl"
	},

	// private
	getAnchor: function () {
		return this.anchors[this.position];
	},

	// private
	getCollapseAnchor: function () {
		return this.canchors[this.position];
	},

	// private
	getSlideAnchor: function () {
		return this.sanchors[this.position];
	},

	// private
	getAlignAdj: function () {
		var cm = this.cmargins;
		switch (this.position) {
			case "west":
				return [0, 0];
				break;
			case "east":
				return [0, 0];
				break;
			case "north":
				return [0, 0];
				break;
			case "south":
				return [0, 0];
				break;
		}
	},

	// private
	getExpandAdj: function () {
		var c = this.collapsedEl, cm = this.cmargins;
		switch (this.position) {
			case "west":
				return [-(cm.right + c.getWidth() + cm.left), 0];
				break;
			case "east":
				return [cm.right + c.getWidth() + cm.left, 0];
				break;
			case "north":
				return [0, -(cm.top + cm.bottom + c.getHeight())];
				break;
			case "south":
				return [0, cm.top + cm.bottom + c.getHeight()];
				break;
		}
	},

	destroy: function () {
		if (this.autoHideSlideTask && this.autoHideSlideTask.cancel) {
			this.autoHideSlideTask.cancel();
		}
		Ext.destroy(this.miniCollapsedEl, this.collapsedEl);
	}
};

/**
* @class Ext.layout.BorderLayout.SplitRegion
* @extends Ext.layout.BorderLayout.Region
* <p>This is a specialized type of {@link Ext.layout.BorderLayout.Region BorderLayout region} that
* has a built-in {@link Ext.SplitBar} for user resizing of regions.  The movement of the split bar
* is configurable to move either {@link #tickSize smooth or incrementally}.</p>
* @constructor
* Create a new SplitRegion.
* @param {Layout} layout The {@link Ext.layout.BorderLayout BorderLayout} instance that is managing this Region.
* @param {Object} config The configuration options
* @param {String} position The region position.  Valid values are: north, south, east, west and center.  Every
* BorderLayout must have a center region for the primary content -- all other regions are optional.
*/
Ext.layout.BorderLayout.SplitRegion = function (layout, config, pos) {
	Ext.layout.BorderLayout.SplitRegion.superclass.constructor.call(this, layout, config, pos);
	// prevent switch
	this.applyLayout = this.applyFns[pos];
};

Ext.extend(Ext.layout.BorderLayout.SplitRegion, Ext.layout.BorderLayout.Region, {
	/**
	* @cfg {Number} tickSize
	* The increment, in pixels by which to move this Region's {@link Ext.SplitBar SplitBar}.
	* By default, the {@link Ext.SplitBar SplitBar} moves smoothly.
	*/
	/**
	* @cfg {String} splitTip
	* The tooltip to display when the user hovers over a
	* {@link Ext.layout.BorderLayout.Region#collapsible non-collapsible} region's split bar
	* (defaults to <tt>"Drag to resize."</tt>).  Only applies if
	* <tt>{@link #useSplitTips} = true</tt>.
	*/
	splitTip: "Drag to resize.",
	/**
	* @cfg {String} collapsibleSplitTip
	* The tooltip to display when the user hovers over a
	* {@link Ext.layout.BorderLayout.Region#collapsible collapsible} region's split bar
	* (defaults to "Drag to resize. Double click to hide."). Only applies if
	* <tt>{@link #useSplitTips} = true</tt>.
	*/
	collapsibleSplitTip: "Drag to resize. Double click to hide.",
	/**
	* @cfg {Boolean} useSplitTips
	* <tt>true</tt> to display a tooltip when the user hovers over a region's split bar
	* (defaults to <tt>false</tt>).  The tooltip text will be the value of either
	* <tt>{@link #splitTip}</tt> or <tt>{@link #collapsibleSplitTip}</tt> as appropriate.
	*/
	useSplitTips: false,

	// private
	splitSettings: {
		north: {
			orientation: Ext.SplitBar.VERTICAL,
			placement: Ext.SplitBar.TOP,
			maxFn: 'getVMaxSize',
			minProp: 'minHeight',
			maxProp: 'maxHeight'
		},
		south: {
			orientation: Ext.SplitBar.VERTICAL,
			placement: Ext.SplitBar.BOTTOM,
			maxFn: 'getVMaxSize',
			minProp: 'minHeight',
			maxProp: 'maxHeight'
		},
		east: {
			orientation: Ext.SplitBar.HORIZONTAL,
			placement: Ext.SplitBar.RIGHT,
			maxFn: 'getHMaxSize',
			minProp: 'minWidth',
			maxProp: 'maxWidth'
		},
		west: {
			orientation: Ext.SplitBar.HORIZONTAL,
			placement: Ext.SplitBar.LEFT,
			maxFn: 'getHMaxSize',
			minProp: 'minWidth',
			maxProp: 'maxWidth'
		}
	},

	// private
	applyFns: {
		west: function (box) {
			if (this.isCollapsed) {
				return this.applyLayoutCollapsed(box);
			}
			var sd = this.splitEl.dom, s = sd.style;
			this.panel.setPosition(box.x, box.y);
			var sw = sd.offsetWidth;
			s.left = (box.x + box.width - sw) + 'px';
			s.top = (box.y) + 'px';
			s.height = Math.max(0, box.height) + 'px';
			this.panel.setSize(box.width - sw, box.height);
		},
		east: function (box) {
			if (this.isCollapsed) {
				return this.applyLayoutCollapsed(box);
			}
			var sd = this.splitEl.dom, s = sd.style;
			var sw = sd.offsetWidth;
			this.panel.setPosition(box.x + sw, box.y);
			s.left = (box.x) + 'px';
			s.top = (box.y) + 'px';
			s.height = Math.max(0, box.height) + 'px';
			this.panel.setSize(box.width - sw, box.height);
		},
		north: function (box) {
			if (this.isCollapsed) {
				return this.applyLayoutCollapsed(box);
			}
			var sd = this.splitEl.dom, s = sd.style;
			var sh = sd.offsetHeight;
			this.panel.setPosition(box.x, box.y);
			s.left = (box.x) + 'px';
			s.top = (box.y + box.height - sh) + 'px';
			s.width = Math.max(0, box.width) + 'px';
			this.panel.setSize(box.width, box.height - sh);
		},
		south: function (box) {
			if (this.isCollapsed) {
				return this.applyLayoutCollapsed(box);
			}
			var sd = this.splitEl.dom, s = sd.style;
			var sh = sd.offsetHeight;
			this.panel.setPosition(box.x, box.y + sh);
			s.left = (box.x) + 'px';
			s.top = (box.y) + 'px';
			s.width = Math.max(0, box.width) + 'px';
			this.panel.setSize(box.width, box.height - sh);
		}
	},

	// private
	render: function (ct, p) {
		Ext.layout.BorderLayout.SplitRegion.superclass.render.call(this, ct, p);

		var ps = this.position;

		this.splitEl = ct.createChild({
			cls: "x-layout-split x-layout-split-" + ps, html: "&#160;",
			id: this.panel.id + '-xsplit'
		});

		if (this.collapseMode == 'mini') {
			this.miniSplitEl = this.splitEl.createChild({
				cls: "x-layout-mini x-layout-mini-" + ps, html: "&#160;"
			});
			this.miniSplitEl.addClassOnOver('x-layout-mini-over');
			this.miniSplitEl.on('click', this.onCollapseClick, this, { stopEvent: true });
		}

		var s = this.splitSettings[ps];

		this.split = new Ext.SplitBar(this.splitEl.dom, p.el, s.orientation);
		this.split.tickSize = this.tickSize;
		this.split.placement = s.placement;
		this.split.getMaximumSize = this[s.maxFn].createDelegate(this);
		this.split.minSize = this.minSize || this[s.minProp];
		this.split.on("beforeapply", this.onSplitMove, this);
		this.split.useShim = this.useShim === true;
		this.maxSize = this.maxSize || this[s.maxProp];

		if (p.hidden) {
			this.splitEl.hide();
		}

		if (this.useSplitTips) {
			this.splitEl.dom.title = this.collapsible ? this.collapsibleSplitTip : this.splitTip;
		}
		if (this.collapsible) {
			this.splitEl.on("dblclick", this.onCollapseClick, this);
		}
	},

	//docs inherit from superclass
	getSize: function () {
		if (this.isCollapsed) {
			return this.collapsedEl.getSize();
		}
		var s = this.panel.getSize();
		if (this.position == 'north' || this.position == 'south') {
			s.height += this.splitEl.dom.offsetHeight;
		} else {
			s.width += this.splitEl.dom.offsetWidth;
		}
		return s;
	},

	// private
	getHMaxSize: function () {
		var cmax = this.maxSize || 10000;
		var center = this.layout.center;
		return Math.min(cmax, (this.el.getWidth() + center.el.getWidth()) - center.getMinWidth());
	},

	// private
	getVMaxSize: function () {
		var cmax = this.maxSize || 10000;
		var center = this.layout.center;
		return Math.min(cmax, (this.el.getHeight() + center.el.getHeight()) - center.getMinHeight());
	},

	// private
	onSplitMove: function (split, newSize) {
		var s = this.panel.getSize();
		this.lastSplitSize = newSize;
		if (this.position == 'north' || this.position == 'south') {
			this.panel.setSize(s.width, newSize);
			this.state.height = newSize;
		} else {
			this.panel.setSize(newSize, s.height);
			this.state.width = newSize;
		}
		this.layout.layout();
		this.panel.saveState();
		return false;
	},

	/**
	* Returns a reference to the split bar in use by this region.
	* @return {Ext.SplitBar} The split bar
	*/
	getSplitBar: function () {
		return this.split;
	},

	// inherit docs
	destroy: function () {
		Ext.destroy(this.miniSplitEl, this.split, this.splitEl);
		Ext.layout.BorderLayout.SplitRegion.superclass.destroy.call(this);
	}
});

Ext.Container.LAYOUTS['border'] = Ext.layout.BorderLayout; /**
 * @class Ext.layout.FormLayout
 * @extends Ext.layout.AnchorLayout
 * <p>This layout manager is specifically designed for rendering and managing child Components of
 * {@link Ext.form.FormPanel forms}. It is responsible for rendering the labels of
 * {@link Ext.form.Field Field}s.</p>
 *
 * <p>This layout manager is used when a Container is configured with the <tt>layout:'form'</tt>
 * {@link Ext.Container#layout layout} config option, and should generally not need to be created directly
 * via the new keyword. See <tt><b>{@link Ext.Container#layout}</b></tt> for additional details.</p>
 *
 * <p>In an application, it will usually be preferrable to use a {@link Ext.form.FormPanel FormPanel}
 * (which is configured with FormLayout as its layout class by default) since it also provides built-in
 * functionality for {@link Ext.form.BasicForm#doAction loading, validating and submitting} the form.</p>
 *
 * <p>A {@link Ext.Container Container} <i>using</i> the FormLayout layout manager (e.g.
 * {@link Ext.form.FormPanel} or specifying <tt>layout:'form'</tt>) can also accept the following
 * layout-specific config properties:<div class="mdetail-params"><ul>
 * <li><b><tt>{@link Ext.form.FormPanel#hideLabels hideLabels}</tt></b></li>
 * <li><b><tt>{@link Ext.form.FormPanel#labelAlign labelAlign}</tt></b></li>
 * <li><b><tt>{@link Ext.form.FormPanel#labelPad labelPad}</tt></b></li>
 * <li><b><tt>{@link Ext.form.FormPanel#labelSeparator labelSeparator}</tt></b></li>
 * <li><b><tt>{@link Ext.form.FormPanel#labelWidth labelWidth}</tt></b></li>
 * </ul></div></p>
 *
 * <p>Any Component (including Fields) managed by FormLayout accepts the following as a config option:
 * <div class="mdetail-params"><ul>
 * <li><b><tt>{@link Ext.Component#anchor anchor}</tt></b></li>
 * </ul></div></p>
 *
 * <p>Any Component managed by FormLayout may be rendered as a form field (with an associated label) by
 * configuring it with a non-null <b><tt>{@link Ext.Component#fieldLabel fieldLabel}</tt></b>. Components configured
 * in this way may be configured with the following options which affect the way the FormLayout renders them:
 * <div class="mdetail-params"><ul>
 * <li><b><tt>{@link Ext.Component#clearCls clearCls}</tt></b></li>
 * <li><b><tt>{@link Ext.Component#fieldLabel fieldLabel}</tt></b></li>
 * <li><b><tt>{@link Ext.Component#hideLabel hideLabel}</tt></b></li>
 * <li><b><tt>{@link Ext.Component#itemCls itemCls}</tt></b></li>
 * <li><b><tt>{@link Ext.Component#labelSeparator labelSeparator}</tt></b></li>
 * <li><b><tt>{@link Ext.Component#labelStyle labelStyle}</tt></b></li>
 * </ul></div></p>
 *
 * <p>Example usage:</p>
 * <pre><code>
// Required if showing validation messages
Ext.QuickTips.init();

// While you can create a basic Panel with layout:'form', practically
// you should usually use a FormPanel to also get its form functionality
// since it already creates a FormLayout internally.
var form = new Ext.form.FormPanel({
    title: 'Form Layout',
    bodyStyle: 'padding:15px',
    width: 350,
    defaultType: 'textfield',
    defaults: {
        // applied to each contained item
        width: 230,
        msgTarget: 'side'
    },
    items: [{
            fieldLabel: 'First Name',
            name: 'first',
            allowBlank: false,
            {@link Ext.Component#labelSeparator labelSeparator}: ':' // override labelSeparator layout config
        },{
            fieldLabel: 'Last Name',
            name: 'last'
        },{
            fieldLabel: 'Email',
            name: 'email',
            vtype:'email'
        }, {
            xtype: 'textarea',
            hideLabel: true,     // override hideLabels layout config
            name: 'msg',
            anchor: '100% -53'
        }
    ],
    buttons: [
        {text: 'Save'},
        {text: 'Cancel'}
    ],
    layoutConfig: {
        {@link #labelSeparator}: '~' // superseded by assignment below
    },
    // config options applicable to container when layout='form':
    hideLabels: false,
    labelAlign: 'left',   // or 'right' or 'top'
    {@link Ext.form.FormPanel#labelSeparator labelSeparator}: '>>', // takes precedence over layoutConfig value
    labelWidth: 65,       // defaults to 100
    labelPad: 8           // defaults to 5, must specify labelWidth to be honored
});
</code></pre>
 */
Ext.layout.FormLayout = Ext.extend(Ext.layout.AnchorLayout, {

	/**
	* @cfg {String} labelSeparator
	* See {@link Ext.form.FormPanel}.{@link Ext.form.FormPanel#labelSeparator labelSeparator}.  Configuration
	* of this property at the <b>container</b> level takes precedence.
	*/
	labelSeparator: ':',

	/**
	* Read only. The CSS style specification string added to field labels in this layout if not
	* otherwise {@link Ext.Component#labelStyle specified by each contained field}.
	* @type String
	* @property labelStyle
	*/

	/**
	* @cfg {Boolean} trackLabels
	* True to show/hide the field label when the field is hidden. Defaults to <tt>false</tt>.
	*/
	trackLabels: false,

	type: 'form',

	onRemove: function (c) {
		Ext.layout.FormLayout.superclass.onRemove.call(this, c);
		if (this.trackLabels) {
			c.un('show', this.onFieldShow, this);
			c.un('hide', this.onFieldHide, this);
		}
		// check for itemCt, since we may be removing a fieldset or something similar
		var el = c.getPositionEl(),
            ct = c.getItemCt && c.getItemCt();
		if (c.rendered && ct) {
			if (el && el.dom) {
				el.insertAfter(ct);
			}
			Ext.destroy(ct);
			Ext.destroyMembers(c, 'label', 'itemCt');
			if (c.customItemCt) {
				Ext.destroyMembers(c, 'getItemCt', 'customItemCt');
			}
		}
	},

	// private
	setContainer: function (ct) {
		Ext.layout.FormLayout.superclass.setContainer.call(this, ct);
		if (ct.labelAlign) {
			ct.addClass('x-form-label-' + ct.labelAlign);
		}

		if (ct.hideLabels) {
			Ext.apply(this, {
				labelStyle: 'display:none',
				elementStyle: 'padding-left:0;',
				labelAdjust: 0
			});
		} else {
			this.labelSeparator = ct.labelSeparator || this.labelSeparator;
			ct.labelWidth = ct.labelWidth || 100;
			if (Ext.isNumber(ct.labelWidth)) {
				var pad = Ext.isNumber(ct.labelPad) ? ct.labelPad : 5;
				Ext.apply(this, {
					labelAdjust: ct.labelWidth + pad,
					labelStyle: 'width:' + ct.labelWidth + 'px;',
					elementStyle: 'padding-left:' + (ct.labelWidth + pad) + 'px'
				});
			}
			if (ct.labelAlign == 'top') {
				Ext.apply(this, {
					labelStyle: 'width:auto;',
					labelAdjust: 0,
					elementStyle: 'padding-left:0;'
				});
			}
		}
	},

	// private
	isHide: function (c) {
		return c.hideLabel || this.container.hideLabels;
	},

	onFieldShow: function (c) {
		c.getItemCt().removeClass('x-hide-' + c.hideMode);

		// Composite fields will need to layout after the container is made visible
		if (c.isComposite) {
			c.doLayout();
		}
	},

	onFieldHide: function (c) {
		c.getItemCt().addClass('x-hide-' + c.hideMode);
	},

	//private
	getLabelStyle: function (s) {
		var ls = '', items = [this.labelStyle, s];
		for (var i = 0, len = items.length; i < len; ++i) {
			if (items[i]) {
				ls += items[i];
				if (ls.substr(-1, 1) != ';') {
					ls += ';';
				}
			}
		}
		return ls;
	},

	/**
	* @cfg {Ext.Template} fieldTpl
	* A {@link Ext.Template#compile compile}d {@link Ext.Template} for rendering
	* the fully wrapped, labeled and styled form Field. Defaults to:</p><pre><code>
	new Ext.Template(
	&#39;&lt;div class="x-form-item {itemCls}" tabIndex="-1">&#39;,
	&#39;&lt;&#108;abel for="{id}" style="{labelStyle}" class="x-form-item-&#108;abel">{&#108;abel}{labelSeparator}&lt;/&#108;abel>&#39;,
	&#39;&lt;div class="x-form-element" id="x-form-el-{id}" style="{elementStyle}">&#39;,
	&#39;&lt;/div>&lt;div class="{clearCls}">&lt;/div>&#39;,
	'&lt;/div>'
	);
	</code></pre>
	* <p>This may be specified to produce a different DOM structure when rendering form Fields.</p>
	* <p>A description of the properties within the template follows:</p><div class="mdetail-params"><ul>
	* <li><b><tt>itemCls</tt></b> : String<div class="sub-desc">The CSS class applied to the outermost div wrapper
	* that contains this field label and field element (the default class is <tt>'x-form-item'</tt> and <tt>itemCls</tt>
	* will be added to that). If supplied, <tt>itemCls</tt> at the field level will override the default <tt>itemCls</tt>
	* supplied at the container level.</div></li>
	* <li><b><tt>id</tt></b> : String<div class="sub-desc">The id of the Field</div></li>
	* <li><b><tt>{@link #labelStyle}</tt></b> : String<div class="sub-desc">
	* A CSS style specification string to add to the field label for this field (defaults to <tt>''</tt> or the
	* {@link #labelStyle layout's value for <tt>labelStyle</tt>}).</div></li>
	* <li><b><tt>label</tt></b> : String<div class="sub-desc">The text to display as the label for this
	* field (defaults to <tt>''</tt>)</div></li>
	* <li><b><tt>{@link #labelSeparator}</tt></b> : String<div class="sub-desc">The separator to display after
	* the text of the label for this field (defaults to a colon <tt>':'</tt> or the
	* {@link #labelSeparator layout's value for labelSeparator}). To hide the separator use empty string ''.</div></li>
	* <li><b><tt>elementStyle</tt></b> : String<div class="sub-desc">The styles text for the input element's wrapper.</div></li>
	* <li><b><tt>clearCls</tt></b> : String<div class="sub-desc">The CSS class to apply to the special clearing div
	* rendered directly after each form field wrapper (defaults to <tt>'x-form-clear-left'</tt>)</div></li>
	* </ul></div>
	* <p>Also see <tt>{@link #getTemplateArgs}</tt></p>
	*/

	/**
	* @private
	*
	*/
	renderItem: function (c, position, target) {
		if (c && (c.isFormField || c.fieldLabel) && c.inputType != 'hidden') {
			var args = this.getTemplateArgs(c);
			if (Ext.isNumber(position)) {
				position = target.dom.childNodes[position] || null;
			}
			if (position) {
				c.itemCt = this.fieldTpl.insertBefore(position, args, true);
			} else {
				c.itemCt = this.fieldTpl.append(target, args, true);
			}
			if (!c.getItemCt) {
				// Non form fields don't have getItemCt, apply it here
				// This will get cleaned up in onRemove
				Ext.apply(c, {
					getItemCt: function () {
						return c.itemCt;
					},
					customItemCt: true
				});
			}
			c.label = c.getItemCt().child('label.x-form-item-label');
			if (!c.rendered) {
				c.render('x-form-el-' + c.id);
			} else if (!this.isValidParent(c, target)) {
				Ext.fly('x-form-el-' + c.id).appendChild(c.getPositionEl());
			}
			if (this.trackLabels) {
				if (c.hidden) {
					this.onFieldHide(c);
				}
				c.on({
					scope: this,
					show: this.onFieldShow,
					hide: this.onFieldHide
				});
			}
			this.configureItem(c);
		} else {
			Ext.layout.FormLayout.superclass.renderItem.apply(this, arguments);
		}
	},

	/**
	* <p>Provides template arguments for rendering the fully wrapped, labeled and styled form Field.</p>
	* <p>This method returns an object hash containing properties used by the layout's {@link #fieldTpl}
	* to create a correctly wrapped, labeled and styled form Field. This may be overriden to
	* create custom layouts. The properties which must be returned are:</p><div class="mdetail-params"><ul>
	* <li><b><tt>itemCls</tt></b> : String<div class="sub-desc">The CSS class applied to the outermost div wrapper
	* that contains this field label and field element (the default class is <tt>'x-form-item'</tt> and <tt>itemCls</tt>
	* will be added to that). If supplied, <tt>itemCls</tt> at the field level will override the default <tt>itemCls</tt>
	* supplied at the container level.</div></li>
	* <li><b><tt>id</tt></b> : String<div class="sub-desc">The id of the Field</div></li>
	* <li><b><tt>{@link #labelStyle}</tt></b> : String<div class="sub-desc">
	* A CSS style specification string to add to the field label for this field (defaults to <tt>''</tt> or the
	* {@link #labelStyle layout's value for <tt>labelStyle</tt>}).</div></li>
	* <li><b><tt>label</tt></b> : String<div class="sub-desc">The text to display as the label for this
	* field (defaults to the field's configured fieldLabel property)</div></li>
	* <li><b><tt>{@link #labelSeparator}</tt></b> : String<div class="sub-desc">The separator to display after
	* the text of the label for this field (defaults to a colon <tt>':'</tt> or the
	* {@link #labelSeparator layout's value for labelSeparator}). To hide the separator use empty string ''.</div></li>
	* <li><b><tt>elementStyle</tt></b> : String<div class="sub-desc">The styles text for the input element's wrapper.</div></li>
	* <li><b><tt>clearCls</tt></b> : String<div class="sub-desc">The CSS class to apply to the special clearing div
	* rendered directly after each form field wrapper (defaults to <tt>'x-form-clear-left'</tt>)</div></li>
	* </ul></div>
	* @param (Ext.form.Field} field The {@link Ext.form.Field Field} being rendered.
	* @return {Object} An object hash containing the properties required to render the Field.
	*/
	getTemplateArgs: function (field) {
		var noLabelSep = !field.fieldLabel || field.hideLabel;

		return {
			id: field.id,
			label: field.fieldLabel,
			itemCls: (field.itemCls || this.container.itemCls || '') + (field.hideLabel ? ' x-hide-label' : ''),
			clearCls: field.clearCls || 'x-form-clear-left',
			labelStyle: this.getLabelStyle(field.labelStyle),
			elementStyle: this.elementStyle || '',
			labelSeparator: noLabelSep ? '' : (Ext.isDefined(field.labelSeparator) ? field.labelSeparator : this.labelSeparator)
		};
	},

	// private
	adjustWidthAnchor: function (value, c) {
		if (c.label && !this.isHide(c) && (this.container.labelAlign != 'top')) {
			var adjust = Ext.isIE6 || (Ext.isIE && !Ext.isStrict);
			return value - this.labelAdjust + (adjust ? -3 : 0);
		}
		return value;
	},

	adjustHeightAnchor: function (value, c) {
		if (c.label && !this.isHide(c) && (this.container.labelAlign == 'top')) {
			return value - c.label.getHeight();
		}
		return value;
	},

	// private
	isValidParent: function (c, target) {
		return target && this.container.getEl().contains(c.getPositionEl());
	}

	/**
	* @property activeItem
	* @hide
	*/
});

Ext.Container.LAYOUTS['form'] = Ext.layout.FormLayout;
/**
* @class Ext.layout.AccordionLayout
* @extends Ext.layout.FitLayout
* <p>This is a layout that manages multiple Panels in an expandable accordion style such that only
* <b>one Panel can be expanded at any given time</b>. Each Panel has built-in support for expanding and collapsing.</p>
* <p>Note: Only Ext.Panels <b>and all subclasses of Ext.Panel</b> may be used in an accordion layout Container.</p>
* <p>This class is intended to be extended or created via the <tt><b>{@link Ext.Container#layout layout}</b></tt>
* configuration property.  See <tt><b>{@link Ext.Container#layout}</b></tt> for additional details.</p>
* <p>Example usage:</p>
* <pre><code>
var accordion = new Ext.Panel({
title: 'Accordion Layout',
layout:'accordion',
defaults: {
// applied to each contained panel
bodyStyle: 'padding:15px'
},
layoutConfig: {
// layout-specific configs go here
titleCollapse: false,
animate: true,
activeOnTop: true
},
items: [{
title: 'Panel 1',
html: '&lt;p&gt;Panel content!&lt;/p&gt;'
},{
title: 'Panel 2',
html: '&lt;p&gt;Panel content!&lt;/p&gt;'
},{
title: 'Panel 3',
html: '&lt;p&gt;Panel content!&lt;/p&gt;'
}]
});
</code></pre>
*/
Ext.layout.AccordionLayout = Ext.extend(Ext.layout.FitLayout, {
	/**
	* @cfg {Boolean} fill
	* True to adjust the active item's height to fill the available space in the container, false to use the
	* item's current height, or auto height if not explicitly set (defaults to true).
	*/
	fill: true,
	/**
	* @cfg {Boolean} autoWidth
	* True to set each contained item's width to 'auto', false to use the item's current width (defaults to true).
	* Note that some components, in particular the {@link Ext.grid.GridPanel grid}, will not function properly within
	* layouts if they have auto width, so in such cases this config should be set to false.
	*/
	autoWidth: true,
	/**
	* @cfg {Boolean} titleCollapse
	* True to allow expand/collapse of each contained panel by clicking anywhere on the title bar, false to allow
	* expand/collapse only when the toggle tool button is clicked (defaults to true).  When set to false,
	* {@link #hideCollapseTool} should be false also.
	*/
	titleCollapse: true,
	/**
	* @cfg {Boolean} hideCollapseTool
	* True to hide the contained panels' collapse/expand toggle buttons, false to display them (defaults to false).
	* When set to true, {@link #titleCollapse} should be true also.
	*/
	hideCollapseTool: false,
	/**
	* @cfg {Boolean} collapseFirst
	* True to make sure the collapse/expand toggle button always renders first (to the left of) any other tools
	* in the contained panels' title bars, false to render it last (defaults to false).
	*/
	collapseFirst: false,
	/**
	* @cfg {Boolean} animate
	* True to slide the contained panels open and closed during expand/collapse using animation, false to open and
	* close directly with no animation (defaults to false).  Note: to defer to the specific config setting of each
	* contained panel for this property, set this to undefined at the layout level.
	*/
	animate: false,
	/**
	* @cfg {Boolean} sequence
	* <b>Experimental</b>. If animate is set to true, this will result in each animation running in sequence.
	*/
	sequence: false,
	/**
	* @cfg {Boolean} activeOnTop
	* True to swap the position of each panel as it is expanded so that it becomes the first item in the container,
	* false to keep the panels in the rendered order. <b>This is NOT compatible with "animate:true"</b> (defaults to false).
	*/
	activeOnTop: false,

	type: 'accordion',

	renderItem: function (c) {
		if (this.animate === false) {
			c.animCollapse = false;
		}
		c.collapsible = true;
		if (this.autoWidth) {
			c.autoWidth = true;
		}
		if (this.titleCollapse) {
			c.titleCollapse = true;
		}
		if (this.hideCollapseTool) {
			c.hideCollapseTool = true;
		}
		if (this.collapseFirst !== undefined) {
			c.collapseFirst = this.collapseFirst;
		}
		if (!this.activeItem && !c.collapsed) {
			this.setActiveItem(c, true);
		} else if (this.activeItem && this.activeItem != c) {
			c.collapsed = true;
		}
		Ext.layout.AccordionLayout.superclass.renderItem.apply(this, arguments);
		c.header.addClass('x-accordion-hd');
		c.on('beforeexpand', this.beforeExpand, this);
	},

	onRemove: function (c) {
		Ext.layout.AccordionLayout.superclass.onRemove.call(this, c);
		if (c.rendered) {
			c.header.removeClass('x-accordion-hd');
		}
		c.un('beforeexpand', this.beforeExpand, this);
	},

	// private
	beforeExpand: function (p, anim) {
		var ai = this.activeItem;
		if (ai) {
			if (this.sequence) {
				delete this.activeItem;
				if (!ai.collapsed) {
					ai.collapse({ callback: function () {
						p.expand(anim || true);
					}, scope: this
					});
					return false;
				}
			} else {
				ai.collapse(this.animate);
			}
		}
		this.setActive(p);
		if (this.activeOnTop) {
			p.el.dom.parentNode.insertBefore(p.el.dom, p.el.dom.parentNode.firstChild);
		}
		// Items have been hidden an possibly rearranged, we need to get the container size again.
		this.layout();
	},

	// private
	setItemSize: function (item, size) {
		if (this.fill && item) {
			var hh = 0, i, ct = this.getRenderedItems(this.container), len = ct.length, p;
			// Add up all the header heights
			for (i = 0; i < len; i++) {
				if ((p = ct[i]) != item && !p.hidden) {
					hh += p.header.getHeight();
				}
			};
			// Subtract the header heights from the container size
			size.height -= hh;
			// Call setSize on the container to set the correct height.  For Panels, deferedHeight
			// will simply store this size for when the expansion is done.
			item.setSize(size);
		}
	},

	/**
	* Sets the active (expanded) item in the layout.
	* @param {String/Number} item The string component id or numeric index of the item to activate
	*/
	setActiveItem: function (item) {
		this.setActive(item, true);
	},

	// private
	setActive: function (item, expand) {
		var ai = this.activeItem;
		item = this.container.getComponent(item);
		if (ai != item) {
			if (item.rendered && item.collapsed && expand) {
				item.expand();
			} else {
				if (ai) {
					ai.fireEvent('deactivate', ai);
				}
				this.activeItem = item;
				item.fireEvent('activate', item);
			}
		}
	}
});
Ext.Container.LAYOUTS.accordion = Ext.layout.AccordionLayout;

//backwards compat
Ext.layout.Accordion = Ext.layout.AccordionLayout; /**
 * @class Ext.layout.TableLayout
 * @extends Ext.layout.ContainerLayout
 * <p>This layout allows you to easily render content into an HTML table.  The total number of columns can be
 * specified, and rowspan and colspan can be used to create complex layouts within the table.
 * This class is intended to be extended or created via the layout:'table' {@link Ext.Container#layout} config,
 * and should generally not need to be created directly via the new keyword.</p>
 * <p>Note that when creating a layout via config, the layout-specific config properties must be passed in via
 * the {@link Ext.Container#layoutConfig} object which will then be applied internally to the layout.  In the
 * case of TableLayout, the only valid layout config property is {@link #columns}.  However, the items added to a
 * TableLayout can supply the following table-specific config properties:</p>
 * <ul>
 * <li><b>rowspan</b> Applied to the table cell containing the item.</li>
 * <li><b>colspan</b> Applied to the table cell containing the item.</li>
 * <li><b>cellId</b> An id applied to the table cell containing the item.</li>
 * <li><b>cellCls</b> A CSS class name added to the table cell containing the item.</li>
 * </ul>
 * <p>The basic concept of building up a TableLayout is conceptually very similar to building up a standard
 * HTML table.  You simply add each panel (or "cell") that you want to include along with any span attributes
 * specified as the special config properties of rowspan and colspan which work exactly like their HTML counterparts.
 * Rather than explicitly creating and nesting rows and columns as you would in HTML, you simply specify the
 * total column count in the layoutConfig and start adding panels in their natural order from left to right,
 * top to bottom.  The layout will automatically figure out, based on the column count, rowspans and colspans,
 * how to position each panel within the table.  Just like with HTML tables, your rowspans and colspans must add
 * up correctly in your overall layout or you'll end up with missing and/or extra cells!  Example usage:</p>
 * <pre><code>
// This code will generate a layout table that is 3 columns by 2 rows
// with some spanning included.  The basic layout will be:
// +--------+-----------------+
// |   A    |   B             |
// |        |--------+--------|
// |        |   C    |   D    |
// +--------+--------+--------+
var table = new Ext.Panel({
    title: 'Table Layout',
    layout:'table',
    defaults: {
        // applied to each contained panel
        bodyStyle:'padding:20px'
    },
    layoutConfig: {
        // The total column count must be specified here
        columns: 3
    },
    items: [{
        html: '&lt;p&gt;Cell A content&lt;/p&gt;',
        rowspan: 2
    },{
        html: '&lt;p&gt;Cell B content&lt;/p&gt;',
        colspan: 2
    },{
        html: '&lt;p&gt;Cell C content&lt;/p&gt;',
        cellCls: 'highlight'
    },{
        html: '&lt;p&gt;Cell D content&lt;/p&gt;'
    }]
});
</code></pre>
 */
Ext.layout.TableLayout = Ext.extend(Ext.layout.ContainerLayout, {
	/**
	* @cfg {Number} columns
	* The total number of columns to create in the table for this layout.  If not specified, all Components added to
	* this layout will be rendered into a single row using one column per Component.
	*/

	// private
	monitorResize: false,

	type: 'table',

	targetCls: 'x-table-layout-ct',

	/**
	* @cfg {Object} tableAttrs
	* <p>An object containing properties which are added to the {@link Ext.DomHelper DomHelper} specification
	* used to create the layout's <tt>&lt;table&gt;</tt> element. Example:</p><pre><code>
	{
	xtype: 'panel',
	layout: 'table',
	layoutConfig: {
	tableAttrs: {
	style: {
	width: '100%'
	}
	},
	columns: 3
	}
	}</code></pre>
	*/
	tableAttrs: null,

	// private
	setContainer: function (ct) {
		Ext.layout.TableLayout.superclass.setContainer.call(this, ct);

		this.currentRow = 0;
		this.currentColumn = 0;
		this.cells = [];
	},

	// private
	onLayout: function (ct, target) {
		var cs = ct.items.items, len = cs.length, c, i;

		if (!this.table) {
			target.addClass('x-table-layout-ct');

			this.table = target.createChild(
                Ext.apply({ tag: 'table', cls: 'x-table-layout', cellspacing: 0, cn: { tag: 'tbody'} }, this.tableAttrs), null, true);
		}
		this.renderAll(ct, target);
	},

	// private
	getRow: function (index) {
		var row = this.table.tBodies[0].childNodes[index];
		if (!row) {
			row = document.createElement('tr');
			this.table.tBodies[0].appendChild(row);
		}
		return row;
	},

	// private
	getNextCell: function (c) {
		var cell = this.getNextNonSpan(this.currentColumn, this.currentRow);
		var curCol = this.currentColumn = cell[0], curRow = this.currentRow = cell[1];
		for (var rowIndex = curRow; rowIndex < curRow + (c.rowspan || 1); rowIndex++) {
			if (!this.cells[rowIndex]) {
				this.cells[rowIndex] = [];
			}
			for (var colIndex = curCol; colIndex < curCol + (c.colspan || 1); colIndex++) {
				this.cells[rowIndex][colIndex] = true;
			}
		}
		var td = document.createElement('td');
		if (c.cellId) {
			td.id = c.cellId;
		}
		var cls = 'x-table-layout-cell';
		if (c.cellCls) {
			cls += ' ' + c.cellCls;
		}
		td.className = cls;
		if (c.colspan) {
			td.colSpan = c.colspan;
		}
		if (c.rowspan) {
			td.rowSpan = c.rowspan;
		}
		this.getRow(curRow).appendChild(td);
		return td;
	},

	// private
	getNextNonSpan: function (colIndex, rowIndex) {
		var cols = this.columns;
		while ((cols && colIndex >= cols) || (this.cells[rowIndex] && this.cells[rowIndex][colIndex])) {
			if (cols && colIndex >= cols) {
				rowIndex++;
				colIndex = 0;
			} else {
				colIndex++;
			}
		}
		return [colIndex, rowIndex];
	},

	// private
	renderItem: function (c, position, target) {
		// Ensure we have our inner table to get cells to render into.
		if (!this.table) {
			this.table = target.createChild(
                Ext.apply({ tag: 'table', cls: 'x-table-layout', cellspacing: 0, cn: { tag: 'tbody'} }, this.tableAttrs), null, true);
		}
		if (c && !c.rendered) {
			c.render(this.getNextCell(c));
			this.configureItem(c, position);
		} else if (c && !this.isValidParent(c, target)) {
			var container = this.getNextCell(c);
			container.insertBefore(c.getPositionEl().dom, null);
			c.container = Ext.get(container);
			this.configureItem(c, position);
		}
	},

	// private
	isValidParent: function (c, target) {
		return c.getPositionEl().up('table', 5).dom.parentNode === (target.dom || target);
	}

	/**
	* @property activeItem
	* @hide
	*/
});

Ext.Container.LAYOUTS['table'] = Ext.layout.TableLayout; /**
 * @class Ext.layout.AbsoluteLayout
 * @extends Ext.layout.AnchorLayout
 * <p>This is a layout that inherits the anchoring of <b>{@link Ext.layout.AnchorLayout}</b> and adds the
 * ability for x/y positioning using the standard x and y component config options.</p>
 * <p>This class is intended to be extended or created via the <tt><b>{@link Ext.Container#layout layout}</b></tt>
 * configuration property.  See <tt><b>{@link Ext.Container#layout}</b></tt> for additional details.</p>
 * <p>Example usage:</p>
 * <pre><code>
var form = new Ext.form.FormPanel({
    title: 'Absolute Layout',
    layout:'absolute',
    layoutConfig: {
        // layout-specific configs go here
        extraCls: 'x-abs-layout-item',
    },
    baseCls: 'x-plain',
    url:'save-form.php',
    defaultType: 'textfield',
    items: [{
        x: 0,
        y: 5,
        xtype:'label',
        text: 'Send To:'
    },{
        x: 60,
        y: 0,
        name: 'to',
        anchor:'100%'  // anchor width by percentage
    },{
        x: 0,
        y: 35,
        xtype:'label',
        text: 'Subject:'
    },{
        x: 60,
        y: 30,
        name: 'subject',
        anchor: '100%'  // anchor width by percentage
    },{
        x:0,
        y: 60,
        xtype: 'textarea',
        name: 'msg',
        anchor: '100% 100%'  // anchor width and height
    }]
});
</code></pre>
 */
Ext.layout.AbsoluteLayout = Ext.extend(Ext.layout.AnchorLayout, {

	extraCls: 'x-abs-layout-item',

	type: 'absolute',

	onLayout: function (ct, target) {
		target.position();
		this.paddingLeft = target.getPadding('l');
		this.paddingTop = target.getPadding('t');
		Ext.layout.AbsoluteLayout.superclass.onLayout.call(this, ct, target);
	},

	// private
	adjustWidthAnchor: function (value, comp) {
		return value ? value - comp.getPosition(true)[0] + this.paddingLeft : value;
	},

	// private
	adjustHeightAnchor: function (value, comp) {
		return value ? value - comp.getPosition(true)[1] + this.paddingTop : value;
	}
	/**
	* @property activeItem
	* @hide
	*/
});
Ext.Container.LAYOUTS['absolute'] = Ext.layout.AbsoluteLayout;
/**
* @class Ext.layout.BoxLayout
* @extends Ext.layout.ContainerLayout
* <p>Base Class for HBoxLayout and VBoxLayout Classes. Generally it should not need to be used directly.</p>
*/
Ext.layout.BoxLayout = Ext.extend(Ext.layout.ContainerLayout, {
	/**
	* @cfg {Object} defaultMargins
	* <p>If the individual contained items do not have a <tt>margins</tt>
	* property specified, the default margins from this property will be
	* applied to each item.</p>
	* <br><p>This property may be specified as an object containing margins
	* to apply in the format:</p><pre><code>
	{
	top: (top margin),
	right: (right margin),
	bottom: (bottom margin),
	left: (left margin)
	}</code></pre>
	* <p>This property may also be specified as a string containing
	* space-separated, numeric margin values. The order of the sides associated
	* with each value matches the way CSS processes margin values:</p>
	* <div class="mdetail-params"><ul>
	* <li>If there is only one value, it applies to all sides.</li>
	* <li>If there are two values, the top and bottom borders are set to the
	* first value and the right and left are set to the second.</li>
	* <li>If there are three values, the top is set to the first value, the left
	* and right are set to the second, and the bottom is set to the third.</li>
	* <li>If there are four values, they apply to the top, right, bottom, and
	* left, respectively.</li>
	* </ul></div>
	* <p>Defaults to:</p><pre><code>
	* {top:0, right:0, bottom:0, left:0}
	* </code></pre>
	*/
	defaultMargins: { left: 0, top: 0, right: 0, bottom: 0 },
	/**
	* @cfg {String} padding
	* <p>Sets the padding to be applied to all child items managed by this layout.</p>
	* <p>This property must be specified as a string containing
	* space-separated, numeric padding values. The order of the sides associated
	* with each value matches the way CSS processes padding values:</p>
	* <div class="mdetail-params"><ul>
	* <li>If there is only one value, it applies to all sides.</li>
	* <li>If there are two values, the top and bottom borders are set to the
	* first value and the right and left are set to the second.</li>
	* <li>If there are three values, the top is set to the first value, the left
	* and right are set to the second, and the bottom is set to the third.</li>
	* <li>If there are four values, they apply to the top, right, bottom, and
	* left, respectively.</li>
	* </ul></div>
	* <p>Defaults to: <code>"0"</code></p>
	*/
	padding: '0',
	// documented in subclasses
	pack: 'start',

	// private
	monitorResize: true,
	type: 'box',
	scrollOffset: 0,
	extraCls: 'x-box-item',
	targetCls: 'x-box-layout-ct',
	innerCls: 'x-box-inner',

	constructor: function (config) {
		Ext.layout.BoxLayout.superclass.constructor.call(this, config);

		if (Ext.isString(this.defaultMargins)) {
			this.defaultMargins = this.parseMargins(this.defaultMargins);
		}
	},

	/**
	* @private
	* Runs the child box calculations and caches them in childBoxCache. Subclasses can used these cached values
	* when laying out
	*/
	onLayout: function (container, target) {
		Ext.layout.BoxLayout.superclass.onLayout.call(this, container, target);

		var items = this.getVisibleItems(container),
            tSize = this.getLayoutTargetSize();

		/**
		* @private
		* @property layoutTargetLastSize
		* @type Object
		* Private cache of the last measured size of the layout target. This should never be used except by
		* BoxLayout subclasses during their onLayout run.
		*/
		this.layoutTargetLastSize = tSize;

		/**
		* @private
		* @property childBoxCache
		* @type Array
		* Array of the last calculated height, width, top and left positions of each visible rendered component
		* within the Box layout.
		*/
		this.childBoxCache = this.calculateChildBoxes(items, tSize);

		this.updateInnerCtSize(tSize, this.childBoxCache);
		this.updateChildBoxes(this.childBoxCache.boxes);

		// Putting a box layout into an overflowed container is NOT correct and will make a second layout pass necessary.
		this.handleTargetOverflow(tSize, container, target);
	},

	/**
	* Resizes and repositions each child component
	* @param {Array} boxes The box measurements
	*/
	updateChildBoxes: function (boxes) {
		for (var i = 0, length = boxes.length; i < length; i++) {
			var box = boxes[i],
                comp = box.component;

			if (box.dirtySize) {
				comp.setSize(box.width, box.height);
			}
			// Don't set positions to NaN
			if (isNaN(box.left) || isNaN(box.top)) {
				continue;
			}
			comp.setPosition(box.left, box.top);
		}
	},

	/**
	* @private
	* Called by onRender just before the child components are sized and positioned. This resizes the innerCt
	* to make sure all child items fit within it. We call this before sizing the children because if our child
	* items are larger than the previous innerCt size the browser will insert scrollbars and then remove them
	* again immediately afterwards, giving a performance hit.
	* Subclasses should provide an implementation.
	* @param {Object} currentSize The current height and width of the innerCt
	* @param {Array} calculations The new box calculations of all items to be laid out
	*/
	updateInnerCtSize: Ext.emptyFn,

	/**
	* @private
	* This should be called after onLayout of any BoxLayout subclass. If the target's overflow is not set to 'hidden',
	* we need to lay out a second time because the scrollbars may have modified the height and width of the layout
	* target. Having a Box layout inside such a target is therefore not recommended.
	* @param {Object} previousTargetSize The size and height of the layout target before we just laid out
	* @param {Ext.Container} container The container
	* @param {Ext.Element} target The target element
	*/
	handleTargetOverflow: function (previousTargetSize, container, target) {
		var overflow = target.getStyle('overflow');

		if (overflow && overflow != 'hidden' && !this.adjustmentPass) {
			var newTargetSize = this.getLayoutTargetSize();
			if (newTargetSize.width != previousTargetSize.width || newTargetSize.height != previousTargetSize.height) {
				this.adjustmentPass = true;
				this.onLayout(container, target);
			}
		}

		delete this.adjustmentPass;
	},

	// private
	isValidParent: function (c, target) {
		return this.innerCt && c.getPositionEl().dom.parentNode == this.innerCt.dom;
	},

	/**
	* @private
	* Returns all items that are both rendered and visible
	* @return {Array} All matching items
	*/
	getVisibleItems: function (ct) {
		var ct = ct || this.container,
            t = ct.getLayoutTarget(),
            cti = ct.items.items,
            len = cti.length,

            i, c, items = [];

		for (i = 0; i < len; i++) {
			if ((c = cti[i]).rendered && this.isValidParent(c, t) && c.hidden !== true && c.collapsed !== true) {
				items.push(c);
			}
		}

		return items;
	},

	// private
	renderAll: function (ct, target) {
		if (!this.innerCt) {
			// the innerCt prevents wrapping and shuffling while
			// the container is resizing
			this.innerCt = target.createChild({ cls: this.innerCls });
			this.padding = this.parseMargins(this.padding);
		}
		Ext.layout.BoxLayout.superclass.renderAll.call(this, ct, this.innerCt);
	},

	getLayoutTargetSize: function () {
		var target = this.container.getLayoutTarget(), ret;
		if (target) {
			ret = target.getViewSize();

			// IE in strict mode will return a width of 0 on the 1st pass of getViewSize.
			// Use getStyleSize to verify the 0 width, the adjustment pass will then work properly
			// with getViewSize
			if (Ext.isIE && Ext.isStrict && ret.width == 0) {
				ret = target.getStyleSize();
			}

			ret.width -= target.getPadding('lr');
			ret.height -= target.getPadding('tb');
		}
		return ret;
	},

	// private
	renderItem: function (c) {
		if (Ext.isString(c.margins)) {
			c.margins = this.parseMargins(c.margins);
		} else if (!c.margins) {
			c.margins = this.defaultMargins;
		}
		Ext.layout.BoxLayout.superclass.renderItem.apply(this, arguments);
	}
});

/**
* @class Ext.layout.VBoxLayout
* @extends Ext.layout.BoxLayout
* <p>A layout that arranges items vertically down a Container. This layout optionally divides available vertical
* space between child items containing a numeric <code>flex</code> configuration.</p>
* This layout may also be used to set the widths of child items by configuring it with the {@link #align} option.
*/
Ext.layout.VBoxLayout = Ext.extend(Ext.layout.BoxLayout, {
	/**
	* @cfg {String} align
	* Controls how the child items of the container are aligned. Acceptable configuration values for this
	* property are:
	* <div class="mdetail-params"><ul>
	* <li><b><tt>left</tt></b> : <b>Default</b><div class="sub-desc">child items are aligned horizontally
	* at the <b>left</b> side of the container</div></li>
	* <li><b><tt>center</tt></b> : <div class="sub-desc">child items are aligned horizontally at the
	* <b>mid-width</b> of the container</div></li>
	* <li><b><tt>stretch</tt></b> : <div class="sub-desc">child items are stretched horizontally to fill
	* the width of the container</div></li>
	* <li><b><tt>stretchmax</tt></b> : <div class="sub-desc">child items are stretched horizontally to
	* the size of the largest item.</div></li>
	* </ul></div>
	*/
	align: 'left', // left, center, stretch, strechmax
	type: 'vbox',

	/**
	* @cfg {String} pack
	* Controls how the child items of the container are packed together. Acceptable configuration values
	* for this property are:
	* <div class="mdetail-params"><ul>
	* <li><b><tt>start</tt></b> : <b>Default</b><div class="sub-desc">child items are packed together at
	* <b>top</b> side of container</div></li>
	* <li><b><tt>center</tt></b> : <div class="sub-desc">child items are packed together at
	* <b>mid-height</b> of container</div></li>
	* <li><b><tt>end</tt></b> : <div class="sub-desc">child items are packed together at <b>bottom</b>
	* side of container</div></li>
	* </ul></div>
	*/

	/**
	* @cfg {Number} flex
	* This configuation option is to be applied to <b>child <tt>items</tt></b> of the container managed
	* by this layout. Each child item with a <tt>flex</tt> property will be flexed <b>vertically</b>
	* according to each item's <b>relative</b> <tt>flex</tt> value compared to the sum of all items with
	* a <tt>flex</tt> value specified.  Any child items that have either a <tt>flex = 0</tt> or
	* <tt>flex = undefined</tt> will not be 'flexed' (the initial size will not be changed).
	*/

	/**
	* @private
	* See parent documentation
	*/
	updateInnerCtSize: function (tSize, calcs) {
		var innerCtHeight = tSize.height,
            innerCtWidth = calcs.meta.maxWidth + this.padding.left + this.padding.right;

		if (this.align == 'stretch') {
			innerCtWidth = tSize.width;
		} else if (this.align == 'center') {
			innerCtWidth = Math.max(tSize.width, innerCtWidth);
		}

		//we set the innerCt size first because if our child items are larger than the previous innerCt size
		//the browser will insert scrollbars and then remove them again immediately afterwards
		this.innerCt.setSize(innerCtWidth || undefined, innerCtHeight || undefined);
	},

	/**
	* @private
	* Calculates the size and positioning of each item in the VBox. This iterates over all of the rendered,
	* visible items and returns a height, width, top and left for each, as well as a reference to each. Also
	* returns meta data such as maxHeight which are useful when resizing layout wrappers such as this.innerCt.
	* @param {Array} visibleItems The array of all rendered, visible items to be calculated for
	* @param {Object} targetSize Object containing target size and height
	* @return {Object} Object containing box measurements for each child, plus meta data
	*/
	calculateChildBoxes: function (visibleItems, targetSize) {
		var visibleCount = visibleItems.length,

            padding = this.padding,
            topOffset = padding.top,
            leftOffset = padding.left,
            paddingVert = topOffset + padding.bottom,
            paddingHoriz = leftOffset + padding.right,

            width = targetSize.width - this.scrollOffset,
            height = targetSize.height,
            availWidth = Math.max(0, width - paddingHoriz),

            isStart = this.pack == 'start',
            isCenter = this.pack == 'center',
            isEnd = this.pack == 'end',

            nonFlexHeight = 0,
            maxWidth = 0,
            totalFlex = 0,

		//used to cache the calculated size and position values for each child item
            boxes = [],

		//used in the for loops below, just declared here for brevity
            child, childWidth, childHeight, childSize, childMargins, canLayout, i, calcs, flexedHeight, horizMargins, stretchWidth;

		//gather the total flex of all flexed items and the width taken up by fixed width items
		for (i = 0; i < visibleCount; i++) {
			child = visibleItems[i];
			childHeight = child.height;
			childWidth = child.width;
			canLayout = !child.hasLayout && Ext.isFunction(child.doLayout);


			// Static height (numeric) requires no calcs
			if (!Ext.isNumber(childHeight)) {

				// flex and not 'auto' height
				if (child.flex && !childHeight) {
					totalFlex += child.flex;

					// Not flexed or 'auto' height or undefined height
				} else {
					//Render and layout sub-containers without a flex or width defined, as otherwise we
					//don't know how wide the sub-container should be and cannot calculate flexed widths
					if (!childHeight && canLayout) {
						child.doLayout();
					}

					childSize = child.getSize();
					childWidth = childSize.width;
					childHeight = childSize.height;
				}
			}

			childMargins = child.margins;

			nonFlexHeight += (childHeight || 0) + childMargins.top + childMargins.bottom;

			// Max width for align - force layout of non-layed out subcontainers without a numeric width
			if (!Ext.isNumber(childWidth)) {
				if (canLayout) {
					child.doLayout();
				}
				childWidth = child.getWidth();
			}

			maxWidth = Math.max(maxWidth, childWidth + childMargins.left + childMargins.right);

			//cache the size of each child component
			boxes.push({
				component: child,
				height: childHeight || undefined,
				width: childWidth || undefined
			});
		}

		//the height available to the flexed items
		var availableHeight = Math.max(0, (height - nonFlexHeight - paddingVert));

		if (isCenter) {
			topOffset += availableHeight / 2;
		} else if (isEnd) {
			topOffset += availableHeight;
		}

		//temporary variables used in the flex height calculations below
		var remainingHeight = availableHeight,
                remainingFlex = totalFlex;

		//calculate the height of each flexed item, and the left + top positions of every item
		for (i = 0; i < visibleCount; i++) {
			child = visibleItems[i];
			calcs = boxes[i];

			childMargins = child.margins;
			horizMargins = childMargins.left + childMargins.right;

			topOffset += childMargins.top;

			if (isStart && child.flex && !child.height) {
				flexedHeight = Math.ceil((child.flex / remainingFlex) * remainingHeight);
				remainingHeight -= flexedHeight;
				remainingFlex -= child.flex;

				calcs.height = flexedHeight;
				calcs.dirtySize = true;
			}

			calcs.left = leftOffset + childMargins.left;
			calcs.top = topOffset;

			switch (this.align) {
				case 'stretch':
					stretchWidth = availWidth - horizMargins;
					calcs.width = stretchWidth.constrain(child.minWidth || 0, child.maxWidth || 1000000);
					calcs.dirtySize = true;
					break;
				case 'stretchmax':
					stretchWidth = maxWidth - horizMargins;
					calcs.width = stretchWidth.constrain(child.minWidth || 0, child.maxWidth || 1000000);
					calcs.dirtySize = true;
					break;
				case 'center':
					var diff = availWidth - calcs.width - horizMargins;
					if (diff > 0) {
						calcs.left = leftOffset + horizMargins + (diff / 2);
					}
			}

			topOffset += calcs.height + childMargins.bottom;
		}

		return {
			boxes: boxes,
			meta: {
				maxWidth: maxWidth
			}
		};
	}
});

Ext.Container.LAYOUTS.vbox = Ext.layout.VBoxLayout;

/**
* @class Ext.layout.HBoxLayout
* @extends Ext.layout.BoxLayout
* <p>A layout that arranges items horizontally across a Container. This layout optionally divides available horizontal
* space between child items containing a numeric <code>flex</code> configuration.</p>
* This layout may also be used to set the heights of child items by configuring it with the {@link #align} option.
*/
Ext.layout.HBoxLayout = Ext.extend(Ext.layout.BoxLayout, {
	/**
	* @cfg {String} align
	* Controls how the child items of the container are aligned. Acceptable configuration values for this
	* property are:
	* <div class="mdetail-params"><ul>
	* <li><b><tt>top</tt></b> : <b>Default</b><div class="sub-desc">child items are aligned vertically
	* at the <b>top</b> of the container</div></li>
	* <li><b><tt>middle</tt></b> : <div class="sub-desc">child items are aligned vertically in the
	* <b>middle</b> of the container</div></li>
	* <li><b><tt>stretch</tt></b> : <div class="sub-desc">child items are stretched vertically to fill
	* the height of the container</div></li>
	* <li><b><tt>stretchmax</tt></b> : <div class="sub-desc">child items are stretched vertically to
	* the height of the largest item.</div></li>
	*/
	align: 'top', // top, middle, stretch, strechmax

	type: 'hbox',

	/**
	* @private
	* See parent documentation
	*/
	updateInnerCtSize: function (tSize, calcs) {
		var innerCtWidth = tSize.width,
            innerCtHeight = calcs.meta.maxHeight + this.padding.top + this.padding.bottom;

		if (this.align == 'stretch') {
			innerCtHeight = tSize.height;
		} else if (this.align == 'middle') {
			innerCtHeight = Math.max(tSize.height, innerCtHeight);
		}

		this.innerCt.setSize(innerCtWidth || undefined, innerCtHeight || undefined);
	},

	/**
	* @cfg {String} pack
	* Controls how the child items of the container are packed together. Acceptable configuration values
	* for this property are:
	* <div class="mdetail-params"><ul>
	* <li><b><tt>start</tt></b> : <b>Default</b><div class="sub-desc">child items are packed together at
	* <b>left</b> side of container</div></li>
	* <li><b><tt>center</tt></b> : <div class="sub-desc">child items are packed together at
	* <b>mid-width</b> of container</div></li>
	* <li><b><tt>end</tt></b> : <div class="sub-desc">child items are packed together at <b>right</b>
	* side of container</div></li>
	* </ul></div>
	*/
	/**
	* @cfg {Number} flex
	* This configuation option is to be applied to <b>child <tt>items</tt></b> of the container managed
	* by this layout. Each child item with a <tt>flex</tt> property will be flexed <b>horizontally</b>
	* according to each item's <b>relative</b> <tt>flex</tt> value compared to the sum of all items with
	* a <tt>flex</tt> value specified.  Any child items that have either a <tt>flex = 0</tt> or
	* <tt>flex = undefined</tt> will not be 'flexed' (the initial size will not be changed).
	*/

	/**
	* @private
	* Calculates the size and positioning of each item in the HBox. This iterates over all of the rendered,
	* visible items and returns a height, width, top and left for each, as well as a reference to each. Also
	* returns meta data such as maxHeight which are useful when resizing layout wrappers such as this.innerCt.
	* @param {Array} visibleItems The array of all rendered, visible items to be calculated for
	* @param {Object} targetSize Object containing target size and height
	* @return {Object} Object containing box measurements for each child, plus meta data
	*/
	calculateChildBoxes: function (visibleItems, targetSize) {
		var visibleCount = visibleItems.length,

            padding = this.padding,
            topOffset = padding.top,
            leftOffset = padding.left,
            paddingVert = topOffset + padding.bottom,
            paddingHoriz = leftOffset + padding.right,

            width = targetSize.width - this.scrollOffset,
            height = targetSize.height,
            availHeight = Math.max(0, height - paddingVert),

            isStart = this.pack == 'start',
            isCenter = this.pack == 'center',
            isEnd = this.pack == 'end',
		// isRestore    = ['stretch', 'stretchmax'].indexOf(this.align) == -1,

            nonFlexWidth = 0,
            maxHeight = 0,
            totalFlex = 0,

		//used to cache the calculated size and position values for each child item
            boxes = [],

		//used in the for loops below, just declared here for brevity
            child, childWidth, childHeight, childSize, childMargins, canLayout, i, calcs, flexedWidth, vertMargins, stretchHeight;

		//gather the total flex of all flexed items and the width taken up by fixed width items
		for (i = 0; i < visibleCount; i++) {
			child = visibleItems[i];
			childHeight = child.height;
			childWidth = child.width;
			canLayout = !child.hasLayout && Ext.isFunction(child.doLayout);

			// Static width (numeric) requires no calcs
			if (!Ext.isNumber(childWidth)) {

				// flex and not 'auto' width
				if (child.flex && !childWidth) {
					totalFlex += child.flex;

					// Not flexed or 'auto' width or undefined width
				} else {
					//Render and layout sub-containers without a flex or width defined, as otherwise we
					//don't know how wide the sub-container should be and cannot calculate flexed widths
					if (!childWidth && canLayout) {
						child.doLayout();
					}

					childSize = child.getSize();
					childWidth = childSize.width;
					childHeight = childSize.height;
				}
			}

			childMargins = child.margins;

			nonFlexWidth += (childWidth || 0) + childMargins.left + childMargins.right;

			// Max height for align - force layout of non-layed out subcontainers without a numeric height
			if (!Ext.isNumber(childHeight)) {
				if (canLayout) {
					child.doLayout();
				}
				childHeight = child.getHeight();
			}

			maxHeight = Math.max(maxHeight, childHeight + childMargins.top + childMargins.bottom);

			//cache the size of each child component
			boxes.push({
				component: child,
				height: childHeight || undefined,
				width: childWidth || undefined
			});
		}

		//the width available to the flexed items
		var availableWidth = Math.max(0, (width - nonFlexWidth - paddingHoriz));

		if (isCenter) {
			leftOffset += availableWidth / 2;
		} else if (isEnd) {
			leftOffset += availableWidth;
		}

		//temporary variables used in the flex width calculations below
		var remainingWidth = availableWidth,
                remainingFlex = totalFlex;

		//calculate the widths of each flexed item, and the left + top positions of every item
		for (i = 0; i < visibleCount; i++) {
			child = visibleItems[i];
			calcs = boxes[i];

			childMargins = child.margins;
			vertMargins = childMargins.top + childMargins.bottom;

			leftOffset += childMargins.left;

			if (isStart && child.flex && !child.width) {
				flexedWidth = Math.ceil((child.flex / remainingFlex) * remainingWidth);
				remainingWidth -= flexedWidth;
				remainingFlex -= child.flex;

				calcs.width = flexedWidth;
				calcs.dirtySize = true;
			}

			calcs.left = leftOffset;
			calcs.top = topOffset + childMargins.top;

			switch (this.align) {
				case 'stretch':
					stretchHeight = availHeight - vertMargins;
					calcs.height = stretchHeight.constrain(child.minHeight || 0, child.maxHeight || 1000000);
					calcs.dirtySize = true;
					break;
				case 'stretchmax':
					stretchHeight = maxHeight - vertMargins;
					calcs.height = stretchHeight.constrain(child.minHeight || 0, child.maxHeight || 1000000);
					calcs.dirtySize = true;
					break;
				case 'middle':
					var diff = availHeight - calcs.height - vertMargins;
					if (diff > 0) {
						calcs.top = topOffset + vertMargins + (diff / 2);
					}
			}
			leftOffset += calcs.width + childMargins.right;
		}

		return {
			boxes: boxes,
			meta: {
				maxHeight: maxHeight
			}
		};
	}
});

Ext.Container.LAYOUTS.hbox = Ext.layout.HBoxLayout;
/**
* @class Ext.layout.ToolbarLayout
* @extends Ext.layout.ContainerLayout
* Layout manager used by Ext.Toolbar. This is highly specialised for use by Toolbars and would not
* usually be used by any other class.
*/
Ext.layout.ToolbarLayout = Ext.extend(Ext.layout.ContainerLayout, {
	monitorResize: true,

	type: 'toolbar',

	/**
	* @property triggerWidth
	* @type Number
	* The width allocated for the menu trigger at the extreme right end of the Toolbar
	*/
	triggerWidth: 18,

	/**
	* @property noItemsMenuText
	* @type String
	* HTML fragment to render into the toolbar overflow menu if there are no items to display
	*/
	noItemsMenuText: '<div class="x-toolbar-no-items">(None)</div>',

	/**
	* @private
	* @property lastOverflow
	* @type Boolean
	* Used internally to record whether the last layout caused an overflow or not
	*/
	lastOverflow: false,

	/**
	* @private
	* @property tableHTML
	* @type String
	* String used to build the HTML injected to support the Toolbar's layout. The align property is
	* injected into this string inside the td.x-toolbar-left element during onLayout.
	*/
	tableHTML: [
        '<table cellspacing="0" class="x-toolbar-ct">',
            '<tbody>',
                '<tr>',
                    '<td class="x-toolbar-left" align="{0}">',
                        '<table cellspacing="0">',
                            '<tbody>',
                                '<tr class="x-toolbar-left-row"></tr>',
                            '</tbody>',
                        '</table>',
                    '</td>',
                    '<td class="x-toolbar-right" align="right">',
                        '<table cellspacing="0" class="x-toolbar-right-ct">',
                            '<tbody>',
                                '<tr>',
                                    '<td>',
                                        '<table cellspacing="0">',
                                            '<tbody>',
                                                '<tr class="x-toolbar-right-row"></tr>',
                                            '</tbody>',
                                        '</table>',
                                    '</td>',
                                    '<td>',
                                        '<table cellspacing="0">',
                                            '<tbody>',
                                                '<tr class="x-toolbar-extras-row"></tr>',
                                            '</tbody>',
                                        '</table>',
                                    '</td>',
                                '</tr>',
                            '</tbody>',
                        '</table>',
                    '</td>',
                '</tr>',
            '</tbody>',
        '</table>'
    ].join(""),

	/**
	* @private
	* Create the wrapping Toolbar HTML and render/move all the items into the correct places
	*/
	onLayout: function (ct, target) {
		//render the Toolbar <table> HTML if it's not already present
		if (!this.leftTr) {
			var align = ct.buttonAlign == 'center' ? 'center' : 'left';

			target.addClass('x-toolbar-layout-ct');
			target.insertHtml('beforeEnd', String.format(this.tableHTML, align));

			this.leftTr = target.child('tr.x-toolbar-left-row', true);
			this.rightTr = target.child('tr.x-toolbar-right-row', true);
			this.extrasTr = target.child('tr.x-toolbar-extras-row', true);

			if (this.hiddenItem == undefined) {
				/**
				* @property hiddenItems
				* @type Array
				* Holds all items that are currently hidden due to there not being enough space to render them
				* These items will appear on the expand menu.
				*/
				this.hiddenItems = [];
			}
		}

		var side = ct.buttonAlign == 'right' ? this.rightTr : this.leftTr,
            items = ct.items.items,
            position = 0;

		//render each item if not already rendered, place it into the correct (left or right) target
		for (var i = 0, len = items.length, c; i < len; i++, position++) {
			c = items[i];

			if (c.isFill) {
				side = this.rightTr;
				position = -1;
			} else if (!c.rendered) {
				c.render(this.insertCell(c, side, position));
			} else {
				if (!c.xtbHidden && !this.isValidParent(c, side.childNodes[position])) {
					var td = this.insertCell(c, side, position);
					td.appendChild(c.getPositionEl().dom);
					c.container = Ext.get(td);
				}
			}
		}

		//strip extra empty cells
		this.cleanup(this.leftTr);
		this.cleanup(this.rightTr);
		this.cleanup(this.extrasTr);
		this.fitToSize(target);
	},

	/**
	* @private
	* Removes any empty nodes from the given element
	* @param {Ext.Element} el The element to clean up
	*/
	cleanup: function (el) {
		var cn = el.childNodes, i, c;

		for (i = cn.length - 1; i >= 0 && (c = cn[i]); i--) {
			if (!c.firstChild) {
				el.removeChild(c);
			}
		}
	},

	/**
	* @private
	* Inserts the given Toolbar item into the given element
	* @param {Ext.Component} c The component to add
	* @param {Ext.Element} target The target to add the component to
	* @param {Number} position The position to add the component at
	*/
	insertCell: function (c, target, position) {
		var td = document.createElement('td');
		td.className = 'x-toolbar-cell';

		target.insertBefore(td, target.childNodes[position] || null);

		return td;
	},

	/**
	* @private
	* Hides an item because it will not fit in the available width. The item will be unhidden again
	* if the Toolbar is resized to be large enough to show it
	* @param {Ext.Component} item The item to hide
	*/
	hideItem: function (item) {
		this.hiddenItems.push(item);

		item.xtbHidden = true;
		item.xtbWidth = item.getPositionEl().dom.parentNode.offsetWidth;
		item.hide();
	},

	/**
	* @private
	* Unhides an item that was previously hidden due to there not being enough space left on the Toolbar
	* @param {Ext.Component} item The item to show
	*/
	unhideItem: function (item) {
		item.show();
		item.xtbHidden = false;
		this.hiddenItems.remove(item);
	},

	/**
	* @private
	* Returns the width of the given toolbar item. If the item is currently hidden because there
	* is not enough room to render it, its previous width is returned
	* @param {Ext.Component} c The component to measure
	* @return {Number} The width of the item
	*/
	getItemWidth: function (c) {
		return c.hidden ? (c.xtbWidth || 0) : c.getPositionEl().dom.parentNode.offsetWidth;
	},

	/**
	* @private
	* Called at the end of onLayout. At this point the Toolbar has already been resized, so we need
	* to fit the items into the available width. We add up the width required by all of the items in
	* the toolbar - if we don't have enough space we hide the extra items and render the expand menu
	* trigger.
	* @param {Ext.Element} target The Element the Toolbar is currently laid out within
	*/
	fitToSize: function (target) {
		if (this.container.enableOverflow === false) {
			return;
		}

		var width = target.dom.clientWidth,
            tableWidth = target.dom.firstChild.offsetWidth,
            clipWidth = width - this.triggerWidth,
            lastWidth = this.lastWidth || 0,

            hiddenItems = this.hiddenItems,
            hasHiddens = hiddenItems.length != 0,
            isLarger = width >= lastWidth;

		this.lastWidth = width;

		if (tableWidth > width || (hasHiddens && isLarger)) {
			var items = this.container.items.items,
                len = items.length,
                loopWidth = 0,
                item;

			for (var i = 0; i < len; i++) {
				item = items[i];

				if (!item.isFill) {
					loopWidth += this.getItemWidth(item);
					if (loopWidth > clipWidth) {
						if (!(item.hidden || item.xtbHidden)) {
							this.hideItem(item);
						}
					} else if (item.xtbHidden) {
						this.unhideItem(item);
					}
				}
			}
		}

		//test for number of hidden items again here because they may have changed above
		hasHiddens = hiddenItems.length != 0;

		if (hasHiddens) {
			this.initMore();

			if (!this.lastOverflow) {
				this.container.fireEvent('overflowchange', this.container, true);
				this.lastOverflow = true;
			}
		} else if (this.more) {
			this.clearMenu();
			this.more.destroy();
			delete this.more;

			if (this.lastOverflow) {
				this.container.fireEvent('overflowchange', this.container, false);
				this.lastOverflow = false;
			}
		}
	},

	/**
	* @private
	* Returns a menu config for a given component. This config is used to create a menu item
	* to be added to the expander menu
	* @param {Ext.Component} component The component to create the config for
	* @param {Boolean} hideOnClick Passed through to the menu item
	*/
	createMenuConfig: function (component, hideOnClick) {
		var config = Ext.apply({}, component.initialConfig),
            group = component.toggleGroup;

		Ext.copyTo(config, component, [
            'iconCls', 'icon', 'itemId', 'disabled', 'handler', 'scope', 'menu'
        ]);

		Ext.apply(config, {
			text: component.overflowText || component.text,
			hideOnClick: hideOnClick
		});

		if (group || component.enableToggle) {
			Ext.apply(config, {
				group: group,
				checked: component.pressed,
				listeners: {
					checkchange: function (item, checked) {
						component.toggle(checked);
					}
				}
			});
		}

		delete config.ownerCt;
		delete config.xtype;
		delete config.id;

		return config;
	},

	/**
	* @private
	* Adds the given Toolbar item to the given menu. Buttons inside a buttongroup are added individually.
	* @param {Ext.menu.Menu} menu The menu to add to
	* @param {Ext.Component} component The component to add
	*/
	addComponentToMenu: function (menu, component) {
		if (component instanceof Ext.Toolbar.Separator) {
			menu.add('-');

		} else if (Ext.isFunction(component.isXType)) {
			if (component.isXType('splitbutton')) {
				menu.add(this.createMenuConfig(component, true));

			} else if (component.isXType('button')) {
				menu.add(this.createMenuConfig(component, !component.menu));

			} else if (component.isXType('buttongroup')) {
				component.items.each(function (item) {
					this.addComponentToMenu(menu, item);
				}, this);
			}
		}
	},

	/**
	* @private
	* Deletes the sub-menu of each item in the expander menu. Submenus are created for items such as
	* splitbuttons and buttongroups, where the Toolbar item cannot be represented by a single menu item
	*/
	clearMenu: function () {
		var menu = this.moreMenu;
		if (menu && menu.items) {
			menu.items.each(function (item) {
				delete item.menu;
			});
		}
	},

	/**
	* @private
	* Called before the expand menu is shown, this rebuilds the menu since it was last shown because
	* it is possible that the items hidden due to space limitations on the Toolbar have changed since.
	* @param {Ext.menu.Menu} m The menu
	*/
	beforeMoreShow: function (menu) {
		var items = this.container.items.items,
            len = items.length,
            item,
            prev;

		var needsSep = function (group, item) {
			return group.isXType('buttongroup') && !(item instanceof Ext.Toolbar.Separator);
		};

		this.clearMenu();
		menu.removeAll();
		for (var i = 0; i < len; i++) {
			item = items[i];
			if (item.xtbHidden) {
				if (prev && (needsSep(item, prev) || needsSep(prev, item))) {
					menu.add('-');
				}
				this.addComponentToMenu(menu, item);
				prev = item;
			}
		}

		// put something so the menu isn't empty if no compatible items found
		if (menu.items.length < 1) {
			menu.add(this.noItemsMenuText);
		}
	},

	/**
	* @private
	* Creates the expand trigger and menu, adding them to the <tr> at the extreme right of the
	* Toolbar table
	*/
	initMore: function () {
		if (!this.more) {
			/**
			* @private
			* @property moreMenu
			* @type Ext.menu.Menu
			* The expand menu - holds items for every Toolbar item that cannot be shown
			* because the Toolbar is currently not wide enough.
			*/
			this.moreMenu = new Ext.menu.Menu({
				ownerCt: this.container,
				listeners: {
					beforeshow: this.beforeMoreShow,
					scope: this
				}
			});

			/**
			* @private
			* @property more
			* @type Ext.Button
			* The expand button which triggers the overflow menu to be shown
			*/
			this.more = new Ext.Button({
				iconCls: 'x-toolbar-more-icon',
				cls: 'x-toolbar-more',
				menu: this.moreMenu,
				ownerCt: this.container
			});

			var td = this.insertCell(this.more, this.extrasTr, 100);
			this.more.render(td);
		}
	},

	destroy: function () {
		Ext.destroy(this.more, this.moreMenu);
		delete this.leftTr;
		delete this.rightTr;
		delete this.extrasTr;
		Ext.layout.ToolbarLayout.superclass.destroy.call(this);
	}
});

Ext.Container.LAYOUTS.toolbar = Ext.layout.ToolbarLayout;
/**
* @class Ext.layout.MenuLayout
* @extends Ext.layout.ContainerLayout
* <p>Layout manager used by {@link Ext.menu.Menu}. Generally this class should not need to be used directly.</p>
*/
Ext.layout.MenuLayout = Ext.extend(Ext.layout.ContainerLayout, {
	monitorResize: true,

	type: 'menu',

	setContainer: function (ct) {
		this.monitorResize = !ct.floating;
		// This event is only fired by the menu in IE, used so we don't couple
		// the menu with the layout.
		ct.on('autosize', this.doAutoSize, this);
		Ext.layout.MenuLayout.superclass.setContainer.call(this, ct);
	},

	renderItem: function (c, position, target) {
		if (!this.itemTpl) {
			this.itemTpl = Ext.layout.MenuLayout.prototype.itemTpl = new Ext.XTemplate(
                '<li id="{itemId}" class="{itemCls}">',
                    '<tpl if="needsIcon">',
                        '<img src="{icon}" class="{iconCls}"/>',
                    '</tpl>',
                '</li>'
            );
		}

		if (c && !c.rendered) {
			if (Ext.isNumber(position)) {
				position = target.dom.childNodes[position];
			}
			var a = this.getItemArgs(c);

			//          The Component's positionEl is the <li> it is rendered into
			c.render(c.positionEl = position ?
                this.itemTpl.insertBefore(position, a, true) :
                this.itemTpl.append(target, a, true));

			//          Link the containing <li> to the item.
			c.positionEl.menuItemId = c.getItemId();

			//          If rendering a regular Component, and it needs an icon,
			//          move the Component rightwards.
			if (!a.isMenuItem && a.needsIcon) {
				c.positionEl.addClass('x-menu-list-item-indent');
			}
			this.configureItem(c, position);
		} else if (c && !this.isValidParent(c, target)) {
			if (Ext.isNumber(position)) {
				position = target.dom.childNodes[position];
			}
			target.dom.insertBefore(c.getActionEl().dom, position || null);
		}
	},

	getItemArgs: function (c) {
		var isMenuItem = c instanceof Ext.menu.Item;
		return {
			isMenuItem: isMenuItem,
			needsIcon: !isMenuItem && (c.icon || c.iconCls),
			icon: c.icon || Ext.BLANK_IMAGE_URL,
			iconCls: 'x-menu-item-icon ' + (c.iconCls || ''),
			itemId: 'x-menu-el-' + c.id,
			itemCls: 'x-menu-list-item '
		};
	},

	//  Valid if the Component is in a <li> which is part of our target <ul>
	isValidParent: function (c, target) {
		return c.el.up('li.x-menu-list-item', 5).dom.parentNode === (target.dom || target);
	},

	onLayout: function (ct, target) {
		Ext.layout.MenuLayout.superclass.onLayout.call(this, ct, target);
		this.doAutoSize();
	},

	doAutoSize: function () {
		var ct = this.container, w = ct.width;
		if (ct.floating) {
			if (w) {
				ct.setWidth(w);
			} else if (Ext.isIE) {
				ct.setWidth(Ext.isStrict && (Ext.isIE7 || Ext.isIE8) ? 'auto' : ct.minWidth);
				var el = ct.getEl(), t = el.dom.offsetWidth; // force recalc
				ct.setWidth(ct.getLayoutTarget().getWidth() + el.getFrameWidth('lr'));
			}
		}
	}
});
Ext.Container.LAYOUTS['menu'] = Ext.layout.MenuLayout;
/**
* @class Ext.Viewport
* @extends Ext.Container
* <p>A specialized container representing the viewable application area (the browser viewport).</p>
* <p>The Viewport renders itself to the document body, and automatically sizes itself to the size of
* the browser viewport and manages window resizing. There may only be one Viewport created
* in a page. Inner layouts are available by virtue of the fact that all {@link Ext.Panel Panel}s
* added to the Viewport, either through its {@link #items}, or through the items, or the {@link #add}
* method of any of its child Panels may themselves have a layout.</p>
* <p>The Viewport does not provide scrolling, so child Panels within the Viewport should provide
* for scrolling if needed using the {@link #autoScroll} config.</p>
* <p>An example showing a classic application border layout:</p><pre><code>
new Ext.Viewport({
layout: 'border',
items: [{
region: 'north',
html: '&lt;h1 class="x-panel-header">Page Title&lt;/h1>',
autoHeight: true,
border: false,
margins: '0 0 5 0'
}, {
region: 'west',
collapsible: true,
title: 'Navigation',
width: 200
// the west region might typically utilize a {@link Ext.tree.TreePanel TreePanel} or a Panel with {@link Ext.layout.AccordionLayout Accordion layout}
}, {
region: 'south',
title: 'Title for Panel',
collapsible: true,
html: 'Information goes here',
split: true,
height: 100,
minHeight: 100
}, {
region: 'east',
title: 'Title for the Grid Panel',
collapsible: true,
split: true,
width: 200,
xtype: 'grid',
// remaining grid configuration not shown ...
// notice that the GridPanel is added directly as the region
// it is not "overnested" inside another Panel
}, {
region: 'center',
xtype: 'tabpanel', // TabPanel itself has no title
items: {
title: 'Default Tab',
html: 'The first tab\'s content. Others may be added dynamically'
}
}]
});
</code></pre>
* @constructor
* Create a new Viewport
* @param {Object} config The config object
* @xtype viewport
*/
Ext.Viewport = Ext.extend(Ext.Container, {
	/*
	* Privatize config options which, if used, would interfere with the
	* correct operation of the Viewport as the sole manager of the
	* layout of the document body.
	*/
	/**
	* @cfg {Mixed} applyTo @hide
	*/
	/**
	* @cfg {Boolean} allowDomMove @hide
	*/
	/**
	* @cfg {Boolean} hideParent @hide
	*/
	/**
	* @cfg {Mixed} renderTo @hide
	*/
	/**
	* @cfg {Boolean} hideParent @hide
	*/
	/**
	* @cfg {Number} height @hide
	*/
	/**
	* @cfg {Number} width @hide
	*/
	/**
	* @cfg {Boolean} autoHeight @hide
	*/
	/**
	* @cfg {Boolean} autoWidth @hide
	*/
	/**
	* @cfg {Boolean} deferHeight @hide
	*/
	/**
	* @cfg {Boolean} monitorResize @hide
	*/

	initComponent: function () {
		Ext.Viewport.superclass.initComponent.call(this);
		document.getElementsByTagName('html')[0].className += ' x-viewport';
		this.el = Ext.getBody();
		this.el.setHeight = Ext.emptyFn;
		this.el.setWidth = Ext.emptyFn;
		this.el.setSize = Ext.emptyFn;
		this.el.dom.scroll = 'no';
		this.allowDomMove = false;
		this.autoWidth = true;
		this.autoHeight = true;
		Ext.EventManager.onWindowResize(this.fireResize, this);
		this.renderTo = this.el;
	},

	fireResize: function (w, h) {
		this.fireEvent('resize', this, w, h, w, h);
	}
});
Ext.reg('viewport', Ext.Viewport);
/**
* @class Ext.Panel
* @extends Ext.Container
* <p>Panel is a container that has specific functionality and structural components that make
* it the perfect building block for application-oriented user interfaces.</p>
* <p>Panels are, by virtue of their inheritance from {@link Ext.Container}, capable
* of being configured with a {@link Ext.Container#layout layout}, and containing child Components.</p>
* <p>When either specifying child {@link Ext.Component#items items} of a Panel, or dynamically {@link Ext.Container#add adding} Components
* to a Panel, remember to consider how you wish the Panel to arrange those child elements, and whether
* those child elements need to be sized using one of Ext's built-in <code><b>{@link Ext.Container#layout layout}</b></code> schemes. By
* default, Panels use the {@link Ext.layout.ContainerLayout ContainerLayout} scheme. This simply renders
* child components, appending them one after the other inside the Container, and <b>does not apply any sizing</b>
* at all.</p>
* <p>A Panel may also contain {@link #bbar bottom} and {@link #tbar top} toolbars, along with separate
* {@link #header}, {@link #footer} and {@link #body} sections (see {@link #frame} for additional
* information).</p>
* <p>Panel also provides built-in {@link #collapsible expandable and collapsible behavior}, along with
* a variety of {@link #tools prebuilt tool buttons} that can be wired up to provide other customized
* behavior.  Panels can be easily dropped into any {@link Ext.Container Container} or layout, and the
* layout and rendering pipeline is {@link Ext.Container#add completely managed by the framework}.</p>
* @constructor
* @param {Object} config The config object
* @xtype panel
*/
Ext.Panel = Ext.extend(Ext.Container, {
	/**
	* The Panel's header {@link Ext.Element Element}. Read-only.
	* <p>This Element is used to house the {@link #title} and {@link #tools}</p>
	* <br><p><b>Note</b>: see the Note for <code>{@link Ext.Component#el el}</code> also.</p>
	* @type Ext.Element
	* @property header
	*/
	/**
	* The Panel's body {@link Ext.Element Element} which may be used to contain HTML content.
	* The content may be specified in the {@link #html} config, or it may be loaded using the
	* {@link autoLoad} config, or through the Panel's {@link #getUpdater Updater}. Read-only.
	* <p>If this is used to load visible HTML elements in either way, then
	* the Panel may not be used as a Layout for hosting nested Panels.</p>
	* <p>If this Panel is intended to be used as the host of a Layout (See {@link #layout}
	* then the body Element must not be loaded or changed - it is under the control
	* of the Panel's Layout.
	* <br><p><b>Note</b>: see the Note for <code>{@link Ext.Component#el el}</code> also.</p>
	* @type Ext.Element
	* @property body
	*/
	/**
	* The Panel's bwrap {@link Ext.Element Element} used to contain other Panel elements
	* (tbar, body, bbar, footer). See {@link #bodyCfg}. Read-only.
	* @type Ext.Element
	* @property bwrap
	*/
	/**
	* True if this panel is collapsed. Read-only.
	* @type Boolean
	* @property collapsed
	*/
	/**
	* @cfg {Object} bodyCfg
	* <p>A {@link Ext.DomHelper DomHelper} element specification object may be specified for any
	* Panel Element.</p>
	* <p>By default, the Default element in the table below will be used for the html markup to
	* create a child element with the commensurate Default class name (<code>baseCls</code> will be
	* replaced by <code>{@link #baseCls}</code>):</p>
	* <pre>
	* Panel      Default  Default             Custom      Additional       Additional
	* Element    element  class               element     class            style
	* ========   ==========================   =========   ==============   ===========
	* {@link #header}     div      {@link #baseCls}+'-header'   {@link #headerCfg}   headerCssClass   headerStyle
	* {@link #bwrap}      div      {@link #baseCls}+'-bwrap'     {@link #bwrapCfg}    bwrapCssClass    bwrapStyle
	* + tbar     div      {@link #baseCls}+'-tbar'       {@link #tbarCfg}     tbarCssClass     tbarStyle
	* + {@link #body}     div      {@link #baseCls}+'-body'       {@link #bodyCfg}     {@link #bodyCssClass}     {@link #bodyStyle}
	* + bbar     div      {@link #baseCls}+'-bbar'       {@link #bbarCfg}     bbarCssClass     bbarStyle
	* + {@link #footer}   div      {@link #baseCls}+'-footer'   {@link #footerCfg}   footerCssClass   footerStyle
	* </pre>
	* <p>Configuring a Custom element may be used, for example, to force the {@link #body} Element
	* to use a different form of markup than is created by default. An example of this might be
	* to {@link Ext.Element#createChild create a child} Panel containing a custom content, such as
	* a header, or forcing centering of all Panel content by having the body be a &lt;center&gt;
	* element:</p>
	* <pre><code>
	new Ext.Panel({
	title: 'Message Title',
	renderTo: Ext.getBody(),
	width: 200, height: 130,
	<b>bodyCfg</b>: {
	tag: 'center',
	cls: 'x-panel-body',  // Default class not applied if Custom element specified
	html: 'Message'
	},
	footerCfg: {
	tag: 'h2',
	cls: 'x-panel-footer'        // same as the Default class
	html: 'footer html'
	},
	footerCssClass: 'custom-footer', // additional css class, see {@link Ext.element#addClass addClass}
	footerStyle:    'background-color:red' // see {@link #bodyStyle}
	});
	* </code></pre>
	* <p>The example above also explicitly creates a <code>{@link #footer}</code> with custom markup and
	* styling applied.</p>
	*/
	/**
	* @cfg {Object} headerCfg
	* <p>A {@link Ext.DomHelper DomHelper} element specification object specifying the element structure
	* of this Panel's {@link #header} Element.  See <code>{@link #bodyCfg}</code> also.</p>
	*/
	/**
	* @cfg {Object} bwrapCfg
	* <p>A {@link Ext.DomHelper DomHelper} element specification object specifying the element structure
	* of this Panel's {@link #bwrap} Element.  See <code>{@link #bodyCfg}</code> also.</p>
	*/
	/**
	* @cfg {Object} tbarCfg
	* <p>A {@link Ext.DomHelper DomHelper} element specification object specifying the element structure
	* of this Panel's {@link #tbar} Element.  See <code>{@link #bodyCfg}</code> also.</p>
	*/
	/**
	* @cfg {Object} bbarCfg
	* <p>A {@link Ext.DomHelper DomHelper} element specification object specifying the element structure
	* of this Panel's {@link #bbar} Element.  See <code>{@link #bodyCfg}</code> also.</p>
	*/
	/**
	* @cfg {Object} footerCfg
	* <p>A {@link Ext.DomHelper DomHelper} element specification object specifying the element structure
	* of this Panel's {@link #footer} Element.  See <code>{@link #bodyCfg}</code> also.</p>
	*/
	/**
	* @cfg {Boolean} closable
	* Panels themselves do not directly support being closed, but some Panel subclasses do (like
	* {@link Ext.Window}) or a Panel Class within an {@link Ext.TabPanel}.  Specify <code>true</code>
	* to enable closing in such situations. Defaults to <code>false</code>.
	*/
	/**
	* The Panel's footer {@link Ext.Element Element}. Read-only.
	* <p>This Element is used to house the Panel's <code>{@link #buttons}</code> or <code>{@link #fbar}</code>.</p>
	* <br><p><b>Note</b>: see the Note for <code>{@link Ext.Component#el el}</code> also.</p>
	* @type Ext.Element
	* @property footer
	*/
	/**
	* @cfg {Mixed} applyTo
	* <p>The id of the node, a DOM node or an existing Element corresponding to a DIV that is already present in
	* the document that specifies some panel-specific structural markup.  When <code>applyTo</code> is used,
	* constituent parts of the panel can be specified by CSS class name within the main element, and the panel
	* will automatically create those components from that markup. Any required components not specified in the
	* markup will be autogenerated if necessary.</p>
	* <p>The following class names are supported (baseCls will be replaced by {@link #baseCls}):</p>
	* <ul><li>baseCls + '-header'</li>
	* <li>baseCls + '-header-text'</li>
	* <li>baseCls + '-bwrap'</li>
	* <li>baseCls + '-tbar'</li>
	* <li>baseCls + '-body'</li>
	* <li>baseCls + '-bbar'</li>
	* <li>baseCls + '-footer'</li></ul>
	* <p>Using this config, a call to render() is not required.  If applyTo is specified, any value passed for
	* {@link #renderTo} will be ignored and the target element's parent node will automatically be used as the
	* panel's container.</p>
	*/
	/**
	* @cfg {Object/Array} tbar
	* <p>The top toolbar of the panel. This can be a {@link Ext.Toolbar} object, a toolbar config, or an array of
	* buttons/button configs to be added to the toolbar.  Note that this is not available as a property after render.
	* To access the top toolbar after render, use {@link #getTopToolbar}.</p>
	* <p><b>Note:</b> Although a Toolbar may contain Field components, these will <b>not</b> be updated by a load
	* of an ancestor FormPanel. A Panel's toolbars are not part of the standard Container->Component hierarchy, and
	* so are not scanned to collect form items. However, the values <b>will</b> be submitted because form
	* submission parameters are collected from the DOM tree.</p>
	*/
	/**
	* @cfg {Object/Array} bbar
	* <p>The bottom toolbar of the panel. This can be a {@link Ext.Toolbar} object, a toolbar config, or an array of
	* buttons/button configs to be added to the toolbar.  Note that this is not available as a property after render.
	* To access the bottom toolbar after render, use {@link #getBottomToolbar}.</p>
	* <p><b>Note:</b> Although a Toolbar may contain Field components, these will <b>not</b> be updated by a load
	* of an ancestor FormPanel. A Panel's toolbars are not part of the standard Container->Component hierarchy, and
	* so are not scanned to collect form items. However, the values <b>will</b> be submitted because form
	* submission parameters are collected from the DOM tree.</p>
	*/
	/** @cfg {Object/Array} fbar
	* <p>A {@link Ext.Toolbar Toolbar} object, a Toolbar config, or an array of
	* {@link Ext.Button Button}s/{@link Ext.Button Button} configs, describing a {@link Ext.Toolbar Toolbar} to be rendered into this Panel's footer element.</p>
	* <p>After render, the <code>fbar</code> property will be an {@link Ext.Toolbar Toolbar} instance.</p>
	* <p>If <code>{@link #buttons}</code> are specified, they will supersede the <code>fbar</code> configuration property.</p>
	* The Panel's <code>{@link #buttonAlign}</code> configuration affects the layout of these items, for example:
	* <pre><code>
	var w = new Ext.Window({
	height: 250,
	width: 500,
	bbar: new Ext.Toolbar({
	items: [{
	text: 'bbar Left'
	},'->',{
	text: 'bbar Right'
	}]
	}),
	{@link #buttonAlign}: 'left', // anything but 'center' or 'right' and you can use '-', and '->'
	// to control the alignment of fbar items
	fbar: [{
	text: 'fbar Left'
	},'->',{
	text: 'fbar Right'
	}]
	}).show();
	* </code></pre>
	* <p><b>Note:</b> Although a Toolbar may contain Field components, these will <b>not</b> be updated by a load
	* of an ancestor FormPanel. A Panel's toolbars are not part of the standard Container->Component hierarchy, and
	* so are not scanned to collect form items. However, the values <b>will</b> be submitted because form
	* submission parameters are collected from the DOM tree.</p>
	*/
	/**
	* @cfg {Boolean} header
	* <code>true</code> to create the Panel's header element explicitly, <code>false</code> to skip creating
	* it.  If a <code>{@link #title}</code> is set the header will be created automatically, otherwise it will not.
	* If a <code>{@link #title}</code> is set but <code>header</code> is explicitly set to <code>false</code>, the header
	* will not be rendered.
	*/
	/**
	* @cfg {Boolean} footer
	* <code>true</code> to create the footer element explicitly, false to skip creating it. The footer
	* will be created automatically if <code>{@link #buttons}</code> or a <code>{@link #fbar}</code> have
	* been configured.  See <code>{@link #bodyCfg}</code> for an example.
	*/
	/**
	* @cfg {String} title
	* The title text to be used as innerHTML (html tags are accepted) to display in the panel
	* <code>{@link #header}</code> (defaults to ''). When a <code>title</code> is specified the
	* <code>{@link #header}</code> element will automatically be created and displayed unless
	* {@link #header} is explicitly set to <code>false</code>.  If you do not want to specify a
	* <code>title</code> at config time, but you may want one later, you must either specify a non-empty
	* <code>title</code> (a blank space ' ' will do) or <code>header:true</code> so that the container
	* element will get created.
	*/
	/**
	* @cfg {Array} buttons
	* <code>buttons</code> will be used as <code>{@link Ext.Container#items items}</code> for the toolbar in
	* the footer (<code>{@link #fbar}</code>). Typically the value of this configuration property will be
	* an array of {@link Ext.Button}s or {@link Ext.Button} configuration objects.
	* If an item is configured with <code>minWidth</code> or the Panel is configured with <code>minButtonWidth</code>,
	* that width will be applied to the item.
	*/
	/**
	* @cfg {Object/String/Function} autoLoad
	* A valid url spec according to the Updater {@link Ext.Updater#update} method.
	* If autoLoad is not null, the panel will attempt to load its contents
	* immediately upon render.<p>
	* The URL will become the default URL for this panel's {@link #body} element,
	* so it may be {@link Ext.Element#refresh refresh}ed at any time.</p>
	*/
	/**
	* @cfg {Boolean} frame
	* <code>false</code> by default to render with plain 1px square borders. <code>true</code> to render with
	* 9 elements, complete with custom rounded corners (also see {@link Ext.Element#boxWrap}).
	* <p>The template generated for each condition is depicted below:</p><pre><code>
	*
	// frame = false
	&lt;div id="developer-specified-id-goes-here" class="x-panel">

	&lt;div class="x-panel-header">&lt;span class="x-panel-header-text">Title: (frame:false)&lt;/span>&lt;/div>

	&lt;div class="x-panel-bwrap">
	&lt;div class="x-panel-body">&lt;p>html value goes here&lt;/p>&lt;/div>
	&lt;/div>
	&lt;/div>

	// frame = true (create 9 elements)
	&lt;div id="developer-specified-id-goes-here" class="x-panel">
	&lt;div class="x-panel-tl">&lt;div class="x-panel-tr">&lt;div class="x-panel-tc">
	&lt;div class="x-panel-header">&lt;span class="x-panel-header-text">Title: (frame:true)&lt;/span>&lt;/div>
	&lt;/div>&lt;/div>&lt;/div>

	&lt;div class="x-panel-bwrap">
	&lt;div class="x-panel-ml">&lt;div class="x-panel-mr">&lt;div class="x-panel-mc">
	&lt;div class="x-panel-body">&lt;p>html value goes here&lt;/p>&lt;/div>
	&lt;/div>&lt;/div>&lt;/div>

	&lt;div class="x-panel-bl">&lt;div class="x-panel-br">&lt;div class="x-panel-bc"/>
	&lt;/div>&lt;/div>&lt;/div>
	&lt;/div>
	* </code></pre>
	*/
	/**
	* @cfg {Boolean} border
	* True to display the borders of the panel's body element, false to hide them (defaults to true).  By default,
	* the border is a 2px wide inset border, but this can be further altered by setting {@link #bodyBorder} to false.
	*/
	/**
	* @cfg {Boolean} bodyBorder
	* True to display an interior border on the body element of the panel, false to hide it (defaults to true).
	* This only applies when {@link #border} == true.  If border == true and bodyBorder == false, the border will display
	* as a 1px wide inset border, giving the entire body element an inset appearance.
	*/
	/**
	* @cfg {String/Object/Function} bodyCssClass
	* Additional css class selector to be applied to the {@link #body} element in the format expected by
	* {@link Ext.Element#addClass} (defaults to null). See {@link #bodyCfg}.
	*/
	/**
	* @cfg {String/Object/Function} bodyStyle
	* Custom CSS styles to be applied to the {@link #body} element in the format expected by
	* {@link Ext.Element#applyStyles} (defaults to null). See {@link #bodyCfg}.
	*/
	/**
	* @cfg {String} iconCls
	* The CSS class selector that specifies a background image to be used as the header icon (defaults to '').
	* <p>An example of specifying a custom icon class would be something like:
	* </p><pre><code>
	// specify the property in the config for the class:
	...
	iconCls: 'my-icon'

	// css class that specifies background image to be used as the icon image:
	.my-icon { background-image: url(../images/my-icon.gif) 0 6px no-repeat !important; }
	</code></pre>
	*/
	/**
	* @cfg {Boolean} collapsible
	* True to make the panel collapsible and have the expand/collapse toggle button automatically rendered into
	* the header tool button area, false to keep the panel statically sized with no button (defaults to false).
	*/
	/**
	* @cfg {Array} tools
	* An array of tool button configs to be added to the header tool area. When rendered, each tool is
	* stored as an {@link Ext.Element Element} referenced by a public property called <code><b></b>tools.<i>&lt;tool-type&gt;</i></code>
	* <p>Each tool config may contain the following properties:
	* <div class="mdetail-params"><ul>
	* <li><b>id</b> : String<div class="sub-desc"><b>Required.</b> The type
	* of tool to create. By default, this assigns a CSS class of the form <code>x-tool-<i>&lt;tool-type&gt;</i></code> to the
	* resulting tool Element. Ext provides CSS rules, and an icon sprite containing images for the tool types listed below.
	* The developer may implement custom tools by supplying alternate CSS rules and background images:
	* <ul>
	* <div class="x-tool x-tool-toggle" style="float:left; margin-right:5;"> </div><div><code> toggle</code> (Created by default when {@link #collapsible} is <code>true</code>)</div>
	* <div class="x-tool x-tool-close" style="float:left; margin-right:5;"> </div><div><code> close</code></div>
	* <div class="x-tool x-tool-minimize" style="float:left; margin-right:5;"> </div><div><code> minimize</code></div>
	* <div class="x-tool x-tool-maximize" style="float:left; margin-right:5;"> </div><div><code> maximize</code></div>
	* <div class="x-tool x-tool-restore" style="float:left; margin-right:5;"> </div><div><code> restore</code></div>
	* <div class="x-tool x-tool-gear" style="float:left; margin-right:5;"> </div><div><code> gear</code></div>
	* <div class="x-tool x-tool-pin" style="float:left; margin-right:5;"> </div><div><code> pin</code></div>
	* <div class="x-tool x-tool-unpin" style="float:left; margin-right:5;"> </div><div><code> unpin</code></div>
	* <div class="x-tool x-tool-right" style="float:left; margin-right:5;"> </div><div><code> right</code></div>
	* <div class="x-tool x-tool-left" style="float:left; margin-right:5;"> </div><div><code> left</code></div>
	* <div class="x-tool x-tool-up" style="float:left; margin-right:5;"> </div><div><code> up</code></div>
	* <div class="x-tool x-tool-down" style="float:left; margin-right:5;"> </div><div><code> down</code></div>
	* <div class="x-tool x-tool-refresh" style="float:left; margin-right:5;"> </div><div><code> refresh</code></div>
	* <div class="x-tool x-tool-minus" style="float:left; margin-right:5;"> </div><div><code> minus</code></div>
	* <div class="x-tool x-tool-plus" style="float:left; margin-right:5;"> </div><div><code> plus</code></div>
	* <div class="x-tool x-tool-help" style="float:left; margin-right:5;"> </div><div><code> help</code></div>
	* <div class="x-tool x-tool-search" style="float:left; margin-right:5;"> </div><div><code> search</code></div>
	* <div class="x-tool x-tool-save" style="float:left; margin-right:5;"> </div><div><code> save</code></div>
	* <div class="x-tool x-tool-print" style="float:left; margin-right:5;"> </div><div><code> print</code></div>
	* </ul></div></li>
	* <li><b>handler</b> : Function<div class="sub-desc"><b>Required.</b> The function to
	* call when clicked. Arguments passed are:<ul>
	* <li><b>event</b> : Ext.EventObject<div class="sub-desc">The click event.</div></li>
	* <li><b>toolEl</b> : Ext.Element<div class="sub-desc">The tool Element.</div></li>
	* <li><b>panel</b> : Ext.Panel<div class="sub-desc">The host Panel</div></li>
	* <li><b>tc</b> : Object<div class="sub-desc">The tool configuration object</div></li>
	* </ul></div></li>
	* <li><b>stopEvent</b> : Boolean<div class="sub-desc">Defaults to true. Specify as false to allow click event to propagate.</div></li>
	* <li><b>scope</b> : Object<div class="sub-desc">The scope in which to call the handler.</div></li>
	* <li><b>qtip</b> : String/Object<div class="sub-desc">A tip string, or
	* a config argument to {@link Ext.QuickTip#register}</div></li>
	* <li><b>hidden</b> : Boolean<div class="sub-desc">True to initially render hidden.</div></li>
	* <li><b>on</b> : Object<div class="sub-desc">A listener config object specifiying
	* event listeners in the format of an argument to {@link #addListener}</div></li>
	* </ul></div>
	* <p>Note that, apart from the toggle tool which is provided when a panel is collapsible, these
	* tools only provide the visual button. Any required functionality must be provided by adding
	* handlers that implement the necessary behavior.</p>
	* <p>Example usage:</p>
	* <pre><code>
	tools:[{
	id:'refresh',
	qtip: 'Refresh form Data',
	// hidden:true,
	handler: function(event, toolEl, panel){
	// refresh logic
	}
	},
	{
	id:'help',
	qtip: 'Get Help',
	handler: function(event, toolEl, panel){
	// whatever
	}
	}]
	</code></pre>
	* <p>For the custom id of <code>'help'</code> define two relevant css classes with a link to
	* a 15x15 image:</p>
	* <pre><code>
	.x-tool-help {background-image: url(images/help.png);}
	.x-tool-help-over {background-image: url(images/help_over.png);}
	// if using an image sprite:
	.x-tool-help {background-image: url(images/help.png) no-repeat 0 0;}
	.x-tool-help-over {background-position:-15px 0;}
	</code></pre>
	*/
	/**
	* @cfg {Ext.Template/Ext.XTemplate} toolTemplate
	* <p>A Template used to create {@link #tools} in the {@link #header} Element. Defaults to:</p><pre><code>
	new Ext.Template('&lt;div class="x-tool x-tool-{id}">&amp;#160;&lt;/div>')</code></pre>
	* <p>This may may be overridden to provide a custom DOM structure for tools based upon a more
	* complex XTemplate. The template's data is a single tool configuration object (Not the entire Array)
	* as specified in {@link #tools}.  In the following example an &lt;a> tag is used to provide a
	* visual indication when hovering over the tool:</p><pre><code>
	var win = new Ext.Window({
	tools: [{
	id: 'download',
	href: '/MyPdfDoc.pdf'
	}],
	toolTemplate: new Ext.XTemplate(
	'&lt;tpl if="id==\'download\'">',
	'&lt;a class="x-tool x-tool-pdf" href="{href}">&lt;/a>',
	'&lt;/tpl>',
	'&lt;tpl if="id!=\'download\'">',
	'&lt;div class="x-tool x-tool-{id}">&amp;#160;&lt;/div>',
	'&lt;/tpl>'
	),
	width:500,
	height:300,
	closeAction:'hide'
	});</code></pre>
	* <p>Note that the CSS class 'x-tool-pdf' should have an associated style rule which provides an
	* appropriate background image, something like:</p>
	<pre><code>
	a.x-tool-pdf {background-image: url(../shared/extjs/images/pdf.gif)!important;}
	</code></pre>
	*/
	/**
	* @cfg {Boolean} hideCollapseTool
	* <code>true</code> to hide the expand/collapse toggle button when <code>{@link #collapsible} == true</code>,
	* <code>false</code> to display it (defaults to <code>false</code>).
	*/
	/**
	* @cfg {Boolean} titleCollapse
	* <code>true</code> to allow expanding and collapsing the panel (when <code>{@link #collapsible} = true</code>)
	* by clicking anywhere in the header bar, <code>false</code>) to allow it only by clicking to tool button
	* (defaults to <code>false</code>)). If this panel is a child item of a border layout also see the
	* {@link Ext.layout.BorderLayout.Region BorderLayout.Region}
	* <code>{@link Ext.layout.BorderLayout.Region#floatable floatable}</code> config option.
	*/

	/**
	* @cfg {Mixed} floating
	* <p>This property is used to configure the underlying {@link Ext.Layer}. Acceptable values for this
	* configuration property are:</p><div class="mdetail-params"><ul>
	* <li><b><code>false</code></b> : <b>Default.</b><div class="sub-desc">Display the panel inline where it is
	* rendered.</div></li>
	* <li><b><code>true</code></b> : <div class="sub-desc">Float the panel (absolute position it with automatic
	* shimming and shadow).<ul>
	* <div class="sub-desc">Setting floating to true will create an Ext.Layer for this panel and display the
	* panel at negative offsets so that it is hidden.</div>
	* <div class="sub-desc">Since the panel will be absolute positioned, the position must be set explicitly
	* <i>after</i> render (e.g., <code>myPanel.setPosition(100,100);</code>).</div>
	* <div class="sub-desc"><b>Note</b>: when floating a panel you should always assign a fixed width,
	* otherwise it will be auto width and will expand to fill to the right edge of the viewport.</div>
	* </ul></div></li>
	* <li><b><code>{@link Ext.Layer object}</code></b> : <div class="sub-desc">The specified object will be used
	* as the configuration object for the {@link Ext.Layer} that will be created.</div></li>
	* </ul></div>
	*/
	/**
	* @cfg {Boolean/String} shadow
	* <code>true</code> (or a valid Ext.Shadow {@link Ext.Shadow#mode} value) to display a shadow behind the
	* panel, <code>false</code> to display no shadow (defaults to <code>'sides'</code>).  Note that this option
	* only applies when <code>{@link #floating} = true</code>.
	*/
	/**
	* @cfg {Number} shadowOffset
	* The number of pixels to offset the shadow if displayed (defaults to <code>4</code>). Note that this
	* option only applies when <code>{@link #floating} = true</code>.
	*/
	/**
	* @cfg {Boolean} shim
	* <code>false</code> to disable the iframe shim in browsers which need one (defaults to <code>true</code>).
	* Note that this option only applies when <code>{@link #floating} = true</code>.
	*/
	/**
	* @cfg {Object/Array} keys
	* A {@link Ext.KeyMap} config object (in the format expected by {@link Ext.KeyMap#addBinding}
	* used to assign custom key handling to this panel (defaults to <code>null</code>).
	*/
	/**
	* @cfg {Boolean/Object} draggable
	* <p><code>true</code> to enable dragging of this Panel (defaults to <code>false</code>).</p>
	* <p>For custom drag/drop implementations, an <b>Ext.Panel.DD</b> config could also be passed
	* in this config instead of <code>true</code>. Ext.Panel.DD is an internal, undocumented class which
	* moves a proxy Element around in place of the Panel's element, but provides no other behaviour
	* during dragging or on drop. It is a subclass of {@link Ext.dd.DragSource}, so behaviour may be
	* added by implementing the interface methods of {@link Ext.dd.DragDrop} e.g.:
	* <pre><code>
	new Ext.Panel({
	title: 'Drag me',
	x: 100,
	y: 100,
	renderTo: Ext.getBody(),
	floating: true,
	frame: true,
	width: 400,
	height: 200,
	draggable: {
	//      Config option of Ext.Panel.DD class.
	//      It&#39;s a floating Panel, so do not show a placeholder proxy in the original position.
	insertProxy: false,

	//      Called for each mousemove event while dragging the DD object.
	onDrag : function(e){
	//          Record the x,y position of the drag proxy so that we can
	//          position the Panel at end of drag.
	var pel = this.proxy.getEl();
	this.x = pel.getLeft(true);
	this.y = pel.getTop(true);

	//          Keep the Shadow aligned if there is one.
	var s = this.panel.getEl().shadow;
	if (s) {
	s.realign(this.x, this.y, pel.getWidth(), pel.getHeight());
	}
	},

	//      Called on the mouseup event.
	endDrag : function(e){
	this.panel.setPosition(this.x, this.y);
	}
	}
	}).show();
	</code></pre>
	*/
	/**
	* @cfg {Boolean} disabled
	* Render this panel disabled (default is <code>false</code>). An important note when using the disabled
	* config on panels is that IE will often fail to initialize the disabled mask element correectly if
	* the panel's layout has not yet completed by the time the Panel is disabled during the render process.
	* If you experience this issue, you may need to instead use the {@link #afterlayout} event to initialize
	* the disabled state:
	* <pre><code>
	new Ext.Panel({
	...
	listeners: {
	'afterlayout': {
	fn: function(p){
	p.disable();
	},
	single: true // important, as many layouts can occur
	}
	}
	});
	</code></pre>
	*/
	/**
	* @cfg {Boolean} autoHeight
	* <code>true</code> to use height:'auto', <code>false</code> to use fixed height (defaults to <code>false</code>).
	* <b>Note</b>: Setting <code>autoHeight: true</code> means that the browser will manage the panel's height
	* based on its contents, and that Ext will not manage it at all. If the panel is within a layout that
	* manages dimensions (<code>fit</code>, <code>border</code>, etc.) then setting <code>autoHeight: true</code>
	* can cause issues with scrolling and will not generally work as expected since the panel will take
	* on the height of its contents rather than the height required by the Ext layout.
	*/


	/**
	* @cfg {String} baseCls
	* The base CSS class to apply to this panel's element (defaults to <code>'x-panel'</code>).
	* <p>Another option available by default is to specify <code>'x-plain'</code> which strips all styling
	* except for required attributes for Ext layouts to function (e.g. overflow:hidden).
	* See <code>{@link #unstyled}</code> also.</p>
	*/
	baseCls: 'x-panel',
	/**
	* @cfg {String} collapsedCls
	* A CSS class to add to the panel's element after it has been collapsed (defaults to
	* <code>'x-panel-collapsed'</code>).
	*/
	collapsedCls: 'x-panel-collapsed',
	/**
	* @cfg {Boolean} maskDisabled
	* <code>true</code> to mask the panel when it is {@link #disabled}, <code>false</code> to not mask it (defaults
	* to <code>true</code>).  Either way, the panel will always tell its contained elements to disable themselves
	* when it is disabled, but masking the panel can provide an additional visual cue that the panel is
	* disabled.
	*/
	maskDisabled: true,
	/**
	* @cfg {Boolean} animCollapse
	* <code>true</code> to animate the transition when the panel is collapsed, <code>false</code> to skip the
	* animation (defaults to <code>true</code> if the {@link Ext.Fx} class is available, otherwise <code>false</code>).
	*/
	animCollapse: Ext.enableFx,
	/**
	* @cfg {Boolean} headerAsText
	* <code>true</code> to display the panel <code>{@link #title}</code> in the <code>{@link #header}</code>,
	* <code>false</code> to hide it (defaults to <code>true</code>).
	*/
	headerAsText: true,
	/**
	* @cfg {String} buttonAlign
	* The alignment of any {@link #buttons} added to this panel.  Valid values are <code>'right'</code>,
	* <code>'left'</code> and <code>'center'</code> (defaults to <code>'right'</code>).
	*/
	buttonAlign: 'right',
	/**
	* @cfg {Boolean} collapsed
	* <code>true</code> to render the panel collapsed, <code>false</code> to render it expanded (defaults to
	* <code>false</code>).
	*/
	collapsed: false,
	/**
	* @cfg {Boolean} collapseFirst
	* <code>true</code> to make sure the collapse/expand toggle button always renders first (to the left of)
	* any other tools in the panel's title bar, <code>false</code> to render it last (defaults to <code>true</code>).
	*/
	collapseFirst: true,
	/**
	* @cfg {Number} minButtonWidth
	* Minimum width in pixels of all {@link #buttons} in this panel (defaults to <code>75</code>)
	*/
	minButtonWidth: 75,
	/**
	* @cfg {Boolean} unstyled
	* Overrides the <code>{@link #baseCls}</code> setting to <code>{@link #baseCls} = 'x-plain'</code> which renders
	* the panel unstyled except for required attributes for Ext layouts to function (e.g. overflow:hidden).
	*/
	/**
	* @cfg {String} elements
	* A comma-delimited list of panel elements to initialize when the panel is rendered.  Normally, this list will be
	* generated automatically based on the items added to the panel at config time, but sometimes it might be useful to
	* make sure a structural element is rendered even if not specified at config time (for example, you may want
	* to add a button or toolbar dynamically after the panel has been rendered).  Adding those elements to this
	* list will allocate the required placeholders in the panel when it is rendered.  Valid values are<div class="mdetail-params"><ul>
	* <li><code>header</code></li>
	* <li><code>tbar</code> (top bar)</li>
	* <li><code>body</code></li>
	* <li><code>bbar</code> (bottom bar)</li>
	* <li><code>footer</code></li>
	* </ul></div>
	* Defaults to '<code>body</code>'.
	*/
	elements: 'body',
	/**
	* @cfg {Boolean} preventBodyReset
	* Defaults to <code>false</code>.  When set to <code>true</code>, an extra css class <code>'x-panel-normal'</code>
	* will be added to the panel's element, effectively applying css styles suggested by the W3C
	* (see http://www.w3.org/TR/CSS21/sample.html) to the Panel's <b>body</b> element (not the header,
	* footer, etc.).
	*/
	preventBodyReset: false,

	/**
	* @cfg {Number/String} padding
	* A shortcut for setting a padding style on the body element. The value can either be
	* a number to be applied to all sides, or a normal css string describing padding.
	* Defaults to <tt>undefined</tt>.
	*
	*/
	padding: undefined,

	/** @cfg {String} resizeEvent
	* The event to listen to for resizing in layouts. Defaults to <tt>'bodyresize'</tt>.
	*/
	resizeEvent: 'bodyresize',

	// protected - these could be used to customize the behavior of the window,
	// but changing them would not be useful without further mofifications and
	// could lead to unexpected or undesirable results.
	toolTarget: 'header',
	collapseEl: 'bwrap',
	slideAnchor: 't',
	disabledClass: '',

	// private, notify box this class will handle heights
	deferHeight: true,
	// private
	expandDefaults: {
		duration: 0.25
	},
	// private
	collapseDefaults: {
		duration: 0.25
	},

	// private
	initComponent: function () {
		Ext.Panel.superclass.initComponent.call(this);

		this.addEvents(
		/**
		* @event bodyresize
		* Fires after the Panel has been resized.
		* @param {Ext.Panel} p the Panel which has been resized.
		* @param {Number} width The Panel body's new width.
		* @param {Number} height The Panel body's new height.
		*/
            'bodyresize',
		/**
		* @event titlechange
		* Fires after the Panel title has been {@link #title set} or {@link #setTitle changed}.
		* @param {Ext.Panel} p the Panel which has had its title changed.
		* @param {String} The new title.
		*/
            'titlechange',
		/**
		* @event iconchange
		* Fires after the Panel icon class has been {@link #iconCls set} or {@link #setIconClass changed}.
		* @param {Ext.Panel} p the Panel which has had its {@link #iconCls icon class} changed.
		* @param {String} The new icon class.
		* @param {String} The old icon class.
		*/
            'iconchange',
		/**
		* @event collapse
		* Fires after the Panel has been collapsed.
		* @param {Ext.Panel} p the Panel that has been collapsed.
		*/
            'collapse',
		/**
		* @event expand
		* Fires after the Panel has been expanded.
		* @param {Ext.Panel} p The Panel that has been expanded.
		*/
            'expand',
		/**
		* @event beforecollapse
		* Fires before the Panel is collapsed.  A handler can return false to cancel the collapse.
		* @param {Ext.Panel} p the Panel being collapsed.
		* @param {Boolean} animate True if the collapse is animated, else false.
		*/
            'beforecollapse',
		/**
		* @event beforeexpand
		* Fires before the Panel is expanded.  A handler can return false to cancel the expand.
		* @param {Ext.Panel} p The Panel being expanded.
		* @param {Boolean} animate True if the expand is animated, else false.
		*/
            'beforeexpand',
		/**
		* @event beforeclose
		* Fires before the Panel is closed.  Note that Panels do not directly support being closed, but some
		* Panel subclasses do (like {@link Ext.Window}) or a Panel within a Ext.TabPanel.  This event only
		* applies to such subclasses.
		* A handler can return false to cancel the close.
		* @param {Ext.Panel} p The Panel being closed.
		*/
            'beforeclose',
		/**
		* @event close
		* Fires after the Panel is closed.  Note that Panels do not directly support being closed, but some
		* Panel subclasses do (like {@link Ext.Window}) or a Panel within a Ext.TabPanel.
		* @param {Ext.Panel} p The Panel that has been closed.
		*/
            'close',
		/**
		* @event activate
		* Fires after the Panel has been visually activated.
		* Note that Panels do not directly support being activated, but some Panel subclasses
		* do (like {@link Ext.Window}). Panels which are child Components of a TabPanel fire the
		* activate and deactivate events under the control of the TabPanel.
		* @param {Ext.Panel} p The Panel that has been activated.
		*/
            'activate',
		/**
		* @event deactivate
		* Fires after the Panel has been visually deactivated.
		* Note that Panels do not directly support being deactivated, but some Panel subclasses
		* do (like {@link Ext.Window}). Panels which are child Components of a TabPanel fire the
		* activate and deactivate events under the control of the TabPanel.
		* @param {Ext.Panel} p The Panel that has been deactivated.
		*/
            'deactivate'
        );

		if (this.unstyled) {
			this.baseCls = 'x-plain';
		}


		this.toolbars = [];
		// shortcuts
		if (this.tbar) {
			this.elements += ',tbar';
			this.topToolbar = this.createToolbar(this.tbar);
			this.tbar = null;

		}
		if (this.bbar) {
			this.elements += ',bbar';
			this.bottomToolbar = this.createToolbar(this.bbar);
			this.bbar = null;
		}

		if (this.header === true) {
			this.elements += ',header';
			this.header = null;
		} else if (this.headerCfg || (this.title && this.header !== false)) {
			this.elements += ',header';
		}

		if (this.footerCfg || this.footer === true) {
			this.elements += ',footer';
			this.footer = null;
		}

		if (this.buttons) {
			this.fbar = this.buttons;
			this.buttons = null;
		}
		if (this.fbar) {
			this.createFbar(this.fbar);
		}
		if (this.autoLoad) {
			this.on('render', this.doAutoLoad, this, { delay: 10 });
		}
	},

	// private
	createFbar: function (fbar) {
		var min = this.minButtonWidth;
		this.elements += ',footer';
		this.fbar = this.createToolbar(fbar, {
			buttonAlign: this.buttonAlign,
			toolbarCls: 'x-panel-fbar',
			enableOverflow: false,
			defaults: function (c) {
				return {
					minWidth: c.minWidth || min
				};
			}
		});
		// @compat addButton and buttons could possibly be removed
		// @target 4.0
		/**
		* This Panel's Array of buttons as created from the <code>{@link #buttons}</code>
		* config property. Read only.
		* @type Array
		* @property buttons
		*/
		this.fbar.items.each(function (c) {
			c.minWidth = c.minWidth || this.minButtonWidth;
		}, this);
		this.buttons = this.fbar.items.items;
	},

	// private
	createToolbar: function (tb, options) {
		var result;
		// Convert array to proper toolbar config
		if (Ext.isArray(tb)) {
			tb = {
				items: tb
			};
		}
		result = tb.events ? Ext.apply(tb, options) : this.createComponent(Ext.apply({}, tb, options), 'toolbar');
		this.toolbars.push(result);
		return result;
	},

	// private
	createElement: function (name, pnode) {
		if (this[name]) {
			pnode.appendChild(this[name].dom);
			return;
		}

		if (name === 'bwrap' || this.elements.indexOf(name) != -1) {
			if (this[name + 'Cfg']) {
				this[name] = Ext.fly(pnode).createChild(this[name + 'Cfg']);
			} else {
				var el = document.createElement('div');
				el.className = this[name + 'Cls'];
				this[name] = Ext.get(pnode.appendChild(el));
			}
			if (this[name + 'CssClass']) {
				this[name].addClass(this[name + 'CssClass']);
			}
			if (this[name + 'Style']) {
				this[name].applyStyles(this[name + 'Style']);
			}
		}
	},

	// private
	onRender: function (ct, position) {
		Ext.Panel.superclass.onRender.call(this, ct, position);
		this.createClasses();

		var el = this.el,
            d = el.dom,
            bw,
            ts;


		if (this.collapsible && !this.hideCollapseTool) {
			this.tools = this.tools ? this.tools.slice(0) : [];
			this.tools[this.collapseFirst ? 'unshift' : 'push']({
				id: 'toggle',
				handler: this.toggleCollapse,
				scope: this
			});
		}

		if (this.tools) {
			ts = this.tools;
			this.elements += (this.header !== false) ? ',header' : '';
		}
		this.tools = {};

		el.addClass(this.baseCls);
		if (d.firstChild) { // existing markup
			this.header = el.down('.' + this.headerCls);
			this.bwrap = el.down('.' + this.bwrapCls);
			var cp = this.bwrap ? this.bwrap : el;
			this.tbar = cp.down('.' + this.tbarCls);
			this.body = cp.down('.' + this.bodyCls);
			this.bbar = cp.down('.' + this.bbarCls);
			this.footer = cp.down('.' + this.footerCls);
			this.fromMarkup = true;
		}
		if (this.preventBodyReset === true) {
			el.addClass('x-panel-reset');
		}
		if (this.cls) {
			el.addClass(this.cls);
		}

		if (this.buttons) {
			this.elements += ',footer';
		}

		// This block allows for maximum flexibility and performance when using existing markup

		// framing requires special markup
		if (this.frame) {
			el.insertHtml('afterBegin', String.format(Ext.Element.boxMarkup, this.baseCls));

			this.createElement('header', d.firstChild.firstChild.firstChild);
			this.createElement('bwrap', d);

			// append the mid and bottom frame to the bwrap
			bw = this.bwrap.dom;
			var ml = d.childNodes[1], bl = d.childNodes[2];
			bw.appendChild(ml);
			bw.appendChild(bl);

			var mc = bw.firstChild.firstChild.firstChild;
			this.createElement('tbar', mc);
			this.createElement('body', mc);
			this.createElement('bbar', mc);
			this.createElement('footer', bw.lastChild.firstChild.firstChild);

			if (!this.footer) {
				this.bwrap.dom.lastChild.className += ' x-panel-nofooter';
			}
			/*
			* Store a reference to this element so:
			* a) We aren't looking it up all the time
			* b) The last element is reported incorrectly when using a loadmask
			*/
			this.ft = Ext.get(this.bwrap.dom.lastChild);
			this.mc = Ext.get(mc);
		} else {
			this.createElement('header', d);
			this.createElement('bwrap', d);

			// append the mid and bottom frame to the bwrap
			bw = this.bwrap.dom;
			this.createElement('tbar', bw);
			this.createElement('body', bw);
			this.createElement('bbar', bw);
			this.createElement('footer', bw);

			if (!this.header) {
				this.body.addClass(this.bodyCls + '-noheader');
				if (this.tbar) {
					this.tbar.addClass(this.tbarCls + '-noheader');
				}
			}
		}

		if (Ext.isDefined(this.padding)) {
			this.body.setStyle('padding', this.body.addUnits(this.padding));
		}

		if (this.border === false) {
			this.el.addClass(this.baseCls + '-noborder');
			this.body.addClass(this.bodyCls + '-noborder');
			if (this.header) {
				this.header.addClass(this.headerCls + '-noborder');
			}
			if (this.footer) {
				this.footer.addClass(this.footerCls + '-noborder');
			}
			if (this.tbar) {
				this.tbar.addClass(this.tbarCls + '-noborder');
			}
			if (this.bbar) {
				this.bbar.addClass(this.bbarCls + '-noborder');
			}
		}

		if (this.bodyBorder === false) {
			this.body.addClass(this.bodyCls + '-noborder');
		}

		this.bwrap.enableDisplayMode('block');

		if (this.header) {
			this.header.unselectable();

			// for tools, we need to wrap any existing header markup
			if (this.headerAsText) {
				this.header.dom.innerHTML =
                    '<span class="' + this.headerTextCls + '">' + this.header.dom.innerHTML + '</span>';

				if (this.iconCls) {
					this.setIconClass(this.iconCls);
				}
			}
		}

		if (this.floating) {
			this.makeFloating(this.floating);
		}

		if (this.collapsible && this.titleCollapse && this.header) {
			this.mon(this.header, 'click', this.toggleCollapse, this);
			this.header.setStyle('cursor', 'pointer');
		}
		if (ts) {
			this.addTool.apply(this, ts);
		}

		// Render Toolbars.
		if (this.fbar) {
			this.footer.addClass('x-panel-btns');
			this.fbar.ownerCt = this;
			this.fbar.render(this.footer);
			this.footer.createChild({ cls: 'x-clear' });
		}
		if (this.tbar && this.topToolbar) {
			this.topToolbar.ownerCt = this;
			this.topToolbar.render(this.tbar);
		}
		if (this.bbar && this.bottomToolbar) {
			this.bottomToolbar.ownerCt = this;
			this.bottomToolbar.render(this.bbar);
		}
	},

	/**
	* Sets the CSS class that provides the icon image for this panel.  This method will replace any existing
	* icon class if one has already been set and fire the {@link #iconchange} event after completion.
	* @param {String} cls The new CSS class name
	*/
	setIconClass: function (cls) {
		var old = this.iconCls;
		this.iconCls = cls;
		if (this.rendered && this.header) {
			if (this.frame) {
				this.header.addClass('x-panel-icon');
				this.header.replaceClass(old, this.iconCls);
			} else {
				var hd = this.header,
                    img = hd.child('img.x-panel-inline-icon');
				if (img) {
					Ext.fly(img).replaceClass(old, this.iconCls);
				} else {
					var hdspan = hd.child('span.' + this.headerTextCls);
					if (hdspan) {
						Ext.DomHelper.insertBefore(hdspan.dom, {
							tag: 'img', src: Ext.BLANK_IMAGE_URL, cls: 'x-panel-inline-icon ' + this.iconCls
						});
					}
				}
			}
		}
		this.fireEvent('iconchange', this, cls, old);
	},

	// private
	makeFloating: function (cfg) {
		this.floating = true;
		this.el = new Ext.Layer(Ext.apply({}, cfg, {
			shadow: Ext.isDefined(this.shadow) ? this.shadow : 'sides',
			shadowOffset: this.shadowOffset,
			constrain: false,
			shim: this.shim === false ? false : undefined
		}), this.el);
	},

	/**
	* Returns the {@link Ext.Toolbar toolbar} from the top (<code>{@link #tbar}</code>) section of the panel.
	* @return {Ext.Toolbar} The toolbar
	*/
	getTopToolbar: function () {
		return this.topToolbar;
	},

	/**
	* Returns the {@link Ext.Toolbar toolbar} from the bottom (<code>{@link #bbar}</code>) section of the panel.
	* @return {Ext.Toolbar} The toolbar
	*/
	getBottomToolbar: function () {
		return this.bottomToolbar;
	},

	/**
	* Returns the {@link Ext.Toolbar toolbar} from the footer (<code>{@link #fbar}</code>) section of the panel.
	* @return {Ext.Toolbar} The toolbar
	*/
	getFooterToolbar: function () {
		return this.fbar;
	},

	/**
	* Adds a button to this panel.  Note that this method must be called prior to rendering.  The preferred
	* approach is to add buttons via the {@link #buttons} config.
	* @param {String/Object} config A valid {@link Ext.Button} config.  A string will become the text for a default
	* button config, an object will be treated as a button config object.
	* @param {Function} handler The function to be called on button {@link Ext.Button#click}
	* @param {Object} scope The scope (<code>this</code> reference) in which the button handler function is executed. Defaults to the Button.
	* @return {Ext.Button} The button that was added
	*/
	addButton: function (config, handler, scope) {
		if (!this.fbar) {
			this.createFbar([]);
		}
		if (handler) {
			if (Ext.isString(config)) {
				config = { text: config };
			}
			config = Ext.apply({
				handler: handler,
				scope: scope
			}, config);
		}
		return this.fbar.add(config);
	},

	// private
	addTool: function () {
		if (!this.rendered) {
			if (!this.tools) {
				this.tools = [];
			}
			Ext.each(arguments, function (arg) {
				this.tools.push(arg);
			}, this);
			return;
		}
		// nowhere to render tools!
		if (!this[this.toolTarget]) {
			return;
		}
		if (!this.toolTemplate) {
			// initialize the global tool template on first use
			var tt = new Ext.Template(
                 '<div class="x-tool x-tool-{id}">&#160;</div>'
            );
			tt.disableFormats = true;
			tt.compile();
			Ext.Panel.prototype.toolTemplate = tt;
		}
		for (var i = 0, a = arguments, len = a.length; i < len; i++) {
			var tc = a[i];
			if (!this.tools[tc.id]) {
				var overCls = 'x-tool-' + tc.id + '-over';
				var t = this.toolTemplate.insertFirst(this[this.toolTarget], tc, true);
				this.tools[tc.id] = t;
				t.enableDisplayMode('block');
				this.mon(t, 'click', this.createToolHandler(t, tc, overCls, this));
				if (tc.on) {
					this.mon(t, tc.on);
				}
				if (tc.hidden) {
					t.hide();
				}
				if (tc.qtip) {
					if (Ext.isObject(tc.qtip)) {
						Ext.QuickTips.register(Ext.apply({
							target: t.id
						}, tc.qtip));
					} else {
						t.dom.qtip = tc.qtip;
					}
				}
				t.addClassOnOver(overCls);
			}
		}
	},

	onLayout: function (shallow, force) {
		Ext.Panel.superclass.onLayout.apply(this, arguments);
		if (this.hasLayout && this.toolbars.length > 0) {
			Ext.each(this.toolbars, function (tb) {
				tb.doLayout(undefined, force);
			});
			this.syncHeight();
		}
	},

	syncHeight: function () {
		var h = this.toolbarHeight,
                bd = this.body,
                lsh = this.lastSize.height,
                sz;

		if (this.autoHeight || !Ext.isDefined(lsh) || lsh == 'auto') {
			return;
		}


		if (h != this.getToolbarHeight()) {
			h = Math.max(0, lsh - this.getFrameHeight());
			bd.setHeight(h);
			sz = bd.getSize();
			this.toolbarHeight = this.getToolbarHeight();
			this.onBodyResize(sz.width, sz.height);
		}
	},

	// private
	onShow: function () {
		if (this.floating) {
			return this.el.show();
		}
		Ext.Panel.superclass.onShow.call(this);
	},

	// private
	onHide: function () {
		if (this.floating) {
			return this.el.hide();
		}
		Ext.Panel.superclass.onHide.call(this);
	},

	// private
	createToolHandler: function (t, tc, overCls, panel) {
		return function (e) {
			t.removeClass(overCls);
			if (tc.stopEvent !== false) {
				e.stopEvent();
			}
			if (tc.handler) {
				tc.handler.call(tc.scope || t, e, t, panel, tc);
			}
		};
	},

	// private
	afterRender: function () {
		if (this.floating && !this.hidden) {
			this.el.show();
		}
		if (this.title) {
			this.setTitle(this.title);
		}
		Ext.Panel.superclass.afterRender.call(this); // do sizing calcs last
		if (this.collapsed) {
			this.collapsed = false;
			this.collapse(false);
		}
		this.initEvents();
	},

	// private
	getKeyMap: function () {
		if (!this.keyMap) {
			this.keyMap = new Ext.KeyMap(this.el, this.keys);
		}
		return this.keyMap;
	},

	// private
	initEvents: function () {
		if (this.keys) {
			this.getKeyMap();
		}
		if (this.draggable) {
			this.initDraggable();
		}
		if (this.toolbars.length > 0) {
			Ext.each(this.toolbars, function (tb) {
				tb.doLayout();
				tb.on({
					scope: this,
					afterlayout: this.syncHeight,
					remove: this.syncHeight
				});
			}, this);
			this.syncHeight();
		}

	},

	// private
	initDraggable: function () {
		/**
		* <p>If this Panel is configured {@link #draggable}, this property will contain
		* an instance of {@link Ext.dd.DragSource} which handles dragging the Panel.</p>
		* The developer must provide implementations of the abstract methods of {@link Ext.dd.DragSource}
		* in order to supply behaviour for each stage of the drag/drop process. See {@link #draggable}.
		* @type Ext.dd.DragSource.
		* @property dd
		*/
		this.dd = new Ext.Panel.DD(this, Ext.isBoolean(this.draggable) ? null : this.draggable);
	},

	// private
	beforeEffect: function (anim) {
		if (this.floating) {
			this.el.beforeAction();
		}
		if (anim !== false) {
			this.el.addClass('x-panel-animated');
		}
	},

	// private
	afterEffect: function (anim) {
		this.syncShadow();
		this.el.removeClass('x-panel-animated');
	},

	// private - wraps up an animation param with internal callbacks
	createEffect: function (a, cb, scope) {
		var o = {
			scope: scope,
			block: true
		};
		if (a === true) {
			o.callback = cb;
			return o;
		} else if (!a.callback) {
			o.callback = cb;
		} else { // wrap it up
			o.callback = function () {
				cb.call(scope);
				Ext.callback(a.callback, a.scope);
			};
		}
		return Ext.applyIf(o, a);
	},

	/**
	* Collapses the panel body so that it becomes hidden.  Fires the {@link #beforecollapse} event which will
	* cancel the collapse action if it returns false.
	* @param {Boolean} animate True to animate the transition, else false (defaults to the value of the
	* {@link #animCollapse} panel config)
	* @return {Ext.Panel} this
	*/
	collapse: function (animate) {
		if (this.collapsed || this.el.hasFxBlock() || this.fireEvent('beforecollapse', this, animate) === false) {
			return;
		}
		var doAnim = animate === true || (animate !== false && this.animCollapse);
		this.beforeEffect(doAnim);
		this.onCollapse(doAnim, animate);
		return this;
	},

	// private
	onCollapse: function (doAnim, animArg) {
		if (doAnim) {
			this[this.collapseEl].slideOut(this.slideAnchor,
                    Ext.apply(this.createEffect(animArg || true, this.afterCollapse, this),
                        this.collapseDefaults));
		} else {
			this[this.collapseEl].hide(this.hideMode);
			this.afterCollapse(false);
		}
	},

	// private
	afterCollapse: function (anim) {
		this.collapsed = true;
		this.el.addClass(this.collapsedCls);
		if (anim !== false) {
			this[this.collapseEl].hide(this.hideMode);
		}
		this.afterEffect(anim);

		// Reset lastSize of all sub-components so they KNOW they are in a collapsed container
		this.cascade(function (c) {
			if (c.lastSize) {
				c.lastSize = { width: undefined, height: undefined };
			}
		});
		this.fireEvent('collapse', this);
	},

	/**
	* Expands the panel body so that it becomes visible.  Fires the {@link #beforeexpand} event which will
	* cancel the expand action if it returns false.
	* @param {Boolean} animate True to animate the transition, else false (defaults to the value of the
	* {@link #animCollapse} panel config)
	* @return {Ext.Panel} this
	*/
	expand: function (animate) {
		if (!this.collapsed || this.el.hasFxBlock() || this.fireEvent('beforeexpand', this, animate) === false) {
			return;
		}
		var doAnim = animate === true || (animate !== false && this.animCollapse);
		this.el.removeClass(this.collapsedCls);
		this.beforeEffect(doAnim);
		this.onExpand(doAnim, animate);
		return this;
	},

	// private
	onExpand: function (doAnim, animArg) {
		if (doAnim) {
			this[this.collapseEl].slideIn(this.slideAnchor,
                    Ext.apply(this.createEffect(animArg || true, this.afterExpand, this),
                        this.expandDefaults));
		} else {
			this[this.collapseEl].show(this.hideMode);
			this.afterExpand(false);
		}
	},

	// private
	afterExpand: function (anim) {
		this.collapsed = false;
		if (anim !== false) {
			this[this.collapseEl].show(this.hideMode);
		}
		this.afterEffect(anim);
		if (this.deferLayout) {
			delete this.deferLayout;
			this.doLayout(true);
		}
		this.fireEvent('expand', this);
	},

	/**
	* Shortcut for performing an {@link #expand} or {@link #collapse} based on the current state of the panel.
	* @param {Boolean} animate True to animate the transition, else false (defaults to the value of the
	* {@link #animCollapse} panel config)
	* @return {Ext.Panel} this
	*/
	toggleCollapse: function (animate) {
		this[this.collapsed ? 'expand' : 'collapse'](animate);
		return this;
	},

	// private
	onDisable: function () {
		if (this.rendered && this.maskDisabled) {
			this.el.mask();
		}
		Ext.Panel.superclass.onDisable.call(this);
	},

	// private
	onEnable: function () {
		if (this.rendered && this.maskDisabled) {
			this.el.unmask();
		}
		Ext.Panel.superclass.onEnable.call(this);
	},

	// private
	onResize: function (adjWidth, adjHeight, rawWidth, rawHeight) {
		var w = adjWidth,
            h = adjHeight;

		if (Ext.isDefined(w) || Ext.isDefined(h)) {
			if (!this.collapsed) {
				// First, set the the Panel's body width.
				// If we have auto-widthed it, get the resulting full offset width so we can size the Toolbars to match
				// The Toolbars must not buffer this resize operation because we need to know their heights.

				if (Ext.isNumber(w)) {
					this.body.setWidth(w = this.adjustBodyWidth(w - this.getFrameWidth()));
				} else if (w == 'auto') {
					w = this.body.setWidth('auto').dom.offsetWidth;
				} else {
					w = this.body.dom.offsetWidth;
				}

				if (this.tbar) {
					this.tbar.setWidth(w);
					if (this.topToolbar) {
						this.topToolbar.setSize(w);
					}
				}
				if (this.bbar) {
					this.bbar.setWidth(w);
					if (this.bottomToolbar) {
						this.bottomToolbar.setSize(w);
						// The bbar does not move on resize without this.
						if (Ext.isIE) {
							this.bbar.setStyle('position', 'static');
							this.bbar.setStyle('position', '');
						}
					}
				}
				if (this.footer) {
					this.footer.setWidth(w);
					if (this.fbar) {
						this.fbar.setSize(Ext.isIE ? (w - this.footer.getFrameWidth('lr')) : 'auto');
					}
				}

				// At this point, the Toolbars must be layed out for getFrameHeight to find a result.
				if (Ext.isNumber(h)) {
					h = Math.max(0, h - this.getFrameHeight());
					//h = Math.max(0, h - (this.getHeight() - this.body.getHeight()));
					this.body.setHeight(h);
				} else if (h == 'auto') {
					this.body.setHeight(h);
				}

				if (this.disabled && this.el._mask) {
					this.el._mask.setSize(this.el.dom.clientWidth, this.el.getHeight());
				}
			} else {
				// Adds an event to set the correct height afterExpand.  This accounts for the deferHeight flag in panel
				this.queuedBodySize = { width: w, height: h };
				if (!this.queuedExpand && this.allowQueuedExpand !== false) {
					this.queuedExpand = true;
					this.on('expand', function () {
						delete this.queuedExpand;
						this.onResize(this.queuedBodySize.width, this.queuedBodySize.height);
					}, this, { single: true });
				}
			}
			this.onBodyResize(w, h);
		}
		this.syncShadow();
		Ext.Panel.superclass.onResize.call(this, adjWidth, adjHeight, rawWidth, rawHeight);

	},

	// private
	onBodyResize: function (w, h) {
		this.fireEvent('bodyresize', this, w, h);
	},

	// private
	getToolbarHeight: function () {
		var h = 0;
		if (this.rendered) {
			Ext.each(this.toolbars, function (tb) {
				h += tb.getHeight();
			}, this);
		}
		return h;
	},

	// deprecate
	adjustBodyHeight: function (h) {
		return h;
	},

	// private
	adjustBodyWidth: function (w) {
		return w;
	},

	// private
	onPosition: function () {
		this.syncShadow();
	},

	/**
	* Returns the width in pixels of the framing elements of this panel (not including the body width).  To
	* retrieve the body width see {@link #getInnerWidth}.
	* @return {Number} The frame width
	*/
	getFrameWidth: function () {
		var w = this.el.getFrameWidth('lr') + this.bwrap.getFrameWidth('lr');

		if (this.frame) {
			var l = this.bwrap.dom.firstChild;
			w += (Ext.fly(l).getFrameWidth('l') + Ext.fly(l.firstChild).getFrameWidth('r'));
			w += this.mc.getFrameWidth('lr');
		}
		return w;
	},

	/**
	* Returns the height in pixels of the framing elements of this panel (including any top and bottom bars and
	* header and footer elements, but not including the body height).  To retrieve the body height see {@link #getInnerHeight}.
	* @return {Number} The frame height
	*/
	getFrameHeight: function () {
		var h = Math.max(0, this.getHeight() - this.body.getHeight());

		if (isNaN(h)) {
			h = 0;
		}
		return h;

		/* Deprecate
		var h  = this.el.getFrameWidth('tb') + this.bwrap.getFrameWidth('tb');
		h += (this.tbar ? this.tbar.getHeight() : 0) +
		(this.bbar ? this.bbar.getHeight() : 0);

		if(this.frame){
		h += this.el.dom.firstChild.offsetHeight + this.ft.dom.offsetHeight + this.mc.getFrameWidth('tb');
		}else{
		h += (this.header ? this.header.getHeight() : 0) +
		(this.footer ? this.footer.getHeight() : 0);
		}
		return h;
		*/
	},

	/**
	* Returns the width in pixels of the body element (not including the width of any framing elements).
	* For the frame width see {@link #getFrameWidth}.
	* @return {Number} The body width
	*/
	getInnerWidth: function () {
		return this.getSize().width - this.getFrameWidth();
	},

	/**
	* Returns the height in pixels of the body element (not including the height of any framing elements).
	* For the frame height see {@link #getFrameHeight}.
	* @return {Number} The body height
	*/
	getInnerHeight: function () {
		return this.body.getHeight();
		/* Deprecate
		return this.getSize().height - this.getFrameHeight();
		*/
	},

	// private
	syncShadow: function () {
		if (this.floating) {
			this.el.sync(true);
		}
	},

	// private
	getLayoutTarget: function () {
		return this.body;
	},

	// private
	getContentTarget: function () {
		return this.body;
	},

	/**
	* <p>Sets the title text for the panel and optionally the {@link #iconCls icon class}.</p>
	* <p>In order to be able to set the title, a header element must have been created
	* for the Panel. This is triggered either by configuring the Panel with a non-blank <code>{@link #title}</code>,
	* or configuring it with <code><b>{@link #header}: true</b></code>.</p>
	* @param {String} title The title text to set
	* @param {String} iconCls (optional) {@link #iconCls iconCls} A user-defined CSS class that provides the icon image for this panel
	*/
	setTitle: function (title, iconCls) {
		this.title = title;
		if (this.header && this.headerAsText) {
			this.header.child('span').update(title);
		}
		if (iconCls) {
			this.setIconClass(iconCls);
		}
		this.fireEvent('titlechange', this, title);
		return this;
	},

	/**
	* Get the {@link Ext.Updater} for this panel. Enables you to perform Ajax updates of this panel's body.
	* @return {Ext.Updater} The Updater
	*/
	getUpdater: function () {
		return this.body.getUpdater();
	},

	/**
	* Loads this content panel immediately with content returned from an XHR call.
	* @param {Object/String/Function} config A config object containing any of the following options:
	<pre><code>
	panel.load({
	url: 'your-url.php',
	params: {param1: 'foo', param2: 'bar'}, // or a URL encoded string
	callback: yourFunction,
	scope: yourObject, // optional scope for the callback
	discardUrl: false,
	nocache: false,
	text: 'Loading...',
	timeout: 30,
	scripts: false
	});
	</code></pre>
	* The only required property is url. The optional properties nocache, text and scripts
	* are shorthand for disableCaching, indicatorText and loadScripts and are used to set their
	* associated property on this panel Updater instance.
	* @return {Ext.Panel} this
	*/
	load: function () {
		var um = this.body.getUpdater();
		um.update.apply(um, arguments);
		return this;
	},

	// private
	beforeDestroy: function () {
		Ext.Panel.superclass.beforeDestroy.call(this);
		if (this.header) {
			this.header.removeAllListeners();
		}
		if (this.tools) {
			for (var k in this.tools) {
				Ext.destroy(this.tools[k]);
			}
		}
		if (this.toolbars.length > 0) {
			Ext.each(this.toolbars, function (tb) {
				tb.un('afterlayout', this.syncHeight, this);
				tb.un('remove', this.syncHeight, this);
			}, this);
		}
		if (Ext.isArray(this.buttons)) {
			while (this.buttons.length) {
				Ext.destroy(this.buttons[0]);
			}
		}
		if (this.rendered) {
			Ext.destroy(
                this.ft,
                this.header,
                this.footer,
                this.tbar,
                this.bbar,
                this.body,
                this.mc,
                this.bwrap,
                this.dd
            );
			if (this.fbar) {
				Ext.destroy(
                    this.fbar,
                    this.fbar.el
                );
			}
		}
		Ext.destroy(this.toolbars);
	},

	// private
	createClasses: function () {
		this.headerCls = this.baseCls + '-header';
		this.headerTextCls = this.baseCls + '-header-text';
		this.bwrapCls = this.baseCls + '-bwrap';
		this.tbarCls = this.baseCls + '-tbar';
		this.bodyCls = this.baseCls + '-body';
		this.bbarCls = this.baseCls + '-bbar';
		this.footerCls = this.baseCls + '-footer';
	},

	// private
	createGhost: function (cls, useShim, appendTo) {
		var el = document.createElement('div');
		el.className = 'x-panel-ghost ' + (cls ? cls : '');
		if (this.header) {
			el.appendChild(this.el.dom.firstChild.cloneNode(true));
		}
		Ext.fly(el.appendChild(document.createElement('ul'))).setHeight(this.bwrap.getHeight());
		el.style.width = this.el.dom.offsetWidth + 'px'; ;
		if (!appendTo) {
			this.container.dom.appendChild(el);
		} else {
			Ext.getDom(appendTo).appendChild(el);
		}
		if (useShim !== false && this.el.useShim !== false) {
			var layer = new Ext.Layer({ shadow: false, useDisplay: true, constrain: false }, el);
			layer.show();
			return layer;
		} else {
			return new Ext.Element(el);
		}
	},

	// private
	doAutoLoad: function () {
		var u = this.body.getUpdater();
		if (this.renderer) {
			u.setRenderer(this.renderer);
		}
		u.update(Ext.isObject(this.autoLoad) ? this.autoLoad : { url: this.autoLoad });
	},

	/**
	* Retrieve a tool by id.
	* @param {String} id
	* @return {Object} tool
	*/
	getTool: function (id) {
		return this.tools[id];
	}

	/**
	* @cfg {String} autoEl @hide
	*/
});
Ext.reg('panel', Ext.Panel);
/**
* @class Ext.Editor
* @extends Ext.Component
* A base editor field that handles displaying/hiding on demand and has some built-in sizing and event handling logic.
* @constructor
* Create a new Editor
* @param {Object} config The config object
* @xtype editor
*/
Ext.Editor = function (field, config) {
	if (field.field) {
		this.field = Ext.create(field.field, 'textfield');
		config = Ext.apply({}, field); // copy so we don't disturb original config
		delete config.field;
	} else {
		this.field = field;
	}
	Ext.Editor.superclass.constructor.call(this, config);
};

Ext.extend(Ext.Editor, Ext.Component, {
	/**
	* @cfg {Ext.form.Field} field
	* The Field object (or descendant) or config object for field
	*/
	/**
	* @cfg {Boolean} allowBlur
	* True to {@link #completeEdit complete the editing process} if in edit mode when the
	* field is blurred. Defaults to <tt>true</tt>.
	*/
	allowBlur: true,
	/**
	* @cfg {Boolean/String} autoSize
	* True for the editor to automatically adopt the size of the underlying field, "width" to adopt the width only,
	* or "height" to adopt the height only, "none" to always use the field dimensions. (defaults to false)
	*/
	/**
	* @cfg {Boolean} revertInvalid
	* True to automatically revert the field value and cancel the edit when the user completes an edit and the field
	* validation fails (defaults to true)
	*/
	/**
	* @cfg {Boolean} ignoreNoChange
	* True to skip the edit completion process (no save, no events fired) if the user completes an edit and
	* the value has not changed (defaults to false).  Applies only to string values - edits for other data types
	* will never be ignored.
	*/
	/**
	* @cfg {Boolean} hideEl
	* False to keep the bound element visible while the editor is displayed (defaults to true)
	*/
	/**
	* @cfg {Mixed} value
	* The data value of the underlying field (defaults to "")
	*/
	value: "",
	/**
	* @cfg {String} alignment
	* The position to align to (see {@link Ext.Element#alignTo} for more details, defaults to "c-c?").
	*/
	alignment: "c-c?",
	/**
	* @cfg {Array} offsets
	* The offsets to use when aligning (see {@link Ext.Element#alignTo} for more details. Defaults to <tt>[0, 0]</tt>.
	*/
	offsets: [0, 0],
	/**
	* @cfg {Boolean/String} shadow "sides" for sides/bottom only, "frame" for 4-way shadow, and "drop"
	* for bottom-right shadow (defaults to "frame")
	*/
	shadow: "frame",
	/**
	* @cfg {Boolean} constrain True to constrain the editor to the viewport
	*/
	constrain: false,
	/**
	* @cfg {Boolean} swallowKeys Handle the keydown/keypress events so they don't propagate (defaults to true)
	*/
	swallowKeys: true,
	/**
	* @cfg {Boolean} completeOnEnter True to complete the edit when the enter key is pressed. Defaults to <tt>true</tt>.
	*/
	completeOnEnter: true,
	/**
	* @cfg {Boolean} cancelOnEsc True to cancel the edit when the escape key is pressed. Defaults to <tt>true</tt>.
	*/
	cancelOnEsc: true,
	/**
	* @cfg {Boolean} updateEl True to update the innerHTML of the bound element when the update completes (defaults to false)
	*/
	updateEl: false,

	initComponent: function () {
		Ext.Editor.superclass.initComponent.call(this);
		this.addEvents(
		/**
		* @event beforestartedit
		* Fires when editing is initiated, but before the value changes.  Editing can be canceled by returning
		* false from the handler of this event.
		* @param {Editor} this
		* @param {Ext.Element} boundEl The underlying element bound to this editor
		* @param {Mixed} value The field value being set
		*/
            "beforestartedit",
		/**
		* @event startedit
		* Fires when this editor is displayed
		* @param {Ext.Element} boundEl The underlying element bound to this editor
		* @param {Mixed} value The starting field value
		*/
            "startedit",
		/**
		* @event beforecomplete
		* Fires after a change has been made to the field, but before the change is reflected in the underlying
		* field.  Saving the change to the field can be canceled by returning false from the handler of this event.
		* Note that if the value has not changed and ignoreNoChange = true, the editing will still end but this
		* event will not fire since no edit actually occurred.
		* @param {Editor} this
		* @param {Mixed} value The current field value
		* @param {Mixed} startValue The original field value
		*/
            "beforecomplete",
		/**
		* @event complete
		* Fires after editing is complete and any changed value has been written to the underlying field.
		* @param {Editor} this
		* @param {Mixed} value The current field value
		* @param {Mixed} startValue The original field value
		*/
            "complete",
		/**
		* @event canceledit
		* Fires after editing has been canceled and the editor's value has been reset.
		* @param {Editor} this
		* @param {Mixed} value The user-entered field value that was discarded
		* @param {Mixed} startValue The original field value that was set back into the editor after cancel
		*/
            "canceledit",
		/**
		* @event specialkey
		* Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed.  You can check
		* {@link Ext.EventObject#getKey} to determine which key was pressed.
		* @param {Ext.form.Field} this
		* @param {Ext.EventObject} e The event object
		*/
            "specialkey"
        );
	},

	// private
	onRender: function (ct, position) {
		this.el = new Ext.Layer({
			shadow: this.shadow,
			cls: "x-editor",
			parentEl: ct,
			shim: this.shim,
			shadowOffset: this.shadowOffset || 4,
			id: this.id,
			constrain: this.constrain
		});
		if (this.zIndex) {
			this.el.setZIndex(this.zIndex);
		}
		this.el.setStyle("overflow", Ext.isGecko ? "auto" : "hidden");
		if (this.field.msgTarget != 'title') {
			this.field.msgTarget = 'qtip';
		}
		this.field.inEditor = true;
		this.mon(this.field, {
			scope: this,
			blur: this.onBlur,
			specialkey: this.onSpecialKey
		});
		if (this.field.grow) {
			this.mon(this.field, "autosize", this.el.sync, this.el, { delay: 1 });
		}
		this.field.render(this.el).show();
		this.field.getEl().dom.name = '';
		if (this.swallowKeys) {
			this.field.el.swallowEvent([
                'keypress', // *** Opera
                'keydown'   // *** all other browsers
            ]);
		}
	},

	// private
	onSpecialKey: function (field, e) {
		var key = e.getKey(),
            complete = this.completeOnEnter && key == e.ENTER,
            cancel = this.cancelOnEsc && key == e.ESC;
		if (complete || cancel) {
			e.stopEvent();
			if (complete) {
				this.completeEdit();
			} else {
				this.cancelEdit();
			}
			if (field.triggerBlur) {
				field.triggerBlur();
			}
		}
		this.fireEvent('specialkey', field, e);
	},

	/**
	* Starts the editing process and shows the editor.
	* @param {Mixed} el The element to edit
	* @param {String} value (optional) A value to initialize the editor with. If a value is not provided, it defaults
	* to the innerHTML of el.
	*/
	startEdit: function (el, value) {
		if (this.editing) {
			this.completeEdit();
		}
		this.boundEl = Ext.get(el);
		var v = value !== undefined ? value : this.boundEl.dom.innerHTML;
		if (!this.rendered) {
			this.render(this.parentEl || document.body);
		}
		if (this.fireEvent("beforestartedit", this, this.boundEl, v) !== false) {
			this.startValue = v;
			this.field.reset();
			this.field.setValue(v);
			this.realign(true);
			this.editing = true;
			this.show();
		}
	},

	// private
	doAutoSize: function () {
		if (this.autoSize) {
			var sz = this.boundEl.getSize(),
                fs = this.field.getSize();

			switch (this.autoSize) {
				case "width":
					this.setSize(sz.width, fs.height);
					break;
				case "height":
					this.setSize(fs.width, sz.height);
					break;
				case "none":
					this.setSize(fs.width, fs.height);
					break;
				default:
					this.setSize(sz.width, sz.height);
			}
		}
	},

	/**
	* Sets the height and width of this editor.
	* @param {Number} width The new width
	* @param {Number} height The new height
	*/
	setSize: function (w, h) {
		delete this.field.lastSize;
		this.field.setSize(w, h);
		if (this.el) {
			if (Ext.isGecko2 || Ext.isOpera) {
				// prevent layer scrollbars
				this.el.setSize(w, h);
			}
			this.el.sync();
		}
	},

	/**
	* Realigns the editor to the bound field based on the current alignment config value.
	* @param {Boolean} autoSize (optional) True to size the field to the dimensions of the bound element.
	*/
	realign: function (autoSize) {
		if (autoSize === true) {
			this.doAutoSize();
		}
		this.el.alignTo(this.boundEl, this.alignment, this.offsets);
	},

	/**
	* Ends the editing process, persists the changed value to the underlying field, and hides the editor.
	* @param {Boolean} remainVisible Override the default behavior and keep the editor visible after edit (defaults to false)
	*/
	completeEdit: function (remainVisible) {
		if (!this.editing) {
			return;
		}
		// Assert combo values first
		if (this.field.assertValue) {
			this.field.assertValue();
		}
		var v = this.getValue();
		if (!this.field.isValid()) {
			if (this.revertInvalid !== false) {
				this.cancelEdit(remainVisible);
			}
			return;
		}
		if (String(v) === String(this.startValue) && this.ignoreNoChange) {
			this.hideEdit(remainVisible);
			return;
		}
		if (this.fireEvent("beforecomplete", this, v, this.startValue) !== false) {
			v = this.getValue();
			if (this.updateEl && this.boundEl) {
				this.boundEl.update(v);
			}
			this.hideEdit(remainVisible);
			this.fireEvent("complete", this, v, this.startValue);
		}
	},

	// private
	onShow: function () {
		this.el.show();
		if (this.hideEl !== false) {
			this.boundEl.hide();
		}
		this.field.show().focus(false, true);
		this.fireEvent("startedit", this.boundEl, this.startValue);
	},

	/**
	* Cancels the editing process and hides the editor without persisting any changes.  The field value will be
	* reverted to the original starting value.
	* @param {Boolean} remainVisible Override the default behavior and keep the editor visible after
	* cancel (defaults to false)
	*/
	cancelEdit: function (remainVisible) {
		if (this.editing) {
			var v = this.getValue();
			this.setValue(this.startValue);
			this.hideEdit(remainVisible);
			this.fireEvent("canceledit", this, v, this.startValue);
		}
	},

	// private
	hideEdit: function (remainVisible) {
		if (remainVisible !== true) {
			this.editing = false;
			this.hide();
		}
	},

	// private
	onBlur: function () {
		// selectSameEditor flag allows the same editor to be started without onBlur firing on itself
		if (this.allowBlur === true && this.editing && this.selectSameEditor !== true) {
			this.completeEdit();
		}
	},

	// private
	onHide: function () {
		if (this.editing) {
			this.completeEdit();
			return;
		}
		this.field.blur();
		if (this.field.collapse) {
			this.field.collapse();
		}
		this.el.hide();
		if (this.hideEl !== false) {
			this.boundEl.show();
		}
	},

	/**
	* Sets the data value of the editor
	* @param {Mixed} value Any valid value supported by the underlying field
	*/
	setValue: function (v) {
		this.field.setValue(v);
	},

	/**
	* Gets the data value of the editor
	* @return {Mixed} The data value
	*/
	getValue: function () {
		return this.field.getValue();
	},

	beforeDestroy: function () {
		Ext.destroyMembers(this, 'field');

		delete this.parentEl;
		delete this.boundEl;
	}
});
Ext.reg('editor', Ext.Editor);
/**
* @class Ext.ColorPalette
* @extends Ext.Component
* Simple color palette class for choosing colors.  The palette can be rendered to any container.<br />
* Here's an example of typical usage:
* <pre><code>
var cp = new Ext.ColorPalette({value:'993300'});  // initial selected color
cp.render('my-div');

cp.on('select', function(palette, selColor){
// do something with selColor
});
</code></pre>
* @constructor
* Create a new ColorPalette
* @param {Object} config The config object
* @xtype colorpalette
*/
Ext.ColorPalette = Ext.extend(Ext.Component, {
	/**
	* @cfg {String} tpl An existing XTemplate instance to be used in place of the default template for rendering the component.
	*/
	/**
	* @cfg {String} itemCls
	* The CSS class to apply to the containing element (defaults to 'x-color-palette')
	*/
	itemCls: 'x-color-palette',
	/**
	* @cfg {String} value
	* The initial color to highlight (should be a valid 6-digit color hex code without the # symbol).  Note that
	* the hex codes are case-sensitive.
	*/
	value: null,
	/**
	* @cfg {String} clickEvent
	* The DOM event that will cause a color to be selected. This can be any valid event name (dblclick, contextmenu). 
	* Defaults to <tt>'click'</tt>.
	*/
	clickEvent: 'click',
	// private
	ctype: 'Ext.ColorPalette',

	/**
	* @cfg {Boolean} allowReselect If set to true then reselecting a color that is already selected fires the {@link #select} event
	*/
	allowReselect: false,

	/**
	* <p>An array of 6-digit color hex code strings (without the # symbol).  This array can contain any number
	* of colors, and each hex code should be unique.  The width of the palette is controlled via CSS by adjusting
	* the width property of the 'x-color-palette' class (or assigning a custom class), so you can balance the number
	* of colors with the width setting until the box is symmetrical.</p>
	* <p>You can override individual colors if needed:</p>
	* <pre><code>
	var cp = new Ext.ColorPalette();
	cp.colors[0] = 'FF0000';  // change the first box to red
	</code></pre>

	Or you can provide a custom array of your own for complete control:
	<pre><code>
	var cp = new Ext.ColorPalette();
	cp.colors = ['000000', '993300', '333300'];
	</code></pre>
	* @type Array
	*/
	colors: [
        '000000', '993300', '333300', '003300', '003366', '000080', '333399', '333333',
        '800000', 'FF6600', '808000', '008000', '008080', '0000FF', '666699', '808080',
        'FF0000', 'FF9900', '99CC00', '339966', '33CCCC', '3366FF', '800080', '969696',
        'FF00FF', 'FFCC00', 'FFFF00', '00FF00', '00FFFF', '00CCFF', '993366', 'C0C0C0',
        'FF99CC', 'FFCC99', 'FFFF99', 'CCFFCC', 'CCFFFF', '99CCFF', 'CC99FF', 'FFFFFF'
    ],

	/**
	* @cfg {Function} handler
	* Optional. A function that will handle the select event of this palette.
	* The handler is passed the following parameters:<div class="mdetail-params"><ul>
	* <li><code>palette</code> : ColorPalette<div class="sub-desc">The {@link #palette Ext.ColorPalette}.</div></li>
	* <li><code>color</code> : String<div class="sub-desc">The 6-digit color hex code (without the # symbol).</div></li>
	* </ul></div>
	*/
	/**
	* @cfg {Object} scope
	* The scope (<tt><b>this</b></tt> reference) in which the <code>{@link #handler}</code>
	* function will be called.  Defaults to this ColorPalette instance.
	*/

	// private
	initComponent: function () {
		Ext.ColorPalette.superclass.initComponent.call(this);
		this.addEvents(
		/**
		* @event select
		* Fires when a color is selected
		* @param {ColorPalette} this
		* @param {String} color The 6-digit color hex code (without the # symbol)
		*/
            'select'
        );

		if (this.handler) {
			this.on('select', this.handler, this.scope, true);
		}
	},

	// private
	onRender: function (container, position) {
		this.autoEl = {
			tag: 'div',
			cls: this.itemCls
		};
		Ext.ColorPalette.superclass.onRender.call(this, container, position);
		var t = this.tpl || new Ext.XTemplate(
            '<tpl for="."><a href="#" class="color-{.}" hidefocus="on"><em><span style="background:#{.}" unselectable="on">&#160;</span></em></a></tpl>'
        );
		t.overwrite(this.el, this.colors);
		this.mon(this.el, this.clickEvent, this.handleClick, this, { delegate: 'a' });
		if (this.clickEvent != 'click') {
			this.mon(this.el, 'click', Ext.emptyFn, this, { delegate: 'a', preventDefault: true });
		}
	},

	// private
	afterRender: function () {
		Ext.ColorPalette.superclass.afterRender.call(this);
		if (this.value) {
			var s = this.value;
			this.value = null;
			this.select(s, true);
		}
	},

	// private
	handleClick: function (e, t) {
		e.preventDefault();
		if (!this.disabled) {
			var c = t.className.match(/(?:^|\s)color-(.{6})(?:\s|$)/)[1];
			this.select(c.toUpperCase());
		}
	},

	/**
	* Selects the specified color in the palette (fires the {@link #select} event)
	* @param {String} color A valid 6-digit color hex code (# will be stripped if included)
	* @param {Boolean} suppressEvent (optional) True to stop the select event from firing. Defaults to <tt>false</tt>.
	*/
	select: function (color, suppressEvent) {
		color = color.replace('#', '');
		if (color != this.value || this.allowReselect) {
			var el = this.el;
			if (this.value) {
				el.child('a.color-' + this.value).removeClass('x-color-palette-sel');
			}
			el.child('a.color-' + color).addClass('x-color-palette-sel');
			this.value = color;
			if (suppressEvent !== true) {
				this.fireEvent('select', this, color);
			}
		}
	}

	/**
	* @cfg {String} autoEl @hide
	*/
});
Ext.reg('colorpalette', Ext.ColorPalette); /**
 * @class Ext.DatePicker
 * @extends Ext.Component
 * <p>A popup date picker. This class is used by the {@link Ext.form.DateField DateField} class
 * to allow browsing and selection of valid dates.</p>
 * <p>All the string values documented below may be overridden by including an Ext locale file in
 * your page.</p>
 * @constructor
 * Create a new DatePicker
 * @param {Object} config The config object
 * @xtype datepicker
 */
Ext.DatePicker = Ext.extend(Ext.BoxComponent, {
	/**
	* @cfg {String} todayText
	* The text to display on the button that selects the current date (defaults to <code>'Today'</code>)
	*/
	todayText: 'Today',
	/**
	* @cfg {String} okText
	* The text to display on the ok button (defaults to <code>'&#160;OK&#160;'</code> to give the user extra clicking room)
	*/
	okText: '&#160;OK&#160;',
	/**
	* @cfg {String} cancelText
	* The text to display on the cancel button (defaults to <code>'Cancel'</code>)
	*/
	cancelText: 'Cancel',
	/**
	* @cfg {Function} handler
	* Optional. A function that will handle the select event of this picker.
	* The handler is passed the following parameters:<div class="mdetail-params"><ul>
	* <li><code>picker</code> : DatePicker<div class="sub-desc">This DatePicker.</div></li>
	* <li><code>date</code> : Date<div class="sub-desc">The selected date.</div></li>
	* </ul></div>
	*/
	/**
	* @cfg {Object} scope
	* The scope (<code><b>this</b></code> reference) in which the <code>{@link #handler}</code>
	* function will be called.  Defaults to this DatePicker instance.
	*/
	/**
	* @cfg {String} todayTip
	* A string used to format the message for displaying in a tooltip over the button that
	* selects the current date. Defaults to <code>'{0} (Spacebar)'</code> where
	* the <code>{0}</code> token is replaced by today's date.
	*/
	todayTip: '{0} (Spacebar)',
	/**
	* @cfg {String} minText
	* The error text to display if the minDate validation fails (defaults to <code>'This date is before the minimum date'</code>)
	*/
	minText: 'This date is before the minimum date',
	/**
	* @cfg {String} maxText
	* The error text to display if the maxDate validation fails (defaults to <code>'This date is after the maximum date'</code>)
	*/
	maxText: 'This date is after the maximum date',
	/**
	* @cfg {String} format
	* The default date format string which can be overriden for localization support.  The format must be
	* valid according to {@link Date#parseDate} (defaults to <code>'m/d/y'</code>).
	*/
	format: 'm/d/y',
	/**
	* @cfg {String} disabledDaysText
	* The tooltip to display when the date falls on a disabled day (defaults to <code>'Disabled'</code>)
	*/
	disabledDaysText: 'Disabled',
	/**
	* @cfg {String} disabledDatesText
	* The tooltip text to display when the date falls on a disabled date (defaults to <code>'Disabled'</code>)
	*/
	disabledDatesText: 'Disabled',
	/**
	* @cfg {Array} monthNames
	* An array of textual month names which can be overriden for localization support (defaults to Date.monthNames)
	*/
	monthNames: Date.monthNames,
	/**
	* @cfg {Array} dayNames
	* An array of textual day names which can be overriden for localization support (defaults to Date.dayNames)
	*/
	dayNames: Date.dayNames,
	/**
	* @cfg {String} nextText
	* The next month navigation button tooltip (defaults to <code>'Next Month (Control+Right)'</code>)
	*/
	nextText: 'Next Month (Control+Right)',
	/**
	* @cfg {String} prevText
	* The previous month navigation button tooltip (defaults to <code>'Previous Month (Control+Left)'</code>)
	*/
	prevText: 'Previous Month (Control+Left)',
	/**
	* @cfg {String} monthYearText
	* The header month selector tooltip (defaults to <code>'Choose a month (Control+Up/Down to move years)'</code>)
	*/
	monthYearText: 'Choose a month (Control+Up/Down to move years)',
	/**
	* @cfg {Number} startDay
	* Day index at which the week should begin, 0-based (defaults to 0, which is Sunday)
	*/
	startDay: 0,
	/**
	* @cfg {Boolean} showToday
	* False to hide the footer area containing the Today button and disable the keyboard handler for spacebar
	* that selects the current date (defaults to <code>true</code>).
	*/
	showToday: true,
	/**
	* @cfg {Date} minDate
	* Minimum allowable date (JavaScript date object, defaults to null)
	*/
	/**
	* @cfg {Date} maxDate
	* Maximum allowable date (JavaScript date object, defaults to null)
	*/
	/**
	* @cfg {Array} disabledDays
	* An array of days to disable, 0-based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
	*/
	/**
	* @cfg {RegExp} disabledDatesRE
	* JavaScript regular expression used to disable a pattern of dates (defaults to null).  The {@link #disabledDates}
	* config will generate this regex internally, but if you specify disabledDatesRE it will take precedence over the
	* disabledDates value.
	*/
	/**
	* @cfg {Array} disabledDates
	* An array of 'dates' to disable, as strings. These strings will be used to build a dynamic regular
	* expression so they are very powerful. Some examples:
	* <ul>
	* <li>['03/08/2003', '09/16/2003'] would disable those exact dates</li>
	* <li>['03/08', '09/16'] would disable those days for every year</li>
	* <li>['^03/08'] would only match the beginning (useful if you are using short years)</li>
	* <li>['03/../2006'] would disable every day in March 2006</li>
	* <li>['^03'] would disable every day in every March</li>
	* </ul>
	* Note that the format of the dates included in the array should exactly match the {@link #format} config.
	* In order to support regular expressions, if you are using a date format that has '.' in it, you will have to
	* escape the dot when restricting dates. For example: ['03\\.08\\.03'].
	*/

	// private
	// Set by other components to stop the picker focus being updated when the value changes.
	focusOnSelect: true,

	// default value used to initialise each date in the DatePicker
	// (note: 12 noon was chosen because it steers well clear of all DST timezone changes)
	initHour: 12, // 24-hour format

	// private
	initComponent: function () {
		Ext.DatePicker.superclass.initComponent.call(this);

		this.value = this.value ?
                 this.value.clearTime(true) : new Date().clearTime();

		this.addEvents(
		/**
		* @event select
		* Fires when a date is selected
		* @param {DatePicker} this DatePicker
		* @param {Date} date The selected date
		*/
            'select'
        );

		if (this.handler) {
			this.on('select', this.handler, this.scope || this);
		}

		this.initDisabledDays();
	},

	// private
	initDisabledDays: function () {
		if (!this.disabledDatesRE && this.disabledDates) {
			var dd = this.disabledDates,
                len = dd.length - 1,
                re = '(?:';

			Ext.each(dd, function (d, i) {
				re += Ext.isDate(d) ? '^' + Ext.escapeRe(d.dateFormat(this.format)) + '$' : dd[i];
				if (i != len) {
					re += '|';
				}
			}, this);
			this.disabledDatesRE = new RegExp(re + ')');
		}
	},

	/**
	* Replaces any existing disabled dates with new values and refreshes the DatePicker.
	* @param {Array/RegExp} disabledDates An array of date strings (see the {@link #disabledDates} config
	* for details on supported values), or a JavaScript regular expression used to disable a pattern of dates.
	*/
	setDisabledDates: function (dd) {
		if (Ext.isArray(dd)) {
			this.disabledDates = dd;
			this.disabledDatesRE = null;
		} else {
			this.disabledDatesRE = dd;
		}
		this.initDisabledDays();
		this.update(this.value, true);
	},

	/**
	* Replaces any existing disabled days (by index, 0-6) with new values and refreshes the DatePicker.
	* @param {Array} disabledDays An array of disabled day indexes. See the {@link #disabledDays} config
	* for details on supported values.
	*/
	setDisabledDays: function (dd) {
		this.disabledDays = dd;
		this.update(this.value, true);
	},

	/**
	* Replaces any existing {@link #minDate} with the new value and refreshes the DatePicker.
	* @param {Date} value The minimum date that can be selected
	*/
	setMinDate: function (dt) {
		this.minDate = dt;
		this.update(this.value, true);
	},

	/**
	* Replaces any existing {@link #maxDate} with the new value and refreshes the DatePicker.
	* @param {Date} value The maximum date that can be selected
	*/
	setMaxDate: function (dt) {
		this.maxDate = dt;
		this.update(this.value, true);
	},

	/**
	* Sets the value of the date field
	* @param {Date} value The date to set
	*/
	setValue: function (value) {
		this.value = value.clearTime(true);
		this.update(this.value);
	},

	/**
	* Gets the current selected value of the date field
	* @return {Date} The selected date
	*/
	getValue: function () {
		return this.value;
	},

	// private
	focus: function () {
		this.update(this.activeDate);
	},

	// private
	onEnable: function (initial) {
		Ext.DatePicker.superclass.onEnable.call(this);
		this.doDisabled(false);
		this.update(initial ? this.value : this.activeDate);
		if (Ext.isIE) {
			this.el.repaint();
		}

	},

	// private
	onDisable: function () {
		Ext.DatePicker.superclass.onDisable.call(this);
		this.doDisabled(true);
		if (Ext.isIE && !Ext.isIE8) {
			/* Really strange problem in IE6/7, when disabled, have to explicitly
			* repaint each of the nodes to get them to display correctly, simply
			* calling repaint on the main element doesn't appear to be enough.
			*/
			Ext.each([].concat(this.textNodes, this.el.query('th span')), function (el) {
				Ext.fly(el).repaint();
			});
		}
	},

	// private
	doDisabled: function (disabled) {
		this.keyNav.setDisabled(disabled);
		this.prevRepeater.setDisabled(disabled);
		this.nextRepeater.setDisabled(disabled);
		if (this.showToday) {
			this.todayKeyListener.setDisabled(disabled);
			this.todayBtn.setDisabled(disabled);
		}
	},

	// private
	onRender: function (container, position) {
		var m = [
             '<table cellspacing="0">',
                '<tr><td class="x-date-left"><a href="#" title="', this.prevText, '">&#160;</a></td><td class="x-date-middle" align="center"></td><td class="x-date-right"><a href="#" title="', this.nextText, '">&#160;</a></td></tr>',
                '<tr><td colspan="3"><table class="x-date-inner" cellspacing="0"><thead><tr>'],
                dn = this.dayNames,
                i;
		for (i = 0; i < 7; i++) {
			var d = this.startDay + i;
			if (d > 6) {
				d = d - 7;
			}
			m.push('<th><span>', dn[d].substr(0, 1), '</span></th>');
		}
		m[m.length] = '</tr></thead><tbody><tr>';
		for (i = 0; i < 42; i++) {
			if (i % 7 === 0 && i !== 0) {
				m[m.length] = '</tr><tr>';
			}
			m[m.length] = '<td><a href="#" hidefocus="on" class="x-date-date" tabIndex="1"><em><span></span></em></a></td>';
		}
		m.push('</tr></tbody></table></td></tr>',
                this.showToday ? '<tr><td colspan="3" class="x-date-bottom" align="center"></td></tr>' : '',
                '</table><div class="x-date-mp"></div>');

		var el = document.createElement('div');
		el.className = 'x-date-picker';
		el.innerHTML = m.join('');

		container.dom.insertBefore(el, position);

		this.el = Ext.get(el);
		this.eventEl = Ext.get(el.firstChild);

		this.prevRepeater = new Ext.util.ClickRepeater(this.el.child('td.x-date-left a'), {
			handler: this.showPrevMonth,
			scope: this,
			preventDefault: true,
			stopDefault: true
		});

		this.nextRepeater = new Ext.util.ClickRepeater(this.el.child('td.x-date-right a'), {
			handler: this.showNextMonth,
			scope: this,
			preventDefault: true,
			stopDefault: true
		});

		this.monthPicker = this.el.down('div.x-date-mp');
		this.monthPicker.enableDisplayMode('block');

		this.keyNav = new Ext.KeyNav(this.eventEl, {
			'left': function (e) {
				if (e.ctrlKey) {
					this.showPrevMonth();
				} else {
					this.update(this.activeDate.add('d', -1));
				}
			},

			'right': function (e) {
				if (e.ctrlKey) {
					this.showNextMonth();
				} else {
					this.update(this.activeDate.add('d', 1));
				}
			},

			'up': function (e) {
				if (e.ctrlKey) {
					this.showNextYear();
				} else {
					this.update(this.activeDate.add('d', -7));
				}
			},

			'down': function (e) {
				if (e.ctrlKey) {
					this.showPrevYear();
				} else {
					this.update(this.activeDate.add('d', 7));
				}
			},

			'pageUp': function (e) {
				this.showNextMonth();
			},

			'pageDown': function (e) {
				this.showPrevMonth();
			},

			'enter': function (e) {
				e.stopPropagation();
				return true;
			},

			scope: this
		});

		this.el.unselectable();

		this.cells = this.el.select('table.x-date-inner tbody td');
		this.textNodes = this.el.query('table.x-date-inner tbody span');

		this.mbtn = new Ext.Button({
			text: '&#160;',
			tooltip: this.monthYearText,
			renderTo: this.el.child('td.x-date-middle', true)
		});
		this.mbtn.el.child('em').addClass('x-btn-arrow');

		if (this.showToday) {
			this.todayKeyListener = this.eventEl.addKeyListener(Ext.EventObject.SPACE, this.selectToday, this);
			var today = (new Date()).dateFormat(this.format);
			this.todayBtn = new Ext.Button({
				renderTo: this.el.child('td.x-date-bottom', true),
				text: String.format(this.todayText, today),
				tooltip: String.format(this.todayTip, today),
				handler: this.selectToday,
				scope: this
			});
		}
		this.mon(this.eventEl, 'mousewheel', this.handleMouseWheel, this);
		this.mon(this.eventEl, 'click', this.handleDateClick, this, { delegate: 'a.x-date-date' });
		this.mon(this.mbtn, 'click', this.showMonthPicker, this);
		this.onEnable(true);
	},

	// private
	createMonthPicker: function () {
		if (!this.monthPicker.dom.firstChild) {
			var buf = ['<table border="0" cellspacing="0">'];
			for (var i = 0; i < 6; i++) {
				buf.push(
                    '<tr><td class="x-date-mp-month"><a href="#">', Date.getShortMonthName(i), '</a></td>',
                    '<td class="x-date-mp-month x-date-mp-sep"><a href="#">', Date.getShortMonthName(i + 6), '</a></td>',
                    i === 0 ?
                    '<td class="x-date-mp-ybtn" align="center"><a class="x-date-mp-prev"></a></td><td class="x-date-mp-ybtn" align="center"><a class="x-date-mp-next"></a></td></tr>' :
                    '<td class="x-date-mp-year"><a href="#"></a></td><td class="x-date-mp-year"><a href="#"></a></td></tr>'
                );
			}
			buf.push(
                '<tr class="x-date-mp-btns"><td colspan="4"><button type="button" class="x-date-mp-ok">',
                    this.okText,
                    '</button><button type="button" class="x-date-mp-cancel">',
                    this.cancelText,
                    '</button></td></tr>',
                '</table>'
            );
			this.monthPicker.update(buf.join(''));

			this.mon(this.monthPicker, 'click', this.onMonthClick, this);
			this.mon(this.monthPicker, 'dblclick', this.onMonthDblClick, this);

			this.mpMonths = this.monthPicker.select('td.x-date-mp-month');
			this.mpYears = this.monthPicker.select('td.x-date-mp-year');

			this.mpMonths.each(function (m, a, i) {
				i += 1;
				if ((i % 2) === 0) {
					m.dom.xmonth = 5 + Math.round(i * 0.5);
				} else {
					m.dom.xmonth = Math.round((i - 1) * 0.5);
				}
			});
		}
	},

	// private
	showMonthPicker: function () {
		if (!this.disabled) {
			this.createMonthPicker();
			var size = this.el.getSize();
			this.monthPicker.setSize(size);
			this.monthPicker.child('table').setSize(size);

			this.mpSelMonth = (this.activeDate || this.value).getMonth();
			this.updateMPMonth(this.mpSelMonth);
			this.mpSelYear = (this.activeDate || this.value).getFullYear();
			this.updateMPYear(this.mpSelYear);

			this.monthPicker.slideIn('t', { duration: 0.2 });
		}
	},

	// private
	updateMPYear: function (y) {
		this.mpyear = y;
		var ys = this.mpYears.elements;
		for (var i = 1; i <= 10; i++) {
			var td = ys[i - 1], y2;
			if ((i % 2) === 0) {
				y2 = y + Math.round(i * 0.5);
				td.firstChild.innerHTML = y2;
				td.xyear = y2;
			} else {
				y2 = y - (5 - Math.round(i * 0.5));
				td.firstChild.innerHTML = y2;
				td.xyear = y2;
			}
			this.mpYears.item(i - 1)[y2 == this.mpSelYear ? 'addClass' : 'removeClass']('x-date-mp-sel');
		}
	},

	// private
	updateMPMonth: function (sm) {
		this.mpMonths.each(function (m, a, i) {
			m[m.dom.xmonth == sm ? 'addClass' : 'removeClass']('x-date-mp-sel');
		});
	},

	// private
	selectMPMonth: function (m) {

	},

	// private
	onMonthClick: function (e, t) {
		e.stopEvent();
		var el = new Ext.Element(t), pn;
		if (el.is('button.x-date-mp-cancel')) {
			this.hideMonthPicker();
		}
		else if (el.is('button.x-date-mp-ok')) {
			var d = new Date(this.mpSelYear, this.mpSelMonth, (this.activeDate || this.value).getDate());
			if (d.getMonth() != this.mpSelMonth) {
				// 'fix' the JS rolling date conversion if needed
				d = new Date(this.mpSelYear, this.mpSelMonth, 1).getLastDateOfMonth();
			}
			this.update(d);
			this.hideMonthPicker();
		}
		else if ((pn = el.up('td.x-date-mp-month', 2))) {
			this.mpMonths.removeClass('x-date-mp-sel');
			pn.addClass('x-date-mp-sel');
			this.mpSelMonth = pn.dom.xmonth;
		}
		else if ((pn = el.up('td.x-date-mp-year', 2))) {
			this.mpYears.removeClass('x-date-mp-sel');
			pn.addClass('x-date-mp-sel');
			this.mpSelYear = pn.dom.xyear;
		}
		else if (el.is('a.x-date-mp-prev')) {
			this.updateMPYear(this.mpyear - 10);
		}
		else if (el.is('a.x-date-mp-next')) {
			this.updateMPYear(this.mpyear + 10);
		}
	},

	// private
	onMonthDblClick: function (e, t) {
		e.stopEvent();
		var el = new Ext.Element(t), pn;
		if ((pn = el.up('td.x-date-mp-month', 2))) {
			this.update(new Date(this.mpSelYear, pn.dom.xmonth, (this.activeDate || this.value).getDate()));
			this.hideMonthPicker();
		}
		else if ((pn = el.up('td.x-date-mp-year', 2))) {
			this.update(new Date(pn.dom.xyear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
			this.hideMonthPicker();
		}
	},

	// private
	hideMonthPicker: function (disableAnim) {
		if (this.monthPicker) {
			if (disableAnim === true) {
				this.monthPicker.hide();
			} else {
				this.monthPicker.slideOut('t', { duration: 0.2 });
			}
		}
	},

	// private
	showPrevMonth: function (e) {
		this.update(this.activeDate.add('mo', -1));
	},

	// private
	showNextMonth: function (e) {
		this.update(this.activeDate.add('mo', 1));
	},

	// private
	showPrevYear: function () {
		this.update(this.activeDate.add('y', -1));
	},

	// private
	showNextYear: function () {
		this.update(this.activeDate.add('y', 1));
	},

	// private
	handleMouseWheel: function (e) {
		e.stopEvent();
		if (!this.disabled) {
			var delta = e.getWheelDelta();
			if (delta > 0) {
				this.showPrevMonth();
			} else if (delta < 0) {
				this.showNextMonth();
			}
		}
	},

	// private
	handleDateClick: function (e, t) {
		e.stopEvent();
		if (!this.disabled && t.dateValue && !Ext.fly(t.parentNode).hasClass('x-date-disabled')) {
			this.cancelFocus = this.focusOnSelect === false;
			this.setValue(new Date(t.dateValue));
			delete this.cancelFocus;
			this.fireEvent('select', this, this.value);
		}
	},

	// private
	selectToday: function () {
		if (this.todayBtn && !this.todayBtn.disabled) {
			this.setValue(new Date().clearTime());
			this.fireEvent('select', this, this.value);
		}
	},

	// private
	update: function (date, forceRefresh) {
		if (this.rendered) {
			var vd = this.activeDate, vis = this.isVisible();
			this.activeDate = date;
			if (!forceRefresh && vd && this.el) {
				var t = date.getTime();
				if (vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()) {
					this.cells.removeClass('x-date-selected');
					this.cells.each(function (c) {
						if (c.dom.firstChild.dateValue == t) {
							c.addClass('x-date-selected');
							if (vis && !this.cancelFocus) {
								Ext.fly(c.dom.firstChild).focus(50);
							}
							return false;
						}
					}, this);
					return;
				}
			}
			var days = date.getDaysInMonth(),
                firstOfMonth = date.getFirstDateOfMonth(),
                startingPos = firstOfMonth.getDay() - this.startDay;

			if (startingPos < 0) {
				startingPos += 7;
			}
			days += startingPos;

			var pm = date.add('mo', -1),
                prevStart = pm.getDaysInMonth() - startingPos,
                cells = this.cells.elements,
                textEls = this.textNodes,
			// convert everything to numbers so it's fast
                d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart, this.initHour)),
                today = new Date().clearTime().getTime(),
                sel = date.clearTime(true).getTime(),
                min = this.minDate ? this.minDate.clearTime(true) : Number.NEGATIVE_INFINITY,
                max = this.maxDate ? this.maxDate.clearTime(true) : Number.POSITIVE_INFINITY,
                ddMatch = this.disabledDatesRE,
                ddText = this.disabledDatesText,
                ddays = this.disabledDays ? this.disabledDays.join('') : false,
                ddaysText = this.disabledDaysText,
                format = this.format;

			if (this.showToday) {
				var td = new Date().clearTime(),
                    disable = (td < min || td > max ||
                    (ddMatch && format && ddMatch.test(td.dateFormat(format))) ||
                    (ddays && ddays.indexOf(td.getDay()) != -1));

				if (!this.disabled) {
					this.todayBtn.setDisabled(disable);
					this.todayKeyListener[disable ? 'disable' : 'enable']();
				}
			}

			var setCellClass = function (cal, cell) {
				cell.title = '';
				var t = d.clearTime(true).getTime();
				cell.firstChild.dateValue = t;
				if (t == today) {
					cell.className += ' x-date-today';
					cell.title = cal.todayText;
				}
				if (t == sel) {
					cell.className += ' x-date-selected';
					if (vis) {
						Ext.fly(cell.firstChild).focus(50);
					}
				}
				// disabling
				if (t < min) {
					cell.className = ' x-date-disabled';
					cell.title = cal.minText;
					return;
				}
				if (t > max) {
					cell.className = ' x-date-disabled';
					cell.title = cal.maxText;
					return;
				}
				if (ddays) {
					if (ddays.indexOf(d.getDay()) != -1) {
						cell.title = ddaysText;
						cell.className = ' x-date-disabled';
					}
				}
				if (ddMatch && format) {
					var fvalue = d.dateFormat(format);
					if (ddMatch.test(fvalue)) {
						cell.title = ddText.replace('%0', fvalue);
						cell.className = ' x-date-disabled';
					}
				}
			};

			var i = 0;
			for (; i < startingPos; i++) {
				textEls[i].innerHTML = (++prevStart);
				d.setDate(d.getDate() + 1);
				cells[i].className = 'x-date-prevday';
				setCellClass(this, cells[i]);
			}
			for (; i < days; i++) {
				var intDay = i - startingPos + 1;
				textEls[i].innerHTML = (intDay);
				d.setDate(d.getDate() + 1);
				cells[i].className = 'x-date-active';
				setCellClass(this, cells[i]);
			}
			var extraDays = 0;
			for (; i < 42; i++) {
				textEls[i].innerHTML = (++extraDays);
				d.setDate(d.getDate() + 1);
				cells[i].className = 'x-date-nextday';
				setCellClass(this, cells[i]);
			}

			this.mbtn.setText(this.monthNames[date.getMonth()] + ' ' + date.getFullYear());

			if (!this.internalRender) {
				var main = this.el.dom.firstChild,
                    w = main.offsetWidth;
				this.el.setWidth(w + this.el.getBorderWidth('lr'));
				Ext.fly(main).setWidth(w);
				this.internalRender = true;
				// opera does not respect the auto grow header center column
				// then, after it gets a width opera refuses to recalculate
				// without a second pass
				if (Ext.isOpera && !this.secondPass) {
					main.rows[0].cells[1].style.width = (w - (main.rows[0].cells[0].offsetWidth + main.rows[0].cells[2].offsetWidth)) + 'px';
					this.secondPass = true;
					this.update.defer(10, this, [date]);
				}
			}
		}
	},

	// private
	beforeDestroy: function () {
		if (this.rendered) {
			Ext.destroy(
                this.keyNav,
                this.monthPicker,
                this.eventEl,
                this.mbtn,
                this.nextRepeater,
                this.prevRepeater,
                this.cells.el,
                this.todayBtn
            );
			delete this.textNodes;
			delete this.cells.elements;
		}
	}

	/**
	* @cfg {String} autoEl @hide
	*/
});

Ext.reg('datepicker', Ext.DatePicker);
/**
* @class Ext.LoadMask
* A simple utility class for generically masking elements while loading data.  If the {@link #store}
* config option is specified, the masking will be automatically synchronized with the store's loading
* process and the mask element will be cached for reuse.  For all other elements, this mask will replace the
* element's Updater load indicator and will be destroyed after the initial load.
* <p>Example usage:</p>
*<pre><code>
// Basic mask:
var myMask = new Ext.LoadMask(Ext.getBody(), {msg:"Please wait..."});
myMask.show();
</code></pre>
* @constructor
* Create a new LoadMask
* @param {Mixed} el The element or DOM node, or its id
* @param {Object} config The config object
*/
Ext.LoadMask = function (el, config) {
	this.el = Ext.get(el);
	Ext.apply(this, config);
	if (this.store) {
		this.store.on({
			scope: this,
			beforeload: this.onBeforeLoad,
			load: this.onLoad,
			exception: this.onLoad
		});
		this.removeMask = Ext.value(this.removeMask, false);
	} else {
		var um = this.el.getUpdater();
		um.showLoadIndicator = false; // disable the default indicator
		um.on({
			scope: this,
			beforeupdate: this.onBeforeLoad,
			update: this.onLoad,
			failure: this.onLoad
		});
		this.removeMask = Ext.value(this.removeMask, true);
	}
};

Ext.LoadMask.prototype = {
	/**
	* @cfg {Ext.data.Store} store
	* Optional Store to which the mask is bound. The mask is displayed when a load request is issued, and
	* hidden on either load sucess, or load fail.
	*/
	/**
	* @cfg {Boolean} removeMask
	* True to create a single-use mask that is automatically destroyed after loading (useful for page loads),
	* False to persist the mask element reference for multiple uses (e.g., for paged data widgets).  Defaults to false.
	*/
	/**
	* @cfg {String} msg
	* The text to display in a centered loading message box (defaults to 'Loading...')
	*/
	msg: 'Loading...',
	/**
	* @cfg {String} msgCls
	* The CSS class to apply to the loading message element (defaults to "x-mask-loading")
	*/
	msgCls: 'x-mask-loading',

	/**
	* Read-only. True if the mask is currently disabled so that it will not be displayed (defaults to false)
	* @type Boolean
	*/
	disabled: false,

	/**
	* Disables the mask to prevent it from being displayed
	*/
	disable: function () {
		this.disabled = true;
	},

	/**
	* Enables the mask so that it can be displayed
	*/
	enable: function () {
		this.disabled = false;
	},

	// private
	onLoad: function () {
		this.el.unmask(this.removeMask);
	},

	// private
	onBeforeLoad: function () {
		if (!this.disabled) {
			this.el.mask(this.msg, this.msgCls);
		}
	},

	/**
	* Show this LoadMask over the configured Element.
	*/
	show: function () {
		this.onBeforeLoad();
	},

	/**
	* Hide this LoadMask.
	*/
	hide: function () {
		this.onLoad();
	},

	// private
	destroy: function () {
		if (this.store) {
			this.store.un('beforeload', this.onBeforeLoad, this);
			this.store.un('load', this.onLoad, this);
			this.store.un('exception', this.onLoad, this);
		} else {
			var um = this.el.getUpdater();
			um.un('beforeupdate', this.onBeforeLoad, this);
			um.un('update', this.onLoad, this);
			um.un('failure', this.onLoad, this);
		}
	}
}; Ext.ns('Ext.slider');

/**
* @class Ext.slider.Thumb
* @extends Object
* Represents a single thumb element on a Slider. This would not usually be created manually and would instead
* be created internally by an {@link Ext.slider.MultiSlider Ext.Slider}.
*/
Ext.slider.Thumb = Ext.extend(Object, {

	/**
	* @constructor
	* @cfg {Ext.slider.MultiSlider} slider The Slider to render to (required)
	*/
	constructor: function (config) {
		/**
		* @property slider
		* @type Ext.slider.MultiSlider
		* The slider this thumb is contained within
		*/
		Ext.apply(this, config || {}, {
			cls: 'x-slider-thumb',

			/**
			* @cfg {Boolean} constrain True to constrain the thumb so that it cannot overlap its siblings
			*/
			constrain: false
		});

		Ext.slider.Thumb.superclass.constructor.call(this, config);

		if (this.slider.vertical) {
			Ext.apply(this, Ext.slider.Thumb.Vertical);
		}
	},

	/**
	* Renders the thumb into a slider
	*/
	render: function () {
		this.el = this.slider.innerEl.insertFirst({ cls: this.cls });

		this.initEvents();
	},

	/**
	* Enables the thumb if it is currently disabled
	*/
	enable: function () {
		this.disabled = false;
		this.el.removeClass(this.slider.disabledClass);
	},

	/**
	* Disables the thumb if it is currently enabled
	*/
	disable: function () {
		this.disabled = true;
		this.el.addClass(this.slider.disabledClass);
	},

	/**
	* Sets up an Ext.dd.DragTracker for this thumb
	*/
	initEvents: function () {
		var el = this.el;

		el.addClassOnOver('x-slider-thumb-over');

		this.tracker = new Ext.dd.DragTracker({
			onBeforeStart: this.onBeforeDragStart.createDelegate(this),
			onStart: this.onDragStart.createDelegate(this),
			onDrag: this.onDrag.createDelegate(this),
			onEnd: this.onDragEnd.createDelegate(this),
			tolerance: 3,
			autoStart: 300
		});

		this.tracker.initEl(el);
	},

	/**
	* @private
	* This is tied into the internal Ext.dd.DragTracker. If the slider is currently disabled,
	* this returns false to disable the DragTracker too.
	* @return {Boolean} False if the slider is currently disabled
	*/
	onBeforeDragStart: function (e) {
		if (this.disabled) {
			return false;
		} else {
			this.slider.promoteThumb(this);
			return true;
		}
	},

	/**
	* @private
	* This is tied into the internal Ext.dd.DragTracker's onStart template method. Adds the drag CSS class
	* to the thumb and fires the 'dragstart' event
	*/
	onDragStart: function (e) {
		this.el.addClass('x-slider-thumb-drag');
		this.dragging = true;
		this.dragStartValue = this.value;

		this.slider.fireEvent('dragstart', this.slider, e, this);
	},

	/**
	* @private
	* This is tied into the internal Ext.dd.DragTracker's onDrag template method. This is called every time
	* the DragTracker detects a drag movement. It updates the Slider's value using the position of the drag
	*/
	onDrag: function (e) {
		var slider = this.slider,
            index = this.index,
            newValue = this.getNewValue();

		if (this.constrain) {
			var above = slider.thumbs[index + 1],
                below = slider.thumbs[index - 1];

			if (below != undefined && newValue <= below.value) newValue = below.value;
			if (above != undefined && newValue >= above.value) newValue = above.value;
		}

		slider.setValue(index, newValue, false);
		slider.fireEvent('drag', slider, e, this);
	},

	getNewValue: function () {
		var slider = this.slider,
            pos = slider.innerEl.translatePoints(this.tracker.getXY());

		return Ext.util.Format.round(slider.reverseValue(pos.left), slider.decimalPrecision);
	},

	/**
	* @private
	* This is tied to the internal Ext.dd.DragTracker's onEnd template method. Removes the drag CSS class and
	* fires the 'changecomplete' event with the new value
	*/
	onDragEnd: function (e) {
		var slider = this.slider,
            value = this.value;

		this.el.removeClass('x-slider-thumb-drag');

		this.dragging = false;
		slider.fireEvent('dragend', slider, e);

		if (this.dragStartValue != value) {
			slider.fireEvent('changecomplete', slider, value, this);
		}
	}
});

/**
* @class Ext.slider.MultiSlider
* @extends Ext.BoxComponent
* Slider which supports vertical or horizontal orientation, keyboard adjustments, configurable snapping, axis clicking and animation. Can be added as an item to any container. Example usage:
<pre>
new Ext.Slider({
renderTo: Ext.getBody(),
width: 200,
value: 50,
increment: 10,
minValue: 0,
maxValue: 100
});
</pre>
* Sliders can be created with more than one thumb handle by passing an array of values instead of a single one:
<pre>
new Ext.Slider({
renderTo: Ext.getBody(),
width: 200,
values: [25, 50, 75],
minValue: 0,
maxValue: 100,

//this defaults to true, setting to false allows the thumbs to pass each other
{@link #constrainThumbs}: false
});
</pre>
*/
Ext.slider.MultiSlider = Ext.extend(Ext.BoxComponent, {
	/**
	* @cfg {Number} value The value to initialize the slider with. Defaults to minValue.
	*/
	/**
	* @cfg {Boolean} vertical Orient the Slider vertically rather than horizontally, defaults to false.
	*/
	vertical: false,
	/**
	* @cfg {Number} minValue The minimum value for the Slider. Defaults to 0.
	*/
	minValue: 0,
	/**
	* @cfg {Number} maxValue The maximum value for the Slider. Defaults to 100.
	*/
	maxValue: 100,
	/**
	* @cfg {Number/Boolean} decimalPrecision.
	* <p>The number of decimal places to which to round the Slider's value. Defaults to 0.</p>
	* <p>To disable rounding, configure as <tt><b>false</b></tt>.</p>
	*/
	decimalPrecision: 0,
	/**
	* @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.
	*/
	keyIncrement: 1,
	/**
	* @cfg {Number} increment How many units to change the slider when adjusting by drag and drop. Use this option to enable 'snapping'.
	*/
	increment: 0,

	/**
	* @private
	* @property clickRange
	* @type Array
	* 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],
	* 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'
	* 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
	*/
	clickRange: [5, 15],

	/**
	* @cfg {Boolean} clickToChange Determines whether or not clicking on the Slider axis will change the slider. Defaults to true
	*/
	clickToChange: true,
	/**
	* @cfg {Boolean} animate Turn on or off animation. Defaults to true
	*/
	animate: true,

	/**
	* True while the thumb is in a drag operation
	* @type Boolean
	*/
	dragging: false,

	/**
	* @cfg {Boolean} constrainThumbs True to disallow thumbs from overlapping one another. Defaults to true
	*/
	constrainThumbs: true,

	/**
	* @private
	* @property topThumbZIndex
	* @type Number
	* The number used internally to set the z index of the top thumb (see promoteThumb for details)
	*/
	topThumbZIndex: 10000,

	// private override
	initComponent: function () {
		if (!Ext.isDefined(this.value)) {
			this.value = this.minValue;
		}

		/**
		* @property thumbs
		* @type Array
		* Array containing references to each thumb
		*/
		this.thumbs = [];

		Ext.slider.MultiSlider.superclass.initComponent.call(this);

		this.keyIncrement = Math.max(this.increment, this.keyIncrement);
		this.addEvents(
		/**
		* @event beforechange
		* Fires before the slider value is changed. By returning false from an event handler,
		* you can cancel the event and prevent the slider from changing.
		* @param {Ext.Slider} slider The slider
		* @param {Number} newValue The new value which the slider is being changed to.
		* @param {Number} oldValue The old value which the slider was previously.
		*/
            'beforechange',

		/**
		* @event change
		* Fires when the slider value is changed.
		* @param {Ext.Slider} slider The slider
		* @param {Number} newValue The new value which the slider has been changed to.
		* @param {Ext.slider.Thumb} thumb The thumb that was changed
		*/
            'change',

		/**
		* @event changecomplete
		* Fires when the slider value is changed by the user and any drag operations have completed.
		* @param {Ext.Slider} slider The slider
		* @param {Number} newValue The new value which the slider has been changed to.
		* @param {Ext.slider.Thumb} thumb The thumb that was changed
		*/
            'changecomplete',

		/**
		* @event dragstart
		* Fires after a drag operation has started.
		* @param {Ext.Slider} slider The slider
		* @param {Ext.EventObject} e The event fired from Ext.dd.DragTracker
		*/
            'dragstart',

		/**
		* @event drag
		* Fires continuously during the drag operation while the mouse is moving.
		* @param {Ext.Slider} slider The slider
		* @param {Ext.EventObject} e The event fired from Ext.dd.DragTracker
		*/
            'drag',

		/**
		* @event dragend
		* Fires after the drag operation has completed.
		* @param {Ext.Slider} slider The slider
		* @param {Ext.EventObject} e The event fired from Ext.dd.DragTracker
		*/
            'dragend'
        );

		/**
		* @property values
		* @type Array
		* Array of values to initalize the thumbs with
		*/
		if (this.values == undefined || Ext.isEmpty(this.values)) this.values = [0];

		var values = this.values;

		for (var i = 0; i < values.length; i++) {
			this.addThumb(values[i]);
		}

		if (this.vertical) {
			Ext.apply(this, Ext.slider.Vertical);
		}
	},

	/**
	* Creates a new thumb and adds it to the slider
	* @param {Number} value The initial value to set on the thumb. Defaults to 0
	*/
	addThumb: function (value) {
		var thumb = new Ext.slider.Thumb({
			value: value,
			slider: this,
			index: this.thumbs.length,
			constrain: this.constrainThumbs
		});
		this.thumbs.push(thumb);

		//render the thumb now if needed
		if (this.rendered) thumb.render();
	},

	/**
	* @private
	* Moves the given thumb above all other by increasing its z-index. This is called when as drag
	* any thumb, so that the thumb that was just dragged is always at the highest z-index. This is
	* required when the thumbs are stacked on top of each other at one of the ends of the slider's
	* range, which can result in the user not being able to move any of them.
	* @param {Ext.slider.Thumb} topThumb The thumb to move to the top
	*/
	promoteThumb: function (topThumb) {
		var thumbs = this.thumbs,
            zIndex, thumb;

		for (var i = 0, j = thumbs.length; i < j; i++) {
			thumb = thumbs[i];

			if (thumb == topThumb) {
				zIndex = this.topThumbZIndex;
			} else {
				zIndex = '';
			}

			thumb.el.setStyle('zIndex', zIndex);
		}
	},

	// private override
	onRender: function () {
		this.autoEl = {
			cls: 'x-slider ' + (this.vertical ? 'x-slider-vert' : 'x-slider-horz'),
			cn: {
				cls: 'x-slider-end',
				cn: {
					cls: 'x-slider-inner',
					cn: [{ tag: 'a', cls: 'x-slider-focus', href: "#", tabIndex: '-1', hidefocus: 'on'}]
				}
			}
		};

		Ext.slider.MultiSlider.superclass.onRender.apply(this, arguments);

		this.endEl = this.el.first();
		this.innerEl = this.endEl.first();
		this.focusEl = this.innerEl.child('.x-slider-focus');

		//render each thumb
		for (var i = 0; i < this.thumbs.length; i++) {
			this.thumbs[i].render();
		}

		//calculate the size of half a thumb
		var thumb = this.innerEl.child('.x-slider-thumb');
		this.halfThumb = (this.vertical ? thumb.getHeight() : thumb.getWidth()) / 2;

		this.initEvents();
	},

	/**
	* @private
	* Adds keyboard and mouse listeners on this.el. Ignores click events on the internal focus element.
	* Creates a new DragTracker which is used to control what happens when the user drags the thumb around.
	*/
	initEvents: function () {
		this.mon(this.el, {
			scope: this,
			mousedown: this.onMouseDown,
			keydown: this.onKeyDown
		});

		this.focusEl.swallowEvent("click", true);
	},

	/**
	* @private
	* Mousedown handler for the slider. If the clickToChange is enabled and the click was not on the draggable 'thumb',
	* this calculates the new value of the slider and tells the implementation (Horizontal or Vertical) to move the thumb
	* @param {Ext.EventObject} e The click event
	*/
	onMouseDown: function (e) {
		if (this.disabled) {
			return;
		}

		//see if the click was on any of the thumbs
		var thumbClicked = false;
		for (var i = 0; i < this.thumbs.length; i++) {
			thumbClicked = thumbClicked || e.target == this.thumbs[i].el.dom;
		}

		if (this.clickToChange && !thumbClicked) {
			var local = this.innerEl.translatePoints(e.getXY());
			this.onClickChange(local);
		}
		this.focus();
	},

	/**
	* @private
	* Moves the thumb to the indicated position. Note that a Vertical implementation is provided in Ext.slider.Vertical.
	* Only changes the value if the click was within this.clickRange.
	* @param {Object} local Object containing top and left values for the click event.
	*/
	onClickChange: function (local) {
		if (local.top > this.clickRange[0] && local.top < this.clickRange[1]) {
			//find the nearest thumb to the click event
			var thumb = this.getNearest(local, 'left'),
                index = thumb.index;

			this.setValue(index, Ext.util.Format.round(this.reverseValue(local.left), this.decimalPrecision), undefined, true);
		}
	},

	/**
	* @private
	* Returns the nearest thumb to a click event, along with its distance
	* @param {Object} local Object containing top and left values from a click event
	* @param {String} prop The property of local to compare on. Use 'left' for horizontal sliders, 'top' for vertical ones
	* @return {Object} The closest thumb object and its distance from the click event
	*/
	getNearest: function (local, prop) {
		var localValue = prop == 'top' ? this.innerEl.getHeight() - local[prop] : local[prop],
            clickValue = this.reverseValue(localValue),
            nearestDistance = (this.maxValue - this.minValue) + 5, //add a small fudge for the end of the slider 
            index = 0,
            nearest = null;

		for (var i = 0; i < this.thumbs.length; i++) {
			var thumb = this.thumbs[i],
                value = thumb.value,
                dist = Math.abs(value - clickValue);

			if (Math.abs(dist <= nearestDistance)) {
				nearest = thumb;
				index = i;
				nearestDistance = dist;
			}
		}
		return nearest;
	},

	/**
	* @private
	* Handler for any keypresses captured by the slider. If the key is UP or RIGHT, the thumb is moved along to the right
	* by this.keyIncrement. If DOWN or LEFT it is moved left. Pressing CTRL moves the slider to the end in either direction
	* @param {Ext.EventObject} e The Event object
	*/
	onKeyDown: function (e) {
		/*
		* The behaviour for keyboard handling with multiple thumbs is currently undefined.
		* There's no real sane default for it, so leave it like this until we come up
		* with a better way of doing it.
		*/
		if (this.disabled || this.thumbs.length !== 1) {
			e.preventDefault();
			return;
		}
		var k = e.getKey(),
            val;
		switch (k) {
			case e.UP:
			case e.RIGHT:
				e.stopEvent();
				val = e.ctrlKey ? this.maxValue : this.getValue(0) + this.keyIncrement;
				this.setValue(0, val, undefined, true);
				break;
			case e.DOWN:
			case e.LEFT:
				e.stopEvent();
				val = e.ctrlKey ? this.minValue : this.getValue(0) - this.keyIncrement;
				this.setValue(0, val, undefined, true);
				break;
			default:
				e.preventDefault();
		}
	},

	/**
	* @private
	* If using snapping, this takes a desired new value and returns the closest snapped
	* value to it
	* @param {Number} value The unsnapped value
	* @return {Number} The value of the nearest snap target
	*/
	doSnap: function (value) {
		if (!(this.increment && value)) {
			return value;
		}
		var newValue = value,
            inc = this.increment,
            m = value % inc;
		if (m != 0) {
			newValue -= m;
			if (m * 2 >= inc) {
				newValue += inc;
			} else if (m * 2 < -inc) {
				newValue -= inc;
			}
		}
		return newValue.constrain(this.minValue, this.maxValue);
	},

	// private
	afterRender: function () {
		Ext.slider.MultiSlider.superclass.afterRender.apply(this, arguments);

		for (var i = 0; i < this.thumbs.length; i++) {
			var thumb = this.thumbs[i];

			if (thumb.value !== undefined) {
				var v = this.normalizeValue(thumb.value);

				if (v !== thumb.value) {
					// delete this.value;
					this.setValue(i, v, false);
				} else {
					this.moveThumb(i, this.translateValue(v), false);
				}
			}
		};
	},

	/**
	* @private
	* Returns the ratio of pixels to mapped values. e.g. if the slider is 200px wide and maxValue - minValue is 100,
	* the ratio is 2
	* @return {Number} The ratio of pixels to mapped values
	*/
	getRatio: function () {
		var w = this.innerEl.getWidth(),
            v = this.maxValue - this.minValue;
		return v == 0 ? w : (w / v);
	},

	/**
	* @private
	* Returns a snapped, constrained value when given a desired value
	* @param {Number} value Raw number value
	* @return {Number} The raw value rounded to the correct d.p. and constrained within the set max and min values
	*/
	normalizeValue: function (v) {
		v = this.doSnap(v);
		v = Ext.util.Format.round(v, this.decimalPrecision);
		v = v.constrain(this.minValue, this.maxValue);
		return v;
	},

	/**
	* Sets the minimum value for the slider instance. If the current value is less than the
	* minimum value, the current value will be changed.
	* @param {Number} val The new minimum value
	*/
	setMinValue: function (val) {
		this.minValue = val;
		var i = 0,
            thumbs = this.thumbs,
            len = thumbs.length,
            t;

		for (; i < len; ++i) {
			t = thumbs[i];
			t.value = t.value < val ? val : t.value;
		}
		this.syncThumb();
	},

	/**
	* Sets the maximum value for the slider instance. If the current value is more than the
	* maximum value, the current value will be changed.
	* @param {Number} val The new maximum value
	*/
	setMaxValue: function (val) {
		this.maxValue = val;
		var i = 0,
            thumbs = this.thumbs,
            len = thumbs.length,
            t;

		for (; i < len; ++i) {
			t = thumbs[i];
			t.value = t.value > val ? val : t.value;
		}
		this.syncThumb();
	},

	/**
	* Programmatically sets the value of the Slider. Ensures that the value is constrained within
	* the minValue and maxValue.
	* @param {Number} index Index of the thumb to move
	* @param {Number} value The value to set the slider to. (This will be constrained within minValue and maxValue)
	* @param {Boolean} animate Turn on or off animation, defaults to true
	*/
	setValue: function (index, v, animate, changeComplete) {
		var thumb = this.thumbs[index],
            el = thumb.el;

		v = this.normalizeValue(v);

		if (v !== thumb.value && this.fireEvent('beforechange', this, v, thumb.value, thumb) !== false) {
			thumb.value = v;
			if (this.rendered) {
				this.moveThumb(index, this.translateValue(v), animate !== false);
				this.fireEvent('change', this, v, thumb);
				if (changeComplete) {
					this.fireEvent('changecomplete', this, v, thumb);
				}
			}
		}
	},

	/**
	* @private
	*/
	translateValue: function (v) {
		var ratio = this.getRatio();
		return (v * ratio) - (this.minValue * ratio) - this.halfThumb;
	},

	/**
	* @private
	* Given a pixel location along the slider, returns the mapped slider value for that pixel.
	* E.g. if we have a slider 200px wide with minValue = 100 and maxValue = 500, reverseValue(50)
	* returns 200
	* @param {Number} pos The position along the slider to return a mapped value for
	* @return {Number} The mapped value for the given position
	*/
	reverseValue: function (pos) {
		var ratio = this.getRatio();
		return (pos + (this.minValue * ratio)) / ratio;
	},

	/**
	* @private
	* @param {Number} index Index of the thumb to move
	*/
	moveThumb: function (index, v, animate) {
		var thumb = this.thumbs[index].el;

		if (!animate || this.animate === false) {
			thumb.setLeft(v);
		} else {
			thumb.shift({ left: v, stopFx: true, duration: .35 });
		}
	},

	// private
	focus: function () {
		this.focusEl.focus(10);
	},

	// private
	onResize: function (w, h) {
		var thumbs = this.thumbs,
            len = thumbs.length,
            i = 0;

		/*
		* If we happen to be animating during a resize, the position of the thumb will likely be off
		* when the animation stops. As such, just stop any animations before syncing the thumbs.
		*/
		for (; i < len; ++i) {
			thumbs[i].el.stopFx();
		}
		this.innerEl.setWidth(w - (this.el.getPadding('l') + this.endEl.getPadding('r')));
		this.syncThumb();
		Ext.slider.MultiSlider.superclass.onResize.apply(this, arguments);
	},

	//private
	onDisable: function () {
		Ext.slider.MultiSlider.superclass.onDisable.call(this);

		for (var i = 0; i < this.thumbs.length; i++) {
			var thumb = this.thumbs[i],
                el = thumb.el;

			thumb.disable();

			if (Ext.isIE) {
				//IE breaks when using overflow visible and opacity other than 1.
				//Create a place holder for the thumb and display it.
				var xy = el.getXY();
				el.hide();

				this.innerEl.addClass(this.disabledClass).dom.disabled = true;

				if (!this.thumbHolder) {
					this.thumbHolder = this.endEl.createChild({ cls: 'x-slider-thumb ' + this.disabledClass });
				}

				this.thumbHolder.show().setXY(xy);
			}
		}
	},

	//private
	onEnable: function () {
		Ext.slider.MultiSlider.superclass.onEnable.call(this);

		for (var i = 0; i < this.thumbs.length; i++) {
			var thumb = this.thumbs[i],
                el = thumb.el;

			thumb.enable();

			if (Ext.isIE) {
				this.innerEl.removeClass(this.disabledClass).dom.disabled = false;

				if (this.thumbHolder) this.thumbHolder.hide();

				el.show();
				this.syncThumb();
			}
		}
	},

	/**
	* Synchronizes the thumb position to the proper proportion of the total component width based
	* on the current slider {@link #value}.  This will be called automatically when the Slider
	* is resized by a layout, but if it is rendered auto width, this method can be called from
	* another resize handler to sync the Slider if necessary.
	*/
	syncThumb: function () {
		if (this.rendered) {
			for (var i = 0; i < this.thumbs.length; i++) {
				this.moveThumb(i, this.translateValue(this.thumbs[i].value));
			}
		}
	},

	/**
	* Returns the current value of the slider
	* @param {Number} index The index of the thumb to return a value for
	* @return {Number} The current value of the slider
	*/
	getValue: function (index) {
		return this.thumbs[index].value;
	},

	/**
	* Returns an array of values - one for the location of each thumb
	* @return {Array} The set of thumb values
	*/
	getValues: function () {
		var values = [];

		for (var i = 0; i < this.thumbs.length; i++) {
			values.push(this.thumbs[i].value);
		}

		return values;
	},

	// private
	beforeDestroy: function () {
		Ext.destroyMembers(this, 'endEl', 'innerEl', 'thumb', 'halfThumb', 'focusEl', 'tracker', 'thumbHolder');
		Ext.slider.MultiSlider.superclass.beforeDestroy.call(this);
	}
});

Ext.reg('multislider', Ext.slider.MultiSlider);

/**
* @class Ext.slider.SingleSlider
* @extends Ext.slider.MultiSlider
* Slider which supports vertical or horizontal orientation, keyboard adjustments,
* configurable snapping, axis clicking and animation. Can be added as an item to
* any container. Example usage:
<pre><code>
new Ext.slider.SingleSlider({
renderTo: Ext.getBody(),
width: 200,
value: 50,
increment: 10,
minValue: 0,
maxValue: 100
});
</code></pre>
* The class Ext.slider.SingleSlider is aliased to Ext.Slider for backwards compatibility.
*/
Ext.slider.SingleSlider = Ext.extend(Ext.slider.MultiSlider, {
	constructor: function (config) {
		config = config || {};

		Ext.applyIf(config, {
			values: [config.value || 0]
		});

		Ext.slider.SingleSlider.superclass.constructor.call(this, config);
	},

	/**
	* Returns the current value of the slider
	* @return {Number} The current value of the slider
	*/
	getValue: function () {
		//just returns the value of the first thumb, which should be the only one in a single slider
		return Ext.slider.SingleSlider.superclass.getValue.call(this, 0);
	},

	/**
	* Programmatically sets the value of the Slider. Ensures that the value is constrained within
	* the minValue and maxValue.
	* @param {Number} value The value to set the slider to. (This will be constrained within minValue and maxValue)
	* @param {Boolean} animate Turn on or off animation, defaults to true
	*/
	setValue: function (value, animate) {
		var args = Ext.toArray(arguments),
            len = args.length;

		//this is to maintain backwards compatiblity for sliders with only one thunb. Usually you must pass the thumb
		//index to setValue, but if we only have one thumb we inject the index here first if given the multi-slider
		//signature without the required index. The index will always be 0 for a single slider
		if (len == 1 || (len <= 3 && typeof arguments[1] != 'number')) {
			args.unshift(0);
		}

		return Ext.slider.SingleSlider.superclass.setValue.apply(this, args);
	},

	/**
	* Synchronizes the thumb position to the proper proportion of the total component width based
	* on the current slider {@link #value}.  This will be called automatically when the Slider
	* is resized by a layout, but if it is rendered auto width, this method can be called from
	* another resize handler to sync the Slider if necessary.
	*/
	syncThumb: function () {
		return Ext.slider.SingleSlider.superclass.syncThumb.apply(this, [0].concat(arguments));
	},

	// private
	getNearest: function () {
		// Since there's only 1 thumb, it's always the nearest
		return this.thumbs[0];
	}
});

//backwards compatibility
Ext.Slider = Ext.slider.SingleSlider;

Ext.reg('slider', Ext.slider.SingleSlider);

// private class to support vertical sliders
Ext.slider.Vertical = {
	onResize: function (w, h) {
		this.innerEl.setHeight(h - (this.el.getPadding('t') + this.endEl.getPadding('b')));
		this.syncThumb();
	},

	getRatio: function () {
		var h = this.innerEl.getHeight(),
            v = this.maxValue - this.minValue;
		return h / v;
	},

	moveThumb: function (index, v, animate) {
		var thumb = this.thumbs[index],
            el = thumb.el;

		if (!animate || this.animate === false) {
			el.setBottom(v);
		} else {
			el.shift({ bottom: v, stopFx: true, duration: .35 });
		}
	},

	onClickChange: function (local) {
		if (local.left > this.clickRange[0] && local.left < this.clickRange[1]) {
			var thumb = this.getNearest(local, 'top'),
                index = thumb.index,
                value = this.minValue + this.reverseValue(this.innerEl.getHeight() - local.top);

			this.setValue(index, Ext.util.Format.round(value, this.decimalPrecision), undefined, true);
		}
	}
};

//private class to support vertical dragging of thumbs within a slider
Ext.slider.Thumb.Vertical = {
	getNewValue: function () {
		var slider = this.slider,
            innerEl = slider.innerEl,
            pos = innerEl.translatePoints(this.tracker.getXY()),
            bottom = innerEl.getHeight() - pos.top;

		return slider.minValue + Ext.util.Format.round(bottom / slider.getRatio(), slider.decimalPrecision);
	}
};
/**
* @class Ext.ProgressBar
* @extends Ext.BoxComponent
* <p>An updateable progress bar component.  The progress bar supports two different modes: manual and automatic.</p>
* <p>In manual mode, you are responsible for showing, updating (via {@link #updateProgress}) and clearing the
* progress bar as needed from your own code.  This method is most appropriate when you want to show progress
* throughout an operation that has predictable points of interest at which you can update the control.</p>
* <p>In automatic mode, you simply call {@link #wait} and let the progress bar run indefinitely, only clearing it
* once the operation is complete.  You can optionally have the progress bar wait for a specific amount of time
* and then clear itself.  Automatic mode is most appropriate for timed operations or asynchronous operations in
* which you have no need for indicating intermediate progress.</p>
* @cfg {Float} value A floating point value between 0 and 1 (e.g., .5, defaults to 0)
* @cfg {String} text The progress bar text (defaults to '')
* @cfg {Mixed} textEl The element to render the progress text to (defaults to the progress
* bar's internal text element)
* @cfg {String} id The progress bar element's id (defaults to an auto-generated id)
* @xtype progress
*/
Ext.ProgressBar = Ext.extend(Ext.BoxComponent, {
	/**
	* @cfg {String} baseCls
	* The base CSS class to apply to the progress bar's wrapper element (defaults to 'x-progress')
	*/
	baseCls: 'x-progress',

	/**
	* @cfg {Boolean} animate
	* True to animate the progress bar during transitions (defaults to false)
	*/
	animate: false,

	// private
	waitTimer: null,

	// private
	initComponent: function () {
		Ext.ProgressBar.superclass.initComponent.call(this);
		this.addEvents(
		/**
		* @event update
		* Fires after each update interval
		* @param {Ext.ProgressBar} this
		* @param {Number} The current progress value
		* @param {String} The current progress text
		*/
            "update"
        );
	},

	// private
	onRender: function (ct, position) {
		var tpl = new Ext.Template(
            '<div class="{cls}-wrap">',
                '<div class="{cls}-inner">',
                    '<div class="{cls}-bar">',
                        '<div class="{cls}-text">',
                            '<div>&#160;</div>',
                        '</div>',
                    '</div>',
                    '<div class="{cls}-text {cls}-text-back">',
                        '<div>&#160;</div>',
                    '</div>',
                '</div>',
            '</div>'
        );

		this.el = position ? tpl.insertBefore(position, { cls: this.baseCls }, true)
            : tpl.append(ct, { cls: this.baseCls }, true);

		if (this.id) {
			this.el.dom.id = this.id;
		}
		var inner = this.el.dom.firstChild;
		this.progressBar = Ext.get(inner.firstChild);

		if (this.textEl) {
			//use an external text el
			this.textEl = Ext.get(this.textEl);
			delete this.textTopEl;
		} else {
			//setup our internal layered text els
			this.textTopEl = Ext.get(this.progressBar.dom.firstChild);
			var textBackEl = Ext.get(inner.childNodes[1]);
			this.textTopEl.setStyle("z-index", 99).addClass('x-hidden');
			this.textEl = new Ext.CompositeElement([this.textTopEl.dom.firstChild, textBackEl.dom.firstChild]);
			this.textEl.setWidth(inner.offsetWidth);
		}
		this.progressBar.setHeight(inner.offsetHeight);
	},

	// private
	afterRender: function () {
		Ext.ProgressBar.superclass.afterRender.call(this);
		if (this.value) {
			this.updateProgress(this.value, this.text);
		} else {
			this.updateText(this.text);
		}
	},

	/**
	* Updates the progress bar value, and optionally its text.  If the text argument is not specified,
	* any existing text value will be unchanged.  To blank out existing text, pass ''.  Note that even
	* if the progress bar value exceeds 1, it will never automatically reset -- you are responsible for
	* determining when the progress is complete and calling {@link #reset} to clear and/or hide the control.
	* @param {Float} value (optional) A floating point value between 0 and 1 (e.g., .5, defaults to 0)
	* @param {String} text (optional) The string to display in the progress text element (defaults to '')
	* @param {Boolean} animate (optional) Whether to animate the transition of the progress bar. If this value is
	* not specified, the default for the class is used (default to false)
	* @return {Ext.ProgressBar} this
	*/
	updateProgress: function (value, text, animate) {
		this.value = value || 0;
		if (text) {
			this.updateText(text);
		}
		if (this.rendered && !this.isDestroyed) {
			var w = Math.floor(value * this.el.dom.firstChild.offsetWidth);
			this.progressBar.setWidth(w, animate === true || (animate !== false && this.animate));
			if (this.textTopEl) {
				//textTopEl should be the same width as the bar so overflow will clip as the bar moves
				this.textTopEl.removeClass('x-hidden').setWidth(w);
			}
		}
		this.fireEvent('update', this, value, text);
		return this;
	},

	/**
	* Initiates an auto-updating progress bar.  A duration can be specified, in which case the progress
	* bar will automatically reset after a fixed amount of time and optionally call a callback function
	* if specified.  If no duration is passed in, then the progress bar will run indefinitely and must
	* be manually cleared by calling {@link #reset}.  The wait method accepts a config object with
	* the following properties:
	* <pre>
	Property   Type          Description
	---------- ------------  ----------------------------------------------------------------------
	duration   Number        The length of time in milliseconds that the progress bar should
	run before resetting itself (defaults to undefined, in which case it
	will run indefinitely until reset is called)
	interval   Number        The length of time in milliseconds between each progress update
	(defaults to 1000 ms)
	animate    Boolean       Whether to animate the transition of the progress bar. If this value is
	not specified, the default for the class is used.                                                   
	increment  Number        The number of progress update segments to display within the progress
	bar (defaults to 10).  If the bar reaches the end and is still
	updating, it will automatically wrap back to the beginning.
	text       String        Optional text to display in the progress bar element (defaults to '').
	fn         Function      A callback function to execute after the progress bar finishes auto-
	updating.  The function will be called with no arguments.  This function
	will be ignored if duration is not specified since in that case the
	progress bar can only be stopped programmatically, so any required function
	should be called by the same code after it resets the progress bar.
	scope      Object        The scope that is passed to the callback function (only applies when
	duration and fn are both passed).
	</pre>
	*
	* Example usage:
	* <pre><code>
	var p = new Ext.ProgressBar({
	renderTo: 'my-el'
	});

	//Wait for 5 seconds, then update the status el (progress bar will auto-reset)
	p.wait({
	interval: 100, //bar will move fast!
	duration: 5000,
	increment: 15,
	text: 'Updating...',
	scope: this,
	fn: function(){
	Ext.fly('status').update('Done!');
	}
	});

	//Or update indefinitely until some async action completes, then reset manually
	p.wait();
	myAction.on('complete', function(){
	p.reset();
	Ext.fly('status').update('Done!');
	});
	</code></pre>
	* @param {Object} config (optional) Configuration options
	* @return {Ext.ProgressBar} this
	*/
	wait: function (o) {
		if (!this.waitTimer) {
			var scope = this;
			o = o || {};
			this.updateText(o.text);
			this.waitTimer = Ext.TaskMgr.start({
				run: function (i) {
					var inc = o.increment || 10;
					i -= 1;
					this.updateProgress(((((i + inc) % inc) + 1) * (100 / inc)) * 0.01, null, o.animate);
				},
				interval: o.interval || 1000,
				duration: o.duration,
				onStop: function () {
					if (o.fn) {
						o.fn.apply(o.scope || this);
					}
					this.reset();
				},
				scope: scope
			});
		}
		return this;
	},

	/**
	* Returns true if the progress bar is currently in a {@link #wait} operation
	* @return {Boolean} True if waiting, else false
	*/
	isWaiting: function () {
		return this.waitTimer !== null;
	},

	/**
	* Updates the progress bar text.  If specified, textEl will be updated, otherwise the progress
	* bar itself will display the updated text.
	* @param {String} text (optional) The string to display in the progress text element (defaults to '')
	* @return {Ext.ProgressBar} this
	*/
	updateText: function (text) {
		this.text = text || '&#160;';
		if (this.rendered) {
			this.textEl.update(this.text);
		}
		return this;
	},

	/**
	* Synchronizes the inner bar width to the proper proportion of the total componet width based
	* on the current progress {@link #value}.  This will be called automatically when the ProgressBar
	* is resized by a layout, but if it is rendered auto width, this method can be called from
	* another resize handler to sync the ProgressBar if necessary.
	*/
	syncProgressBar: function () {
		if (this.value) {
			this.updateProgress(this.value, this.text);
		}
		return this;
	},

	/**
	* Sets the size of the progress bar.
	* @param {Number} width The new width in pixels
	* @param {Number} height The new height in pixels
	* @return {Ext.ProgressBar} this
	*/
	setSize: function (w, h) {
		Ext.ProgressBar.superclass.setSize.call(this, w, h);
		if (this.textTopEl) {
			var inner = this.el.dom.firstChild;
			this.textEl.setSize(inner.offsetWidth, inner.offsetHeight);
		}
		this.syncProgressBar();
		return this;
	},

	/**
	* Resets the progress bar value to 0 and text to empty string.  If hide = true, the progress
	* bar will also be hidden (using the {@link #hideMode} property internally).
	* @param {Boolean} hide (optional) True to hide the progress bar (defaults to false)
	* @return {Ext.ProgressBar} this
	*/
	reset: function (hide) {
		this.updateProgress(0);
		if (this.textTopEl) {
			this.textTopEl.addClass('x-hidden');
		}
		this.clearTimer();
		if (hide === true) {
			this.hide();
		}
		return this;
	},

	// private
	clearTimer: function () {
		if (this.waitTimer) {
			this.waitTimer.onStop = null; //prevent recursion
			Ext.TaskMgr.stop(this.waitTimer);
			this.waitTimer = null;
		}
	},

	onDestroy: function () {
		this.clearTimer();
		if (this.rendered) {
			if (this.textEl.isComposite) {
				this.textEl.clear();
			}
			Ext.destroyMembers(this, 'textEl', 'progressBar', 'textTopEl');
		}
		Ext.ProgressBar.superclass.onDestroy.call(this);
	}
});
Ext.reg('progress', Ext.ProgressBar); /*
 * These classes are derivatives of the similarly named classes in the YUI Library.
 * The original license:
 * Copyright (c) 2006, Yahoo! Inc. All rights reserved.
 * Code licensed under the BSD License:
 * http://developer.yahoo.net/yui/license.txt
 */

(function () {

	var Event = Ext.EventManager;
	var Dom = Ext.lib.Dom;

	/**
	* @class Ext.dd.DragDrop
	* Defines the interface and base operation of items that that can be
	* dragged or can be drop targets.  It was designed to be extended, overriding
	* the event handlers for startDrag, onDrag, onDragOver and onDragOut.
	* Up to three html elements can be associated with a DragDrop instance:
	* <ul>
	* <li>linked element: the element that is passed into the constructor.
	* This is the element which defines the boundaries for interaction with
	* other DragDrop objects.</li>
	* <li>handle element(s): The drag operation only occurs if the element that
	* was clicked matches a handle element.  By default this is the linked
	* element, but there are times that you will want only a portion of the
	* linked element to initiate the drag operation, and the setHandleElId()
	* method provides a way to define this.</li>
	* <li>drag element: this represents the element that would be moved along
	* with the cursor during a drag operation.  By default, this is the linked
	* element itself as in {@link Ext.dd.DD}.  setDragElId() lets you define
	* a separate element that would be moved, as in {@link Ext.dd.DDProxy}.
	* </li>
	* </ul>
	* This class should not be instantiated until the onload event to ensure that
	* the associated elements are available.
	* The following would define a DragDrop obj that would interact with any
	* other DragDrop obj in the "group1" group:
	* <pre>
	*  dd = new Ext.dd.DragDrop("div1", "group1");
	* </pre>
	* Since none of the event handlers have been implemented, nothing would
	* actually happen if you were to run the code above.  Normally you would
	* override this class or one of the default implementations, but you can
	* also override the methods you want on an instance of the class...
	* <pre>
	*  dd.onDragDrop = function(e, id) {
	*  &nbsp;&nbsp;alert("dd was dropped on " + id);
	*  }
	* </pre>
	* @constructor
	* @param {String} id of the element that is linked to this instance
	* @param {String} sGroup the group of related DragDrop objects
	* @param {object} config an object containing configurable attributes
	*                Valid properties for DragDrop:
	*                    padding, isTarget, maintainOffset, primaryButtonOnly
	*/
	Ext.dd.DragDrop = function (id, sGroup, config) {
		if (id) {
			this.init(id, sGroup, config);
		}
	};

	Ext.dd.DragDrop.prototype = {

		/**
		* Set to false to enable a DragDrop object to fire drag events while dragging
		* over its own Element. Defaults to true - DragDrop objects do not by default
		* fire drag events to themselves.
		* @property ignoreSelf
		* @type Boolean
		*/

		/**
		* The id of the element associated with this object.  This is what we
		* refer to as the "linked element" because the size and position of
		* this element is used to determine when the drag and drop objects have
		* interacted.
		* @property id
		* @type String
		*/
		id: null,

		/**
		* Configuration attributes passed into the constructor
		* @property config
		* @type object
		*/
		config: null,

		/**
		* The id of the element that will be dragged.  By default this is same
		* as the linked element, but could be changed to another element. Ex:
		* Ext.dd.DDProxy
		* @property dragElId
		* @type String
		* @private
		*/
		dragElId: null,

		/**
		* The ID of the element that initiates the drag operation.  By default
		* this is the linked element, but could be changed to be a child of this
		* element.  This lets us do things like only starting the drag when the
		* header element within the linked html element is clicked.
		* @property handleElId
		* @type String
		* @private
		*/
		handleElId: null,

		/**
		* An object who's property names identify HTML tags to be considered invalid as drag handles.
		* A non-null property value identifies the tag as invalid. Defaults to the 
		* following value which prevents drag operations from being initiated by &lt;a> elements:<pre><code>
		{
		A: "A"
		}</code></pre>
		* @property invalidHandleTypes
		* @type Object
		*/
		invalidHandleTypes: null,

		/**
		* An object who's property names identify the IDs of elements to be considered invalid as drag handles.
		* A non-null property value identifies the ID as invalid. For example, to prevent
		* dragging from being initiated on element ID "foo", use:<pre><code>
		{
		foo: true
		}</code></pre>
		* @property invalidHandleIds
		* @type Object
		*/
		invalidHandleIds: null,

		/**
		* An Array of CSS class names for elements to be considered in valid as drag handles.
		* @property invalidHandleClasses
		* @type Array
		*/
		invalidHandleClasses: null,

		/**
		* The linked element's absolute X position at the time the drag was
		* started
		* @property startPageX
		* @type int
		* @private
		*/
		startPageX: 0,

		/**
		* The linked element's absolute X position at the time the drag was
		* started
		* @property startPageY
		* @type int
		* @private
		*/
		startPageY: 0,

		/**
		* The group defines a logical collection of DragDrop objects that are
		* related.  Instances only get events when interacting with other
		* DragDrop object in the same group.  This lets us define multiple
		* groups using a single DragDrop subclass if we want.
		* @property groups
		* @type object An object in the format {'group1':true, 'group2':true}
		*/
		groups: null,

		/**
		* Individual drag/drop instances can be locked.  This will prevent
		* onmousedown start drag.
		* @property locked
		* @type boolean
		* @private
		*/
		locked: false,

		/**
		* Lock this instance
		* @method lock
		*/
		lock: function () {
			this.locked = true;
		},

		/**
		* When set to true, other DD objects in cooperating DDGroups do not receive
		* notification events when this DD object is dragged over them. Defaults to false.
		* @property moveOnly
		* @type boolean
		*/
		moveOnly: false,

		/**
		* Unlock this instace
		* @method unlock
		*/
		unlock: function () {
			this.locked = false;
		},

		/**
		* By default, all instances can be a drop target.  This can be disabled by
		* setting isTarget to false.
		* @property isTarget
		* @type boolean
		*/
		isTarget: true,

		/**
		* The padding configured for this drag and drop object for calculating
		* the drop zone intersection with this object.
		* @property padding
		* @type int[] An array containing the 4 padding values: [top, right, bottom, left]
		*/
		padding: null,

		/**
		* Cached reference to the linked element
		* @property _domRef
		* @private
		*/
		_domRef: null,

		/**
		* Internal typeof flag
		* @property __ygDragDrop
		* @private
		*/
		__ygDragDrop: true,

		/**
		* Set to true when horizontal contraints are applied
		* @property constrainX
		* @type boolean
		* @private
		*/
		constrainX: false,

		/**
		* Set to true when vertical contraints are applied
		* @property constrainY
		* @type boolean
		* @private
		*/
		constrainY: false,

		/**
		* The left constraint
		* @property minX
		* @type int
		* @private
		*/
		minX: 0,

		/**
		* The right constraint
		* @property maxX
		* @type int
		* @private
		*/
		maxX: 0,

		/**
		* The up constraint
		* @property minY
		* @type int
		* @private
		*/
		minY: 0,

		/**
		* The down constraint
		* @property maxY
		* @type int
		* @private
		*/
		maxY: 0,

		/**
		* Maintain offsets when we resetconstraints.  Set to true when you want
		* the position of the element relative to its parent to stay the same
		* when the page changes
		*
		* @property maintainOffset
		* @type boolean
		*/
		maintainOffset: false,

		/**
		* Array of pixel locations the element will snap to if we specified a
		* horizontal graduation/interval.  This array is generated automatically
		* when you define a tick interval.
		* @property xTicks
		* @type int[]
		*/
		xTicks: null,

		/**
		* Array of pixel locations the element will snap to if we specified a
		* vertical graduation/interval.  This array is generated automatically
		* when you define a tick interval.
		* @property yTicks
		* @type int[]
		*/
		yTicks: null,

		/**
		* By default the drag and drop instance will only respond to the primary
		* button click (left button for a right-handed mouse).  Set to true to
		* allow drag and drop to start with any mouse click that is propogated
		* by the browser
		* @property primaryButtonOnly
		* @type boolean
		*/
		primaryButtonOnly: true,

		/**
		* The available property is false until the linked dom element is accessible.
		* @property available
		* @type boolean
		*/
		available: false,

		/**
		* By default, drags can only be initiated if the mousedown occurs in the
		* region the linked element is.  This is done in part to work around a
		* bug in some browsers that mis-report the mousedown if the previous
		* mouseup happened outside of the window.  This property is set to true
		* if outer handles are defined.
		*
		* @property hasOuterHandles
		* @type boolean
		* @default false
		*/
		hasOuterHandles: false,

		/**
		* Code that executes immediately before the startDrag event
		* @method b4StartDrag
		* @private
		*/
		b4StartDrag: function (x, y) { },

		/**
		* Abstract method called after a drag/drop object is clicked
		* and the drag or mousedown time thresholds have beeen met.
		* @method startDrag
		* @param {int} X click location
		* @param {int} Y click location
		*/
		startDrag: function (x, y) { /* override this */ },

		/**
		* Code that executes immediately before the onDrag event
		* @method b4Drag
		* @private
		*/
		b4Drag: function (e) { },

		/**
		* Abstract method called during the onMouseMove event while dragging an
		* object.
		* @method onDrag
		* @param {Event} e the mousemove event
		*/
		onDrag: function (e) { /* override this */ },

		/**
		* Abstract method called when this element fist begins hovering over
		* another DragDrop obj
		* @method onDragEnter
		* @param {Event} e the mousemove event
		* @param {String|DragDrop[]} id In POINT mode, the element
		* id this is hovering over.  In INTERSECT mode, an array of one or more
		* dragdrop items being hovered over.
		*/
		onDragEnter: function (e, id) { /* override this */ },

		/**
		* Code that executes immediately before the onDragOver event
		* @method b4DragOver
		* @private
		*/
		b4DragOver: function (e) { },

		/**
		* Abstract method called when this element is hovering over another
		* DragDrop obj
		* @method onDragOver
		* @param {Event} e the mousemove event
		* @param {String|DragDrop[]} id In POINT mode, the element
		* id this is hovering over.  In INTERSECT mode, an array of dd items
		* being hovered over.
		*/
		onDragOver: function (e, id) { /* override this */ },

		/**
		* Code that executes immediately before the onDragOut event
		* @method b4DragOut
		* @private
		*/
		b4DragOut: function (e) { },

		/**
		* Abstract method called when we are no longer hovering over an element
		* @method onDragOut
		* @param {Event} e the mousemove event
		* @param {String|DragDrop[]} id In POINT mode, the element
		* id this was hovering over.  In INTERSECT mode, an array of dd items
		* that the mouse is no longer over.
		*/
		onDragOut: function (e, id) { /* override this */ },

		/**
		* Code that executes immediately before the onDragDrop event
		* @method b4DragDrop
		* @private
		*/
		b4DragDrop: function (e) { },

		/**
		* Abstract method called when this item is dropped on another DragDrop
		* obj
		* @method onDragDrop
		* @param {Event} e the mouseup event
		* @param {String|DragDrop[]} id In POINT mode, the element
		* id this was dropped on.  In INTERSECT mode, an array of dd items this
		* was dropped on.
		*/
		onDragDrop: function (e, id) { /* override this */ },

		/**
		* Abstract method called when this item is dropped on an area with no
		* drop target
		* @method onInvalidDrop
		* @param {Event} e the mouseup event
		*/
		onInvalidDrop: function (e) { /* override this */ },

		/**
		* Code that executes immediately before the endDrag event
		* @method b4EndDrag
		* @private
		*/
		b4EndDrag: function (e) { },

		/**
		* Fired when we are done dragging the object
		* @method endDrag
		* @param {Event} e the mouseup event
		*/
		endDrag: function (e) { /* override this */ },

		/**
		* Code executed immediately before the onMouseDown event
		* @method b4MouseDown
		* @param {Event} e the mousedown event
		* @private
		*/
		b4MouseDown: function (e) { },

		/**
		* Event handler that fires when a drag/drop obj gets a mousedown
		* @method onMouseDown
		* @param {Event} e the mousedown event
		*/
		onMouseDown: function (e) { /* override this */ },

		/**
		* Event handler that fires when a drag/drop obj gets a mouseup
		* @method onMouseUp
		* @param {Event} e the mouseup event
		*/
		onMouseUp: function (e) { /* override this */ },

		/**
		* Override the onAvailable method to do what is needed after the initial
		* position was determined.
		* @method onAvailable
		*/
		onAvailable: function () {
		},

		/**
		* Provides default constraint padding to "constrainTo" elements (defaults to {left: 0, right:0, top:0, bottom:0}).
		* @type Object
		*/
		defaultPadding: { left: 0, right: 0, top: 0, bottom: 0 },

		/**
		* Initializes the drag drop object's constraints to restrict movement to a certain element.
		*
		* Usage:
		<pre><code>
		var dd = new Ext.dd.DDProxy("dragDiv1", "proxytest",
		{ dragElId: "existingProxyDiv" });
		dd.startDrag = function(){
		this.constrainTo("parent-id");
		};
		</code></pre>
		* Or you can initalize it using the {@link Ext.Element} object:
		<pre><code>
		Ext.get("dragDiv1").initDDProxy("proxytest", {dragElId: "existingProxyDiv"}, {
		startDrag : function(){
		this.constrainTo("parent-id");
		}
		});
		</code></pre>
		* @param {Mixed} constrainTo The element to constrain to.
		* @param {Object/Number} pad (optional) Pad provides a way to specify "padding" of the constraints,
		* and can be either a number for symmetrical padding (4 would be equal to {left:4, right:4, top:4, bottom:4}) or
		* an object containing the sides to pad. For example: {right:10, bottom:10}
		* @param {Boolean} inContent (optional) Constrain the draggable in the content box of the element (inside padding and borders)
		*/
		constrainTo: function (constrainTo, pad, inContent) {
			if (Ext.isNumber(pad)) {
				pad = { left: pad, right: pad, top: pad, bottom: pad };
			}
			pad = pad || this.defaultPadding;
			var b = Ext.get(this.getEl()).getBox(),
            ce = Ext.get(constrainTo),
            s = ce.getScroll(),
            c,
            cd = ce.dom;
			if (cd == document.body) {
				c = { x: s.left, y: s.top, width: Ext.lib.Dom.getViewWidth(), height: Ext.lib.Dom.getViewHeight() };
			} else {
				var xy = ce.getXY();
				c = { x: xy[0], y: xy[1], width: cd.clientWidth, height: cd.clientHeight };
			}


			var topSpace = b.y - c.y,
            leftSpace = b.x - c.x;

			this.resetConstraints();
			this.setXConstraint(leftSpace - (pad.left || 0), // left
                c.width - leftSpace - b.width - (pad.right || 0), //right
				this.xTickSize
        );
			this.setYConstraint(topSpace - (pad.top || 0), //top
                c.height - topSpace - b.height - (pad.bottom || 0), //bottom
				this.yTickSize
        );
		},

		/**
		* Returns a reference to the linked element
		* @method getEl
		* @return {HTMLElement} the html element
		*/
		getEl: function () {
			if (!this._domRef) {
				this._domRef = Ext.getDom(this.id);
			}

			return this._domRef;
		},

		/**
		* Returns a reference to the actual element to drag.  By default this is
		* the same as the html element, but it can be assigned to another
		* element. An example of this can be found in Ext.dd.DDProxy
		* @method getDragEl
		* @return {HTMLElement} the html element
		*/
		getDragEl: function () {
			return Ext.getDom(this.dragElId);
		},

		/**
		* Sets up the DragDrop object.  Must be called in the constructor of any
		* Ext.dd.DragDrop subclass
		* @method init
		* @param id the id of the linked element
		* @param {String} sGroup the group of related items
		* @param {object} config configuration attributes
		*/
		init: function (id, sGroup, config) {
			this.initTarget(id, sGroup, config);
			Event.on(this.id, "mousedown", this.handleMouseDown, this);
			// Event.on(this.id, "selectstart", Event.preventDefault);
		},

		/**
		* Initializes Targeting functionality only... the object does not
		* get a mousedown handler.
		* @method initTarget
		* @param id the id of the linked element
		* @param {String} sGroup the group of related items
		* @param {object} config configuration attributes
		*/
		initTarget: function (id, sGroup, config) {

			// configuration attributes
			this.config = config || {};

			// create a local reference to the drag and drop manager
			this.DDM = Ext.dd.DDM;
			// initialize the groups array
			this.groups = {};

			// assume that we have an element reference instead of an id if the
			// parameter is not a string
			if (typeof id !== "string") {
				id = Ext.id(id);
			}

			// set the id
			this.id = id;

			// add to an interaction group
			this.addToGroup((sGroup) ? sGroup : "default");

			// We don't want to register this as the handle with the manager
			// so we just set the id rather than calling the setter.
			this.handleElId = id;

			// the linked element is the element that gets dragged by default
			this.setDragElId(id);

			// by default, clicked anchors will not start drag operations.
			this.invalidHandleTypes = { A: "A" };
			this.invalidHandleIds = {};
			this.invalidHandleClasses = [];

			this.applyConfig();

			this.handleOnAvailable();
		},

		/**
		* Applies the configuration parameters that were passed into the constructor.
		* This is supposed to happen at each level through the inheritance chain.  So
		* a DDProxy implentation will execute apply config on DDProxy, DD, and
		* DragDrop in order to get all of the parameters that are available in
		* each object.
		* @method applyConfig
		*/
		applyConfig: function () {

			// configurable properties:
			//    padding, isTarget, maintainOffset, primaryButtonOnly
			this.padding = this.config.padding || [0, 0, 0, 0];
			this.isTarget = (this.config.isTarget !== false);
			this.maintainOffset = (this.config.maintainOffset);
			this.primaryButtonOnly = (this.config.primaryButtonOnly !== false);

		},

		/**
		* Executed when the linked element is available
		* @method handleOnAvailable
		* @private
		*/
		handleOnAvailable: function () {
			this.available = true;
			this.resetConstraints();
			this.onAvailable();
		},

		/**
		* Configures the padding for the target zone in px.  Effectively expands
		* (or reduces) the virtual object size for targeting calculations.
		* Supports css-style shorthand; if only one parameter is passed, all sides
		* will have that padding, and if only two are passed, the top and bottom
		* will have the first param, the left and right the second.
		* @method setPadding
		* @param {int} iTop    Top pad
		* @param {int} iRight  Right pad
		* @param {int} iBot    Bot pad
		* @param {int} iLeft   Left pad
		*/
		setPadding: function (iTop, iRight, iBot, iLeft) {
			// this.padding = [iLeft, iRight, iTop, iBot];
			if (!iRight && 0 !== iRight) {
				this.padding = [iTop, iTop, iTop, iTop];
			} else if (!iBot && 0 !== iBot) {
				this.padding = [iTop, iRight, iTop, iRight];
			} else {
				this.padding = [iTop, iRight, iBot, iLeft];
			}
		},

		/**
		* Stores the initial placement of the linked element.
		* @method setInitPosition
		* @param {int} diffX   the X offset, default 0
		* @param {int} diffY   the Y offset, default 0
		*/
		setInitPosition: function (diffX, diffY) {
			var el = this.getEl();

			if (!this.DDM.verifyEl(el)) {
				return;
			}

			var dx = diffX || 0;
			var dy = diffY || 0;

			var p = Dom.getXY(el);

			this.initPageX = p[0] - dx;
			this.initPageY = p[1] - dy;

			this.lastPageX = p[0];
			this.lastPageY = p[1];

			this.setStartPosition(p);
		},

		/**
		* Sets the start position of the element.  This is set when the obj
		* is initialized, the reset when a drag is started.
		* @method setStartPosition
		* @param pos current position (from previous lookup)
		* @private
		*/
		setStartPosition: function (pos) {
			var p = pos || Dom.getXY(this.getEl());
			this.deltaSetXY = null;

			this.startPageX = p[0];
			this.startPageY = p[1];
		},

		/**
		* Add this instance to a group of related drag/drop objects.  All
		* instances belong to at least one group, and can belong to as many
		* groups as needed.
		* @method addToGroup
		* @param sGroup {string} the name of the group
		*/
		addToGroup: function (sGroup) {
			this.groups[sGroup] = true;
			this.DDM.regDragDrop(this, sGroup);
		},

		/**
		* Remove's this instance from the supplied interaction group
		* @method removeFromGroup
		* @param {string}  sGroup  The group to drop
		*/
		removeFromGroup: function (sGroup) {
			if (this.groups[sGroup]) {
				delete this.groups[sGroup];
			}

			this.DDM.removeDDFromGroup(this, sGroup);
		},

		/**
		* Allows you to specify that an element other than the linked element
		* will be moved with the cursor during a drag
		* @method setDragElId
		* @param id {string} the id of the element that will be used to initiate the drag
		*/
		setDragElId: function (id) {
			this.dragElId = id;
		},

		/**
		* Allows you to specify a child of the linked element that should be
		* used to initiate the drag operation.  An example of this would be if
		* you have a content div with text and links.  Clicking anywhere in the
		* content area would normally start the drag operation.  Use this method
		* to specify that an element inside of the content div is the element
		* that starts the drag operation.
		* @method setHandleElId
		* @param id {string} the id of the element that will be used to
		* initiate the drag.
		*/
		setHandleElId: function (id) {
			if (typeof id !== "string") {
				id = Ext.id(id);
			}
			this.handleElId = id;
			this.DDM.regHandle(this.id, id);
		},

		/**
		* Allows you to set an element outside of the linked element as a drag
		* handle
		* @method setOuterHandleElId
		* @param id the id of the element that will be used to initiate the drag
		*/
		setOuterHandleElId: function (id) {
			if (typeof id !== "string") {
				id = Ext.id(id);
			}
			Event.on(id, "mousedown",
                this.handleMouseDown, this);
			this.setHandleElId(id);

			this.hasOuterHandles = true;
		},

		/**
		* Remove all drag and drop hooks for this element
		* @method unreg
		*/
		unreg: function () {
			Event.un(this.id, "mousedown",
                this.handleMouseDown);
			this._domRef = null;
			this.DDM._remove(this);
		},

		destroy: function () {
			this.unreg();
		},

		/**
		* Returns true if this instance is locked, or the drag drop mgr is locked
		* (meaning that all drag/drop is disabled on the page.)
		* @method isLocked
		* @return {boolean} true if this obj or all drag/drop is locked, else
		* false
		*/
		isLocked: function () {
			return (this.DDM.isLocked() || this.locked);
		},

		/**
		* Fired when this object is clicked
		* @method handleMouseDown
		* @param {Event} e
		* @param {Ext.dd.DragDrop} oDD the clicked dd object (this dd obj)
		* @private
		*/
		handleMouseDown: function (e, oDD) {
			if (this.primaryButtonOnly && e.button != 0) {
				return;
			}

			if (this.isLocked()) {
				return;
			}

			this.DDM.refreshCache(this.groups);

			var pt = new Ext.lib.Point(Ext.lib.Event.getPageX(e), Ext.lib.Event.getPageY(e));
			if (!this.hasOuterHandles && !this.DDM.isOverTarget(pt, this)) {
			} else {
				if (this.clickValidator(e)) {

					// set the initial element position
					this.setStartPosition();

					this.b4MouseDown(e);
					this.onMouseDown(e);

					this.DDM.handleMouseDown(e, this);

					this.DDM.stopEvent(e);
				} else {


				}
			}
		},

		clickValidator: function (e) {
			var target = e.getTarget();
			return (this.isValidHandleChild(target) &&
                    (this.id == this.handleElId ||
                        this.DDM.handleWasClicked(target, this.id)));
		},

		/**
		* Allows you to specify a tag name that should not start a drag operation
		* when clicked.  This is designed to facilitate embedding links within a
		* drag handle that do something other than start the drag.
		* @method addInvalidHandleType
		* @param {string} tagName the type of element to exclude
		*/
		addInvalidHandleType: function (tagName) {
			var type = tagName.toUpperCase();
			this.invalidHandleTypes[type] = type;
		},

		/**
		* Lets you to specify an element id for a child of a drag handle
		* that should not initiate a drag
		* @method addInvalidHandleId
		* @param {string} id the element id of the element you wish to ignore
		*/
		addInvalidHandleId: function (id) {
			if (typeof id !== "string") {
				id = Ext.id(id);
			}
			this.invalidHandleIds[id] = id;
		},

		/**
		* Lets you specify a css class of elements that will not initiate a drag
		* @method addInvalidHandleClass
		* @param {string} cssClass the class of the elements you wish to ignore
		*/
		addInvalidHandleClass: function (cssClass) {
			this.invalidHandleClasses.push(cssClass);
		},

		/**
		* Unsets an excluded tag name set by addInvalidHandleType
		* @method removeInvalidHandleType
		* @param {string} tagName the type of element to unexclude
		*/
		removeInvalidHandleType: function (tagName) {
			var type = tagName.toUpperCase();
			// this.invalidHandleTypes[type] = null;
			delete this.invalidHandleTypes[type];
		},

		/**
		* Unsets an invalid handle id
		* @method removeInvalidHandleId
		* @param {string} id the id of the element to re-enable
		*/
		removeInvalidHandleId: function (id) {
			if (typeof id !== "string") {
				id = Ext.id(id);
			}
			delete this.invalidHandleIds[id];
		},

		/**
		* Unsets an invalid css class
		* @method removeInvalidHandleClass
		* @param {string} cssClass the class of the element(s) you wish to
		* re-enable
		*/
		removeInvalidHandleClass: function (cssClass) {
			for (var i = 0, len = this.invalidHandleClasses.length; i < len; ++i) {
				if (this.invalidHandleClasses[i] == cssClass) {
					delete this.invalidHandleClasses[i];
				}
			}
		},

		/**
		* Checks the tag exclusion list to see if this click should be ignored
		* @method isValidHandleChild
		* @param {HTMLElement} node the HTMLElement to evaluate
		* @return {boolean} true if this is a valid tag type, false if not
		*/
		isValidHandleChild: function (node) {

			var valid = true;
			// var n = (node.nodeName == "#text") ? node.parentNode : node;
			var nodeName;
			try {
				nodeName = node.nodeName.toUpperCase();
			} catch (e) {
				nodeName = node.nodeName;
			}
			valid = valid && !this.invalidHandleTypes[nodeName];
			valid = valid && !this.invalidHandleIds[node.id];

			for (var i = 0, len = this.invalidHandleClasses.length; valid && i < len; ++i) {
				valid = !Ext.fly(node).hasClass(this.invalidHandleClasses[i]);
			}


			return valid;

		},

		/**
		* Create the array of horizontal tick marks if an interval was specified
		* in setXConstraint().
		* @method setXTicks
		* @private
		*/
		setXTicks: function (iStartX, iTickSize) {
			this.xTicks = [];
			this.xTickSize = iTickSize;

			var tickMap = {};

			for (var i = this.initPageX; i >= this.minX; i = i - iTickSize) {
				if (!tickMap[i]) {
					this.xTicks[this.xTicks.length] = i;
					tickMap[i] = true;
				}
			}

			for (i = this.initPageX; i <= this.maxX; i = i + iTickSize) {
				if (!tickMap[i]) {
					this.xTicks[this.xTicks.length] = i;
					tickMap[i] = true;
				}
			}

			this.xTicks.sort(this.DDM.numericSort);
		},

		/**
		* Create the array of vertical tick marks if an interval was specified in
		* setYConstraint().
		* @method setYTicks
		* @private
		*/
		setYTicks: function (iStartY, iTickSize) {
			this.yTicks = [];
			this.yTickSize = iTickSize;

			var tickMap = {};

			for (var i = this.initPageY; i >= this.minY; i = i - iTickSize) {
				if (!tickMap[i]) {
					this.yTicks[this.yTicks.length] = i;
					tickMap[i] = true;
				}
			}

			for (i = this.initPageY; i <= this.maxY; i = i + iTickSize) {
				if (!tickMap[i]) {
					this.yTicks[this.yTicks.length] = i;
					tickMap[i] = true;
				}
			}

			this.yTicks.sort(this.DDM.numericSort);
		},

		/**
		* By default, the element can be dragged any place on the screen.  Use
		* this method to limit the horizontal travel of the element.  Pass in
		* 0,0 for the parameters if you want to lock the drag to the y axis.
		* @method setXConstraint
		* @param {int} iLeft the number of pixels the element can move to the left
		* @param {int} iRight the number of pixels the element can move to the
		* right
		* @param {int} iTickSize optional parameter for specifying that the
		* element
		* should move iTickSize pixels at a time.
		*/
		setXConstraint: function (iLeft, iRight, iTickSize) {
			this.leftConstraint = iLeft;
			this.rightConstraint = iRight;

			this.minX = this.initPageX - iLeft;
			this.maxX = this.initPageX + iRight;
			if (iTickSize) { this.setXTicks(this.initPageX, iTickSize); }

			this.constrainX = true;
		},

		/**
		* Clears any constraints applied to this instance.  Also clears ticks
		* since they can't exist independent of a constraint at this time.
		* @method clearConstraints
		*/
		clearConstraints: function () {
			this.constrainX = false;
			this.constrainY = false;
			this.clearTicks();
		},

		/**
		* Clears any tick interval defined for this instance
		* @method clearTicks
		*/
		clearTicks: function () {
			this.xTicks = null;
			this.yTicks = null;
			this.xTickSize = 0;
			this.yTickSize = 0;
		},

		/**
		* By default, the element can be dragged any place on the screen.  Set
		* this to limit the vertical travel of the element.  Pass in 0,0 for the
		* parameters if you want to lock the drag to the x axis.
		* @method setYConstraint
		* @param {int} iUp the number of pixels the element can move up
		* @param {int} iDown the number of pixels the element can move down
		* @param {int} iTickSize optional parameter for specifying that the
		* element should move iTickSize pixels at a time.
		*/
		setYConstraint: function (iUp, iDown, iTickSize) {
			this.topConstraint = iUp;
			this.bottomConstraint = iDown;

			this.minY = this.initPageY - iUp;
			this.maxY = this.initPageY + iDown;
			if (iTickSize) { this.setYTicks(this.initPageY, iTickSize); }

			this.constrainY = true;

		},

		/**
		* resetConstraints must be called if you manually reposition a dd element.
		* @method resetConstraints
		* @param {boolean} maintainOffset
		*/
		resetConstraints: function () {
			// Maintain offsets if necessary
			if (this.initPageX || this.initPageX === 0) {
				// figure out how much this thing has moved
				var dx = (this.maintainOffset) ? this.lastPageX - this.initPageX : 0;
				var dy = (this.maintainOffset) ? this.lastPageY - this.initPageY : 0;

				this.setInitPosition(dx, dy);

				// This is the first time we have detected the element's position
			} else {
				this.setInitPosition();
			}

			if (this.constrainX) {
				this.setXConstraint(this.leftConstraint,
                                 this.rightConstraint,
                                 this.xTickSize);
			}

			if (this.constrainY) {
				this.setYConstraint(this.topConstraint,
                                 this.bottomConstraint,
                                 this.yTickSize);
			}
		},

		/**
		* Normally the drag element is moved pixel by pixel, but we can specify
		* that it move a number of pixels at a time.  This method resolves the
		* location when we have it set up like this.
		* @method getTick
		* @param {int} val where we want to place the object
		* @param {int[]} tickArray sorted array of valid points
		* @return {int} the closest tick
		* @private
		*/
		getTick: function (val, tickArray) {
			if (!tickArray) {
				// If tick interval is not defined, it is effectively 1 pixel,
				// so we return the value passed to us.
				return val;
			} else if (tickArray[0] >= val) {
				// The value is lower than the first tick, so we return the first
				// tick.
				return tickArray[0];
			} else {
				for (var i = 0, len = tickArray.length; i < len; ++i) {
					var next = i + 1;
					if (tickArray[next] && tickArray[next] >= val) {
						var diff1 = val - tickArray[i];
						var diff2 = tickArray[next] - val;
						return (diff2 > diff1) ? tickArray[i] : tickArray[next];
					}
				}

				// The value is larger than the last tick, so we return the last
				// tick.
				return tickArray[tickArray.length - 1];
			}
		},

		/**
		* toString method
		* @method toString
		* @return {string} string representation of the dd obj
		*/
		toString: function () {
			return ("DragDrop " + this.id);
		}

	};

})();
/*
* The drag and drop utility provides a framework for building drag and drop
* applications.  In addition to enabling drag and drop for specific elements,
* the drag and drop elements are tracked by the manager class, and the
* interactions between the various elements are tracked during the drag and
* the implementing code is notified about these important moments.
*/

// Only load the library once.  Rewriting the manager class would orphan
// existing drag and drop instances.
if (!Ext.dd.DragDropMgr) {

	/**
	* @class Ext.dd.DragDropMgr
	* DragDropMgr is a singleton that tracks the element interaction for
	* all DragDrop items in the window.  Generally, you will not call
	* this class directly, but it does have helper methods that could
	* be useful in your DragDrop implementations.
	* @singleton
	*/
	Ext.dd.DragDropMgr = function () {

		var Event = Ext.EventManager;

		return {

			/**
			* Two dimensional Array of registered DragDrop objects.  The first
			* dimension is the DragDrop item group, the second the DragDrop
			* object.
			* @property ids
			* @type String[]
			* @private
			* @static
			*/
			ids: {},

			/**
			* Array of element ids defined as drag handles.  Used to determine
			* if the element that generated the mousedown event is actually the
			* handle and not the html element itself.
			* @property handleIds
			* @type String[]
			* @private
			* @static
			*/
			handleIds: {},

			/**
			* the DragDrop object that is currently being dragged
			* @property dragCurrent
			* @type DragDrop
			* @private
			* @static
			**/
			dragCurrent: null,

			/**
			* the DragDrop object(s) that are being hovered over
			* @property dragOvers
			* @type Array
			* @private
			* @static
			*/
			dragOvers: {},

			/**
			* the X distance between the cursor and the object being dragged
			* @property deltaX
			* @type int
			* @private
			* @static
			*/
			deltaX: 0,

			/**
			* the Y distance between the cursor and the object being dragged
			* @property deltaY
			* @type int
			* @private
			* @static
			*/
			deltaY: 0,

			/**
			* Flag to determine if we should prevent the default behavior of the
			* events we define. By default this is true, but this can be set to
			* false if you need the default behavior (not recommended)
			* @property preventDefault
			* @type boolean
			* @static
			*/
			preventDefault: true,

			/**
			* Flag to determine if we should stop the propagation of the events
			* we generate. This is true by default but you may want to set it to
			* false if the html element contains other features that require the
			* mouse click.
			* @property stopPropagation
			* @type boolean
			* @static
			*/
			stopPropagation: true,

			/**
			* Internal flag that is set to true when drag and drop has been
			* intialized
			* @property initialized
			* @private
			* @static
			*/
			initialized: false,

			/**
			* All drag and drop can be disabled.
			* @property locked
			* @private
			* @static
			*/
			locked: false,

			/**
			* Called the first time an element is registered.
			* @method init
			* @private
			* @static
			*/
			init: function () {
				this.initialized = true;
			},

			/**
			* In point mode, drag and drop interaction is defined by the
			* location of the cursor during the drag/drop
			* @property POINT
			* @type int
			* @static
			*/
			POINT: 0,

			/**
			* In intersect mode, drag and drop interaction is defined by the
			* overlap of two or more drag and drop objects.
			* @property INTERSECT
			* @type int
			* @static
			*/
			INTERSECT: 1,

			/**
			* The current drag and drop mode.  Default: POINT
			* @property mode
			* @type int
			* @static
			*/
			mode: 0,

			/**
			* Runs method on all drag and drop objects
			* @method _execOnAll
			* @private
			* @static
			*/
			_execOnAll: function (sMethod, args) {
				for (var i in this.ids) {
					for (var j in this.ids[i]) {
						var oDD = this.ids[i][j];
						if (!this.isTypeOfDD(oDD)) {
							continue;
						}
						oDD[sMethod].apply(oDD, args);
					}
				}
			},

			/**
			* Drag and drop initialization.  Sets up the global event handlers
			* @method _onLoad
			* @private
			* @static
			*/
			_onLoad: function () {

				this.init();


				Event.on(document, "mouseup", this.handleMouseUp, this, true);
				Event.on(document, "mousemove", this.handleMouseMove, this, true);
				Event.on(window, "unload", this._onUnload, this, true);
				Event.on(window, "resize", this._onResize, this, true);
				// Event.on(window,   "mouseout",    this._test);

			},

			/**
			* Reset constraints on all drag and drop objs
			* @method _onResize
			* @private
			* @static
			*/
			_onResize: function (e) {
				this._execOnAll("resetConstraints", []);
			},

			/**
			* Lock all drag and drop functionality
			* @method lock
			* @static
			*/
			lock: function () { this.locked = true; },

			/**
			* Unlock all drag and drop functionality
			* @method unlock
			* @static
			*/
			unlock: function () { this.locked = false; },

			/**
			* Is drag and drop locked?
			* @method isLocked
			* @return {boolean} True if drag and drop is locked, false otherwise.
			* @static
			*/
			isLocked: function () { return this.locked; },

			/**
			* Location cache that is set for all drag drop objects when a drag is
			* initiated, cleared when the drag is finished.
			* @property locationCache
			* @private
			* @static
			*/
			locationCache: {},

			/**
			* Set useCache to false if you want to force object the lookup of each
			* drag and drop linked element constantly during a drag.
			* @property useCache
			* @type boolean
			* @static
			*/
			useCache: true,

			/**
			* The number of pixels that the mouse needs to move after the
			* mousedown before the drag is initiated.  Default=3;
			* @property clickPixelThresh
			* @type int
			* @static
			*/
			clickPixelThresh: 3,

			/**
			* The number of milliseconds after the mousedown event to initiate the
			* drag if we don't get a mouseup event. Default=350
			* @property clickTimeThresh
			* @type int
			* @static
			*/
			clickTimeThresh: 350,

			/**
			* Flag that indicates that either the drag pixel threshold or the
			* mousdown time threshold has been met
			* @property dragThreshMet
			* @type boolean
			* @private
			* @static
			*/
			dragThreshMet: false,

			/**
			* Timeout used for the click time threshold
			* @property clickTimeout
			* @type Object
			* @private
			* @static
			*/
			clickTimeout: null,

			/**
			* The X position of the mousedown event stored for later use when a
			* drag threshold is met.
			* @property startX
			* @type int
			* @private
			* @static
			*/
			startX: 0,

			/**
			* The Y position of the mousedown event stored for later use when a
			* drag threshold is met.
			* @property startY
			* @type int
			* @private
			* @static
			*/
			startY: 0,

			/**
			* Each DragDrop instance must be registered with the DragDropMgr.
			* This is executed in DragDrop.init()
			* @method regDragDrop
			* @param {DragDrop} oDD the DragDrop object to register
			* @param {String} sGroup the name of the group this element belongs to
			* @static
			*/
			regDragDrop: function (oDD, sGroup) {
				if (!this.initialized) { this.init(); }

				if (!this.ids[sGroup]) {
					this.ids[sGroup] = {};
				}
				this.ids[sGroup][oDD.id] = oDD;
			},

			/**
			* Removes the supplied dd instance from the supplied group. Executed
			* by DragDrop.removeFromGroup, so don't call this function directly.
			* @method removeDDFromGroup
			* @private
			* @static
			*/
			removeDDFromGroup: function (oDD, sGroup) {
				if (!this.ids[sGroup]) {
					this.ids[sGroup] = {};
				}

				var obj = this.ids[sGroup];
				if (obj && obj[oDD.id]) {
					delete obj[oDD.id];
				}
			},

			/**
			* Unregisters a drag and drop item.  This is executed in
			* DragDrop.unreg, use that method instead of calling this directly.
			* @method _remove
			* @private
			* @static
			*/
			_remove: function (oDD) {
				for (var g in oDD.groups) {
					if (g && this.ids[g] && this.ids[g][oDD.id]) {
						delete this.ids[g][oDD.id];
					}
				}
				delete this.handleIds[oDD.id];
			},

			/**
			* Each DragDrop handle element must be registered.  This is done
			* automatically when executing DragDrop.setHandleElId()
			* @method regHandle
			* @param {String} sDDId the DragDrop id this element is a handle for
			* @param {String} sHandleId the id of the element that is the drag
			* handle
			* @static
			*/
			regHandle: function (sDDId, sHandleId) {
				if (!this.handleIds[sDDId]) {
					this.handleIds[sDDId] = {};
				}
				this.handleIds[sDDId][sHandleId] = sHandleId;
			},

			/**
			* Utility function to determine if a given element has been
			* registered as a drag drop item.
			* @method isDragDrop
			* @param {String} id the element id to check
			* @return {boolean} true if this element is a DragDrop item,
			* false otherwise
			* @static
			*/
			isDragDrop: function (id) {
				return (this.getDDById(id)) ? true : false;
			},

			/**
			* Returns the drag and drop instances that are in all groups the
			* passed in instance belongs to.
			* @method getRelated
			* @param {DragDrop} p_oDD the obj to get related data for
			* @param {boolean} bTargetsOnly if true, only return targetable objs
			* @return {DragDrop[]} the related instances
			* @static
			*/
			getRelated: function (p_oDD, bTargetsOnly) {
				var oDDs = [];
				for (var i in p_oDD.groups) {
					for (var j in this.ids[i]) {
						var dd = this.ids[i][j];
						if (!this.isTypeOfDD(dd)) {
							continue;
						}
						if (!bTargetsOnly || dd.isTarget) {
							oDDs[oDDs.length] = dd;
						}
					}
				}

				return oDDs;
			},

			/**
			* Returns true if the specified dd target is a legal target for
			* the specifice drag obj
			* @method isLegalTarget
			* @param {DragDrop} oDD the drag obj
			* @param {DragDrop} oTargetDD the target
			* @return {boolean} true if the target is a legal target for the
			* dd obj
			* @static
			*/
			isLegalTarget: function (oDD, oTargetDD) {
				var targets = this.getRelated(oDD, true);
				for (var i = 0, len = targets.length; i < len; ++i) {
					if (targets[i].id == oTargetDD.id) {
						return true;
					}
				}

				return false;
			},

			/**
			* My goal is to be able to transparently determine if an object is
			* typeof DragDrop, and the exact subclass of DragDrop.  typeof
			* returns "object", oDD.constructor.toString() always returns
			* "DragDrop" and not the name of the subclass.  So for now it just
			* evaluates a well-known variable in DragDrop.
			* @method isTypeOfDD
			* @param {Object} the object to evaluate
			* @return {boolean} true if typeof oDD = DragDrop
			* @static
			*/
			isTypeOfDD: function (oDD) {
				return (oDD && oDD.__ygDragDrop);
			},

			/**
			* Utility function to determine if a given element has been
			* registered as a drag drop handle for the given Drag Drop object.
			* @method isHandle
			* @param {String} id the element id to check
			* @return {boolean} true if this element is a DragDrop handle, false
			* otherwise
			* @static
			*/
			isHandle: function (sDDId, sHandleId) {
				return (this.handleIds[sDDId] &&
                            this.handleIds[sDDId][sHandleId]);
			},

			/**
			* Returns the DragDrop instance for a given id
			* @method getDDById
			* @param {String} id the id of the DragDrop object
			* @return {DragDrop} the drag drop object, null if it is not found
			* @static
			*/
			getDDById: function (id) {
				for (var i in this.ids) {
					if (this.ids[i][id]) {
						return this.ids[i][id];
					}
				}
				return null;
			},

			/**
			* Fired after a registered DragDrop object gets the mousedown event.
			* Sets up the events required to track the object being dragged
			* @method handleMouseDown
			* @param {Event} e the event
			* @param oDD the DragDrop object being dragged
			* @private
			* @static
			*/
			handleMouseDown: function (e, oDD) {
				if (Ext.QuickTips) {
					Ext.QuickTips.disable();
				}
				if (this.dragCurrent) {
					// the original browser mouseup wasn't handled (e.g. outside FF browser window)
					// so clean up first to avoid breaking the next drag
					this.handleMouseUp(e);
				}

				this.currentTarget = e.getTarget();
				this.dragCurrent = oDD;

				var el = oDD.getEl();

				// track start position
				this.startX = e.getPageX();
				this.startY = e.getPageY();

				this.deltaX = this.startX - el.offsetLeft;
				this.deltaY = this.startY - el.offsetTop;

				this.dragThreshMet = false;

				this.clickTimeout = setTimeout(
                    function () {
                    	var DDM = Ext.dd.DDM;
                    	DDM.startDrag(DDM.startX, DDM.startY);
                    },
                    this.clickTimeThresh);
			},

			/**
			* Fired when either the drag pixel threshol or the mousedown hold
			* time threshold has been met.
			* @method startDrag
			* @param x {int} the X position of the original mousedown
			* @param y {int} the Y position of the original mousedown
			* @static
			*/
			startDrag: function (x, y) {
				clearTimeout(this.clickTimeout);
				if (this.dragCurrent) {
					this.dragCurrent.b4StartDrag(x, y);
					this.dragCurrent.startDrag(x, y);
				}
				this.dragThreshMet = true;
			},

			/**
			* Internal function to handle the mouseup event.  Will be invoked
			* from the context of the document.
			* @method handleMouseUp
			* @param {Event} e the event
			* @private
			* @static
			*/
			handleMouseUp: function (e) {

				if (Ext.QuickTips) {
					Ext.QuickTips.enable();
				}
				if (!this.dragCurrent) {
					return;
				}

				clearTimeout(this.clickTimeout);

				if (this.dragThreshMet) {
					this.fireEvents(e, true);
				} else {
				}

				this.stopDrag(e);

				this.stopEvent(e);
			},

			/**
			* Utility to stop event propagation and event default, if these
			* features are turned on.
			* @method stopEvent
			* @param {Event} e the event as returned by this.getEvent()
			* @static
			*/
			stopEvent: function (e) {
				if (this.stopPropagation) {
					e.stopPropagation();
				}

				if (this.preventDefault) {
					e.preventDefault();
				}
			},

			/**
			* Internal function to clean up event handlers after the drag
			* operation is complete
			* @method stopDrag
			* @param {Event} e the event
			* @private
			* @static
			*/
			stopDrag: function (e) {
				// Fire the drag end event for the item that was dragged
				if (this.dragCurrent) {
					if (this.dragThreshMet) {
						this.dragCurrent.b4EndDrag(e);
						this.dragCurrent.endDrag(e);
					}

					this.dragCurrent.onMouseUp(e);
				}

				this.dragCurrent = null;
				this.dragOvers = {};
			},

			/**
			* Internal function to handle the mousemove event.  Will be invoked
			* from the context of the html element.
			*
			* @TODO figure out what we can do about mouse events lost when the
			* user drags objects beyond the window boundary.  Currently we can
			* detect this in internet explorer by verifying that the mouse is
			* down during the mousemove event.  Firefox doesn't give us the
			* button state on the mousemove event.
			* @method handleMouseMove
			* @param {Event} e the event
			* @private
			* @static
			*/
			handleMouseMove: function (e) {
				if (!this.dragCurrent) {
					return true;
				}
				// var button = e.which || e.button;

				// check for IE mouseup outside of page boundary
				if (Ext.isIE && (e.button !== 0 && e.button !== 1 && e.button !== 2)) {
					this.stopEvent(e);
					return this.handleMouseUp(e);
				}

				if (!this.dragThreshMet) {
					var diffX = Math.abs(this.startX - e.getPageX());
					var diffY = Math.abs(this.startY - e.getPageY());
					if (diffX > this.clickPixelThresh ||
                            diffY > this.clickPixelThresh) {
						this.startDrag(this.startX, this.startY);
					}
				}

				if (this.dragThreshMet) {
					this.dragCurrent.b4Drag(e);
					this.dragCurrent.onDrag(e);
					if (!this.dragCurrent.moveOnly) {
						this.fireEvents(e, false);
					}
				}

				this.stopEvent(e);

				return true;
			},

			/**
			* Iterates over all of the DragDrop elements to find ones we are
			* hovering over or dropping on
			* @method fireEvents
			* @param {Event} e the event
			* @param {boolean} isDrop is this a drop op or a mouseover op?
			* @private
			* @static
			*/
			fireEvents: function (e, isDrop) {
				var dc = this.dragCurrent;

				// If the user did the mouse up outside of the window, we could
				// get here even though we have ended the drag.
				if (!dc || dc.isLocked()) {
					return;
				}

				var pt = e.getPoint();

				// cache the previous dragOver array
				var oldOvers = [];

				var outEvts = [];
				var overEvts = [];
				var dropEvts = [];
				var enterEvts = [];

				// Check to see if the object(s) we were hovering over is no longer
				// being hovered over so we can fire the onDragOut event
				for (var i in this.dragOvers) {

					var ddo = this.dragOvers[i];

					if (!this.isTypeOfDD(ddo)) {
						continue;
					}

					if (!this.isOverTarget(pt, ddo, this.mode)) {
						outEvts.push(ddo);
					}

					oldOvers[i] = true;
					delete this.dragOvers[i];
				}

				for (var sGroup in dc.groups) {

					if ("string" != typeof sGroup) {
						continue;
					}

					for (i in this.ids[sGroup]) {
						var oDD = this.ids[sGroup][i];
						if (!this.isTypeOfDD(oDD)) {
							continue;
						}

						if (oDD.isTarget && !oDD.isLocked() && ((oDD != dc) || (dc.ignoreSelf === false))) {
							if (this.isOverTarget(pt, oDD, this.mode)) {
								// look for drop interactions
								if (isDrop) {
									dropEvts.push(oDD);
									// look for drag enter and drag over interactions
								} else {

									// initial drag over: dragEnter fires
									if (!oldOvers[oDD.id]) {
										enterEvts.push(oDD);
										// subsequent drag overs: dragOver fires
									} else {
										overEvts.push(oDD);
									}

									this.dragOvers[oDD.id] = oDD;
								}
							}
						}
					}
				}

				if (this.mode) {
					if (outEvts.length) {
						dc.b4DragOut(e, outEvts);
						dc.onDragOut(e, outEvts);
					}

					if (enterEvts.length) {
						dc.onDragEnter(e, enterEvts);
					}

					if (overEvts.length) {
						dc.b4DragOver(e, overEvts);
						dc.onDragOver(e, overEvts);
					}

					if (dropEvts.length) {
						dc.b4DragDrop(e, dropEvts);
						dc.onDragDrop(e, dropEvts);
					}

				} else {
					// fire dragout events
					var len = 0;
					for (i = 0, len = outEvts.length; i < len; ++i) {
						dc.b4DragOut(e, outEvts[i].id);
						dc.onDragOut(e, outEvts[i].id);
					}

					// fire enter events
					for (i = 0, len = enterEvts.length; i < len; ++i) {
						// dc.b4DragEnter(e, oDD.id);
						dc.onDragEnter(e, enterEvts[i].id);
					}

					// fire over events
					for (i = 0, len = overEvts.length; i < len; ++i) {
						dc.b4DragOver(e, overEvts[i].id);
						dc.onDragOver(e, overEvts[i].id);
					}

					// fire drop events
					for (i = 0, len = dropEvts.length; i < len; ++i) {
						dc.b4DragDrop(e, dropEvts[i].id);
						dc.onDragDrop(e, dropEvts[i].id);
					}

				}

				// notify about a drop that did not find a target
				if (isDrop && !dropEvts.length) {
					dc.onInvalidDrop(e);
				}

			},

			/**
			* Helper function for getting the best match from the list of drag
			* and drop objects returned by the drag and drop events when we are
			* in INTERSECT mode.  It returns either the first object that the
			* cursor is over, or the object that has the greatest overlap with
			* the dragged element.
			* @method getBestMatch
			* @param  {DragDrop[]} dds The array of drag and drop objects
			* targeted
			* @return {DragDrop}       The best single match
			* @static
			*/
			getBestMatch: function (dds) {
				var winner = null;
				// Return null if the input is not what we expect
				//if (!dds || !dds.length || dds.length == 0) {
				// winner = null;
				// If there is only one item, it wins
				//} else if (dds.length == 1) {

				var len = dds.length;

				if (len == 1) {
					winner = dds[0];
				} else {
					// Loop through the targeted items
					for (var i = 0; i < len; ++i) {
						var dd = dds[i];
						// If the cursor is over the object, it wins.  If the
						// cursor is over multiple matches, the first one we come
						// to wins.
						if (dd.cursorIsOver) {
							winner = dd;
							break;
							// Otherwise the object with the most overlap wins
						} else {
							if (!winner ||
                            winner.overlap.getArea() < dd.overlap.getArea()) {
								winner = dd;
							}
						}
					}
				}

				return winner;
			},

			/**
			* Refreshes the cache of the top-left and bottom-right points of the
			* drag and drop objects in the specified group(s).  This is in the
			* format that is stored in the drag and drop instance, so typical
			* usage is:
			* <code>
			* Ext.dd.DragDropMgr.refreshCache(ddinstance.groups);
			* </code>
			* Alternatively:
			* <code>
			* Ext.dd.DragDropMgr.refreshCache({group1:true, group2:true});
			* </code>
			* @TODO this really should be an indexed array.  Alternatively this
			* method could accept both.
			* @method refreshCache
			* @param {Object} groups an associative array of groups to refresh
			* @static
			*/
			refreshCache: function (groups) {
				for (var sGroup in groups) {
					if ("string" != typeof sGroup) {
						continue;
					}
					for (var i in this.ids[sGroup]) {
						var oDD = this.ids[sGroup][i];

						if (this.isTypeOfDD(oDD)) {
							// if (this.isTypeOfDD(oDD) && oDD.isTarget) {
							var loc = this.getLocation(oDD);
							if (loc) {
								this.locationCache[oDD.id] = loc;
							} else {
								delete this.locationCache[oDD.id];
								// this will unregister the drag and drop object if
								// the element is not in a usable state
								// oDD.unreg();
							}
						}
					}
				}
			},

			/**
			* This checks to make sure an element exists and is in the DOM.  The
			* main purpose is to handle cases where innerHTML is used to remove
			* drag and drop objects from the DOM.  IE provides an 'unspecified
			* error' when trying to access the offsetParent of such an element
			* @method verifyEl
			* @param {HTMLElement} el the element to check
			* @return {boolean} true if the element looks usable
			* @static
			*/
			verifyEl: function (el) {
				if (el) {
					var parent;
					if (Ext.isIE) {
						try {
							parent = el.offsetParent;
						} catch (e) { }
					} else {
						parent = el.offsetParent;
					}
					if (parent) {
						return true;
					}
				}

				return false;
			},

			/**
			* Returns a Region object containing the drag and drop element's position
			* and size, including the padding configured for it
			* @method getLocation
			* @param {DragDrop} oDD the drag and drop object to get the
			*                       location for
			* @return {Ext.lib.Region} a Region object representing the total area
			*                             the element occupies, including any padding
			*                             the instance is configured for.
			* @static
			*/
			getLocation: function (oDD) {
				if (!this.isTypeOfDD(oDD)) {
					return null;
				}

				var el = oDD.getEl(), pos, x1, x2, y1, y2, t, r, b, l;

				try {
					pos = Ext.lib.Dom.getXY(el);
				} catch (e) { }

				if (!pos) {
					return null;
				}

				x1 = pos[0];
				x2 = x1 + el.offsetWidth;
				y1 = pos[1];
				y2 = y1 + el.offsetHeight;

				t = y1 - oDD.padding[0];
				r = x2 + oDD.padding[1];
				b = y2 + oDD.padding[2];
				l = x1 - oDD.padding[3];

				return new Ext.lib.Region(t, r, b, l);
			},

			/**
			* Checks the cursor location to see if it over the target
			* @method isOverTarget
			* @param {Ext.lib.Point} pt The point to evaluate
			* @param {DragDrop} oTarget the DragDrop object we are inspecting
			* @return {boolean} true if the mouse is over the target
			* @private
			* @static
			*/
			isOverTarget: function (pt, oTarget, intersect) {
				// use cache if available
				var loc = this.locationCache[oTarget.id];
				if (!loc || !this.useCache) {
					loc = this.getLocation(oTarget);
					this.locationCache[oTarget.id] = loc;

				}

				if (!loc) {
					return false;
				}

				oTarget.cursorIsOver = loc.contains(pt);

				// DragDrop is using this as a sanity check for the initial mousedown
				// in this case we are done.  In POINT mode, if the drag obj has no
				// contraints, we are also done. Otherwise we need to evaluate the
				// location of the target as related to the actual location of the
				// dragged element.
				var dc = this.dragCurrent;
				if (!dc || !dc.getTargetCoord ||
                    (!intersect && !dc.constrainX && !dc.constrainY)) {
					return oTarget.cursorIsOver;
				}

				oTarget.overlap = null;

				// Get the current location of the drag element, this is the
				// location of the mouse event less the delta that represents
				// where the original mousedown happened on the element.  We
				// need to consider constraints and ticks as well.
				var pos = dc.getTargetCoord(pt.x, pt.y);

				var el = dc.getDragEl();
				var curRegion = new Ext.lib.Region(pos.y,
                                                   pos.x + el.offsetWidth,
                                                   pos.y + el.offsetHeight,
                                                   pos.x);

				var overlap = curRegion.intersect(loc);

				if (overlap) {
					oTarget.overlap = overlap;
					return (intersect) ? true : oTarget.cursorIsOver;
				} else {
					return false;
				}
			},

			/**
			* unload event handler
			* @method _onUnload
			* @private
			* @static
			*/
			_onUnload: function (e, me) {
				Ext.dd.DragDropMgr.unregAll();
			},

			/**
			* Cleans up the drag and drop events and objects.
			* @method unregAll
			* @private
			* @static
			*/
			unregAll: function () {

				if (this.dragCurrent) {
					this.stopDrag();
					this.dragCurrent = null;
				}

				this._execOnAll("unreg", []);

				for (var i in this.elementCache) {
					delete this.elementCache[i];
				}

				this.elementCache = {};
				this.ids = {};
			},

			/**
			* A cache of DOM elements
			* @property elementCache
			* @private
			* @static
			*/
			elementCache: {},

			/**
			* Get the wrapper for the DOM element specified
			* @method getElWrapper
			* @param {String} id the id of the element to get
			* @return {Ext.dd.DDM.ElementWrapper} the wrapped element
			* @private
			* @deprecated This wrapper isn't that useful
			* @static
			*/
			getElWrapper: function (id) {
				var oWrapper = this.elementCache[id];
				if (!oWrapper || !oWrapper.el) {
					oWrapper = this.elementCache[id] =
                    new this.ElementWrapper(Ext.getDom(id));
				}
				return oWrapper;
			},

			/**
			* Returns the actual DOM element
			* @method getElement
			* @param {String} id the id of the elment to get
			* @return {Object} The element
			* @deprecated use Ext.lib.Ext.getDom instead
			* @static
			*/
			getElement: function (id) {
				return Ext.getDom(id);
			},

			/**
			* Returns the style property for the DOM element (i.e.,
			* document.getElById(id).style)
			* @method getCss
			* @param {String} id the id of the elment to get
			* @return {Object} The style property of the element
			* @deprecated use Ext.lib.Dom instead
			* @static
			*/
			getCss: function (id) {
				var el = Ext.getDom(id);
				return (el) ? el.style : null;
			},

			/**
			* Inner class for cached elements
			* @class Ext.dd.DragDropMgr.ElementWrapper
			* @for DragDropMgr
			* @private
			* @deprecated
			*/
			ElementWrapper: function (el) {
				/**
				* The element
				* @property el
				*/
				this.el = el || null;
				/**
				* The element id
				* @property id
				*/
				this.id = this.el && el.id;
				/**
				* A reference to the style property
				* @property css
				*/
				this.css = this.el && el.style;
			},

			/**
			* Returns the X position of an html element
			* @method getPosX
			* @param el the element for which to get the position
			* @return {int} the X coordinate
			* @for DragDropMgr
			* @deprecated use Ext.lib.Dom.getX instead
			* @static
			*/
			getPosX: function (el) {
				return Ext.lib.Dom.getX(el);
			},

			/**
			* Returns the Y position of an html element
			* @method getPosY
			* @param el the element for which to get the position
			* @return {int} the Y coordinate
			* @deprecated use Ext.lib.Dom.getY instead
			* @static
			*/
			getPosY: function (el) {
				return Ext.lib.Dom.getY(el);
			},

			/**
			* Swap two nodes.  In IE, we use the native method, for others we
			* emulate the IE behavior
			* @method swapNode
			* @param n1 the first node to swap
			* @param n2 the other node to swap
			* @static
			*/
			swapNode: function (n1, n2) {
				if (n1.swapNode) {
					n1.swapNode(n2);
				} else {
					var p = n2.parentNode;
					var s = n2.nextSibling;

					if (s == n1) {
						p.insertBefore(n1, n2);
					} else if (n2 == n1.nextSibling) {
						p.insertBefore(n2, n1);
					} else {
						n1.parentNode.replaceChild(n2, n1);
						p.insertBefore(n1, s);
					}
				}
			},

			/**
			* Returns the current scroll position
			* @method getScroll
			* @private
			* @static
			*/
			getScroll: function () {
				var t, l, dde = document.documentElement, db = document.body;
				if (dde && (dde.scrollTop || dde.scrollLeft)) {
					t = dde.scrollTop;
					l = dde.scrollLeft;
				} else if (db) {
					t = db.scrollTop;
					l = db.scrollLeft;
				} else {

				}
				return { top: t, left: l };
			},

			/**
			* Returns the specified element style property
			* @method getStyle
			* @param {HTMLElement} el          the element
			* @param {string}      styleProp   the style property
			* @return {string} The value of the style property
			* @deprecated use Ext.lib.Dom.getStyle
			* @static
			*/
			getStyle: function (el, styleProp) {
				return Ext.fly(el).getStyle(styleProp);
			},

			/**
			* Gets the scrollTop
			* @method getScrollTop
			* @return {int} the document's scrollTop
			* @static
			*/
			getScrollTop: function () {
				return this.getScroll().top;
			},

			/**
			* Gets the scrollLeft
			* @method getScrollLeft
			* @return {int} the document's scrollTop
			* @static
			*/
			getScrollLeft: function () {
				return this.getScroll().left;
			},

			/**
			* Sets the x/y position of an element to the location of the
			* target element.
			* @method moveToEl
			* @param {HTMLElement} moveEl      The element to move
			* @param {HTMLElement} targetEl    The position reference element
			* @static
			*/
			moveToEl: function (moveEl, targetEl) {
				var aCoord = Ext.lib.Dom.getXY(targetEl);
				Ext.lib.Dom.setXY(moveEl, aCoord);
			},

			/**
			* Numeric array sort function
			* @method numericSort
			* @static
			*/
			numericSort: function (a, b) {
				return (a - b);
			},

			/**
			* Internal counter
			* @property _timeoutCount
			* @private
			* @static
			*/
			_timeoutCount: 0,

			/**
			* Trying to make the load order less important.  Without this we get
			* an error if this file is loaded before the Event Utility.
			* @method _addListeners
			* @private
			* @static
			*/
			_addListeners: function () {
				var DDM = Ext.dd.DDM;
				if (Ext.lib.Event && document) {
					DDM._onLoad();
				} else {
					if (DDM._timeoutCount > 2000) {
					} else {
						setTimeout(DDM._addListeners, 10);
						if (document && document.body) {
							DDM._timeoutCount += 1;
						}
					}
				}
			},

			/**
			* Recursively searches the immediate parent and all child nodes for
			* the handle element in order to determine wheter or not it was
			* clicked.
			* @method handleWasClicked
			* @param node the html element to inspect
			* @static
			*/
			handleWasClicked: function (node, id) {
				if (this.isHandle(id, node.id)) {
					return true;
				} else {
					// check to see if this is a text node child of the one we want
					var p = node.parentNode;

					while (p) {
						if (this.isHandle(id, p.id)) {
							return true;
						} else {
							p = p.parentNode;
						}
					}
				}

				return false;
			}

		};

	} ();

	// shorter alias, save a few bytes
	Ext.dd.DDM = Ext.dd.DragDropMgr;
	Ext.dd.DDM._addListeners();

}

/**
* @class Ext.dd.DD
* A DragDrop implementation where the linked element follows the
* mouse cursor during a drag.
* @extends Ext.dd.DragDrop
* @constructor
* @param {String} id the id of the linked element
* @param {String} sGroup the group of related DragDrop items
* @param {object} config an object containing configurable attributes
*                Valid properties for DD:
*                    scroll
*/
Ext.dd.DD = function (id, sGroup, config) {
	if (id) {
		this.init(id, sGroup, config);
	}
};

Ext.extend(Ext.dd.DD, Ext.dd.DragDrop, {

	/**
	* When set to true, the utility automatically tries to scroll the browser
	* window when a drag and drop element is dragged near the viewport boundary.
	* Defaults to true.
	* @property scroll
	* @type boolean
	*/
	scroll: true,

	/**
	* Sets the pointer offset to the distance between the linked element's top
	* left corner and the location the element was clicked
	* @method autoOffset
	* @param {int} iPageX the X coordinate of the click
	* @param {int} iPageY the Y coordinate of the click
	*/
	autoOffset: function (iPageX, iPageY) {
		var x = iPageX - this.startPageX;
		var y = iPageY - this.startPageY;
		this.setDelta(x, y);
	},

	/**
	* Sets the pointer offset.  You can call this directly to force the
	* offset to be in a particular location (e.g., pass in 0,0 to set it
	* to the center of the object)
	* @method setDelta
	* @param {int} iDeltaX the distance from the left
	* @param {int} iDeltaY the distance from the top
	*/
	setDelta: function (iDeltaX, iDeltaY) {
		this.deltaX = iDeltaX;
		this.deltaY = iDeltaY;
	},

	/**
	* Sets the drag element to the location of the mousedown or click event,
	* maintaining the cursor location relative to the location on the element
	* that was clicked.  Override this if you want to place the element in a
	* location other than where the cursor is.
	* @method setDragElPos
	* @param {int} iPageX the X coordinate of the mousedown or drag event
	* @param {int} iPageY the Y coordinate of the mousedown or drag event
	*/
	setDragElPos: function (iPageX, iPageY) {
		// the first time we do this, we are going to check to make sure
		// the element has css positioning

		var el = this.getDragEl();
		this.alignElWithMouse(el, iPageX, iPageY);
	},

	/**
	* Sets the element to the location of the mousedown or click event,
	* maintaining the cursor location relative to the location on the element
	* that was clicked.  Override this if you want to place the element in a
	* location other than where the cursor is.
	* @method alignElWithMouse
	* @param {HTMLElement} el the element to move
	* @param {int} iPageX the X coordinate of the mousedown or drag event
	* @param {int} iPageY the Y coordinate of the mousedown or drag event
	*/
	alignElWithMouse: function (el, iPageX, iPageY) {
		var oCoord = this.getTargetCoord(iPageX, iPageY);
		var fly = el.dom ? el : Ext.fly(el, '_dd');
		if (!this.deltaSetXY) {
			var aCoord = [oCoord.x, oCoord.y];
			fly.setXY(aCoord);
			var newLeft = fly.getLeft(true);
			var newTop = fly.getTop(true);
			this.deltaSetXY = [newLeft - oCoord.x, newTop - oCoord.y];
		} else {
			fly.setLeftTop(oCoord.x + this.deltaSetXY[0], oCoord.y + this.deltaSetXY[1]);
		}

		this.cachePosition(oCoord.x, oCoord.y);
		this.autoScroll(oCoord.x, oCoord.y, el.offsetHeight, el.offsetWidth);
		return oCoord;
	},

	/**
	* Saves the most recent position so that we can reset the constraints and
	* tick marks on-demand.  We need to know this so that we can calculate the
	* number of pixels the element is offset from its original position.
	* @method cachePosition
	* @param iPageX the current x position (optional, this just makes it so we
	* don't have to look it up again)
	* @param iPageY the current y position (optional, this just makes it so we
	* don't have to look it up again)
	*/
	cachePosition: function (iPageX, iPageY) {
		if (iPageX) {
			this.lastPageX = iPageX;
			this.lastPageY = iPageY;
		} else {
			var aCoord = Ext.lib.Dom.getXY(this.getEl());
			this.lastPageX = aCoord[0];
			this.lastPageY = aCoord[1];
		}
	},

	/**
	* Auto-scroll the window if the dragged object has been moved beyond the
	* visible window boundary.
	* @method autoScroll
	* @param {int} x the drag element's x position
	* @param {int} y the drag element's y position
	* @param {int} h the height of the drag element
	* @param {int} w the width of the drag element
	* @private
	*/
	autoScroll: function (x, y, h, w) {

		if (this.scroll) {
			// The client height
			var clientH = Ext.lib.Dom.getViewHeight();

			// The client width
			var clientW = Ext.lib.Dom.getViewWidth();

			// The amt scrolled down
			var st = this.DDM.getScrollTop();

			// The amt scrolled right
			var sl = this.DDM.getScrollLeft();

			// Location of the bottom of the element
			var bot = h + y;

			// Location of the right of the element
			var right = w + x;

			// The distance from the cursor to the bottom of the visible area,
			// adjusted so that we don't scroll if the cursor is beyond the
			// element drag constraints
			var toBot = (clientH + st - y - this.deltaY);

			// The distance from the cursor to the right of the visible area
			var toRight = (clientW + sl - x - this.deltaX);


			// How close to the edge the cursor must be before we scroll
			// var thresh = (document.all) ? 100 : 40;
			var thresh = 40;

			// How many pixels to scroll per autoscroll op.  This helps to reduce
			// clunky scrolling. IE is more sensitive about this ... it needs this
			// value to be higher.
			var scrAmt = (document.all) ? 80 : 30;

			// Scroll down if we are near the bottom of the visible page and the
			// obj extends below the crease
			if (bot > clientH && toBot < thresh) {
				window.scrollTo(sl, st + scrAmt);
			}

			// Scroll up if the window is scrolled down and the top of the object
			// goes above the top border
			if (y < st && st > 0 && y - st < thresh) {
				window.scrollTo(sl, st - scrAmt);
			}

			// Scroll right if the obj is beyond the right border and the cursor is
			// near the border.
			if (right > clientW && toRight < thresh) {
				window.scrollTo(sl + scrAmt, st);
			}

			// Scroll left if the window has been scrolled to the right and the obj
			// extends past the left border
			if (x < sl && sl > 0 && x - sl < thresh) {
				window.scrollTo(sl - scrAmt, st);
			}
		}
	},

	/**
	* Finds the location the element should be placed if we want to move
	* it to where the mouse location less the click offset would place us.
	* @method getTargetCoord
	* @param {int} iPageX the X coordinate of the click
	* @param {int} iPageY the Y coordinate of the click
	* @return an object that contains the coordinates (Object.x and Object.y)
	* @private
	*/
	getTargetCoord: function (iPageX, iPageY) {
		var x = iPageX - this.deltaX;
		var y = iPageY - this.deltaY;

		if (this.constrainX) {
			if (x < this.minX) { x = this.minX; }
			if (x > this.maxX) { x = this.maxX; }
		}

		if (this.constrainY) {
			if (y < this.minY) { y = this.minY; }
			if (y > this.maxY) { y = this.maxY; }
		}

		x = this.getTick(x, this.xTicks);
		y = this.getTick(y, this.yTicks);


		return { x: x, y: y };
	},

	/**
	* Sets up config options specific to this class. Overrides
	* Ext.dd.DragDrop, but all versions of this method through the
	* inheritance chain are called
	*/
	applyConfig: function () {
		Ext.dd.DD.superclass.applyConfig.call(this);
		this.scroll = (this.config.scroll !== false);
	},

	/**
	* Event that fires prior to the onMouseDown event.  Overrides
	* Ext.dd.DragDrop.
	*/
	b4MouseDown: function (e) {
		// this.resetConstraints();
		this.autoOffset(e.getPageX(),
                            e.getPageY());
	},

	/**
	* Event that fires prior to the onDrag event.  Overrides
	* Ext.dd.DragDrop.
	*/
	b4Drag: function (e) {
		this.setDragElPos(e.getPageX(),
                            e.getPageY());
	},

	toString: function () {
		return ("DD " + this.id);
	}

	//////////////////////////////////////////////////////////////////////////
	// Debugging ygDragDrop events that can be overridden
	//////////////////////////////////////////////////////////////////////////
	/*
	startDrag: function(x, y) {
	},

	onDrag: function(e) {
	},

	onDragEnter: function(e, id) {
	},

	onDragOver: function(e, id) {
	},

	onDragOut: function(e, id) {
	},

	onDragDrop: function(e, id) {
	},

	endDrag: function(e) {
	}

	*/

});
/**
* @class Ext.dd.DDProxy
* A DragDrop implementation that inserts an empty, bordered div into
* the document that follows the cursor during drag operations.  At the time of
* the click, the frame div is resized to the dimensions of the linked html
* element, and moved to the exact location of the linked element.
*
* References to the "frame" element refer to the single proxy element that
* was created to be dragged in place of all DDProxy elements on the
* page.
*
* @extends Ext.dd.DD
* @constructor
* @param {String} id the id of the linked html element
* @param {String} sGroup the group of related DragDrop objects
* @param {object} config an object containing configurable attributes
*                Valid properties for DDProxy in addition to those in DragDrop:
*                   resizeFrame, centerFrame, dragElId
*/
Ext.dd.DDProxy = function (id, sGroup, config) {
	if (id) {
		this.init(id, sGroup, config);
		this.initFrame();
	}
};

/**
* The default drag frame div id
* @property Ext.dd.DDProxy.dragElId
* @type String
* @static
*/
Ext.dd.DDProxy.dragElId = "ygddfdiv";

Ext.extend(Ext.dd.DDProxy, Ext.dd.DD, {

	/**
	* By default we resize the drag frame to be the same size as the element
	* we want to drag (this is to get the frame effect).  We can turn it off
	* if we want a different behavior.
	* @property resizeFrame
	* @type boolean
	*/
	resizeFrame: true,

	/**
	* By default the frame is positioned exactly where the drag element is, so
	* we use the cursor offset provided by Ext.dd.DD.  Another option that works only if
	* you do not have constraints on the obj is to have the drag frame centered
	* around the cursor.  Set centerFrame to true for this effect.
	* @property centerFrame
	* @type boolean
	*/
	centerFrame: false,

	/**
	* Creates the proxy element if it does not yet exist
	* @method createFrame
	*/
	createFrame: function () {
		var self = this;
		var body = document.body;

		if (!body || !body.firstChild) {
			setTimeout(function () { self.createFrame(); }, 50);
			return;
		}

		var div = this.getDragEl();

		if (!div) {
			div = document.createElement("div");
			div.id = this.dragElId;
			var s = div.style;

			s.position = "absolute";
			s.visibility = "hidden";
			s.cursor = "move";
			s.border = "2px solid #aaa";
			s.zIndex = 999;

			// appendChild can blow up IE if invoked prior to the window load event
			// while rendering a table.  It is possible there are other scenarios
			// that would cause this to happen as well.
			body.insertBefore(div, body.firstChild);
		}
	},

	/**
	* Initialization for the drag frame element.  Must be called in the
	* constructor of all subclasses
	* @method initFrame
	*/
	initFrame: function () {
		this.createFrame();
	},

	applyConfig: function () {
		Ext.dd.DDProxy.superclass.applyConfig.call(this);

		this.resizeFrame = (this.config.resizeFrame !== false);
		this.centerFrame = (this.config.centerFrame);
		this.setDragElId(this.config.dragElId || Ext.dd.DDProxy.dragElId);
	},

	/**
	* Resizes the drag frame to the dimensions of the clicked object, positions
	* it over the object, and finally displays it
	* @method showFrame
	* @param {int} iPageX X click position
	* @param {int} iPageY Y click position
	* @private
	*/
	showFrame: function (iPageX, iPageY) {
		var el = this.getEl();
		var dragEl = this.getDragEl();
		var s = dragEl.style;

		this._resizeProxy();

		if (this.centerFrame) {
			this.setDelta(Math.round(parseInt(s.width, 10) / 2),
                           Math.round(parseInt(s.height, 10) / 2));
		}

		this.setDragElPos(iPageX, iPageY);

		Ext.fly(dragEl).show();
	},

	/**
	* The proxy is automatically resized to the dimensions of the linked
	* element when a drag is initiated, unless resizeFrame is set to false
	* @method _resizeProxy
	* @private
	*/
	_resizeProxy: function () {
		if (this.resizeFrame) {
			var el = this.getEl();
			Ext.fly(this.getDragEl()).setSize(el.offsetWidth, el.offsetHeight);
		}
	},

	// overrides Ext.dd.DragDrop
	b4MouseDown: function (e) {
		var x = e.getPageX();
		var y = e.getPageY();
		this.autoOffset(x, y);
		this.setDragElPos(x, y);
	},

	// overrides Ext.dd.DragDrop
	b4StartDrag: function (x, y) {
		// show the drag frame
		this.showFrame(x, y);
	},

	// overrides Ext.dd.DragDrop
	b4EndDrag: function (e) {
		Ext.fly(this.getDragEl()).hide();
	},

	// overrides Ext.dd.DragDrop
	// By default we try to move the element to the last location of the frame.
	// This is so that the default behavior mirrors that of Ext.dd.DD.
	endDrag: function (e) {

		var lel = this.getEl();
		var del = this.getDragEl();

		// Show the drag frame briefly so we can get its position
		del.style.visibility = "";

		this.beforeMove();
		// Hide the linked element before the move to get around a Safari
		// rendering bug.
		lel.style.visibility = "hidden";
		Ext.dd.DDM.moveToEl(lel, del);
		del.style.visibility = "hidden";
		lel.style.visibility = "";

		this.afterDrag();
	},

	beforeMove: function () {

	},

	afterDrag: function () {

	},

	toString: function () {
		return ("DDProxy " + this.id);
	}

});
/**
* @class Ext.dd.DDTarget
* A DragDrop implementation that does not move, but can be a drop
* target.  You would get the same result by simply omitting implementation
* for the event callbacks, but this way we reduce the processing cost of the
* event listener and the callbacks.
* @extends Ext.dd.DragDrop
* @constructor
* @param {String} id the id of the element that is a drop target
* @param {String} sGroup the group of related DragDrop objects
* @param {object} config an object containing configurable attributes
*                 Valid properties for DDTarget in addition to those in
*                 DragDrop:
*                    none
*/
Ext.dd.DDTarget = function (id, sGroup, config) {
	if (id) {
		this.initTarget(id, sGroup, config);
	}
};

// Ext.dd.DDTarget.prototype = new Ext.dd.DragDrop();
Ext.extend(Ext.dd.DDTarget, Ext.dd.DragDrop, {
	/**
	* @hide
	* Overridden and disabled. A DDTarget does not support being dragged.
	* @method
	*/
	getDragEl: Ext.emptyFn,
	/**
	* @hide
	* Overridden and disabled. A DDTarget does not support being dragged.
	* @method
	*/
	isValidHandleChild: Ext.emptyFn,
	/**
	* @hide
	* Overridden and disabled. A DDTarget does not support being dragged.
	* @method
	*/
	startDrag: Ext.emptyFn,
	/**
	* @hide
	* Overridden and disabled. A DDTarget does not support being dragged.
	* @method
	*/
	endDrag: Ext.emptyFn,
	/**
	* @hide
	* Overridden and disabled. A DDTarget does not support being dragged.
	* @method
	*/
	onDrag: Ext.emptyFn,
	/**
	* @hide
	* Overridden and disabled. A DDTarget does not support being dragged.
	* @method
	*/
	onDragDrop: Ext.emptyFn,
	/**
	* @hide
	* Overridden and disabled. A DDTarget does not support being dragged.
	* @method
	*/
	onDragEnter: Ext.emptyFn,
	/**
	* @hide
	* Overridden and disabled. A DDTarget does not support being dragged.
	* @method
	*/
	onDragOut: Ext.emptyFn,
	/**
	* @hide
	* Overridden and disabled. A DDTarget does not support being dragged.
	* @method
	*/
	onDragOver: Ext.emptyFn,
	/**
	* @hide
	* Overridden and disabled. A DDTarget does not support being dragged.
	* @method
	*/
	onInvalidDrop: Ext.emptyFn,
	/**
	* @hide
	* Overridden and disabled. A DDTarget does not support being dragged.
	* @method
	*/
	onMouseDown: Ext.emptyFn,
	/**
	* @hide
	* Overridden and disabled. A DDTarget does not support being dragged.
	* @method
	*/
	onMouseUp: Ext.emptyFn,
	/**
	* @hide
	* Overridden and disabled. A DDTarget does not support being dragged.
	* @method
	*/
	setXConstraint: Ext.emptyFn,
	/**
	* @hide
	* Overridden and disabled. A DDTarget does not support being dragged.
	* @method
	*/
	setYConstraint: Ext.emptyFn,
	/**
	* @hide
	* Overridden and disabled. A DDTarget does not support being dragged.
	* @method
	*/
	resetConstraints: Ext.emptyFn,
	/**
	* @hide
	* Overridden and disabled. A DDTarget does not support being dragged.
	* @method
	*/
	clearConstraints: Ext.emptyFn,
	/**
	* @hide
	* Overridden and disabled. A DDTarget does not support being dragged.
	* @method
	*/
	clearTicks: Ext.emptyFn,
	/**
	* @hide
	* Overridden and disabled. A DDTarget does not support being dragged.
	* @method
	*/
	setInitPosition: Ext.emptyFn,
	/**
	* @hide
	* Overridden and disabled. A DDTarget does not support being dragged.
	* @method
	*/
	setDragElId: Ext.emptyFn,
	/**
	* @hide
	* Overridden and disabled. A DDTarget does not support being dragged.
	* @method
	*/
	setHandleElId: Ext.emptyFn,
	/**
	* @hide
	* Overridden and disabled. A DDTarget does not support being dragged.
	* @method
	*/
	setOuterHandleElId: Ext.emptyFn,
	/**
	* @hide
	* Overridden and disabled. A DDTarget does not support being dragged.
	* @method
	*/
	addInvalidHandleClass: Ext.emptyFn,
	/**
	* @hide
	* Overridden and disabled. A DDTarget does not support being dragged.
	* @method
	*/
	addInvalidHandleId: Ext.emptyFn,
	/**
	* @hide
	* Overridden and disabled. A DDTarget does not support being dragged.
	* @method
	*/
	addInvalidHandleType: Ext.emptyFn,
	/**
	* @hide
	* Overridden and disabled. A DDTarget does not support being dragged.
	* @method
	*/
	removeInvalidHandleClass: Ext.emptyFn,
	/**
	* @hide
	* Overridden and disabled. A DDTarget does not support being dragged.
	* @method
	*/
	removeInvalidHandleId: Ext.emptyFn,
	/**
	* @hide
	* Overridden and disabled. A DDTarget does not support being dragged.
	* @method
	*/
	removeInvalidHandleType: Ext.emptyFn,

	toString: function () {
		return ("DDTarget " + this.id);
	}
}); /**
 * @class Ext.dd.DragTracker
 * @extends Ext.util.Observable
 * A DragTracker listens for drag events on an Element and fires events at the start and end of the drag,
 * as well as during the drag. This is useful for components such as {@link Ext.Slider}, where there is
 * an element that can be dragged around to change the Slider's value.
 * DragTracker provides a series of template methods that should be overridden to provide functionality
 * in response to detected drag operations. These are onBeforeStart, onStart, onDrag and onEnd.
 * See {@link Ext.Slider}'s initEvents function for an example implementation.
 */
Ext.dd.DragTracker = Ext.extend(Ext.util.Observable, {
	/**
	* @cfg {Boolean} active
	* Defaults to <tt>false</tt>.
	*/
	active: false,
	/**
	* @cfg {Number} tolerance
	* Number of pixels the drag target must be moved before dragging is considered to have started. Defaults to <tt>5</tt>.
	*/
	tolerance: 5,
	/**
	* @cfg {Boolean/Number} autoStart
	* Defaults to <tt>false</tt>. Specify <tt>true</tt> to defer trigger start by 1000 ms.
	* Specify a Number for the number of milliseconds to defer trigger start.
	*/
	autoStart: false,

	constructor: function (config) {
		Ext.apply(this, config);
		this.addEvents(
		/**
		* @event mousedown
		* @param {Object} this
		* @param {Object} e event object
		*/
	        'mousedown',
		/**
		* @event mouseup
		* @param {Object} this
		* @param {Object} e event object
		*/
	        'mouseup',
		/**
		* @event mousemove
		* @param {Object} this
		* @param {Object} e event object
		*/
	        'mousemove',
		/**
		* @event dragstart
		* @param {Object} this
		* @param {Object} startXY the page coordinates of the event
		*/
	        'dragstart',
		/**
		* @event dragend
		* @param {Object} this
		* @param {Object} e event object
		*/
	        'dragend',
		/**
		* @event drag
		* @param {Object} this
		* @param {Object} e event object
		*/
	        'drag'
	    );

		this.dragRegion = new Ext.lib.Region(0, 0, 0, 0);

		if (this.el) {
			this.initEl(this.el);
		}
		Ext.dd.DragTracker.superclass.constructor.call(this, config);
	},

	initEl: function (el) {
		this.el = Ext.get(el);
		el.on('mousedown', this.onMouseDown, this,
                this.delegate ? { delegate: this.delegate} : undefined);
	},

	destroy: function () {
		this.el.un('mousedown', this.onMouseDown, this);
	},

	onMouseDown: function (e, target) {
		if (this.fireEvent('mousedown', this, e) !== false && this.onBeforeStart(e) !== false) {
			this.startXY = this.lastXY = e.getXY();
			this.dragTarget = this.delegate ? target : this.el.dom;
			if (this.preventDefault !== false) {
				e.preventDefault();
			}
			var doc = Ext.getDoc();
			doc.on('mouseup', this.onMouseUp, this);
			doc.on('mousemove', this.onMouseMove, this);
			doc.on('selectstart', this.stopSelect, this);
			if (this.autoStart) {
				this.timer = this.triggerStart.defer(this.autoStart === true ? 1000 : this.autoStart, this);
			}
		}
	},

	onMouseMove: function (e, target) {
		// HACK: IE hack to see if button was released outside of window. */
		if (this.active && Ext.isIE && !e.browserEvent.button) {
			e.preventDefault();
			this.onMouseUp(e);
			return;
		}

		e.preventDefault();
		var xy = e.getXY(), s = this.startXY;
		this.lastXY = xy;
		if (!this.active) {
			if (Math.abs(s[0] - xy[0]) > this.tolerance || Math.abs(s[1] - xy[1]) > this.tolerance) {
				this.triggerStart();
			} else {
				return;
			}
		}
		this.fireEvent('mousemove', this, e);
		this.onDrag(e);
		this.fireEvent('drag', this, e);
	},

	onMouseUp: function (e) {
		var doc = Ext.getDoc();
		doc.un('mousemove', this.onMouseMove, this);
		doc.un('mouseup', this.onMouseUp, this);
		doc.un('selectstart', this.stopSelect, this);
		e.preventDefault();
		this.clearStart();
		var wasActive = this.active;
		this.active = false;
		delete this.elRegion;
		this.fireEvent('mouseup', this, e);
		if (wasActive) {
			this.onEnd(e);
			this.fireEvent('dragend', this, e);
		}
	},

	triggerStart: function (isTimer) {
		this.clearStart();
		this.active = true;
		this.onStart(this.startXY);
		this.fireEvent('dragstart', this, this.startXY);
	},

	clearStart: function () {
		if (this.timer) {
			clearTimeout(this.timer);
			delete this.timer;
		}
	},

	stopSelect: function (e) {
		e.stopEvent();
		return false;
	},

	/**
	* Template method which should be overridden by each DragTracker instance. Called when the user first clicks and
	* holds the mouse button down. Return false to disallow the drag
	* @param {Ext.EventObject} e The event object
	*/
	onBeforeStart: function (e) {

	},

	/**
	* Template method which should be overridden by each DragTracker instance. Called when a drag operation starts
	* (e.g. the user has moved the tracked element beyond the specified tolerance)
	* @param {Array} xy x and y co-ordinates of the original location of the tracked element
	*/
	onStart: function (xy) {

	},

	/**
	* Template method which should be overridden by each DragTracker instance. Called whenever a drag has been detected.
	* @param {Ext.EventObject} e The event object
	*/
	onDrag: function (e) {

	},

	/**
	* Template method which should be overridden by each DragTracker instance. Called when a drag operation has been completed
	* (e.g. the user clicked and held the mouse down, dragged the element and then released the mouse button)
	* @param {Ext.EventObject} e The event object
	*/
	onEnd: function (e) {

	},

	/**
	* Returns the drag target
	* @return {Ext.Element} The element currently being tracked
	*/
	getDragTarget: function () {
		return this.dragTarget;
	},

	getDragCt: function () {
		return this.el;
	},

	getXY: function (constrain) {
		return constrain ?
               this.constrainModes[constrain].call(this, this.lastXY) : this.lastXY;
	},

	getOffset: function (constrain) {
		var xy = this.getXY(constrain);
		var s = this.startXY;
		return [s[0] - xy[0], s[1] - xy[1]];
	},

	constrainModes: {
		'point': function (xy) {

			if (!this.elRegion) {
				this.elRegion = this.getDragCt().getRegion();
			}

			var dr = this.dragRegion;

			dr.left = xy[0];
			dr.top = xy[1];
			dr.right = xy[0];
			dr.bottom = xy[1];

			dr.constrainTo(this.elRegion);

			return [dr.left, dr.top];
		}
	}
}); /**
 * @class Ext.dd.ScrollManager
 * <p>Provides automatic scrolling of overflow regions in the page during drag operations.</p>
 * <p>The ScrollManager configs will be used as the defaults for any scroll container registered with it,
 * but you can also override most of the configs per scroll container by adding a 
 * <tt>ddScrollConfig</tt> object to the target element that contains these properties: {@link #hthresh},
 * {@link #vthresh}, {@link #increment} and {@link #frequency}.  Example usage:
 * <pre><code>
var el = Ext.get('scroll-ct');
el.ddScrollConfig = {
    vthresh: 50,
    hthresh: -1,
    frequency: 100,
    increment: 200
};
Ext.dd.ScrollManager.register(el);
</code></pre>
 * <b>Note: This class uses "Point Mode" and is untested in "Intersect Mode".</b>
 * @singleton
 */
Ext.dd.ScrollManager = function () {
	var ddm = Ext.dd.DragDropMgr;
	var els = {};
	var dragEl = null;
	var proc = {};

	var onStop = function (e) {
		dragEl = null;
		clearProc();
	};

	var triggerRefresh = function () {
		if (ddm.dragCurrent) {
			ddm.refreshCache(ddm.dragCurrent.groups);
		}
	};

	var doScroll = function () {
		if (ddm.dragCurrent) {
			var dds = Ext.dd.ScrollManager;
			var inc = proc.el.ddScrollConfig ?
                      proc.el.ddScrollConfig.increment : dds.increment;
			if (!dds.animate) {
				if (proc.el.scroll(proc.dir, inc)) {
					triggerRefresh();
				}
			} else {
				proc.el.scroll(proc.dir, inc, true, dds.animDuration, triggerRefresh);
			}
		}
	};

	var clearProc = function () {
		if (proc.id) {
			clearInterval(proc.id);
		}
		proc.id = 0;
		proc.el = null;
		proc.dir = "";
	};

	var startProc = function (el, dir) {
		clearProc();
		proc.el = el;
		proc.dir = dir;
		var freq = (el.ddScrollConfig && el.ddScrollConfig.frequency) ?
                el.ddScrollConfig.frequency : Ext.dd.ScrollManager.frequency;
		proc.id = setInterval(doScroll, freq);
	};

	var onFire = function (e, isDrop) {
		if (isDrop || !ddm.dragCurrent) { return; }
		var dds = Ext.dd.ScrollManager;
		if (!dragEl || dragEl != ddm.dragCurrent) {
			dragEl = ddm.dragCurrent;
			// refresh regions on drag start
			dds.refreshCache();
		}

		var xy = Ext.lib.Event.getXY(e);
		var pt = new Ext.lib.Point(xy[0], xy[1]);
		for (var id in els) {
			var el = els[id], r = el._region;
			var c = el.ddScrollConfig ? el.ddScrollConfig : dds;
			if (r && r.contains(pt) && el.isScrollable()) {
				if (r.bottom - pt.y <= c.vthresh) {
					if (proc.el != el) {
						startProc(el, "down");
					}
					return;
				} else if (r.right - pt.x <= c.hthresh) {
					if (proc.el != el) {
						startProc(el, "left");
					}
					return;
				} else if (pt.y - r.top <= c.vthresh) {
					if (proc.el != el) {
						startProc(el, "up");
					}
					return;
				} else if (pt.x - r.left <= c.hthresh) {
					if (proc.el != el) {
						startProc(el, "right");
					}
					return;
				}
			}
		}
		clearProc();
	};

	ddm.fireEvents = ddm.fireEvents.createSequence(onFire, ddm);
	ddm.stopDrag = ddm.stopDrag.createSequence(onStop, ddm);

	return {
		/**
		* Registers new overflow element(s) to auto scroll
		* @param {Mixed/Array} el The id of or the element to be scrolled or an array of either
		*/
		register: function (el) {
			if (Ext.isArray(el)) {
				for (var i = 0, len = el.length; i < len; i++) {
					this.register(el[i]);
				}
			} else {
				el = Ext.get(el);
				els[el.id] = el;
			}
		},

		/**
		* Unregisters overflow element(s) so they are no longer scrolled
		* @param {Mixed/Array} el The id of or the element to be removed or an array of either
		*/
		unregister: function (el) {
			if (Ext.isArray(el)) {
				for (var i = 0, len = el.length; i < len; i++) {
					this.unregister(el[i]);
				}
			} else {
				el = Ext.get(el);
				delete els[el.id];
			}
		},

		/**
		* The number of pixels from the top or bottom edge of a container the pointer needs to be to
		* trigger scrolling (defaults to 25)
		* @type Number
		*/
		vthresh: 25,
		/**
		* The number of pixels from the right or left edge of a container the pointer needs to be to
		* trigger scrolling (defaults to 25)
		* @type Number
		*/
		hthresh: 25,

		/**
		* The number of pixels to scroll in each scroll increment (defaults to 50)
		* @type Number
		*/
		increment: 100,

		/**
		* The frequency of scrolls in milliseconds (defaults to 500)
		* @type Number
		*/
		frequency: 500,

		/**
		* True to animate the scroll (defaults to true)
		* @type Boolean
		*/
		animate: true,

		/**
		* The animation duration in seconds - 
		* MUST BE less than Ext.dd.ScrollManager.frequency! (defaults to .4)
		* @type Number
		*/
		animDuration: .4,

		/**
		* Manually trigger a cache refresh.
		*/
		refreshCache: function () {
			for (var id in els) {
				if (typeof els[id] == 'object') { // for people extending the object prototype
					els[id]._region = els[id].getRegion();
				}
			}
		}
	};
} (); /**
 * @class Ext.dd.Registry
 * Provides easy access to all drag drop components that are registered on a page.  Items can be retrieved either
 * directly by DOM node id, or by passing in the drag drop event that occurred and looking up the event target.
 * @singleton
 */
Ext.dd.Registry = function () {
	var elements = {};
	var handles = {};
	var autoIdSeed = 0;

	var getId = function (el, autogen) {
		if (typeof el == "string") {
			return el;
		}
		var id = el.id;
		if (!id && autogen !== false) {
			id = "extdd-" + (++autoIdSeed);
			el.id = id;
		}
		return id;
	};

	return {
		/**
		* Resgister a drag drop element
		* @param {String/HTMLElement} element The id or DOM node to register
		* @param {Object} data (optional) An custom data object that will be passed between the elements that are involved
		* in drag drop operations.  You can populate this object with any arbitrary properties that your own code
		* knows how to interpret, plus there are some specific properties known to the Registry that should be
		* populated in the data object (if applicable):
		* <pre>
		Value      Description<br />
		---------  ------------------------------------------<br />
		handles    Array of DOM nodes that trigger dragging<br />
		for the element being registered<br />
		isHandle   True if the element passed in triggers<br />
		dragging itself, else false
		</pre>
		*/
		register: function (el, data) {
			data = data || {};
			if (typeof el == "string") {
				el = document.getElementById(el);
			}
			data.ddel = el;
			elements[getId(el)] = data;
			if (data.isHandle !== false) {
				handles[data.ddel.id] = data;
			}
			if (data.handles) {
				var hs = data.handles;
				for (var i = 0, len = hs.length; i < len; i++) {
					handles[getId(hs[i])] = data;
				}
			}
		},

		/**
		* Unregister a drag drop element
		* @param {String/HTMLElement} element The id or DOM node to unregister
		*/
		unregister: function (el) {
			var id = getId(el, false);
			var data = elements[id];
			if (data) {
				delete elements[id];
				if (data.handles) {
					var hs = data.handles;
					for (var i = 0, len = hs.length; i < len; i++) {
						delete handles[getId(hs[i], false)];
					}
				}
			}
		},

		/**
		* Returns the handle registered for a DOM Node by id
		* @param {String/HTMLElement} id The DOM node or id to look up
		* @return {Object} handle The custom handle data
		*/
		getHandle: function (id) {
			if (typeof id != "string") { // must be element?
				id = id.id;
			}
			return handles[id];
		},

		/**
		* Returns the handle that is registered for the DOM node that is the target of the event
		* @param {Event} e The event
		* @return {Object} handle The custom handle data
		*/
		getHandleFromEvent: function (e) {
			var t = Ext.lib.Event.getTarget(e);
			return t ? handles[t.id] : null;
		},

		/**
		* Returns a custom data object that is registered for a DOM node by id
		* @param {String/HTMLElement} id The DOM node or id to look up
		* @return {Object} data The custom data
		*/
		getTarget: function (id) {
			if (typeof id != "string") { // must be element?
				id = id.id;
			}
			return elements[id];
		},

		/**
		* Returns a custom data object that is registered for the DOM node that is the target of the event
		* @param {Event} e The event
		* @return {Object} data The custom data
		*/
		getTargetFromEvent: function (e) {
			var t = Ext.lib.Event.getTarget(e);
			return t ? elements[t.id] || handles[t.id] : null;
		}
	};
} (); /**
 * @class Ext.dd.StatusProxy
 * A specialized drag proxy that supports a drop status icon, {@link Ext.Layer} styles and auto-repair.  This is the
 * default drag proxy used by all Ext.dd components.
 * @constructor
 * @param {Object} config
 */
Ext.dd.StatusProxy = function (config) {
	Ext.apply(this, config);
	this.id = this.id || Ext.id();
	this.el = new Ext.Layer({
		dh: {
			id: this.id, tag: "div", cls: "x-dd-drag-proxy " + this.dropNotAllowed, children: [
                { tag: "div", cls: "x-dd-drop-icon" },
                { tag: "div", cls: "x-dd-drag-ghost" }
            ]
		},
		shadow: !config || config.shadow !== false
	});
	this.ghost = Ext.get(this.el.dom.childNodes[1]);
	this.dropStatus = this.dropNotAllowed;
};

Ext.dd.StatusProxy.prototype = {
	/**
	* @cfg {String} dropAllowed
	* The CSS class to apply to the status element when drop is allowed (defaults to "x-dd-drop-ok").
	*/
	dropAllowed: "x-dd-drop-ok",
	/**
	* @cfg {String} dropNotAllowed
	* The CSS class to apply to the status element when drop is not allowed (defaults to "x-dd-drop-nodrop").
	*/
	dropNotAllowed: "x-dd-drop-nodrop",

	/**
	* Updates the proxy's visual element to indicate the status of whether or not drop is allowed
	* over the current target element.
	* @param {String} cssClass The css class for the new drop status indicator image
	*/
	setStatus: function (cssClass) {
		cssClass = cssClass || this.dropNotAllowed;
		if (this.dropStatus != cssClass) {
			this.el.replaceClass(this.dropStatus, cssClass);
			this.dropStatus = cssClass;
		}
	},

	/**
	* Resets the status indicator to the default dropNotAllowed value
	* @param {Boolean} clearGhost True to also remove all content from the ghost, false to preserve it
	*/
	reset: function (clearGhost) {
		this.el.dom.className = "x-dd-drag-proxy " + this.dropNotAllowed;
		this.dropStatus = this.dropNotAllowed;
		if (clearGhost) {
			this.ghost.update("");
		}
	},

	/**
	* Updates the contents of the ghost element
	* @param {String/HTMLElement} html The html that will replace the current innerHTML of the ghost element, or a
	* DOM node to append as the child of the ghost element (in which case the innerHTML will be cleared first).
	*/
	update: function (html) {
		if (typeof html == "string") {
			this.ghost.update(html);
		} else {
			this.ghost.update("");
			html.style.margin = "0";
			this.ghost.dom.appendChild(html);
		}
		var el = this.ghost.dom.firstChild;
		if (el) {
			Ext.fly(el).setStyle('float', 'none');
		}
	},

	/**
	* Returns the underlying proxy {@link Ext.Layer}
	* @return {Ext.Layer} el
	*/
	getEl: function () {
		return this.el;
	},

	/**
	* Returns the ghost element
	* @return {Ext.Element} el
	*/
	getGhost: function () {
		return this.ghost;
	},

	/**
	* Hides the proxy
	* @param {Boolean} clear True to reset the status and clear the ghost contents, false to preserve them
	*/
	hide: function (clear) {
		this.el.hide();
		if (clear) {
			this.reset(true);
		}
	},

	/**
	* Stops the repair animation if it's currently running
	*/
	stop: function () {
		if (this.anim && this.anim.isAnimated && this.anim.isAnimated()) {
			this.anim.stop();
		}
	},

	/**
	* Displays this proxy
	*/
	show: function () {
		this.el.show();
	},

	/**
	* Force the Layer to sync its shadow and shim positions to the element
	*/
	sync: function () {
		this.el.sync();
	},

	/**
	* Causes the proxy to return to its position of origin via an animation.  Should be called after an
	* invalid drop operation by the item being dragged.
	* @param {Array} xy The XY position of the element ([x, y])
	* @param {Function} callback The function to call after the repair is complete.
	* @param {Object} scope The scope (<code>this</code> reference) in which the callback function is executed. Defaults to the browser window.
	*/
	repair: function (xy, callback, scope) {
		this.callback = callback;
		this.scope = scope;
		if (xy && this.animRepair !== false) {
			this.el.addClass("x-dd-drag-repair");
			this.el.hideUnders(true);
			this.anim = this.el.shift({
				duration: this.repairDuration || .5,
				easing: 'easeOut',
				xy: xy,
				stopFx: true,
				callback: this.afterRepair,
				scope: this
			});
		} else {
			this.afterRepair();
		}
	},

	// private
	afterRepair: function () {
		this.hide(true);
		if (typeof this.callback == "function") {
			this.callback.call(this.scope || this);
		}
		this.callback = null;
		this.scope = null;
	},

	destroy: function () {
		Ext.destroy(this.ghost, this.el);
	}
}; /**
 * @class Ext.dd.DragSource
 * @extends Ext.dd.DDProxy
 * A simple class that provides the basic implementation needed to make any element draggable.
 * @constructor
 * @param {Mixed} el The container element
 * @param {Object} config
 */
Ext.dd.DragSource = function (el, config) {
	this.el = Ext.get(el);
	if (!this.dragData) {
		this.dragData = {};
	}

	Ext.apply(this, config);

	if (!this.proxy) {
		this.proxy = new Ext.dd.StatusProxy();
	}
	Ext.dd.DragSource.superclass.constructor.call(this, this.el.dom, this.ddGroup || this.group,
          { dragElId: this.proxy.id, resizeFrame: false, isTarget: false, scroll: this.scroll === true });

	this.dragging = false;
};

Ext.extend(Ext.dd.DragSource, Ext.dd.DDProxy, {
	/**
	* @cfg {String} ddGroup
	* A named drag drop group to which this object belongs.  If a group is specified, then this object will only
	* interact with other drag drop objects in the same group (defaults to undefined).
	*/
	/**
	* @cfg {String} dropAllowed
	* The CSS class returned to the drag source when drop is allowed (defaults to "x-dd-drop-ok").
	*/
	dropAllowed: "x-dd-drop-ok",
	/**
	* @cfg {String} dropNotAllowed
	* The CSS class returned to the drag source when drop is not allowed (defaults to "x-dd-drop-nodrop").
	*/
	dropNotAllowed: "x-dd-drop-nodrop",

	/**
	* Returns the data object associated with this drag source
	* @return {Object} data An object containing arbitrary data
	*/
	getDragData: function (e) {
		return this.dragData;
	},

	// private
	onDragEnter: function (e, id) {
		var target = Ext.dd.DragDropMgr.getDDById(id);
		this.cachedTarget = target;
		if (this.beforeDragEnter(target, e, id) !== false) {
			if (target.isNotifyTarget) {
				var status = target.notifyEnter(this, e, this.dragData);
				this.proxy.setStatus(status);
			} else {
				this.proxy.setStatus(this.dropAllowed);
			}

			if (this.afterDragEnter) {
				/**
				* An empty function by default, but provided so that you can perform a custom action
				* when the dragged item enters the drop target by providing an implementation.
				* @param {Ext.dd.DragDrop} target The drop target
				* @param {Event} e The event object
				* @param {String} id The id of the dragged element
				* @method afterDragEnter
				*/
				this.afterDragEnter(target, e, id);
			}
		}
	},

	/**
	* An empty function by default, but provided so that you can perform a custom action
	* before the dragged item enters the drop target and optionally cancel the onDragEnter.
	* @param {Ext.dd.DragDrop} target The drop target
	* @param {Event} e The event object
	* @param {String} id The id of the dragged element
	* @return {Boolean} isValid True if the drag event is valid, else false to cancel
	*/
	beforeDragEnter: function (target, e, id) {
		return true;
	},

	// private
	alignElWithMouse: function () {
		Ext.dd.DragSource.superclass.alignElWithMouse.apply(this, arguments);
		this.proxy.sync();
	},

	// private
	onDragOver: function (e, id) {
		var target = this.cachedTarget || Ext.dd.DragDropMgr.getDDById(id);
		if (this.beforeDragOver(target, e, id) !== false) {
			if (target.isNotifyTarget) {
				var status = target.notifyOver(this, e, this.dragData);
				this.proxy.setStatus(status);
			}

			if (this.afterDragOver) {
				/**
				* An empty function by default, but provided so that you can perform a custom action
				* while the dragged item is over the drop target by providing an implementation.
				* @param {Ext.dd.DragDrop} target The drop target
				* @param {Event} e The event object
				* @param {String} id The id of the dragged element
				* @method afterDragOver
				*/
				this.afterDragOver(target, e, id);
			}
		}
	},

	/**
	* An empty function by default, but provided so that you can perform a custom action
	* while the dragged item is over the drop target and optionally cancel the onDragOver.
	* @param {Ext.dd.DragDrop} target The drop target
	* @param {Event} e The event object
	* @param {String} id The id of the dragged element
	* @return {Boolean} isValid True if the drag event is valid, else false to cancel
	*/
	beforeDragOver: function (target, e, id) {
		return true;
	},

	// private
	onDragOut: function (e, id) {
		var target = this.cachedTarget || Ext.dd.DragDropMgr.getDDById(id);
		if (this.beforeDragOut(target, e, id) !== false) {
			if (target.isNotifyTarget) {
				target.notifyOut(this, e, this.dragData);
			}
			this.proxy.reset();
			if (this.afterDragOut) {
				/**
				* An empty function by default, but provided so that you can perform a custom action
				* after the dragged item is dragged out of the target without dropping.
				* @param {Ext.dd.DragDrop} target The drop target
				* @param {Event} e The event object
				* @param {String} id The id of the dragged element
				* @method afterDragOut
				*/
				this.afterDragOut(target, e, id);
			}
		}
		this.cachedTarget = null;
	},

	/**
	* An empty function by default, but provided so that you can perform a custom action before the dragged
	* item is dragged out of the target without dropping, and optionally cancel the onDragOut.
	* @param {Ext.dd.DragDrop} target The drop target
	* @param {Event} e The event object
	* @param {String} id The id of the dragged element
	* @return {Boolean} isValid True if the drag event is valid, else false to cancel
	*/
	beforeDragOut: function (target, e, id) {
		return true;
	},

	// private
	onDragDrop: function (e, id) {
		var target = this.cachedTarget || Ext.dd.DragDropMgr.getDDById(id);
		if (this.beforeDragDrop(target, e, id) !== false) {
			if (target.isNotifyTarget) {
				if (target.notifyDrop(this, e, this.dragData)) { // valid drop?
					this.onValidDrop(target, e, id);
				} else {
					this.onInvalidDrop(target, e, id);
				}
			} else {
				this.onValidDrop(target, e, id);
			}

			if (this.afterDragDrop) {
				/**
				* An empty function by default, but provided so that you can perform a custom action
				* after a valid drag drop has occurred by providing an implementation.
				* @param {Ext.dd.DragDrop} target The drop target
				* @param {Event} e The event object
				* @param {String} id The id of the dropped element
				* @method afterDragDrop
				*/
				this.afterDragDrop(target, e, id);
			}
		}
		delete this.cachedTarget;
	},

	/**
	* An empty function by default, but provided so that you can perform a custom action before the dragged
	* item is dropped onto the target and optionally cancel the onDragDrop.
	* @param {Ext.dd.DragDrop} target The drop target
	* @param {Event} e The event object
	* @param {String} id The id of the dragged element
	* @return {Boolean} isValid True if the drag drop event is valid, else false to cancel
	*/
	beforeDragDrop: function (target, e, id) {
		return true;
	},

	// private
	onValidDrop: function (target, e, id) {
		this.hideProxy();
		if (this.afterValidDrop) {
			/**
			* An empty function by default, but provided so that you can perform a custom action
			* after a valid drop has occurred by providing an implementation.
			* @param {Object} target The target DD 
			* @param {Event} e The event object
			* @param {String} id The id of the dropped element
			* @method afterInvalidDrop
			*/
			this.afterValidDrop(target, e, id);
		}
	},

	// private
	getRepairXY: function (e, data) {
		return this.el.getXY();
	},

	// private
	onInvalidDrop: function (target, e, id) {
		this.beforeInvalidDrop(target, e, id);
		if (this.cachedTarget) {
			if (this.cachedTarget.isNotifyTarget) {
				this.cachedTarget.notifyOut(this, e, this.dragData);
			}
			this.cacheTarget = null;
		}
		this.proxy.repair(this.getRepairXY(e, this.dragData), this.afterRepair, this);

		if (this.afterInvalidDrop) {
			/**
			* An empty function by default, but provided so that you can perform a custom action
			* after an invalid drop has occurred by providing an implementation.
			* @param {Event} e The event object
			* @param {String} id The id of the dropped element
			* @method afterInvalidDrop
			*/
			this.afterInvalidDrop(e, id);
		}
	},

	// private
	afterRepair: function () {
		if (Ext.enableFx) {
			this.el.highlight(this.hlColor || "c3daf9");
		}
		this.dragging = false;
	},

	/**
	* An empty function by default, but provided so that you can perform a custom action after an invalid
	* drop has occurred.
	* @param {Ext.dd.DragDrop} target The drop target
	* @param {Event} e The event object
	* @param {String} id The id of the dragged element
	* @return {Boolean} isValid True if the invalid drop should proceed, else false to cancel
	*/
	beforeInvalidDrop: function (target, e, id) {
		return true;
	},

	// private
	handleMouseDown: function (e) {
		if (this.dragging) {
			return;
		}
		var data = this.getDragData(e);
		if (data && this.onBeforeDrag(data, e) !== false) {
			this.dragData = data;
			this.proxy.stop();
			Ext.dd.DragSource.superclass.handleMouseDown.apply(this, arguments);
		}
	},

	/**
	* An empty function by default, but provided so that you can perform a custom action before the initial
	* drag event begins and optionally cancel it.
	* @param {Object} data An object containing arbitrary data to be shared with drop targets
	* @param {Event} e The event object
	* @return {Boolean} isValid True if the drag event is valid, else false to cancel
	*/
	onBeforeDrag: function (data, e) {
		return true;
	},

	/**
	* An empty function by default, but provided so that you can perform a custom action once the initial
	* drag event has begun.  The drag cannot be canceled from this function.
	* @param {Number} x The x position of the click on the dragged object
	* @param {Number} y The y position of the click on the dragged object
	*/
	onStartDrag: Ext.emptyFn,

	// private override
	startDrag: function (x, y) {
		this.proxy.reset();
		this.dragging = true;
		this.proxy.update("");
		this.onInitDrag(x, y);
		this.proxy.show();
	},

	// private
	onInitDrag: function (x, y) {
		var clone = this.el.dom.cloneNode(true);
		clone.id = Ext.id(); // prevent duplicate ids
		this.proxy.update(clone);
		this.onStartDrag(x, y);
		return true;
	},

	/**
	* Returns the drag source's underlying {@link Ext.dd.StatusProxy}
	* @return {Ext.dd.StatusProxy} proxy The StatusProxy
	*/
	getProxy: function () {
		return this.proxy;
	},

	/**
	* Hides the drag source's {@link Ext.dd.StatusProxy}
	*/
	hideProxy: function () {
		this.proxy.hide();
		this.proxy.reset(true);
		this.dragging = false;
	},

	// private
	triggerCacheRefresh: function () {
		Ext.dd.DDM.refreshCache(this.groups);
	},

	// private - override to prevent hiding
	b4EndDrag: function (e) {
	},

	// private - override to prevent moving
	endDrag: function (e) {
		this.onEndDrag(this.dragData, e);
	},

	// private
	onEndDrag: function (data, e) {
	},

	// private - pin to cursor
	autoOffset: function (x, y) {
		this.setDelta(-12, -20);
	},

	destroy: function () {
		Ext.dd.DragSource.superclass.destroy.call(this);
		Ext.destroy(this.proxy);
	}
}); /**
 * @class Ext.dd.DropTarget
 * @extends Ext.dd.DDTarget
 * A simple class that provides the basic implementation needed to make any element a drop target that can have
 * draggable items dropped onto it.  The drop has no effect until an implementation of notifyDrop is provided.
 * @constructor
 * @param {Mixed} el The container element
 * @param {Object} config
 */
Ext.dd.DropTarget = function (el, config) {
	this.el = Ext.get(el);

	Ext.apply(this, config);

	if (this.containerScroll) {
		Ext.dd.ScrollManager.register(this.el);
	}

	Ext.dd.DropTarget.superclass.constructor.call(this, this.el.dom, this.ddGroup || this.group,
          { isTarget: true });

};

Ext.extend(Ext.dd.DropTarget, Ext.dd.DDTarget, {
	/**
	* @cfg {String} ddGroup
	* A named drag drop group to which this object belongs.  If a group is specified, then this object will only
	* interact with other drag drop objects in the same group (defaults to undefined).
	*/
	/**
	* @cfg {String} overClass
	* The CSS class applied to the drop target element while the drag source is over it (defaults to "").
	*/
	/**
	* @cfg {String} dropAllowed
	* The CSS class returned to the drag source when drop is allowed (defaults to "x-dd-drop-ok").
	*/
	dropAllowed: "x-dd-drop-ok",
	/**
	* @cfg {String} dropNotAllowed
	* The CSS class returned to the drag source when drop is not allowed (defaults to "x-dd-drop-nodrop").
	*/
	dropNotAllowed: "x-dd-drop-nodrop",

	// private
	isTarget: true,

	// private
	isNotifyTarget: true,

	/**
	* The function a {@link Ext.dd.DragSource} calls once to notify this drop target that the source is now over the
	* target.  This default implementation adds the CSS class specified by overClass (if any) to the drop element
	* and returns the dropAllowed config value.  This method should be overridden if drop validation is required.
	* @param {Ext.dd.DragSource} source The drag source that was dragged over this drop target
	* @param {Event} e The event
	* @param {Object} data An object containing arbitrary data supplied by the drag source
	* @return {String} status The CSS class that communicates the drop status back to the source so that the
	* underlying {@link Ext.dd.StatusProxy} can be updated
	*/
	notifyEnter: function (dd, e, data) {
		if (this.overClass) {
			this.el.addClass(this.overClass);
		}
		return this.dropAllowed;
	},

	/**
	* The function a {@link Ext.dd.DragSource} calls continuously while it is being dragged over the target.
	* This method will be called on every mouse movement while the drag source is over the drop target.
	* This default implementation simply returns the dropAllowed config value.
	* @param {Ext.dd.DragSource} source The drag source that was dragged over this drop target
	* @param {Event} e The event
	* @param {Object} data An object containing arbitrary data supplied by the drag source
	* @return {String} status The CSS class that communicates the drop status back to the source so that the
	* underlying {@link Ext.dd.StatusProxy} can be updated
	*/
	notifyOver: function (dd, e, data) {
		return this.dropAllowed;
	},

	/**
	* The function a {@link Ext.dd.DragSource} calls once to notify this drop target that the source has been dragged
	* out of the target without dropping.  This default implementation simply removes the CSS class specified by
	* overClass (if any) from the drop element.
	* @param {Ext.dd.DragSource} source The drag source that was dragged over this drop target
	* @param {Event} e The event
	* @param {Object} data An object containing arbitrary data supplied by the drag source
	*/
	notifyOut: function (dd, e, data) {
		if (this.overClass) {
			this.el.removeClass(this.overClass);
		}
	},

	/**
	* The function a {@link Ext.dd.DragSource} calls once to notify this drop target that the dragged item has
	* been dropped on it.  This method has no default implementation and returns false, so you must provide an
	* implementation that does something to process the drop event and returns true so that the drag source's
	* repair action does not run.
	* @param {Ext.dd.DragSource} source The drag source that was dragged over this drop target
	* @param {Event} e The event
	* @param {Object} data An object containing arbitrary data supplied by the drag source
	* @return {Boolean} True if the drop was valid, else false
	*/
	notifyDrop: function (dd, e, data) {
		return false;
	}
}); /**
 * @class Ext.dd.DragZone
 * @extends Ext.dd.DragSource
 * <p>This class provides a container DD instance that allows dragging of multiple child source nodes.</p>
 * <p>This class does not move the drag target nodes, but a proxy element which may contain
 * any DOM structure you wish. The DOM element to show in the proxy is provided by either a
 * provided implementation of {@link #getDragData}, or by registered draggables registered with {@link Ext.dd.Registry}</p>
 * <p>If you wish to provide draggability for an arbitrary number of DOM nodes, each of which represent some
 * application object (For example nodes in a {@link Ext.DataView DataView}) then use of this class
 * is the most efficient way to "activate" those nodes.</p>
 * <p>By default, this class requires that draggable child nodes are registered with {@link Ext.dd.Registry}.
 * However a simpler way to allow a DragZone to manage any number of draggable elements is to configure
 * the DragZone with  an implementation of the {@link #getDragData} method which interrogates the passed
 * mouse event to see if it has taken place within an element, or class of elements. This is easily done
 * by using the event's {@link Ext.EventObject#getTarget getTarget} method to identify a node based on a
 * {@link Ext.DomQuery} selector. For example, to make the nodes of a DataView draggable, use the following
 * technique. Knowledge of the use of the DataView is required:</p><pre><code>
myDataView.on('render', function(v) {
    myDataView.dragZone = new Ext.dd.DragZone(v.getEl(), {

//      On receipt of a mousedown event, see if it is within a DataView node.
//      Return a drag data object if so.
        getDragData: function(e) {

//          Use the DataView's own itemSelector (a mandatory property) to
//          test if the mousedown is within one of the DataView's nodes.
            var sourceEl = e.getTarget(v.itemSelector, 10);

//          If the mousedown is within a DataView node, clone the node to produce
//          a ddel element for use by the drag proxy. Also add application data
//          to the returned data object.
            if (sourceEl) {
                d = sourceEl.cloneNode(true);
                d.id = Ext.id();
                return {
                    ddel: d,
                    sourceEl: sourceEl,
                    repairXY: Ext.fly(sourceEl).getXY(),
                    sourceStore: v.store,
                    draggedRecord: v.{@link Ext.DataView#getRecord getRecord}(sourceEl)
                }
            }
        },

//      Provide coordinates for the proxy to slide back to on failed drag.
//      This is the original XY coordinates of the draggable element captured
//      in the getDragData method.
        getRepairXY: function() {
            return this.dragData.repairXY;
        }
    });
});</code></pre>
 * See the {@link Ext.dd.DropZone DropZone} documentation for details about building a DropZone which
 * cooperates with this DragZone.
 * @constructor
 * @param {Mixed} el The container element
 * @param {Object} config
 */
Ext.dd.DragZone = function (el, config) {
	Ext.dd.DragZone.superclass.constructor.call(this, el, config);
	if (this.containerScroll) {
		Ext.dd.ScrollManager.register(this.el);
	}
};

Ext.extend(Ext.dd.DragZone, Ext.dd.DragSource, {
	/**
	* This property contains the data representing the dragged object. This data is set up by the implementation
	* of the {@link #getDragData} method. It must contain a <tt>ddel</tt> property, but can contain
	* any other data according to the application's needs.
	* @type Object
	* @property dragData
	*/
	/**
	* @cfg {Boolean} containerScroll True to register this container with the Scrollmanager
	* for auto scrolling during drag operations.
	*/
	/**
	* @cfg {String} hlColor The color to use when visually highlighting the drag source in the afterRepair
	* method after a failed drop (defaults to "c3daf9" - light blue)
	*/

	/**
	* Called when a mousedown occurs in this container. Looks in {@link Ext.dd.Registry}
	* for a valid target to drag based on the mouse down. Override this method
	* to provide your own lookup logic (e.g. finding a child by class name). Make sure your returned
	* object has a "ddel" attribute (with an HTML Element) for other functions to work.
	* @param {EventObject} e The mouse down event
	* @return {Object} The dragData
	*/
	getDragData: function (e) {
		return Ext.dd.Registry.getHandleFromEvent(e);
	},

	/**
	* Called once drag threshold has been reached to initialize the proxy element. By default, it clones the
	* this.dragData.ddel
	* @param {Number} x The x position of the click on the dragged object
	* @param {Number} y The y position of the click on the dragged object
	* @return {Boolean} true to continue the drag, false to cancel
	*/
	onInitDrag: function (x, y) {
		this.proxy.update(this.dragData.ddel.cloneNode(true));
		this.onStartDrag(x, y);
		return true;
	},

	/**
	* Called after a repair of an invalid drop. By default, highlights this.dragData.ddel 
	*/
	afterRepair: function () {
		if (Ext.enableFx) {
			Ext.Element.fly(this.dragData.ddel).highlight(this.hlColor || "c3daf9");
		}
		this.dragging = false;
	},

	/**
	* Called before a repair of an invalid drop to get the XY to animate to. By default returns
	* the XY of this.dragData.ddel
	* @param {EventObject} e The mouse up event
	* @return {Array} The xy location (e.g. [100, 200])
	*/
	getRepairXY: function (e) {
		return Ext.Element.fly(this.dragData.ddel).getXY();
	}
}); /**
 * @class Ext.dd.DropZone
 * @extends Ext.dd.DropTarget
 * <p>This class provides a container DD instance that allows dropping on multiple child target nodes.</p>
 * <p>By default, this class requires that child nodes accepting drop are registered with {@link Ext.dd.Registry}.
 * However a simpler way to allow a DropZone to manage any number of target elements is to configure the
 * DropZone with an implementation of {@link #getTargetFromEvent} which interrogates the passed
 * mouse event to see if it has taken place within an element, or class of elements. This is easily done
 * by using the event's {@link Ext.EventObject#getTarget getTarget} method to identify a node based on a
 * {@link Ext.DomQuery} selector.</p>
 * <p>Once the DropZone has detected through calling getTargetFromEvent, that the mouse is over
 * a drop target, that target is passed as the first parameter to {@link #onNodeEnter}, {@link #onNodeOver},
 * {@link #onNodeOut}, {@link #onNodeDrop}. You may configure the instance of DropZone with implementations
 * of these methods to provide application-specific behaviour for these events to update both
 * application state, and UI state.</p>
 * <p>For example to make a GridPanel a cooperating target with the example illustrated in
 * {@link Ext.dd.DragZone DragZone}, the following technique might be used:</p><pre><code>
myGridPanel.on('render', function() {
    myGridPanel.dropZone = new Ext.dd.DropZone(myGridPanel.getView().scroller, {

//      If the mouse is over a grid row, return that node. This is
//      provided as the "target" parameter in all "onNodeXXXX" node event handling functions
        getTargetFromEvent: function(e) {
            return e.getTarget(myGridPanel.getView().rowSelector);
        },

//      On entry into a target node, highlight that node.
        onNodeEnter : function(target, dd, e, data){ 
            Ext.fly(target).addClass('my-row-highlight-class');
        },

//      On exit from a target node, unhighlight that node.
        onNodeOut : function(target, dd, e, data){ 
            Ext.fly(target).removeClass('my-row-highlight-class');
        },

//      While over a target node, return the default drop allowed class which
//      places a "tick" icon into the drag proxy.
        onNodeOver : function(target, dd, e, data){ 
            return Ext.dd.DropZone.prototype.dropAllowed;
        },

//      On node drop we can interrogate the target to find the underlying
//      application object that is the real target of the dragged data.
//      In this case, it is a Record in the GridPanel's Store.
//      We can use the data set up by the DragZone's getDragData method to read
//      any data we decided to attach in the DragZone's getDragData method.
        onNodeDrop : function(target, dd, e, data){
            var rowIndex = myGridPanel.getView().findRowIndex(target);
            var r = myGridPanel.getStore().getAt(rowIndex);
            Ext.Msg.alert('Drop gesture', 'Dropped Record id ' + data.draggedRecord.id +
                ' on Record id ' + r.id);
            return true;
        }
    });
}
</code></pre>
 * See the {@link Ext.dd.DragZone DragZone} documentation for details about building a DragZone which
 * cooperates with this DropZone.
 * @constructor
 * @param {Mixed} el The container element
 * @param {Object} config
 */
Ext.dd.DropZone = function (el, config) {
	Ext.dd.DropZone.superclass.constructor.call(this, el, config);
};

Ext.extend(Ext.dd.DropZone, Ext.dd.DropTarget, {
	/**
	* Returns a custom data object associated with the DOM node that is the target of the event.  By default
	* this looks up the event target in the {@link Ext.dd.Registry}, although you can override this method to
	* provide your own custom lookup.
	* @param {Event} e The event
	* @return {Object} data The custom data
	*/
	getTargetFromEvent: function (e) {
		return Ext.dd.Registry.getTargetFromEvent(e);
	},

	/**
	* Called when the DropZone determines that a {@link Ext.dd.DragSource} has entered a drop node
	* that has either been registered or detected by a configured implementation of {@link #getTargetFromEvent}.
	* This method has no default implementation and should be overridden to provide
	* node-specific processing if necessary.
	* @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from 
	* {@link #getTargetFromEvent} for this node)
	* @param {Ext.dd.DragSource} source The drag source that was dragged over this drop zone
	* @param {Event} e The event
	* @param {Object} data An object containing arbitrary data supplied by the drag source
	*/
	onNodeEnter: function (n, dd, e, data) {

	},

	/**
	* Called while the DropZone determines that a {@link Ext.dd.DragSource} is over a drop node
	* that has either been registered or detected by a configured implementation of {@link #getTargetFromEvent}.
	* The default implementation returns this.dropNotAllowed, so it should be
	* overridden to provide the proper feedback.
	* @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
	* {@link #getTargetFromEvent} for this node)
	* @param {Ext.dd.DragSource} source The drag source that was dragged over this drop zone
	* @param {Event} e The event
	* @param {Object} data An object containing arbitrary data supplied by the drag source
	* @return {String} status The CSS class that communicates the drop status back to the source so that the
	* underlying {@link Ext.dd.StatusProxy} can be updated
	*/
	onNodeOver: function (n, dd, e, data) {
		return this.dropAllowed;
	},

	/**
	* Called when the DropZone determines that a {@link Ext.dd.DragSource} has been dragged out of
	* the drop node without dropping.  This method has no default implementation and should be overridden to provide
	* node-specific processing if necessary.
	* @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
	* {@link #getTargetFromEvent} for this node)
	* @param {Ext.dd.DragSource} source The drag source that was dragged over this drop zone
	* @param {Event} e The event
	* @param {Object} data An object containing arbitrary data supplied by the drag source
	*/
	onNodeOut: function (n, dd, e, data) {

	},

	/**
	* Called when the DropZone determines that a {@link Ext.dd.DragSource} has been dropped onto
	* the drop node.  The default implementation returns false, so it should be overridden to provide the
	* appropriate processing of the drop event and return true so that the drag source's repair action does not run.
	* @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
	* {@link #getTargetFromEvent} for this node)
	* @param {Ext.dd.DragSource} source The drag source that was dragged over this drop zone
	* @param {Event} e The event
	* @param {Object} data An object containing arbitrary data supplied by the drag source
	* @return {Boolean} True if the drop was valid, else false
	*/
	onNodeDrop: function (n, dd, e, data) {
		return false;
	},

	/**
	* Called while the DropZone determines that a {@link Ext.dd.DragSource} is being dragged over it,
	* but not over any of its registered drop nodes.  The default implementation returns this.dropNotAllowed, so
	* it should be overridden to provide the proper feedback if necessary.
	* @param {Ext.dd.DragSource} source The drag source that was dragged over this drop zone
	* @param {Event} e The event
	* @param {Object} data An object containing arbitrary data supplied by the drag source
	* @return {String} status The CSS class that communicates the drop status back to the source so that the
	* underlying {@link Ext.dd.StatusProxy} can be updated
	*/
	onContainerOver: function (dd, e, data) {
		return this.dropNotAllowed;
	},

	/**
	* Called when the DropZone determines that a {@link Ext.dd.DragSource} has been dropped on it,
	* but not on any of its registered drop nodes.  The default implementation returns false, so it should be
	* overridden to provide the appropriate processing of the drop event if you need the drop zone itself to
	* be able to accept drops.  It should return true when valid so that the drag source's repair action does not run.
	* @param {Ext.dd.DragSource} source The drag source that was dragged over this drop zone
	* @param {Event} e The event
	* @param {Object} data An object containing arbitrary data supplied by the drag source
	* @return {Boolean} True if the drop was valid, else false
	*/
	onContainerDrop: function (dd, e, data) {
		return false;
	},

	/**
	* The function a {@link Ext.dd.DragSource} calls once to notify this drop zone that the source is now over
	* the zone.  The default implementation returns this.dropNotAllowed and expects that only registered drop
	* nodes can process drag drop operations, so if you need the drop zone itself to be able to process drops
	* you should override this method and provide a custom implementation.
	* @param {Ext.dd.DragSource} source The drag source that was dragged over this drop zone
	* @param {Event} e The event
	* @param {Object} data An object containing arbitrary data supplied by the drag source
	* @return {String} status The CSS class that communicates the drop status back to the source so that the
	* underlying {@link Ext.dd.StatusProxy} can be updated
	*/
	notifyEnter: function (dd, e, data) {
		return this.dropNotAllowed;
	},

	/**
	* The function a {@link Ext.dd.DragSource} calls continuously while it is being dragged over the drop zone.
	* This method will be called on every mouse movement while the drag source is over the drop zone.
	* It will call {@link #onNodeOver} while the drag source is over a registered node, and will also automatically
	* delegate to the appropriate node-specific methods as necessary when the drag source enters and exits
	* registered nodes ({@link #onNodeEnter}, {@link #onNodeOut}). If the drag source is not currently over a
	* registered node, it will call {@link #onContainerOver}.
	* @param {Ext.dd.DragSource} source The drag source that was dragged over this drop zone
	* @param {Event} e The event
	* @param {Object} data An object containing arbitrary data supplied by the drag source
	* @return {String} status The CSS class that communicates the drop status back to the source so that the
	* underlying {@link Ext.dd.StatusProxy} can be updated
	*/
	notifyOver: function (dd, e, data) {
		var n = this.getTargetFromEvent(e);
		if (!n) { // not over valid drop target
			if (this.lastOverNode) {
				this.onNodeOut(this.lastOverNode, dd, e, data);
				this.lastOverNode = null;
			}
			return this.onContainerOver(dd, e, data);
		}
		if (this.lastOverNode != n) {
			if (this.lastOverNode) {
				this.onNodeOut(this.lastOverNode, dd, e, data);
			}
			this.onNodeEnter(n, dd, e, data);
			this.lastOverNode = n;
		}
		return this.onNodeOver(n, dd, e, data);
	},

	/**
	* The function a {@link Ext.dd.DragSource} calls once to notify this drop zone that the source has been dragged
	* out of the zone without dropping.  If the drag source is currently over a registered node, the notification
	* will be delegated to {@link #onNodeOut} for node-specific handling, otherwise it will be ignored.
	* @param {Ext.dd.DragSource} source The drag source that was dragged over this drop target
	* @param {Event} e The event
	* @param {Object} data An object containing arbitrary data supplied by the drag zone
	*/
	notifyOut: function (dd, e, data) {
		if (this.lastOverNode) {
			this.onNodeOut(this.lastOverNode, dd, e, data);
			this.lastOverNode = null;
		}
	},

	/**
	* The function a {@link Ext.dd.DragSource} calls once to notify this drop zone that the dragged item has
	* been dropped on it.  The drag zone will look up the target node based on the event passed in, and if there
	* is a node registered for that event, it will delegate to {@link #onNodeDrop} for node-specific handling,
	* otherwise it will call {@link #onContainerDrop}.
	* @param {Ext.dd.DragSource} source The drag source that was dragged over this drop zone
	* @param {Event} e The event
	* @param {Object} data An object containing arbitrary data supplied by the drag source
	* @return {Boolean} True if the drop was valid, else false
	*/
	notifyDrop: function (dd, e, data) {
		if (this.lastOverNode) {
			this.onNodeOut(this.lastOverNode, dd, e, data);
			this.lastOverNode = null;
		}
		var n = this.getTargetFromEvent(e);
		return n ?
            this.onNodeDrop(n, dd, e, data) :
            this.onContainerDrop(dd, e, data);
	},

	// private
	triggerCacheRefresh: function () {
		Ext.dd.DDM.refreshCache(this.groups);
	}
}); /**
 * @class Ext.Element
 */
Ext.Element.addMethods({
	/**
	* Initializes a {@link Ext.dd.DD} drag drop object for this element.
	* @param {String} group The group the DD object is member of
	* @param {Object} config The DD config object
	* @param {Object} overrides An object containing methods to override/implement on the DD object
	* @return {Ext.dd.DD} The DD object
	*/
	initDD: function (group, config, overrides) {
		var dd = new Ext.dd.DD(Ext.id(this.dom), group, config);
		return Ext.apply(dd, overrides);
	},

	/**
	* Initializes a {@link Ext.dd.DDProxy} object for this element.
	* @param {String} group The group the DDProxy object is member of
	* @param {Object} config The DDProxy config object
	* @param {Object} overrides An object containing methods to override/implement on the DDProxy object
	* @return {Ext.dd.DDProxy} The DDProxy object
	*/
	initDDProxy: function (group, config, overrides) {
		var dd = new Ext.dd.DDProxy(Ext.id(this.dom), group, config);
		return Ext.apply(dd, overrides);
	},

	/**
	* Initializes a {@link Ext.dd.DDTarget} object for this element.
	* @param {String} group The group the DDTarget object is member of
	* @param {Object} config The DDTarget config object
	* @param {Object} overrides An object containing methods to override/implement on the DDTarget object
	* @return {Ext.dd.DDTarget} The DDTarget object
	*/
	initDDTarget: function (group, config, overrides) {
		var dd = new Ext.dd.DDTarget(Ext.id(this.dom), group, config);
		return Ext.apply(dd, overrides);
	}
});
/**
* @class Ext.data.Api
* @extends Object
* Ext.data.Api is a singleton designed to manage the data API including methods
* for validating a developer's DataProxy API.  Defines variables for CRUD actions
* create, read, update and destroy in addition to a mapping of RESTful HTTP methods
* GET, POST, PUT and DELETE to CRUD actions.
* @singleton
*/
Ext.data.Api = (function () {

	// private validActions.  validActions is essentially an inverted hash of Ext.data.Api.actions, where value becomes the key.
	// Some methods in this singleton (e.g.: getActions, getVerb) will loop through actions with the code <code>for (var verb in this.actions)</code>
	// For efficiency, some methods will first check this hash for a match.  Those methods which do acces validActions will cache their result here.
	// We cannot pre-define this hash since the developer may over-ride the actions at runtime.
	var validActions = {};

	return {
		/**
		* Defined actions corresponding to remote actions:
		* <pre><code>
		actions: {
		create  : 'create',  // Text representing the remote-action to create records on server.
		read    : 'read',    // Text representing the remote-action to read/load data from server.
		update  : 'update',  // Text representing the remote-action to update records on server.
		destroy : 'destroy'  // Text representing the remote-action to destroy records on server.
		}
		* </code></pre>
		* @property actions
		* @type Object
		*/
		actions: {
			create: 'create',
			read: 'read',
			update: 'update',
			destroy: 'destroy'
		},

		/**
		* Defined {CRUD action}:{HTTP method} pairs to associate HTTP methods with the
		* corresponding actions for {@link Ext.data.DataProxy#restful RESTful proxies}.
		* Defaults to:
		* <pre><code>
		restActions : {
		create  : 'POST',
		read    : 'GET',
		update  : 'PUT',
		destroy : 'DELETE'
		},
		* </code></pre>
		*/
		restActions: {
			create: 'POST',
			read: 'GET',
			update: 'PUT',
			destroy: 'DELETE'
		},

		/**
		* Returns true if supplied action-name is a valid API action defined in <code>{@link #actions}</code> constants
		* @param {String} action Action to test for availability.
		* @return {Boolean}
		*/
		isAction: function (action) {
			return (Ext.data.Api.actions[action]) ? true : false;
		},

		/**
		* Returns the actual CRUD action KEY "create", "read", "update" or "destroy" from the supplied action-name.  This method is used internally and shouldn't generally
		* need to be used directly.  The key/value pair of Ext.data.Api.actions will often be identical but this is not necessarily true.  A developer can override this naming
		* convention if desired.  However, the framework internally calls methods based upon the KEY so a way of retreiving the the words "create", "read", "update" and "destroy" is
		* required.  This method will cache discovered KEYS into the private validActions hash.
		* @param {String} name The runtime name of the action.
		* @return {String||null} returns the action-key, or verb of the user-action or null if invalid.
		* @nodoc
		*/
		getVerb: function (name) {
			if (validActions[name]) {
				return validActions[name];  // <-- found in cache.  return immediately.
			}
			for (var verb in this.actions) {
				if (this.actions[verb] === name) {
					validActions[name] = verb;
					break;
				}
			}
			return (validActions[name] !== undefined) ? validActions[name] : null;
		},

		/**
		* Returns true if the supplied API is valid; that is, check that all keys match defined actions
		* otherwise returns an array of mistakes.
		* @return {String[]|true}
		*/
		isValid: function (api) {
			var invalid = [];
			var crud = this.actions; // <-- cache a copy of the actions.
			for (var action in api) {
				if (!(action in crud)) {
					invalid.push(action);
				}
			}
			return (!invalid.length) ? true : invalid;
		},

		/**
		* Returns true if the supplied verb upon the supplied proxy points to a unique url in that none of the other api-actions
		* point to the same url.  The question is important for deciding whether to insert the "xaction" HTTP parameter within an
		* Ajax request.  This method is used internally and shouldn't generally need to be called directly.
		* @param {Ext.data.DataProxy} proxy
		* @param {String} verb
		* @return {Boolean}
		*/
		hasUniqueUrl: function (proxy, verb) {
			var url = (proxy.api[verb]) ? proxy.api[verb].url : null;
			var unique = true;
			for (var action in proxy.api) {
				if ((unique = (action === verb) ? true : (proxy.api[action].url != url) ? true : false) === false) {
					break;
				}
			}
			return unique;
		},

		/**
		* This method is used internally by <tt>{@link Ext.data.DataProxy DataProxy}</tt> and should not generally need to be used directly.
		* Each action of a DataProxy api can be initially defined as either a String or an Object.  When specified as an object,
		* one can explicitly define the HTTP method (GET|POST) to use for each CRUD action.  This method will prepare the supplied API, setting
		* each action to the Object form.  If your API-actions do not explicitly define the HTTP method, the "method" configuration-parameter will
		* be used.  If the method configuration parameter is not specified, POST will be used.
		<pre><code>
		new Ext.data.HttpProxy({
		method: "POST",     // <-- default HTTP method when not specified.
		api: {
		create: 'create.php',
		load: 'read.php',
		save: 'save.php',
		destroy: 'destroy.php'
		}
		});

		// Alternatively, one can use the object-form to specify the API
		new Ext.data.HttpProxy({
		api: {
		load: {url: 'read.php', method: 'GET'},
		create: 'create.php',
		destroy: 'destroy.php',
		save: 'update.php'
		}
		});
		</code></pre>
		*
		* @param {Ext.data.DataProxy} proxy
		*/
		prepare: function (proxy) {
			if (!proxy.api) {
				proxy.api = {}; // <-- No api?  create a blank one.
			}
			for (var verb in this.actions) {
				var action = this.actions[verb];
				proxy.api[action] = proxy.api[action] || proxy.url || proxy.directFn;
				if (typeof (proxy.api[action]) == 'string') {
					proxy.api[action] = {
						url: proxy.api[action],
						method: (proxy.restful === true) ? Ext.data.Api.restActions[action] : undefined
					};
				}
			}
		},

		/**
		* Prepares a supplied Proxy to be RESTful.  Sets the HTTP method for each api-action to be one of
		* GET, POST, PUT, DELETE according to the defined {@link #restActions}.
		* @param {Ext.data.DataProxy} proxy
		*/
		restify: function (proxy) {
			proxy.restful = true;
			for (var verb in this.restActions) {
				proxy.api[this.actions[verb]].method ||
                    (proxy.api[this.actions[verb]].method = this.restActions[verb]);
			}
			// TODO: perhaps move this interceptor elsewhere?  like into DataProxy, perhaps?  Placed here
			// to satisfy initial 3.0 final release of REST features.
			proxy.onWrite = proxy.onWrite.createInterceptor(function (action, o, response, rs) {
				var reader = o.reader;
				var res = new Ext.data.Response({
					action: action,
					raw: response
				});

				switch (response.status) {
					case 200:   // standard 200 response, send control back to HttpProxy#onWrite by returning true from this intercepted #onWrite
						return true;
						break;
					case 201:   // entity created but no response returned
						if (Ext.isEmpty(res.raw.responseText)) {
							res.success = true;
						} else {
							//if the response contains data, treat it like a 200
							return true;
						}
						break;
					case 204:  // no-content.  Create a fake response.
						res.success = true;
						res.data = null;
						break;
					default:
						return true;
						break;
				}
				if (res.success === true) {
					this.fireEvent("write", this, action, res.data, res, rs, o.request.arg);
				} else {
					this.fireEvent('exception', this, 'remote', action, o, res, rs);
				}
				o.request.callback.call(o.request.scope, res.data, res, res.success);

				return false;   // <-- false to prevent intercepted function from running.
			}, proxy);
		}
	};
})();

/**
* Ext.data.Response
* Experimental.  Do not use directly.
*/
Ext.data.Response = function (params, response) {
	Ext.apply(this, params, {
		raw: response
	});
};
Ext.data.Response.prototype = {
	message: null,
	success: false,
	status: null,
	root: null,
	raw: null,

	getMessage: function () {
		return this.message;
	},
	getSuccess: function () {
		return this.success;
	},
	getStatus: function () {
		return this.status;
	},
	getRoot: function () {
		return this.root;
	},
	getRawResponse: function () {
		return this.raw;
	}
};

/**
* @class Ext.data.Api.Error
* @extends Ext.Error
* Error class for Ext.data.Api errors
*/
Ext.data.Api.Error = Ext.extend(Ext.Error, {
	constructor: function (message, arg) {
		this.arg = arg;
		Ext.Error.call(this, message);
	},
	name: 'Ext.data.Api'
});
Ext.apply(Ext.data.Api.Error.prototype, {
	lang: {
		'action-url-undefined': 'No fallback url defined for this action.  When defining a DataProxy api, please be sure to define an url for each CRUD action in Ext.data.Api.actions or define a default url in addition to your api-configuration.',
		'invalid': 'received an invalid API-configuration.  Please ensure your proxy API-configuration contains only the actions defined in Ext.data.Api.actions',
		'invalid-url': 'Invalid url.  Please review your proxy configuration.',
		'execute': 'Attempted to execute an unknown action.  Valid API actions are defined in Ext.data.Api.actions"'
	}
});



/**
* @class Ext.data.SortTypes
* @singleton
* Defines the default sorting (casting?) comparison functions used when sorting data.
*/
Ext.data.SortTypes = {
	/**
	* Default sort that does nothing
	* @param {Mixed} s The value being converted
	* @return {Mixed} The comparison value
	*/
	none: function (s) {
		return s;
	},

	/**
	* The regular expression used to strip tags
	* @type {RegExp}
	* @property
	*/
	stripTagsRE: /<\/?[^>]+>/gi,

	/**
	* Strips all HTML tags to sort on text only
	* @param {Mixed} s The value being converted
	* @return {String} The comparison value
	*/
	asText: function (s) {
		return String(s).replace(this.stripTagsRE, "");
	},

	/**
	* Strips all HTML tags to sort on text only - Case insensitive
	* @param {Mixed} s The value being converted
	* @return {String} The comparison value
	*/
	asUCText: function (s) {
		return String(s).toUpperCase().replace(this.stripTagsRE, "");
	},

	/**
	* Case insensitive string
	* @param {Mixed} s The value being converted
	* @return {String} The comparison value
	*/
	asUCString: function (s) {
		return String(s).toUpperCase();
	},

	/**
	* Date sorting
	* @param {Mixed} s The value being converted
	* @return {Number} The comparison value
	*/
	asDate: function (s) {
		if (!s) {
			return 0;
		}
		if (Ext.isDate(s)) {
			return s.getTime();
		}
		return Date.parse(String(s));
	},

	/**
	* Float sorting
	* @param {Mixed} s The value being converted
	* @return {Float} The comparison value
	*/
	asFloat: function (s) {
		var val = parseFloat(String(s).replace(/,/g, ""));
		return isNaN(val) ? 0 : val;
	},

	/**
	* Integer sorting
	* @param {Mixed} s The value being converted
	* @return {Number} The comparison value
	*/
	asInt: function (s) {
		var val = parseInt(String(s).replace(/,/g, ""), 10);
		return isNaN(val) ? 0 : val;
	}
}; /**
 * @class Ext.data.Record
 * <p>Instances of this class encapsulate both Record <em>definition</em> information, and Record
 * <em>value</em> information for use in {@link Ext.data.Store} objects, or any code which needs
 * to access Records cached in an {@link Ext.data.Store} object.</p>
 * <p>Constructors for this class are generated by passing an Array of field definition objects to {@link #create}.
 * Instances are usually only created by {@link Ext.data.Reader} implementations when processing unformatted data
 * objects.</p>
 * <p>Note that an instance of a Record class may only belong to one {@link Ext.data.Store Store} at a time.
 * In order to copy data from one Store to another, use the {@link #copy} method to create an exact
 * copy of the Record, and insert the new instance into the other Store.</p>
 * <p>When serializing a Record for submission to the server, be aware that it contains many private
 * properties, and also a reference to its owning Store which in turn holds references to its Records.
 * This means that a whole Record may not be encoded using {@link Ext.util.JSON.encode}. Instead, use the
 * <code>{@link #data}</code> and <code>{@link #id}</code> properties.</p>
 * <p>Record objects generated by this constructor inherit all the methods of Ext.data.Record listed below.</p>
 * @constructor
 * <p>This constructor should not be used to create Record objects. Instead, use {@link #create} to
 * generate a subclass of Ext.data.Record configured with information about its constituent fields.<p>
 * <p><b>The generated constructor has the same signature as this constructor.</b></p>
 * @param {Object} data (Optional) An object, the properties of which provide values for the new Record's
 * fields. If not specified the <code>{@link Ext.data.Field#defaultValue defaultValue}</code>
 * for each field will be assigned.
 * @param {Object} id (Optional) The id of the Record. The id is used by the
 * {@link Ext.data.Store} object which owns the Record to index its collection
 * of Records (therefore this id should be unique within each store). If an
 * <code>id</code> is not specified a <b><code>{@link #phantom}</code></b>
 * Record will be created with an {@link #Record.id automatically generated id}.
 */
Ext.data.Record = function (data, id) {
	// if no id, call the auto id method
	this.id = (id || id === 0) ? id : Ext.data.Record.id(this);
	this.data = data || {};
};

/**
* Generate a constructor for a specific Record layout.
* @param {Array} o An Array of <b>{@link Ext.data.Field Field}</b> definition objects.
* The constructor generated by this method may be used to create new Record instances. The data
* object must contain properties named after the {@link Ext.data.Field field}
* <b><tt>{@link Ext.data.Field#name}s</tt></b>.  Example usage:<pre><code>
// create a Record constructor from a description of the fields
var TopicRecord = Ext.data.Record.create([ // creates a subclass of Ext.data.Record
{{@link Ext.data.Field#name name}: 'title', {@link Ext.data.Field#mapping mapping}: 'topic_title'},
{name: 'author', mapping: 'username', allowBlank: false},
{name: 'totalPosts', mapping: 'topic_replies', type: 'int'},
{name: 'lastPost', mapping: 'post_time', type: 'date'},
{name: 'lastPoster', mapping: 'user2'},
{name: 'excerpt', mapping: 'post_text', allowBlank: false},
// In the simplest case, if no properties other than <tt>name</tt> are required,
// a field definition may consist of just a String for the field name.
'signature'
]);

// create Record instance
var myNewRecord = new TopicRecord(
{
title: 'Do my job please',
author: 'noobie',
totalPosts: 1,
lastPost: new Date(),
lastPoster: 'Animal',
excerpt: 'No way dude!',
signature: ''
},
id // optionally specify the id of the record otherwise {@link #Record.id one is auto-assigned}
);
myStore.{@link Ext.data.Store#add add}(myNewRecord);
</code></pre>
* @method create
* @return {Function} A constructor which is used to create new Records according
* to the definition. The constructor has the same signature as {@link #Record}.
* @static
*/
Ext.data.Record.create = function (o) {
	var f = Ext.extend(Ext.data.Record, {});
	var p = f.prototype;
	p.fields = new Ext.util.MixedCollection(false, function (field) {
		return field.name;
	});
	for (var i = 0, len = o.length; i < len; i++) {
		p.fields.add(new Ext.data.Field(o[i]));
	}
	f.getField = function (name) {
		return p.fields.get(name);
	};
	return f;
};

Ext.data.Record.PREFIX = 'ext-record';
Ext.data.Record.AUTO_ID = 1;
Ext.data.Record.EDIT = 'edit';
Ext.data.Record.REJECT = 'reject';
Ext.data.Record.COMMIT = 'commit';


/**
* Generates a sequential id. This method is typically called when a record is {@link #create}d
* and {@link #Record no id has been specified}. The returned id takes the form:
* <tt>&#123;PREFIX}-&#123;AUTO_ID}</tt>.<div class="mdetail-params"><ul>
* <li><b><tt>PREFIX</tt></b> : String<p class="sub-desc"><tt>Ext.data.Record.PREFIX</tt>
* (defaults to <tt>'ext-record'</tt>)</p></li>
* <li><b><tt>AUTO_ID</tt></b> : String<p class="sub-desc"><tt>Ext.data.Record.AUTO_ID</tt>
* (defaults to <tt>1</tt> initially)</p></li>
* </ul></div>
* @param {Record} rec The record being created.  The record does not exist, it's a {@link #phantom}.
* @return {String} auto-generated string id, <tt>"ext-record-i++'</tt>;
*/
Ext.data.Record.id = function (rec) {
	rec.phantom = true;
	return [Ext.data.Record.PREFIX, '-', Ext.data.Record.AUTO_ID++].join('');
};

Ext.data.Record.prototype = {
	/**
	* <p><b>This property is stored in the Record definition's <u>prototype</u></b></p>
	* A MixedCollection containing the defined {@link Ext.data.Field Field}s for this Record.  Read-only.
	* @property fields
	* @type Ext.util.MixedCollection
	*/
	/**
	* An object hash representing the data for this Record. Every field name in the Record definition
	* is represented by a property of that name in this object. Note that unless you specified a field
	* with {@link Ext.data.Field#name name} "id" in the Record definition, this will <b>not</b> contain
	* an <tt>id</tt> property.
	* @property data
	* @type {Object}
	*/
	/**
	* The unique ID of the Record {@link #Record as specified at construction time}.
	* @property id
	* @type {Object}
	*/
	/**
	* <p><b>Only present if this Record was created by an {@link Ext.data.XmlReader XmlReader}</b>.</p>
	* <p>The XML element which was the source of the data for this Record.</p>
	* @property node
	* @type {XMLElement}
	*/
	/**
	* <p><b>Only present if this Record was created by an {@link Ext.data.ArrayReader ArrayReader} or a {@link Ext.data.JsonReader JsonReader}</b>.</p>
	* <p>The Array or object which was the source of the data for this Record.</p>
	* @property json
	* @type {Array|Object}
	*/
	/**
	* Readonly flag - true if this Record has been modified.
	* @type Boolean
	*/
	dirty: false,
	editing: false,
	error: null,
	/**
	* This object contains a key and value storing the original values of all modified
	* fields or is null if no fields have been modified.
	* @property modified
	* @type {Object}
	*/
	modified: null,
	/**
	* <tt>true</tt> when the record does not yet exist in a server-side database (see
	* {@link #markDirty}).  Any record which has a real database pk set as its id property
	* is NOT a phantom -- it's real.
	* @property phantom
	* @type {Boolean}
	*/
	phantom: false,

	// private
	join: function (store) {
		/**
		* The {@link Ext.data.Store} to which this Record belongs.
		* @property store
		* @type {Ext.data.Store}
		*/
		this.store = store;
	},

	/**
	* Set the {@link Ext.data.Field#name named field} to the specified value.  For example:
	* <pre><code>
	// record has a field named 'firstname'
	var Employee = Ext.data.Record.{@link #create}([
	{name: 'firstname'},
	...
	]);

	// update the 2nd record in the store:
	var rec = myStore.{@link Ext.data.Store#getAt getAt}(1);

	// set the value (shows dirty flag):
	rec.set('firstname', 'Betty');

	// commit the change (removes dirty flag):
	rec.{@link #commit}();

	// update the record in the store, bypass setting dirty flag,
	// and do not store the change in the {@link Ext.data.Store#getModifiedRecords modified records}
	rec.{@link #data}['firstname'] = 'Wilma'; // updates record, but not the view
	rec.{@link #commit}(); // updates the view
	* </code></pre>
	* <b>Notes</b>:<div class="mdetail-params"><ul>
	* <li>If the store has a writer and <code>autoSave=true</code>, each set()
	* will execute an XHR to the server.</li>
	* <li>Use <code>{@link #beginEdit}</code> to prevent the store's <code>update</code>
	* event firing while using set().</li>
	* <li>Use <code>{@link #endEdit}</code> to have the store's <code>update</code>
	* event fire.</li>
	* </ul></div>
	* @param {String} name The {@link Ext.data.Field#name name of the field} to set.
	* @param {String/Object/Array} value The value to set the field to.
	*/
	set: function (name, value) {
		var encode = Ext.isPrimitive(value) ? String : Ext.encode;
		if (encode(this.data[name]) == encode(value)) {
			return;
		}
		this.dirty = true;
		if (!this.modified) {
			this.modified = {};
		}
		if (this.modified[name] === undefined) {
			this.modified[name] = this.data[name];
		}
		this.data[name] = value;
		if (!this.editing) {
			this.afterEdit();
		}
	},

	// private
	afterEdit: function () {
		if (this.store != undefined && typeof this.store.afterEdit == "function") {
			this.store.afterEdit(this);
		}
	},

	// private
	afterReject: function () {
		if (this.store) {
			this.store.afterReject(this);
		}
	},

	// private
	afterCommit: function () {
		if (this.store) {
			this.store.afterCommit(this);
		}
	},

	/**
	* Get the value of the {@link Ext.data.Field#name named field}.
	* @param {String} name The {@link Ext.data.Field#name name of the field} to get the value of.
	* @return {Object} The value of the field.
	*/
	get: function (name) {
		return this.data[name];
	},

	/**
	* Begin an edit. While in edit mode, no events (e.g.. the <code>update</code> event)
	* are relayed to the containing store.
	* See also: <code>{@link #endEdit}</code> and <code>{@link #cancelEdit}</code>.
	*/
	beginEdit: function () {
		this.editing = true;
		this.modified = this.modified || {};
	},

	/**
	* Cancels all changes made in the current edit operation.
	*/
	cancelEdit: function () {
		this.editing = false;
		delete this.modified;
	},

	/**
	* End an edit. If any data was modified, the containing store is notified
	* (ie, the store's <code>update</code> event will fire).
	*/
	endEdit: function () {
		this.editing = false;
		if (this.dirty) {
			this.afterEdit();
		}
	},

	/**
	* Usually called by the {@link Ext.data.Store} which owns the Record.
	* Rejects all changes made to the Record since either creation, or the last commit operation.
	* Modified fields are reverted to their original values.
	* <p>Developers should subscribe to the {@link Ext.data.Store#update} event
	* to have their code notified of reject operations.</p>
	* @param {Boolean} silent (optional) True to skip notification of the owning
	* store of the change (defaults to false)
	*/
	reject: function (silent) {
		var m = this.modified;
		for (var n in m) {
			if (typeof m[n] != "function") {
				this.data[n] = m[n];
			}
		}
		this.dirty = false;
		delete this.modified;
		this.editing = false;
		if (silent !== true) {
			this.afterReject();
		}
	},

	/**
	* Usually called by the {@link Ext.data.Store} which owns the Record.
	* Commits all changes made to the Record since either creation, or the last commit operation.
	* <p>Developers should subscribe to the {@link Ext.data.Store#update} event
	* to have their code notified of commit operations.</p>
	* @param {Boolean} silent (optional) True to skip notification of the owning
	* store of the change (defaults to false)
	*/
	commit: function (silent) {
		this.dirty = false;
		delete this.modified;
		this.editing = false;
		if (silent !== true) {
			this.afterCommit();
		}
	},

	/**
	* Gets a hash of only the fields that have been modified since this Record was created or commited.
	* @return Object
	*/
	getChanges: function () {
		var m = this.modified, cs = {};
		for (var n in m) {
			if (m.hasOwnProperty(n)) {
				cs[n] = this.data[n];
			}
		}
		return cs;
	},

	// private
	hasError: function () {
		return this.error !== null;
	},

	// private
	clearError: function () {
		this.error = null;
	},

	/**
	* Creates a copy (clone) of this Record.
	* @param {String} id (optional) A new Record id, defaults to the id
	* of the record being copied. See <code>{@link #id}</code>. 
	* To generate a phantom record with a new id use:<pre><code>
	var rec = record.copy(); // clone the record
	Ext.data.Record.id(rec); // automatically generate a unique sequential id
	* </code></pre>
	* @return {Record}
	*/
	copy: function (newId) {
		return new this.constructor(Ext.apply({}, this.data), newId || this.id);
	},

	/**
	* Returns <tt>true</tt> if the passed field name has been <code>{@link #modified}</code>
	* since the load or last commit.
	* @param {String} fieldName {@link Ext.data.Field.{@link Ext.data.Field#name}
	* @return {Boolean}
	*/
	isModified: function (fieldName) {
		return !!(this.modified && this.modified.hasOwnProperty(fieldName));
	},

	/**
	* By default returns <tt>false</tt> if any {@link Ext.data.Field field} within the
	* record configured with <tt>{@link Ext.data.Field#allowBlank} = false</tt> returns
	* <tt>true</tt> from an {@link Ext}.{@link Ext#isEmpty isempty} test.
	* @return {Boolean}
	*/
	isValid: function () {
		return this.fields.find(function (f) {
			return (f.allowBlank === false && Ext.isEmpty(this.data[f.name])) ? true : false;
		}, this) ? false : true;
	},

	/**
	* <p>Marks this <b>Record</b> as <code>{@link #dirty}</code>.  This method
	* is used interally when adding <code>{@link #phantom}</code> records to a
	* {@link Ext.data.Store#writer writer enabled store}.</p>
	* <br><p>Marking a record <code>{@link #dirty}</code> causes the phantom to
	* be returned by {@link Ext.data.Store#getModifiedRecords} where it will
	* have a create action composed for it during {@link Ext.data.Store#save store save}
	* operations.</p>
	*/
	markDirty: function () {
		this.dirty = true;
		if (!this.modified) {
			this.modified = {};
		}
		this.fields.each(function (f) {
			this.modified[f.name] = this.data[f.name];
		}, this);
	}
};
/**
* @class Ext.StoreMgr
* @extends Ext.util.MixedCollection
* The default global group of stores.
* @singleton
*/
Ext.StoreMgr = Ext.apply(new Ext.util.MixedCollection(), {
	/**
	* @cfg {Object} listeners @hide
	*/

	/**
	* Registers one or more Stores with the StoreMgr. You do not normally need to register stores
	* manually.  Any store initialized with a {@link Ext.data.Store#storeId} will be auto-registered. 
	* @param {Ext.data.Store} store1 A Store instance
	* @param {Ext.data.Store} store2 (optional)
	* @param {Ext.data.Store} etc... (optional)
	*/
	register: function () {
		for (var i = 0, s; (s = arguments[i]); i++) {
			this.add(s);
		}
	},

	/**
	* Unregisters one or more Stores with the StoreMgr
	* @param {String/Object} id1 The id of the Store, or a Store instance
	* @param {String/Object} id2 (optional)
	* @param {String/Object} etc... (optional)
	*/
	unregister: function () {
		for (var i = 0, s; (s = arguments[i]); i++) {
			this.remove(this.lookup(s));
		}
	},

	/**
	* Gets a registered Store by id
	* @param {String/Object} id The id of the Store, or a Store instance
	* @return {Ext.data.Store}
	*/
	lookup: function (id) {
		if (Ext.isArray(id)) {
			var fields = ['field1'], expand = !Ext.isArray(id[0]);
			if (!expand) {
				for (var i = 2, len = id[0].length; i <= len; ++i) {
					fields.push('field' + i);
				}
			}
			return new Ext.data.ArrayStore({
				fields: fields,
				data: id,
				expandData: expand,
				autoDestroy: true,
				autoCreated: true

			});
		}
		return Ext.isObject(id) ? (id.events ? id : Ext.create(id, 'store')) : this.get(id);
	},

	// getKey implementation for MixedCollection
	getKey: function (o) {
		return o.storeId;
	}
}); /**
 * @class Ext.data.Store
 * @extends Ext.util.Observable
 * <p>The Store class encapsulates a client side cache of {@link Ext.data.Record Record}
 * objects which provide input data for Components such as the {@link Ext.grid.GridPanel GridPanel},
 * the {@link Ext.form.ComboBox ComboBox}, or the {@link Ext.DataView DataView}.</p>
 * <p><u>Retrieving Data</u></p>
 * <p>A Store object may access a data object using:<div class="mdetail-params"><ul>
 * <li>{@link #proxy configured implementation} of {@link Ext.data.DataProxy DataProxy}</li>
 * <li>{@link #data} to automatically pass in data</li>
 * <li>{@link #loadData} to manually pass in data</li>
 * </ul></div></p>
 * <p><u>Reading Data</u></p>
 * <p>A Store object has no inherent knowledge of the format of the data object (it could be
 * an Array, XML, or JSON). A Store object uses an appropriate {@link #reader configured implementation}
 * of a {@link Ext.data.DataReader DataReader} to create {@link Ext.data.Record Record} instances from the data
 * object.</p>
 * <p><u>Store Types</u></p>
 * <p>There are several implementations of Store available which are customized for use with
 * a specific DataReader implementation.  Here is an example using an ArrayStore which implicitly
 * creates a reader commensurate to an Array data object.</p>
 * <pre><code>
var myStore = new Ext.data.ArrayStore({
    fields: ['fullname', 'first'],
    idIndex: 0 // id for each record will be the first element
});
 * </code></pre>
 * <p>For custom implementations create a basic {@link Ext.data.Store} configured as needed:</p>
 * <pre><code>
// create a {@link Ext.data.Record Record} constructor:
var rt = Ext.data.Record.create([
    {name: 'fullname'},
    {name: 'first'}
]);
var myStore = new Ext.data.Store({
    // explicitly create reader
    reader: new Ext.data.ArrayReader(
        {
            idIndex: 0  // id for each record will be the first element
        },
        rt // recordType
    )
});
 * </code></pre>
 * <p>Load some data into store (note the data object is an array which corresponds to the reader):</p>
 * <pre><code>
var myData = [
    [1, 'Fred Flintstone', 'Fred'],  // note that id for the record is the first element
    [2, 'Barney Rubble', 'Barney']
];
myStore.loadData(myData);
 * </code></pre>
 * <p>Records are cached and made available through accessor functions.  An example of adding
 * a record to the store:</p>
 * <pre><code>
var defaultData = {
    fullname: 'Full Name',
    first: 'First Name'
};
var recId = 100; // provide unique id for the record
var r = new myStore.recordType(defaultData, ++recId); // create new record
myStore.{@link #insert}(0, r); // insert a new record into the store (also see {@link #add})
 * </code></pre>
 * <p><u>Writing Data</u></p>
 * <p>And <b>new in Ext version 3</b>, use the new {@link Ext.data.DataWriter DataWriter} to create an automated, <a href="http://extjs.com/deploy/dev/examples/writer/writer.html">Writable Store</a>
 * along with <a href="http://extjs.com/deploy/dev/examples/restful/restful.html">RESTful features.</a>
 * @constructor
 * Creates a new Store.
 * @param {Object} config A config object containing the objects needed for the Store to access data,
 * and read the data into Records.
 * @xtype store
 */
Ext.data.Store = Ext.extend(Ext.util.Observable, {
	/**
	* @cfg {String} storeId If passed, the id to use to register with the <b>{@link Ext.StoreMgr StoreMgr}</b>.
	* <p><b>Note</b>: if a (deprecated) <tt>{@link #id}</tt> is specified it will supersede the <tt>storeId</tt>
	* assignment.</p>
	*/
	/**
	* @cfg {String} url If a <tt>{@link #proxy}</tt> is not specified the <tt>url</tt> will be used to
	* implicitly configure a {@link Ext.data.HttpProxy HttpProxy} if an <tt>url</tt> is specified.
	* Typically this option, or the <code>{@link #data}</code> option will be specified.
	*/
	/**
	* @cfg {Boolean/Object} autoLoad If <tt>{@link #data}</tt> is not specified, and if <tt>autoLoad</tt>
	* is <tt>true</tt> or an <tt>Object</tt>, this store's {@link #load} method is automatically called
	* after creation. If the value of <tt>autoLoad</tt> is an <tt>Object</tt>, this <tt>Object</tt> will
	* be passed to the store's {@link #load} method.
	*/
	/**
	* @cfg {Ext.data.DataProxy} proxy The {@link Ext.data.DataProxy DataProxy} object which provides
	* access to a data object.  See <code>{@link #url}</code>.
	*/
	/**
	* @cfg {Array} data An inline data object readable by the <code>{@link #reader}</code>.
	* Typically this option, or the <code>{@link #url}</code> option will be specified.
	*/
	/**
	* @cfg {Ext.data.DataReader} reader The {@link Ext.data.DataReader Reader} object which processes the
	* data object and returns an Array of {@link Ext.data.Record} objects which are cached keyed by their
	* <b><tt>{@link Ext.data.Record#id id}</tt></b> property.
	*/
	/**
	* @cfg {Ext.data.DataWriter} writer
	* <p>The {@link Ext.data.DataWriter Writer} object which processes a record object for being written
	* to the server-side database.</p>
	* <br><p>When a writer is installed into a Store the {@link #add}, {@link #remove}, and {@link #update}
	* events on the store are monitored in order to remotely {@link #createRecords create records},
	* {@link #destroyRecord destroy records}, or {@link #updateRecord update records}.</p>
	* <br><p>The proxy for this store will relay any {@link #writexception} events to this store.</p>
	* <br><p>Sample implementation:
	* <pre><code>
	var writer = new {@link Ext.data.JsonWriter}({
	encode: true,
	writeAllFields: true // write all fields, not just those that changed
	});

	// Typical Store collecting the Proxy, Reader and Writer together.
	var store = new Ext.data.Store({
	storeId: 'user',
	root: 'records',
	proxy: proxy,
	reader: reader,
	writer: writer,     // <-- plug a DataWriter into the store just as you would a Reader
	paramsAsHash: true,
	autoSave: false    // <-- false to delay executing create, update, destroy requests
	//     until specifically told to do so.
	});
	* </code></pre></p>
	*/
	writer: undefined,
	/**
	* @cfg {Object} baseParams
	* <p>An object containing properties which are to be sent as parameters
	* for <i>every</i> HTTP request.</p>
	* <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p>
	* <p><b>Note</b>: <code>baseParams</code> may be superseded by any <code>params</code>
	* specified in a <code>{@link #load}</code> request, see <code>{@link #load}</code>
	* for more details.</p>
	* This property may be modified after creation using the <code>{@link #setBaseParam}</code>
	* method.
	* @property
	*/
	/**
	* @cfg {Object} sortInfo A config object to specify the sort order in the request of a Store's
	* {@link #load} operation.  Note that for local sorting, the <tt>direction</tt> property is
	* case-sensitive. See also {@link #remoteSort} and {@link #paramNames}.
	* For example:<pre><code>
	sortInfo: {
	field: 'fieldName',
	direction: 'ASC' // or 'DESC' (case sensitive for local sorting)
	}
	</code></pre>
	*/
	/**
	* @cfg {boolean} remoteSort <tt>true</tt> if sorting is to be handled by requesting the <tt>{@link #proxy Proxy}</tt>
	* to provide a refreshed version of the data object in sorted order, as opposed to sorting the Record cache
	* in place (defaults to <tt>false</tt>).
	* <p>If <tt>remoteSort</tt> is <tt>true</tt>, then clicking on a {@link Ext.grid.Column Grid Column}'s
	* {@link Ext.grid.Column#header header} causes the current page to be requested from the server appending
	* the following two parameters to the <b><tt>{@link #load params}</tt></b>:<div class="mdetail-params"><ul>
	* <li><b><tt>sort</tt></b> : String<p class="sub-desc">The <tt>name</tt> (as specified in the Record's
	* {@link Ext.data.Field Field definition}) of the field to sort on.</p></li>
	* <li><b><tt>dir</tt></b> : String<p class="sub-desc">The direction of the sort, 'ASC' or 'DESC' (case-sensitive).</p></li>
	* </ul></div></p>
	*/
	remoteSort: false,

	/**
	* @cfg {Boolean} autoDestroy <tt>true</tt> to destroy the store when the component the store is bound
	* to is destroyed (defaults to <tt>false</tt>).
	* <p><b>Note</b>: this should be set to true when using stores that are bound to only 1 component.</p>
	*/
	autoDestroy: false,

	/**
	* @cfg {Boolean} pruneModifiedRecords <tt>true</tt> to clear all modified record information each time
	* the store is loaded or when a record is removed (defaults to <tt>false</tt>). See {@link #getModifiedRecords}
	* for the accessor method to retrieve the modified records.
	*/
	pruneModifiedRecords: false,

	/**
	* Contains the last options object used as the parameter to the {@link #load} method. See {@link #load}
	* for the details of what this may contain. This may be useful for accessing any params which were used
	* to load the current Record cache.
	* @property
	*/
	lastOptions: null,

	/**
	* @cfg {Boolean} autoSave
	* <p>Defaults to <tt>true</tt> causing the store to automatically {@link #save} records to
	* the server when a record is modified (ie: becomes 'dirty'). Specify <tt>false</tt> to manually call {@link #save}
	* to send all modifiedRecords to the server.</p>
	* <br><p><b>Note</b>: each CRUD action will be sent as a separate request.</p>
	*/
	autoSave: true,

	/**
	* @cfg {Boolean} batch
	* <p>Defaults to <tt>true</tt> (unless <code>{@link #restful}:true</code>). Multiple
	* requests for each CRUD action (CREATE, READ, UPDATE and DESTROY) will be combined
	* and sent as one transaction. Only applies when <code>{@link #autoSave}</code> is set
	* to <tt>false</tt>.</p>
	* <br><p>If Store is RESTful, the DataProxy is also RESTful, and a unique transaction is
	* generated for each record.</p>
	*/
	batch: true,

	/**
	* @cfg {Boolean} restful
	* Defaults to <tt>false</tt>.  Set to <tt>true</tt> to have the Store and the set
	* Proxy operate in a RESTful manner. The store will automatically generate GET, POST,
	* PUT and DELETE requests to the server. The HTTP method used for any given CRUD
	* action is described in {@link Ext.data.Api#restActions}.  For additional information
	* see {@link Ext.data.DataProxy#restful}.
	* <p><b>Note</b>: if <code>{@link #restful}:true</code> <code>batch</code> will
	* internally be set to <tt>false</tt>.</p>
	*/
	restful: false,

	/**
	* @cfg {Object} paramNames
	* <p>An object containing properties which specify the names of the paging and
	* sorting parameters passed to remote servers when loading blocks of data. By default, this
	* object takes the following form:</p><pre><code>
	{
	start : 'start',  // The parameter name which specifies the start row
	limit : 'limit',  // The parameter name which specifies number of rows to return
	sort : 'sort',    // The parameter name which specifies the column to sort on
	dir : 'dir'       // The parameter name which specifies the sort direction
	}
	</code></pre>
	* <p>The server must produce the requested data block upon receipt of these parameter names.
	* If different parameter names are required, this property can be overriden using a configuration
	* property.</p>
	* <p>A {@link Ext.PagingToolbar PagingToolbar} bound to this Store uses this property to determine
	* the parameter names to use in its {@link #load requests}.
	*/
	paramNames: undefined,

	/**
	* @cfg {Object} defaultParamNames
	* Provides the default values for the {@link #paramNames} property. To globally modify the parameters
	* for all stores, this object should be changed on the store prototype.
	*/
	defaultParamNames: {
		start: 'start',
		limit: 'limit',
		sort: 'sort',
		dir: 'dir'
	},

	/**
	* @property isDestroyed
	* @type Boolean
	* True if the store has been destroyed already. Read only
	*/
	isDestroyed: false,

	/**
	* @property hasMultiSort
	* @type Boolean
	* True if this store is currently sorted by more than one field/direction combination.
	*/
	hasMultiSort: false,

	// private
	batchKey: '_ext_batch_',

	constructor: function (config) {
		this.data = new Ext.util.MixedCollection(false);
		this.data.getKey = function (o) {
			return o.id;
		};


		// temporary removed-records cache
		this.removed = [];

		if (config && config.data) {
			this.inlineData = config.data;
			delete config.data;
		}

		Ext.apply(this, config);

		/**
		* See the <code>{@link #baseParams corresponding configuration option}</code>
		* for a description of this property.
		* To modify this property see <code>{@link #setBaseParam}</code>.
		* @property
		*/
		this.baseParams = Ext.isObject(this.baseParams) ? this.baseParams : {};

		this.paramNames = Ext.applyIf(this.paramNames || {}, this.defaultParamNames);

		if ((this.url || this.api) && !this.proxy) {
			this.proxy = new Ext.data.HttpProxy({ url: this.url, api: this.api });
		}
		// If Store is RESTful, so too is the DataProxy
		if (this.restful === true && this.proxy) {
			// When operating RESTfully, a unique transaction is generated for each record.
			// TODO might want to allow implemention of faux REST where batch is possible using RESTful routes only.
			this.batch = false;
			Ext.data.Api.restify(this.proxy);
		}

		if (this.reader) { // reader passed
			if (!this.recordType) {
				this.recordType = this.reader.recordType;
			}
			if (this.reader.onMetaChange) {
				this.reader.onMetaChange = this.reader.onMetaChange.createSequence(this.onMetaChange, this);
			}
			if (this.writer) { // writer passed
				if (this.writer instanceof (Ext.data.DataWriter) === false) {    // <-- config-object instead of instance.
					this.writer = this.buildWriter(this.writer);
				}
				this.writer.meta = this.reader.meta;
				this.pruneModifiedRecords = true;
			}
		}

		/**
		* The {@link Ext.data.Record Record} constructor as supplied to (or created by) the
		* {@link Ext.data.DataReader Reader}. Read-only.
		* <p>If the Reader was constructed by passing in an Array of {@link Ext.data.Field} definition objects,
		* instead of a Record constructor, it will implicitly create a Record constructor from that Array (see
		* {@link Ext.data.Record}.{@link Ext.data.Record#create create} for additional details).</p>
		* <p>This property may be used to create new Records of the type held in this Store, for example:</p><pre><code>
		// create the data store
		var store = new Ext.data.ArrayStore({
		autoDestroy: true,
		fields: [
		{name: 'company'},
		{name: 'price', type: 'float'},
		{name: 'change', type: 'float'},
		{name: 'pctChange', type: 'float'},
		{name: 'lastChange', type: 'date', dateFormat: 'n/j h:ia'}
		]
		});
		store.loadData(myData);

		// create the Grid
		var grid = new Ext.grid.EditorGridPanel({
		store: store,
		colModel: new Ext.grid.ColumnModel({
		columns: [
		{id:'company', header: 'Company', width: 160, dataIndex: 'company'},
		{header: 'Price', renderer: 'usMoney', dataIndex: 'price'},
		{header: 'Change', renderer: change, dataIndex: 'change'},
		{header: '% Change', renderer: pctChange, dataIndex: 'pctChange'},
		{header: 'Last Updated', width: 85,
		renderer: Ext.util.Format.dateRenderer('m/d/Y'),
		dataIndex: 'lastChange'}
		],
		defaults: {
		sortable: true,
		width: 75
		}
		}),
		autoExpandColumn: 'company', // match the id specified in the column model
		height:350,
		width:600,
		title:'Array Grid',
		tbar: [{
		text: 'Add Record',
		handler : function(){
		var defaultData = {
		change: 0,
		company: 'New Company',
		lastChange: (new Date()).clearTime(),
		pctChange: 0,
		price: 10
		};
		var recId = 3; // provide unique id
		var p = new store.recordType(defaultData, recId); // create new record
		grid.stopEditing();
		store.{@link #insert}(0, p); // insert a new record into the store (also see {@link #add})
		grid.startEditing(0, 0);
		}
		}]
		});
		* </code></pre>
		* @property recordType
		* @type Function
		*/

		if (this.recordType) {
			/**
			* A {@link Ext.util.MixedCollection MixedCollection} containing the defined {@link Ext.data.Field Field}s
			* for the {@link Ext.data.Record Records} stored in this Store. Read-only.
			* @property fields
			* @type Ext.util.MixedCollection
			*/
			this.fields = this.recordType.prototype.fields;
		}
		this.modified = [];

		this.addEvents(
		/**
		* @event datachanged
		* Fires when the data cache has changed in a bulk manner (e.g., it has been sorted, filtered, etc.) and a
		* widget that is using this Store as a Record cache should refresh its view.
		* @param {Store} this
		*/
            'datachanged',
		/**
		* @event metachange
		* Fires when this store's reader provides new metadata (fields). This is currently only supported for JsonReaders.
		* @param {Store} this
		* @param {Object} meta The JSON metadata
		*/
            'metachange',
		/**
		* @event add
		* Fires when Records have been {@link #add}ed to the Store
		* @param {Store} this
		* @param {Ext.data.Record[]} records The array of Records added
		* @param {Number} index The index at which the record(s) were added
		*/
            'add',
		/**
		* @event remove
		* Fires when a Record has been {@link #remove}d from the Store
		* @param {Store} this
		* @param {Ext.data.Record} record The Record that was removed
		* @param {Number} index The index at which the record was removed
		*/
            'remove',
		/**
		* @event update
		* Fires when a Record has been updated
		* @param {Store} this
		* @param {Ext.data.Record} record The Record that was updated
		* @param {String} operation The update operation being performed.  Value may be one of:
		* <pre><code>
		Ext.data.Record.EDIT
		Ext.data.Record.REJECT
		Ext.data.Record.COMMIT
		* </code></pre>
		*/
            'update',
		/**
		* @event clear
		* Fires when the data cache has been cleared.
		* @param {Store} this
		* @param {Record[]} The records that were cleared.
		*/
            'clear',
		/**
		* @event exception
		* <p>Fires if an exception occurs in the Proxy during a remote request.
		* This event is relayed through the corresponding {@link Ext.data.DataProxy}.
		* See {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#exception exception}
		* for additional details.
		* @param {misc} misc See {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#exception exception}
		* for description.
		*/
            'exception',
		/**
		* @event beforeload
		* Fires before a request is made for a new data object.  If the beforeload handler returns
		* <tt>false</tt> the {@link #load} action will be canceled.
		* @param {Store} this
		* @param {Object} options The loading options that were specified (see {@link #load} for details)
		*/
            'beforeload',
		/**
		* @event load
		* Fires after a new set of Records has been loaded.
		* @param {Store} this
		* @param {Ext.data.Record[]} records The Records that were loaded
		* @param {Object} options The loading options that were specified (see {@link #load} for details)
		*/
            'load',
		/**
		* @event loadexception
		* <p>This event is <b>deprecated</b> in favor of the catch-all <b><code>{@link #exception}</code></b>
		* event instead.</p>
		* <p>This event is relayed through the corresponding {@link Ext.data.DataProxy}.
		* See {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#loadexception loadexception}
		* for additional details.
		* @param {misc} misc See {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#loadexception loadexception}
		* for description.
		*/
            'loadexception',
		/**
		* @event beforewrite
		* @param {Ext.data.Store} store
		* @param {String} action [Ext.data.Api.actions.create|update|destroy]
		* @param {Record/Record[]} rs The Record(s) being written.
		* @param {Object} options The loading options that were specified. Edit <code>options.params</code> to add Http parameters to the request.  (see {@link #save} for details)
		* @param {Object} arg The callback's arg object passed to the {@link #request} function
		*/
            'beforewrite',
		/**
		* @event write
		* Fires if the server returns 200 after an Ext.data.Api.actions CRUD action.
		* Success of the action is determined in the <code>result['successProperty']</code>property (<b>NOTE</b> for RESTful stores,
		* a simple 20x response is sufficient for the actions "destroy" and "update".  The "create" action should should return 200 along with a database pk).
		* @param {Ext.data.Store} store
		* @param {String} action [Ext.data.Api.actions.create|update|destroy]
		* @param {Object} result The 'data' picked-out out of the response for convenience.
		* @param {Ext.Direct.Transaction} res
		* @param {Record/Record[]} rs Store's records, the subject(s) of the write-action
		*/
            'write',
		/**
		* @event beforesave
		* Fires before a save action is called. A save encompasses destroying records, updating records and creating records.
		* @param {Ext.data.Store} store
		* @param {Object} data An object containing the data that is to be saved. The object will contain a key for each appropriate action,
		* with an array of records for each action.
		*/
            'beforesave',
		/**
		* @event save
		* Fires after a save is completed. A save encompasses destroying records, updating records and creating records.
		* @param {Ext.data.Store} store
		* @param {Number} batch The identifier for the batch that was saved.
		* @param {Object} data An object containing the data that is to be saved. The object will contain a key for each appropriate action,
		* with an array of records for each action.
		*/
            'save'

        );

		if (this.proxy) {
			// TODO remove deprecated loadexception with ext-3.0.1
			this.relayEvents(this.proxy, ['loadexception', 'exception']);
		}
		// With a writer set for the Store, we want to listen to add/remove events to remotely create/destroy records.
		if (this.writer) {
			this.on({
				scope: this,
				add: this.createRecords,
				remove: this.destroyRecord,
				update: this.updateRecord,
				clear: this.onClear
			});
		}

		this.sortToggle = {};
		if (this.sortField) {
			this.setDefaultSort(this.sortField, this.sortDir);
		} else if (this.sortInfo) {
			this.setDefaultSort(this.sortInfo.field, this.sortInfo.direction);
		}

		Ext.data.Store.superclass.constructor.call(this);

		if (this.id) {
			this.storeId = this.id;
			delete this.id;
		}
		if (this.storeId) {
			Ext.StoreMgr.register(this);
		}
		if (this.inlineData) {
			this.loadData(this.inlineData);
			delete this.inlineData;
		} else if (this.autoLoad) {
			this.load.defer(10, this, [
                typeof this.autoLoad == 'object' ?
                    this.autoLoad : undefined]);
		}
		// used internally to uniquely identify a batch
		this.batchCounter = 0;
		this.batches = {};
	},

	/**
	* builds a DataWriter instance when Store constructor is provided with a writer config-object instead of an instace.
	* @param {Object} config Writer configuration
	* @return {Ext.data.DataWriter}
	* @private
	*/
	buildWriter: function (config) {
		var klass = undefined,
            type = (config.format || 'json').toLowerCase();
		switch (type) {
			case 'json':
				klass = Ext.data.JsonWriter;
				break;
			case 'xml':
				klass = Ext.data.XmlWriter;
				break;
			default:
				klass = Ext.data.JsonWriter;
		}
		return new klass(config);
	},

	/**
	* Destroys the store.
	*/
	destroy: function () {
		if (!this.isDestroyed) {
			if (this.storeId) {
				Ext.StoreMgr.unregister(this);
			}
			this.clearData();
			this.data = null;
			Ext.destroy(this.proxy);
			this.reader = this.writer = null;
			this.purgeListeners();
			this.isDestroyed = true;
		}
	},

	/**
	* Add Records to the Store and fires the {@link #add} event.  To add Records
	* to the store from a remote source use <code>{@link #load}({add:true})</code>.
	* See also <code>{@link #recordType}</code> and <code>{@link #insert}</code>.
	* @param {Ext.data.Record[]} records An Array of Ext.data.Record objects
	* to add to the cache. See {@link #recordType}.
	*/
	add: function (records) {
		records = [].concat(records);
		if (records.length < 1) {
			return;
		}
		for (var i = 0, len = records.length; i < len; i++) {
			records[i].join(this);
		}
		var index = this.data.length;
		this.data.addAll(records);
		if (this.snapshot) {
			this.snapshot.addAll(records);
		}
		this.fireEvent('add', this, records, index);
	},

	/**
	* (Local sort only) Inserts the passed Record into the Store at the index where it
	* should go based on the current sort information.
	* @param {Ext.data.Record} record
	*/
	addSorted: function (record) {
		var index = this.findInsertIndex(record);
		this.insert(index, record);
	},

	/**
	* Remove Records from the Store and fires the {@link #remove} event.
	* @param {Ext.data.Record/Ext.data.Record[]} record The record object or array of records to remove from the cache.
	*/
	remove: function (record) {
		if (Ext.isArray(record)) {
			Ext.each(record, function (r) {
				this.remove(r);
			}, this);
			return;
		}
		var index = this.data.indexOf(record);
		if (index > -1) {
			record.join(null);
			this.data.removeAt(index);
		}
		if (this.pruneModifiedRecords) {
			this.modified.remove(record);
		}
		if (this.snapshot) {
			this.snapshot.remove(record);
		}
		if (index > -1) {
			this.fireEvent('remove', this, record, index);
		}
	},

	/**
	* Remove a Record from the Store at the specified index. Fires the {@link #remove} event.
	* @param {Number} index The index of the record to remove.
	*/
	removeAt: function (index) {
		this.remove(this.getAt(index));
	},

	/**
	* Remove all Records from the Store and fires the {@link #clear} event.
	* @param {Boolean} silent [false] Defaults to <tt>false</tt>.  Set <tt>true</tt> to not fire clear event.
	*/
	removeAll: function (silent) {
		var items = [];
		this.each(function (rec) {
			items.push(rec);
		});
		this.clearData();
		if (this.snapshot) {
			this.snapshot.clear();
		}
		if (this.pruneModifiedRecords) {
			this.modified = [];
		}
		if (silent !== true) {  // <-- prevents write-actions when we just want to clear a store.
			this.fireEvent('clear', this, items);
		}
	},

	// private
	onClear: function (store, records) {
		Ext.each(records, function (rec, index) {
			this.destroyRecord(this, rec, index);
		}, this);
	},

	/**
	* Inserts Records into the Store at the given index and fires the {@link #add} event.
	* See also <code>{@link #add}</code> and <code>{@link #addSorted}</code>.
	* @param {Number} index The start index at which to insert the passed Records.
	* @param {Ext.data.Record[]} records An Array of Ext.data.Record objects to add to the cache.
	*/
	insert: function (index, records) {
		records = [].concat(records);
		for (var i = 0, len = records.length; i < len; i++) {
			this.data.insert(index, records[i]);
			records[i].join(this);
		}
		if (this.snapshot) {
			this.snapshot.addAll(records);
		}
		this.fireEvent('add', this, records, index);
	},

	/**
	* Get the index within the cache of the passed Record.
	* @param {Ext.data.Record} record The Ext.data.Record object to find.
	* @return {Number} The index of the passed Record. Returns -1 if not found.
	*/
	indexOf: function (record) {
		return this.data.indexOf(record);
	},

	/**
	* Get the index within the cache of the Record with the passed id.
	* @param {String} id The id of the Record to find.
	* @return {Number} The index of the Record. Returns -1 if not found.
	*/
	indexOfId: function (id) {
		return this.data.indexOfKey(id);
	},

	/**
	* Get the Record with the specified id.
	* @param {String} id The id of the Record to find.
	* @return {Ext.data.Record} The Record with the passed id. Returns undefined if not found.
	*/
	getById: function (id) {
		return (this.snapshot || this.data).key(id);
	},

	/**
	* Get the Record at the specified index.
	* @param {Number} index The index of the Record to find.
	* @return {Ext.data.Record} The Record at the passed index. Returns undefined if not found.
	*/
	getAt: function (index) {
		return this.data.itemAt(index);
	},

	/**
	* Returns a range of Records between specified indices.
	* @param {Number} startIndex (optional) The starting index (defaults to 0)
	* @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)
	* @return {Ext.data.Record[]} An array of Records
	*/
	getRange: function (start, end) {
		return this.data.getRange(start, end);
	},

	// private
	storeOptions: function (o) {
		o = Ext.apply({}, o);
		delete o.callback;
		delete o.scope;
		this.lastOptions = o;
	},

	// private
	clearData: function () {
		this.data.each(function (rec) {
			rec.join(null);
		});
		this.data.clear();
	},

	/**
	* <p>Loads the Record cache from the configured <tt>{@link #proxy}</tt> using the configured <tt>{@link #reader}</tt>.</p>
	* <br><p>Notes:</p><div class="mdetail-params"><ul>
	* <li><b><u>Important</u></b>: loading is asynchronous! This call will return before the new data has been
	* loaded. To perform any post-processing where information from the load call is required, specify
	* the <tt>callback</tt> function to be called, or use a {@link Ext.util.Observable#listeners a 'load' event handler}.</li>
	* <li>If using {@link Ext.PagingToolbar remote paging}, the first load call must specify the <tt>start</tt> and <tt>limit</tt>
	* properties in the <code>options.params</code> property to establish the initial position within the
	* dataset, and the number of Records to cache on each read from the Proxy.</li>
	* <li>If using {@link #remoteSort remote sorting}, the configured <code>{@link #sortInfo}</code>
	* will be automatically included with the posted parameters according to the specified
	* <code>{@link #paramNames}</code>.</li>
	* </ul></div>
	* @param {Object} options An object containing properties which control loading options:<ul>
	* <li><b><tt>params</tt></b> :Object<div class="sub-desc"><p>An object containing properties to pass as HTTP
	* parameters to a remote data source. <b>Note</b>: <code>params</code> will override any
	* <code>{@link #baseParams}</code> of the same name.</p>
	* <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p></div></li>
	* <li><b>callback</b> : Function<div class="sub-desc"><p>A function to be called after the Records
	* have been loaded. The callback is called after the load event is fired, and is passed the following arguments:<ul>
	* <li>r : Ext.data.Record[] An Array of Records loaded.</li>
	* <li>options : Options object from the load call.</li>
	* <li>success : Boolean success indicator.</li></ul></p></div></li>
	* <li><b>scope</b> : Object<div class="sub-desc"><p>Scope with which to call the callback (defaults
	* to the Store object)</p></div></li>
	* <li><b>add</b> : Boolean<div class="sub-desc"><p>Indicator to append loaded records rather than
	* replace the current cache.  <b>Note</b>: see note for <tt>{@link #loadData}</tt></p></div></li>
	* </ul>
	* @return {Boolean} If the <i>developer</i> provided <tt>{@link #beforeload}</tt> event handler returns
	* <tt>false</tt>, the load call will abort and will return <tt>false</tt>; otherwise will return <tt>true</tt>.
	*/
	load: function (options) {
		options = Ext.apply({}, options);
		this.storeOptions(options);
		if (this.sortInfo && this.remoteSort) {
			var pn = this.paramNames;
			options.params = Ext.apply({}, options.params);
			options.params[pn.sort] = this.sortInfo.field;
			options.params[pn.dir] = this.sortInfo.direction;
		}
		try {
			return this.execute('read', null, options); // <-- null represents rs.  No rs for load actions.
		} catch (e) {
			this.handleException(e);
			return false;
		}
	},

	/**
	* updateRecord  Should not be used directly.  This method will be called automatically if a Writer is set.
	* Listens to 'update' event.
	* @param {Object} store
	* @param {Object} record
	* @param {Object} action
	* @private
	*/
	updateRecord: function (store, record, action) {
		if (action == Ext.data.Record.EDIT && this.autoSave === true && (!record.phantom || (record.phantom && record.isValid()))) {
			this.save();
		}
	},

	/**
	* Should not be used directly.  Store#add will call this automatically if a Writer is set
	* @param {Object} store
	* @param {Object} rs
	* @param {Object} index
	* @private
	*/
	createRecords: function (store, rs, index) {
		for (var i = 0, len = rs.length; i < len; i++) {
			if (rs[i].phantom && rs[i].isValid()) {
				rs[i].markDirty();  // <-- Mark new records dirty
				this.modified.push(rs[i]);  // <-- add to modified
			}
		}
		if (this.autoSave === true) {
			this.save();
		}
	},

	/**
	* Destroys a Record.  Should not be used directly.  It's called by Store#remove if a Writer is set.
	* @param {Store} store this
	* @param {Ext.data.Record} record
	* @param {Number} index
	* @private
	*/
	destroyRecord: function (store, record, index) {
		if (this.modified.indexOf(record) != -1) {  // <-- handled already if @cfg pruneModifiedRecords == true
			this.modified.remove(record);
		}
		if (!record.phantom) {
			this.removed.push(record);

			// since the record has already been removed from the store but the server request has not yet been executed,
			// must keep track of the last known index this record existed.  If a server error occurs, the record can be
			// put back into the store.  @see Store#createCallback where the record is returned when response status === false
			record.lastIndex = index;

			if (this.autoSave === true) {
				this.save();
			}
		}
	},

	/**
	* This method should generally not be used directly.  This method is called internally
	* by {@link #load}, or if a Writer is set will be called automatically when {@link #add},
	* {@link #remove}, or {@link #update} events fire.
	* @param {String} action Action name ('read', 'create', 'update', or 'destroy')
	* @param {Record/Record[]} rs
	* @param {Object} options
	* @throws Error
	* @private
	*/
	execute: function (action, rs, options, /* private */batch) {
		// blow up if action not Ext.data.CREATE, READ, UPDATE, DESTROY
		if (!Ext.data.Api.isAction(action)) {
			throw new Ext.data.Api.Error('execute', action);
		}
		// make sure options has a fresh, new params hash
		options = Ext.applyIf(options || {}, {
			params: {}
		});
		if (batch !== undefined) {
			this.addToBatch(batch);
		}
		// have to separate before-events since load has a different signature than create,destroy and save events since load does not
		// include the rs (record resultset) parameter.  Capture return values from the beforeaction into doRequest flag.
		var doRequest = true;

		if (action === 'read') {
			doRequest = this.fireEvent('beforeload', this, options);
			Ext.applyIf(options.params, this.baseParams);
		}
		else {
			// if Writer is configured as listful, force single-record rs to be [{}] instead of {}
			// TODO Move listful rendering into DataWriter where the @cfg is defined.  Should be easy now.
			if (this.writer.listful === true && this.restful !== true) {
				rs = (Ext.isArray(rs)) ? rs : [rs];
			}
			// if rs has just a single record, shift it off so that Writer writes data as '{}' rather than '[{}]'
			else if (Ext.isArray(rs) && rs.length == 1) {
				rs = rs.shift();
			}
			// Write the action to options.params
			if ((doRequest = this.fireEvent('beforewrite', this, action, rs, options)) !== false) {
				this.writer.apply(options.params, this.baseParams, action, rs);
			}
		}
		if (doRequest !== false) {
			// Send request to proxy.
			if (this.writer && this.proxy.url && !this.proxy.restful && !Ext.data.Api.hasUniqueUrl(this.proxy, action)) {
				options.params.xaction = action;    // <-- really old, probaby unecessary.
			}
			// Note:  Up until this point we've been dealing with 'action' as a key from Ext.data.Api.actions.
			// We'll flip it now and send the value into DataProxy#request, since it's the value which maps to
			// the user's configured DataProxy#api
			// TODO Refactor all Proxies to accept an instance of Ext.data.Request (not yet defined) instead of this looooooong list
			// of params.  This method is an artifact from Ext2.
			this.proxy.request(Ext.data.Api.actions[action], rs, options.params, this.reader, this.createCallback(action, rs, batch), this, options);
		}
		return doRequest;
	},

	/**
	* Saves all pending changes to the store.  If the commensurate Ext.data.Api.actions action is not configured, then
	* the configured <code>{@link #url}</code> will be used.
	* <pre>
	* change            url
	* ---------------   --------------------
	* removed records   Ext.data.Api.actions.destroy
	* phantom records   Ext.data.Api.actions.create
	* {@link #getModifiedRecords modified records}  Ext.data.Api.actions.update
	* </pre>
	* @TODO:  Create extensions of Error class and send associated Record with thrown exceptions.
	* e.g.:  Ext.data.DataReader.Error or Ext.data.Error or Ext.data.DataProxy.Error, etc.
	* @return {Number} batch Returns a number to uniquely identify the "batch" of saves occurring. -1 will be returned
	* if there are no items to save or the save was cancelled.
	*/
	save: function () {
		if (!this.writer) {
			throw new Ext.data.Store.Error('writer-undefined');
		}

		var queue = [],
            len,
            trans,
            batch,
            data = {};
		// DESTROY:  First check for removed records.  Records in this.removed are guaranteed non-phantoms.  @see Store#remove
		if (this.removed.length) {
			queue.push(['destroy', this.removed]);
		}

		// Check for modified records. Use a copy so Store#rejectChanges will work if server returns error.
		var rs = [].concat(this.getModifiedRecords());
		if (rs.length) {
			// CREATE:  Next check for phantoms within rs.  splice-off and execute create.
			var phantoms = [];
			for (var i = rs.length - 1; i >= 0; i--) {
				if (rs[i].phantom === true) {
					var rec = rs.splice(i, 1).shift();
					if (rec.isValid()) {
						phantoms.push(rec);
					}
				} else if (!rs[i].isValid()) { // <-- while we're here, splice-off any !isValid real records
					rs.splice(i, 1);
				}
			}
			// If we have valid phantoms, create them...
			if (phantoms.length) {
				queue.push(['create', phantoms]);
			}

			// UPDATE:  And finally, if we're still here after splicing-off phantoms and !isValid real records, update the rest...
			if (rs.length) {
				queue.push(['update', rs]);
			}
		}
		len = queue.length;
		if (len) {
			batch = ++this.batchCounter;
			for (var i = 0; i < len; ++i) {
				trans = queue[i];
				data[trans[0]] = trans[1];
			}
			if (this.fireEvent('beforesave', this, data) !== false) {
				for (var i = 0; i < len; ++i) {
					trans = queue[i];
					this.doTransaction(trans[0], trans[1], batch);
				}
				return batch;
			}
		}
		return -1;
	},

	// private.  Simply wraps call to Store#execute in try/catch.  Defers to Store#handleException on error.  Loops if batch: false
	doTransaction: function (action, rs, batch) {
		function transaction(records) {
			try {
				this.execute(action, records, undefined, batch);
			} catch (e) {
				this.handleException(e);
			}
		}
		if (this.batch === false) {
			for (var i = 0, len = rs.length; i < len; i++) {
				transaction.call(this, rs[i]);
			}
		} else {
			transaction.call(this, rs);
		}
	},

	// private
	addToBatch: function (batch) {
		var b = this.batches,
            key = this.batchKey + batch,
            o = b[key];

		if (!o) {
			b[key] = o = {
				id: batch,
				count: 0,
				data: {}
			};
		}
		++o.count;
	},

	removeFromBatch: function (batch, action, data) {
		var b = this.batches,
            key = this.batchKey + batch,
            o = b[key],
            data,
            arr;


		if (o) {
			arr = o.data[action] || [];
			o.data[action] = arr.concat(data);
			if (o.count === 1) {
				data = o.data;
				delete b[key];
				this.fireEvent('save', this, batch, data);
			} else {
				--o.count;
			}
		}
	},

	// @private callback-handler for remote CRUD actions
	// Do not override -- override loadRecords, onCreateRecords, onDestroyRecords and onUpdateRecords instead.
	createCallback: function (action, rs, batch) {
		var actions = Ext.data.Api.actions;
		return (action == 'read') ? this.loadRecords : function (data, response, success) {
			// calls: onCreateRecords | onUpdateRecords | onDestroyRecords
			this['on' + Ext.util.Format.capitalize(action) + 'Records'](success, rs, [].concat(data));
			// If success === false here, exception will have been called in DataProxy
			if (success === true) {
				this.fireEvent('write', this, action, data, response, rs);
			}
			this.removeFromBatch(batch, action, data);
		};
	},

	// Clears records from modified array after an exception event.
	// NOTE:  records are left marked dirty.  Do we want to commit them even though they were not updated/realized?
	// TODO remove this method?
	clearModified: function (rs) {
		if (Ext.isArray(rs)) {
			for (var n = rs.length - 1; n >= 0; n--) {
				this.modified.splice(this.modified.indexOf(rs[n]), 1);
			}
		} else {
			this.modified.splice(this.modified.indexOf(rs), 1);
		}
	},

	// remap record ids in MixedCollection after records have been realized.  @see Store#onCreateRecords, @see DataReader#realize
	reMap: function (record) {
		if (Ext.isArray(record)) {
			for (var i = 0, len = record.length; i < len; i++) {
				this.reMap(record[i]);
			}
		} else {
			delete this.data.map[record._phid];
			this.data.map[record.id] = record;
			var index = this.data.keys.indexOf(record._phid);
			this.data.keys.splice(index, 1, record.id);
			delete record._phid;
		}
	},

	// @protected onCreateRecord proxy callback for create action
	onCreateRecords: function (success, rs, data) {
		if (success === true) {
			try {
				this.reader.realize(rs, data);
				this.reMap(rs);
			}
			catch (e) {
				this.handleException(e);
				if (Ext.isArray(rs)) {
					// Recurse to run back into the try {}.  DataReader#realize splices-off the rs until empty.
					this.onCreateRecords(success, rs, data);
				}
			}
		}
	},

	// @protected, onUpdateRecords proxy callback for update action
	onUpdateRecords: function (success, rs, data) {
		if (success === true) {
			try {
				this.reader.update(rs, data);
			} catch (e) {
				this.handleException(e);
				if (Ext.isArray(rs)) {
					// Recurse to run back into the try {}.  DataReader#update splices-off the rs until empty.
					this.onUpdateRecords(success, rs, data);
				}
			}
		}
	},

	// @protected onDestroyRecords proxy callback for destroy action
	onDestroyRecords: function (success, rs, data) {
		// splice each rec out of this.removed
		rs = (rs instanceof Ext.data.Record) ? [rs] : [].concat(rs);
		for (var i = 0, len = rs.length; i < len; i++) {
			this.removed.splice(this.removed.indexOf(rs[i]), 1);
		}
		if (success === false) {
			// put records back into store if remote destroy fails.
			// @TODO: Might want to let developer decide.
			for (i = rs.length - 1; i >= 0; i--) {
				this.insert(rs[i].lastIndex, rs[i]);    // <-- lastIndex set in Store#destroyRecord
			}
		}
	},

	// protected handleException.  Possibly temporary until Ext framework has an exception-handler.
	handleException: function (e) {
		// @see core/Error.js
		Ext.handleError(e);
	},

	/**
	* <p>Reloads the Record cache from the configured Proxy using the configured
	* {@link Ext.data.Reader Reader} and the options from the last load operation
	* performed.</p>
	* <p><b>Note</b>: see the Important note in {@link #load}.</p>
	* @param {Object} options <p>(optional) An <tt>Object</tt> containing
	* {@link #load loading options} which may override the {@link #lastOptions options}
	* used in the last {@link #load} operation. See {@link #load} for details
	* (defaults to <tt>null</tt>, in which case the {@link #lastOptions} are
	* used).</p>
	* <br><p>To add new params to the existing params:</p><pre><code>
	lastOptions = myStore.lastOptions;
	Ext.apply(lastOptions.params, {
	myNewParam: true
	});
	myStore.reload(lastOptions);
	* </code></pre>
	*/
	reload: function (options) {
		this.load(Ext.applyIf(options || {}, this.lastOptions));
	},

	// private
	// Called as a callback by the Reader during a load operation.
	loadRecords: function (o, options, success) {
		if (this.isDestroyed === true) {
			return;
		}
		if (!o || success === false) {
			if (success !== false) {
				this.fireEvent('load', this, [], options);
			}
			if (options.callback) {
				options.callback.call(options.scope || this, [], options, false, o);
			}
			return;
		}
		var r = o.records, t = o.totalRecords || r.length;
		if (!options || options.add !== true) {
			if (this.pruneModifiedRecords) {
				this.modified = [];
			}
			for (var i = 0, len = r.length; i < len; i++) {
				r[i].join(this);
			}
			if (this.snapshot) {
				this.data = this.snapshot;
				delete this.snapshot;
			}
			this.clearData();
			this.data.addAll(r);
			this.totalLength = t;
			this.applySort();
			this.fireEvent('datachanged', this);
		} else {
			this.totalLength = Math.max(t, this.data.length + r.length);
			this.add(r);
		}
		this.fireEvent('load', this, r, options);
		if (options.callback) {
			options.callback.call(options.scope || this, r, options, true);
		}
	},

	/**
	* Loads data from a passed data block and fires the {@link #load} event. A {@link Ext.data.Reader Reader}
	* which understands the format of the data must have been configured in the constructor.
	* @param {Object} data The data block from which to read the Records.  The format of the data expected
	* is dependent on the type of {@link Ext.data.Reader Reader} that is configured and should correspond to
	* that {@link Ext.data.Reader Reader}'s <tt>{@link Ext.data.Reader#readRecords}</tt> parameter.
	* @param {Boolean} append (Optional) <tt>true</tt> to append the new Records rather the default to replace
	* the existing cache.
	* <b>Note</b>: that Records in a Store are keyed by their {@link Ext.data.Record#id id}, so added Records
	* with ids which are already present in the Store will <i>replace</i> existing Records. Only Records with
	* new, unique ids will be added.
	*/
	loadData: function (o, append) {
		var r = this.reader.readRecords(o);
		this.loadRecords(r, { add: append }, true);
	},

	/**
	* Gets the number of cached records.
	* <p>If using paging, this may not be the total size of the dataset. If the data object
	* used by the Reader contains the dataset size, then the {@link #getTotalCount} function returns
	* the dataset size.  <b>Note</b>: see the Important note in {@link #load}.</p>
	* @return {Number} The number of Records in the Store's cache.
	*/
	getCount: function () {
		return this.data.length || 0;
	},

	/**
	* Gets the total number of records in the dataset as returned by the server.
	* <p>If using paging, for this to be accurate, the data object used by the {@link #reader Reader}
	* must contain the dataset size. For remote data sources, the value for this property
	* (<tt>totalProperty</tt> for {@link Ext.data.JsonReader JsonReader},
	* <tt>totalRecords</tt> for {@link Ext.data.XmlReader XmlReader}) shall be returned by a query on the server.
	* <b>Note</b>: see the Important note in {@link #load}.</p>
	* @return {Number} The number of Records as specified in the data object passed to the Reader
	* by the Proxy.
	* <p><b>Note</b>: this value is not updated when changing the contents of the Store locally.</p>
	*/
	getTotalCount: function () {
		return this.totalLength || 0;
	},

	/**
	* Returns an object describing the current sort state of this Store.
	* @return {Object} The sort state of the Store. An object with two properties:<ul>
	* <li><b>field : String<p class="sub-desc">The name of the field by which the Records are sorted.</p></li>
	* <li><b>direction : String<p class="sub-desc">The sort order, 'ASC' or 'DESC' (case-sensitive).</p></li>
	* </ul>
	* See <tt>{@link #sortInfo}</tt> for additional details.
	*/
	getSortState: function () {
		return this.sortInfo;
	},

	/**
	* @private
	* Invokes sortData if we have sortInfo to sort on and are not sorting remotely
	*/
	applySort: function () {
		if ((this.sortInfo || this.multiSortInfo) && !this.remoteSort) {
			this.sortData();
		}
	},

	/**
	* @private
	* Performs the actual sorting of data. This checks to see if we currently have a multi sort or not. It applies
	* each sorter field/direction pair in turn by building an OR'ed master sorting function and running it against
	* the full dataset
	*/
	sortData: function () {
		var sortInfo = this.hasMultiSort ? this.multiSortInfo : this.sortInfo,
            direction = sortInfo.direction || "ASC",
            sorters = sortInfo.sorters,
            sortFns = [];

		//if we just have a single sorter, pretend it's the first in an array
		if (!this.hasMultiSort) {
			sorters = [{ direction: direction, field: sortInfo.field}];
		}

		//create a sorter function for each sorter field/direction combo
		for (var i = 0, j = sorters.length; i < j; i++) {
			sortFns.push(this.createSortFunction(sorters[i].field, sorters[i].direction));
		}

		if (sortFns.length == 0) {
			return;
		}

		//the direction modifier is multiplied with the result of the sorting functions to provide overall sort direction
		//(as opposed to direction per field)
		var directionModifier = direction.toUpperCase() == "DESC" ? -1 : 1;

		//create a function which ORs each sorter together to enable multi-sort
		var fn = function (r1, r2) {
			var result = sortFns[0].call(this, r1, r2);

			//if we have more than one sorter, OR any additional sorter functions together
			if (sortFns.length > 1) {
				for (var i = 1, j = sortFns.length; i < j; i++) {
					result = result || sortFns[i].call(this, r1, r2);
				}
			}

			return directionModifier * result;
		};

		//sort the data
		this.data.sort(direction, fn);
		if (this.snapshot && this.snapshot != this.data) {
			this.snapshot.sort(direction, fn);
		}
	},

	/**
	* @private
	* Creates and returns a function which sorts an array by the given field and direction
	* @param {String} field The field to create the sorter for
	* @param {String} direction The direction to sort by (defaults to "ASC")
	* @return {Function} A function which sorts by the field/direction combination provided
	*/
	createSortFunction: function (field, direction) {
		direction = direction || "ASC";
		var directionModifier = direction.toUpperCase() == "DESC" ? -1 : 1;

		var sortType = this.fields.get(field).sortType;

		//create a comparison function. Takes 2 records, returns 1 if record 1 is greater,
		//-1 if record 2 is greater or 0 if they are equal
		return function (r1, r2) {
			var v1 = sortType(r1.data[field]),
                v2 = sortType(r2.data[field]);

			return directionModifier * (v1 > v2 ? 1 : (v1 < v2 ? -1 : 0));
		};
	},

	/**
	* Sets the default sort column and order to be used by the next {@link #load} operation.
	* @param {String} fieldName The name of the field to sort by.
	* @param {String} dir (optional) The sort order, 'ASC' or 'DESC' (case-sensitive, defaults to <tt>'ASC'</tt>)
	*/
	setDefaultSort: function (field, dir) {
		dir = dir ? dir.toUpperCase() : 'ASC';
		this.sortInfo = { field: field, direction: dir };
		this.sortToggle[field] = dir;
	},

	/**
	* Sort the Records.
	* If remote sorting is used, the sort is performed on the server, and the cache is reloaded. If local
	* sorting is used, the cache is sorted internally. See also {@link #remoteSort} and {@link #paramNames}.
	* This function accepts two call signatures - pass in a field name as the first argument to sort on a single
	* field, or pass in an array of sort configuration objects to sort by multiple fields.
	* Single sort example:
	* store.sort('name', 'ASC');
	* Multi sort example:
	* store.sort([
	*   {
	*     field    : 'name',
	*     direction: 'ASC'
	*   },
	*   {
	*     field    : 'salary',
	*     direction: 'DESC'
	*   }
	* ], 'ASC');
	* In this second form, the sort configs are applied in order, with later sorters sorting within earlier sorters' results.
	* For example, if two records with the same name are present they will also be sorted by salary if given the sort configs
	* above. Any number of sort configs can be added.
	* @param {String/Array} fieldName The name of the field to sort by, or an array of ordered sort configs
	* @param {String} dir (optional) The sort order, 'ASC' or 'DESC' (case-sensitive, defaults to <tt>'ASC'</tt>)
	*/
	sort: function (fieldName, dir) {
		if (Ext.isArray(arguments[0])) {
			return this.multiSort.call(this, fieldName, dir);
		} else {
			return this.singleSort(fieldName, dir);
		}
	},

	/**
	* Sorts the store contents by a single field and direction. This is called internally by {@link sort} and would
	* not usually be called manually
	* @param {String} fieldName The name of the field to sort by.
	* @param {String} dir (optional) The sort order, 'ASC' or 'DESC' (case-sensitive, defaults to <tt>'ASC'</tt>)
	*/
	singleSort: function (fieldName, dir) {
		var field = this.fields.get(fieldName);
		if (!field) return false;

		var name = field.name,
            sortInfo = this.sortInfo || null,
            sortToggle = this.sortToggle ? this.sortToggle[name] : null;

		if (!dir) {
			if (sortInfo && sortInfo.field == name) { // toggle sort dir
				dir = (this.sortToggle[name] || 'ASC').toggle('ASC', 'DESC');
			} else {
				dir = field.sortDir;
			}
		}

		this.sortToggle[name] = dir;
		this.sortInfo = { field: name, direction: dir };
		this.hasMultiSort = false;

		if (this.remoteSort) {
			if (!this.load(this.lastOptions)) {
				if (sortToggle) {
					this.sortToggle[name] = sortToggle;
				}
				if (sortInfo) {
					this.sortInfo = sortInfo;
				}
			}
		} else {
			this.applySort();
			this.fireEvent('datachanged', this);
		}
	},

	/**
	* Sorts the contents of this store by multiple field/direction sorters. This is called internally by {@link sort}
	* and would not usually be called manually.
	* Multi sorting only currently applies to local datasets - multiple sort data is not currently sent to a proxy
	* if remoteSort is used.
	* @param {Array} sorters Array of sorter objects (field and direction)
	* @param {String} direction Overall direction to sort the ordered results by (defaults to "ASC")
	*/
	multiSort: function (sorters, direction) {
		this.hasMultiSort = true;
		direction = direction || "ASC";

		//toggle sort direction
		if (this.multiSortInfo && direction == this.multiSortInfo.direction) {
			direction = direction.toggle("ASC", "DESC");
		}

		/**
		* @property multiSortInfo
		* @type Object
		* Object containing overall sort direction and an ordered array of sorter configs used when sorting on multiple fields
		*/
		this.multiSortInfo = {
			sorters: sorters,
			direction: direction
		};

		if (this.remoteSort) {
			this.singleSort(sorters[0].field, sorters[0].direction);

		} else {
			this.applySort();
			this.fireEvent('datachanged', this);
		}
	},

	/**
	* Calls the specified function for each of the {@link Ext.data.Record Records} in the cache.
	* @param {Function} fn The function to call. The {@link Ext.data.Record Record} is passed as the first parameter.
	* Returning <tt>false</tt> aborts and exits the iteration.
	* @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed.
	* Defaults to the current {@link Ext.data.Record Record} in the iteration.
	*/
	each: function (fn, scope) {
		this.data.each(fn, scope);
	},

	/**
	* Gets all {@link Ext.data.Record records} modified since the last commit.  Modified records are
	* persisted across load operations (e.g., during paging). <b>Note</b>: deleted records are not
	* included.  See also <tt>{@link #pruneModifiedRecords}</tt> and
	* {@link Ext.data.Record}<tt>{@link Ext.data.Record#markDirty markDirty}.</tt>.
	* @return {Ext.data.Record[]} An array of {@link Ext.data.Record Records} containing outstanding
	* modifications.  To obtain modified fields within a modified record see
	*{@link Ext.data.Record}<tt>{@link Ext.data.Record#modified modified}.</tt>.
	*/
	getModifiedRecords: function () {
		return this.modified;
	},

	/**
	* Sums the value of <tt>property</tt> for each {@link Ext.data.Record record} between <tt>start</tt>
	* and <tt>end</tt> and returns the result.
	* @param {String} property A field in each record
	* @param {Number} start (optional) The record index to start at (defaults to <tt>0</tt>)
	* @param {Number} end (optional) The last record index to include (defaults to length - 1)
	* @return {Number} The sum
	*/
	sum: function (property, start, end) {
		var rs = this.data.items, v = 0;
		start = start || 0;
		end = (end || end === 0) ? end : rs.length - 1;

		for (var i = start; i <= end; i++) {
			v += (rs[i].data[property] || 0);
		}
		return v;
	},

	/**
	* @private
	* Returns a filter function used to test a the given property's value. Defers most of the work to
	* Ext.util.MixedCollection's createValueMatcher function
	* @param {String} property The property to create the filter function for
	* @param {String/RegExp} value The string/regex to compare the property value to
	* @param {Boolean} anyMatch True if we don't care if the filter value is not the full value (defaults to false)
	* @param {Boolean} caseSensitive True to create a case-sensitive regex (defaults to false)
	* @param {Boolean} exactMatch True to force exact match (^ and $ characters added to the regex). Defaults to false. Ignored if anyMatch is true.
	*/
	createFilterFn: function (property, value, anyMatch, caseSensitive, exactMatch) {
		if (Ext.isEmpty(value, false)) {
			return false;
		}
		value = this.data.createValueMatcher(value, anyMatch, caseSensitive, exactMatch);
		return function (r) {
			return value.test(r.data[property]);
		};
	},

	/**
	* @private
	* Given an array of filter functions (each with optional scope), constructs and returns a single function that returns
	* the result of all of the filters ANDed together
	* @param {Array} filters The array of filter objects (each object should contain an 'fn' and optional scope)
	* @return {Function} The multiple filter function
	*/
	createMultipleFilterFn: function (filters) {
		return function (record) {
			var isMatch = true;

			for (var i = 0, j = filters.length; i < j; i++) {
				var filter = filters[i],
                    fn = filter.fn,
                    scope = filter.scope;

				isMatch = isMatch && fn.call(scope, record);
			}

			return isMatch;
		};
	},

	/**
	* Filter the {@link Ext.data.Record records} by a specified property. Alternatively, pass an array of filter
	* options to filter by more than one property.
	* Single filter example:
	* store.filter('name', 'Ed', true, true); //finds all records containing the substring 'Ed'
	* Multiple filter example:
	* <pre><code>
	* store.filter([
	*   {
	*     property     : 'name',
	*     value        : 'Ed',
	*     anyMatch     : true, //optional, defaults to true
	*     caseSensitive: true  //optional, defaults to true
	*   },
	*
	*   //filter functions can also be passed
	*   {
	*     fn   : function(record) {
	*       return record.get('age') == 24
	*     },
	*     scope: this
	*   }
	* ]);
	* </code></pre>
	* @param {String|Array} field A field on your records, or an array containing multiple filter options
	* @param {String/RegExp} value Either a string that the field should begin with, or a RegExp to test
	* against the field.
	* @param {Boolean} anyMatch (optional) <tt>true</tt> to match any part not just the beginning
	* @param {Boolean} caseSensitive (optional) <tt>true</tt> for case sensitive comparison
	* @param {Boolean} exactMatch True to force exact match (^ and $ characters added to the regex). Defaults to false. Ignored if anyMatch is true.
	*/
	filter: function (property, value, anyMatch, caseSensitive, exactMatch) {
		//we can accept an array of filter objects, or a single filter object - normalize them here
		if (Ext.isObject(property)) {
			property = [property];
		}

		if (Ext.isArray(property)) {
			var filters = [];

			//normalize the filters passed into an array of filter functions
			for (var i = 0, j = property.length; i < j; i++) {
				var filter = property[i],
                    func = filter.fn,
                    scope = filter.scope || this;

				//if we weren't given a filter function, construct one now
				if (!Ext.isFunction(func)) {
					func = this.createFilterFn(filter.property, filter.value, filter.anyMatch, filter.caseSensitive, filter.exactMatch);
				}

				filters.push({ fn: func, scope: scope });
			}

			var fn = this.createMultipleFilterFn(filters);
		} else {
			//classic single property filter
			var fn = this.createFilterFn(property, value, anyMatch, caseSensitive, exactMatch);
		}

		return fn ? this.filterBy(fn) : this.clearFilter();
	},

	/**
	* Filter by a function. The specified function will be called for each
	* Record in this Store. If the function returns <tt>true</tt> the Record is included,
	* otherwise it is filtered out.
	* @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
	* <li><b>record</b> : Ext.data.Record<p class="sub-desc">The {@link Ext.data.Record record}
	* to test for filtering. Access field values using {@link Ext.data.Record#get}.</p></li>
	* <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
	* </ul>
	* @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this Store.
	*/
	filterBy: function (fn, scope) {
		this.snapshot = this.snapshot || this.data;
		this.data = this.queryBy(fn, scope || this);
		this.fireEvent('datachanged', this);
	},

	/**
	* Revert to a view of the Record cache with no filtering applied.
	* @param {Boolean} suppressEvent If <tt>true</tt> the filter is cleared silently without firing the
	* {@link #datachanged} event.
	*/
	clearFilter: function (suppressEvent) {
		if (this.isFiltered()) {
			this.data = this.snapshot;
			delete this.snapshot;
			if (suppressEvent !== true) {
				this.fireEvent('datachanged', this);
			}
		}
	},

	/**
	* Returns true if this store is currently filtered
	* @return {Boolean}
	*/
	isFiltered: function () {
		return !!this.snapshot && this.snapshot != this.data;
	},

	/**
	* Query the records by a specified property.
	* @param {String} field A field on your records
	* @param {String/RegExp} value Either a string that the field
	* should begin with, or a RegExp to test against the field.
	* @param {Boolean} anyMatch (optional) True to match any part not just the beginning
	* @param {Boolean} caseSensitive (optional) True for case sensitive comparison
	* @return {MixedCollection} Returns an Ext.util.MixedCollection of the matched records
	*/
	query: function (property, value, anyMatch, caseSensitive) {
		var fn = this.createFilterFn(property, value, anyMatch, caseSensitive);
		return fn ? this.queryBy(fn) : this.data.clone();
	},

	/**
	* Query the cached records in this Store using a filtering function. The specified function
	* will be called with each record in this Store. If the function returns <tt>true</tt> the record is
	* included in the results.
	* @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
	* <li><b>record</b> : Ext.data.Record<p class="sub-desc">The {@link Ext.data.Record record}
	* to test for filtering. Access field values using {@link Ext.data.Record#get}.</p></li>
	* <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
	* </ul>
	* @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this Store.
	* @return {MixedCollection} Returns an Ext.util.MixedCollection of the matched records
	**/
	queryBy: function (fn, scope) {
		var data = this.snapshot || this.data;
		return data.filterBy(fn, scope || this);
	},

	/**
	* Finds the index of the first matching Record in this store by a specific field value.
	* @param {String} fieldName The name of the Record field to test.
	* @param {String/RegExp} value Either a string that the field value
	* should begin with, or a RegExp to test against the field.
	* @param {Number} startIndex (optional) The index to start searching at
	* @param {Boolean} anyMatch (optional) True to match any part of the string, not just the beginning
	* @param {Boolean} caseSensitive (optional) True for case sensitive comparison
	* @return {Number} The matched index or -1
	*/
	find: function (property, value, start, anyMatch, caseSensitive) {
		var fn = this.createFilterFn(property, value, anyMatch, caseSensitive);
		return fn ? this.data.findIndexBy(fn, null, start) : -1;
	},

	/**
	* Finds the index of the first matching Record in this store by a specific field value.
	* @param {String} fieldName The name of the Record field to test.
	* @param {Mixed} value The value to match the field against.
	* @param {Number} startIndex (optional) The index to start searching at
	* @return {Number} The matched index or -1
	*/
	findExact: function (property, value, start) {
		return this.data.findIndexBy(function (rec) {
			return rec.get(property) === value;
		}, this, start);
	},

	/**
	* Find the index of the first matching Record in this Store by a function.
	* If the function returns <tt>true</tt> it is considered a match.
	* @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
	* <li><b>record</b> : Ext.data.Record<p class="sub-desc">The {@link Ext.data.Record record}
	* to test for filtering. Access field values using {@link Ext.data.Record#get}.</p></li>
	* <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
	* </ul>
	* @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this Store.
	* @param {Number} startIndex (optional) The index to start searching at
	* @return {Number} The matched index or -1
	*/
	findBy: function (fn, scope, start) {
		return this.data.findIndexBy(fn, scope, start);
	},

	/**
	* Collects unique values for a particular dataIndex from this store.
	* @param {String} dataIndex The property to collect
	* @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
	* @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
	* @return {Array} An array of the unique values
	**/
	collect: function (dataIndex, allowNull, bypassFilter) {
		var d = (bypassFilter === true && this.snapshot) ?
                this.snapshot.items : this.data.items;
		var v, sv, r = [], l = {};
		for (var i = 0, len = d.length; i < len; i++) {
			v = d[i].data[dataIndex];
			sv = String(v);
			if ((allowNull || !Ext.isEmpty(v)) && !l[sv]) {
				l[sv] = true;
				r[r.length] = v;
			}
		}
		return r;
	},

	// private
	afterEdit: function (record) {
		if (this.modified.indexOf(record) == -1) {
			this.modified.push(record);
		}
		this.fireEvent('update', this, record, Ext.data.Record.EDIT);
	},

	// private
	afterReject: function (record) {
		this.modified.remove(record);
		this.fireEvent('update', this, record, Ext.data.Record.REJECT);
	},

	// private
	afterCommit: function (record) {
		this.modified.remove(record);
		this.fireEvent('update', this, record, Ext.data.Record.COMMIT);
	},

	/**
	* Commit all Records with {@link #getModifiedRecords outstanding changes}. To handle updates for changes,
	* subscribe to the Store's {@link #update update event}, and perform updating when the third parameter is
	* Ext.data.Record.COMMIT.
	*/
	commitChanges: function () {
		var m = this.modified.slice(0);
		this.modified = [];
		for (var i = 0, len = m.length; i < len; i++) {
			m[i].commit();
		}
	},

	/**
	* {@link Ext.data.Record#reject Reject} outstanding changes on all {@link #getModifiedRecords modified records}.
	*/
	rejectChanges: function () {
		var m = this.modified.slice(0);
		this.modified = [];
		for (var i = 0, len = m.length; i < len; i++) {
			m[i].reject();
		}
		var m = this.removed.slice(0).reverse();
		this.removed = [];
		for (var i = 0, len = m.length; i < len; i++) {
			this.insert(m[i].lastIndex || 0, m[i]);
			m[i].reject();
		}
	},

	// private
	onMetaChange: function (meta) {
		this.recordType = this.reader.recordType;
		this.fields = this.recordType.prototype.fields;
		delete this.snapshot;
		if (this.reader.meta.sortInfo) {
			this.sortInfo = this.reader.meta.sortInfo;
		} else if (this.sortInfo && !this.fields.get(this.sortInfo.field)) {
			delete this.sortInfo;
		}
		if (this.writer) {
			this.writer.meta = this.reader.meta;
		}
		this.modified = [];
		this.fireEvent('metachange', this, this.reader.meta);
	},

	// private
	findInsertIndex: function (record) {
		this.suspendEvents();
		var data = this.data.clone();
		this.data.add(record);
		this.applySort();
		var index = this.data.indexOf(record);
		this.data = data;
		this.resumeEvents();
		return index;
	},

	/**
	* Set the value for a property name in this store's {@link #baseParams}.  Usage:</p><pre><code>
	myStore.setBaseParam('foo', {bar:3});
	</code></pre>
	* @param {String} name Name of the property to assign
	* @param {Mixed} value Value to assign the <tt>name</tt>d property
	**/
	setBaseParam: function (name, value) {
		this.baseParams = this.baseParams || {};
		this.baseParams[name] = value;
	}
});

Ext.reg('store', Ext.data.Store);

/**
* @class Ext.data.Store.Error
* @extends Ext.Error
* Store Error extension.
* @param {String} name
*/
Ext.data.Store.Error = Ext.extend(Ext.Error, {
	name: 'Ext.data.Store'
});
Ext.apply(Ext.data.Store.Error.prototype, {
	lang: {
		'writer-undefined': 'Attempted to execute a write-action without a DataWriter installed.'
	}
});
/**
* @class Ext.data.Field
* <p>This class encapsulates the field definition information specified in the field definition objects
* passed to {@link Ext.data.Record#create}.</p>
* <p>Developers do not need to instantiate this class. Instances are created by {@link Ext.data.Record.create}
* and cached in the {@link Ext.data.Record#fields fields} property of the created Record constructor's <b>prototype.</b></p>
*/
Ext.data.Field = Ext.extend(Object, {

	constructor: function (config) {
		if (Ext.isString(config)) {
			config = { name: config };
		}
		Ext.apply(this, config);

		var types = Ext.data.Types,
            st = this.sortType,
            t;

		if (this.type) {
			if (Ext.isString(this.type)) {
				this.type = Ext.data.Types[this.type.toUpperCase()] || types.AUTO;
			}
		} else {
			this.type = types.AUTO;
		}

		// named sortTypes are supported, here we look them up
		if (Ext.isString(st)) {
			this.sortType = Ext.data.SortTypes[st];
		} else if (Ext.isEmpty(st)) {
			this.sortType = this.type.sortType;
		}

		if (!this.convert) {
			this.convert = this.type.convert;
		}
	},

	/**
	* @cfg {String} name
	* The name by which the field is referenced within the Record. This is referenced by, for example,
	* the <code>dataIndex</code> property in column definition objects passed to {@link Ext.grid.ColumnModel}.
	* <p>Note: In the simplest case, if no properties other than <code>name</code> are required, a field
	* definition may consist of just a String for the field name.</p>
	*/
	/**
	* @cfg {Mixed} type
	* (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>
	* has not been specified. This may be specified as a string value. Possible values are
	* <div class="mdetail-params"><ul>
	* <li>auto (Default, implies no conversion)</li>
	* <li>string</li>
	* <li>int</li>
	* <li>float</li>
	* <li>boolean</li>
	* <li>date</li></ul></div>
	* <p>This may also be specified by referencing a member of the {@link Ext.data.Types} class.</p>
	* <p>Developers may create their own application-specific data types by defining new members of the
	* {@link Ext.data.Types} class.</p>
	*/
	/**
	* @cfg {Function} convert
	* (Optional) A function which converts the value provided by the Reader into an object that will be stored
	* in the Record. It is passed the following parameters:<div class="mdetail-params"><ul>
	* <li><b>v</b> : Mixed<div class="sub-desc">The data value as read by the Reader, if undefined will use
	* the configured <code>{@link Ext.data.Field#defaultValue defaultValue}</code>.</div></li>
	* <li><b>rec</b> : Mixed<div class="sub-desc">The data object containing the row as read by the Reader.
	* Depending on the Reader type, this could be an Array ({@link Ext.data.ArrayReader ArrayReader}), an object
	*  ({@link Ext.data.JsonReader JsonReader}), or an XML element ({@link Ext.data.XMLReader XMLReader}).</div></li>
	* </ul></div>
	* <pre><code>
	// example of convert function
	function fullName(v, record){
	return record.name.last + ', ' + record.name.first;
	}

	function location(v, record){
	return !record.city ? '' : (record.city + ', ' + record.state);
	}

	var Dude = Ext.data.Record.create([
	{name: 'fullname',  convert: fullName},
	{name: 'firstname', mapping: 'name.first'},
	{name: 'lastname',  mapping: 'name.last'},
	{name: 'city', defaultValue: 'homeless'},
	'state',
	{name: 'location',  convert: location}
	]);

	// create the data store
	var store = new Ext.data.Store({
	reader: new Ext.data.JsonReader(
	{
	idProperty: 'key',
	root: 'daRoot',
	totalProperty: 'total'
	},
	Dude  // recordType
	)
	});

	var myData = [
	{ key: 1,
	name: { first: 'Fat',    last:  'Albert' }
	// notice no city, state provided in data object
	},
	{ key: 2,
	name: { first: 'Barney', last:  'Rubble' },
	city: 'Bedrock', state: 'Stoneridge'
	},
	{ key: 3,
	name: { first: 'Cliff',  last:  'Claven' },
	city: 'Boston',  state: 'MA'
	}
	];
	* </code></pre>
	*/
	/**
	* @cfg {String} dateFormat
	* <p>(Optional) Used when converting received data into a Date when the {@link #type} is specified as <code>"date"</code>.</p>
	* <p>A format string for the {@link Date#parseDate Date.parseDate} function, or "timestamp" if the
	* value provided by the Reader is a UNIX timestamp, or "time" if the value provided by the Reader is a
	* javascript millisecond timestamp. See {@link Date}</p>
	*/
	dateFormat: null,
	/**
	* @cfg {Mixed} defaultValue
	* (Optional) The default value used <b>when a Record is being created by a {@link Ext.data.Reader Reader}</b>
	* when the item referenced by the <code>{@link Ext.data.Field#mapping mapping}</code> does not exist in the data
	* object (i.e. undefined). (defaults to "")
	*/
	defaultValue: "",
	/**
	* @cfg {String/Number} mapping
	* <p>(Optional) A path expression for use by the {@link Ext.data.DataReader} implementation
	* that is creating the {@link Ext.data.Record Record} to extract the Field value from the data object.
	* If the path expression is the same as the field name, the mapping may be omitted.</p>
	* <p>The form of the mapping expression depends on the Reader being used.</p>
	* <div class="mdetail-params"><ul>
	* <li>{@link Ext.data.JsonReader}<div class="sub-desc">The mapping is a string containing the javascript
	* expression to reference the data from an element of the data item's {@link Ext.data.JsonReader#root root} Array. Defaults to the field name.</div></li>
	* <li>{@link Ext.data.XmlReader}<div class="sub-desc">The mapping is an {@link Ext.DomQuery} path to the data
	* item relative to the DOM element that represents the {@link Ext.data.XmlReader#record record}. Defaults to the field name.</div></li>
	* <li>{@link Ext.data.ArrayReader}<div class="sub-desc">The mapping is a number indicating the Array index
	* of the field's value. Defaults to the field specification's Array position.</div></li>
	* </ul></div>
	* <p>If a more complex value extraction strategy is required, then configure the Field with a {@link #convert}
	* function. This is passed the whole row object, and may interrogate it in whatever way is necessary in order to
	* return the desired data.</p>
	*/
	mapping: null,
	/**
	* @cfg {Function} sortType
	* (Optional) A function which converts a Field's value to a comparable value in order to ensure
	* correct sort ordering. Predefined functions are provided in {@link Ext.data.SortTypes}. A custom
	* sort example:<pre><code>
	// current sort     after sort we want
	// +-+------+          +-+------+
	// |1|First |          |1|First |
	// |2|Last  |          |3|Second|
	// |3|Second|          |2|Last  |
	// +-+------+          +-+------+

	sortType: function(value) {
	switch (value.toLowerCase()) // native toLowerCase():
	{
	case 'first': return 1;
	case 'second': return 2;
	default: return 3;
	}
	}
	* </code></pre>
	*/
	sortType: null,
	/**
	* @cfg {String} sortDir
	* (Optional) Initial direction to sort (<code>"ASC"</code> or  <code>"DESC"</code>).  Defaults to
	* <code>"ASC"</code>.
	*/
	sortDir: "ASC",
	/**
	* @cfg {Boolean} allowBlank
	* (Optional) Used for validating a {@link Ext.data.Record record}, defaults to <code>true</code>.
	* An empty value here will cause {@link Ext.data.Record}.{@link Ext.data.Record#isValid isValid}
	* to evaluate to <code>false</code>.
	*/
	allowBlank: true
});
/**
* @class Ext.data.DataReader
* Abstract base class for reading structured data from a data source and converting
* it into an object containing {@link Ext.data.Record} objects and metadata for use
* by an {@link Ext.data.Store}.  This class is intended to be extended and should not
* be created directly. For existing implementations, see {@link Ext.data.ArrayReader},
* {@link Ext.data.JsonReader} and {@link Ext.data.XmlReader}.
* @constructor Create a new DataReader
* @param {Object} meta Metadata configuration options (implementation-specific).
* @param {Array/Object} recordType
* <p>Either an Array of {@link Ext.data.Field Field} definition objects (which
* will be passed to {@link Ext.data.Record#create}, or a {@link Ext.data.Record Record}
* constructor created using {@link Ext.data.Record#create}.</p>
*/
Ext.data.DataReader = function (meta, recordType) {
	/**
	* This DataReader's configured metadata as passed to the constructor.
	* @type Mixed
	* @property meta
	*/
	this.meta = meta;
	/**
	* @cfg {Array/Object} fields
	* <p>Either an Array of {@link Ext.data.Field Field} definition objects (which
	* will be passed to {@link Ext.data.Record#create}, or a {@link Ext.data.Record Record}
	* constructor created from {@link Ext.data.Record#create}.</p>
	*/
	this.recordType = Ext.isArray(recordType) ?
        Ext.data.Record.create(recordType) : recordType;

	// if recordType defined make sure extraction functions are defined
	if (this.recordType) {
		this.buildExtractors();
	}
};

Ext.data.DataReader.prototype = {
	/**
	* @cfg {String} messageProperty [undefined] Optional name of a property within a server-response that represents a user-feedback message.
	*/
	/**
	* Abstract method created in extension's buildExtractors impl.
	*/
	getTotal: Ext.emptyFn,
	/**
	* Abstract method created in extension's buildExtractors impl.
	*/
	getRoot: Ext.emptyFn,
	/**
	* Abstract method created in extension's buildExtractors impl.
	*/
	getMessage: Ext.emptyFn,
	/**
	* Abstract method created in extension's buildExtractors impl.
	*/
	getSuccess: Ext.emptyFn,
	/**
	* Abstract method created in extension's buildExtractors impl.
	*/
	getId: Ext.emptyFn,
	/**
	* Abstract method, overridden in DataReader extensions such as {@link Ext.data.JsonReader} and {@link Ext.data.XmlReader}
	*/
	buildExtractors: Ext.emptyFn,
	/**
	* Abstract method overridden in DataReader extensions such as {@link Ext.data.JsonReader} and {@link Ext.data.XmlReader}
	*/
	extractValues: Ext.emptyFn,

	/**
	* Used for un-phantoming a record after a successful database insert.  Sets the records pk along with new data from server.
	* You <b>must</b> return at least the database pk using the idProperty defined in your DataReader configuration.  The incoming
	* data from server will be merged with the data in the local record.
	* In addition, you <b>must</b> return record-data from the server in the same order received.
	* Will perform a commit as well, un-marking dirty-fields.  Store's "update" event will be suppressed.
	* @param {Record/Record[]} record The phantom record to be realized.
	* @param {Object/Object[]} data The new record data to apply.  Must include the primary-key from database defined in idProperty field.
	*/
	realize: function (rs, data) {
		if (Ext.isArray(rs)) {
			for (var i = rs.length - 1; i >= 0; i--) {
				// recurse
				if (Ext.isArray(data)) {
					this.realize(rs.splice(i, 1).shift(), data.splice(i, 1).shift());
				}
				else {
					// weird...rs is an array but data isn't??  recurse but just send in the whole invalid data object.
					// the else clause below will detect !this.isData and throw exception.
					this.realize(rs.splice(i, 1).shift(), data);
				}
			}
		}
		else {
			// If rs is NOT an array but data IS, see if data contains just 1 record.  If so extract it and carry on.
			if (Ext.isArray(data) && data.length == 1) {
				data = data.shift();
			}
			if (!this.isData(data)) {
				// TODO: Let exception-handler choose to commit or not rather than blindly rs.commit() here.
				//rs.commit();
				throw new Ext.data.DataReader.Error('realize', rs);
			}
			rs.phantom = false; // <-- That's what it's all about
			rs._phid = rs.id;  // <-- copy phantom-id -> _phid, so we can remap in Store#onCreateRecords
			rs.id = this.getId(data);
			rs.data = data;

			rs.commit();
		}
	},

	/**
	* Used for updating a non-phantom or "real" record's data with fresh data from server after remote-save.
	* If returning data from multiple-records after a batch-update, you <b>must</b> return record-data from the server in
	* the same order received.  Will perform a commit as well, un-marking dirty-fields.  Store's "update" event will be
	* suppressed as the record receives fresh new data-hash
	* @param {Record/Record[]} rs
	* @param {Object/Object[]} data
	*/
	update: function (rs, data) {
		if (Ext.isArray(rs)) {
			for (var i = rs.length - 1; i >= 0; i--) {
				if (Ext.isArray(data)) {
					this.update(rs.splice(i, 1).shift(), data.splice(i, 1).shift());
				}
				else {
					// weird...rs is an array but data isn't??  recurse but just send in the whole data object.
					// the else clause below will detect !this.isData and throw exception.
					this.update(rs.splice(i, 1).shift(), data);
				}
			}
		}
		else {
			// If rs is NOT an array but data IS, see if data contains just 1 record.  If so extract it and carry on.
			if (Ext.isArray(data) && data.length == 1) {
				data = data.shift();
			}
			if (this.isData(data)) {
				rs.data = Ext.apply(rs.data, data);
			}
			rs.commit();
		}
	},

	/**
	* returns extracted, type-cast rows of data.  Iterates to call #extractValues for each row
	* @param {Object[]/Object} data-root from server response
	* @param {Boolean} returnRecords [false] Set true to return instances of Ext.data.Record
	* @private
	*/
	extractData: function (root, returnRecords) {
		// A bit ugly this, too bad the Record's raw data couldn't be saved in a common property named "raw" or something.
		var rawName = (this instanceof Ext.data.JsonReader) ? 'json' : 'node';

		var rs = [];

		// Had to add Check for XmlReader, #isData returns true if root is an Xml-object.  Want to check in order to re-factor
		// #extractData into DataReader base, since the implementations are almost identical for JsonReader, XmlReader
		if (this.isData(root) && !(this instanceof Ext.data.XmlReader)) {
			root = [root];
		}
		var f = this.recordType.prototype.fields,
            fi = f.items,
            fl = f.length,
            rs = [];
		if (returnRecords === true) {
			var Record = this.recordType;
			for (var i = 0; i < root.length; i++) {
				var n = root[i];
				var record = new Record(this.extractValues(n, fi, fl), this.getId(n));
				record[rawName] = n;    // <-- There's implementation of ugly bit, setting the raw record-data.
				rs.push(record);
			}
		}
		else {
			for (var i = 0; i < root.length; i++) {
				var data = this.extractValues(root[i], fi, fl);
				data[this.meta.idProperty] = this.getId(root[i]);
				rs.push(data);
			}
		}
		return rs;
	},

	/**
	* Returns true if the supplied data-hash <b>looks</b> and quacks like data.  Checks to see if it has a key
	* corresponding to idProperty defined in your DataReader config containing non-empty pk.
	* @param {Object} data
	* @return {Boolean}
	*/
	isData: function (data) {
		return (data && Ext.isObject(data) && !Ext.isEmpty(this.getId(data))) ? true : false;
	},

	// private function a store will createSequence upon
	onMetaChange: function (meta) {
		delete this.ef;
		this.meta = meta;
		this.recordType = Ext.data.Record.create(meta.fields);
		this.buildExtractors();
	}
};

/**
* @class Ext.data.DataReader.Error
* @extends Ext.Error
* General error class for Ext.data.DataReader
*/
Ext.data.DataReader.Error = Ext.extend(Ext.Error, {
	constructor: function (message, arg) {
		this.arg = arg;
		Ext.Error.call(this, message);
	},
	name: 'Ext.data.DataReader'
});
Ext.apply(Ext.data.DataReader.Error.prototype, {
	lang: {
		'update': "#update received invalid data from server.  Please see docs for DataReader#update and review your DataReader configuration.",
		'realize': "#realize was called with invalid remote-data.  Please see the docs for DataReader#realize and review your DataReader configuration.",
		'invalid-response': "#readResponse received an invalid response from the server."
	}
});
/**
* @class Ext.data.DataWriter
* <p>Ext.data.DataWriter facilitates create, update, and destroy actions between
* an Ext.data.Store and a server-side framework. A Writer enabled Store will
* automatically manage the Ajax requests to perform CRUD actions on a Store.</p>
* <p>Ext.data.DataWriter is an abstract base class which is intended to be extended
* and should not be created directly. For existing implementations, see
* {@link Ext.data.JsonWriter}.</p>
* <p>Creating a writer is simple:</p>
* <pre><code>
var writer = new Ext.data.JsonWriter({
encode: false   // &lt;--- false causes data to be printed to jsonData config-property of Ext.Ajax#reqeust
});
* </code></pre>
* * <p>Same old JsonReader as Ext-2.x:</p>
* <pre><code>
var reader = new Ext.data.JsonReader({idProperty: 'id'}, [{name: 'first'}, {name: 'last'}, {name: 'email'}]);
* </code></pre>
*
* <p>The proxy for a writer enabled store can be configured with a simple <code>url</code>:</p>
* <pre><code>
// Create a standard HttpProxy instance.
var proxy = new Ext.data.HttpProxy({
url: 'app.php/users'    // &lt;--- Supports "provides"-type urls, such as '/users.json', '/products.xml' (Hello Rails/Merb)
});
* </code></pre>
* <p>For finer grained control, the proxy may also be configured with an <code>API</code>:</p>
* <pre><code>
// Maximum flexibility with the API-configuration
var proxy = new Ext.data.HttpProxy({
api: {
read    : 'app.php/users/read',
create  : 'app.php/users/create',
update  : 'app.php/users/update',
destroy : {  // &lt;--- Supports object-syntax as well
url: 'app.php/users/destroy',
method: "DELETE"
}
}
});
* </code></pre>
* <p>Pulling it all together into a Writer-enabled Store:</p>
* <pre><code>
var store = new Ext.data.Store({
proxy: proxy,
reader: reader,
writer: writer,
autoLoad: true,
autoSave: true  // -- Cell-level updates.
});
* </code></pre>
* <p>Initiating write-actions <b>automatically</b>, using the existing Ext2.0 Store/Record API:</p>
* <pre><code>
var rec = store.getAt(0);
rec.set('email', 'foo@bar.com');  // &lt;--- Immediately initiates an UPDATE action through configured proxy.

store.remove(rec);  // &lt;---- Immediately initiates a DESTROY action through configured proxy.
* </code></pre>
* <p>For <b>record/batch</b> updates, use the Store-configuration {@link Ext.data.Store#autoSave autoSave:false}</p>
* <pre><code>
var store = new Ext.data.Store({
proxy: proxy,
reader: reader,
writer: writer,
autoLoad: true,
autoSave: false  // -- disable cell-updates
});

var urec = store.getAt(0);
urec.set('email', 'foo@bar.com');

var drec = store.getAt(1);
store.remove(drec);

// Push the button!
store.save();
* </code></pre>
* @constructor Create a new DataWriter
* @param {Object} meta Metadata configuration options (implementation-specific)
* @param {Object} recordType Either an Array of field definition objects as specified
* in {@link Ext.data.Record#create}, or an {@link Ext.data.Record} object created
* using {@link Ext.data.Record#create}.
*/
Ext.data.DataWriter = function (config) {
	Ext.apply(this, config);
};
Ext.data.DataWriter.prototype = {

	/**
	* @cfg {Boolean} writeAllFields
	* <tt>false</tt> by default.  Set <tt>true</tt> to have DataWriter return ALL fields of a modified
	* record -- not just those that changed.
	* <tt>false</tt> to have DataWriter only request modified fields from a record.
	*/
	writeAllFields: false,
	/**
	* @cfg {Boolean} listful
	* <tt>false</tt> by default.  Set <tt>true</tt> to have the DataWriter <b>always</b> write HTTP params as a list,
	* even when acting upon a single record.
	*/
	listful: false,    // <-- listful is actually not used internally here in DataWriter.  @see Ext.data.Store#execute.

	/**
	* Compiles a Store recordset into a data-format defined by an extension such as {@link Ext.data.JsonWriter} or {@link Ext.data.XmlWriter} in preparation for a {@link Ext.data.Api#actions server-write action}.  The first two params are similar similar in nature to {@link Ext#apply},
	* Where the first parameter is the <i>receiver</i> of paramaters and the second, baseParams, <i>the source</i>.
	* @param {Object} params The request-params receiver.
	* @param {Object} baseParams as defined by {@link Ext.data.Store#baseParams}.  The baseParms must be encoded by the extending class, eg: {@link Ext.data.JsonWriter}, {@link Ext.data.XmlWriter}.
	* @param {String} action [{@link Ext.data.Api#actions create|update|destroy}]
	* @param {Record/Record[]} rs The recordset to write, the subject(s) of the write action.
	*/
	apply: function (params, baseParams, action, rs) {
		var data = [],
        renderer = action + 'Record';
		// TODO implement @cfg listful here
		if (Ext.isArray(rs)) {
			Ext.each(rs, function (rec) {
				data.push(this[renderer](rec));
			}, this);
		}
		else if (rs instanceof Ext.data.Record) {
			data = this[renderer](rs);
		}
		this.render(params, baseParams, data);
	},

	/**
	* abstract method meant to be overridden by all DataWriter extensions.  It's the extension's job to apply the "data" to the "params".
	* The data-object provided to render is populated with data according to the meta-info defined in the user's DataReader config,
	* @param {String} action [Ext.data.Api.actions.create|read|update|destroy]
	* @param {Record[]} rs Store recordset
	* @param {Object} params Http params to be sent to server.
	* @param {Object} data object populated according to DataReader meta-data.
	*/
	render: Ext.emptyFn,

	/**
	* @cfg {Function} updateRecord Abstract method that should be implemented in all subclasses
	* (e.g.: {@link Ext.data.JsonWriter#updateRecord JsonWriter.updateRecord}
	*/
	updateRecord: Ext.emptyFn,

	/**
	* @cfg {Function} createRecord Abstract method that should be implemented in all subclasses
	* (e.g.: {@link Ext.data.JsonWriter#createRecord JsonWriter.createRecord})
	*/
	createRecord: Ext.emptyFn,

	/**
	* @cfg {Function} destroyRecord Abstract method that should be implemented in all subclasses
	* (e.g.: {@link Ext.data.JsonWriter#destroyRecord JsonWriter.destroyRecord})
	*/
	destroyRecord: Ext.emptyFn,

	/**
	* Converts a Record to a hash, taking into account the state of the Ext.data.Record along with configuration properties
	* related to its rendering, such as {@link #writeAllFields}, {@link Ext.data.Record#phantom phantom}, {@link Ext.data.Record#getChanges getChanges} and
	* {@link Ext.data.DataReader#idProperty idProperty}
	* @param {Ext.data.Record} rec The Record from which to create a hash.
	* @param {Object} config <b>NOT YET IMPLEMENTED</b>.  Will implement an exlude/only configuration for fine-control over which fields do/don't get rendered.
	* @return {Object}
	* @protected
	* TODO Implement excludes/only configuration with 2nd param?
	*/
	toHash: function (rec, config) {
		var map = rec.fields.map,
            data = {},
            raw = (this.writeAllFields === false && rec.phantom === false) ? rec.getChanges() : rec.data,
            m;
		Ext.iterate(raw, function (prop, value) {
			if ((m = map[prop])) {
				data[m.mapping ? m.mapping : m.name] = value;
			}
		});
		// we don't want to write Ext auto-generated id to hash.  Careful not to remove it on Models not having auto-increment pk though.
		// We can tell its not auto-increment if the user defined a DataReader field for it *and* that field's value is non-empty.
		// we could also do a RegExp here for the Ext.data.Record AUTO_ID prefix.
		if (rec.phantom) {
			if (rec.fields.containsKey(this.meta.idProperty) && Ext.isEmpty(rec.data[this.meta.idProperty])) {
				delete data[this.meta.idProperty];
			}
		} else {
			data[this.meta.idProperty] = rec.id
		}
		return data;
	},

	/**
	* Converts a {@link Ext.data.DataWriter#toHash Hashed} {@link Ext.data.Record} to fields-array array suitable
	* for encoding to xml via XTemplate, eg:
	<code><pre>&lt;tpl for=".">&lt;{name}>{value}&lt;/{name}&lt;/tpl></pre></code>
	* eg, <b>non-phantom</b>:
	<code><pre>{id: 1, first: 'foo', last: 'bar'} --> [{name: 'id', value: 1}, {name: 'first', value: 'foo'}, {name: 'last', value: 'bar'}]</pre></code>
	* {@link Ext.data.Record#phantom Phantom} records will have had their idProperty omitted in {@link #toHash} if determined to be auto-generated.
	* Non AUTOINCREMENT pks should have been protected.
	* @param {Hash} data Hashed by Ext.data.DataWriter#toHash
	* @return {[Object]} Array of attribute-objects.
	* @protected
	*/
	toArray: function (data) {
		var fields = [];
		Ext.iterate(data, function (k, v) { fields.push({ name: k, value: v }); }, this);
		return fields;
	}
}; /**
 * @class Ext.data.DataProxy
 * @extends Ext.util.Observable
 * <p>Abstract base class for implementations which provide retrieval of unformatted data objects.
 * This class is intended to be extended and should not be created directly. For existing implementations,
 * see {@link Ext.data.DirectProxy}, {@link Ext.data.HttpProxy}, {@link Ext.data.ScriptTagProxy} and
 * {@link Ext.data.MemoryProxy}.</p>
 * <p>DataProxy implementations are usually used in conjunction with an implementation of {@link Ext.data.DataReader}
 * (of the appropriate type which knows how to parse the data object) to provide a block of
 * {@link Ext.data.Records} to an {@link Ext.data.Store}.</p>
 * <p>The parameter to a DataProxy constructor may be an {@link Ext.data.Connection} or can also be the
 * config object to an {@link Ext.data.Connection}.</p>
 * <p>Custom implementations must implement either the <code><b>doRequest</b></code> method (preferred) or the
 * <code>load</code> method (deprecated). See
 * {@link Ext.data.HttpProxy}.{@link Ext.data.HttpProxy#doRequest doRequest} or
 * {@link Ext.data.HttpProxy}.{@link Ext.data.HttpProxy#load load} for additional details.</p>
 * <p><b><u>Example 1</u></b></p>
 * <pre><code>
proxy: new Ext.data.ScriptTagProxy({
    {@link Ext.data.Connection#url url}: 'http://extjs.com/forum/topics-remote.php'
}),
 * </code></pre>
 * <p><b><u>Example 2</u></b></p>
 * <pre><code>
proxy : new Ext.data.HttpProxy({
    {@link Ext.data.Connection#method method}: 'GET',
    {@link Ext.data.HttpProxy#prettyUrls prettyUrls}: false,
    {@link Ext.data.Connection#url url}: 'local/default.php', // see options parameter for {@link Ext.Ajax#request}
    {@link #api}: {
        // all actions except the following will use above url
        create  : 'local/new.php',
        update  : 'local/update.php'
    }
}),
 * </code></pre>
 * <p>And <b>new in Ext version 3</b>, attach centralized event-listeners upon the DataProxy class itself!  This is a great place
 * to implement a <i>messaging system</i> to centralize your application's user-feedback and error-handling.</p>
 * <pre><code>
// Listen to all "beforewrite" event fired by all proxies.
Ext.data.DataProxy.on('beforewrite', function(proxy, action) {
    console.log('beforewrite: ', action);
});

// Listen to "write" event fired by all proxies
Ext.data.DataProxy.on('write', function(proxy, action, data, res, rs) {
    console.info('write: ', action);
});

// Listen to "exception" event fired by all proxies
Ext.data.DataProxy.on('exception', function(proxy, type, action) {
    console.error(type + action + ' exception);
});
 * </code></pre>
 * <b>Note:</b> These three events are all fired with the signature of the corresponding <i>DataProxy instance</i> event {@link #beforewrite beforewrite}, {@link #write write} and {@link #exception exception}.
 */
Ext.data.DataProxy = function (conn) {
	// make sure we have a config object here to support ux proxies.
	// All proxies should now send config into superclass constructor.
	conn = conn || {};

	// This line caused a bug when people use custom Connection object having its own request method.
	// http://extjs.com/forum/showthread.php?t=67194.  Have to set DataProxy config
	//Ext.applyIf(this, conn);

	this.api = conn.api;
	this.url = conn.url;
	this.restful = conn.restful;
	this.listeners = conn.listeners;

	// deprecated
	this.prettyUrls = conn.prettyUrls;

	/**
	* @cfg {Object} api
	* Specific urls to call on CRUD action methods "read", "create", "update" and "destroy".
	* Defaults to:<pre><code>
	api: {
	read    : undefined,
	create  : undefined,
	update  : undefined,
	destroy : undefined
	}
	* </code></pre>
	* <p>The url is built based upon the action being executed <tt>[load|create|save|destroy]</tt>
	* using the commensurate <tt>{@link #api}</tt> property, or if undefined default to the
	* configured {@link Ext.data.Store}.{@link Ext.data.Store#url url}.</p><br>
	* <p>For example:</p>
	* <pre><code>
	api: {
	load :    '/controller/load',
	create :  '/controller/new',  // Server MUST return idProperty of new record
	save :    '/controller/update',
	destroy : '/controller/destroy_action'
	}

	// Alternatively, one can use the object-form to specify each API-action
	api: {
	load: {url: 'read.php', method: 'GET'},
	create: 'create.php',
	destroy: 'destroy.php',
	save: 'update.php'
	}
	* </code></pre>
	* <p>If the specific URL for a given CRUD action is undefined, the CRUD action request
	* will be directed to the configured <tt>{@link Ext.data.Connection#url url}</tt>.</p>
	* <br><p><b>Note</b>: To modify the URL for an action dynamically the appropriate API
	* property should be modified before the action is requested using the corresponding before
	* action event.  For example to modify the URL associated with the load action:
	* <pre><code>
	// modify the url for the action
	myStore.on({
	beforeload: {
	fn: function (store, options) {
	// use <tt>{@link Ext.data.HttpProxy#setUrl setUrl}</tt> to change the URL for *just* this request.
	store.proxy.setUrl('changed1.php');

	// set optional second parameter to true to make this URL change
	// permanent, applying this URL for all subsequent requests.
	store.proxy.setUrl('changed1.php', true);

	// Altering the proxy API should be done using the public
	// method <tt>{@link Ext.data.DataProxy#setApi setApi}</tt>.
	store.proxy.setApi('read', 'changed2.php');

	// Or set the entire API with a config-object.
	// When using the config-object option, you must redefine the <b>entire</b>
	// API -- not just a specific action of it.
	store.proxy.setApi({
	read    : 'changed_read.php',
	create  : 'changed_create.php',
	update  : 'changed_update.php',
	destroy : 'changed_destroy.php'
	});
	}
	}
	});
	* </code></pre>
	* </p>
	*/

	this.addEvents(
	/**
	* @event exception
	* <p>Fires if an exception occurs in the Proxy during a remote request. This event is relayed
	* through a corresponding {@link Ext.data.Store}.{@link Ext.data.Store#exception exception},
	* so any Store instance may observe this event.</p>
	* <p>In addition to being fired through the DataProxy instance that raised the event, this event is also fired
	* through the Ext.data.DataProxy <i>class</i> to allow for centralized processing of exception events from <b>all</b>
	* DataProxies by attaching a listener to the Ext.data.Proxy class itself.</p>
	* <p>This event can be fired for one of two reasons:</p>
	* <div class="mdetail-params"><ul>
	* <li>remote-request <b>failed</b> : <div class="sub-desc">
	* The server did not return status === 200.
	* </div></li>
	* <li>remote-request <b>succeeded</b> : <div class="sub-desc">
	* The remote-request succeeded but the reader could not read the response.
	* This means the server returned data, but the configured Reader threw an
	* error while reading the response.  In this case, this event will be
	* raised and the caught error will be passed along into this event.
	* </div></li>
	* </ul></div>
	* <br><p>This event fires with two different contexts based upon the 2nd
	* parameter <tt>type [remote|response]</tt>.  The first four parameters
	* are identical between the two contexts -- only the final two parameters
	* differ.</p>
	* @param {DataProxy} this The proxy that sent the request
	* @param {String} type
	* <p>The value of this parameter will be either <tt>'response'</tt> or <tt>'remote'</tt>.</p>
	* <div class="mdetail-params"><ul>
	* <li><b><tt>'response'</tt></b> : <div class="sub-desc">
	* <p>An <b>invalid</b> response from the server was returned: either 404,
	* 500 or the response meta-data does not match that defined in the DataReader
	* (e.g.: root, idProperty, successProperty).</p>
	* </div></li>
	* <li><b><tt>'remote'</tt></b> : <div class="sub-desc">
	* <p>A <b>valid</b> response was returned from the server having
	* successProperty === false.  This response might contain an error-message
	* sent from the server.  For example, the user may have failed
	* authentication/authorization or a database validation error occurred.</p>
	* </div></li>
	* </ul></div>
	* @param {String} action Name of the action (see {@link Ext.data.Api#actions}.
	* @param {Object} options The options for the action that were specified in the {@link #request}.
	* @param {Object} response
	* <p>The value of this parameter depends on the value of the <code>type</code> parameter:</p>
	* <div class="mdetail-params"><ul>
	* <li><b><tt>'response'</tt></b> : <div class="sub-desc">
	* <p>The raw browser response object (e.g.: XMLHttpRequest)</p>
	* </div></li>
	* <li><b><tt>'remote'</tt></b> : <div class="sub-desc">
	* <p>The decoded response object sent from the server.</p>
	* </div></li>
	* </ul></div>
	* @param {Mixed} arg
	* <p>The type and value of this parameter depends on the value of the <code>type</code> parameter:</p>
	* <div class="mdetail-params"><ul>
	* <li><b><tt>'response'</tt></b> : Error<div class="sub-desc">
	* <p>The JavaScript Error object caught if the configured Reader could not read the data.
	* If the remote request returns success===false, this parameter will be null.</p>
	* </div></li>
	* <li><b><tt>'remote'</tt></b> : Record/Record[]<div class="sub-desc">
	* <p>This parameter will only exist if the <tt>action</tt> was a <b>write</b> action
	* (Ext.data.Api.actions.create|update|destroy).</p>
	* </div></li>
	* </ul></div>
	*/
        'exception',
	/**
	* @event beforeload
	* Fires before a request to retrieve a data object.
	* @param {DataProxy} this The proxy for the request
	* @param {Object} params The params object passed to the {@link #request} function
	*/
        'beforeload',
	/**
	* @event load
	* Fires before the load method's callback is called.
	* @param {DataProxy} this The proxy for the request
	* @param {Object} o The request transaction object
	* @param {Object} options The callback's <tt>options</tt> property as passed to the {@link #request} function
	*/
        'load',
	/**
	* @event loadexception
	* <p>This event is <b>deprecated</b>.  The signature of the loadexception event
	* varies depending on the proxy, use the catch-all {@link #exception} event instead.
	* This event will fire in addition to the {@link #exception} event.</p>
	* @param {misc} misc See {@link #exception}.
	* @deprecated
	*/
        'loadexception',
	/**
	* @event beforewrite
	* <p>Fires before a request is generated for one of the actions Ext.data.Api.actions.create|update|destroy</p>
	* <p>In addition to being fired through the DataProxy instance that raised the event, this event is also fired
	* through the Ext.data.DataProxy <i>class</i> to allow for centralized processing of beforewrite events from <b>all</b>
	* DataProxies by attaching a listener to the Ext.data.Proxy class itself.</p>
	* @param {DataProxy} this The proxy for the request
	* @param {String} action [Ext.data.Api.actions.create|update|destroy]
	* @param {Record/Record[]} rs The Record(s) to create|update|destroy.
	* @param {Object} params The request <code>params</code> object.  Edit <code>params</code> to add parameters to the request.
	*/
        'beforewrite',
	/**
	* @event write
	* <p>Fires before the request-callback is called</p>
	* <p>In addition to being fired through the DataProxy instance that raised the event, this event is also fired
	* through the Ext.data.DataProxy <i>class</i> to allow for centralized processing of write events from <b>all</b>
	* DataProxies by attaching a listener to the Ext.data.Proxy class itself.</p>
	* @param {DataProxy} this The proxy that sent the request
	* @param {String} action [Ext.data.Api.actions.create|upate|destroy]
	* @param {Object} data The data object extracted from the server-response
	* @param {Object} response The decoded response from server
	* @param {Record/Record[]} rs The Record(s) from Store
	* @param {Object} options The callback's <tt>options</tt> property as passed to the {@link #request} function
	*/
        'write'
    );
	Ext.data.DataProxy.superclass.constructor.call(this);

	// Prepare the proxy api.  Ensures all API-actions are defined with the Object-form.
	try {
		Ext.data.Api.prepare(this);
	} catch (e) {
		if (e instanceof Ext.data.Api.Error) {
			e.toConsole();
		}
	}
	// relay each proxy's events onto Ext.data.DataProxy class for centralized Proxy-listening
	Ext.data.DataProxy.relayEvents(this, ['beforewrite', 'write', 'exception']);
};

Ext.extend(Ext.data.DataProxy, Ext.util.Observable, {
	/**
	* @cfg {Boolean} restful
	* <p>Defaults to <tt>false</tt>.  Set to <tt>true</tt> to operate in a RESTful manner.</p>
	* <br><p> Note: this parameter will automatically be set to <tt>true</tt> if the
	* {@link Ext.data.Store} it is plugged into is set to <code>restful: true</code>. If the
	* Store is RESTful, there is no need to set this option on the proxy.</p>
	* <br><p>RESTful implementations enable the serverside framework to automatically route
	* actions sent to one url based upon the HTTP method, for example:
	* <pre><code>
	store: new Ext.data.Store({
	restful: true,
	proxy: new Ext.data.HttpProxy({url:'/users'}); // all requests sent to /users
	...
	)}
	* </code></pre>
	* If there is no <code>{@link #api}</code> specified in the configuration of the proxy,
	* all requests will be marshalled to a single RESTful url (/users) so the serverside
	* framework can inspect the HTTP Method and act accordingly:
	* <pre>
	<u>Method</u>   <u>url</u>        <u>action</u>
	POST     /users     create
	GET      /users     read
	PUT      /users/23  update
	DESTROY  /users/23  delete
	* </pre></p>
	* <p>If set to <tt>true</tt>, a {@link Ext.data.Record#phantom non-phantom} record's
	* {@link Ext.data.Record#id id} will be appended to the url. Some MVC (e.g., Ruby on Rails,
	* Merb and Django) support segment based urls where the segments in the URL follow the
	* Model-View-Controller approach:<pre><code>
	* someSite.com/controller/action/id
	* </code></pre>
	* Where the segments in the url are typically:<div class="mdetail-params"><ul>
	* <li>The first segment : represents the controller class that should be invoked.</li>
	* <li>The second segment : represents the class function, or method, that should be called.</li>
	* <li>The third segment : represents the ID (a variable typically passed to the method).</li>
	* </ul></div></p>
	* <br><p>Refer to <code>{@link Ext.data.DataProxy#api}</code> for additional information.</p>
	*/
	restful: false,

	/**
	* <p>Redefines the Proxy's API or a single action of an API. Can be called with two method signatures.</p>
	* <p>If called with an object as the only parameter, the object should redefine the <b>entire</b> API, e.g.:</p><pre><code>
	proxy.setApi({
	read    : '/users/read',
	create  : '/users/create',
	update  : '/users/update',
	destroy : '/users/destroy'
	});
	</code></pre>
	* <p>If called with two parameters, the first parameter should be a string specifying the API action to
	* redefine and the second parameter should be the URL (or function if using DirectProxy) to call for that action, e.g.:</p><pre><code>
	proxy.setApi(Ext.data.Api.actions.read, '/users/new_load_url');
	</code></pre>
	* @param {String/Object} api An API specification object, or the name of an action.
	* @param {String/Function} url The URL (or function if using DirectProxy) to call for the action.
	*/
	setApi: function () {
		if (arguments.length == 1) {
			var valid = Ext.data.Api.isValid(arguments[0]);
			if (valid === true) {
				this.api = arguments[0];
			}
			else {
				throw new Ext.data.Api.Error('invalid', valid);
			}
		}
		else if (arguments.length == 2) {
			if (!Ext.data.Api.isAction(arguments[0])) {
				throw new Ext.data.Api.Error('invalid', arguments[0]);
			}
			this.api[arguments[0]] = arguments[1];
		}
		Ext.data.Api.prepare(this);
	},

	/**
	* Returns true if the specified action is defined as a unique action in the api-config.
	* request.  If all API-actions are routed to unique urls, the xaction parameter is unecessary.  However, if no api is defined
	* and all Proxy actions are routed to DataProxy#url, the server-side will require the xaction parameter to perform a switch to
	* the corresponding code for CRUD action.
	* @param {String [Ext.data.Api.CREATE|READ|UPDATE|DESTROY]} action
	* @return {Boolean}
	*/
	isApiAction: function (action) {
		return (this.api[action]) ? true : false;
	},

	/**
	* All proxy actions are executed through this method.  Automatically fires the "before" + action event
	* @param {String} action Name of the action
	* @param {Ext.data.Record/Ext.data.Record[]/null} rs Will be null when action is 'load'
	* @param {Object} params
	* @param {Ext.data.DataReader} reader
	* @param {Function} callback
	* @param {Object} scope The scope (<code>this</code> reference) in which the callback function is executed. Defaults to the Proxy object.
	* @param {Object} options Any options specified for the action (e.g. see {@link Ext.data.Store#load}.
	*/
	request: function (action, rs, params, reader, callback, scope, options) {
		if (!this.api[action] && !this.load) {
			throw new Ext.data.DataProxy.Error('action-undefined', action);
		}
		params = params || {};
		if ((action === Ext.data.Api.actions.read) ? this.fireEvent("beforeload", this, params) : this.fireEvent("beforewrite", this, action, rs, params) !== false) {
			this.doRequest.apply(this, arguments);
		}
		else {
			callback.call(scope || this, null, options, false);
		}
	},


	/**
	* <b>Deprecated</b> load method using old method signature. See {@doRequest} for preferred method.
	* @deprecated
	* @param {Object} params
	* @param {Object} reader
	* @param {Object} callback
	* @param {Object} scope
	* @param {Object} arg
	*/
	load: null,

	/**
	* @cfg {Function} doRequest Abstract method that should be implemented in all subclasses.  <b>Note:</b> Should only be used by custom-proxy developers.
	* (e.g.: {@link Ext.data.HttpProxy#doRequest HttpProxy.doRequest},
	* {@link Ext.data.DirectProxy#doRequest DirectProxy.doRequest}).
	*/
	doRequest: function (action, rs, params, reader, callback, scope, options) {
		// default implementation of doRequest for backwards compatibility with 2.0 proxies.
		// If we're executing here, the action is probably "load".
		// Call with the pre-3.0 method signature.
		this.load(params, reader, callback, scope, options);
	},

	/**
	* @cfg {Function} onRead Abstract method that should be implemented in all subclasses.  <b>Note:</b> Should only be used by custom-proxy developers.  Callback for read {@link Ext.data.Api#actions action}.
	* @param {String} action Action name as per {@link Ext.data.Api.actions#read}.
	* @param {Object} o The request transaction object
	* @param {Object} res The server response
	* @fires loadexception (deprecated)
	* @fires exception
	* @fires load
	* @protected
	*/
	onRead: Ext.emptyFn,
	/**
	* @cfg {Function} onWrite Abstract method that should be implemented in all subclasses.  <b>Note:</b> Should only be used by custom-proxy developers.  Callback for <i>create, update and destroy</i> {@link Ext.data.Api#actions actions}.
	* @param {String} action [Ext.data.Api.actions.create|read|update|destroy]
	* @param {Object} trans The request transaction object
	* @param {Object} res The server response
	* @fires exception
	* @fires write
	* @protected
	*/
	onWrite: Ext.emptyFn,
	/**
	* buildUrl
	* Sets the appropriate url based upon the action being executed.  If restful is true, and only a single record is being acted upon,
	* url will be built Rails-style, as in "/controller/action/32".  restful will aply iff the supplied record is an
	* instance of Ext.data.Record rather than an Array of them.
	* @param {String} action The api action being executed [read|create|update|destroy]
	* @param {Ext.data.Record/Ext.data.Record[]} record The record or Array of Records being acted upon.
	* @return {String} url
	* @private
	*/
	buildUrl: function (action, record) {
		record = record || null;

		// conn.url gets nullified after each request.  If it's NOT null here, that means the user must have intervened with a call
		// to DataProxy#setUrl or DataProxy#setApi and changed it before the request was executed.  If that's the case, use conn.url,
		// otherwise, build the url from the api or this.url.
		var url = (this.conn && this.conn.url) ? this.conn.url : (this.api[action]) ? this.api[action].url : this.url;
		if (!url) {
			throw new Ext.data.Api.Error('invalid-url', action);
		}

		// look for urls having "provides" suffix used in some MVC frameworks like Rails/Merb and others.  The provides suffice informs
		// the server what data-format the client is dealing with and returns data in the same format (eg: application/json, application/xml, etc)
		// e.g.: /users.json, /users.xml, etc.
		// with restful routes, we need urls like:
		// PUT /users/1.json
		// DELETE /users/1.json
		var provides = null;
		var m = url.match(/(.*)(\.json|\.xml|\.html)$/);
		if (m) {
			provides = m[2];    // eg ".json"
			url = m[1];    // eg: "/users"
		}
		// prettyUrls is deprectated in favor of restful-config
		if ((this.restful === true || this.prettyUrls === true) && record instanceof Ext.data.Record && !record.phantom) {
			url += '/' + record.id;
		}
		return (provides === null) ? url : url + provides;
	},

	/**
	* Destroys the proxy by purging any event listeners and cancelling any active requests.
	*/
	destroy: function () {
		this.purgeListeners();
	}
});

// Apply the Observable prototype to the DataProxy class so that proxy instances can relay their
// events to the class.  Allows for centralized listening of all proxy instances upon the DataProxy class.
Ext.apply(Ext.data.DataProxy, Ext.util.Observable.prototype);
Ext.util.Observable.call(Ext.data.DataProxy);

/**
* @class Ext.data.DataProxy.Error
* @extends Ext.Error
* DataProxy Error extension.
* constructor
* @param {String} message Message describing the error.
* @param {Record/Record[]} arg
*/
Ext.data.DataProxy.Error = Ext.extend(Ext.Error, {
	constructor: function (message, arg) {
		this.arg = arg;
		Ext.Error.call(this, message);
	},
	name: 'Ext.data.DataProxy'
});
Ext.apply(Ext.data.DataProxy.Error.prototype, {
	lang: {
		'action-undefined': "DataProxy attempted to execute an API-action but found an undefined url / function.  Please review your Proxy url/api-configuration.",
		'api-invalid': 'Recieved an invalid API-configuration.  Please ensure your proxy API-configuration contains only the actions from Ext.data.Api.actions.'
	}
});


/**
* @class Ext.data.Request
* A simple Request class used internally to the data package to provide more generalized remote-requests
* to a DataProxy.
* TODO Not yet implemented.  Implement in Ext.data.Store#execute
*/
Ext.data.Request = function (params) {
	Ext.apply(this, params);
};
Ext.data.Request.prototype = {
	/**
	* @cfg {String} action
	*/
	action: undefined,
	/**
	* @cfg {Ext.data.Record[]/Ext.data.Record} rs The Store recordset associated with the request.
	*/
	rs: undefined,
	/**
	* @cfg {Object} params HTTP request params
	*/
	params: undefined,
	/**
	* @cfg {Function} callback The function to call when request is complete
	*/
	callback: Ext.emptyFn,
	/**
	* @cfg {Object} scope The scope of the callback funtion
	*/
	scope: undefined,
	/**
	* @cfg {Ext.data.DataReader} reader The DataReader instance which will parse the received response
	*/
	reader: undefined
};
/**
* @class Ext.data.Response
* A generic response class to normalize response-handling internally to the framework.
*/
Ext.data.Response = function (params) {
	Ext.apply(this, params);
};
Ext.data.Response.prototype = {
	/**
	* @cfg {String} action {@link Ext.data.Api#actions}
	*/
	action: undefined,
	/**
	* @cfg {Boolean} success
	*/
	success: undefined,
	/**
	* @cfg {String} message
	*/
	message: undefined,
	/**
	* @cfg {Array/Object} data
	*/
	data: undefined,
	/**
	* @cfg {Object} raw The raw response returned from server-code
	*/
	raw: undefined,
	/**
	* @cfg {Ext.data.Record/Ext.data.Record[]} records related to the Request action
	*/
	records: undefined
};
/**
* @class Ext.data.ScriptTagProxy
* @extends Ext.data.DataProxy
* An implementation of Ext.data.DataProxy that reads a data object from a URL which may be in a domain
* other than the originating domain of the running page.<br>
* <p>
* <b>Note that if you are retrieving data from a page that is in a domain that is NOT the same as the originating domain
* of the running page, you must use this class, rather than HttpProxy.</b><br>
* <p>
* The content passed back from a server resource requested by a ScriptTagProxy <b>must</b> be executable JavaScript
* source code because it is used as the source inside a &lt;script> tag.<br>
* <p>
* In order for the browser to process the returned data, the server must wrap the data object
* with a call to a callback function, the name of which is passed as a parameter by the ScriptTagProxy.
* Below is a Java example for a servlet which returns data for either a ScriptTagProxy, or an HttpProxy
* depending on whether the callback name was passed:
* <p>
* <pre><code>
boolean scriptTag = false;
String cb = request.getParameter("callback");
if (cb != null) {
scriptTag = true;
response.setContentType("text/javascript");
} else {
response.setContentType("application/x-json");
}
Writer out = response.getWriter();
if (scriptTag) {
out.write(cb + "(");
}
out.print(dataBlock.toJsonString());
if (scriptTag) {
out.write(");");
}
</code></pre>
* <p>Below is a PHP example to do the same thing:</p><pre><code>
$callback = $_REQUEST['callback'];

// Create the output object.
$output = array('a' => 'Apple', 'b' => 'Banana');

//start output
if ($callback) {
header('Content-Type: text/javascript');
echo $callback . '(' . json_encode($output) . ');';
} else {
header('Content-Type: application/x-json');
echo json_encode($output);
}
</code></pre>
* <p>Below is the ASP.Net code to do the same thing:</p><pre><code>
String jsonString = "{success: true}";
String cb = Request.Params.Get("callback");
String responseString = "";
if (!String.IsNullOrEmpty(cb)) {
responseString = cb + "(" + jsonString + ")";
} else {
responseString = jsonString;
}
Response.Write(responseString);
</code></pre>
*
* @constructor
* @param {Object} config A configuration object.
*/
Ext.data.ScriptTagProxy = function (config) {
	Ext.apply(this, config);

	Ext.data.ScriptTagProxy.superclass.constructor.call(this, config);

	this.head = document.getElementsByTagName("head")[0];

	/**
	* @event loadexception
	* <b>Deprecated</b> in favor of 'exception' event.
	* Fires if an exception occurs in the Proxy during data loading.  This event can be fired for one of two reasons:
	* <ul><li><b>The load call timed out.</b>  This means the load callback did not execute within the time limit
	* specified by {@link #timeout}.  In this case, this event will be raised and the
	* fourth parameter (read error) will be null.</li>
	* <li><b>The load succeeded but the reader could not read the response.</b>  This means the server returned
	* data, but the configured Reader threw an error while reading the data.  In this case, this event will be
	* raised and the caught error will be passed along as the fourth parameter of this event.</li></ul>
	* Note that this event is also relayed through {@link Ext.data.Store}, so you can listen for it directly
	* on any Store instance.
	* @param {Object} this
	* @param {Object} options The loading options that were specified (see {@link #load} for details).  If the load
	* call timed out, this parameter will be null.
	* @param {Object} arg The callback's arg object passed to the {@link #load} function
	* @param {Error} e The JavaScript Error object caught if the configured Reader could not read the data.
	* If the remote request returns success: false, this parameter will be null.
	*/
};

Ext.data.ScriptTagProxy.TRANS_ID = 1000;

Ext.extend(Ext.data.ScriptTagProxy, Ext.data.DataProxy, {
	/**
	* @cfg {String} url The URL from which to request the data object.
	*/
	/**
	* @cfg {Number} timeout (optional) The number of milliseconds to wait for a response. Defaults to 30 seconds.
	*/
	timeout: 30000,
	/**
	* @cfg {String} callbackParam (Optional) The name of the parameter to pass to the server which tells
	* the server the name of the callback function set up by the load call to process the returned data object.
	* Defaults to "callback".<p>The server-side processing must read this parameter value, and generate
	* javascript output which calls this named function passing the data object as its only parameter.
	*/
	callbackParam: "callback",
	/**
	*  @cfg {Boolean} nocache (optional) Defaults to true. Disable caching by adding a unique parameter
	* name to the request.
	*/
	nocache: true,

	/**
	* HttpProxy implementation of DataProxy#doRequest
	* @param {String} action
	* @param {Ext.data.Record/Ext.data.Record[]} rs If action is <tt>read</tt>, rs will be null
	* @param {Object} params An object containing properties which are to be used as HTTP parameters
	* for the request to the remote server.
	* @param {Ext.data.DataReader} reader The Reader object which converts the data
	* object into a block of Ext.data.Records.
	* @param {Function} callback The function into which to pass the block of Ext.data.Records.
	* The function must be passed <ul>
	* <li>The Record block object</li>
	* <li>The "arg" argument from the load function</li>
	* <li>A boolean success indicator</li>
	* </ul>
	* @param {Object} scope The scope (<code>this</code> reference) in which the callback function is executed. Defaults to the browser window.
	* @param {Object} arg An optional argument which is passed to the callback as its second parameter.
	*/
	doRequest: function (action, rs, params, reader, callback, scope, arg) {
		var p = Ext.urlEncode(Ext.apply(params, this.extraParams));

		var url = this.buildUrl(action, rs);
		if (!url) {
			throw new Ext.data.Api.Error('invalid-url', url);
		}
		url = Ext.urlAppend(url, p);

		if (this.nocache) {
			url = Ext.urlAppend(url, '_dc=' + (new Date().getTime()));
		}
		var transId = ++Ext.data.ScriptTagProxy.TRANS_ID;
		var trans = {
			id: transId,
			action: action,
			cb: "stcCallback" + transId,
			scriptId: "stcScript" + transId,
			params: params,
			arg: arg,
			url: url,
			callback: callback,
			scope: scope,
			reader: reader
		};
		window[trans.cb] = this.createCallback(action, rs, trans);
		url += String.format("&{0}={1}", this.callbackParam, trans.cb);
		if (this.autoAbort !== false) {
			this.abort();
		}

		trans.timeoutId = this.handleFailure.defer(this.timeout, this, [trans]);

		var script = document.createElement("script");
		script.setAttribute("src", url);
		script.setAttribute("type", "text/javascript");
		script.setAttribute("id", trans.scriptId);
		this.head.appendChild(script);

		this.trans = trans;
	},

	// @private createCallback
	createCallback: function (action, rs, trans) {
		var self = this;
		return function (res) {
			self.trans = false;
			self.destroyTrans(trans, true);
			if (action === Ext.data.Api.actions.read) {
				self.onRead.call(self, action, trans, res);
			} else {
				self.onWrite.call(self, action, trans, res, rs);
			}
		};
	},
	/**
	* Callback for read actions
	* @param {String} action [Ext.data.Api.actions.create|read|update|destroy]
	* @param {Object} trans The request transaction object
	* @param {Object} res The server response
	* @protected
	*/
	onRead: function (action, trans, res) {
		var result;
		try {
			result = trans.reader.readRecords(res);
		} catch (e) {
			// @deprecated: fire loadexception
			this.fireEvent("loadexception", this, trans, res, e);

			this.fireEvent('exception', this, 'response', action, trans, res, e);
			trans.callback.call(trans.scope || window, null, trans.arg, false);
			return;
		}
		if (result.success === false) {
			// @deprecated: fire old loadexception for backwards-compat.
			this.fireEvent('loadexception', this, trans, res);

			this.fireEvent('exception', this, 'remote', action, trans, res, null);
		} else {
			this.fireEvent("load", this, res, trans.arg);
		}
		trans.callback.call(trans.scope || window, result, trans.arg, result.success);
	},
	/**
	* Callback for write actions
	* @param {String} action [Ext.data.Api.actions.create|read|update|destroy]
	* @param {Object} trans The request transaction object
	* @param {Object} res The server response
	* @protected
	*/
	onWrite: function (action, trans, response, rs) {
		var reader = trans.reader;
		try {
			// though we already have a response object here in STP, run through readResponse to catch any meta-data exceptions.
			var res = reader.readResponse(action, response);
		} catch (e) {
			this.fireEvent('exception', this, 'response', action, trans, res, e);
			trans.callback.call(trans.scope || window, null, res, false);
			return;
		}
		if (!res.success === true) {
			this.fireEvent('exception', this, 'remote', action, trans, res, rs);
			trans.callback.call(trans.scope || window, null, res, false);
			return;
		}
		this.fireEvent("write", this, action, res.data, res, rs, trans.arg);
		trans.callback.call(trans.scope || window, res.data, res, true);
	},

	// private
	isLoading: function () {
		return this.trans ? true : false;
	},

	/**
	* Abort the current server request.
	*/
	abort: function () {
		if (this.isLoading()) {
			this.destroyTrans(this.trans);
		}
	},

	// private
	destroyTrans: function (trans, isLoaded) {
		this.head.removeChild(document.getElementById(trans.scriptId));
		clearTimeout(trans.timeoutId);
		if (isLoaded) {
			window[trans.cb] = undefined;
			try {
				delete window[trans.cb];
			} catch (e) { }
		} else {
			// if hasn't been loaded, wait for load to remove it to prevent script error
			window[trans.cb] = function () {
				window[trans.cb] = undefined;
				try {
					delete window[trans.cb];
				} catch (e) { }
			};
		}
	},

	// private
	handleFailure: function (trans) {
		this.trans = false;
		this.destroyTrans(trans, false);
		if (trans.action === Ext.data.Api.actions.read) {
			// @deprecated firing loadexception
			this.fireEvent("loadexception", this, null, trans.arg);
		}

		this.fireEvent('exception', this, 'response', trans.action, {
			response: null,
			options: trans.arg
		});
		trans.callback.call(trans.scope || window, null, trans.arg, false);
	},

	// inherit docs
	destroy: function () {
		this.abort();
		Ext.data.ScriptTagProxy.superclass.destroy.call(this);
	}
}); /**
 * @class Ext.data.HttpProxy
 * @extends Ext.data.DataProxy
 * <p>An implementation of {@link Ext.data.DataProxy} that processes data requests within the same
 * domain of the originating page.</p>
 * <p><b>Note</b>: this class cannot be used to retrieve data from a domain other
 * than the domain from which the running page was served. For cross-domain requests, use a
 * {@link Ext.data.ScriptTagProxy ScriptTagProxy}.</p>
 * <p>Be aware that to enable the browser to parse an XML document, the server must set
 * the Content-Type header in the HTTP response to "<tt>text/xml</tt>".</p>
 * @constructor
 * @param {Object} conn
 * An {@link Ext.data.Connection} object, or options parameter to {@link Ext.Ajax#request}.
 * <p>Note that if this HttpProxy is being used by a {@link Ext.data.Store Store}, then the
 * Store's call to {@link #load} will override any specified <tt>callback</tt> and <tt>params</tt>
 * options. In this case, use the Store's {@link Ext.data.Store#events events} to modify parameters,
 * or react to loading events. The Store's {@link Ext.data.Store#baseParams baseParams} may also be
 * used to pass parameters known at instantiation time.</p>
 * <p>If an options parameter is passed, the singleton {@link Ext.Ajax} object will be used to make
 * the request.</p>
 */
Ext.data.HttpProxy = function (conn) {
	Ext.data.HttpProxy.superclass.constructor.call(this, conn);

	/**
	* The Connection object (Or options parameter to {@link Ext.Ajax#request}) which this HttpProxy
	* uses to make requests to the server. Properties of this object may be changed dynamically to
	* change the way data is requested.
	* @property
	*/
	this.conn = conn;

	// nullify the connection url.  The url param has been copied to 'this' above.  The connection
	// url will be set during each execution of doRequest when buildUrl is called.  This makes it easier for users to override the
	// connection url during beforeaction events (ie: beforeload, beforewrite, etc).
	// Url is always re-defined during doRequest.
	this.conn.url = null;

	this.useAjax = !conn || !conn.events;

	// A hash containing active requests, keyed on action [Ext.data.Api.actions.create|read|update|destroy]
	var actions = Ext.data.Api.actions;
	this.activeRequest = {};
	for (var verb in actions) {
		this.activeRequest[actions[verb]] = undefined;
	}
};

Ext.extend(Ext.data.HttpProxy, Ext.data.DataProxy, {
	/**
	* Return the {@link Ext.data.Connection} object being used by this Proxy.
	* @return {Connection} The Connection object. This object may be used to subscribe to events on
	* a finer-grained basis than the DataProxy events.
	*/
	getConnection: function () {
		return this.useAjax ? Ext.Ajax : this.conn;
	},

	/**
	* Used for overriding the url used for a single request.  Designed to be called during a beforeaction event.  Calling setUrl
	* will override any urls set via the api configuration parameter.  Set the optional parameter makePermanent to set the url for
	* all subsequent requests.  If not set to makePermanent, the next request will use the same url or api configuration defined
	* in the initial proxy configuration.
	* @param {String} url
	* @param {Boolean} makePermanent (Optional) [false]
	*
	* (e.g.: beforeload, beforesave, etc).
	*/
	setUrl: function (url, makePermanent) {
		this.conn.url = url;
		if (makePermanent === true) {
			this.url = url;
			this.api = null;
			Ext.data.Api.prepare(this);
		}
	},

	/**
	* HttpProxy implementation of DataProxy#doRequest
	* @param {String} action The crud action type (create, read, update, destroy)
	* @param {Ext.data.Record/Ext.data.Record[]} rs If action is load, rs will be null
	* @param {Object} params An object containing properties which are to be used as HTTP parameters
	* for the request to the remote server.
	* @param {Ext.data.DataReader} reader The Reader object which converts the data
	* object into a block of Ext.data.Records.
	* @param {Function} callback
	* <div class="sub-desc"><p>A function to be called after the request.
	* The <tt>callback</tt> is passed the following arguments:<ul>
	* <li><tt>r</tt> : Ext.data.Record[] The block of Ext.data.Records.</li>
	* <li><tt>options</tt>: Options object from the action request</li>
	* <li><tt>success</tt>: Boolean success indicator</li></ul></p></div>
	* @param {Object} scope The scope (<code>this</code> reference) in which the callback function is executed. Defaults to the browser window.
	* @param {Object} arg An optional argument which is passed to the callback as its second parameter.
	* @protected
	*/
	doRequest: function (action, rs, params, reader, cb, scope, arg) {
		var o = {
			method: (this.api[action]) ? this.api[action]['method'] : undefined,
			request: {
				callback: cb,
				scope: scope,
				arg: arg
			},
			reader: reader,
			callback: this.createCallback(action, rs),
			scope: this
		};

		// If possible, transmit data using jsonData || xmlData on Ext.Ajax.request (An installed DataWriter would have written it there.).
		// Use std HTTP params otherwise.
		if (params.jsonData) {
			o.jsonData = params.jsonData;
		} else if (params.xmlData) {
			o.xmlData = params.xmlData;
		} else {
			o.params = params || {};
		}
		// Set the connection url.  If this.conn.url is not null here,
		// the user must have overridden the url during a beforewrite/beforeload event-handler.
		// this.conn.url is nullified after each request.
		this.conn.url = this.buildUrl(action, rs);

		if (this.useAjax) {

			Ext.applyIf(o, this.conn);

			// If a currently running request is found for this action, abort it.
			if (this.activeRequest[action]) {
				////
				// Disabled aborting activeRequest while implementing REST.  activeRequest[action] will have to become an array
				// TODO ideas anyone?
				//
				//Ext.Ajax.abort(this.activeRequest[action]);
			}
			this.activeRequest[action] = Ext.Ajax.request(o);
		} else {
			this.conn.request(o);
		}
		// request is sent, nullify the connection url in preparation for the next request
		this.conn.url = null;
	},

	/**
	* Returns a callback function for a request.  Note a special case is made for the
	* read action vs all the others.
	* @param {String} action [create|update|delete|load]
	* @param {Ext.data.Record[]} rs The Store-recordset being acted upon
	* @private
	*/
	createCallback: function (action, rs) {
		return function (o, success, response) {
			this.activeRequest[action] = undefined;
			if (!success) {
				if (action === Ext.data.Api.actions.read) {
					// @deprecated: fire loadexception for backwards compat.
					// TODO remove
					this.fireEvent('loadexception', this, o, response);
				}
				this.fireEvent('exception', this, 'response', action, o, response);
				o.request.callback.call(o.request.scope, null, o.request.arg, false);
				return;
			}
			if (action === Ext.data.Api.actions.read) {
				this.onRead(action, o, response);
			} else {
				this.onWrite(action, o, response, rs);
			}
		};
	},

	/**
	* Callback for read action
	* @param {String} action Action name as per {@link Ext.data.Api.actions#read}.
	* @param {Object} o The request transaction object
	* @param {Object} res The server response
	* @fires loadexception (deprecated)
	* @fires exception
	* @fires load
	* @protected
	*/
	onRead: function (action, o, response) {
		var result;
		try {
			result = o.reader.read(response);
		} catch (e) {
			// @deprecated: fire old loadexception for backwards-compat.
			// TODO remove
			this.fireEvent('loadexception', this, o, response, e);

			this.fireEvent('exception', this, 'response', action, o, response, e);
			o.request.callback.call(o.request.scope, null, o.request.arg, false);
			return;
		}
		if (result.success === false) {
			// @deprecated: fire old loadexception for backwards-compat.
			// TODO remove
			this.fireEvent('loadexception', this, o, response);

			// Get DataReader read-back a response-object to pass along to exception event
			var res = o.reader.readResponse(action, response);
			this.fireEvent('exception', this, 'remote', action, o, res, null);
		}
		else {
			this.fireEvent('load', this, o, o.request.arg);
		}
		// TODO refactor onRead, onWrite to be more generalized now that we're dealing with Ext.data.Response instance
		// the calls to request.callback(...) in each will have to be made identical.
		// NOTE reader.readResponse does not currently return Ext.data.Response
		o.request.callback.call(o.request.scope, result, o.request.arg, result.success);
	},
	/**
	* Callback for write actions
	* @param {String} action [Ext.data.Api.actions.create|read|update|destroy]
	* @param {Object} trans The request transaction object
	* @param {Object} res The server response
	* @fires exception
	* @fires write
	* @protected
	*/
	onWrite: function (action, o, response, rs) {
		var reader = o.reader;
		var res;
		try {
			res = reader.readResponse(action, response);
		} catch (e) {
			this.fireEvent('exception', this, 'response', action, o, response, e);
			o.request.callback.call(o.request.scope, null, o.request.arg, false);
			return;
		}
		if (res.success === true) {
			this.fireEvent('write', this, action, res.data, res, rs, o.request.arg);
		} else {
			this.fireEvent('exception', this, 'remote', action, o, res, rs);
		}
		// TODO refactor onRead, onWrite to be more generalized now that we're dealing with Ext.data.Response instance
		// the calls to request.callback(...) in each will have to be made similar.
		// NOTE reader.readResponse does not currently return Ext.data.Response
		o.request.callback.call(o.request.scope, res.data, res, res.success);
	},

	// inherit docs
	destroy: function () {
		if (!this.useAjax) {
			this.conn.abort();
		} else if (this.activeRequest) {
			var actions = Ext.data.Api.actions;
			for (var verb in actions) {
				if (this.activeRequest[actions[verb]]) {
					Ext.Ajax.abort(this.activeRequest[actions[verb]]);
				}
			}
		}
		Ext.data.HttpProxy.superclass.destroy.call(this);
	}
}); /**
 * @class Ext.data.MemoryProxy
 * @extends Ext.data.DataProxy
 * An implementation of Ext.data.DataProxy that simply passes the data specified in its constructor
 * to the Reader when its load method is called.
 * @constructor
 * @param {Object} data The data object which the Reader uses to construct a block of Ext.data.Records.
 */
Ext.data.MemoryProxy = function (data) {
	// Must define a dummy api with "read" action to satisfy DataProxy#doRequest and Ext.data.Api#prepare *before* calling super
	var api = {};
	api[Ext.data.Api.actions.read] = true;
	Ext.data.MemoryProxy.superclass.constructor.call(this, {
		api: api
	});
	this.data = data;
};

Ext.extend(Ext.data.MemoryProxy, Ext.data.DataProxy, {
	/**
	* @event loadexception
	* Fires if an exception occurs in the Proxy during data loading. Note that this event is also relayed
	* through {@link Ext.data.Store}, so you can listen for it directly on any Store instance.
	* @param {Object} this
	* @param {Object} arg The callback's arg object passed to the {@link #load} function
	* @param {Object} null This parameter does not apply and will always be null for MemoryProxy
	* @param {Error} e The JavaScript Error object caught if the configured Reader could not read the data
	*/

	/**
	* MemoryProxy implementation of DataProxy#doRequest
	* @param {String} action
	* @param {Ext.data.Record/Ext.data.Record[]} rs If action is load, rs will be null
	* @param {Object} params An object containing properties which are to be used as HTTP parameters
	* for the request to the remote server.
	* @param {Ext.data.DataReader} reader The Reader object which converts the data
	* object into a block of Ext.data.Records.
	* @param {Function} callback The function into which to pass the block of Ext.data.Records.
	* The function must be passed <ul>
	* <li>The Record block object</li>
	* <li>The "arg" argument from the load function</li>
	* <li>A boolean success indicator</li>
	* </ul>
	* @param {Object} scope The scope (<code>this</code> reference) in which the callback function is executed. Defaults to the browser window.
	* @param {Object} arg An optional argument which is passed to the callback as its second parameter.
	*/
	doRequest: function (action, rs, params, reader, callback, scope, arg) {
		// No implementation for CRUD in MemoryProxy.  Assumes all actions are 'load'
		params = params || {};
		var result;
		try {
			result = reader.readRecords(this.data);
		} catch (e) {
			// @deprecated loadexception
			this.fireEvent("loadexception", this, null, arg, e);

			this.fireEvent('exception', this, 'response', action, arg, null, e);
			callback.call(scope, null, arg, false);
			return;
		}
		callback.call(scope, result, arg, true);
	}
}); /**
 * @class Ext.data.Types
 * <p>This is s static class containing the system-supplied data types which may be given to a {@link Ext.data.Field Field}.<p/>
 * <p>The properties in this class are used as type indicators in the {@link Ext.data.Field Field} class, so to
 * test whether a Field is of a certain type, compare the {@link Ext.data.Field#type type} property against properties
 * of this class.</p>
 * <p>Developers may add their own application-specific data types to this class. Definition names must be UPPERCASE.
 * each type definition must contain three properties:</p>
 * <div class="mdetail-params"><ul>
 * <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
 * to be stored in the Field. The function is passed the collowing parameters:
 * <div class="mdetail-params"><ul>
 * <li><b>v</b> : Mixed<div class="sub-desc">The data value as read by the Reader, if undefined will use
 * the configured <tt>{@link Ext.data.Field#defaultValue defaultValue}</tt>.</div></li>
 * <li><b>rec</b> : Mixed<div class="sub-desc">The data object containing the row as read by the Reader.
 * Depending on the Reader type, this could be an Array ({@link Ext.data.ArrayReader ArrayReader}), an object
 * ({@link Ext.data.JsonReader JsonReader}), or an XML element ({@link Ext.data.XMLReader XMLReader}).</div></li>
 * </ul></div></div></li>
 * <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>
 * <li><code>type</code> : <i>String</i> <div class="sub-desc">A textual data type name.</div></li>
 * </ul></div>
 * <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
 * which contained the properties <code>lat</code> and <code>long</code>, you would define a new data type like this:</p>
 *<pre><code>
// Add a new Field data type which stores a VELatLong object in the Record.
Ext.data.Types.VELATLONG = {
    convert: function(v, data) {
        return new VELatLong(data.lat, data.long);
    },
    sortType: function(v) {
        return v.Latitude;  // When sorting, order by latitude
    },
    type: 'VELatLong'
};
</code></pre>
 * <p>Then, when declaring a Record, use <pre><code>
var types = Ext.data.Types; // allow shorthand type access
UnitRecord = Ext.data.Record.create([
    { name: 'unitName', mapping: 'UnitName' },
    { name: 'curSpeed', mapping: 'CurSpeed', type: types.INT },
    { name: 'latitude', mapping: 'lat', type: types.FLOAT },
    { name: 'latitude', mapping: 'lat', type: types.FLOAT },
    { name: 'position', type: types.VELATLONG }
]);
</code></pre>
 * @singleton
 */
Ext.data.Types = new function () {
	var st = Ext.data.SortTypes;
	Ext.apply(this, {
		/**
		* @type Regexp
		* @property stripRe
		* A regular expression for stripping non-numeric characters from a numeric value. Defaults to <tt>/[\$,%]/g</tt>.
		* This should be overridden for localization.
		*/
		stripRe: /[\$,%]/g,

		/**
		* @type Object.
		* @property AUTO
		* This data type means that no conversion is applied to the raw data before it is placed into a Record.
		*/
		AUTO: {
			convert: function (v) { return v; },
			sortType: st.none,
			type: 'auto'
		},

		/**
		* @type Object.
		* @property STRING
		* This data type means that the raw data is converted into a String before it is placed into a Record.
		*/
		STRING: {
			convert: function (v) { return (v === undefined || v === null) ? '' : String(v); },
			sortType: st.asUCString,
			type: 'string'
		},

		/**
		* @type Object.
		* @property INT
		* This data type means that the raw data is converted into an integer before it is placed into a Record.
		* <p>The synonym <code>INTEGER</code> is equivalent.</p>
		*/
		INT: {
			convert: function (v) {
				return v !== undefined && v !== null && v !== '' ?
                    parseInt(String(v).replace(Ext.data.Types.stripRe, ''), 10) : 0;
			},
			sortType: st.none,
			type: 'int'
		},

		/**
		* @type Object.
		* @property FLOAT
		* This data type means that the raw data is converted into a number before it is placed into a Record.
		* <p>The synonym <code>NUMBER</code> is equivalent.</p>
		*/
		FLOAT: {
			convert: function (v) {
				return v !== undefined && v !== null && v !== '' ?
                    parseFloat(String(v).replace(Ext.data.Types.stripRe, ''), 10) : 0;
			},
			sortType: st.none,
			type: 'float'
		},

		/**
		* @type Object.
		* @property BOOL
		* <p>This data type means that the raw data is converted into a boolean before it is placed into
		* a Record. The string "true" and the number 1 are converted to boolean <code>true</code>.</p>
		* <p>The synonym <code>BOOLEAN</code> is equivalent.</p>
		*/
		BOOL: {
			convert: function (v) { return v === true || v === 'true' || v == 1; },
			sortType: st.none,
			type: 'bool'
		},

		/**
		* @type Object.
		* @property DATE
		* This data type means that the raw data is converted into a Date before it is placed into a Record.
		* The date format is specified in the constructor of the {@link Ext.data.Field} to which this type is
		* being applied.
		*/
		DATE: {
			convert: function (v) {
				var df = this.dateFormat;
				if (!v) {
					return null;
				}
				if (Ext.isDate(v)) {
					return v;
				}
				if (df) {
					if (df == 'timestamp') {
						return new Date(v * 1000);
					}
					if (df == 'time') {
						return new Date(parseInt(v, 10));
					}
					return Date.parseDate(v, df);
				}
				var parsed = Date.parse(v);
				return parsed ? new Date(parsed) : null;
			},
			sortType: st.asDate,
			type: 'date'
		}
	});

	Ext.apply(this, {
		/**
		* @type Object.
		* @property BOOLEAN
		* <p>This data type means that the raw data is converted into a boolean before it is placed into
		* a Record. The string "true" and the number 1 are converted to boolean <code>true</code>.</p>
		* <p>The synonym <code>BOOL</code> is equivalent.</p>
		*/
		BOOLEAN: this.BOOL,
		/**
		* @type Object.
		* @property INTEGER
		* This data type means that the raw data is converted into an integer before it is placed into a Record.
		* <p>The synonym <code>INT</code> is equivalent.</p>
		*/
		INTEGER: this.INT,
		/**
		* @type Object.
		* @property NUMBER
		* This data type means that the raw data is converted into a number before it is placed into a Record.
		* <p>The synonym <code>FLOAT</code> is equivalent.</p>
		*/
		NUMBER: this.FLOAT
	});
}; /**
 * @class Ext.data.JsonWriter
 * @extends Ext.data.DataWriter
 * DataWriter extension for writing an array or single {@link Ext.data.Record} object(s) in preparation for executing a remote CRUD action.
 */
Ext.data.JsonWriter = Ext.extend(Ext.data.DataWriter, {
	/**
	* @cfg {Boolean} encode <tt>true</tt> to {@link Ext.util.JSON#encode encode} the
	* {@link Ext.data.DataWriter#toHash hashed data}. Defaults to <tt>true</tt>.  When using
	* {@link Ext.data.DirectProxy}, set this to <tt>false</tt> since Ext.Direct.JsonProvider will perform
	* its own json-encoding.  In addition, if you're using {@link Ext.data.HttpProxy}, setting to <tt>false</tt>
	* will cause HttpProxy to transmit data using the <b>jsonData</b> configuration-params of {@link Ext.Ajax#request}
	* instead of <b>params</b>.  When using a {@link Ext.data.Store#restful} Store, some serverside frameworks are
	* tuned to expect data through the jsonData mechanism.  In those cases, one will want to set <b>encode: <tt>false</tt></b>, as in
	* let the lower-level connection object (eg: Ext.Ajax) do the encoding.
	*/
	encode: true,
	/**
	* @cfg {Boolean} encodeDelete False to send only the id to the server on delete, true to encode it in an object
	* literal, eg: <pre><code>
	{id: 1}
	* </code></pre> Defaults to <tt>false</tt>
	*/
	encodeDelete: false,

	constructor: function (config) {
		Ext.data.JsonWriter.superclass.constructor.call(this, config);
	},

	/**
	* Final action of a write event.  Apply the written data-object to params.
	* @param {Object} http params-object to write-to.
	* @param {Object} baseParams as defined by {@link Ext.data.Store#baseParams}.  The baseParms must be encoded by the extending class, eg: {@link Ext.data.JsonWriter}, {@link Ext.data.XmlWriter}.
	* @param {Object/Object[]} data Data-object representing compiled Store-recordset.
	*/
	render: function (params, baseParams, data) {
		if (this.encode === true) {
			// Encode here now.
			Ext.apply(params, baseParams);
			params[this.meta.root] = Ext.encode(data);
		} else {
			// defer encoding for some other layer, probably in {@link Ext.Ajax#request}.  Place everything into "jsonData" key.
			var jdata = Ext.apply({}, baseParams);
			jdata[this.meta.root] = data;
			params.jsonData = jdata;
		}
	},
	/**
	* Implements abstract Ext.data.DataWriter#createRecord
	* @protected
	* @param {Ext.data.Record} rec
	* @return {Object}
	*/
	createRecord: function (rec) {
		return this.toHash(rec);
	},
	/**
	* Implements abstract Ext.data.DataWriter#updateRecord
	* @protected
	* @param {Ext.data.Record} rec
	* @return {Object}
	*/
	updateRecord: function (rec) {
		return this.toHash(rec);

	},
	/**
	* Implements abstract Ext.data.DataWriter#destroyRecord
	* @protected
	* @param {Ext.data.Record} rec
	* @return {Object}
	*/
	destroyRecord: function (rec) {
		if (this.encodeDelete) {
			var data = {};
			data[this.meta.idProperty] = rec.id;
			return data;
		} else {
			return rec.id;
		}
	}
}); /**
 * @class Ext.data.JsonReader
 * @extends Ext.data.DataReader
 * <p>Data reader class to create an Array of {@link Ext.data.Record} objects
 * from a JSON packet based on mappings in a provided {@link Ext.data.Record}
 * constructor.</p>
 * <p>Example code:</p>
 * <pre><code>
var myReader = new Ext.data.JsonReader({
    // metadata configuration options:
    {@link #idProperty}: 'id'
    {@link #root}: 'rows',
    {@link #totalProperty}: 'results',
    {@link Ext.data.DataReader#messageProperty}: "msg"  // The element within the response that provides a user-feedback message (optional)

    // the fields config option will internally create an {@link Ext.data.Record}
    // constructor that provides mapping for reading the record data objects
    {@link Ext.data.DataReader#fields fields}: [
        // map Record&#39;s 'firstname' field to data object&#39;s key of same name
        {name: 'name'},
        // map Record&#39;s 'job' field to data object&#39;s 'occupation' key
        {name: 'job', mapping: 'occupation'}
    ]
});
</code></pre>
 * <p>This would consume a JSON data object of the form:</p><pre><code>
{
    results: 2000, // Reader&#39;s configured {@link #totalProperty}
    rows: [        // Reader&#39;s configured {@link #root}
        // record data objects:
        { {@link #idProperty id}: 1, firstname: 'Bill', occupation: 'Gardener' },
        { {@link #idProperty id}: 2, firstname: 'Ben' , occupation: 'Horticulturalist' },
        ...
    ]
}
</code></pre>
 * <p><b><u>Automatic configuration using metaData</u></b></p>
 * <p>It is possible to change a JsonReader's metadata at any time by including
 * a <b><tt>metaData</tt></b> property in the JSON data object. If the JSON data
 * object has a <b><tt>metaData</tt></b> property, a {@link Ext.data.Store Store}
 * object using this Reader will reconfigure itself to use the newly provided
 * field definition and fire its {@link Ext.data.Store#metachange metachange}
 * event. The metachange event handler may interrogate the <b><tt>metaData</tt></b>
 * property to perform any configuration required.</p>
 * <p>Note that reconfiguring a Store potentially invalidates objects which may
 * refer to Fields or Records which no longer exist.</p>
 * <p>To use this facility you would create the JsonReader like this:</p><pre><code>
var myReader = new Ext.data.JsonReader();
</code></pre>
 * <p>The first data packet from the server would configure the reader by
 * containing a <b><tt>metaData</tt></b> property <b>and</b> the data. For
 * example, the JSON data object might take the form:</p><pre><code>
{
    metaData: {
        "{@link #idProperty}": "id",
        "{@link #root}": "rows",
        "{@link #totalProperty}": "results"
        "{@link #successProperty}": "success",
        "{@link Ext.data.DataReader#fields fields}": [
            {"name": "name"},
            {"name": "job", "mapping": "occupation"}
        ],
        // used by store to set its sortInfo
        "sortInfo":{
           "field": "name",
           "direction": "ASC"
        },
        // {@link Ext.PagingToolbar paging data} (if applicable)
        "start": 0,
        "limit": 2,
        // custom property
        "foo": "bar"
    },
    // Reader&#39;s configured {@link #successProperty}
    "success": true,
    // Reader&#39;s configured {@link #totalProperty}
    "results": 2000,
    // Reader&#39;s configured {@link #root}
    // (this data simulates 2 results {@link Ext.PagingToolbar per page})
    "rows": [ // <b>*Note:</b> this must be an Array
        { "id": 1, "name": "Bill", "occupation": "Gardener" },
        { "id": 2, "name":  "Ben", "occupation": "Horticulturalist" }
    ]
}
 * </code></pre>
 * <p>The <b><tt>metaData</tt></b> property in the JSON data object should contain:</p>
 * <div class="mdetail-params"><ul>
 * <li>any of the configuration options for this class</li>
 * <li>a <b><tt>{@link Ext.data.Record#fields fields}</tt></b> property which
 * the JsonReader will use as an argument to the
 * {@link Ext.data.Record#create data Record create method} in order to
 * configure the layout of the Records it will produce.</li>
 * <li>a <b><tt>{@link Ext.data.Store#sortInfo sortInfo}</tt></b> property
 * which the JsonReader will use to set the {@link Ext.data.Store}'s
 * {@link Ext.data.Store#sortInfo sortInfo} property</li>
 * <li>any custom properties needed</li>
 * </ul></div>
 *
 * @constructor
 * Create a new JsonReader
 * @param {Object} meta Metadata configuration options.
 * @param {Array/Object} recordType
 * <p>Either an Array of {@link Ext.data.Field Field} definition objects (which
 * will be passed to {@link Ext.data.Record#create}, or a {@link Ext.data.Record Record}
 * constructor created from {@link Ext.data.Record#create}.</p>
 */
Ext.data.JsonReader = function (meta, recordType) {
	meta = meta || {};
	/**
	* @cfg {String} idProperty [id] Name of the property within a row object
	* that contains a record identifier value.  Defaults to <tt>id</tt>
	*/
	/**
	* @cfg {String} successProperty [success] Name of the property from which to
	* retrieve the success attribute. Defaults to <tt>success</tt>.  See
	* {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#exception exception}
	* for additional information.
	*/
	/**
	* @cfg {String} totalProperty [total] Name of the property from which to
	* retrieve the total number of records in the dataset. This is only needed
	* if the whole dataset is not passed in one go, but is being paged from
	* the remote server.  Defaults to <tt>total</tt>.
	*/
	/**
	* @cfg {String} root [undefined] <b>Required</b>.  The name of the property
	* which contains the Array of row objects.  Defaults to <tt>undefined</tt>.
	* An exception will be thrown if the root property is undefined. The data
	* packet value for this property should be an empty array to clear the data
	* or show no data.
	*/
	Ext.applyIf(meta, {
		idProperty: 'id',
		successProperty: 'success',
		totalProperty: 'total'
	});

	Ext.data.JsonReader.superclass.constructor.call(this, meta, recordType || meta.fields);
};
Ext.extend(Ext.data.JsonReader, Ext.data.DataReader, {
	/**
	* This JsonReader's metadata as passed to the constructor, or as passed in
	* the last data packet's <b><tt>metaData</tt></b> property.
	* @type Mixed
	* @property meta
	*/
	/**
	* This method is only used by a DataProxy which has retrieved data from a remote server.
	* @param {Object} response The XHR object which contains the JSON data in its responseText.
	* @return {Object} data A data block which is used by an Ext.data.Store object as
	* a cache of Ext.data.Records.
	*/
	read: function (response) {
		var json = response.responseText;
		var o = Ext.decode(json);
		if (!o) {
			throw { message: 'JsonReader.read: Json object not found' };
		}
		return this.readRecords(o);
	},

	/*
	* TODO: refactor code between JsonReader#readRecords, #readResponse into 1 method.
	* there's ugly duplication going on due to maintaining backwards compat. with 2.0.  It's time to do this.
	*/
	/**
	* Decode a JSON response from server.
	* @param {String} action [Ext.data.Api.actions.create|read|update|destroy]
	* @param {Object} response The XHR object returned through an Ajax server request.
	* @return {Response} A {@link Ext.data.Response Response} object containing the data response, and also status information.
	*/
	readResponse: function (action, response) {
		var o = (response.responseText !== undefined) ? Ext.decode(response.responseText) : response;
		if (!o) {
			throw new Ext.data.JsonReader.Error('response');
		}

		var root = this.getRoot(o);
		if (action === Ext.data.Api.actions.create) {
			var def = Ext.isDefined(root);
			if (def && Ext.isEmpty(root)) {
				throw new Ext.data.JsonReader.Error('root-empty', this.meta.root);
			}
			else if (!def) {
				throw new Ext.data.JsonReader.Error('root-undefined-response', this.meta.root);
			}
		}

		// instantiate response object
		var res = new Ext.data.Response({
			action: action,
			success: this.getSuccess(o),
			data: (root) ? this.extractData(root, false) : [],
			message: this.getMessage(o),
			raw: o
		});

		// blow up if no successProperty
		if (Ext.isEmpty(res.success)) {
			throw new Ext.data.JsonReader.Error('successProperty-response', this.meta.successProperty);
		}
		return res;
	},

	/**
	* Create a data block containing Ext.data.Records from a JSON object.
	* @param {Object} o An object which contains an Array of row objects in the property specified
	* in the config as 'root, and optionally a property, specified in the config as 'totalProperty'
	* which contains the total size of the dataset.
	* @return {Object} data A data block which is used by an Ext.data.Store object as
	* a cache of Ext.data.Records.
	*/
	readRecords: function (o) {
		/**
		* After any data loads, the raw JSON data is available for further custom processing.  If no data is
		* loaded or there is a load exception this property will be undefined.
		* @type Object
		*/
		this.jsonData = o;
		if (o.metaData) {
			this.onMetaChange(o.metaData);
		}
		var s = this.meta, Record = this.recordType,
            f = Record.prototype.fields, fi = f.items, fl = f.length, v;

		var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
		if (s.totalProperty) {
			v = parseInt(this.getTotal(o), 10);
			if (!isNaN(v)) {
				totalRecords = v;
			}
		}
		if (s.successProperty) {
			v = this.getSuccess(o);
			if (v === false || v === 'false') {
				success = false;
			}
		}

		// TODO return Ext.data.Response instance instead.  @see #readResponse
		return {
			success: success,
			records: this.extractData(root, true), // <-- true to return [Ext.data.Record]
			totalRecords: totalRecords
		};
	},

	// private
	buildExtractors: function () {
		if (this.ef) {
			return;
		}
		var s = this.meta, Record = this.recordType,
            f = Record.prototype.fields, fi = f.items, fl = f.length;

		if (s.totalProperty) {
			this.getTotal = this.createAccessor(s.totalProperty);
		}
		if (s.successProperty) {
			this.getSuccess = this.createAccessor(s.successProperty);
		}
		if (s.messageProperty) {
			this.getMessage = this.createAccessor(s.messageProperty);
		}
		this.getRoot = s.root ? this.createAccessor(s.root) : function (p) { return p; };
		if (s.id || s.idProperty) {
			var g = this.createAccessor(s.id || s.idProperty);
			this.getId = function (rec) {
				var r = g(rec);
				return (r === undefined || r === '') ? null : r;
			};
		} else {
			this.getId = function () { return null; };
		}
		var ef = [];
		for (var i = 0; i < fl; i++) {
			f = fi[i];
			var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
			ef.push(this.createAccessor(map));
		}
		this.ef = ef;
	},

	/**
	* @ignore
	* TODO This isn't used anywhere??  Don't we want to use this where possible instead of complex #createAccessor?
	*/
	simpleAccess: function (obj, subsc) {
		return obj[subsc];
	},

	/**
	* @ignore
	*/
	createAccessor: function () {
		var re = /[\[\.]/;
		return function (expr) {
			if (Ext.isEmpty(expr)) {
				return Ext.emptyFn;
			}
			if (Ext.isFunction(expr)) {
				return expr;
			}
			var i = String(expr).search(re);
			if (i >= 0) {
				return new Function('obj', 'return obj' + (i > 0 ? '.' : '') + expr);
			}
			return function (obj) {
				return obj[expr];
			};

		};
	} (),

	/**
	* type-casts a single row of raw-data from server
	* @param {Object} data
	* @param {Array} items
	* @param {Integer} len
	* @private
	*/
	extractValues: function (data, items, len) {
		var f, values = {};
		for (var j = 0; j < len; j++) {
			f = items[j];
			var v = this.ef[j](data);
			values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue, data);
		}
		return values;
	}
});

/**
* @class Ext.data.JsonReader.Error
* Error class for JsonReader
*/
Ext.data.JsonReader.Error = Ext.extend(Ext.Error, {
	constructor: function (message, arg) {
		this.arg = arg;
		Ext.Error.call(this, message);
	},
	name: 'Ext.data.JsonReader'
});
Ext.apply(Ext.data.JsonReader.Error.prototype, {
	lang: {
		'response': 'An error occurred while json-decoding your server response',
		'successProperty-response': 'Could not locate your "successProperty" in your server response.  Please review your JsonReader config to ensure the config-property "successProperty" matches the property in your server-response.  See the JsonReader docs.',
		'root-undefined-config': 'Your JsonReader was configured without a "root" property.  Please review your JsonReader config and make sure to define the root property.  See the JsonReader docs.',
		'idProperty-undefined': 'Your JsonReader was configured without an "idProperty"  Please review your JsonReader configuration and ensure the "idProperty" is set (e.g.: "id").  See the JsonReader docs.',
		'root-empty': 'Data was expected to be returned by the server in the "root" property of the response.  Please review your JsonReader configuration to ensure the "root" property matches that returned in the server-response.  See JsonReader docs.'
	}
});
/**
* @class Ext.data.ArrayReader
* @extends Ext.data.JsonReader
* <p>Data reader class to create an Array of {@link Ext.data.Record} objects from an Array.
* Each element of that Array represents a row of data fields. The
* fields are pulled into a Record object using as a subscript, the <code>mapping</code> property
* of the field definition if it exists, or the field's ordinal position in the definition.</p>
* <p>Example code:</p>
* <pre><code>
var Employee = Ext.data.Record.create([
{name: 'name', mapping: 1},         // "mapping" only needed if an "id" field is present which
{name: 'occupation', mapping: 2}    // precludes using the ordinal position as the index.
]);
var myReader = new Ext.data.ArrayReader({
{@link #idIndex}: 0
}, Employee);
</code></pre>
* <p>This would consume an Array like this:</p>
* <pre><code>
[ [1, 'Bill', 'Gardener'], [2, 'Ben', 'Horticulturalist'] ]
* </code></pre>
* @constructor
* Create a new ArrayReader
* @param {Object} meta Metadata configuration options.
* @param {Array/Object} recordType
* <p>Either an Array of {@link Ext.data.Field Field} definition objects (which
* will be passed to {@link Ext.data.Record#create}, or a {@link Ext.data.Record Record}
* constructor created from {@link Ext.data.Record#create}.</p>
*/
Ext.data.ArrayReader = Ext.extend(Ext.data.JsonReader, {
	/**
	* @cfg {String} successProperty
	* @hide
	*/
	/**
	* @cfg {Number} id (optional) The subscript within row Array that provides an ID for the Record.
	* Deprecated. Use {@link #idIndex} instead.
	*/
	/**
	* @cfg {Number} idIndex (optional) The subscript within row Array that provides an ID for the Record.
	*/
	/**
	* Create a data block containing Ext.data.Records from an Array.
	* @param {Object} o An Array of row objects which represents the dataset.
	* @return {Object} data A data block which is used by an Ext.data.Store object as
	* a cache of Ext.data.Records.
	*/
	readRecords: function (o) {
		this.arrayData = o;
		var s = this.meta,
            sid = s ? Ext.num(s.idIndex, s.id) : null,
            recordType = this.recordType,
            fields = recordType.prototype.fields,
            records = [],
            success = true,
            v;

		var root = this.getRoot(o);

		for (var i = 0, len = root.length; i < len; i++) {
			var n = root[i],
                values = {},
                id = ((sid || sid === 0) && n[sid] !== undefined && n[sid] !== "" ? n[sid] : null);
			for (var j = 0, jlen = fields.length; j < jlen; j++) {
				var f = fields.items[j],
                    k = f.mapping !== undefined && f.mapping !== null ? f.mapping : j;
				v = n[k] !== undefined ? n[k] : f.defaultValue;
				v = f.convert(v, n);
				values[f.name] = v;
			}
			var record = new recordType(values, id);
			record.json = n;
			records[records.length] = record;
		}

		var totalRecords = records.length;

		if (s.totalProperty) {
			v = parseInt(this.getTotal(o), 10);
			if (!isNaN(v)) {
				totalRecords = v;
			}
		}
		if (s.successProperty) {
			v = this.getSuccess(o);
			if (v === false || v === 'false') {
				success = false;
			}
		}

		return {
			success: success,
			records: records,
			totalRecords: totalRecords
		};
	}
}); /**
 * @class Ext.data.ArrayStore
 * @extends Ext.data.Store
 * <p>Formerly known as "SimpleStore".</p>
 * <p>Small helper class to make creating {@link Ext.data.Store}s from Array data easier.
 * An ArrayStore will be automatically configured with a {@link Ext.data.ArrayReader}.</p>
 * <p>A store configuration would be something like:<pre><code>
var store = new Ext.data.ArrayStore({
    // store configs
    autoDestroy: true,
    storeId: 'myStore',
    // reader configs
    idIndex: 0,  
    fields: [
       'company',
       {name: 'price', type: 'float'},
       {name: 'change', type: 'float'},
       {name: 'pctChange', type: 'float'},
       {name: 'lastChange', type: 'date', dateFormat: 'n/j h:ia'}
    ]
});
 * </code></pre></p>
 * <p>This store is configured to consume a returned object of the form:<pre><code>
var myData = [
    ['3m Co',71.72,0.02,0.03,'9/1 12:00am'],
    ['Alcoa Inc',29.01,0.42,1.47,'9/1 12:00am'],
    ['Boeing Co.',75.43,0.53,0.71,'9/1 12:00am'],
    ['Hewlett-Packard Co.',36.53,-0.03,-0.08,'9/1 12:00am'],
    ['Wal-Mart Stores, Inc.',45.45,0.73,1.63,'9/1 12:00am']
];
 * </code></pre>
 * An object literal of this form could also be used as the {@link #data} config option.</p>
 * <p><b>*Note:</b> Although not listed here, this class accepts all of the configuration options of 
 * <b>{@link Ext.data.ArrayReader ArrayReader}</b>.</p>
 * @constructor
 * @param {Object} config
 * @xtype arraystore
 */
Ext.data.ArrayStore = Ext.extend(Ext.data.Store, {
	/**
	* @cfg {Ext.data.DataReader} reader @hide
	*/
	constructor: function (config) {
		Ext.data.ArrayStore.superclass.constructor.call(this, Ext.apply(config, {
			reader: new Ext.data.ArrayReader(config)
		}));
	},

	loadData: function (data, append) {
		if (this.expandData === true) {
			var r = [];
			for (var i = 0, len = data.length; i < len; i++) {
				r[r.length] = [data[i]];
			}
			data = r;
		}
		Ext.data.ArrayStore.superclass.loadData.call(this, data, append);
	}
});
Ext.reg('arraystore', Ext.data.ArrayStore);

// backwards compat
Ext.data.SimpleStore = Ext.data.ArrayStore;
Ext.reg('simplestore', Ext.data.SimpleStore); /**
 * @class Ext.data.JsonStore
 * @extends Ext.data.Store
 * <p>Small helper class to make creating {@link Ext.data.Store}s from JSON data easier.
 * A JsonStore will be automatically configured with a {@link Ext.data.JsonReader}.</p>
 * <p>A store configuration would be something like:<pre><code>
var store = new Ext.data.JsonStore({
    // store configs
    autoDestroy: true,
    url: 'get-images.php',
    storeId: 'myStore',
    // reader configs
    root: 'images',
    idProperty: 'name',
    fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date'}]
});
 * </code></pre></p>
 * <p>This store is configured to consume a returned object of the form:<pre><code>
{
    images: [
        {name: 'Image one', url:'/GetImage.php?id=1', size:46.5, lastmod: new Date(2007, 10, 29)},
        {name: 'Image Two', url:'/GetImage.php?id=2', size:43.2, lastmod: new Date(2007, 10, 30)}
    ]
}
 * </code></pre>
 * An object literal of this form could also be used as the {@link #data} config option.</p>
 * <p><b>*Note:</b> Although not listed here, this class accepts all of the configuration options of
 * <b>{@link Ext.data.JsonReader JsonReader}</b>.</p>
 * @constructor
 * @param {Object} config
 * @xtype jsonstore
 */
Ext.data.JsonStore = Ext.extend(Ext.data.Store, {
	/**
	* @cfg {Ext.data.DataReader} reader @hide
	*/
	constructor: function (config) {
		Ext.data.JsonStore.superclass.constructor.call(this, Ext.apply(config, {
			reader: new Ext.data.JsonReader(config)
		}));
	}
});
Ext.reg('jsonstore', Ext.data.JsonStore); /**
 * @class Ext.data.XmlWriter
 * @extends Ext.data.DataWriter
 * DataWriter extension for writing an array or single {@link Ext.data.Record} object(s) in preparation for executing a remote CRUD action via XML.
 * XmlWriter uses an instance of {@link Ext.XTemplate} for maximum flexibility in defining your own custom XML schema if the default schema is not appropriate for your needs.
 * See the {@link #tpl} configuration-property.
 */
Ext.data.XmlWriter = function (params) {
	Ext.data.XmlWriter.superclass.constructor.apply(this, arguments);
	// compile the XTemplate for rendering XML documents.
	this.tpl = (typeof (this.tpl) === 'string') ? new Ext.XTemplate(this.tpl).compile() : this.tpl.compile();
};
Ext.extend(Ext.data.XmlWriter, Ext.data.DataWriter, {
	/**
	* @cfg {String} documentRoot [xrequest] (Optional) The name of the XML document root-node.  <b>Note:</b>
	* this parameter is required </b>only when</b> sending extra {@link Ext.data.Store#baseParams baseParams} to the server
	* during a write-request -- if no baseParams are set, the {@link Ext.data.XmlReader#record} meta-property can
	* suffice as the XML document root-node for write-actions involving just a <b>single record</b>.  For requests
	* involving <b>multiple</b> records and <b>NO</b> baseParams, the {@link Ext.data.XmlWriter#root} property can
	* act as the XML document root.
	*/
	documentRoot: 'xrequest',
	/**
	* @cfg {Boolean} forceDocumentRoot [false] Set to <tt>true</tt> to force XML documents having a root-node as defined
	* by {@link #documentRoot}, even with no baseParams defined.
	*/
	forceDocumentRoot: false,
	/**
	* @cfg {String} root [records] The name of the containing element which will contain the nodes of an write-action involving <b>multiple</b> records.  Each
	* xml-record written to the server will be wrapped in an element named after {@link Ext.data.XmlReader#record} property.
	* eg:
	<code><pre>
	&lt;?xml version="1.0" encoding="UTF-8"?>
	&lt;user>&lt;first>Barney&lt;/first>&lt;/user>
	</code></pre>
	* However, when <b>multiple</b> records are written in a batch-operation, these records must be wrapped in a containing
	* Element.
	* eg:
	<code><pre>
	&lt;?xml version="1.0" encoding="UTF-8"?>
	&lt;records>
	&lt;first>Barney&lt;/first>&lt;/user>
	&lt;records>&lt;first>Barney&lt;/first>&lt;/user>
	&lt;/records>
	</code></pre>
	* Defaults to <tt>records</tt>.  Do not confuse the nature of this property with that of {@link #documentRoot}
	*/
	root: 'records',
	/**
	* @cfg {String} xmlVersion [1.0] The <tt>version</tt> written to header of xml documents.
	<code><pre>&lt;?xml version="1.0" encoding="ISO-8859-15"?></pre></code>
	*/
	xmlVersion: '1.0',
	/**
	* @cfg {String} xmlEncoding [ISO-8859-15] The <tt>encoding</tt> written to header of xml documents.
	<code><pre>&lt;?xml version="1.0" encoding="ISO-8859-15"?></pre></code>
	*/
	xmlEncoding: 'ISO-8859-15',
	/**
	* @cfg {String/Ext.XTemplate} tpl The XML template used to render {@link Ext.data.Api#actions write-actions} to your server.
	* <p>One can easily provide his/her own custom {@link Ext.XTemplate#constructor template-definition} if the default does not suffice.</p>
	* <p>Defaults to:</p>
	<code><pre>
	&lt;?xml version="{version}" encoding="{encoding}"?>
	&lt;tpl if="documentRoot">&lt;{documentRoot}>
	&lt;tpl for="baseParams">
	&lt;tpl for=".">
	&lt;{name}>{value}&lt;/{name}>
	&lt;/tpl>
	&lt;/tpl>
	&lt;tpl if="records.length &gt; 1">&lt;{root}>',
	&lt;tpl for="records">
	&lt;{parent.record}>
	&lt;tpl for=".">
	&lt;{name}>{value}&lt;/{name}>
	&lt;/tpl>
	&lt;/{parent.record}>
	&lt;/tpl>
	&lt;tpl if="records.length &gt; 1">&lt;/{root}>&lt;/tpl>
	&lt;tpl if="documentRoot">&lt;/{documentRoot}>&lt;/tpl>
	</pre></code>
	* <p>Templates will be called with the following API</p>
	* <ul>
	* <li>{String} version [1.0] The xml version.</li>
	* <li>{String} encoding [ISO-8859-15] The xml encoding.</li>
	* <li>{String/false} documentRoot The XML document root-node name or <tt>false</tt> if not required.  See {@link #documentRoot} and {@link #forceDocumentRoot}.</li>
	* <li>{String} record The meta-data parameter defined on your {@link Ext.data.XmlReader#record} configuration represents the name of the xml-tag containing each record.</li>
	* <li>{String} root The meta-data parameter defined by {@link Ext.data.XmlWriter#root} configuration-parameter.  Represents the name of the xml root-tag when sending <b>multiple</b> records to the server.</li>
	* <li>{Array} records The records being sent to the server, ie: the subject of the write-action being performed.  The records parameter will be always be an array, even when only a single record is being acted upon.
	*     Each item within the records array will contain an array of field objects having the following properties:
	*     <ul>
	*         <li>{String} name The field-name of the record as defined by your {@link Ext.data.Record#create Ext.data.Record definition}.  The "mapping" property will be used, otherwise it will match the "name" property.  Use this parameter to define the XML tag-name of the property.</li>
	*         <li>{Mixed} value The record value of the field enclosed within XML tags specified by name property above.</li>
	*     </ul></li>
	* <li>{Array} baseParams.  The baseParams as defined upon {@link Ext.data.Store#baseParams}.  Note that the baseParams have been converted into an array of [{name : "foo", value: "bar"}, ...] pairs in the same manner as the <b>records</b> parameter above.  See {@link #documentRoot} and {@link #forceDocumentRoot}.</li>
	* </ul>
	*/
	// Encoding the ? here in case it's being included by some kind of page that will parse it (eg. PHP)
	tpl: '<tpl for="."><\u003fxml version="{version}" encoding="{encoding}"\u003f><tpl if="documentRoot"><{documentRoot}><tpl for="baseParams"><tpl for="."><{name}>{value}</{name}</tpl></tpl></tpl><tpl if="records.length&gt;1"><{root}></tpl><tpl for="records"><{parent.record}><tpl for="."><{name}>{value}</{name}></tpl></{parent.record}></tpl><tpl if="records.length&gt;1"></{root}></tpl><tpl if="documentRoot"></{documentRoot}></tpl></tpl>',


	/**
	* XmlWriter implementation of the final stage of a write action.
	* @param {Object} params Transport-proxy's (eg: {@link Ext.Ajax#request}) params-object to write-to.
	* @param {Object} baseParams as defined by {@link Ext.data.Store#baseParams}.  The baseParms must be encoded by the extending class, eg: {@link Ext.data.JsonWriter}, {@link Ext.data.XmlWriter}.
	* @param {Object/Object[]} data Data-object representing the compiled Store-recordset.
	*/
	render: function (params, baseParams, data) {
		baseParams = this.toArray(baseParams);
		params.xmlData = this.tpl.applyTemplate({
			version: this.xmlVersion,
			encoding: this.xmlEncoding,
			documentRoot: (baseParams.length > 0 || this.forceDocumentRoot === true) ? this.documentRoot : false,
			record: this.meta.record,
			root: this.root,
			baseParams: baseParams,
			records: (Ext.isArray(data[0])) ? data : [data]
		});
	},

	/**
	* createRecord
	* @protected
	* @param {Ext.data.Record} rec
	* @return {Array} Array of <tt>name:value</tt> pairs for attributes of the {@link Ext.data.Record}.  See {@link Ext.data.DataWriter#toHash}.
	*/
	createRecord: function (rec) {
		return this.toArray(this.toHash(rec));
	},

	/**
	* updateRecord
	* @protected
	* @param {Ext.data.Record} rec
	* @return {Array} Array of {name:value} pairs for attributes of the {@link Ext.data.Record}.  See {@link Ext.data.DataWriter#toHash}.
	*/
	updateRecord: function (rec) {
		return this.toArray(this.toHash(rec));

	},
	/**
	* destroyRecord
	* @protected
	* @param {Ext.data.Record} rec
	* @return {Array} Array containing a attribute-object (name/value pair) representing the {@link Ext.data.DataReader#idProperty idProperty}.
	*/
	destroyRecord: function (rec) {
		var data = {};
		data[this.meta.idProperty] = rec.id;
		return this.toArray(data);
	}
});
/**
* @class Ext.data.XmlReader
* @extends Ext.data.DataReader
* <p>Data reader class to create an Array of {@link Ext.data.Record} objects from an XML document
* based on mappings in a provided {@link Ext.data.Record} constructor.</p>
* <p><b>Note</b>: that in order for the browser to parse a returned XML document, the Content-Type
* header in the HTTP response must be set to "text/xml" or "application/xml".</p>
* <p>Example code:</p>
* <pre><code>
var Employee = Ext.data.Record.create([
{name: 'name', mapping: 'name'},     // "mapping" property not needed if it is the same as "name"
{name: 'occupation'}                 // This field will use "occupation" as the mapping.
]);
var myReader = new Ext.data.XmlReader({
totalProperty: "results", // The element which contains the total dataset size (optional)
record: "row",           // The repeated element which contains row information
idProperty: "id"         // The element within the row that provides an ID for the record (optional)
messageProperty: "msg"   // The element within the response that provides a user-feedback message (optional)
}, Employee);
</code></pre>
* <p>
* This would consume an XML file like this:
* <pre><code>
&lt;?xml version="1.0" encoding="UTF-8"?>
&lt;dataset>
&lt;results>2&lt;/results>
&lt;row>
&lt;id>1&lt;/id>
&lt;name>Bill&lt;/name>
&lt;occupation>Gardener&lt;/occupation>
&lt;/row>
&lt;row>
&lt;id>2&lt;/id>
&lt;name>Ben&lt;/name>
&lt;occupation>Horticulturalist&lt;/occupation>
&lt;/row>
&lt;/dataset>
</code></pre>
* @cfg {String} totalProperty The DomQuery path from which to retrieve the total number of records
* in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
* paged from the remote server.
* @cfg {String} record The DomQuery path to the repeated element which contains record information.
* @cfg {String} record The DomQuery path to the repeated element which contains record information.
* @cfg {String} successProperty The DomQuery path to the success attribute used by forms.
* @cfg {String} idPath The DomQuery path relative from the record element to the element that contains
* a record identifier value.
* @constructor
* Create a new XmlReader.
* @param {Object} meta Metadata configuration options
* @param {Object} recordType Either an Array of field definition objects as passed to
* {@link Ext.data.Record#create}, or a Record constructor object created using {@link Ext.data.Record#create}.
*/
Ext.data.XmlReader = function (meta, recordType) {
	meta = meta || {};

	// backwards compat, convert idPath or id / success
	Ext.applyIf(meta, {
		idProperty: meta.idProperty || meta.idPath || meta.id,
		successProperty: meta.successProperty || meta.success
	});

	Ext.data.XmlReader.superclass.constructor.call(this, meta, recordType || meta.fields);
};
Ext.extend(Ext.data.XmlReader, Ext.data.DataReader, {
	/**
	* This method is only used by a DataProxy which has retrieved data from a remote server.
	* @param {Object} response The XHR object which contains the parsed XML document.  The response is expected
	* to contain a property called <tt>responseXML</tt> which refers to an XML document object.
	* @return {Object} records A data block which is used by an {@link Ext.data.Store} as
	* a cache of Ext.data.Records.
	*/
	read: function (response) {
		var doc = response.responseXML;
		if (!doc) {
			throw { message: "XmlReader.read: XML Document not available" };
		}
		return this.readRecords(doc);
	},

	/**
	* Create a data block containing Ext.data.Records from an XML document.
	* @param {Object} doc A parsed XML document.
	* @return {Object} records A data block which is used by an {@link Ext.data.Store} as
	* a cache of Ext.data.Records.
	*/
	readRecords: function (doc) {
		/**
		* After any data loads/reads, the raw XML Document is available for further custom processing.
		* @type XMLDocument
		*/
		this.xmlData = doc;

		var root = doc.documentElement || doc,
            q = Ext.DomQuery,
            totalRecords = 0,
            success = true;

		if (this.meta.totalProperty) {
			totalRecords = this.getTotal(root, 0);
		}
		if (this.meta.successProperty) {
			success = this.getSuccess(root);
		}

		var records = this.extractData(q.select(this.meta.record, root), true); // <-- true to return Ext.data.Record[]

		// TODO return Ext.data.Response instance.  @see #readResponse
		return {
			success: success,
			records: records,
			totalRecords: totalRecords || records.length
		};
	},

	/**
	* Decode an XML response from server.
	* @param {String} action [{@link Ext.data.Api#actions} create|read|update|destroy]
	* @param {Object} response HTTP Response object from browser.
	* @return {Ext.data.Response} An instance of {@link Ext.data.Response}
	*/
	readResponse: function (action, response) {
		var q = Ext.DomQuery,
        doc = response.responseXML;

		// create general Response instance.
		var res = new Ext.data.Response({
			action: action,
			success: this.getSuccess(doc),
			message: this.getMessage(doc),
			data: this.extractData(q.select(this.meta.record, doc) || q.select(this.meta.root, doc), false),
			raw: doc
		});

		if (Ext.isEmpty(res.success)) {
			throw new Ext.data.DataReader.Error('successProperty-response', this.meta.successProperty);
		}

		// Create actions from a response having status 200 must return pk
		if (action === Ext.data.Api.actions.create) {
			var def = Ext.isDefined(res.data);
			if (def && Ext.isEmpty(res.data)) {
				throw new Ext.data.JsonReader.Error('root-empty', this.meta.root);
			}
			else if (!def) {
				throw new Ext.data.JsonReader.Error('root-undefined-response', this.meta.root);
			}
		}
		return res;
	},

	getSuccess: function () {
		return true;
	},

	/**
	* build response-data extractor functions.
	* @private
	* @ignore
	*/
	buildExtractors: function () {
		if (this.ef) {
			return;
		}
		var s = this.meta,
            Record = this.recordType,
            f = Record.prototype.fields,
            fi = f.items,
            fl = f.length;

		if (s.totalProperty) {
			this.getTotal = this.createAccessor(s.totalProperty);
		}
		if (s.successProperty) {
			this.getSuccess = this.createAccessor(s.successProperty);
		}
		if (s.messageProperty) {
			this.getMessage = this.createAccessor(s.messageProperty);
		}
		this.getRoot = function (res) {
			return (!Ext.isEmpty(res[this.meta.record])) ? res[this.meta.record] : res[this.meta.root];
		};
		if (s.idPath || s.idProperty) {
			var g = this.createAccessor(s.idPath || s.idProperty);
			this.getId = function (rec) {
				var id = g(rec) || rec.id;
				return (id === undefined || id === '') ? null : id;
			};
		} else {
			this.getId = function () { return null; };
		}
		var ef = [];
		for (var i = 0; i < fl; i++) {
			f = fi[i];
			var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
			ef.push(this.createAccessor(map));
		}
		this.ef = ef;
	},

	/**
	* Creates a function to return some particular key of data from a response.
	* @param {String} key
	* @return {Function}
	* @private
	* @ignore
	*/
	createAccessor: function () {
		var q = Ext.DomQuery;
		return function (key) {
			switch (key) {
				case this.meta.totalProperty:
					return function (root, def) {
						return q.selectNumber(key, root, def);
					};
					break;
				case this.meta.successProperty:
					return function (root, def) {
						var sv = q.selectValue(key, root, true);
						var success = sv !== false && sv !== 'false';
						return success;
					};
					break;
				default:
					return function (root, def) {
						return q.selectValue(key, root, def);
					};
					break;
			}
		};
	} (),

	/**
	* extracts values and type-casts a row of data from server, extracted by #extractData
	* @param {Hash} data
	* @param {Ext.data.Field[]} items
	* @param {Number} len
	* @private
	* @ignore
	*/
	extractValues: function (data, items, len) {
		var f, values = {};
		for (var j = 0; j < len; j++) {
			f = items[j];
			var v = this.ef[j](data);
			values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue, data);
		}
		return values;
	}
}); /**
 * @class Ext.data.XmlStore
 * @extends Ext.data.Store
 * <p>Small helper class to make creating {@link Ext.data.Store}s from XML data easier.
 * A XmlStore will be automatically configured with a {@link Ext.data.XmlReader}.</p>
 * <p>A store configuration would be something like:<pre><code>
var store = new Ext.data.XmlStore({
    // store configs
    autoDestroy: true,
    storeId: 'myStore',
    url: 'sheldon.xml', // automatically configures a HttpProxy
    // reader configs
    record: 'Item', // records will have an "Item" tag
    idPath: 'ASIN',
    totalRecords: '@TotalResults'
    fields: [
        // set up the fields mapping into the xml doc
        // The first needs mapping, the others are very basic
        {name: 'Author', mapping: 'ItemAttributes > Author'},
        'Title', 'Manufacturer', 'ProductGroup'
    ]
});
 * </code></pre></p>
 * <p>This store is configured to consume a returned object of the form:<pre><code>
&#60?xml version="1.0" encoding="UTF-8"?>
&#60ItemSearchResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2009-05-15">
    &#60Items>
        &#60Request>
            &#60IsValid>True&#60/IsValid>
            &#60ItemSearchRequest>
                &#60Author>Sidney Sheldon&#60/Author>
                &#60SearchIndex>Books&#60/SearchIndex>
            &#60/ItemSearchRequest>
        &#60/Request>
        &#60TotalResults>203&#60/TotalResults>
        &#60TotalPages>21&#60/TotalPages>
        &#60Item>
            &#60ASIN>0446355453&#60/ASIN>
            &#60DetailPageURL>
                http://www.amazon.com/
            &#60/DetailPageURL>
            &#60ItemAttributes>
                &#60Author>Sidney Sheldon&#60/Author>
                &#60Manufacturer>Warner Books&#60/Manufacturer>
                &#60ProductGroup>Book&#60/ProductGroup>
                &#60Title>Master of the Game&#60/Title>
            &#60/ItemAttributes>
        &#60/Item>
    &#60/Items>
&#60/ItemSearchResponse>
 * </code></pre>
 * An object literal of this form could also be used as the {@link #data} config option.</p>
 * <p><b>Note:</b> Although not listed here, this class accepts all of the configuration options of 
 * <b>{@link Ext.data.XmlReader XmlReader}</b>.</p>
 * @constructor
 * @param {Object} config
 * @xtype xmlstore
 */
Ext.data.XmlStore = Ext.extend(Ext.data.Store, {
	/**
	* @cfg {Ext.data.DataReader} reader @hide
	*/
	constructor: function (config) {
		Ext.data.XmlStore.superclass.constructor.call(this, Ext.apply(config, {
			reader: new Ext.data.XmlReader(config)
		}));
	}
});
Ext.reg('xmlstore', Ext.data.XmlStore); /**
 * @class Ext.data.GroupingStore
 * @extends Ext.data.Store
 * A specialized store implementation that provides for grouping records by one of the available fields. This
 * is usually used in conjunction with an {@link Ext.grid.GroupingView} to provide the data model for
 * a grouped GridPanel.
 *
 * Internally, GroupingStore is simply a normal Store with multi sorting enabled from the start. The grouping field
 * and direction are always injected as the first sorter pair. GroupingView picks up on the configured groupField and
 * builds grid rows appropriately.
 *
 * @constructor
 * Creates a new GroupingStore.
 * @param {Object} config A config object containing the objects needed for the Store to access data,
 * and read the data into Records.
 * @xtype groupingstore
 */
Ext.data.GroupingStore = Ext.extend(Ext.data.Store, {

	//inherit docs
	constructor: function (config) {
		config = config || {};

		//We do some preprocessing here to massage the grouping + sorting options into a single
		//multi sort array. If grouping and sorting options are both presented to the constructor,
		//the sorters array consists of the grouping sorter object followed by the sorting sorter object
		//see Ext.data.Store's sorting functions for details about how multi sorting works
		this.hasMultiSort = true;
		this.multiSortInfo = this.multiSortInfo || { sorters: [] };

		var sorters = this.multiSortInfo.sorters,
            groupField = config.groupField || this.groupField,
            sortInfo = config.sortInfo || this.sortInfo,
            groupDir = config.groupDir || this.groupDir;

		//add the grouping sorter object first
		if (groupField) {
			sorters.push({
				field: groupField,
				direction: groupDir
			});
		}

		//add the sorting sorter object if it is present
		if (sortInfo) {
			sorters.push(sortInfo);
		}

		Ext.data.GroupingStore.superclass.constructor.call(this, config);

		this.addEvents(
		/**
		* @event groupchange
		* Fired whenever a call to store.groupBy successfully changes the grouping on the store
		* @param {Ext.data.GroupingStore} store The grouping store
		* @param {String} groupField The field that the store is now grouped by
		*/
          'groupchange'
        );

		this.applyGroupField();
	},

	/**
	* @cfg {String} groupField
	* The field name by which to sort the store's data (defaults to '').
	*/
	/**
	* @cfg {Boolean} remoteGroup
	* True if the grouping should apply on the server side, false if it is local only (defaults to false).  If the
	* grouping is local, it can be applied immediately to the data.  If it is remote, then it will simply act as a
	* helper, automatically sending the grouping field name as the 'groupBy' param with each XHR call.
	*/
	remoteGroup: false,
	/**
	* @cfg {Boolean} groupOnSort
	* True to sort the data on the grouping field when a grouping operation occurs, false to sort based on the
	* existing sort info (defaults to false).
	*/
	groupOnSort: false,

	groupDir: 'ASC',

	/**
	* Clears any existing grouping and refreshes the data using the default sort.
	*/
	clearGrouping: function () {
		this.groupField = false;

		if (this.remoteGroup) {
			if (this.baseParams) {
				delete this.baseParams.groupBy;
				delete this.baseParams.groupDir;
			}
			var lo = this.lastOptions;
			if (lo && lo.params) {
				delete lo.params.groupBy;
				delete lo.params.groupDir;
			}

			this.reload();
		} else {
			this.sort();
			this.fireEvent('datachanged', this);
		}
	},

	/**
	* Groups the data by the specified field.
	* @param {String} field The field name by which to sort the store's data
	* @param {Boolean} forceRegroup (optional) True to force the group to be refreshed even if the field passed
	* in is the same as the current grouping field, false to skip grouping on the same field (defaults to false)
	*/
	groupBy: function (field, forceRegroup, direction) {
		direction = direction ? (String(direction).toUpperCase() == 'DESC' ? 'DESC' : 'ASC') : this.groupDir;

		if (this.groupField == field && this.groupDir == direction && !forceRegroup) {
			return; // already grouped by this field
		}

		//check the contents of the first sorter. If the field matches the CURRENT groupField (before it is set to the new one),
		//remove the sorter as it is actually the grouper. The new grouper is added back in by this.sort
		sorters = this.multiSortInfo.sorters;
		if (sorters.length > 0 && sorters[0].field == this.groupField) {
			sorters.shift();
		}

		this.groupField = field;
		this.groupDir = direction;
		this.applyGroupField();

		var fireGroupEvent = function () {
			this.fireEvent('groupchange', this, this.getGroupState());
		};

		if (this.groupOnSort) {
			this.sort(field, direction);
			fireGroupEvent.call(this);
			return;
		}

		if (this.remoteGroup) {
			this.on('load', fireGroupEvent, this, { single: true });
			this.reload();
		} else {
			this.sort(sorters);
			fireGroupEvent.call(this);
		}
	},

	//GroupingStore always uses multisorting so we intercept calls to sort here to make sure that our grouping sorter object
	//is always injected first.
	sort: function (fieldName, dir) {
		if (this.remoteSort) {
			return Ext.data.GroupingStore.superclass.sort.call(this, fieldName, dir);
		}

		var sorters = [];

		//cater for any existing valid arguments to this.sort, massage them into an array of sorter objects
		if (Ext.isArray(arguments[0])) {
			sorters = arguments[0];
		} else if (fieldName == undefined) {
			//we preserve the existing sortInfo here because this.sort is called after
			//clearGrouping and there may be existing sorting
			sorters = this.sortInfo ? [this.sortInfo] : [];
		} else {
			//TODO: this is lifted straight from Ext.data.Store's singleSort function. It should instead be
			//refactored into a common method if possible
			var field = this.fields.get(fieldName);
			if (!field) return false;

			var name = field.name,
                sortInfo = this.sortInfo || null,
                sortToggle = this.sortToggle ? this.sortToggle[name] : null;

			if (!dir) {
				if (sortInfo && sortInfo.field == name) { // toggle sort dir
					dir = (this.sortToggle[name] || 'ASC').toggle('ASC', 'DESC');
				} else {
					dir = field.sortDir;
				}
			}

			this.sortToggle[name] = dir;
			this.sortInfo = { field: name, direction: dir };

			sorters = [this.sortInfo];
		}

		//add the grouping sorter object as the first multisort sorter
		if (this.groupField) {
			sorters.unshift({ direction: this.groupDir, field: this.groupField });
		}

		return this.multiSort.call(this, sorters, dir);
	},

	/**
	* @private
	* Saves the current grouping field and direction to this.baseParams and this.lastOptions.params
	* if we're using remote grouping. Does not actually perform any grouping - just stores values
	*/
	applyGroupField: function () {
		if (this.remoteGroup) {
			if (!this.baseParams) {
				this.baseParams = {};
			}

			Ext.apply(this.baseParams, {
				groupBy: this.groupField,
				groupDir: this.groupDir
			});

			var lo = this.lastOptions;
			if (lo && lo.params) {
				lo.params.groupDir = this.groupDir;

				//this is deleted because of a bug reported at http://www.extjs.com/forum/showthread.php?t=82907
				delete lo.params.groupBy;
			}
		}
	},

	/**
	* @private
	* TODO: This function is apparently never invoked anywhere in the framework. It has no documentation
	* and should be considered for deletion
	*/
	applyGrouping: function (alwaysFireChange) {
		if (this.groupField !== false) {
			this.groupBy(this.groupField, true, this.groupDir);
			return true;
		} else {
			if (alwaysFireChange === true) {
				this.fireEvent('datachanged', this);
			}
			return false;
		}
	},

	/**
	* @private
	* Returns the grouping field that should be used. If groupOnSort is used this will be sortInfo's field,
	* otherwise it will be this.groupField
	* @return {String} The group field
	*/
	getGroupState: function () {
		return this.groupOnSort && this.groupField !== false ?
               (this.sortInfo ? this.sortInfo.field : undefined) : this.groupField;
	}
});
Ext.reg('groupingstore', Ext.data.GroupingStore);
/**
* @class Ext.data.DirectProxy
* @extends Ext.data.DataProxy
*/
Ext.data.DirectProxy = function (config) {
	Ext.apply(this, config);
	if (typeof this.paramOrder == 'string') {
		this.paramOrder = this.paramOrder.split(/[\s,|]/);
	}
	Ext.data.DirectProxy.superclass.constructor.call(this, config);
};

Ext.extend(Ext.data.DirectProxy, Ext.data.DataProxy, {
	/**
	* @cfg {Array/String} paramOrder Defaults to <tt>undefined</tt>. A list of params to be executed
	* server side.  Specify the params in the order in which they must be executed on the server-side
	* as either (1) an Array of String values, or (2) a String of params delimited by either whitespace,
	* comma, or pipe. For example,
	* any of the following would be acceptable:<pre><code>
	paramOrder: ['param1','param2','param3']
	paramOrder: 'param1 param2 param3'
	paramOrder: 'param1,param2,param3'
	paramOrder: 'param1|param2|param'
	</code></pre>
	*/
	paramOrder: undefined,

	/**
	* @cfg {Boolean} paramsAsHash
	* Send parameters as a collection of named arguments (defaults to <tt>true</tt>). Providing a
	* <tt>{@link #paramOrder}</tt> nullifies this configuration.
	*/
	paramsAsHash: true,

	/**
	* @cfg {Function} directFn
	* Function to call when executing a request.  directFn is a simple alternative to defining the api configuration-parameter
	* for Store's which will not implement a full CRUD api.
	*/
	directFn: undefined,

	/**
	* DirectProxy implementation of {@link Ext.data.DataProxy#doRequest}
	* @param {String} action The crud action type (create, read, update, destroy)
	* @param {Ext.data.Record/Ext.data.Record[]} rs If action is load, rs will be null
	* @param {Object} params An object containing properties which are to be used as HTTP parameters
	* for the request to the remote server.
	* @param {Ext.data.DataReader} reader The Reader object which converts the data
	* object into a block of Ext.data.Records.
	* @param {Function} callback
	* <div class="sub-desc"><p>A function to be called after the request.
	* The <tt>callback</tt> is passed the following arguments:<ul>
	* <li><tt>r</tt> : Ext.data.Record[] The block of Ext.data.Records.</li>
	* <li><tt>options</tt>: Options object from the action request</li>
	* <li><tt>success</tt>: Boolean success indicator</li></ul></p></div>
	* @param {Object} scope The scope (<code>this</code> reference) in which the callback function is executed. Defaults to the browser window.
	* @param {Object} arg An optional argument which is passed to the callback as its second parameter.
	* @protected
	*/
	doRequest: function (action, rs, params, reader, callback, scope, options) {
		var args = [],
            directFn = this.api[action] || this.directFn;

		switch (action) {
			case Ext.data.Api.actions.create:
				args.push(params.jsonData); 	// <-- create(Hash)
				break;
			case Ext.data.Api.actions.read:
				// If the method has no parameters, ignore the paramOrder/paramsAsHash.
				if (directFn.directCfg.method.len > 0) {
					if (this.paramOrder) {
						for (var i = 0, len = this.paramOrder.length; i < len; i++) {
							args.push(params[this.paramOrder[i]]);
						}
					} else if (this.paramsAsHash) {
						args.push(params);
					}
				}
				break;
			case Ext.data.Api.actions.update:
				args.push(params.jsonData);        // <-- update(Hash/Hash[])
				break;
			case Ext.data.Api.actions.destroy:
				args.push(params.jsonData);        // <-- destroy(Int/Int[])
				break;
		}

		var trans = {
			params: params || {},
			request: {
				callback: callback,
				scope: scope,
				arg: options
			},
			reader: reader
		};

		args.push(this.createCallback(action, rs, trans), this);
		directFn.apply(window, args);
	},

	// private
	createCallback: function (action, rs, trans) {
		var me = this;
		return function (result, res) {
			if (!res.status) {
				// @deprecated fire loadexception
				if (action === Ext.data.Api.actions.read) {
					me.fireEvent("loadexception", me, trans, res, null);
				}
				me.fireEvent('exception', me, 'remote', action, trans, res, null);
				trans.request.callback.call(trans.request.scope, null, trans.request.arg, false);
				return;
			}
			if (action === Ext.data.Api.actions.read) {
				me.onRead(action, trans, result, res);
			} else {
				me.onWrite(action, trans, result, res, rs);
			}
		};
	},

	/**
	* Callback for read actions
	* @param {String} action [Ext.data.Api.actions.create|read|update|destroy]
	* @param {Object} trans The request transaction object
	* @param {Object} result Data object picked out of the server-response.
	* @param {Object} res The server response
	* @protected
	*/
	onRead: function (action, trans, result, res) {
		var records;
		try {
			records = trans.reader.readRecords(result);
		}
		catch (ex) {
			// @deprecated: Fire old loadexception for backwards-compat.
			this.fireEvent("loadexception", this, trans, res, ex);

			this.fireEvent('exception', this, 'response', action, trans, res, ex);
			trans.request.callback.call(trans.request.scope, null, trans.request.arg, false);
			return;
		}
		this.fireEvent("load", this, res, trans.request.arg);
		trans.request.callback.call(trans.request.scope, records, trans.request.arg, true);
	},
	/**
	* Callback for write actions
	* @param {String} action [{@link Ext.data.Api#actions create|read|update|destroy}]
	* @param {Object} trans The request transaction object
	* @param {Object} result Data object picked out of the server-response.
	* @param {Object} res The server response
	* @param {Ext.data.Record/[Ext.data.Record]} rs The Store resultset associated with the action.
	* @protected
	*/
	onWrite: function (action, trans, result, res, rs) {
		var data = trans.reader.extractData(trans.reader.getRoot(result), false);
		var success = trans.reader.getSuccess(result);
		success = (success !== false);
		if (success) {
			this.fireEvent("write", this, action, data, res, rs, trans.request.arg);
		} else {
			this.fireEvent('exception', this, 'remote', action, trans, result, rs);
		}
		trans.request.callback.call(trans.request.scope, data, res, success);
	}
});
/**
* @class Ext.data.DirectStore
* @extends Ext.data.Store
* <p>Small helper class to create an {@link Ext.data.Store} configured with an
* {@link Ext.data.DirectProxy} and {@link Ext.data.JsonReader} to make interacting
* with an {@link Ext.Direct} Server-side {@link Ext.direct.Provider Provider} easier.
* To create a different proxy/reader combination create a basic {@link Ext.data.Store}
* configured as needed.</p>
*
* <p><b>*Note:</b> Although they are not listed, this class inherits all of the config options of:</p>
* <div><ul class="mdetail-params">
* <li><b>{@link Ext.data.Store Store}</b></li>
* <div class="sub-desc"><ul class="mdetail-params">
*
* </ul></div>
* <li><b>{@link Ext.data.JsonReader JsonReader}</b></li>
* <div class="sub-desc"><ul class="mdetail-params">
* <li><tt><b>{@link Ext.data.JsonReader#root root}</b></tt></li>
* <li><tt><b>{@link Ext.data.JsonReader#idProperty idProperty}</b></tt></li>
* <li><tt><b>{@link Ext.data.JsonReader#totalProperty totalProperty}</b></tt></li>
* </ul></div>
*
* <li><b>{@link Ext.data.DirectProxy DirectProxy}</b></li>
* <div class="sub-desc"><ul class="mdetail-params">
* <li><tt><b>{@link Ext.data.DirectProxy#directFn directFn}</b></tt></li>
* <li><tt><b>{@link Ext.data.DirectProxy#paramOrder paramOrder}</b></tt></li>
* <li><tt><b>{@link Ext.data.DirectProxy#paramsAsHash paramsAsHash}</b></tt></li>
* </ul></div>
* </ul></div>
*
* @xtype directstore
*
* @constructor
* @param {Object} config
*/
Ext.data.DirectStore = Ext.extend(Ext.data.Store, {
	constructor: function (config) {
		// each transaction upon a singe record will generate a distinct Direct transaction since Direct queues them into one Ajax request.
		var c = Ext.apply({}, {
			batchTransactions: false
		}, config);
		Ext.data.DirectStore.superclass.constructor.call(this, Ext.apply(c, {
			proxy: Ext.isDefined(c.proxy) ? c.proxy : new Ext.data.DirectProxy(Ext.copyTo({}, c, 'paramOrder,paramsAsHash,directFn,api')),
			reader: (!Ext.isDefined(c.reader) && c.fields) ? new Ext.data.JsonReader(Ext.copyTo({}, c, 'totalProperty,root,idProperty'), c.fields) : c.reader
		}));
	}
});
Ext.reg('directstore', Ext.data.DirectStore);
/**
* @class Ext.Direct
* @extends Ext.util.Observable
* <p><b><u>Overview</u></b></p>
*
* <p>Ext.Direct aims to streamline communication between the client and server
* by providing a single interface that reduces the amount of common code
* typically required to validate data and handle returned data packets
* (reading data, error conditions, etc).</p>
*
* <p>The Ext.direct namespace includes several classes for a closer integration
* with the server-side. The Ext.data namespace also includes classes for working
* with Ext.data.Stores which are backed by data from an Ext.Direct method.</p>
*
* <p><b><u>Specification</u></b></p>
*
* <p>For additional information consult the
* <a href="http://extjs.com/products/extjs/direct.php">Ext.Direct Specification</a>.</p>
*
* <p><b><u>Providers</u></b></p>
*
* <p>Ext.Direct uses a provider architecture, where one or more providers are
* used to transport data to and from the server. There are several providers
* that exist in the core at the moment:</p><div class="mdetail-params"><ul>
*
* <li>{@link Ext.direct.JsonProvider JsonProvider} for simple JSON operations</li>
* <li>{@link Ext.direct.PollingProvider PollingProvider} for repeated requests</li>
* <li>{@link Ext.direct.RemotingProvider RemotingProvider} exposes server side
* on the client.</li>
* </ul></div>
*
* <p>A provider does not need to be invoked directly, providers are added via
* {@link Ext.Direct}.{@link Ext.Direct#add add}.</p>
*
* <p><b><u>Router</u></b></p>
*
* <p>Ext.Direct utilizes a "router" on the server to direct requests from the client
* to the appropriate server-side method. Because the Ext.Direct API is completely
* platform-agnostic, you could completely swap out a Java based server solution
* and replace it with one that uses C# without changing the client side JavaScript
* at all.</p>
*
* <p><b><u>Server side events</u></b></p>
*
* <p>Custom events from the server may be handled by the client by adding
* listeners, for example:</p>
* <pre><code>
{"type":"event","name":"message","data":"Successfully polled at: 11:19:30 am"}

// add a handler for a 'message' event sent by the server
Ext.Direct.on('message', function(e){
out.append(String.format('&lt;p>&lt;i>{0}&lt;/i>&lt;/p>', e.data));
out.el.scrollTo('t', 100000, true);
});
* </code></pre>
* @singleton
*/
Ext.Direct = Ext.extend(Ext.util.Observable, {
	/**
	* Each event type implements a getData() method. The default event types are:
	* <div class="mdetail-params"><ul>
	* <li><b><tt>event</tt></b> : Ext.Direct.Event</li>
	* <li><b><tt>exception</tt></b> : Ext.Direct.ExceptionEvent</li>
	* <li><b><tt>rpc</tt></b> : Ext.Direct.RemotingEvent</li>
	* </ul></div>
	* @property eventTypes
	* @type Object
	*/

	/**
	* Four types of possible exceptions which can occur:
	* <div class="mdetail-params"><ul>
	* <li><b><tt>Ext.Direct.exceptions.TRANSPORT</tt></b> : 'xhr'</li>
	* <li><b><tt>Ext.Direct.exceptions.PARSE</tt></b> : 'parse'</li>
	* <li><b><tt>Ext.Direct.exceptions.LOGIN</tt></b> : 'login'</li>
	* <li><b><tt>Ext.Direct.exceptions.SERVER</tt></b> : 'exception'</li>
	* </ul></div>
	* @property exceptions
	* @type Object
	*/
	exceptions: {
		TRANSPORT: 'xhr',
		PARSE: 'parse',
		LOGIN: 'login',
		SERVER: 'exception'
	},

	// private
	constructor: function () {
		this.addEvents(
		/**
		* @event event
		* Fires after an event.
		* @param {event} e The {@link Ext.Direct#eventTypes Ext.Direct.Event type} that occurred.
		* @param {Ext.direct.Provider} provider The {@link Ext.direct.Provider Provider}.
		*/
            'event',
		/**
		* @event exception
		* Fires after an event exception.
		* @param {event} e The {@link Ext.Direct#eventTypes Ext.Direct.Event type} that occurred.
		*/
            'exception'
        );
		this.transactions = {};
		this.providers = {};
	},

	/**
	* Adds an Ext.Direct Provider and creates the proxy or stub methods to execute server-side methods.
	* If the provider is not already connected, it will auto-connect.
	* <pre><code>
	var pollProv = new Ext.direct.PollingProvider({
	url: 'php/poll2.php'
	});

	Ext.Direct.addProvider(
	{
	"type":"remoting",       // create a {@link Ext.direct.RemotingProvider}
	"url":"php\/router.php", // url to connect to the Ext.Direct server-side router.
	"actions":{              // each property within the actions object represents a Class
	"TestAction":[       // array of methods within each server side Class
	{
	"name":"doEcho", // name of method
	"len":1
	},{
	"name":"multiply",
	"len":1
	},{
	"name":"doForm",
	"formHandler":true, // handle form on server with Ext.Direct.Transaction
	"len":1
	}]
	},
	"namespace":"myApplication",// namespace to create the Remoting Provider in
	},{
	type: 'polling', // create a {@link Ext.direct.PollingProvider}
	url:  'php/poll.php'
	},
	pollProv // reference to previously created instance
	);
	* </code></pre>
	* @param {Object/Array} provider Accepts either an Array of Provider descriptions (an instance
	* or config object for a Provider) or any number of Provider descriptions as arguments.  Each
	* Provider description instructs Ext.Direct how to create client-side stub methods.
	*/
	addProvider: function (provider) {
		var a = arguments;
		if (a.length > 1) {
			for (var i = 0, len = a.length; i < len; i++) {
				this.addProvider(a[i]);
			}
			return;
		}

		// if provider has not already been instantiated
		if (!provider.events) {
			provider = new Ext.Direct.PROVIDERS[provider.type](provider);
		}
		provider.id = provider.id || Ext.id();
		this.providers[provider.id] = provider;

		provider.on('data', this.onProviderData, this);
		provider.on('exception', this.onProviderException, this);


		if (!provider.isConnected()) {
			provider.connect();
		}

		return provider;
	},

	/**
	* Retrieve a {@link Ext.direct.Provider provider} by the
	* <b><tt>{@link Ext.direct.Provider#id id}</tt></b> specified when the provider is
	* {@link #addProvider added}.
	* @param {String} id Unique identifier assigned to the provider when calling {@link #addProvider}
	*/
	getProvider: function (id) {
		return this.providers[id];
	},

	removeProvider: function (id) {
		var provider = id.id ? id : this.providers[id];
		provider.un('data', this.onProviderData, this);
		provider.un('exception', this.onProviderException, this);
		delete this.providers[provider.id];
		return provider;
	},

	addTransaction: function (t) {
		this.transactions[t.tid] = t;
		return t;
	},

	removeTransaction: function (t) {
		delete this.transactions[t.tid || t];
		return t;
	},

	getTransaction: function (tid) {
		return this.transactions[tid.tid || tid];
	},

	onProviderData: function (provider, e) {
		if (Ext.isArray(e)) {
			for (var i = 0, len = e.length; i < len; i++) {
				this.onProviderData(provider, e[i]);
			}
			return;
		}
		if (e.name && e.name != 'event' && e.name != 'exception') {
			this.fireEvent(e.name, e);
		} else if (e.type == 'exception') {
			this.fireEvent('exception', e);
		}
		this.fireEvent('event', e, provider);
	},

	createEvent: function (response, extraProps) {
		return new Ext.Direct.eventTypes[response.type](Ext.apply(response, extraProps));
	}
});
// overwrite impl. with static instance
Ext.Direct = new Ext.Direct();

Ext.Direct.TID = 1;
Ext.Direct.PROVIDERS = {}; /**
 * @class Ext.Direct.Transaction
 * @extends Object
 * <p>Supporting Class for Ext.Direct (not intended to be used directly).</p>
 * @constructor
 * @param {Object} config
 */
Ext.Direct.Transaction = function (config) {
	Ext.apply(this, config);
	this.tid = ++Ext.Direct.TID;
	this.retryCount = 0;
};
Ext.Direct.Transaction.prototype = {
	send: function () {
		this.provider.queueTransaction(this);
	},

	retry: function () {
		this.retryCount++;
		this.send();
	},

	getProvider: function () {
		return this.provider;
	}
}; Ext.Direct.Event = function (config) {
	Ext.apply(this, config);
};

Ext.Direct.Event.prototype = {
	status: true,
	getData: function () {
		return this.data;
	}
};

Ext.Direct.RemotingEvent = Ext.extend(Ext.Direct.Event, {
	type: 'rpc',
	getTransaction: function () {
		return this.transaction || Ext.Direct.getTransaction(this.tid);
	}
});

Ext.Direct.ExceptionEvent = Ext.extend(Ext.Direct.RemotingEvent, {
	status: false,
	type: 'exception'
});

Ext.Direct.eventTypes = {
	'rpc': Ext.Direct.RemotingEvent,
	'event': Ext.Direct.Event,
	'exception': Ext.Direct.ExceptionEvent
};
/**
* @class Ext.direct.Provider
* @extends Ext.util.Observable
* <p>Ext.direct.Provider is an abstract class meant to be extended.</p>
* 
* <p>For example ExtJs implements the following subclasses:</p>
* <pre><code>
Provider
|
+---{@link Ext.direct.JsonProvider JsonProvider} 
|
+---{@link Ext.direct.PollingProvider PollingProvider}   
|
+---{@link Ext.direct.RemotingProvider RemotingProvider}   
* </code></pre>
* @abstract
*/
Ext.direct.Provider = Ext.extend(Ext.util.Observable, {
	/**
	* @cfg {String} id
	* The unique id of the provider (defaults to an {@link Ext#id auto-assigned id}).
	* You should assign an id if you need to be able to access the provider later and you do
	* not have an object reference available, for example:
	* <pre><code>
	Ext.Direct.addProvider(
	{
	type: 'polling',
	url:  'php/poll.php',
	id:   'poll-provider'
	}
	);
     
	var p = {@link Ext.Direct Ext.Direct}.{@link Ext.Direct#getProvider getProvider}('poll-provider');
	p.disconnect();
	* </code></pre>
	*/

	/**
	* @cfg {Number} priority
	* Priority of the request. Lower is higher priority, <tt>0</tt> means "duplex" (always on).
	* All Providers default to <tt>1</tt> except for PollingProvider which defaults to <tt>3</tt>.
	*/
	priority: 1,

	/**
	* @cfg {String} type
	* <b>Required</b>, <tt>undefined</tt> by default.  The <tt>type</tt> of provider specified
	* to {@link Ext.Direct Ext.Direct}.{@link Ext.Direct#addProvider addProvider} to create a
	* new Provider. Acceptable values by default are:<div class="mdetail-params"><ul>
	* <li><b><tt>polling</tt></b> : {@link Ext.direct.PollingProvider PollingProvider}</li>
	* <li><b><tt>remoting</tt></b> : {@link Ext.direct.RemotingProvider RemotingProvider}</li>
	* </ul></div>
	*/

	// private
	constructor: function (config) {
		Ext.apply(this, config);
		this.addEvents(
		/**
		* @event connect
		* Fires when the Provider connects to the server-side
		* @param {Ext.direct.Provider} provider The {@link Ext.direct.Provider Provider}.
		*/
            'connect',
		/**
		* @event disconnect
		* Fires when the Provider disconnects from the server-side
		* @param {Ext.direct.Provider} provider The {@link Ext.direct.Provider Provider}.
		*/
            'disconnect',
		/**
		* @event data
		* Fires when the Provider receives data from the server-side
		* @param {Ext.direct.Provider} provider The {@link Ext.direct.Provider Provider}.
		* @param {event} e The {@link Ext.Direct#eventTypes Ext.Direct.Event type} that occurred.
		*/
            'data',
		/**
		* @event exception
		* Fires when the Provider receives an exception from the server-side
		*/
            'exception'
        );
		Ext.direct.Provider.superclass.constructor.call(this, config);
	},

	/**
	* Returns whether or not the server-side is currently connected.
	* Abstract method for subclasses to implement.
	*/
	isConnected: function () {
		return false;
	},

	/**
	* Abstract methods for subclasses to implement.
	*/
	connect: Ext.emptyFn,

	/**
	* Abstract methods for subclasses to implement.
	*/
	disconnect: Ext.emptyFn
});
/**
* @class Ext.direct.JsonProvider
* @extends Ext.direct.Provider
*/
Ext.direct.JsonProvider = Ext.extend(Ext.direct.Provider, {
	parseResponse: function (xhr) {
		if (!Ext.isEmpty(xhr.responseText)) {
			if (typeof xhr.responseText == 'object') {
				return xhr.responseText;
			}
			return Ext.decode(xhr.responseText);
		}
		return null;
	},

	getEvents: function (xhr) {
		var data = null;
		try {
			data = this.parseResponse(xhr);
		} catch (e) {
			var event = new Ext.Direct.ExceptionEvent({
				data: e,
				xhr: xhr,
				code: Ext.Direct.exceptions.PARSE,
				message: 'Error parsing json response: \n\n ' + data
			});
			return [event];
		}
		var events = [];
		if (Ext.isArray(data)) {
			for (var i = 0, len = data.length; i < len; i++) {
				events.push(Ext.Direct.createEvent(data[i]));
			}
		} else {
			events.push(Ext.Direct.createEvent(data));
		}
		return events;
	}
}); /**
 * @class Ext.direct.PollingProvider
 * @extends Ext.direct.JsonProvider
 *
 * <p>Provides for repetitive polling of the server at distinct {@link #interval intervals}.
 * The initial request for data originates from the client, and then is responded to by the
 * server.</p>
 * 
 * <p>All configurations for the PollingProvider should be generated by the server-side
 * API portion of the Ext.Direct stack.</p>
 *
 * <p>An instance of PollingProvider may be created directly via the new keyword or by simply
 * specifying <tt>type = 'polling'</tt>.  For example:</p>
 * <pre><code>
var pollA = new Ext.direct.PollingProvider({
    type:'polling',
    url: 'php/pollA.php',
});
Ext.Direct.addProvider(pollA);
pollA.disconnect();

Ext.Direct.addProvider(
    {
        type:'polling',
        url: 'php/pollB.php',
        id: 'pollB-provider'
    }
);
var pollB = Ext.Direct.getProvider('pollB-provider');
 * </code></pre>
 */
Ext.direct.PollingProvider = Ext.extend(Ext.direct.JsonProvider, {
	/**
	* @cfg {Number} priority
	* Priority of the request (defaults to <tt>3</tt>). See {@link Ext.direct.Provider#priority}.
	*/
	// override default priority
	priority: 3,

	/**
	* @cfg {Number} interval
	* How often to poll the server-side in milliseconds (defaults to <tt>3000</tt> - every
	* 3 seconds).
	*/
	interval: 3000,

	/**
	* @cfg {Object} baseParams An object containing properties which are to be sent as parameters
	* on every polling request
	*/

	/**
	* @cfg {String/Function} url
	* The url which the PollingProvider should contact with each request. This can also be
	* an imported Ext.Direct method which will accept the baseParams as its only argument.
	*/

	// private
	constructor: function (config) {
		Ext.direct.PollingProvider.superclass.constructor.call(this, config);
		this.addEvents(
		/**
		* @event beforepoll
		* Fired immediately before a poll takes place, an event handler can return false
		* in order to cancel the poll.
		* @param {Ext.direct.PollingProvider}
		*/
            'beforepoll',
		/**
		* @event poll
		* This event has not yet been implemented.
		* @param {Ext.direct.PollingProvider}
		*/
            'poll'
        );
	},

	// inherited
	isConnected: function () {
		return !!this.pollTask;
	},

	/**
	* Connect to the server-side and begin the polling process. To handle each
	* response subscribe to the data event.
	*/
	connect: function () {
		if (this.url && !this.pollTask) {
			this.pollTask = Ext.TaskMgr.start({
				run: function () {
					if (this.fireEvent('beforepoll', this) !== false) {
						if (typeof this.url == 'function') {
							this.url(this.baseParams);
						} else {
							Ext.Ajax.request({
								url: this.url,
								callback: this.onData,
								scope: this,
								params: this.baseParams
							});
						}
					}
				},
				interval: this.interval,
				scope: this
			});
			this.fireEvent('connect', this);
		} else if (!this.url) {
			throw 'Error initializing PollingProvider, no url configured.';
		}
	},

	/**
	* Disconnect from the server-side and stop the polling process. The disconnect
	* event will be fired on a successful disconnect.
	*/
	disconnect: function () {
		if (this.pollTask) {
			Ext.TaskMgr.stop(this.pollTask);
			delete this.pollTask;
			this.fireEvent('disconnect', this);
		}
	},

	// private
	onData: function (opt, success, xhr) {
		if (success) {
			var events = this.getEvents(xhr);
			for (var i = 0, len = events.length; i < len; i++) {
				var e = events[i];
				this.fireEvent('data', this, e);
			}
		} else {
			var e = new Ext.Direct.ExceptionEvent({
				data: e,
				code: Ext.Direct.exceptions.TRANSPORT,
				message: 'Unable to connect to the server.',
				xhr: xhr
			});
			this.fireEvent('data', this, e);
		}
	}
});

Ext.Direct.PROVIDERS['polling'] = Ext.direct.PollingProvider; /**
 * @class Ext.direct.RemotingProvider
 * @extends Ext.direct.JsonProvider
 * 
 * <p>The {@link Ext.direct.RemotingProvider RemotingProvider} exposes access to
 * server side methods on the client (a remote procedure call (RPC) type of
 * connection where the client can initiate a procedure on the server).</p>
 * 
 * <p>This allows for code to be organized in a fashion that is maintainable,
 * while providing a clear path between client and server, something that is
 * not always apparent when using URLs.</p>
 * 
 * <p>To accomplish this the server-side needs to describe what classes and methods
 * are available on the client-side. This configuration will typically be
 * outputted by the server-side Ext.Direct stack when the API description is built.</p>
 */
Ext.direct.RemotingProvider = Ext.extend(Ext.direct.JsonProvider, {
	/**
	* @cfg {Object} actions
	* Object literal defining the server side actions and methods. For example, if
	* the Provider is configured with:
	* <pre><code>
	"actions":{ // each property within the 'actions' object represents a server side Class 
	"TestAction":[ // array of methods within each server side Class to be   
	{              // stubbed out on client
	"name":"doEcho", 
	"len":1            
	},{
	"name":"multiply",// name of method
	"len":2           // The number of parameters that will be used to create an
	// array of data to send to the server side function.
	// Ensure the server sends back a Number, not a String. 
	},{
	"name":"doForm",
	"formHandler":true, // direct the client to use specialized form handling method 
	"len":1
	}]
	}
	* </code></pre>
	* <p>Note that a Store is not required, a server method can be called at any time.
	* In the following example a <b>client side</b> handler is used to call the
	* server side method "multiply" in the server-side "TestAction" Class:</p>
	* <pre><code>
	TestAction.multiply(
	2, 4, // pass two arguments to server, so specify len=2
	// callback function after the server is called
	// result: the result returned by the server
	//      e: Ext.Direct.RemotingEvent object
	function(result, e){
	var t = e.getTransaction();
	var action = t.action; // server side Class called
	var method = t.method; // server side method called
	if(e.status){
	var answer = Ext.encode(result); // 8
    
	}else{
	var msg = e.message; // failure message
	}
	}
	);
	* </code></pre>
	* In the example above, the server side "multiply" function will be passed two
	* arguments (2 and 4).  The "multiply" method should return the value 8 which will be
	* available as the <tt>result</tt> in the example above. 
	*/

	/**
	* @cfg {String/Object} namespace
	* Namespace for the Remoting Provider (defaults to the browser global scope of <i>window</i>).
	* Explicitly specify the namespace Object, or specify a String to have a
	* {@link Ext#namespace namespace created} implicitly.
	*/

	/**
	* @cfg {String} url
	* <b>Required<b>. The url to connect to the {@link Ext.Direct} server-side router. 
	*/

	/**
	* @cfg {String} enableUrlEncode
	* Specify which param will hold the arguments for the method.
	* Defaults to <tt>'data'</tt>.
	*/

	/**
	* @cfg {Number/Boolean} enableBuffer
	* <p><tt>true</tt> or <tt>false</tt> to enable or disable combining of method
	* calls. If a number is specified this is the amount of time in milliseconds
	* to wait before sending a batched request (defaults to <tt>10</tt>).</p>
	* <br><p>Calls which are received within the specified timeframe will be
	* concatenated together and sent in a single request, optimizing the
	* application by reducing the amount of round trips that have to be made
	* to the server.</p>
	*/
	enableBuffer: 10,

	/**
	* @cfg {Number} maxRetries
	* Number of times to re-attempt delivery on failure of a call. Defaults to <tt>1</tt>.
	*/
	maxRetries: 1,

	/**
	* @cfg {Number} timeout
	* The timeout to use for each request. Defaults to <tt>undefined</tt>.
	*/
	timeout: undefined,

	constructor: function (config) {
		Ext.direct.RemotingProvider.superclass.constructor.call(this, config);
		this.addEvents(
		/**
		* @event beforecall
		* Fires immediately before the client-side sends off the RPC call.
		* By returning false from an event handler you can prevent the call from
		* executing.
		* @param {Ext.direct.RemotingProvider} provider
		* @param {Ext.Direct.Transaction} transaction
		*/
            'beforecall',
		/**
		* @event call
		* Fires immediately after the request to the server-side is sent. This does
		* NOT fire after the response has come back from the call.
		* @param {Ext.direct.RemotingProvider} provider
		* @param {Ext.Direct.Transaction} transaction
		*/
            'call'
        );
		this.namespace = (Ext.isString(this.namespace)) ? Ext.ns(this.namespace) : this.namespace || window;
		this.transactions = {};
		this.callBuffer = [];
	},

	// private
	initAPI: function () {
		var o = this.actions;
		for (var c in o) {
			var cls = this.namespace[c] || (this.namespace[c] = {}),
                ms = o[c];
			for (var i = 0, len = ms.length; i < len; i++) {
				var m = ms[i];
				cls[m.name] = this.createMethod(c, m);
			}
		}
	},

	// inherited
	isConnected: function () {
		return !!this.connected;
	},

	connect: function () {
		if (this.url) {
			this.initAPI();
			this.connected = true;
			this.fireEvent('connect', this);
		} else if (!this.url) {
			throw 'Error initializing RemotingProvider, no url configured.';
		}
	},

	disconnect: function () {
		if (this.connected) {
			this.connected = false;
			this.fireEvent('disconnect', this);
		}
	},

	onData: function (opt, success, xhr) {
		if (success) {
			var events = this.getEvents(xhr);
			for (var i = 0, len = events.length; i < len; i++) {
				var e = events[i],
                    t = this.getTransaction(e);
				this.fireEvent('data', this, e);
				if (t) {
					this.doCallback(t, e, true);
					Ext.Direct.removeTransaction(t);
				}
			}
		} else {
			var ts = [].concat(opt.ts);
			for (var i = 0, len = ts.length; i < len; i++) {
				var t = this.getTransaction(ts[i]);
				if (t && t.retryCount < this.maxRetries) {
					t.retry();
				} else {
					var e = new Ext.Direct.ExceptionEvent({
						data: e,
						transaction: t,
						code: Ext.Direct.exceptions.TRANSPORT,
						message: 'Unable to connect to the server.',
						xhr: xhr
					});
					this.fireEvent('data', this, e);
					if (t) {
						this.doCallback(t, e, false);
						Ext.Direct.removeTransaction(t);
					}
				}
			}
		}
	},

	getCallData: function (t) {
		return {
			action: t.action,
			method: t.method,
			data: t.data,
			type: 'rpc',
			tid: t.tid
		};
	},

	doSend: function (data) {
		var o = {
			url: this.url,
			callback: this.onData,
			scope: this,
			ts: data,
			timeout: this.timeout
		}, callData;

		if (Ext.isArray(data)) {
			callData = [];
			for (var i = 0, len = data.length; i < len; i++) {
				callData.push(this.getCallData(data[i]));
			}
		} else {
			callData = this.getCallData(data);
		}

		if (this.enableUrlEncode) {
			var params = {};
			params[Ext.isString(this.enableUrlEncode) ? this.enableUrlEncode : 'data'] = Ext.encode(callData);
			o.params = params;
		} else {
			o.jsonData = callData;
		}
		Ext.Ajax.request(o);
	},

	combineAndSend: function () {
		var len = this.callBuffer.length;
		if (len > 0) {
			this.doSend(len == 1 ? this.callBuffer[0] : this.callBuffer);
			this.callBuffer = [];
		}
	},

	queueTransaction: function (t) {
		if (t.form) {
			this.processForm(t);
			return;
		}
		this.callBuffer.push(t);
		if (this.enableBuffer) {
			if (!this.callTask) {
				this.callTask = new Ext.util.DelayedTask(this.combineAndSend, this);
			}
			this.callTask.delay(Ext.isNumber(this.enableBuffer) ? this.enableBuffer : 10);
		} else {
			this.combineAndSend();
		}
	},

	doCall: function (c, m, args) {
		var data = null, hs = args[m.len], scope = args[m.len + 1];

		if (m.len !== 0) {
			data = args.slice(0, m.len);
		}

		var t = new Ext.Direct.Transaction({
			provider: this,
			args: args,
			action: c,
			method: m.name,
			data: data,
			cb: scope && Ext.isFunction(hs) ? hs.createDelegate(scope) : hs
		});

		if (this.fireEvent('beforecall', this, t) !== false) {
			Ext.Direct.addTransaction(t);
			this.queueTransaction(t);
			this.fireEvent('call', this, t);
		}
	},

	doForm: function (c, m, form, callback, scope) {
		var t = new Ext.Direct.Transaction({
			provider: this,
			action: c,
			method: m.name,
			args: [form, callback, scope],
			cb: scope && Ext.isFunction(callback) ? callback.createDelegate(scope) : callback,
			isForm: true
		});

		if (this.fireEvent('beforecall', this, t) !== false) {
			Ext.Direct.addTransaction(t);
			var isUpload = String(form.getAttribute("enctype")).toLowerCase() == 'multipart/form-data',
                params = {
                	extTID: t.tid,
                	extAction: c,
                	extMethod: m.name,
                	extType: 'rpc',
                	extUpload: String(isUpload)
                };

			// change made from typeof callback check to callback.params
			// to support addl param passing in DirectSubmit EAC 6/2
			Ext.apply(t, {
				form: Ext.getDom(form),
				isUpload: isUpload,
				params: callback && Ext.isObject(callback.params) ? Ext.apply(params, callback.params) : params
			});
			this.fireEvent('call', this, t);
			this.processForm(t);
		}
	},

	processForm: function (t) {
		Ext.Ajax.request({
			url: this.url,
			params: t.params,
			callback: this.onData,
			scope: this,
			form: t.form,
			isUpload: t.isUpload,
			ts: t
		});
	},

	createMethod: function (c, m) {
		var f;
		if (!m.formHandler) {
			f = function () {
				this.doCall(c, m, Array.prototype.slice.call(arguments, 0));
			} .createDelegate(this);
		} else {
			f = function (form, callback, scope) {
				this.doForm(c, m, form, callback, scope);
			} .createDelegate(this);
		}
		f.directCfg = {
			action: c,
			method: m
		};
		return f;
	},

	getTransaction: function (opt) {
		return opt && opt.tid ? Ext.Direct.getTransaction(opt.tid) : null;
	},

	doCallback: function (t, e) {
		var fn = e.status ? 'success' : 'failure';
		if (t && t.cb) {
			var hs = t.cb,
                result = Ext.isDefined(e.result) ? e.result : e.data;
			if (Ext.isFunction(hs)) {
				hs(result, e);
			} else {
				Ext.callback(hs[fn], hs.scope, [result, e]);
				Ext.callback(hs.callback, hs.scope, [result, e]);
			}
		}
	}
});
Ext.Direct.PROVIDERS['remoting'] = Ext.direct.RemotingProvider; /**
 * @class Ext.Resizable
 * @extends Ext.util.Observable
 * <p>Applies drag handles to an element to make it resizable. The drag handles are inserted into the element
 * and positioned absolute. Some elements, such as a textarea or image, don't support this. To overcome that, you can wrap
 * the textarea in a div and set 'resizeChild' to true (or to the id of the element), <b>or</b> set wrap:true in your config and
 * the element will be wrapped for you automatically.</p>
 * <p>Here is the list of valid resize handles:</p>
 * <pre>
Value   Description
------  -------------------
 'n'     north
 's'     south
 'e'     east
 'w'     west
 'nw'    northwest
 'sw'    southwest
 'se'    southeast
 'ne'    northeast
 'all'   all
</pre>
 * <p>Here's an example showing the creation of a typical Resizable:</p>
 * <pre><code>
var resizer = new Ext.Resizable('element-id', {
    handles: 'all',
    minWidth: 200,
    minHeight: 100,
    maxWidth: 500,
    maxHeight: 400,
    pinned: true
});
resizer.on('resize', myHandler);
</code></pre>
 * <p>To hide a particular handle, set its display to none in CSS, or through script:<br>
 * resizer.east.setDisplayed(false);</p>
 * @constructor
 * Create a new resizable component
 * @param {Mixed} el The id or element to resize
 * @param {Object} config configuration options
  */
Ext.Resizable = Ext.extend(Ext.util.Observable, {

	constructor: function (el, config) {
		this.el = Ext.get(el);
		if (config && config.wrap) {
			config.resizeChild = this.el;
			this.el = this.el.wrap(typeof config.wrap == 'object' ? config.wrap : { cls: 'xresizable-wrap' });
			this.el.id = this.el.dom.id = config.resizeChild.id + '-rzwrap';
			this.el.setStyle('overflow', 'hidden');
			this.el.setPositioning(config.resizeChild.getPositioning());
			config.resizeChild.clearPositioning();
			if (!config.width || !config.height) {
				var csize = config.resizeChild.getSize();
				this.el.setSize(csize.width, csize.height);
			}
			if (config.pinned && !config.adjustments) {
				config.adjustments = 'auto';
			}
		}

		/**
		* The proxy Element that is resized in place of the real Element during the resize operation.
		* This may be queried using {@link Ext.Element#getBox} to provide the new area to resize to.
		* Read only.
		* @type Ext.Element.
		* @property proxy
		*/
		this.proxy = this.el.createProxy({ tag: 'div', cls: 'x-resizable-proxy', id: this.el.id + '-rzproxy' }, Ext.getBody());
		this.proxy.unselectable();
		this.proxy.enableDisplayMode('block');

		Ext.apply(this, config);

		if (this.pinned) {
			this.disableTrackOver = true;
			this.el.addClass('x-resizable-pinned');
		}
		// if the element isn't positioned, make it relative
		var position = this.el.getStyle('position');
		if (position != 'absolute' && position != 'fixed') {
			this.el.setStyle('position', 'relative');
		}
		if (!this.handles) { // no handles passed, must be legacy style
			this.handles = 's,e,se';
			if (this.multiDirectional) {
				this.handles += ',n,w';
			}
		}
		if (this.handles == 'all') {
			this.handles = 'n s e w ne nw se sw';
		}
		var hs = this.handles.split(/\s*?[,;]\s*?| /);
		var ps = Ext.Resizable.positions;
		for (var i = 0, len = hs.length; i < len; i++) {
			if (hs[i] && ps[hs[i]]) {
				var pos = ps[hs[i]];
				this[pos] = new Ext.Resizable.Handle(this, pos, this.disableTrackOver, this.transparent, this.handleCls);
			}
		}
		// legacy
		this.corner = this.southeast;

		if (this.handles.indexOf('n') != -1 || this.handles.indexOf('w') != -1) {
			this.updateBox = true;
		}

		this.activeHandle = null;

		if (this.resizeChild) {
			if (typeof this.resizeChild == 'boolean') {
				this.resizeChild = Ext.get(this.el.dom.firstChild, true);
			} else {
				this.resizeChild = Ext.get(this.resizeChild, true);
			}
		}

		if (this.adjustments == 'auto') {
			var rc = this.resizeChild;
			var hw = this.west, he = this.east, hn = this.north, hs = this.south;
			if (rc && (hw || hn)) {
				rc.position('relative');
				rc.setLeft(hw ? hw.el.getWidth() : 0);
				rc.setTop(hn ? hn.el.getHeight() : 0);
			}
			this.adjustments = [
                (he ? -he.el.getWidth() : 0) + (hw ? -hw.el.getWidth() : 0),
                (hn ? -hn.el.getHeight() : 0) + (hs ? -hs.el.getHeight() : 0) - 1
            ];
		}

		if (this.draggable) {
			this.dd = this.dynamic ?
                this.el.initDD(null) : this.el.initDDProxy(null, { dragElId: this.proxy.id });
			this.dd.setHandleElId(this.resizeChild ? this.resizeChild.id : this.el.id);
			if (this.constrainTo) {
				this.dd.constrainTo(this.constrainTo);
			}
		}

		this.addEvents(
		/**
		* @event beforeresize
		* Fired before resize is allowed. Set {@link #enabled} to false to cancel resize.
		* @param {Ext.Resizable} this
		* @param {Ext.EventObject} e The mousedown event
		*/
            'beforeresize',
		/**
		* @event resize
		* Fired after a resize.
		* @param {Ext.Resizable} this
		* @param {Number} width The new width
		* @param {Number} height The new height
		* @param {Ext.EventObject} e The mouseup event
		*/
            'resize'
        );

		if (this.width !== null && this.height !== null) {
			this.resizeTo(this.width, this.height);
		} else {
			this.updateChildSize();
		}
		if (Ext.isIE) {
			this.el.dom.style.zoom = 1;
		}
		Ext.Resizable.superclass.constructor.call(this);
	},

	/**
	* @cfg {Array/String} adjustments String 'auto' or an array [width, height] with values to be <b>added</b> to the
	* resize operation's new size (defaults to <tt>[0, 0]</tt>)
	*/
	adjustments: [0, 0],
	/**
	* @cfg {Boolean} animate True to animate the resize (not compatible with dynamic sizing, defaults to false)
	*/
	animate: false,
	/**
	* @cfg {Mixed} constrainTo Constrain the resize to a particular element
	*/
	/**
	* @cfg {Boolean} disableTrackOver True to disable mouse tracking. This is only applied at config time. (defaults to false)
	*/
	disableTrackOver: false,
	/**
	* @cfg {Boolean} draggable Convenience to initialize drag drop (defaults to false)
	*/
	draggable: false,
	/**
	* @cfg {Number} duration Animation duration if animate = true (defaults to 0.35)
	*/
	duration: 0.35,
	/**
	* @cfg {Boolean} dynamic True to resize the element while dragging instead of using a proxy (defaults to false)
	*/
	dynamic: false,
	/**
	* @cfg {String} easing Animation easing if animate = true (defaults to <tt>'easingOutStrong'</tt>)
	*/
	easing: 'easeOutStrong',
	/**
	* @cfg {Boolean} enabled False to disable resizing (defaults to true)
	*/
	enabled: true,
	/**
	* @property enabled Writable. False if resizing is disabled.
	* @type Boolean
	*/
	/**
	* @cfg {String} handles String consisting of the resize handles to display (defaults to undefined).
	* Specify either <tt>'all'</tt> or any of <tt>'n s e w ne nw se sw'</tt>.
	*/
	handles: false,
	/**
	* @cfg {Boolean} multiDirectional <b>Deprecated</b>.  Deprecated style of adding multi-direction resize handles.
	*/
	multiDirectional: false,
	/**
	* @cfg {Number} height The height of the element in pixels (defaults to null)
	*/
	height: null,
	/**
	* @cfg {Number} width The width of the element in pixels (defaults to null)
	*/
	width: null,
	/**
	* @cfg {Number} heightIncrement The increment to snap the height resize in pixels
	* (only applies if <code>{@link #dynamic}==true</code>). Defaults to <tt>0</tt>.
	*/
	heightIncrement: 0,
	/**
	* @cfg {Number} widthIncrement The increment to snap the width resize in pixels
	* (only applies if <code>{@link #dynamic}==true</code>). Defaults to <tt>0</tt>.
	*/
	widthIncrement: 0,
	/**
	* @cfg {Number} minHeight The minimum height for the element (defaults to 5)
	*/
	minHeight: 5,
	/**
	* @cfg {Number} minWidth The minimum width for the element (defaults to 5)
	*/
	minWidth: 5,
	/**
	* @cfg {Number} maxHeight The maximum height for the element (defaults to 10000)
	*/
	maxHeight: 10000,
	/**
	* @cfg {Number} maxWidth The maximum width for the element (defaults to 10000)
	*/
	maxWidth: 10000,
	/**
	* @cfg {Number} minX The minimum x for the element (defaults to 0)
	*/
	minX: 0,
	/**
	* @cfg {Number} minY The minimum x for the element (defaults to 0)
	*/
	minY: 0,
	/**
	* @cfg {Boolean} pinned True to ensure that the resize handles are always visible, false to display them only when the
	* user mouses over the resizable borders. This is only applied at config time. (defaults to false)
	*/
	pinned: false,
	/**
	* @cfg {Boolean} preserveRatio True to preserve the original ratio between height
	* and width during resize (defaults to false)
	*/
	preserveRatio: false,
	/**
	* @cfg {Boolean/String/Element} resizeChild True to resize the first child, or id/element to resize (defaults to false)
	*/
	resizeChild: false,
	/**
	* @cfg {Boolean} transparent True for transparent handles. This is only applied at config time. (defaults to false)
	*/
	transparent: false,
	/**
	* @cfg {Ext.lib.Region} resizeRegion Constrain the resize to a particular region
	*/
	/**
	* @cfg {Boolean} wrap True to wrap an element with a div if needed (required for textareas and images, defaults to false)
	* in favor of the handles config option (defaults to false)
	*/
	/**
	* @cfg {String} handleCls A css class to add to each handle. Defaults to <tt>''</tt>.
	*/


	/**
	* Perform a manual resize and fires the 'resize' event.
	* @param {Number} width
	* @param {Number} height
	*/
	resizeTo: function (width, height) {
		this.el.setSize(width, height);
		this.updateChildSize();
		this.fireEvent('resize', this, width, height, null);
	},

	// private
	startSizing: function (e, handle) {
		this.fireEvent('beforeresize', this, e);
		if (this.enabled) { // 2nd enabled check in case disabled before beforeresize handler

			if (!this.overlay) {
				this.overlay = this.el.createProxy({ tag: 'div', cls: 'x-resizable-overlay', html: '&#160;' }, Ext.getBody());
				this.overlay.unselectable();
				this.overlay.enableDisplayMode('block');
				this.overlay.on({
					scope: this,
					mousemove: this.onMouseMove,
					mouseup: this.onMouseUp
				});
			}
			this.overlay.setStyle('cursor', handle.el.getStyle('cursor'));

			this.resizing = true;
			this.startBox = this.el.getBox();
			this.startPoint = e.getXY();
			this.offsets = [(this.startBox.x + this.startBox.width) - this.startPoint[0],
                            (this.startBox.y + this.startBox.height) - this.startPoint[1]];

			this.overlay.setSize(Ext.lib.Dom.getViewWidth(true), Ext.lib.Dom.getViewHeight(true));
			this.overlay.show();

			if (this.constrainTo) {
				var ct = Ext.get(this.constrainTo);
				this.resizeRegion = ct.getRegion().adjust(
                    ct.getFrameWidth('t'),
                    ct.getFrameWidth('l'),
                    -ct.getFrameWidth('b'),
                    -ct.getFrameWidth('r')
                );
			}

			this.proxy.setStyle('visibility', 'hidden'); // workaround display none
			this.proxy.show();
			this.proxy.setBox(this.startBox);
			if (!this.dynamic) {
				this.proxy.setStyle('visibility', 'visible');
			}
		}
	},

	// private
	onMouseDown: function (handle, e) {
		if (this.enabled) {
			e.stopEvent();
			this.activeHandle = handle;
			this.startSizing(e, handle);
		}
	},

	// private
	onMouseUp: function (e) {
		this.activeHandle = null;
		var size = this.resizeElement();
		this.resizing = false;
		this.handleOut();
		this.overlay.hide();
		this.proxy.hide();
		this.fireEvent('resize', this, size.width, size.height, e);
	},

	// private
	updateChildSize: function () {
		if (this.resizeChild) {
			var el = this.el;
			var child = this.resizeChild;
			var adj = this.adjustments;
			if (el.dom.offsetWidth) {
				var b = el.getSize(true);
				child.setSize(b.width + adj[0], b.height + adj[1]);
			}
			// Second call here for IE
			// The first call enables instant resizing and
			// the second call corrects scroll bars if they
			// exist
			if (Ext.isIE) {
				setTimeout(function () {
					if (el.dom.offsetWidth) {
						var b = el.getSize(true);
						child.setSize(b.width + adj[0], b.height + adj[1]);
					}
				}, 10);
			}
		}
	},

	// private
	snap: function (value, inc, min) {
		if (!inc || !value) {
			return value;
		}
		var newValue = value;
		var m = value % inc;
		if (m > 0) {
			if (m > (inc / 2)) {
				newValue = value + (inc - m);
			} else {
				newValue = value - m;
			}
		}
		return Math.max(min, newValue);
	},

	/**
	* <p>Performs resizing of the associated Element. This method is called internally by this
	* class, and should not be called by user code.</p>
	* <p>If a Resizable is being used to resize an Element which encapsulates a more complex UI
	* component such as a Panel, this method may be overridden by specifying an implementation
	* as a config option to provide appropriate behaviour at the end of the resize operation on
	* mouseup, for example resizing the Panel, and relaying the Panel's content.</p>
	* <p>The new area to be resized to is available by examining the state of the {@link #proxy}
	* Element. Example:
	<pre><code>
	new Ext.Panel({
	title: 'Resize me',
	x: 100,
	y: 100,
	renderTo: Ext.getBody(),
	floating: true,
	frame: true,
	width: 400,
	height: 200,
	listeners: {
	render: function(p) {
	new Ext.Resizable(p.getEl(), {
	handles: 'all',
	pinned: true,
	transparent: true,
	resizeElement: function() {
	var box = this.proxy.getBox();
	p.updateBox(box);
	if (p.layout) {
	p.doLayout();
	}
	return box;
	}
	});
	}
	}
	}).show();
	</code></pre>
	*/
	resizeElement: function () {
		var box = this.proxy.getBox();
		if (this.updateBox) {
			this.el.setBox(box, false, this.animate, this.duration, null, this.easing);
		} else {
			this.el.setSize(box.width, box.height, this.animate, this.duration, null, this.easing);
		}
		this.updateChildSize();
		if (!this.dynamic) {
			this.proxy.hide();
		}
		if (this.draggable && this.constrainTo) {
			this.dd.resetConstraints();
			this.dd.constrainTo(this.constrainTo);
		}
		return box;
	},

	// private
	constrain: function (v, diff, m, mx) {
		if (v - diff < m) {
			diff = v - m;
		} else if (v - diff > mx) {
			diff = v - mx;
		}
		return diff;
	},

	// private
	onMouseMove: function (e) {
		if (this.enabled && this.activeHandle) {
			try {// try catch so if something goes wrong the user doesn't get hung

				if (this.resizeRegion && !this.resizeRegion.contains(e.getPoint())) {
					return;
				}

				//var curXY = this.startPoint;
				var curSize = this.curSize || this.startBox,
                x = this.startBox.x, y = this.startBox.y,
                ox = x,
                oy = y,
                w = curSize.width,
                h = curSize.height,
                ow = w,
                oh = h,
                mw = this.minWidth,
                mh = this.minHeight,
                mxw = this.maxWidth,
                mxh = this.maxHeight,
                wi = this.widthIncrement,
                hi = this.heightIncrement,
                eventXY = e.getXY(),
                diffX = -(this.startPoint[0] - Math.max(this.minX, eventXY[0])),
                diffY = -(this.startPoint[1] - Math.max(this.minY, eventXY[1])),
                pos = this.activeHandle.position,
                tw,
                th;

				switch (pos) {
					case 'east':
						w += diffX;
						w = Math.min(Math.max(mw, w), mxw);
						break;
					case 'south':
						h += diffY;
						h = Math.min(Math.max(mh, h), mxh);
						break;
					case 'southeast':
						w += diffX;
						h += diffY;
						w = Math.min(Math.max(mw, w), mxw);
						h = Math.min(Math.max(mh, h), mxh);
						break;
					case 'north':
						diffY = this.constrain(h, diffY, mh, mxh);
						y += diffY;
						h -= diffY;
						break;
					case 'west':
						diffX = this.constrain(w, diffX, mw, mxw);
						x += diffX;
						w -= diffX;
						break;
					case 'northeast':
						w += diffX;
						w = Math.min(Math.max(mw, w), mxw);
						diffY = this.constrain(h, diffY, mh, mxh);
						y += diffY;
						h -= diffY;
						break;
					case 'northwest':
						diffX = this.constrain(w, diffX, mw, mxw);
						diffY = this.constrain(h, diffY, mh, mxh);
						y += diffY;
						h -= diffY;
						x += diffX;
						w -= diffX;
						break;
					case 'southwest':
						diffX = this.constrain(w, diffX, mw, mxw);
						h += diffY;
						h = Math.min(Math.max(mh, h), mxh);
						x += diffX;
						w -= diffX;
						break;
				}

				var sw = this.snap(w, wi, mw);
				var sh = this.snap(h, hi, mh);
				if (sw != w || sh != h) {
					switch (pos) {
						case 'northeast':
							y -= sh - h;
							break;
						case 'north':
							y -= sh - h;
							break;
						case 'southwest':
							x -= sw - w;
							break;
						case 'west':
							x -= sw - w;
							break;
						case 'northwest':
							x -= sw - w;
							y -= sh - h;
							break;
					}
					w = sw;
					h = sh;
				}

				if (this.preserveRatio) {
					switch (pos) {
						case 'southeast':
						case 'east':
							h = oh * (w / ow);
							h = Math.min(Math.max(mh, h), mxh);
							w = ow * (h / oh);
							break;
						case 'south':
							w = ow * (h / oh);
							w = Math.min(Math.max(mw, w), mxw);
							h = oh * (w / ow);
							break;
						case 'northeast':
							w = ow * (h / oh);
							w = Math.min(Math.max(mw, w), mxw);
							h = oh * (w / ow);
							break;
						case 'north':
							tw = w;
							w = ow * (h / oh);
							w = Math.min(Math.max(mw, w), mxw);
							h = oh * (w / ow);
							x += (tw - w) / 2;
							break;
						case 'southwest':
							h = oh * (w / ow);
							h = Math.min(Math.max(mh, h), mxh);
							tw = w;
							w = ow * (h / oh);
							x += tw - w;
							break;
						case 'west':
							th = h;
							h = oh * (w / ow);
							h = Math.min(Math.max(mh, h), mxh);
							y += (th - h) / 2;
							tw = w;
							w = ow * (h / oh);
							x += tw - w;
							break;
						case 'northwest':
							tw = w;
							th = h;
							h = oh * (w / ow);
							h = Math.min(Math.max(mh, h), mxh);
							w = ow * (h / oh);
							y += th - h;
							x += tw - w;
							break;

					}
				}
				this.proxy.setBounds(x, y, w, h);
				if (this.dynamic) {
					this.resizeElement();
				}
			} catch (ex) { }
		}
	},

	// private
	handleOver: function () {
		if (this.enabled) {
			this.el.addClass('x-resizable-over');
		}
	},

	// private
	handleOut: function () {
		if (!this.resizing) {
			this.el.removeClass('x-resizable-over');
		}
	},

	/**
	* Returns the element this component is bound to.
	* @return {Ext.Element}
	*/
	getEl: function () {
		return this.el;
	},

	/**
	* Returns the resizeChild element (or null).
	* @return {Ext.Element}
	*/
	getResizeChild: function () {
		return this.resizeChild;
	},

	/**
	* Destroys this resizable. If the element was wrapped and
	* removeEl is not true then the element remains.
	* @param {Boolean} removeEl (optional) true to remove the element from the DOM
	*/
	destroy: function (removeEl) {
		Ext.destroy(this.dd, this.overlay, this.proxy);
		this.overlay = null;
		this.proxy = null;

		var ps = Ext.Resizable.positions;
		for (var k in ps) {
			if (typeof ps[k] != 'function' && this[ps[k]]) {
				this[ps[k]].destroy();
			}
		}
		if (removeEl) {
			this.el.update('');
			Ext.destroy(this.el);
			this.el = null;
		}
		this.purgeListeners();
	},

	syncHandleHeight: function () {
		var h = this.el.getHeight(true);
		if (this.west) {
			this.west.el.setHeight(h);
		}
		if (this.east) {
			this.east.el.setHeight(h);
		}
	}
});

// private
// hash to map config positions to true positions
Ext.Resizable.positions = {
	n: 'north', s: 'south', e: 'east', w: 'west', se: 'southeast', sw: 'southwest', nw: 'northwest', ne: 'northeast'
};

Ext.Resizable.Handle = Ext.extend(Object, {
	constructor: function (rz, pos, disableTrackOver, transparent, cls) {
		if (!this.tpl) {
			// only initialize the template if resizable is used
			var tpl = Ext.DomHelper.createTemplate(
                { tag: 'div', cls: 'x-resizable-handle x-resizable-handle-{0}' }
            );
			tpl.compile();
			Ext.Resizable.Handle.prototype.tpl = tpl;
		}
		this.position = pos;
		this.rz = rz;
		this.el = this.tpl.append(rz.el.dom, [this.position], true);
		this.el.unselectable();
		if (transparent) {
			this.el.setOpacity(0);
		}
		if (!Ext.isEmpty(cls)) {
			this.el.addClass(cls);
		}
		this.el.on('mousedown', this.onMouseDown, this);
		if (!disableTrackOver) {
			this.el.on({
				scope: this,
				mouseover: this.onMouseOver,
				mouseout: this.onMouseOut
			});
		}
	},

	// private
	afterResize: function (rz) {
		// do nothing
	},
	// private
	onMouseDown: function (e) {
		this.rz.onMouseDown(this, e);
	},
	// private
	onMouseOver: function (e) {
		this.rz.handleOver(this, e);
	},
	// private
	onMouseOut: function (e) {
		this.rz.handleOut(this, e);
	},
	// private
	destroy: function () {
		Ext.destroy(this.el);
		this.el = null;
	}
});
/**
* @class Ext.Window
* @extends Ext.Panel
* <p>A specialized panel intended for use as an application window.  Windows are floated, {@link #resizable}, and
* {@link #draggable} by default.  Windows can be {@link #maximizable maximized} to fill the viewport,
* restored to their prior size, and can be {@link #minimize}d.</p>
* <p>Windows can also be linked to a {@link Ext.WindowGroup} or managed by the {@link Ext.WindowMgr} to provide
* grouping, activation, to front, to back and other application-specific behavior.</p>
* <p>By default, Windows will be rendered to document.body. To {@link #constrain} a Window to another element
* specify {@link Ext.Component#renderTo renderTo}.</p>
* <p><b>Note:</b> By default, the <code>{@link #closable close}</code> header tool <i>destroys</i> the Window resulting in
* destruction of any child Components. This makes the Window object, and all its descendants <b>unusable</b>. To enable
* re-use of a Window, use <b><code>{@link #closeAction closeAction: 'hide'}</code></b>.</p>
* @constructor
* @param {Object} config The config object
* @xtype window
*/
Ext.Window = Ext.extend(Ext.Panel, {
	/**
	* @cfg {Number} x
	* The X position of the left edge of the window on initial showing. Defaults to centering the Window within
	* the width of the Window's container {@link Ext.Element Element) (The Element that the Window is rendered to).
	*/
	/**
	* @cfg {Number} y
	* The Y position of the top edge of the window on initial showing. Defaults to centering the Window within
	* the height of the Window's container {@link Ext.Element Element) (The Element that the Window is rendered to).
	*/
	/**
	* @cfg {Boolean} modal
	* True to make the window modal and mask everything behind it when displayed, false to display it without
	* restricting access to other UI elements (defaults to false).
	*/
	/**
	* @cfg {String/Element} animateTarget
	* Id or element from which the window should animate while opening (defaults to null with no animation).
	*/
	/**
	* @cfg {String} resizeHandles
	* A valid {@link Ext.Resizable} handles config string (defaults to 'all').  Only applies when resizable = true.
	*/
	/**
	* @cfg {Ext.WindowGroup} manager
	* A reference to the WindowGroup that should manage this window (defaults to {@link Ext.WindowMgr}).
	*/
	/**
	* @cfg {String/Number/Component} defaultButton
	* <p>Specifies a Component to receive focus when this Window is focussed.</p>
	* <p>This may be one of:</p><div class="mdetail-params"><ul>
	* <li>The index of a footer Button.</li>
	* <li>The id of a Component.</li>
	* <li>A Component.</li>
	* </ul></div>
	*/
	/**
	* @cfg {Function} onEsc
	* Allows override of the built-in processing for the escape key. Default action
	* is to close the Window (performing whatever action is specified in {@link #closeAction}.
	* To prevent the Window closing when the escape key is pressed, specify this as
	* Ext.emptyFn (See {@link Ext#emptyFn}).
	*/
	/**
	* @cfg {Boolean} collapsed
	* True to render the window collapsed, false to render it expanded (defaults to false). Note that if
	* {@link #expandOnShow} is true (the default) it will override the <tt>collapsed</tt> config and the window
	* will always be expanded when shown.
	*/
	/**
	* @cfg {Boolean} maximized
	* True to initially display the window in a maximized state. (Defaults to false).
	*/

	/**
	* @cfg {String} baseCls
	* The base CSS class to apply to this panel's element (defaults to 'x-window').
	*/
	baseCls: 'x-window',
	/**
	* @cfg {Boolean} resizable
	* True to allow user resizing at each edge and corner of the window, false to disable resizing (defaults to true).
	*/
	resizable: true,
	/**
	* @cfg {Boolean} draggable
	* True to allow the window to be dragged by the header bar, false to disable dragging (defaults to true).  Note
	* that by default the window will be centered in the viewport, so if dragging is disabled the window may need
	* to be positioned programmatically after render (e.g., myWindow.setPosition(100, 100);).
	*/
	draggable: true,
	/**
	* @cfg {Boolean} closable
	* <p>True to display the 'close' tool button and allow the user to close the window, false to
	* hide the button and disallow closing the window (defaults to true).</p>
	* <p>By default, when close is requested by either clicking the close button in the header
	* or pressing ESC when the Window has focus, the {@link #close} method will be called. This
	* will <i>{@link Ext.Component#destroy destroy}</i> the Window and its content meaning that
	* it may not be reused.</p>
	* <p>To make closing a Window <i>hide</i> the Window so that it may be reused, set
	* {@link #closeAction} to 'hide'.
	*/
	closable: true,
	/**
	* @cfg {String} closeAction
	* <p>The action to take when the close header tool is clicked:
	* <div class="mdetail-params"><ul>
	* <li><b><code>'{@link #close}'</code></b> : <b>Default</b><div class="sub-desc">
	* {@link #close remove} the window from the DOM and {@link Ext.Component#destroy destroy}
	* it and all descendant Components. The window will <b>not</b> be available to be
	* redisplayed via the {@link #show} method.
	* </div></li>
	* <li><b><code>'{@link #hide}'</code></b> : <div class="sub-desc">
	* {@link #hide} the window by setting visibility to hidden and applying negative offsets.
	* The window will be available to be redisplayed via the {@link #show} method.
	* </div></li>
	* </ul></div>
	* <p><b>Note:</b> This setting does not affect the {@link #close} method
	* which will always {@link Ext.Component#destroy destroy} the window. To
	* programatically <i>hide</i> a window, call {@link #hide}.</p>
	*/
	closeAction: 'close',
	/**
	* @cfg {Boolean} constrain
	* True to constrain the window within its containing element, false to allow it to fall outside of its
	* containing element. By default the window will be rendered to document.body.  To render and constrain the
	* window within another element specify {@link #renderTo}.
	* (defaults to false).  Optionally the header only can be constrained using {@link #constrainHeader}.
	*/
	constrain: false,
	/**
	* @cfg {Boolean} constrainHeader
	* True to constrain the window header within its containing element (allowing the window body to fall outside
	* of its containing element) or false to allow the header to fall outside its containing element (defaults to
	* false). Optionally the entire window can be constrained using {@link #constrain}.
	*/
	constrainHeader: false,
	/**
	* @cfg {Boolean} plain
	* True to render the window body with a transparent background so that it will blend into the framing
	* elements, false to add a lighter background color to visually highlight the body element and separate it
	* more distinctly from the surrounding frame (defaults to false).
	*/
	plain: false,
	/**
	* @cfg {Boolean} minimizable
	* True to display the 'minimize' tool button and allow the user to minimize the window, false to hide the button
	* and disallow minimizing the window (defaults to false).  Note that this button provides no implementation --
	* the behavior of minimizing a window is implementation-specific, so the minimize event must be handled and a
	* custom minimize behavior implemented for this option to be useful.
	*/
	minimizable: false,
	/**
	* @cfg {Boolean} maximizable
	* True to display the 'maximize' tool button and allow the user to maximize the window, false to hide the button
	* and disallow maximizing the window (defaults to false).  Note that when a window is maximized, the tool button
	* will automatically change to a 'restore' button with the appropriate behavior already built-in that will
	* restore the window to its previous size.
	*/
	maximizable: false,
	/**
	* @cfg {Number} minHeight
	* The minimum height in pixels allowed for this window (defaults to 100).  Only applies when resizable = true.
	*/
	minHeight: 100,
	/**
	* @cfg {Number} minWidth
	* The minimum width in pixels allowed for this window (defaults to 200).  Only applies when resizable = true.
	*/
	minWidth: 200,
	/**
	* @cfg {Boolean} expandOnShow
	* True to always expand the window when it is displayed, false to keep it in its current state (which may be
	* {@link #collapsed}) when displayed (defaults to true).
	*/
	expandOnShow: true,

	// inherited docs, same default
	collapsible: false,

	/**
	* @cfg {Boolean} initHidden
	* True to hide the window until show() is explicitly called (defaults to true).
	* @deprecated
	*/
	initHidden: undefined,

	/**
	* @cfg {Boolean} hidden
	* Render this component hidden (default is <tt>true</tt>). If <tt>true</tt>, the
	* {@link #hide} method will be called internally.
	*/
	hidden: true,

	// The following configs are set to provide the basic functionality of a window.
	// Changing them would require additional code to handle correctly and should
	// usually only be done in subclasses that can provide custom behavior.  Changing them
	// may have unexpected or undesirable results.
	/** @cfg {String} elements @hide */
	elements: 'header,body',
	/** @cfg {Boolean} frame @hide */
	frame: true,
	/** @cfg {Boolean} floating @hide */
	floating: true,

	// private
	initComponent: function () {
		this.initTools();
		Ext.Window.superclass.initComponent.call(this);
		this.addEvents(
		/**
		* @event activate
		* Fires after the window has been visually activated via {@link #setActive}.
		* @param {Ext.Window} this
		*/
		/**
		* @event deactivate
		* Fires after the window has been visually deactivated via {@link #setActive}.
		* @param {Ext.Window} this
		*/
		/**
		* @event resize
		* Fires after the window has been resized.
		* @param {Ext.Window} this
		* @param {Number} width The window's new width
		* @param {Number} height The window's new height
		*/
            'resize',
		/**
		* @event maximize
		* Fires after the window has been maximized.
		* @param {Ext.Window} this
		*/
            'maximize',
		/**
		* @event minimize
		* Fires after the window has been minimized.
		* @param {Ext.Window} this
		*/
            'minimize',
		/**
		* @event restore
		* Fires after the window has been restored to its original size after being maximized.
		* @param {Ext.Window} this
		*/
            'restore'
        );
		// for backwards compat, this should be removed at some point
		if (Ext.isDefined(this.initHidden)) {
			this.hidden = this.initHidden;
		}
		if (this.hidden === false) {
			this.hidden = true;
			this.show();
		}
	},

	// private
	getState: function () {
		return Ext.apply(Ext.Window.superclass.getState.call(this) || {}, this.getBox(true));
	},

	// private
	onRender: function (ct, position) {
		Ext.Window.superclass.onRender.call(this, ct, position);

		if (this.plain) {
			this.el.addClass('x-window-plain');
		}

		// this element allows the Window to be focused for keyboard events
		this.focusEl = this.el.createChild({
			tag: 'a', href: '#', cls: 'x-dlg-focus',
			tabIndex: '-1', html: '&#160;'
		});
		this.focusEl.swallowEvent('click', true);

		this.proxy = this.el.createProxy('x-window-proxy');
		this.proxy.enableDisplayMode('block');

		if (this.modal) {
			this.mask = this.container.createChild({ cls: 'ext-el-mask' }, this.el.dom);
			this.mask.enableDisplayMode('block');
			this.mask.hide();
			this.mon(this.mask, 'click', this.focus, this);
		}
		if (this.maximizable) {
			this.mon(this.header, 'dblclick', this.toggleMaximize, this);
		}
	},

	// private
	initEvents: function () {
		Ext.Window.superclass.initEvents.call(this);
		if (this.animateTarget) {
			this.setAnimateTarget(this.animateTarget);
		}

		if (this.resizable) {
			this.resizer = new Ext.Resizable(this.el, {
				minWidth: this.minWidth,
				minHeight: this.minHeight,
				handles: this.resizeHandles || 'all',
				pinned: true,
				resizeElement: this.resizerAction,
				handleCls: 'x-window-handle'
			});
			this.resizer.window = this;
			this.mon(this.resizer, 'beforeresize', this.beforeResize, this);
		}

		if (this.draggable) {
			this.header.addClass('x-window-draggable');
		}
		this.mon(this.el, 'mousedown', this.toFront, this);
		this.manager = this.manager || Ext.WindowMgr;
		this.manager.register(this);
		if (this.maximized) {
			this.maximized = false;
			this.maximize();
		}
		if (this.closable) {
			var km = this.getKeyMap();
			km.on(27, this.onEsc, this);
			km.disable();
		}
	},

	initDraggable: function () {
		/**
		* <p>If this Window is configured {@link #draggable}, this property will contain
		* an instance of {@link Ext.dd.DD} which handles dragging the Window's DOM Element.</p>
		* <p>This has implementations of <code>startDrag</code>, <code>onDrag</code> and <code>endDrag</code>
		* which perform the dragging action. If extra logic is needed at these points, use
		* {@link Function#createInterceptor createInterceptor} or {@link Function#createSequence createSequence} to
		* augment the existing implementations.</p>
		* @type Ext.dd.DD
		* @property dd
		*/
		this.dd = new Ext.Window.DD(this);
	},

	// private
	onEsc: function (k, e) {
		e.stopEvent();
		this[this.closeAction]();
	},

	// private
	beforeDestroy: function () {
		if (this.rendered) {
			this.hide();
			this.clearAnchor();
			Ext.destroy(
                this.focusEl,
                this.resizer,
                this.dd,
                this.proxy,
                this.mask
            );
		}
		Ext.Window.superclass.beforeDestroy.call(this);
	},

	// private
	onDestroy: function () {
		if (this.manager) {
			this.manager.unregister(this);
		}
		Ext.Window.superclass.onDestroy.call(this);
	},

	// private
	initTools: function () {
		if (this.minimizable) {
			this.addTool({
				id: 'minimize',
				handler: this.minimize.createDelegate(this, [])
			});
		}
		if (this.maximizable) {
			this.addTool({
				id: 'maximize',
				handler: this.maximize.createDelegate(this, [])
			});
			this.addTool({
				id: 'restore',
				handler: this.restore.createDelegate(this, []),
				hidden: true
			});
		}
		if (this.closable) {
			this.addTool({
				id: 'close',
				handler: this[this.closeAction].createDelegate(this, [])
			});
		}
	},

	// private
	resizerAction: function () {
		var box = this.proxy.getBox();
		this.proxy.hide();
		this.window.handleResize(box);
		return box;
	},

	// private
	beforeResize: function () {
		this.resizer.minHeight = Math.max(this.minHeight, this.getFrameHeight() + 40); // 40 is a magic minimum content size?
		this.resizer.minWidth = Math.max(this.minWidth, this.getFrameWidth() + 40);
		this.resizeBox = this.el.getBox();
	},

	// private
	updateHandles: function () {
		if (Ext.isIE && this.resizer) {
			this.resizer.syncHandleHeight();
			this.el.repaint();
		}
	},

	// private
	handleResize: function (box) {
		var rz = this.resizeBox;
		if (rz.x != box.x || rz.y != box.y) {
			this.updateBox(box);
		} else {
			this.setSize(box);
			if (Ext.isIE6 && Ext.isStrict) {
				this.doLayout();
			}
		}
		this.focus();
		this.updateHandles();
		this.saveState();
	},

	/**
	* Focuses the window.  If a defaultButton is set, it will receive focus, otherwise the
	* window itself will receive focus.
	*/
	focus: function () {
		var f = this.focusEl,
            db = this.defaultButton,
            t = typeof db,
            el,
            ct;
		if (Ext.isDefined(db)) {
			if (Ext.isNumber(db) && this.fbar) {
				f = this.fbar.items.get(db);
			} else if (Ext.isString(db)) {
				f = Ext.getCmp(db);
			} else {
				f = db;
			}
			el = f.getEl();
			ct = Ext.getDom(this.container);
			if (el && ct) {
				if (!Ext.lib.Region.getRegion(ct).contains(Ext.lib.Region.getRegion(el.dom))) {
					return;
				}
			}
		}
		f = f || this.focusEl;
		f.focus.defer(10, f);
	},

	/**
	* Sets the target element from which the window should animate while opening.
	* @param {String/Element} el The target element or id
	*/
	setAnimateTarget: function (el) {
		el = Ext.get(el);
		this.animateTarget = el;
	},

	// private
	beforeShow: function () {
		delete this.el.lastXY;
		delete this.el.lastLT;
		if (this.x === undefined || this.y === undefined) {
			var xy = this.el.getAlignToXY(this.container, 'c-c');
			var pos = this.el.translatePoints(xy[0], xy[1]);
			this.x = this.x === undefined ? pos.left : this.x;
			this.y = this.y === undefined ? pos.top : this.y;
		}
		this.el.setLeftTop(this.x, this.y);

		if (this.expandOnShow) {
			this.expand(false);
		}

		if (this.modal) {
			Ext.getBody().addClass('x-body-masked');
			this.mask.setSize(Ext.lib.Dom.getViewWidth(true), Ext.lib.Dom.getViewHeight(true));
			this.mask.show();
		}
	},

	/**
	* Shows the window, rendering it first if necessary, or activates it and brings it to front if hidden.
	* @param {String/Element} animateTarget (optional) The target element or id from which the window should
	* animate while opening (defaults to null with no animation)
	* @param {Function} callback (optional) A callback function to call after the window is displayed
	* @param {Object} scope (optional) The scope (<code>this</code> reference) in which the callback is executed. Defaults to this Window.
	* @return {Ext.Window} this
	*/
	show: function (animateTarget, cb, scope) {
		if (!this.rendered) {
			this.render(Ext.getBody());
		}
		if (this.hidden === false) {
			this.toFront();
			return this;
		}
		if (this.fireEvent('beforeshow', this) === false) {
			return this;
		}
		if (cb) {
			this.on('show', cb, scope, { single: true });
		}
		this.hidden = false;
		if (Ext.isDefined(animateTarget)) {
			this.setAnimateTarget(animateTarget);
		}
		this.beforeShow();
		if (this.animateTarget) {
			this.animShow();
		} else {
			this.afterShow();
		}
		return this;
	},

	// private
	afterShow: function (isAnim) {
		if (this.isDestroyed) {
			return false;
		}
		this.proxy.hide();
		this.el.setStyle('display', 'block');
		this.el.show();
		if (this.maximized) {
			this.fitContainer();
		}
		if (Ext.isMac && Ext.isGecko2) { // work around stupid FF 2.0/Mac scroll bar bug
			this.cascade(this.setAutoScroll);
		}

		if (this.monitorResize || this.modal || this.constrain || this.constrainHeader) {
			Ext.EventManager.onWindowResize(this.onWindowResize, this);
		}
		this.doConstrain();
		this.doLayout();
		if (this.keyMap) {
			this.keyMap.enable();
		}
		this.toFront();
		this.updateHandles();
		if (isAnim && (Ext.isIE || Ext.isWebKit)) {
			var sz = this.getSize();
			this.onResize(sz.width, sz.height);
		}
		this.onShow();
		this.fireEvent('show', this);
	},

	// private
	animShow: function () {
		this.proxy.show();
		this.proxy.setBox(this.animateTarget.getBox());
		this.proxy.setOpacity(0);
		var b = this.getBox();
		this.el.setStyle('display', 'none');
		this.proxy.shift(Ext.apply(b, {
			callback: this.afterShow.createDelegate(this, [true], false),
			scope: this,
			easing: 'easeNone',
			duration: 0.25,
			opacity: 0.5
		}));
	},

	/**
	* Hides the window, setting it to invisible and applying negative offsets.
	* @param {String/Element} animateTarget (optional) The target element or id to which the window should
	* animate while hiding (defaults to null with no animation)
	* @param {Function} callback (optional) A callback function to call after the window is hidden
	* @param {Object} scope (optional) The scope (<code>this</code> reference) in which the callback is executed. Defaults to this Window.
	* @return {Ext.Window} this
	*/
	hide: function (animateTarget, cb, scope) {
		if (this.hidden || this.fireEvent('beforehide', this) === false) {
			return this;
		}
		if (cb) {
			this.on('hide', cb, scope, { single: true });
		}
		this.hidden = true;
		if (animateTarget !== undefined) {
			this.setAnimateTarget(animateTarget);
		}
		if (this.modal) {
			this.mask.hide();
			Ext.getBody().removeClass('x-body-masked');
		}
		if (this.animateTarget) {
			this.animHide();
		} else {
			this.el.hide();
			this.afterHide();
		}
		return this;
	},

	// private
	afterHide: function () {
		this.proxy.hide();
		if (this.monitorResize || this.modal || this.constrain || this.constrainHeader) {
			Ext.EventManager.removeResizeListener(this.onWindowResize, this);
		}
		if (this.keyMap) {
			this.keyMap.disable();
		}
		this.onHide();
		this.fireEvent('hide', this);
	},

	// private
	animHide: function () {
		this.proxy.setOpacity(0.5);
		this.proxy.show();
		var tb = this.getBox(false);
		this.proxy.setBox(tb);
		this.el.hide();
		this.proxy.shift(Ext.apply(this.animateTarget.getBox(), {
			callback: this.afterHide,
			scope: this,
			duration: 0.25,
			easing: 'easeNone',
			opacity: 0
		}));
	},

	/**
	* Method that is called immediately before the <code>show</code> event is fired.
	* Defaults to <code>Ext.emptyFn</code>.
	*/
	onShow: Ext.emptyFn,

	/**
	* Method that is called immediately before the <code>hide</code> event is fired.
	* Defaults to <code>Ext.emptyFn</code>.
	*/
	onHide: Ext.emptyFn,

	// private
	onWindowResize: function () {
		if (this.maximized) {
			this.fitContainer();
		}
		if (this.modal) {
			this.mask.setSize('100%', '100%');
			var force = this.mask.dom.offsetHeight;
			this.mask.setSize(Ext.lib.Dom.getViewWidth(true), Ext.lib.Dom.getViewHeight(true));
		}
		this.doConstrain();
	},

	// private
	doConstrain: function () {
		if (this.constrain || this.constrainHeader) {
			var offsets;
			if (this.constrain) {
				offsets = {
					right: this.el.shadowOffset,
					left: this.el.shadowOffset,
					bottom: this.el.shadowOffset
				};
			} else {
				var s = this.getSize();
				offsets = {
					right: -(s.width - 100),
					bottom: -(s.height - 25)
				};
			}

			var xy = this.el.getConstrainToXY(this.container, true, offsets);
			if (xy) {
				this.setPosition(xy[0], xy[1]);
			}
		}
	},

	// private - used for dragging
	ghost: function (cls) {
		var ghost = this.createGhost(cls);
		var box = this.getBox(true);
		ghost.setLeftTop(box.x, box.y);
		ghost.setWidth(box.width);
		this.el.hide();
		this.activeGhost = ghost;
		return ghost;
	},

	// private
	unghost: function (show, matchPosition) {
		if (!this.activeGhost) {
			return;
		}
		if (show !== false) {
			this.el.show();
			this.focus.defer(10, this);
			if (Ext.isMac && Ext.isGecko2) { // work around stupid FF 2.0/Mac scroll bar bug
				this.cascade(this.setAutoScroll);
			}
		}
		if (matchPosition !== false) {
			this.setPosition(this.activeGhost.getLeft(true), this.activeGhost.getTop(true));
		}
		this.activeGhost.hide();
		this.activeGhost.remove();
		delete this.activeGhost;
	},

	/**
	* Placeholder method for minimizing the window.  By default, this method simply fires the {@link #minimize} event
	* since the behavior of minimizing a window is application-specific.  To implement custom minimize behavior,
	* either the minimize event can be handled or this method can be overridden.
	* @return {Ext.Window} this
	*/
	minimize: function () {
		this.fireEvent('minimize', this);
		return this;
	},

	/**
	* <p>Closes the Window, removes it from the DOM, {@link Ext.Component#destroy destroy}s
	* the Window object and all its descendant Components. The {@link Ext.Panel#beforeclose beforeclose}
	* event is fired before the close happens and will cancel the close action if it returns false.<p>
	* <p><b>Note:</b> This method is not affected by the {@link #closeAction} setting which
	* only affects the action triggered when clicking the {@link #closable 'close' tool in the header}.
	* To hide the Window without destroying it, call {@link #hide}.</p>
	*/
	close: function () {
		if (this.fireEvent('beforeclose', this) !== false) {
			if (this.hidden) {
				this.doClose();
			} else {
				this.hide(null, this.doClose, this);
			}
		}
	},

	// private
	doClose: function () {
		this.fireEvent('close', this);
		this.destroy();
	},

	/**
	* Fits the window within its current container and automatically replaces
	* the {@link #maximizable 'maximize' tool button} with the 'restore' tool button.
	* Also see {@link #toggleMaximize}.
	* @return {Ext.Window} this
	*/
	maximize: function () {
		if (!this.maximized) {
			this.expand(false);
			this.restoreSize = this.getSize();
			this.restorePos = this.getPosition(true);
			if (this.maximizable) {
				this.tools.maximize.hide();
				this.tools.restore.show();
			}
			this.maximized = true;
			this.el.disableShadow();

			if (this.dd) {
				this.dd.lock();
			}
			if (this.collapsible) {
				this.tools.toggle.hide();
			}
			this.el.addClass('x-window-maximized');
			this.container.addClass('x-window-maximized-ct');

			this.setPosition(0, 0);
			this.fitContainer();
			this.fireEvent('maximize', this);
		}
		return this;
	},

	/**
	* Restores a {@link #maximizable maximized}  window back to its original
	* size and position prior to being maximized and also replaces
	* the 'restore' tool button with the 'maximize' tool button.
	* Also see {@link #toggleMaximize}.
	* @return {Ext.Window} this
	*/
	restore: function () {
		if (this.maximized) {
			var t = this.tools;
			this.el.removeClass('x-window-maximized');
			if (t.restore) {
				t.restore.hide();
			}
			if (t.maximize) {
				t.maximize.show();
			}
			this.setPosition(this.restorePos[0], this.restorePos[1]);
			this.setSize(this.restoreSize.width, this.restoreSize.height);
			delete this.restorePos;
			delete this.restoreSize;
			this.maximized = false;
			this.el.enableShadow(true);

			if (this.dd) {
				this.dd.unlock();
			}
			if (this.collapsible && t.toggle) {
				t.toggle.show();
			}
			this.container.removeClass('x-window-maximized-ct');

			this.doConstrain();
			this.fireEvent('restore', this);
		}
		return this;
	},

	/**
	* A shortcut method for toggling between {@link #maximize} and {@link #restore} based on the current maximized
	* state of the window.
	* @return {Ext.Window} this
	*/
	toggleMaximize: function () {
		return this[this.maximized ? 'restore' : 'maximize']();
	},

	// private
	fitContainer: function () {
		var vs = this.container.getViewSize(false);
		this.setSize(vs.width, vs.height);
	},

	// private
	// z-index is managed by the WindowManager and may be overwritten at any time
	setZIndex: function (index) {
		if (this.modal) {
			this.mask.setStyle('z-index', index);
		}
		this.el.setZIndex(++index);
		index += 5;

		if (this.resizer) {
			this.resizer.proxy.setStyle('z-index', ++index);
		}

		this.lastZIndex = index;
	},

	/**
	* Aligns the window to the specified element
	* @param {Mixed} element The element to align to.
	* @param {String} position (optional, defaults to "tl-bl?") The position to align to (see {@link Ext.Element#alignTo} for more details).
	* @param {Array} offsets (optional) Offset the positioning by [x, y]
	* @return {Ext.Window} this
	*/
	alignTo: function (element, position, offsets) {
		var xy = this.el.getAlignToXY(element, position, offsets);
		this.setPagePosition(xy[0], xy[1]);
		return this;
	},

	/**
	* Anchors this window to another element and realigns it when the window is resized or scrolled.
	* @param {Mixed} element The element to align to.
	* @param {String} position The position to align to (see {@link Ext.Element#alignTo} for more details)
	* @param {Array} offsets (optional) Offset the positioning by [x, y]
	* @param {Boolean/Number} monitorScroll (optional) true to monitor body scroll and reposition. If this parameter
	* is a number, it is used as the buffer delay (defaults to 50ms).
	* @return {Ext.Window} this
	*/
	anchorTo: function (el, alignment, offsets, monitorScroll) {
		this.clearAnchor();
		this.anchorTarget = {
			el: el,
			alignment: alignment,
			offsets: offsets
		};

		Ext.EventManager.onWindowResize(this.doAnchor, this);
		var tm = typeof monitorScroll;
		if (tm != 'undefined') {
			Ext.EventManager.on(window, 'scroll', this.doAnchor, this,
                { buffer: tm == 'number' ? monitorScroll : 50 });
		}
		return this.doAnchor();
	},

	/**
	* Performs the anchor, using the saved anchorTarget property.
	* @return {Ext.Window} this
	* @private
	*/
	doAnchor: function () {
		var o = this.anchorTarget;
		this.alignTo(o.el, o.alignment, o.offsets);
		return this;
	},

	/**
	* Removes any existing anchor from this window. See {@link #anchorTo}.
	* @return {Ext.Window} this
	*/
	clearAnchor: function () {
		if (this.anchorTarget) {
			Ext.EventManager.removeResizeListener(this.doAnchor, this);
			Ext.EventManager.un(window, 'scroll', this.doAnchor, this);
			delete this.anchorTarget;
		}
		return this;
	},

	/**
	* Brings this window to the front of any other visible windows
	* @param {Boolean} e (optional) Specify <tt>false</tt> to prevent the window from being focused.
	* @return {Ext.Window} this
	*/
	toFront: function (e) {
		if (this.manager.bringToFront(this)) {
			if (!e || !e.getTarget().focus) {
				this.focus();
			}
		}
		return this;
	},

	/**
	* Makes this the active window by showing its shadow, or deactivates it by hiding its shadow.  This method also
	* fires the {@link #activate} or {@link #deactivate} event depending on which action occurred. This method is
	* called internally by {@link Ext.WindowMgr}.
	* @param {Boolean} active True to activate the window, false to deactivate it (defaults to false)
	*/
	setActive: function (active) {
		if (active) {
			if (!this.maximized) {
				this.el.enableShadow(true);
			}
			this.fireEvent('activate', this);
		} else {
			this.el.disableShadow();
			this.fireEvent('deactivate', this);
		}
	},

	/**
	* Sends this window to the back of (lower z-index than) any other visible windows
	* @return {Ext.Window} this
	*/
	toBack: function () {
		this.manager.sendToBack(this);
		return this;
	},

	/**
	* Centers this window in the viewport
	* @return {Ext.Window} this
	*/
	center: function () {
		var xy = this.el.getAlignToXY(this.container, 'c-c');
		this.setPagePosition(xy[0], xy[1]);
		return this;
	}

	/**
	* @cfg {Boolean} autoWidth @hide
	**/
});
Ext.reg('window', Ext.Window);

// private - custom Window DD implementation
Ext.Window.DD = function (win) {
	this.win = win;
	Ext.Window.DD.superclass.constructor.call(this, win.el.id, 'WindowDD-' + win.id);
	this.setHandleElId(win.header.id);
	this.scroll = false;
};

Ext.extend(Ext.Window.DD, Ext.dd.DD, {
	moveOnly: true,
	headerOffsets: [100, 25],
	startDrag: function () {
		var w = this.win;
		this.proxy = w.ghost();
		if (w.constrain !== false) {
			var so = w.el.shadowOffset;
			this.constrainTo(w.container, { right: so, left: so, bottom: so });
		} else if (w.constrainHeader !== false) {
			var s = this.proxy.getSize();
			this.constrainTo(w.container, { right: -(s.width - this.headerOffsets[0]), bottom: -(s.height - this.headerOffsets[1]) });
		}
	},
	b4Drag: Ext.emptyFn,

	onDrag: function (e) {
		this.alignElWithMouse(this.proxy, e.getPageX(), e.getPageY());
	},

	endDrag: function (e) {
		this.win.unghost();
		this.win.saveState();
	}
});
/**
* @class Ext.WindowGroup
* An object that manages a group of {@link Ext.Window} instances and provides z-order management
* and window activation behavior.
* @constructor
*/
Ext.WindowGroup = function () {
	var list = {};
	var accessList = [];
	var front = null;

	// private
	var sortWindows = function (d1, d2) {
		return (!d1._lastAccess || d1._lastAccess < d2._lastAccess) ? -1 : 1;
	};

	// private
	var orderWindows = function () {
		var a = accessList, len = a.length;
		if (len > 0) {
			a.sort(sortWindows);
			var seed = a[0].manager.zseed;
			for (var i = 0; i < len; i++) {
				var win = a[i];
				if (win && !win.hidden) {
					win.setZIndex(seed + (i * 10));
				}
			}
		}
		activateLast();
	};

	// private
	var setActiveWin = function (win) {
		if (win != front) {
			if (front) {
				front.setActive(false);
			}
			front = win;
			if (win) {
				win.setActive(true);
			}
		}
	};

	// private
	var activateLast = function () {
		for (var i = accessList.length - 1; i >= 0; --i) {
			if (!accessList[i].hidden) {
				setActiveWin(accessList[i]);
				return;
			}
		}
		// none to activate
		setActiveWin(null);
	};

	return {
		/**
		* The starting z-index for windows in this WindowGroup (defaults to 9000)
		* @type Number The z-index value
		*/
		zseed: 9000,

		/**
		* <p>Registers a {@link Ext.Window Window} with this WindowManager. This should not
		* need to be called under normal circumstances. Windows are automatically registered
		* with a {@link Ext.Window#manager manager} at construction time.</p>
		* <p>Where this may be useful is moving Windows between two WindowManagers. For example,
		* to bring the Ext.MessageBox dialog under the same manager as the Desktop's
		* WindowManager in the desktop sample app:</p><code><pre>
		var msgWin = Ext.MessageBox.getDialog();
		MyDesktop.getDesktop().getManager().register(msgWin);
		</pre></code>
		* @param {Window} win The Window to register.
		*/
		register: function (win) {
			if (win.manager) {
				win.manager.unregister(win);
			}
			win.manager = this;

			list[win.id] = win;
			accessList.push(win);
			win.on('hide', activateLast);
		},

		/**
		* <p>Unregisters a {@link Ext.Window Window} from this WindowManager. This should not
		* need to be called. Windows are automatically unregistered upon destruction.
		* See {@link #register}.</p>
		* @param {Window} win The Window to unregister.
		*/
		unregister: function (win) {
			delete win.manager;
			delete list[win.id];
			win.un('hide', activateLast);
			accessList.remove(win);
		},

		/**
		* Gets a registered window by id.
		* @param {String/Object} id The id of the window or a {@link Ext.Window} instance
		* @return {Ext.Window}
		*/
		get: function (id) {
			return typeof id == "object" ? id : list[id];
		},

		/**
		* Brings the specified window to the front of any other active windows in this WindowGroup.
		* @param {String/Object} win The id of the window or a {@link Ext.Window} instance
		* @return {Boolean} True if the dialog was brought to the front, else false
		* if it was already in front
		*/
		bringToFront: function (win) {
			win = this.get(win);
			if (win != front) {
				win._lastAccess = new Date().getTime();
				orderWindows();
				return true;
			}
			return false;
		},

		/**
		* Sends the specified window to the back of other active windows in this WindowGroup.
		* @param {String/Object} win The id of the window or a {@link Ext.Window} instance
		* @return {Ext.Window} The window
		*/
		sendToBack: function (win) {
			win = this.get(win);
			win._lastAccess = -(new Date().getTime());
			orderWindows();
			return win;
		},

		/**
		* Hides all windows in this WindowGroup.
		*/
		hideAll: function () {
			for (var id in list) {
				if (list[id] && typeof list[id] != "function" && list[id].isVisible()) {
					list[id].hide();
				}
			}
		},

		/**
		* Gets the currently-active window in this WindowGroup.
		* @return {Ext.Window} The active window
		*/
		getActive: function () {
			return front;
		},

		/**
		* Returns zero or more windows in this WindowGroup using the custom search function passed to this method.
		* The function should accept a single {@link Ext.Window} reference as its only argument and should
		* return true if the window matches the search criteria, otherwise it should return false.
		* @param {Function} fn The search function
		* @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to the Window being tested.
		* that gets passed to the function if not specified)
		* @return {Array} An array of zero or more matching windows
		*/
		getBy: function (fn, scope) {
			var r = [];
			for (var i = accessList.length - 1; i >= 0; --i) {
				var win = accessList[i];
				if (fn.call(scope || win, win) !== false) {
					r.push(win);
				}
			}
			return r;
		},

		/**
		* Executes the specified function once for every window in this WindowGroup, passing each
		* window as the only parameter. Returning false from the function will stop the iteration.
		* @param {Function} fn The function to execute for each item
		* @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to the current Window in the iteration.
		*/
		each: function (fn, scope) {
			for (var id in list) {
				if (list[id] && typeof list[id] != "function") {
					if (fn.call(scope || list[id], list[id]) === false) {
						return;
					}
				}
			}
		}
	};
};


/**
* @class Ext.WindowMgr
* @extends Ext.WindowGroup
* The default global window group that is available automatically.  To have more than one group of windows
* with separate z-order stacks, create additional instances of {@link Ext.WindowGroup} as needed.
* @singleton
*/
Ext.WindowMgr = new Ext.WindowGroup(); /**
 * @class Ext.MessageBox
 * <p>Utility class for generating different styles of message boxes.  The alias Ext.Msg can also be used.<p/>
 * <p>Note that the MessageBox is asynchronous.  Unlike a regular JavaScript <code>alert</code> (which will halt
 * browser execution), showing a MessageBox will not cause the code to stop.  For this reason, if you have code
 * that should only run <em>after</em> some user feedback from the MessageBox, you must use a callback function
 * (see the <code>function</code> parameter for {@link #show} for more details).</p>
 * <p>Example usage:</p>
 *<pre><code>
// Basic alert:
Ext.Msg.alert('Status', 'Changes saved successfully.');

// Prompt for user data and process the result using a callback:
Ext.Msg.prompt('Name', 'Please enter your name:', function(btn, text){
    if (btn == 'ok'){
        // process text value and close...
    }
});

// Show a dialog using config options:
Ext.Msg.show({
   title:'Save Changes?',
   msg: 'You are closing a tab that has unsaved changes. Would you like to save your changes?',
   buttons: Ext.Msg.YESNOCANCEL,
   fn: processResult,
   animEl: 'elId',
   icon: Ext.MessageBox.QUESTION
});
</code></pre>
 * @singleton
 */
Ext.MessageBox = function () {
	var dlg, opt, mask, waitTimer,
        bodyEl, msgEl, textboxEl, textareaEl, progressBar, pp, iconEl, spacerEl,
        buttons, activeTextEl, bwidth, bufferIcon = '', iconCls = '',
        buttonNames = ['ok', 'yes', 'no', 'cancel'];

	// private
	var handleButton = function (button) {
		buttons[button].blur();
		if (dlg.isVisible()) {
			dlg.hide();
			handleHide();
			Ext.callback(opt.fn, opt.scope || window, [button, activeTextEl.dom.value, opt], 1);
		}
	};

	// private
	var handleHide = function () {
		if (opt && opt.cls) {
			dlg.el.removeClass(opt.cls);
		}
		progressBar.reset();
	};

	// private
	var handleEsc = function (d, k, e) {
		if (opt && opt.closable !== false) {
			dlg.hide();
			handleHide();
		}
		if (e) {
			e.stopEvent();
		}
	};

	// private
	var updateButtons = function (b) {
		var width = 0,
            cfg;
		if (!b) {
			Ext.each(buttonNames, function (name) {
				buttons[name].hide();
			});
			return width;
		}
		dlg.footer.dom.style.display = '';
		Ext.iterate(buttons, function (name, btn) {
			cfg = b[name];
			if (cfg) {
				btn.show();
				btn.setText(Ext.isString(cfg) ? cfg : Ext.MessageBox.buttonText[name]);
				width += btn.getEl().getWidth() + 15;
			} else {
				btn.hide();
			}
		});
		return width;
	};

	return {
		/**
		* Returns a reference to the underlying {@link Ext.Window} element
		* @return {Ext.Window} The window
		*/
		getDialog: function (titleText) {
			if (!dlg) {
				var btns = [];

				buttons = {};
				Ext.each(buttonNames, function (name) {
					btns.push(buttons[name] = new Ext.Button({
						text: this.buttonText[name],
						handler: handleButton.createCallback(name),
						hideMode: 'offsets'
					}));
				}, this);
				dlg = new Ext.Window({
					autoCreate: true,
					title: titleText,
					resizable: false,
					constrain: true,
					constrainHeader: true,
					minimizable: false,
					maximizable: false,
					stateful: false,
					modal: true,
					shim: true,
					buttonAlign: "center",
					width: 400,
					height: 100,
					minHeight: 80,
					plain: true,
					footer: true,
					closable: true,
					close: function () {
						if (opt && opt.buttons && opt.buttons.no && !opt.buttons.cancel) {
							handleButton("no");
						} else {
							handleButton("cancel");
						}
					},
					fbar: new Ext.Toolbar({
						items: btns,
						enableOverflow: false
					})
				});
				dlg.render(document.body);
				dlg.getEl().addClass('x-window-dlg');
				mask = dlg.mask;
				bodyEl = dlg.body.createChild({
					html: '<div class="ext-mb-icon"></div><div class="ext-mb-content"><span class="ext-mb-text"></span><br /><div class="ext-mb-fix-cursor"><input type="text" class="ext-mb-input" /><textarea class="ext-mb-textarea"></textarea></div></div>'
				});
				iconEl = Ext.get(bodyEl.dom.firstChild);
				var contentEl = bodyEl.dom.childNodes[1];
				msgEl = Ext.get(contentEl.firstChild);
				textboxEl = Ext.get(contentEl.childNodes[2].firstChild);
				textboxEl.enableDisplayMode();
				textboxEl.addKeyListener([10, 13], function () {
					if (dlg.isVisible() && opt && opt.buttons) {
						if (opt.buttons.ok) {
							handleButton("ok");
						} else if (opt.buttons.yes) {
							handleButton("yes");
						}
					}
				});
				textareaEl = Ext.get(contentEl.childNodes[2].childNodes[1]);
				textareaEl.enableDisplayMode();
				progressBar = new Ext.ProgressBar({
					renderTo: bodyEl
				});
				bodyEl.createChild({ cls: 'x-clear' });
			}
			return dlg;
		},

		/**
		* Updates the message box body text
		* @param {String} text (optional) Replaces the message box element's innerHTML with the specified string (defaults to
		* the XHTML-compliant non-breaking space character '&amp;#160;')
		* @return {Ext.MessageBox} this
		*/
		updateText: function (text) {
			if (!dlg.isVisible() && !opt.width) {
				dlg.setSize(this.maxWidth, 100); // resize first so content is never clipped from previous shows
			}
			msgEl.update(text || '&#160;');

			var iw = iconCls != '' ? (iconEl.getWidth() + iconEl.getMargins('lr')) : 0,
                mw = msgEl.getWidth() + msgEl.getMargins('lr'),
                fw = dlg.getFrameWidth('lr'),
                bw = dlg.body.getFrameWidth('lr'),
                w;

			if (Ext.isIE && iw > 0) {
				//3 pixels get subtracted in the icon CSS for an IE margin issue,
				//so we have to add it back here for the overall width to be consistent
				iw += 3;
			}
			w = Math.max(Math.min(opt.width || iw + mw + fw + bw, opt.maxWidth || this.maxWidth),
                    Math.max(opt.minWidth || this.minWidth, bwidth || 0));

			if (opt.prompt === true) {
				activeTextEl.setWidth(w - iw - fw - bw);
			}
			if (opt.progress === true || opt.wait === true) {
				progressBar.setSize(w - iw - fw - bw);
			}
			if (Ext.isIE && w == bwidth) {
				w += 4; //Add offset when the content width is smaller than the buttons.    
			}
			dlg.setSize(w, 'auto').center();
			return this;
		},

		/**
		* Updates a progress-style message box's text and progress bar. Only relevant on message boxes
		* initiated via {@link Ext.MessageBox#progress} or {@link Ext.MessageBox#wait},
		* or by calling {@link Ext.MessageBox#show} with progress: true.
		* @param {Number} value Any number between 0 and 1 (e.g., .5, defaults to 0)
		* @param {String} progressText The progress text to display inside the progress bar (defaults to '')
		* @param {String} msg The message box's body text is replaced with the specified string (defaults to undefined
		* so that any existing body text will not get overwritten by default unless a new value is passed in)
		* @return {Ext.MessageBox} this
		*/
		updateProgress: function (value, progressText, msg) {
			progressBar.updateProgress(value, progressText);
			if (msg) {
				this.updateText(msg);
			}
			return this;
		},

		/**
		* Returns true if the message box is currently displayed
		* @return {Boolean} True if the message box is visible, else false
		*/
		isVisible: function () {
			return dlg && dlg.isVisible();
		},

		/**
		* Hides the message box if it is displayed
		* @return {Ext.MessageBox} this
		*/
		hide: function () {
			var proxy = dlg ? dlg.activeGhost : null;
			if (this.isVisible() || proxy) {
				dlg.hide();
				handleHide();
				if (proxy) {
					// unghost is a private function, but i saw no better solution
					// to fix the locking problem when dragging while it closes
					dlg.unghost(false, false);
				}
			}
			return this;
		},

		/**
		* Displays a new message box, or reinitializes an existing message box, based on the config options
		* passed in. All display functions (e.g. prompt, alert, etc.) on MessageBox call this function internally,
		* although those calls are basic shortcuts and do not support all of the config options allowed here.
		* @param {Object} config The following config options are supported: <ul>
		* <li><b>animEl</b> : String/Element<div class="sub-desc">An id or Element from which the message box should animate as it
		* opens and closes (defaults to undefined)</div></li>
		* <li><b>buttons</b> : Object/Boolean<div class="sub-desc">A button config object (e.g., Ext.MessageBox.OKCANCEL or {ok:'Foo',
		* cancel:'Bar'}), or false to not show any buttons (defaults to false)</div></li>
		* <li><b>closable</b> : Boolean<div class="sub-desc">False to hide the top-right close button (defaults to true). Note that
		* progress and wait dialogs will ignore this property and always hide the close button as they can only
		* be closed programmatically.</div></li>
		* <li><b>cls</b> : String<div class="sub-desc">A custom CSS class to apply to the message box's container element</div></li>
		* <li><b>defaultTextHeight</b> : Number<div class="sub-desc">The default height in pixels of the message box's multiline textarea
		* if displayed (defaults to 75)</div></li>
		* <li><b>fn</b> : Function<div class="sub-desc">A callback function which is called when the dialog is dismissed either
		* by clicking on the configured buttons, or on the dialog close button, or by pressing
		* the return button to enter input.
		* <p>Progress and wait dialogs will ignore this option since they do not respond to user
		* actions and can only be closed programmatically, so any required function should be called
		* by the same code after it closes the dialog. Parameters passed:<ul>
		* <li><b>buttonId</b> : String<div class="sub-desc">The ID of the button pressed, one of:<div class="sub-desc"><ul>
		* <li><tt>ok</tt></li>
		* <li><tt>yes</tt></li>
		* <li><tt>no</tt></li>
		* <li><tt>cancel</tt></li>
		* </ul></div></div></li>
		* <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.MessageBox">prompt</a></tt>
		* or <tt><a href="#show-option-multiline" ext:member="show-option-multiline" ext:cls="Ext.MessageBox">multiline</a></tt> is true</div></li>
		* <li><b>opt</b> : Object<div class="sub-desc">The config object passed to show.</div></li>
		* </ul></p></div></li>
		* <li><b>scope</b> : Object<div class="sub-desc">The scope of the callback function</div></li>
		* <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
		* dialog (e.g. Ext.MessageBox.WARNING or 'custom-class') (defaults to '')</div></li>
		* <li><b>iconCls</b> : String<div class="sub-desc">The standard {@link Ext.Window#iconCls} to
		* add an optional header icon (defaults to '')</div></li>
		* <li><b>maxWidth</b> : Number<div class="sub-desc">The maximum width in pixels of the message box (defaults to 600)</div></li>
		* <li><b>minWidth</b> : Number<div class="sub-desc">The minimum width in pixels of the message box (defaults to 100)</div></li>
		* <li><b>modal</b> : Boolean<div class="sub-desc">False to allow user interaction with the page while the message box is
		* displayed (defaults to true)</div></li>
		* <li><b>msg</b> : String<div class="sub-desc">A string that will replace the existing message box body text (defaults to the
		* XHTML-compliant non-breaking space character '&amp;#160;')</div></li>
		* <li><a id="show-option-multiline"></a><b>multiline</b> : Boolean<div class="sub-desc">
		* True to prompt the user to enter multi-line text (defaults to false)</div></li>
		* <li><b>progress</b> : Boolean<div class="sub-desc">True to display a progress bar (defaults to false)</div></li>
		* <li><b>progressText</b> : String<div class="sub-desc">The text to display inside the progress bar if progress = true (defaults to '')</div></li>
		* <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>
		* <li><b>proxyDrag</b> : Boolean<div class="sub-desc">True to display a lightweight proxy while dragging (defaults to false)</div></li>
		* <li><b>title</b> : String<div class="sub-desc">The title text</div></li>
		* <li><b>value</b> : String<div class="sub-desc">The string value to set into the active textbox element if displayed</div></li>
		* <li><b>wait</b> : Boolean<div class="sub-desc">True to display a progress bar (defaults to false)</div></li>
		* <li><b>waitConfig</b> : Object<div class="sub-desc">A {@link Ext.ProgressBar#waitConfig} object (applies only if wait = true)</div></li>
		* <li><b>width</b> : Number<div class="sub-desc">The width of the dialog in pixels</div></li>
		* </ul>
		* Example usage:
		* <pre><code>
		Ext.Msg.show({
		title: 'Address',
		msg: 'Please enter your address:',
		width: 300,
		buttons: Ext.MessageBox.OKCANCEL,
		multiline: true,
		fn: saveAddress,
		animEl: 'addAddressBtn',
		icon: Ext.MessageBox.INFO
		});
		</code></pre>
		* @return {Ext.MessageBox} this
		*/
		show: function (options) {
			if (this.isVisible()) {
				this.hide();
			}
			opt = options;
			var d = this.getDialog(opt.title || "&#160;");

			d.setTitle(opt.title || "&#160;");
			var allowClose = (opt.closable !== false && opt.progress !== true && opt.wait !== true);
			d.tools.close.setDisplayed(allowClose);
			activeTextEl = textboxEl;
			opt.prompt = opt.prompt || (opt.multiline ? true : false);
			if (opt.prompt) {
				if (opt.multiline) {
					textboxEl.hide();
					textareaEl.show();
					textareaEl.setHeight(Ext.isNumber(opt.multiline) ? opt.multiline : this.defaultTextHeight);
					activeTextEl = textareaEl;
				} else {
					textboxEl.show();
					textareaEl.hide();
				}
			} else {
				textboxEl.hide();
				textareaEl.hide();
			}
			activeTextEl.dom.value = opt.value || "";
			if (opt.prompt) {
				d.focusEl = activeTextEl;
			} else {
				var bs = opt.buttons;
				var db = null;
				if (bs && bs.ok) {
					db = buttons["ok"];
				} else if (bs && bs.yes) {
					db = buttons["yes"];
				}
				if (db) {
					d.focusEl = db;
				}
			}
			if (opt.iconCls) {
				d.setIconClass(opt.iconCls);
			}
			this.setIcon(Ext.isDefined(opt.icon) ? opt.icon : bufferIcon);
			bwidth = updateButtons(opt.buttons);
			progressBar.setVisible(opt.progress === true || opt.wait === true);
			this.updateProgress(0, opt.progressText);
			this.updateText(opt.msg);
			if (opt.cls) {
				d.el.addClass(opt.cls);
			}
			d.proxyDrag = opt.proxyDrag === true;
			d.modal = opt.modal !== false;
			d.mask = opt.modal !== false ? mask : false;
			if (!d.isVisible()) {
				// force it to the end of the z-index stack so it gets a cursor in FF
				document.body.appendChild(dlg.el.dom);
				d.setAnimateTarget(opt.animEl);
				//workaround for window internally enabling key
