X-Git-Url: http://git.ithinksw.org/extjs.git/blobdiff_plain/25ef3491bd9ae007ff1fc2b0d7943e6eaaccf775..0494b8d9b9bb03ab6c22b34dae81261e3cd7e3e6:/ext-all-debug.js diff --git a/ext-all-debug.js b/ext-all-debug.js index d38b19f1..00231c85 100644 --- a/ext-all-debug.js +++ b/ext-all-debug.js @@ -1,1871 +1,13 @@ -/*! - * Ext JS Library 3.0.3 - * Copyright(c) 2006-2009 Ext JS, LLC - * licensing@extjs.com - * http://www.extjs.com/license - */ -/** - * @class Ext.DomHelper - *

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.

- * - *

DomHelper element specification object

- *

A specification object is used when creating elements. Attributes of this object - * are assumed to be element attributes, except for 4 special attributes: - *

- * - *

Insertion methods

- *

Commonly used insertion methods: - *

- * - *

Example

- *

This is an example, where an unordered list with 3 children items is appended to an existing - * element with id 'my-div':
-


-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
-);
- 

- *

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:


-dh.append('my-ul', [
-    {tag: 'li', id: 'item3', html: 'List Item 3'},
-    {tag: 'li', id: 'item4', html: 'List Item 4'}
-]);
- * 

- * - *

Templating

- *

The real power is in the built-in templating. Instead of creating or appending any elements, - * {@link #createTemplate} 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: - *


-// 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
-}
- * 

- *

An example using a template:


-var html = '{2}';
-
-var tpl = new Ext.DomHelper.createTemplate(html);
-tpl.append('blog-roll', ['link1', 'http://www.jackslocum.com/', "Jack's Site"]);
-tpl.append('blog-roll', ['link2', 'http://www.dustindiaz.com/', "Dustin's Site"]);
- * 

- * - *

The same example using named parameters:


-var html = '{text}';
-
-var tpl = new Ext.DomHelper.createTemplate(html);
-tpl.append('blog-roll', {
-    id: 'link1',
-    url: 'http://www.jackslocum.com/',
-    text: "Jack's Site"
-});
-tpl.append('blog-roll', {
-    id: 'link2',
-    url: 'http://www.dustindiaz.com/',
-    text: "Dustin's Site"
-});
- * 

- * - *

Compiling Templates

- *

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. - *


-var html = '{text}';
-
-var tpl = new Ext.DomHelper.createTemplate(html);
-tpl.compile();
-
-//... use template like normal
- * 

- * - *

Performance Boost

- *

DomHelper will transparently create HTML fragments when it can. Using HTML fragments instead - * of DOM can significantly boost performance.

- *

Element creation specification parameters may also be strings. If {@link #useDom} is false, - * then the string is used as innerHTML. If {@link #useDom} is true, a string specification - * results in the creation of a text node. Usage:

- *

-Ext.DomHelper.useDom = true; // force it to use DOM; reduces performance
- * 
- * @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, - pub, - // kill repeat to save bytes - afterbegin = 'afterbegin', - afterend = 'afterend', - beforebegin = 'beforebegin', - beforeend = 'beforeend', - ts = '', - te = '
', - tbs = ts+'', - tbe = ''+te, - trs = tbs + '', - tre = ''+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(Ext.isString(o)){ - b = o; - } else if (Ext.isArray(o)) { - Ext.each(o, function(v) { - b += createHtml(v); - }); - } else { - b += '<' + (o.tag = o.tag || 'div'); - Ext.iterate(o, function(attr, val){ - if(!/tag|children|cn|html$/i.test(attr)){ - if (Ext.isObject(val)) { - b += ' ' + attr + '="'; - Ext.iterate(val, function(key, keyVal){ - b += key + ':' + keyVal + ';'; - }); - 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 += ''; - } - } - 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) || - !/td|tr|tbody/i.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; - - el = Ext.fly(el); - if(Ext.isFunction(styles)){ - styles = styles.call(); - } - if(Ext.isString(styles)){ - styles = styles.trim().split(/\s*(?::|;)\s*/); - for(len = styles.length; i < len;){ - el.setStyle(styles[i++], styles[i++]); - } - }else if (Ext.isObject(styles)){ - 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' + (/end/i.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'; - - // 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 - Ext.each(o, function(v) { - createDom(v, el); - }); - } else if (Ext.isString(o)) { // 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 - Ext.iterate(o, function(attr, val){ - if(!/tag|children|cn|html|style/.test(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 - *

Represents an HTML fragment template. Templates may be {@link #compile precompiled} - * for greater performance.

- *

For example usage {@link #Template see the constructor}.

- * - * @constructor - * An instance of this class may be created by passing to the constructor either - * a single argument, or multiple arguments: - *
- * @param {Mixed} config - */ -Ext.Template = function(html){ - var me = this, - a = arguments, - buf = []; - - if (Ext.isArray(html)) { - html = html.join(""); - } else if (a.length > 1) { - Ext.each(a, function(v) { - if (Ext.isObject(v)) { - Ext.apply(me, v); - } else { - buf.push(v); - } - }); - html = buf.join(''); - } - - /**@private*/ - me.html = html; - /** - * @cfg {Boolean} compiled Specify true to compile the template - * immediately (see {@link #compile}). - * Defaults to false. - */ - if (me.compiled) { - me.compile(); - } -}; -Ext.Template.prototype = { - /** - * @cfg {RegExp} re The regular expression used to match template variables. - * Defaults to:

-     * re : /\{([\w-]+)\}/g                                     // for Ext Core
-     * re : /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g      // for Ext JS
-     * 
- */ - re : /\{([\w-]+)\}/g, - /** - * See {@link #re}. - * @type RegExp - * @property re - */ - - /** - * Returns an HTML fragment of this template with the specified values applied. - * @param {Object/Array} values - * The template values. Can be an array if the params are numeric (i.e. {0}) - * or an object (i.e. {foo: 'bar'}). - * @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 values to the template and appends - * the new node(s) to the specified el. - *

For example usage {@link #Template see the constructor}.

- * @param {Mixed} el The context element - * @param {Object/Array} values - * The template values. Can be an array if the params are numeric (i.e. {0}) - * or an object (i.e. {foo: 'bar'}). - * @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 values applied. - * @param {Object/Array} values - * The template values. Can be an array if the params are numeric (i.e. {0}) - * or an object (i.e. {foo: 'bar'}). - * @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 (display:none 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 true to disable format - * functions in the template. If the template does not contain - * {@link Ext.util.Format format functions}, setting disableFormats - * to true will reduce {@link #apply} time. Defaults to false. - *

-var t = new Ext.Template(
-    '<div name="{id}">',
-        '<span class="{cls}">{name} {value}</span>',
-    '</div>',
-    {
-        compiled: true,      // {@link #compile} immediately
-        disableFormats: true // reduce {@link #apply} time since no formatting
-    }    
-);
-     * 
- * For a list of available format functions, see {@link Ext.util.Format}. - */ - disableFormats : false, - /** - * See {@link #disableFormats}. - * @type Boolean - * @property disableFormats - */ - - /** - * The regular expression used to match template variables - * @type RegExp - * @property - * @hide repeat doc - */ - re : /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/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 = /^\s*['"](.*)["']\s*$/; - 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(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) + - "';};"; - }else{ - body = ["this.compiled = function(values){ return ['"]; - body.push(me.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.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). -

-DomQuery supports most of the CSS3 selectors spec, along with some custom selectors and basic XPath.

- -

-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. -

-

Element Selectors:

- -

Attribute Selectors:

-

The use of @ and quotes are optional. For example, div[@foo='bar'] is also a valid attribute selector.

- -

Pseudo Classes:

- -

CSS Value Selectors:

- - * @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, - isOpera = Ext.isOpera, - key = 30803; - - // this eval is stop the compressor from - // renaming the variable to something shorter - eval("var batch = 30803;"); - - function child(p, index){ - var i = 0, - n = p.firstChild; - while(n){ - if(n.nodeType == 1){ - if(++i == index){ - return n; - } - } - n = n.nextSibling; - } - return null; - }; - - function next(n){ - while((n = n.nextSibling) && n.nodeType != 1); - return n; - }; - - function prev(n){ - while((n = n.previousSibling) && n.nodeType != 1); - return n; - }; - - function children(d){ - var n = d.firstChild, ni = -1, - nx; - while(n){ - nx = n.nextSibling; - if(n.nodeType == 3 && !nonSpace.test(n.nodeValue)){ - d.removeChild(n); - }else{ - n.nodeIndex = ++ni; - } - n = nx; - } - return this; - }; - - function byClassName(c, a, v){ - if(!v){ - return c; - } - var r = [], ri = -1, cn; - for(var i = 0, ci; ci = c[i]; i++){ - if((' '+ci.className+' ').indexOf(v) != -1){ - r[++ri] = ci; - } - } - return r; - }; - - function attrValue(n, attr){ - 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]; - - }; - - function getNodes(ns, mode, tagName){ - var result = [], ri = -1, cs; - if(!ns){ - return result; - } - tagName = tagName || "*"; - if(typeof ns.getElementsByTagName != "undefined"){ - ns = [ns]; - } - 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; - } - } - }else if(mode == "/" || mode == ">"){ - var utag = tagName.toUpperCase(); - for(var i = 0, ni, cn; ni = ns[i]; i++){ - cn = isOpera ? ni.childNodes : (ni.children || ni.childNodes); - for(var j = 0, cj; cj = cn[j]; j++){ - if(cj.nodeName == utag || cj.nodeName == tagName || tagName == '*'){ - result[++ri] = cj; - } - } - } - }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; - } - } - }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 r = [], ri = -1; - tagName = tagName.toLowerCase(); - for(var i = 0, ci; ci = cs[i]; i++){ - if(ci.nodeType == 1 && ci.tagName.toLowerCase()==tagName){ - r[++ri] = ci; - } - } - return r; - }; - - function byId(cs, attr, id){ - if(cs.tagName || cs == document){ - cs = [cs]; - } - if(!id){ - return cs; - } - var r = [], ri = -1; - for(var i = 0,ci; ci = cs[i]; i++){ - if(ci && ci.id == id){ - r[++ri] = ci; - return r; - } - } - return r; - }; - - function byAttribute(cs, attr, value, op, custom){ - var r = [], - ri = -1, - st = custom=="{", - f = Ext.DomQuery.operators[op]; - for(var i = 0, ci; ci = cs[i]; i++){ - if(ci.nodeType != 1){ - continue; - } - var a; - if(st){ - 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"){ - a = ci.getAttribute("href", 2); - }else{ - a = ci.getAttribute(attr); - } - if((f && f(a, value)) || (!f && a)){ - r[++ri] = ci; - } - } - return r; - }; - - 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 && c1[0].selectSingleNode){ - 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, null, 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"; - - var fn = ["var f = function(root){\n var mode; ++batch; var n = root || document;\n"], - q = path, mode, lq, - tk = Ext.DomQuery.matchers, - tklen = tk.length, - mm, - // accept leading mode switch - lmode = q.match(modeRe); - - if(lmode && lmode[1]){ - fn[fn.length] = 'mode="'+lmode[1].replace(trimRe, "")+'";'; - q = q.replace(lmode[1], ""); - } - // strip leading slashes - while(path.substr(0, 1)=="/"){ - path = path.substr(1); - } - - while(q && lq != q){ - lq = q; - var tm = q.match(tagTokenRe); - if(type == "select"){ - if(tm){ - if(tm[1] == "#"){ - fn[fn.length] = 'n = quickId(n, mode, root, "'+tm[2]+'");'; - }else{ - fn[fn.length] = 'n = getNodes(n, mode, "'+tm[2]+'");'; - } - q = q.replace(tm[0], ""); - }else if(q.substr(0, 1) != '@'){ - fn[fn.length] = 'n = getNodes(n, mode, "*");'; - } - }else{ - if(tm){ - if(tm[1] == "#"){ - fn[fn.length] = 'n = byId(n, null, "'+tm[2]+'");'; - }else{ - fn[fn.length] = 'n = byTag(n, "'+tm[2]+'");'; - } - q = q.replace(tm[0], ""); - } - } - while(!(mm = q.match(modeRe))){ - var matched = false; - for(var j = 0; j < tklen; j++){ - var t = tk[j]; - var m = q.match(t.re); - if(m){ - fn[fn.length] = t.select.replace(tplRe, function(x, i){ - return m[i]; - }); - q = q.replace(m[0], ""); - matched = true; - break; - } - } - // prevent infinite loop on bad selector - if(!matched){ - throw 'Error parsing selector, parsing failed at "' + q + '"'; - } - } - if(mm[1]){ - fn[fn.length] = 'mode="'+mm[1].replace(trimRe, "")+'";'; - q = q.replace(mm[1], ""); - } - } - fn[fn.length] = "return nodup(n);\n}"; - 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} 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. - */ - select : function(path, root, type){ - if(!root || root == document){ - root = document; - } - if(typeof root == "string"){ - root = document.getElementById(root); - } - var paths = path.split(","), - results = []; - for(var i = 0, len = paths.length; i < len; i++){ - var p = paths[i].replace(trimRe, ""); - if(!cache[p]){ - cache[p] = Ext.DomQuery.compile(p); - if(!cache[p]){ - throw p + " is not a valid selector"; - } - } - var result = cache[p](root); - if(result && result != document){ - results = results.concat(result); - } - } - if(paths.length > 1){ - return nodup(results); - } - return results; - }, - - /** - * 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; - 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. - */ - matchers : [{ - re: /^\.([\w-]+)/, - select: 'n = byClassName(n, null, " {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, null, "{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 c= where c is any character other than space, > <. - */ - 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; - } - }, - - /** - *

Object hash of "pseudo class" filter functions which are used when filtering selections. Each function is passed - * two parameters:

- *

A filter function returns an Array of DOM elements which conform to the pseudo class.

- *

In addition to the provided pseudo classes listed above such as first-child and nth-child, - * developers may add additional, custom psuedo class filters to select elements according to application-specific requirements.

- *

For example, to filter <a> elements to only return links to external resources:

- *
-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;
-};
- * Then external links could be gathered with the following statement:
-var externalLinks = Ext.select("a:external");
-
- */ - 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; (function(){ var EXTUTIL = Ext.util, - TOARRAY = Ext.toArray, EACH = Ext.each, - ISOBJECT = Ext.isObject, 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.
- * For example: - *

-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's
-        // constructor will add them.
-        this.listeners = config.listeners;
-
-        // Call our superclass constructor to complete construction process.
-        Employee.superclass.constructor.call(config)
-    }
-});
-
- * This could then be used like this:

-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!");
-        }
-    }
-});
-
- */ EXTUTIL.Observable = function(){ - /** - * @cfg {Object} listeners (optional)

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.

- *

DOM events from ExtJs {@link Ext.Component Components}

- *

While some 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 - * {@link Ext.DataView#click click} event passing the node clicked on. To access DOM - * events directly from a Component's HTMLElement, listeners must be added to the {@link Ext.Component#getEl Element} after the Component - * has been rendered. A plugin can simplify this step:


-// 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'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'
-});
-     * 

- */ + var me = this, e = me.events; if(me.listeners){ me.on(me.listeners); @@ -1875,23 +17,17 @@ var combo = new Ext.form.ComboBox({ }; EXTUTIL.Observable.prototype = { - // private + filterOptRe : /^(?:scope|delay|buffer|single)$/, - /** - *

Fires the specified event with the passed parameters (minus the event name).

- *

An event may be set to bubble up an Observable parent hierarchy (See {@link Ext.Component#getBubbleTarget}) - * by calling {@link #enableBubble}.

- * @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 = TOARRAY(arguments), + 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) { @@ -1899,20 +35,21 @@ EXTUTIL.Observable.prototype = { q.push(a); } } - else if(ISOBJECT(ce) && ce.bubble){ - if(ce.fire.apply(ce, a.slice(1)) === FALSE) { - return FALSE; - } - c = me.getBubbleTarget && me.getBubbleTarget(); - if(c && c.enableBubble) { - if(!c.events[ename] || !Ext.isObject(c.events[ename]) || !c.events[ename].bubble) { - c.enableBubble(ename); + 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); } - return c.fireEvent.apply(c, a); } - } - else { - if (ISOBJECT(ce)) { + else { a.shift(); ret = ce.fire.apply(ce, a); } @@ -1920,74 +57,16 @@ EXTUTIL.Observable.prototype = { 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 (this reference) in which the handler function is executed. - * If omitted, defaults to the object which fired the event. - * @param {Object} options (optional) An object containing handler configuration. - * properties. This may contain any of the following properties:
- *

- * Combining Options
- * Using the options argument, it is possible to combine different types of listeners:
- *
- * A delayed, one-time listener. - *


-myDataView.on('click', this.onClick, this, {
-single: true,
-delay: 100
-});
- *

- * Attaching multiple handlers in 1 call
- * The method also allows for a single argument to be passed which is a config object containing properties - * which specify multiple handlers. - *

- *


-myGridPanel.on({
-'click' : {
-    fn: this.onClick,
-    scope: this,
-    delay: 100
-},
-'mouseover' : {
-    fn: this.onMouseOver,
-    scope: this
-},
-'mouseout' : {
-    fn: this.onMouseOut,
-    scope: this
-}
-});
- *

- * Or a shorthand syntax:
- *


-myGridPanel.on({
-'click' : this.onClick,
-'mouseover' : this.onMouseOver,
-'mouseout' : this.onMouseOut,
- scope: this
-});
- */ + addListener : function(eventName, fn, scope, o){ var me = this, e, oe, - isF, - ce; - if (ISOBJECT(eventName)) { + ce; + + if (typeof eventName == 'object') { o = eventName; - for (e in o){ + 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); @@ -1996,77 +75,56 @@ myGridPanel.on({ } else { eventName = eventName.toLowerCase(); ce = me.events[eventName] || TRUE; - if (Ext.isBoolean(ce)) { + if (typeof ce == 'boolean') { me.events[eventName] = ce = new EXTUTIL.Event(me, eventName); } - ce.addListener(fn, scope, ISOBJECT(o) ? o : {}); + 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. This must be a reference to the function passed into the {@link #addListener} call. - * @param {Object} scope (optional) The scope originally specified for the handler. - */ + removeListener : function(eventName, fn, scope){ var ce = this.events[eventName.toLowerCase()]; - if (ISOBJECT(ce)) { + 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(ISOBJECT(evt)){ + 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 true - * 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:

-this.addEvents('storeloaded', 'storecleared');
-
- */ + addEvents : function(o){ var me = this; me.events = me.events || {}; - if (Ext.isString(o)) { - EACH(arguments, function(a) { - me.events[a] = me.events[a] || TRUE; - }); + 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]; - return ISOBJECT(e) && e.listeners.length > 0; + 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){ @@ -2074,11 +132,7 @@ this.addEvents('storeloaded', 'storecleared'); } }, - /** - * Resume firing events. (see {@link #suspendEvents}) - * If events were suspended using the queueSuspended parameter, then all - * events fired during event suspension will be sent to any listeners now. - */ + resumeEvents : function(){ var me = this, queued = me.eventQueue || []; @@ -2091,30 +145,12 @@ this.addEvents('storeloaded', 'storecleared'); }; 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 (this reference) in which the handler function is executed. - * If omitted, defaults to the object which fired the event. - * @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. This must be a reference to the function passed into the {@link #addListener} call. - * @param {Object} scope (optional) The scope originally specified for the handler. - * @method - */ + OBSERVABLE.un = OBSERVABLE.removeListener; -/** - * Removes all added captures from the Observable. - * @param {Observable} o The Observable to release - * @static - */ + EXTUTIL.Observable.releaseCapture = function(o){ o.fireEvent = OBSERVABLE.fireEvent; }; @@ -2122,31 +158,37 @@ EXTUTIL.Observable.releaseCapture = function(o){ function createTargeted(h, o, scope){ return function(){ if(o.target == arguments[0]){ - h.apply(scope, TOARRAY(arguments)); + h.apply(scope, Array.prototype.slice.call(arguments, 0)); } }; }; -function createBuffered(h, o, scope){ - var task = new EXTUTIL.DelayedTask(); +function createBuffered(h, o, l, scope){ + l.task = new EXTUTIL.DelayedTask(); return function(){ - task.delay(o.buffer, h, scope, TOARRAY(arguments)); + 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, scope){ +function createDelayed(h, o, l, scope){ return function(){ - var args = TOARRAY(arguments); - (function(){ + var task = new EXTUTIL.DelayedTask(), + args = Array.prototype.slice.call(arguments, 0); + if(!l.tasks) { + l.tasks = []; + } + l.tasks.push(task); + task.delay(o.delay || 10, function(){ + l.tasks.remove(task); h.apply(scope, args); - }).defer(o.delay || 10); + }, scope); }; }; @@ -2163,7 +205,7 @@ EXTUTIL.Event.prototype = { 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 + if(me.firing){ me.listeners = me.listeners.slice(0); } me.listeners.push(l); @@ -2171,7 +213,8 @@ EXTUTIL.Event.prototype = { }, createListener: function(fn, scope, o){ - o = o || {}, scope = scope || this.obj; + o = o || {}; + scope = scope || this.obj; var l = { fn: fn, scope: scope, @@ -2181,29 +224,33 @@ EXTUTIL.Event.prototype = { h = createTargeted(h, o, scope); } if(o.delay){ - h = createDelayed(h, o, scope); + h = createDelayed(h, o, l, scope); } if(o.single){ h = createSingle(h, this, fn, scope); } if(o.buffer){ - h = createBuffered(h, o, scope); + h = createBuffered(h, o, l, scope); } l.fireFn = h; return l; }, findListener : function(fn, scope){ - var s, ret = -1; - EACH(this.listeners, function(l, i) { - s = l.scope; - if(l.fn == fn && (s == scope || s == this.obj)){ - ret = i; - return FALSE; + 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; + } } - }, - this); - return ret; + } + return -1; }, isListening : function(fn, scope){ @@ -2212,65248 +259,50998 @@ EXTUTIL.Event.prototype = { 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; }, + clearListeners : function(){ - this.listeners = []; + var me = this, + l = me.listeners, + i = l.length; + while(i--) { + me.removeListener(l[i].fn, l[i].scope); + } }, fire : function(){ var me = this, - args = TOARRAY(arguments), - ret = TRUE; + listeners = me.listeners, + len = listeners.length, + i = 0, + l; - EACH(me.listeners, function(l) { + if(len > 0){ me.firing = TRUE; - if (l.fireFn.apply(l.scope || me.obj || window, args) === FALSE) { - return ret = me.firing = FALSE; + 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 ret; + 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 (!Ext.isEmpty(v = fn.apply(scope || obj, args))) { - if (Ext.isObject(v)) { - returnValue = !Ext.isEmpty(v.returnValue) ? v.returnValue : v; - cancel = !!v.cancel; - } - else - if (v === false) { - cancel = true; - } - else { - returnValue = v; - } - } - }; - - this[method] = function(){ - var args = Ext.toArray(arguments); - returnValue = v = undefined; - cancel = false; - - Ext.each(e.before, function(b){ - makeCall(b.fn, b.scope, args); - if (cancel) { - return returnValue; - } - }); - - if (!Ext.isEmpty(v = e.originalFn.apply(obj, args))) { - returnValue = v; - } - Ext.each(e.after, function(a){ - makeCall(a.fn, a.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 = getMethodEvent.call(this, method), found = false; - Ext.each(e.before, function(b, i, arr){ - if (b.fn == fn && b.scope == scope) { - arr.splice(i, 1); - found = true; - return false; - } - }); - if (!found) { - Ext.each(e.after, function(a, i, arr){ - if (a.fn == fn && a.scope == scope) { - arr.splice(i, 1); - return false; - } - }); - } - }, - - /** - * Relays selected events from the specified Observable as if the events were fired by this. - * @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(Ext.toArray(arguments))); - }; - } - Ext.each(events, function(ename){ - me.events[ename] = me.events[ename] || true; - o.on(ename, createHandler(ename), me); - }); - }, - - /** - *

Enables events fired by this Observable to bubble up an owner hierarchy by calling - * this.getBubbleTarget() if present. There is no implementation in the Observable base class.

- *

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.

- *

Example:


-Ext.override(Ext.form.Field, {
-//  Add functionality to Field'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'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");
-        }
-    }
-});
-
- * @param {Object} 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 : Ext.toArray(arguments); - Ext.each(events, function(ename){ - ename = ename.toLowerCase(); - var ce = me.events[ename] || true; - if (Ext.isBoolean(ce)) { - 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 - * before the event is fired. If the supplied function returns false, - * the event will not fire. - * @param {Observable} o The Observable to capture - * @param {Function} fn The function to call - * @param {Object} scope (optional) The scope (this object) for the fn - * @static - */ -Ext.util.Observable.capture = function(o, fn, scope){ - o.fireEvent = o.fireEvent.createInterceptor(fn, scope); -}; - - -/** - * Sets observability on the passed class constructor.

- *

This makes any event fired on any instance of the passed class also fire a single event through - * the class allowing for central handling of events on many instances at once.

- *

Usage:


-Ext.util.Observable.observeClass(Ext.data.Connection);
-Ext.data.Connection.on('beforerequest', function(con, options) {
-    console.log("Ajax request made to " + options.url);
-});
- * @param {Function} c The class constructor to make observable. - * @static - */ -Ext.util.Observable.observeClass = function(c){ - Ext.apply(c, new Ext.util.Observable()); - c.prototype.fireEvent = function(){ - return (c.fireEvent.apply(c, arguments) !== false) && - (Ext.util.Observable.prototype.fireEvent.apply(this, arguments) !== false); - }; -};/** - * @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, - E = Ext.lib.Event, - D = Ext.lib.Dom, - DOC = document, - WINDOW = window, - IEDEFERED = "ie-deferred-loader", - DOMCONTENTLOADED = "DOMContentLoaded", - elHash = {}, - propRe = /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/; +})(); - /// There is some jquery work around stuff here that isn't needed in Ext Core. - function addListener(el, ename, fn, wrap, scope){ - var id = Ext.id(el), - es = elHash[id] = elHash[id] || {}; - - (es[ename] = es[ename] || []).push([fn, wrap, scope]); - E.on(el, ename, wrap); +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, + + afterbegin = 'afterbegin', + afterend = 'afterend', + beforebegin = 'beforebegin', + beforeend = 'beforeend', + ts = '', + te = '
', + tbs = ts+'', + tbe = ''+te, + trs = tbs + '', + tre = ''+tbe; - // this is a workaround for jQuery and should somehow be removed from Ext Core in the future - // without breaking ExtJS. - if(ename == "mousewheel" && el.addEventListener){ // workaround for jQuery - var args = ["DOMMouseScroll", wrap, false]; - el.addEventListener.apply(el, args); - E.on(window, 'unload', function(){ - el.removeEventListener.apply(el, args); - }); - } - if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document - Ext.EventManager.stoppedMouseDownEvent.addListener(wrap); - } - }; - function fireDocReady(){ - if(!docReadyState){ - Ext.isReady = docReadyState = true; - if(docReadyProcId){ - clearInterval(docReadyProcId); - } - if(Ext.isGecko || Ext.isOpera) { - DOC.removeEventListener(DOMCONTENTLOADED, fireDocReady, false); - } - if(Ext.isIE){ - var defer = DOC.getElementById(IEDEFERED); - if(defer){ - defer.onreadystatechange = null; - defer.parentNode.removeChild(defer); + 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; + } + + + function createHtml(o){ + var b = '', + attr, + val, + key, + 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]); } - } - if(docReadyEvent){ - docReadyEvent.fire(); - docReadyEvent.clearListeners(); + }; + } 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 + '"'; + } + } + }; + + 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 += ''; } } - }; + return b; + } - function initDocReady(){ - var COMPLETE = "complete"; - - docReadyEvent = new Ext.util.Event(); - if (Ext.isGecko || Ext.isOpera) { - DOC.addEventListener(DOMCONTENTLOADED, fireDocReady, false); - } else if (Ext.isIE){ - DOC.write(""); - DOC.getElementById(IEDEFERED).onreadystatechange = function(){ - if(this.readyState == COMPLETE){ - fireDocReady(); - } - }; - } else if (Ext.isWebKit){ - docReadyProcId = setInterval(function(){ - if(DOC.readyState == COMPLETE) { - fireDocReady(); - } - }, 10); + function ieTable(depth, s, h, e){ + tempTableEl.innerHTML = [s, h, e].join(''); + var i = -1, + el = tempTableEl, + ns; + while(++i < depth){ + el = el.firstChild; } - // 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); + if(ns = el.nextSibling){ + var df = document.createDocumentFragment(); + while(el){ + ns = el.nextSibling; + df.appendChild(el); + el = ns; } - }; - }; + el = df; + } + return el; + } + - function createBuffered(h, o){ - var task = new Ext.util.DelayedTask(h); - 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 insertIntoTable(tag, where, el, html) { + var node, + before; - function createSingle(h, el, ename, fn, scope){ - return function(e){ - Ext.EventManager.removeListener(el, ename, fn, scope); - h(e); - }; - }; + tempTableEl = tempTableEl || document.createElement('div'); - function createDelayed(h, o){ - return function(e){ - // create new event object impl so new events don't wipe out properties - e = new Ext.EventObjectImpl(e); - setTimeout(function(){ - h(e); - }, o.delay || 10); - }; - }; + 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; - function listen(element, ename, opt, fn, scope){ - var o = !Ext.isObject(opt) ? {} : opt, - el = Ext.getDom(element); - - fn = fn || o.fn; - scope = scope || o.scope; - - if(!el){ - throw "Error listening for \"" + ename + '\". Element "' + element + '" doesn\'t exist.'; + if (where == beforebegin || where == afterend) { + el = el.parentNode; } - 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; + + 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 = { + + markup : function(o){ + return createHtml(o); + }, + + + applyStyles : function(el, styles){ + if (styles) { + var matches; + + el = Ext.fly(el); + if (typeof styles == "function") { + styles = styles.call(); + } + if (typeof styles == "string") { + + cssRe.lastIndex = 0; + while ((matches = cssRe.exec(styles))) { + el.setStyle(matches[1], matches[2]); + } + } else if (typeof styles == "object") { + el.setStyle(styles); } - } 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); - } - if(o.single){ - h = createSingle(h, el, ename, fn, scope); - } - if(o.buffer){ - h = createBuffered(h, o); - } + }, - addListener(el, ename, fn, h, scope); - return h; - }; + + insertHtml : function(where, el, html){ + var hash = {}, + hashVal, + setStart, + range, + frag, + rangeEl, + rs; + + where = where.toLowerCase(); + + hash[beforebegin] = ['BeforeBegin', 'previousSibling']; + hash[afterend] = ['AfterEnd', 'nextSibling']; - 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: - * @param {Object} scope (optional) The scope (this reference) in which the handler function is executed. Defaults to the Element. - * @param {Object} options (optional) An object containing handler configuration properties. - * This may contain any of the following properties:
- *

See {@link Ext.Element#addListener} for examples of how to use these options.

- */ - addListener : function(element, eventName, fn, scope, options){ - if(Ext.isObject(eventName)){ - 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); + if (el.insertAdjacentHTML) { + if(tableRe.test(el.tagName) && (rs = insertIntoTable(el.tagName.toLowerCase(), where, el, html))){ + return rs; + } + + 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{ - // individual options - listen(element, e, val); + el.appendChild(frag); } + } else { + el.innerHTML = html; } + return el[rangeEl]; } - } else { - listen(element, eventName, options, fn, scope); } + throw 'Illegal insertion point -> "' + where + '"'; }, + - /** - * 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. This must be a reference to the function passed into the {@link #addListener} call. - * @param {Object} scope If a scope (this reference) was specified when the listener was added, - * then this must refer to the same object. - */ - removeListener : function(element, eventName, fn, scope){ - var el = Ext.getDom(element), - id = Ext.id(el), - wrap; - - Ext.each((elHash[id] || {})[eventName], function (v,i,a) { - if (Ext.isArray(v) && v[0] == fn && (!scope || v[2] == scope)) { - E.un(el, eventName, wrap = v[1]); - a.splice(i,1); - return false; - } - }); + insertBefore : function(el, o, returnElement){ + return doInsert(el, o, returnElement, beforebegin); + }, - // jQuery workaround that should be removed from Ext Core - if(eventName == "mousewheel" && el.addEventListener && wrap){ - el.removeEventListener("DOMMouseScroll", wrap, false); - } - - if(eventName == "mousedown" && el == DOC && wrap){ // fix stopped mousedowns on the document - Ext.EventManager.stoppedMouseDownEvent.removeListener(wrap); - } + + insertAfter : function(el, o, returnElement){ + return doInsert(el, o, returnElement, afterend, 'nextSibling'); }, + - /** - * 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){ - var id = Ext.id(el = Ext.getDom(el)), - es = elHash[id], - ename; - - for(ename in es){ - if(es.hasOwnProperty(ename)){ - Ext.each(es[ename], function(v) { - E.un(el, ename, v.wrap); - }); - } - } - elHash[id] = null; + insertFirst : function(el, o, returnElement){ + return doInsert(el, o, returnElement, afterbegin, 'firstChild'); }, - /** - * 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 (this 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 - * {single: true} be used so that the handler is removed on first invocation. - */ - onDocumentReady : function(fn, scope, options){ - if(docReadyState){ // if it already fired - docReadyEvent.addListener(fn, scope, options); - docReadyEvent.fire(); - docReadyEvent.clearListeners(); - } else { - if(!docReadyEvent) initDocReady(); - options = options || {}; - options.delay = options.delay || 1; - docReadyEvent.addListener(fn, scope, options); - } + + append : function(el, o, returnElement){ + return doInsert(el, o, returnElement, beforeend, '', true); }, + - elHash : elHash - }; - /** - * 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) (this reference) in which the handler function executes. Defaults to the Element. - * @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. This must be a reference to the function passed into the {@link #on} call. - * @param {Object} scope If a scope (this 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; + overwrite : function(el, o, returnElement){ + el = Ext.getDom(el); + el.innerHTML = createHtml(o); + return returnElement ? Ext.get(el.firstChild) : el.firstChild; + }, - pub.stoppedMouseDownEvent = new Ext.util.Event(); + createHtml : createHtml + }; 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 (this 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 - * {single: true} be used so that the handler is removed on first invocation. - * @member Ext - * @method onReady - */ -Ext.onReady = Ext.EventManager.onDocumentReady; +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(''); + } -//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" : ""]; + me.html = html; + + if (me.compiled) { + me.compile(); + } +}; +Ext.Template.prototype = { + + re : /\{([\w-]+)\}/g, + - 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"); - } + + applyTemplate : function(values){ + var me = this; - if(Ext.isMac){ - cls.push("ext-mac"); - } - if(Ext.isLinux){ - cls.push("ext-linux"); + return me.compiled ? + me.compiled(values) : + me.html.replace(me.re, function(m, name){ + return values[name] !== undefined ? values[name] : ""; + }); + }, + + + set : function(html, compile){ + var me = this; + me.html = html; + me.compiled = null; + return compile ? me.compile() : me; + }, + + + compile : function(){ + var me = this, + sep = Ext.isGecko ? "+" : ","; + + function fn(m, name){ + name = "values['" + name + "']"; + return "'"+ sep + '(' + name + " == undefined ? '' : " + name + ')' + sep + "'"; } - 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'; + 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; + }, + + + insertFirst: function(el, values, returnElement){ + return this.doInsert('afterBegin', el, values, returnElement); + }, + + + insertBefore: function(el, values, returnElement){ + return this.doInsert('beforeBegin', el, values, returnElement); + }, + + + insertAfter : function(el, values, returnElement){ + return this.doInsert('afterEnd', el, values, returnElement); + }, + + + 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; + }, + + + overwrite : function(el, values, returnElement){ + el = Ext.getDom(el); + el.innerHTML = this.applyTemplate(values); + return returnElement ? Ext.get(el.firstChild, true) : el.firstChild; + } +}; + +Ext.Template.prototype.apply = Ext.Template.prototype.applyTemplate; + + +Ext.Template.from = function(el, config){ + el = Ext.getDom(el); + return new Ext.Template(el.value || el.innerHTML, config || ''); +}; + + +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/, + + + + isIE = window.ActiveXObject ? true : false, + key = 30803; + + + + eval("var batch = 30803;"); + + + + function child(parent, index){ + var i = 0, + n = parent.firstChild; + while(n){ + if(n.nodeType == 1){ + if(++i == index){ + return n; + } } + n = n.nextSibling; } - bd.className += cls.join(' '); - return true; + return null; } - if(!initExtCss()){ - Ext.onReady(initExtCss); + + function next(n){ + while((n = n.nextSibling) && n.nodeType != 1); + return n; } -})(); + + function prev(n){ + while((n = n.previousSibling) && n.nodeType != 1); + return n; + } -/** - * @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. - *

For example:

- *

-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);
- 
- * @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}); + + + function children(parent){ + var n = parent.firstChild, + nodeIndex = -1, + nextNode; + while(n){ + nextNode = n.nextSibling; + + if(n.nodeType == 3 && !nonSpace.test(n.nodeValue)){ + parent.removeChild(n); + }else{ + + n.nodeIndex = ++nodeIndex; + } + n = nextNode; + } + return this; + } - Ext.EventObjectImpl = function(e){ - if(e){ - this.setEvent(e.browserEvent || e); + + + + 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; }; - 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; + function attrValue(n, attr){ + + 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]; + + }; + + + + + + function getNodes(ns, mode, tagName){ + var result = [], ri = -1, cs; + if(!ns){ + return result; + } + tagName = tagName || "*"; + + if(typeof ns.getElementsByTagName != "undefined"){ + ns = [ns]; + } + + + + 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; } - 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); + + + } 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; + } } - E.stopEvent(me.browserEvent); } - }, - - /** - * Prevents the browsers default handling of the event. - */ - preventDefault : function(){ - if(this.browserEvent){ - E.preventDefault(this.browserEvent); + + + }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; + } } - }, - - /** - * Cancels bubbling of the event. - */ - stopPropagation : function(){ - var me = this; - if(me.browserEvent){ - if(me.browserEvent.type == 'mousedown'){ - Ext.EventManager.stoppedMouseDownEvent.fire(me); + + + }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; + } } - E.stopPropagation(me.browserEvent); } - }, + } + return result; + } - /** - * Gets the character code for the event. - * @return {Number} - */ - getCharCode : function(){ - return this.charCode || this.keyCode; - }, + 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; + } - /** - * 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; - }, + 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; + } - /** - * Gets the x coordinate of the event. - * @return {Number} - */ - getPageX : function(){ - return this.xy[0]; - }, + 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; + } - /** - * Gets the y coordinate of the event. - * @return {Number} - */ - getPageY : function(){ - return this.xy[1]; + + + function byAttribute(cs, attr, value, op, custom){ + var result = [], + ri = -1, + useGetStyle = custom == "{", + fn = Ext.DomQuery.operators[op], + a, + xml, + hasXml; + + for(var i = 0, ci; ci = cs[i]; i++){ + + if(ci.nodeType != 1){ + continue; + } + + if(!hasXml){ + xml = Ext.DomQuery.isXml(ci); + hasXml = true; + } + + + if(!xml){ + 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"){ + + + 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); + }, + + compile : function(path, type){ + type = type || "select"; + + + 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, + + lmode = path.match(modeRe); + + if(lmode && lmode[1]){ + fn[fn.length] = 'mode="'+lmode[1].replace(trimRe, "")+'";'; + path = path.replace(lmode[1], ""); + } + + + 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){ + + 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, "*");'; + } + + }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; + } + } + + 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], ""); + } + } + + fn[fn.length] = "return nodup(n);\n}"; + + + eval(fn.join("")); + return f; }, - /** - * Gets the page coordinates of the event. - * @return {Array} The xy values like [x, y] - */ - getXY : function(){ - return this.xy; + + jsSelect: function(path, root, type){ + + root = root || document; + + if(typeof root == "string"){ + root = document.getElementById(root); + } + var paths = path.split(","), + results = []; + + + for(var i = 0, len = paths.length; i < len; i++){ + var subPath = paths[i].replace(trimRe, ""); + + 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(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); + }, - /** - * 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); + + selectNode : function(path, root){ + return Ext.DomQuery.select(path, root)[0]; }, - /** - * Gets the related target. - * @return {HTMLElement} - */ - getRelatedTarget : function(){ - return this.browserEvent ? E.getRelatedTarget(this.browserEvent) : null; + + 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; + + + + + + if (typeof n.normalize == 'function') n.normalize(); + + v = (n && n.firstChild ? n.firstChild.nodeValue : null); + return ((v === null||v === undefined||v==='') ? defaultValue : v); }, - /** - * 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; + + selectNumber : function(path, root, defaultValue){ + var v = Ext.DomQuery.selectValue(path, root, defaultValue || 0); + return parseFloat(v); + }, + + + is : function(el, ss){ + if(typeof el == "string"){ + el = document.getElementById(el); } - return delta; + var isArray = Ext.isArray(el), + result = Ext.DomQuery.filter(isArray ? el : [el], ss); + return isArray ? (result.length == el.length) : (result.length > 0); }, + - /** - * 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:

-        // 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!');
+        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;
+        },
+
         
-        // 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!');
+        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}")}};'
             }
-        });
-        
- * @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)); + ], + + + 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; + } + }, + + + 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; } - return false; } - }; + }; +}(); - return new Ext.EventObjectImpl(); -}();/** - * @class Ext.EventManager - */ -Ext.apply(Ext.EventManager, function(){ - var resizeEvent, - resizeTask, - textEvent, - textSize, - D = Ext.lib.Dom, - E = Ext.lib.Event, - 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); - } - }, - - /** - * Fires when the window is resized and provides resize event buffering (50 milliseconds), passes new viewport width and height to handlers. - * @param {Function} fn The method the event invokes - * @param {Object} scope An object that becomes the scope of the handler - * @param {boolean} options - */ - onWindowResize : function(fn, scope, options){ - if(!resizeEvent){ - resizeEvent = new Ext.util.Event(); - resizeTask = new Ext.util.DelayedTask(this.doResizeEvent); - E.on(window, "resize", this.fireWindowResize, this); - } - resizeEvent.addListener(fn, scope, options); - }, - - // exposed only to allow manual firing - fireWindowResize : function(){ - if(resizeEvent){ - if((Ext.isIE||Ext.isAir) && resizeTask){ - resizeTask.delay(50); - }else{ - resizeEvent.fire(D.getViewWidth(), D.getViewHeight()); - } - } - }, - - /** - * Fires 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 method the event invokes - * @param {Object} scope An object that becomes the scope of the handler - * @param {boolean} options - */ - 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 <= 45); // Print Screen, Insert - }, - - 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 - *

Encapsulates a DOM element, adding simple DOM manipulation facilities, normalizing for browser differences.

- *

All instances of this class inherit the methods of {@link Ext.Fx} making visual effects easily available to all DOM elements.

- *

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.

- * Usage:
-

-// by id
-var el = Ext.get("my-div");
-
-// by DOM element reference
-var el = Ext.get(myDivElement);
-
- * Animations
- *

When an element is manipulated, by default there is no animation.

- *

-var el = Ext.get("my-div");
-
-// no animation
-el.setWidth(100);
- * 
- *

Many of the functions for manipulating an element have an optional "animate" parameter. This - * parameter can be specified as boolean (true) for default animation effects.

- *

-// default animation
-el.setWidth(100, true);
- * 
- * - *

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:

-
-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
-
- * - *

-// 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);
- * 
- *

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:

- *

-// using the "anim" property to get the Anim object
-if(opt.anim.isAnimated()){
-    opt.anim.stop();
-}
- * 
- *

Also see the {@link #animate} method for another animation technique.

- *

Composite (Collections of) Elements

- *

For working with collections of Elements, see {@link Ext.CompositeElement}

- * @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.Element.cache[id]){ // element object already exists - return Ext.Element.cache[id]; - } - - /** - * 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; - -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; - - for(attr in o){ - val = o[attr]; - if (attr != "style" && !Ext.isFunction(val)) { - if (attr == "cls" ) { - el.className = val; - } else if (o.hasOwnProperty(attr)) { - if (useSet || !!el.setAttribute) el.setAttribute(attr, val); - else el[attr] = val; - } - } - } - if(o.style){ - DH.applyStyles(el, o.style); - } - 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: - * @param {Object} scope (optional) The scope (this reference) in which the handler function is executed. - * If omitted, defaults to this Element.. - * @param {Object} options (optional) An object containing handler configuration properties. - * This may contain any of the following properties:
- *

- * Combining Options
- * 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:
- *
- * 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.

- * Code:

-el.on('click', this.onClick, this, {
-    single: true,
-    delay: 100,
-    stopEvent : true,
-    forumId: 4
-});

- *

- * Attaching multiple handlers in 1 call
- * The method also allows for a single argument to be passed which is a config object containing properties - * which specify multiple handlers.

- *

- * Code:


-el.on({
-    'click' : {
-        fn: this.onClick,
-        scope: this,
-        delay: 100
-    },
-    'mouseover' : {
-        fn: this.onMouseOver,
-        scope: this
-    },
-    'mouseout' : {
-        fn: this.onMouseOut,
-        scope: this
-    }
-});
- *

- * Or a shorthand syntax:
- * Code:

-el.on({ - 'click' : this.onClick, - 'mouseover' : this.onMouseOver, - 'mouseout' : this.onMouseOut, - scope: this -}); - *

- *

delegate

- *

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:


-// using this markup:
-<div id='elId'>
-    <p id='p1'>paragraph one</p>
-    <p id='p2' class='clickable'>paragraph two</p>
-    <p id='p3'>paragraph three</p>
-</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' 
-    }
-);
-     * 

- * @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. - * Note: if a scope was explicitly specified when {@link #addListener adding} the - * listener, the same scope must be specified here. - * Example: - *

-el.removeListener('click', this.handlerFn);
-// or
-el.un('click', this.handlerFn);
-
- * @param {String} eventName The name of the event from which to remove the handler. - * @param {Function} fn The handler function to remove. This must be a reference to the function passed into the {@link #addListener} call. - * @param {Object} scope If a scope (this 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; - }, - - /** - * @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; - }, - - /** - *

Updates the innerHTML of this Element - * from a specified URL. Note that this is subject to the Same Origin Policy

- *

Updating innerHTML of an element will not execute embedded <script> elements. This is a browser restriction.

- * @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; - }, - - /** - * Removes this element from the DOM and deletes it from the cache - */ - remove : function(){ - var me = this, - dom = me.dom; - - me.removeAllListeners(); - if (dom) { - delete me.dom; - delete El.cache[dom.id]; - delete El.dataCache[dom.id]; - 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 (this 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 options 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 (this 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. This must be a reference to the function passed into the {@link #addListener} call. - * @param {Object} scope If a scope (this 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 - */ -El.cache = {}; -El.dataCache = {}; - -/** - * Retrieves Ext.Element objects. - *

This method does not retrieve {@link Ext.Component Component}s. This method - * retrieves Ext.Element objects which encapsulate DOM elements. To retrieve a Component by - * its ID, use {@link Ext.ComponentMgr#get}.

- *

Uses simple caching to consistently return the same object. Automatically fixes if an - * object was recreated with the same id via AJAX or DOM.

- * @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 (ex = El.cache[el]) { - ex.dom = elm; - } else { - ex = El.cache[el] = new El(elm); - } - return ex; - } else if (el.tagName) { // dom element - if(!(id = el.id)){ - id = Ext.id(el); - } - if(ex = El.cache[id]){ - ex.dom = el; - }else{ - ex = El.cache[id] = new El(el); - } - return ex; - } else if (el instanceof El) { - if(el != docEl){ - el.dom = DOC.getElementById(el.id) || el.dom; // refresh dom element in case no longer valid, - // catch case where it hasn't been appended - El.cache[el.id] = el; // in case it was created directly with Element(), let's cache it - } - 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; -}; - -// private method for getting and setting element data -El.data = function(el, key, value){ - var c = El.dataCache[el.id]; - if(!c){ - c = El.dataCache[el.id] = {}; - } - 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.collectorThread); - } else { - var eid, - el, - d; - - for(eid in El.cache){ - el = El.cache[eid]; - 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))){ - delete El.cache[eid]; - if(d && Ext.enableListenerCollection){ - Ext.EventManager.removeAll(d); - } - } - } - } -} -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 = {}; - -/** - *

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}

- *

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.

- * @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. - *

This method does not retrieve {@link Ext.Component Component}s. This method - * retrieves Ext.Element objects which encapsulate DOM elements. To retrieve a Component by - * its ID, use {@link Ext.ComponentMgr#get}.

- *

Uses simple caching to consistently return the same object. Automatically fixes if an - * object was recreated with the same id via AJAX or DOM.

- * 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; - -/** - *

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}

- *

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.

- * @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; -} - - -Ext.EventManager.on(window, 'unload', function(){ - delete El.cache; - delete El.dataCache; - delete El._flyweights; -}); -})(); -/** - * @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){ - html = html || ""; - - if(loadScripts !== true){ - this.dom.innerHTML = html; - if(Ext.isFunction(callback)){ - callback(); - } - return this; - } - - var id = Ext.id(), - dom = this.dom; - - html += ''; - - Ext.lib.Event.onAvailable(id, function(){ - var DOC = document, - hd = DOC.getElementsByTagName("head")[0], - re = /(?:]*)?>)((\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(Ext.isFunction(callback)){ - callback(); - } - }); - dom.innerHTML = html.replace(/(?:)((\n|\r|.)*?)(?:<\/script>)/ig, ""); - 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 = Ext.isObject(config) ? 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; - -// private -Ext.Element.uncache = function(el){ - for(var i = 0, a = arguments, len = a.length; i < len; i++) { - if(a[i]){ - delete Ext.Element.cache[a[i].id || a[i]]; - } - } -};/** - * @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; - - function action(){ - Ext.fly(dom).alignTo(el, alignment, offsets, animate); - Ext.callback(callback, Ext.fly(dom)); - } - - Ext.EventManager.onWindowResize(action, me); - - if(!Ext.isEmpty(monitorScroll)){ - Ext.EventManager.on(window, 'scroll', action, me, - {buffer: !isNaN(monitorScroll) ? monitorScroll : 50}); - } - action.call(me); // align immediately - return me; - }, - - /** - * 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 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 == "?" ? "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: - *
    - *
  • Blank: Defaults to aligning the element's top-left corner to the target's bottom-left corner ("tl-bl").
  • - *
  • One anchor (deprecated): 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. This method has been - * deprecated in favor of the newer two anchor syntax below.
  • - *
  • Two anchors: 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.
  • - *
- * 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: -
-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
-
-Example Usage: -

-// 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]);
-
- * @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 - * @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 - * @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); - }, - - /** - * 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, unique){ - 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( -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, - Element = Ext.Element; - 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 Element.cache[me.id]; - Ext.removeNode(me.dom); - me.id = Ext.id(me.dom = el); - return Element.cache[me.id] = 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 - */ - insertSibling: function(el, where, returnDom){ - var me = this, - rt; - - if(Ext.isArray(el)){ - Ext.each(el, function(e) { - rt = me.insertSibling(e, where, returnDom); - }); - return rt; - } - - where = (where || 'before').toLowerCase(); - el = el || {}; - - if(el.nodeType || el.dom){ - rt = me.dom.parentNode.insertBefore(GETDOM(el), where == 'before' ? me.dom : me.dom.nextSibling); - if (!returnDom) { - rt = GET(rt); - } - }else{ - if (where == 'after' && !me.dom.nextSibling) { - rt = DH.append(me.dom.parentNode, el, !returnDom); - } else { - rt = DH[where == 'after' ? '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, - 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; - + +Ext.query = Ext.DomQuery.select; + +Ext.util.DelayedTask = function(fn, scope, args){ + var me = this, + id, + call = function(){ + clearInterval(id); + id = null; + fn.apply(scope, args || []); + }; + - // private - function camelFn(m, a) { - return a.charAt(1).toUpperCase(); - } + me.delay = function(delay, newFn, newScope, newArgs){ + me.cancel(); + fn = newFn || fn; + scope = newScope || scope; + args = newArgs || args; + id = setInterval(call, delay); + }; + - function chkCache(prop) { - return propCache[prop] || (propCache[prop] = prop == 'float' ? propFloat : prop.replace(camelRe, camelFn)); + me.cancel = function(){ + if(id){ + clearInterval(id); + id = null; + } + }; +}; +(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]){ + return Ext.elCache[id].el; } - - return { - // private ==> used by Fx - adjustWidth : function(width) { - var me = this; - var isNum = Ext.isNumber(width); - 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 = Ext.isNumber(height); - if(isNum && me.autoBoxAdjust && !me.isBorderBox()){ - height -= (me.getBorderWidth("tb") + me.getPadding("tb")); - } - return (isNum && height < 0) ? 0 : height; - }, + + this.dom = dom; + - /** - * 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; - Ext.each(className, function(v) { - me.dom.className += (!me.hasClass(v) && v ? " " + v : ""); - }); - return me; - }, + this.id = id || Ext.id(dom); +}; + +var DH = Ext.DomHelper, + El = Ext.Element, + EC = Ext.elCache; + +El.prototype = { - /** - * 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){ - Ext.each(this.dom.parentNode.childNodes, function(v) { - if(v.nodeType == 1) { - Ext.fly(v, '_internal').removeClass(className); + 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.addClass(className); - }, - - /** - * 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; - if (me.dom && me.dom.className) { - Ext.each(className, function(v) { - me.dom.className = me.dom.className.replace( - classReCache[v] = classReCache[v] || new RegExp('(?:^|\\s+)' + v + '(?:\\s+|$)', "g"), - " "); - }); } - return me; - }, + } + return this; + }, + + + + + + + + - /** - * 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; - if(el == document) return null; - prop = chkCache(prop); - out = (v = el.style[prop]) ? v : - (cs = view.getComputedStyle(el, "")) ? cs[prop] : null; - - // Webkit returns rgb values for transparent. - if(Ext.isWebKit && out == 'rgba(0, 0, 0, 0)'){ - out = 'transparent'; - } - 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 = Ext.isDefined(prefix) ? 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 (!Ext.isObject(prop)) { - 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 true for - * the default animation ({duration: .35, easing: 'easeIn'}) - * @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, ''); - } + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + defaultUnit : "px", + + + is : function(simpleSelector){ + return Ext.DomQuery.is(this.dom, simpleSelector); + }, + + + focus : function(defer, dom) { + var me = this, + dom = dom || me.dom; + try{ + if(Number(defer)){ + me.focus.defer(defer, null, [null, dom]); }else{ - style.opacity = style['-moz-opacity'] = style['-khtml-opacity'] = ''; + dom.focus(); } - return this; - }, + }catch(e){} + return me; + }, + - /** - * 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; - }, + blur : function() { + try{ + this.dom.blur(); + }catch(e){} + return this; + }, + - /** - * 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; - }, + getValue : function(asNumber){ + var val = this.dom.value; + return asNumber ? parseInt(val, 10) : val; + }, + - /** - * Set the width of this Element. - * @param {Mixed} width The new width. This may be one of:
    - *
  • A Number specifying the new width in this Element's {@link #defaultUnit}s (by default, pixels).
  • - *
  • A String used to set the CSS width style. Animation may not be used. - *
- * @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; - }, + addListener : function(eventName, fn, scope, options){ + Ext.EventManager.on(this.dom, eventName, fn, scope || this, options); + return this; + }, + - /** - * Set the height of this Element. - *

-// 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"); } 
-});
-         * 
- * @param {Mixed} height The new height. This may be one of:
    - *
  • A Number specifying the new height in this Element's {@link #defaultUnit}s (by default, pixels.)
  • - *
  • A String used to set the CSS height style. Animation may not be used.
  • - *
- * @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 'lr' would get the border left width + the border right width. - * @return {Number} The width of the sides passed added together - */ - getBorderWidth : function(side){ - return this.addStyles(side, borders); - }, + removeListener : function(eventName, fn, scope){ + Ext.EventManager.removeListener(this.dom, eventName, fn, scope || this); + return this; + }, + - /** - * 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 'lr' would get the padding left + the padding right. - * @return {Number} The padding of the sides passed added together - */ - getPadding : function(side){ - return this.addStyles(side, paddings); - }, + removeAllListeners : function(){ + Ext.EventManager.removeAll(this.dom); + return this; + }, + - /** - * Store the current overflow setting and clip overflow on the element - use {@link #unclip} 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; - }, + purgeAllListeners : function() { + Ext.EventManager.purgeElement(this, true); + return this; + }, - /** - * Return clipping (overflow) to original clipping before {@link #clip} 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; - }, + 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; + }, - // private - addStyles : function(sides, styles){ - var val = 0; + + 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; + }, - Ext.each(sides.match(/\w/g), function(s) { - if (s = parseInt(this.getStyle(styles[s]), 10)) { - val += MATH.abs(s); - } - }, - this); - return val; - }, + + isBorderBox : function(){ + return Ext.isBorderBox || Ext.isForcedBorderBox || noBoxAdjust[(this.dom.tagName || "").toLowerCase()]; + }, - margins : margins + + remove : function(){ + var me = this, + dom = me.dom; + + if (dom) { + delete me.dom; + Ext.removeNode(dom); + } + }, + + + 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; + }, + + + contains : function(el){ + return !el ? false : Ext.lib.Dom.isAncestor(this.dom, el.dom ? el.dom : el); + }, + + + getAttributeNS : function(ns, name){ + return this.getAttribute(name, ns); + }, + + + 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 : function(html) { + if (this.dom) { + this.dom.innerHTML = html; + } + return this; } -}() -); -/** - * @class Ext.Element - */ - -// special markup used throughout Ext when box wrapping elements -Ext.Element.boxMarkup = '
'; - -Ext.Element.addMethods(function(){ - var INTERNAL = "_internal"; - 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; - }, - - getStyleSize : function(){ - var me = this, - w, - h, - d = this.dom, - s = d.style; - if(s.width && s.width != 'auto'){ - w = parseInt(s.width, 10); - if(me.isBorderBox()){ - w -= me.getFrameWidth('lr'); - } - } - if(s.height && s.height != 'auto'){ - h = parseInt(s.height, 10); - if(me.isBorderBox()){ - h -= me.getFrameWidth('tb'); - } - } - return {width: w || me.getWidth(true), height: h || me.getHeight(true)}; - }, - - // 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; - } - }, - - /** - *

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.

- *

This special markup is used throughout Ext when box wrapping elements ({@link Ext.Button}, - * {@link Ext.Panel} when {@link Ext.Panel#frame frame=true}, {@link Ext.Window}). The markup - * is of this form:

- *

-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>';
-		* 
- *

Example usage:

- *

-// 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");
-		* 
- * @param {String} class (optional) A base CSS class to apply to the containing wrapper element - * (defaults to 'x-box'). 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} this - */ - boxWrap : function(cls){ - cls = cls || 'x-box'; - var el = Ext.get(this.insertHtml("beforeBegin", "
" + String.format(Ext.Element.boxMarkup, cls) + "
")); //String.format('
'+Ext.Element.boxMarkup+'
', 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:
    - *
  • A Number specifying the new width in this Element's {@link #defaultUnit}s (by default, pixels).
  • - *
  • A String used to set the CSS width style. Animation may not be used. - *
  • A size object in the format {width: widthValue, height: heightValue}.
  • - *
- * @param {Mixed} height The new height. This may be one of:
    - *
  • A Number specifying the new height in this Element's {@link #defaultUnit}s (by default, pixels).
  • - *
  • A String used to set the CSS height style. Animation may not be used.
  • - *
- * @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(Ext.isObject(width)){ // 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 = parseInt(me.getStyle('height'), 10) || 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 = parseInt(this.getStyle('width'), 10) || 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; - }, - - /** - * Returns the width and height of the viewport. - *

-        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.
-        
- * @return {Object} An object containing the viewport's size {width: (viewport width), height: (viewport height)} - */ - getViewSize : function(){ - var doc = document, - d = this.dom, - extdom = Ext.lib.Dom, - isDoc = (d == doc || d == doc.body); - return { width : (isDoc ? extdom.getViewWidth() : d.clientWidth), - height : (isDoc ? extdom.getViewHeight() : d.clientHeight) }; - }, - - /** - * 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]] = parseInt(me.getStyle(me.margins[key]), 10) || 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 a box {x, y, width, height} that can be used to set another elements - * 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 {x, y, width, height} - */ - 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:
    - *
  • A Number specifying the new width in this Element's {@link #defaultUnit}s (by default, pixels)
  • - *
  • A String used to set the CSS width style. Animation may not be used. - *
- * @param {Mixed} height The new height. This may be one of:
    - *
  • A Number specifying the new height in this Element's {@link #defaultUnit}s (by default, pixels)
  • - *
  • A String used to set the CSS height style. Animation may not be used.
  • - *
- * @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 - prop = 'scroll' + (top ? 'Left' : 'Top'), // if scrolling top, we need to grab scrollLeft, if left, scrollTop - me = this, - dom = me.dom; - if (!animate || !me.anim) { - dom[prop] = value; - } else { - 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", - 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. - *
    - *
  • Animation Properties
  • - * - *

    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:

      - *
    • bottom, top, left, right
    • - *
    • height, width
    • - *
    • margin, padding
    • - *
    • borderWidth
    • - *
    • opacity
    • - *
    • fontSize
    • - *
    • lineHeight
    • - *
    - * - * - *
  • Animation Property Attributes
  • - * - *

    Each Animation Property is a config object with optional properties:

    - *
      - *
    • by* : relative change - start at current value, change by this value
    • - *
    • from : ignore current value, start from this value
    • - *
    • to* : start at current value, go to this value
    • - *
    • unit : any allowable unit specification
    • - *

      * do not specify both to and by for an animation property

      - *
    - * - *
  • Animation Types
  • - * - *

    The supported animation types:

      - *
    • 'run' : Default - *
      
      -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')    
      -);
      -         * 
      - *
    • - *
    • 'color' - *

      Animates transition of background, text, or border colors.

      - *
      
      -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')    
      -);
      -         * 
      - *
    • - * - *
    • 'motion' - *

      Animates the motion of an element to/from specific points using optional bezier - * way points during transit.

      - *
      
      -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')    
      -);
      -         * 
      - *
    • - *
    • 'scroll' - *

      Animate horizontal or vertical scrolling of an overflowing page element.

      - *
      
      -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')    
      -);
      -         * 
      - *
    • - *
    - * - *
- * - * @param {Object} args The animation control args - * @param {Float} duration (optional) How long the animation lasts in seconds (defaults to .35) - * @param {Function} onComplete (optional) Function to call when animation completes - * @param {String} easing (optional) {@link Ext.Fx#easing} method to use (defaults to 'easeOut') - * @param {String} animType (optional) 'run' is the default. Can also be 'color', - * 'motion', or 'scroll' - * @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 : (Ext.isObject(a[i]) ? 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, - dom = me.dom, - isDisplay = getVisMode(this.dom) == ELDISPLAY; - - if (!animate || !me.anim) { - if(isDisplay){ - me.setDisplayed(visible); - }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){ - 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){ - 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(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: - * {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 of the function - * @return {Ext.KeyMap} The KeyMap created - */ - addKeyListener : function(key, fn, scope){ - var config; - if(!Ext.isObject(key) || 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 - *

A class to provide basic animation and visual effects support. Note: 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 must be - * {@link Ext#enableFx included} in order for the Element effects to work.


- * - *

Method Chaining

- *

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 {@link #callback}.


- * - *

Anchor Options for Motion Effects

- *

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:

-
-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
-
- * Note: 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. - * - * @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 Method Chaining above), for example:

- * el.slideIn().highlight();
- * 
- * 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 (this reference) in which the {@link #callback} function is executed. Defaults to the browser window. - * - * @cfg {String} easing A valid Ext.lib.Easing value for the effect:

    - *
  • backBoth
  • - *
  • backIn
  • - *
  • backOut
  • - *
  • bounceBoth
  • - *
  • bounceIn
  • - *
  • bounceOut
  • - *
  • easeBoth
  • - *
  • easeBothStrong
  • - *
  • easeIn
  • - *
  • easeInStrong
  • - *
  • easeNone
  • - *
  • easeOut
  • - *
  • easeOutStrong
  • - *
  • elasticBoth
  • - *
  • elasticIn
  • - *
  • elasticOut
  • - *
- * - * @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 - * 0 and 1 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 display CSS property instead of visibility 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. "width:100px", or an object - * in the form {width:"100px"}, 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: - *

-// 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
-});
-
- * @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: - *

-// 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
-});
-
- * @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: - *

-// default
-el.puff();
-
-// common config options shown with default values
-el.puff({
-    easing: 'easeOut',
-    duration: .5,
-    remove: false,
-    useDisplay: false
-});
-
- * @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: - *

-// default
-el.switchOff();
-
-// all config options shown with default values
-el.switchOff({
-    easing: 'easeIn',
-    duration: .3,
-    remove: false,
-    useDisplay: false
-});
-
- * @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: -

-// 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
-});
-
- * @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: -

-// 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
-});
-
- * @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: -

-el.pause(1);
-
- * @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 {@link #endOpacity} config option. - * Usage: -

-// 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
-});
-
- * @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 {@link #endOpacity} config option. Note that IE may require - * {@link #useDisplay}:true in order to redisplay correctly. - * Usage: -

-// 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
-});
-
- * @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: -

-// 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's existing values if passed as null.
-el.scale(
-    [element's width],
-    [element's height], {
-        easing: 'easeOut',
-        duration: .35
-    }
-);
-
- * @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: -

-// 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's width],
-    height: [element's height],
-    x: [element's x position],
-    y: [element's y position],
-    opacity: [element's opacity],
-    easing: 'easeOut',
-    duration: .35
-});
-
- * @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: - *

-// 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
-});
-
- * @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 - *

This class encapsulates a collection of DOM elements, providing methods to filter - * members, or to perform collective actions upon the whole set.

- *

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.

- * Example:

-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);
-
- */
-Ext.CompositeElementLite = function(els, root){
-    /**
-     * 

The Array of DOM elements which this CompositeElement encapsulates. Read-only.

- *

This will not usually 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.

- *

For example to add the nextAll method to the class to add all - * following siblings of selected elements, the code would be

-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);
-    }
-});
- * @type Array - * @property elements - */ - this.elements = []; - this.add(els, root); - this.el = new Ext.Element.Flyweight(); -}; - -Ext.CompositeElementLite.prototype = { - isComposite: true, - /** - * 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){ - if(els){ - if (Ext.isArray(els)) { - this.elements = this.elements.concat(els); - } else { - var yels = this.elements; - Ext.each(els, function(e) { - yels.push(e); - }); - } - } - return this; - }, - invoke : function(fn, args){ - var els = this.elements, - el = this.el; - Ext.each(els, function(e) { - el.dom = e; - Ext.Element.prototype[fn].apply(el, args); - }); - return this; - }, - /** - * 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; - if(!me.elements[index]){ - return null; - } - me.el.dom = me.elements[index]; - return me.el; - }, - - // fixes scope with flyweight - addListener : function(eventName, handler, scope, opt){ - Ext.each(this.elements, function(e) { - Ext.EventManager.on(e, eventName, handler, scope || e, opt); - }); - return this; - }, - /** - *

Calls the passed function for each element in this composite.

- * @param {Function} fn The function to call. The function is passed the following parameters:
    - *
  • el : Element
    The current Element in the iteration. - * This is the flyweight (shared) Ext.Element instance, so if you require a - * a reference to the dom node, use el.dom.
  • - *
  • c : Composite
    This Composite object.
  • - *
  • idx : Number
    The zero-based index in the iteration.
  • - *
- * @param {Object} scope (optional) The scope (this reference) in which the function is executed. (defaults to the Element) - * @return {CompositeElement} this - */ - each : function(fn, scope){ - var me = this, - el = me.el; - - Ext.each(me.elements, function(e,i) { - el.dom = e; - return fn.call(scope || el, el, me, i); - }); - 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:
    - *
  • el : Ext.Element
    The current DOM element.
  • - *
  • index : Number
    The current index within the collection.
  • - *
- * @return {CompositeElement} this - */ - filter : function(selector){ - var els = [], - me = this, - 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] = el.dom; - } - }); - me.fill(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(Ext.getDom(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 {Boolean} unique (optional) true to create a unique Ext.Element for each element (defaults to a shared flyweight object) Not supported in core - * @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 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;/** - * @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 - * Standard composite class. Creates a Ext.Element for every element in the collection. - *

- * NOTE: Although they are not listed, this class supports all of the set/update methods of Ext.Element. All Ext.Element - * actions will be performed on all the elements in this collection. - *

- * All methods return this and can be chained. -

- 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);
- 
- */ -Ext.CompositeElement = function(els, root){ - this.elements = []; - this.add(els, root); -}; - -Ext.extend(Ext.CompositeElement, Ext.CompositeElementLite, { - invoke : function(fn, args){ - Ext.each(this.elements, function(e) { - Ext.Element.prototype[fn].apply(e, args); - }); - return this; - }, - - /** - * Adds elements to this composite. - * @param {String/Array} els A string CSS selector, an array of elements or an element - * @return {CompositeElement} this - */ - add : 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 Element object at the specified index - * @param {Number} index - * @return {Ext.Element} - */ - item : function(index){ - return this.elements[index] || null; - }, - - - indexOf : function(el){ - return this.elements.indexOf(Ext.get(el)); - }, - - filter : function(selector){ - var me = this, - out = []; - - Ext.each(me.elements, function(el) { - if(el.is(selector)){ - out.push(Ext.get(el)); - } - }); - me.elements = out; - return me; - }, - - /** - * Iterates each element in this composite - * calling the supplied function using {@link Ext#each}. - * @param {Function} fn The function to be called with each - * element. If the supplied function returns false, - * iteration stops. This function is called with the following arguments: - *
    - *
  • element : Object - *
    The element at the current index - * in the composite
  • - *
  • composite : Object - *
    This composite.
  • - *
  • index : Number - *
    The current index within the composite - *
  • - *
- * @param {Object} scope (optional) The scope to call the specified function. - * Defaults to the element at the current index - * within the composite. - * @return {CompositeElement} this - */ - each : function(fn, scope){ - Ext.each(this.elements, function(e, i){ - return fn.call(scope || e, e, this, i); - }, this); - return 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.Element - * @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 - *

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.

- *

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 - * success callback - * in the request options object, - * or an {@link #requestcomplete event listener}.

- *

File Uploads

File uploads are not performed using normal "Ajax" techniques, that - * is they are not performed using XMLHttpRequests. Instead the form is submitted in the standard - * manner with the DOM <form> element temporarily modified to have its - * target set to refer - * to a dynamically generated, hidden <iframe> which is inserted into the document - * but removed after the return data has been gathered.

- *

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 - * Content-Type header - * must be set to "text/html" in order to tell the browser to insert the text unchanged into the document body.

- *

Characters which are significant to an HTML parser must be sent as HTML entities, so encode - * "<" as "&lt;", "&" as "&amp;" etc.

- *

The response text is retrieved from the document, and a fake XMLHttpRequest object - * is created containing a responseText property in order to conform to the - * requirements of event handlers and callbacks.

- *

Be aware that file upload packets are sent with the content type multipart/form - * and some server technologies (notably JEE) may require some custom processing in order to - * retrieve parameter names and parameter values from the packet content.

- * @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 The XMLHttpRequest Object - * 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 HTTP Status Code Definitions - * for details of HTTP status codes. - * @param {Connection} conn This Connection object. - * @param {Object} response The XHR object containing the response data. - * See The XMLHttpRequest Object - * 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)

The default URL to be used for requests to the server. Defaults to undefined.

- *

The url config may be a function which returns the URL to use for the Ajax request. The scope - * (this reference) of the function is the scope option passed to the {@link #request} method.

- */ - /** - * @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', - - /** - *

Sends an HTTP request to a remote server.

- *

Important: Ajax server requests are asynchronous, and this call will - * return before the response has been received. Process any returned data - * in a callback function.

- *

-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);
-   }
-});
-         * 
- *

To execute a callback function in the correct scope, use the scope option.

- * @param {Object} options An object which may contain the following properties:
    - *
  • url : String/Function (Optional)
    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 scope option. Defaults to the configured - * {@link #url}.
  • - *
  • params : Object/String/Function (Optional)
    - * 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 scope option.
  • - *
  • method : String (Optional)
    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.
  • - *
  • callback : Function (Optional)
    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:
      - *
    • options : Object
      The parameter to the request call.
    • - *
    • success : Boolean
      True if the request succeeded.
    • - *
    • response : Object
      The XMLHttpRequest object containing the response data. - * See http://www.w3.org/TR/XMLHttpRequest/ for details about - * accessing elements of the response.
    • - *
  • - *
  • success : Function (Optional)
    The function - * to be called upon success of the request. The callback is passed the following - * parameters:
      - *
    • response : Object
      The XMLHttpRequest object containing the response data.
    • - *
    • options : Object
      The parameter to the request call.
    • - *
  • - *
  • failure : Function (Optional)
    The function - * to be called upon failure of the request. The callback is passed the - * following parameters:
      - *
    • response : Object
      The XMLHttpRequest object containing the response data.
    • - *
    • options : Object
      The parameter to the request call.
    • - *
  • - *
  • scope : Object (Optional)
    The scope in - * which to execute the callbacks: The "this" object for the callback function. If the url, or params 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.
  • - *
  • timeout : Number (Optional)
    The timeout in milliseconds to be used for this request. Defaults to 30 seconds.
  • - *
  • form : Element/HTMLElement/String (Optional)
    The <form> - * Element or the id of the <form> to pull parameters from.
  • - *
  • isUpload : Boolean (Optional)
    Only meaningful when used - * with the form option. - *

    True if the form object is a file upload (will be set automatically if the form was - * configured with enctype "multipart/form-data").

    - *

    File uploads are not performed using normal "Ajax" techniques, that is they are not - * performed using XMLHttpRequests. Instead the form is submitted in the standard manner with the - * DOM <form> element temporarily modified to have its - * target set to refer - * to a dynamically generated, hidden <iframe> which is inserted into the document - * but removed after the return data has been gathered.

    - *

    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 - * Content-Type header - * must be set to "text/html" in order to tell the browser to insert the text unchanged into the document body.

    - *

    The response text is retrieved from the document, and a fake XMLHttpRequest object - * is created containing a responseText property in order to conform to the - * requirements of event handlers and callbacks.

    - *

    Be aware that file upload packets are sent with the content type multipart/form - * and some server technologies (notably JEE) may require some custom processing in order to - * retrieve parameter names and parameter values from the packet content.

    - *
  • - *
  • headers : Object (Optional)
    Request - * headers to set for the request.
  • - *
  • xmlData : Object (Optional)
    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.
  • - *
  • jsonData : Object/String (Optional)
    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.
  • - *
  • disableCaching : Boolean (Optional)
    True - * to add a unique cache-buster param to GET requests.
  • - *

- *

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.

- * @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 = '
'+o.indicatorText+"
"; - } - 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 - }; - - Ext.fly(frame).set({ - id: id, - name: id, - cls: 'x-hidden', - src: Ext.SSL_SECURE_URL // for IE - }); - 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 - *

The global Ajax request class that provides a simple way to make Ajax requests - * with maximum flexibility.

- *

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.

- *

Common Properties you may want to set are:

    - *
  • {@link #method}

  • - *
  • {@link #extraParams}

  • - *
  • {@link #url}

  • - *
- *

-// Default headers to pass in every request
-Ext.Ajax.defaultHeaders = {
-    'Powered-By': 'Ext'
-};
- * 
- *

- *

Common Events you may want to set are:

    - *
  • {@link Ext.data.Connection#beforerequest beforerequest}

  • - *
  • {@link Ext.data.Connection#requestcomplete requestcomplete}

  • - *
  • {@link Ext.data.Connection#requestexception requestexception}

  • - *
- *

-// 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);
- * 
- *

- *

An example request:

- *

-// 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'
-});
- * 
- *

- * @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 - * "POST", otherwise will use "GET".) - * @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.

- * Usage:
- *

- * 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");
- * 
- * // 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); - *
- * // short handed call directly from the element object - * Ext.get("foo").load({ - url: "bar.php", - scripts: true, - params: "param1=foo&param2=bar", - text: "Loading Foo..." - * }); - *
- * @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 asynchronous request, updating this element with the response. - * If params are specified it uses POST, otherwise it uses GET.

- * Note: 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 update event handler. - * @param {Object} options A config object containing any of the following options:
    - *
  • url : String/Function

    The URL to request or a function which - * returns the URL (defaults to the value of {@link Ext.Ajax#url} if not specified).

  • - *
  • method : String

    The HTTP method to - * use. Defaults to POST if the params argument is present, otherwise GET.

  • - *
  • params : String/Object/Function

    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.

  • - *
  • scripts : Boolean

    If true - * any <script> 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 after the execution of the scripts.

  • - *
  • callback : Function

    A function to - * be called when the response from the server arrives. The following - * parameters are passed:

      - *
    • el : Ext.Element

      The Element being updated.

    • - *
    • success : Boolean

      True for success, false for failure.

    • - *
    • response : XMLHttpRequest

      The XMLHttpRequest which processed the update.

    • - *
    • options : Object

      The config object passed to the update call.

    - *

  • - *
  • scope : Object

    The scope in which - * to execute the callback (The callback's this reference.) If the - * params argument is a function, this scope is used for that function also.

  • - *
  • discardUrl : Boolean

    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 discardUrl:true (defaults to false).

  • - *
  • timeout : Number

    The number of seconds to wait for a response before - * timing out (defaults to {@link Ext.Updater.defaults#timeout}).

  • - *
  • text : String

    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.

  • - *
  • nocache : Boolean

    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}).

- *

- * For example: -


-	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.
-	});
-	
- */ - 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 = '
'+cfg.text+"
";}; - 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); - } - }, - - /** - *

Performs an async form post, updating this element with the response. If the form has the attribute - * enctype="multipart/form-data", it assumes it's a file upload. - * Uses this.sslBlankUrl for SSL file uploads to prevent IE security warning.

- *

File uploads are not performed using normal "Ajax" techniques, that is they are not - * performed using XMLHttpRequests. Instead the form is submitted in the standard manner with the - * DOM <form> element temporarily modified to have its - * target set to refer - * to a dynamically generated, hidden <iframe> which is inserted into the document - * but removed after the return data has been gathered.

- *

Be aware that file upload packets, sent with the content type multipart/form-data - * and some server technologies (notably JEE) may require some custom processing in order to - * retrieve parameter names and parameter values from the packet content.

- * @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:
    - *
  • el : Ext.Element

    The Element being updated.

  • - *
  • success : Boolean

    True for success, false for failure.

  • - *
  • response : XMLHttpRequest

    The XMLHttpRequest which processed the update.

- */ - 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 - * "¶m1=1¶m2=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); - } - } - } -}()); +var ep = El.prototype; -/** - * @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 '<div class="loading-indicator">Loading...</div>'). - * @type String - */ - indicatorText : '
Loading...
', - /** - * 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 +El.addMethods = function(o){ + Ext.apply(ep, o); }; -/** - * Static convenience method. This method is deprecated in favor of el.load({url:'foo.php', ...}). - * Usage: - *
Ext.Updater.updateElement("my-div", "stuff.php");
- * @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); -}; +ep.on = ep.addListener; -/** - * @class Ext.Updater.BasicRenderer - * Default Content renderer. Updates the elements innerHTML with the responseText. - */ -Ext.Updater.BasicRenderer = function(){}; -Ext.Updater.BasicRenderer.prototype = { - /** - * This is called when the transaction is completed and it's time to update the element - The BasicRenderer - * updates the elements innerHTML with the responseText - To perform a custom render (i.e. XML or JSON processing), - * create an object with a "render(el, response)" method and pass it to setRenderer on the Updater. - * @param {Ext.Element} el The element being rendered - * @param {Object} response 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 - * PHP's date() function, and the formats that are - * supported will provide results equivalent to their PHP versions. - * - * The following is a list of all currently supported formats: - *
-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)\/
-
- * - * Example usage (note that you must escape format specifiers with '\\' to render them as character literals): - *

-// 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
-
- * - * 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. - *

-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"
-};
-
- * - * Example usage: - *

-var dt = new Date();
-document.write(dt.format(Date.patterns.ShortDate));
-
- *

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}.

- */ +ep.un = ep.removeListener; -/* - * 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() { +ep.autoBoxAdjust = true; -/** - * 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 false. - * @static - * @type Boolean -*/ -Date.useStrict = false; +var unitPattern = /\d+(px|em|%|en|ex|pt|in|cm|mm|pc)$/i, + docEl; -// 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, { - /** - *

An object hash in which each property is a date parsing function. The property name is the - * format string which that function parses.

- *

This object is automatically populated with date parsing functions as - * date formats are requested for Ext standard formatting strings.

- *

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}.

- *

Example:


-Date.parseFunctions['x-date-format'] = myDateParser;
-
- *

A parsing function should return a Date object, and is passed the following parameters:

    - *
  • date : String
    The date string to parse.
  • - *
  • strict : Boolean
    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.
  • - *

- *

To enable Dates to also be formatted 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; +El.get = function(el){ + var ex, + elm, + id; + if(!el){ return null; } + if (typeof el == "string") { + if (!(elm = DOC.getElementById(el))) { + return null; } - }, - parseRegexes: [], - - /** - *

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.

- *

This object is automatically populated with date formatting functions as - * date formats are requested for Ext standard formatting strings.

- *

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:


-Date.formatFunctions['x-date-format'] = myDateFormatter;
-
- *

A formatting function should return a string repesentation of the passed Date object:

    - *
  • date : Date
    The Date to format.
  • - *

- *

To enable date strings to also be parsed 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() + ')\\/'; + if (EC[el] && EC[el].el) { + ex = EC[el].el; + ex.dom = elm; + } else { + ex = El.addToCache(new El(elm)); } - }, - - y2kYear : 50, + return ex; + } else if (el.tagName) { + 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){ + + - /** - * Date interval constant - * @static - * @type String - */ - MILLI : "ms", + + 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) { + + if(!docEl){ + var f = function(){}; + f.prototype = El.prototype; + docEl = new f(); + docEl.dom = DOC; + } + return docEl; + } + return null; +}; - /** - * Date interval constant - * @static - * @type String - */ - SECOND : "s", +El.addToCache = function(el, id){ + id = id || el.id; + EC[id] = { + el: el, + data: {}, + events: {} + }; + return el; +}; - /** - * Date interval constant - * @static - * @type String - */ - MINUTE : "mi", - /** Date interval constant - * @static - * @type String - */ - HOUR : "h", +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); + } +}; - /** - * Date interval constant - * @static - * @type String - */ - DAY : "d", - /** - * Date interval constant - * @static - * @type String - */ - MONTH : "mo", - /** - * Date interval constant - * @static - * @type String - */ - YEAR : "y", - /** - *

An object hash containing default date values used during date parsing.

- *

The following properties are available:

    - *
  • y : Number
    The default year value. (defaults to undefined)
  • - *
  • m : Number
    The default 1-based month value. (defaults to undefined)
  • - *
  • d : Number
    The default day value. (defaults to undefined)
  • - *
  • h : Number
    The default hour value. (defaults to undefined)
  • - *
  • i : Number
    The default minute value. (defaults to undefined)
  • - *
  • s : Number
    The default second value. (defaults to undefined)
  • - *
  • ms : Number
    The default millisecond value. (defaults to undefined)
  • - *

- *

Override these properties to customize the default date values used by the {@link #parseDate} method.

- *

Note: In countries which experience Daylight Saving Time (i.e. DST), the h, i, s - * and ms properties may coincide with the exact time in which DST takes effect. - * It is the responsiblity of the developer to account for this.

- * Example Usage: - *

-// set default day value to the first day of the month
-Date.defaults.d = 1;
+function garbageCollect(){
+    if(!Ext.enableGarbageCollector){
+        clearInterval(El.collectorThreadId);
+    } else {
+        var eid,
+            el,
+            d,
+            o;
 
-// 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
-
- * @property defaults - * @static - * @type Object - */ - defaults: {}, + for(eid in EC){ + o = EC[eid]; + if(o.skipGC){ + continue; + } + el = o.el; + d = el.dom; + + + + + + + + + + + + + + + + + + if(!d || !d.parentNode || (!d.offsetParent && !DOC.getElementById(eid))){ + if(Ext.enableListenerCollection){ + Ext.EventManager.removeAll(d); + } + delete EC[eid]; + } + } + + if (Ext.isIE) { + var t = {}; + for (eid in EC) { + t[eid] = EC[eid]; + } + EC = Ext.elCache = t; + } + } +} +El.collectorThreadId = setInterval(garbageCollect, 30000); - /** - * An array of textual day names. - * Override these values for international dates. - * Example: - *

-Date.dayNames = [
-    'SundayInYourLang',
-    'MondayInYourLang',
-    ...
-];
-
- * @type Array - * @static - */ - dayNames : [ - "Sunday", - "Monday", - "Tuesday", - "Wednesday", - "Thursday", - "Friday", - "Saturday" - ], +var flyFn = function(){}; +flyFn.prototype = El.prototype; - /** - * An array of textual month names. - * Override these values for international dates. - * Example: - *

-Date.monthNames = [
-    'JanInYourLang',
-    'FebInYourLang',
-    ...
-];
-
- * @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: - *

-Date.monthNumbers = {
-    'ShortJanNameInYourLang':0,
-    'ShortFebNameInYourLang':1,
-    ...
+El.Flyweight = function(dom){
+    this.dom = dom;
 };
-
- * @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()]; - }, +El.Flyweight.prototype = new flyFn(); +El.Flyweight.prototype.isFlyweight = true; +El._flyweights = {}; - /** - * 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: - *

-Date.formatCodes.x = "String.leftPad(this.getDate(), 2, '0')";
-(new Date()).format("X"); // returns the current day of the month
-
- * @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(" + "); - }, - */ +El.fly = function(el, named){ + var ret = null; + named = named || '_global'; - U: "Math.round(this.getTime() / 1000)" - }, + if (el = Ext.getDom(el)) { + (El._flyweights[named] = El._flyweights[named] || new El.Flyweight()).dom = el; + ret = El._flyweights[named]; + } + return ret; +}; - /** - * 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); +Ext.get = El.get; - 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). - *

Example:


-//dt = Fri May 25 2007 (current date)
-var dt = new Date();
-
-//dt = Thu May 25 2006 (today'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
-
- * @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); - }, +Ext.fly = El.fly; - // 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 - } +var noBoxAdjust = Ext.isStrict ? { + select:1 +} : { + input:1, select:1, textarea:1 +}; +if(Ext.isIE || Ext.isGecko){ + noBoxAdjust['button'] = 1; +} - // 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)) +Ext.Element.addMethods(function(){ + var PARENTNODE = 'parentNode', + NEXTSIBLING = 'nextSibling', + PREVIOUSSIBLING = 'previousSibling', + DQ = Ext.DomQuery, + GET = Ext.get; + + return { + + 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; } - } - 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 = y >= 0? y : Ext.num(def.y, dt.getFullYear());", - "m = m >= 0? m : Ext.num(def.m - 1, dt.getMonth());", - "d = d >= 0? d : Ext.num(def.d, dt.getDate());", - - // time calculations (note: these calculations create a dependency on Ext.num()) - "h = h || Ext.num(def.h, dt.getHours());", - "i = i || Ext.num(def.i, dt.getMinutes());", - "s = s || Ext.num(def.s, dt.getSeconds());", - "ms = ms || Ext.num(def.ms, dt.getMilliseconds());", + 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; + }, + + + findParentNode : function(simpleSelector, maxDepth, returnEl){ + var p = Ext.fly(this.dom.parentNode, '_internal'); + return p ? p.findParent(simpleSelector, maxDepth, returnEl) : null; + }, + + + up : function(simpleSelector, maxDepth){ + return this.findParentNode(simpleSelector, maxDepth, true); + }, + + + select : function(selector){ + return Ext.Element.select(selector, this.dom); + }, + + + query : function(selector){ + return DQ.select(selector, this.dom); + }, + + + child : function(selector, returnDom){ + var n = DQ.selectNode(selector, this.dom); + return returnDom ? n : GET(n); + }, + + + down : function(selector, returnDom){ + var n = DQ.selectNode(" > " + selector, this.dom); + return returnDom ? n : GET(n); + }, + + + parent : function(selector, returnDom){ + return this.matchNode(PARENTNODE, PARENTNODE, selector, returnDom); + }, + + + next : function(selector, returnDom){ + return this.matchNode(NEXTSIBLING, NEXTSIBLING, selector, returnDom); + }, + + + prev : function(selector, returnDom){ + return this.matchNode(PREVIOUSSIBLING, PREVIOUSSIBLING, selector, returnDom); + }, + + + + first : function(selector, returnDom){ + return this.matchNode(NEXTSIBLING, 'firstChild', selector, returnDom); + }, + + + 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; + } + }; +}()); +Ext.Element.addMethods( +function() { + var GETDOM = Ext.getDom, + GET = Ext.get, + DH = Ext.DomHelper; + + return { + + appendChild: function(el){ + return GET(el).appendTo(this); + }, + + + appendTo: function(el){ + GETDOM(el).appendChild(this.dom); + return this; + }, + + + insertBefore: function(el){ + (el = GETDOM(el)).parentNode.insertBefore(this.dom, el); + return this; + }, + + + insertAfter: function(el){ + (el = GETDOM(el)).parentNode.insertBefore(this.dom, el.nextSibling); + return this; + }, + + + insertFirst: function(el, returnDom){ + el = el || {}; + if(el.nodeType || el.dom || typeof el == 'string'){ + el = GETDOM(el); + this.dom.insertBefore(el, this.dom.firstChild); + return !returnDom ? GET(el) : el; + }else{ + return this.createChild(el, this.dom.firstChild, returnDom); + } + }, + + + replace: function(el){ + el = GET(el); + this.insertBefore(el); + el.remove(); + return 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; + }, + + + 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); + }, + + + 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; + }, + + + insertHtml : function(where, html, returnEl){ + var el = DH.insertHtml(where, this.dom, html); + return returnEl ? Ext.get(el) : el; + } + }; +}()); +Ext.Element.addMethods(function(){ + + var supports = Ext.supports, + propCache = {}, + camelRe = /(-[a-z])/gi, + view = document.defaultView, + opacityRe = /alpha\(opacity=(.*)\)/i, + trimRe = /^\s+|\s+$/g, + EL = Ext.Element, + spacesRe = /\s+/, + wordsRe = /\w/g, + 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', + + 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; - "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);", + + function camelFn(m, a) { + return a.charAt(1).toUpperCase(); + } - // 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);", - "}", - "}", - "}", + function chkCache(prop) { + return propCache[prop] || (propCache[prop] = prop == 'float' ? (supports.cssFloat ? 'cssFloat' : 'styleFloat') : prop.replace(camelRe, camelFn)); + } - "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 { + + 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; + }, - "return v;" - ].join('\n'); + + 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; + }, - 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); + + addClass : function(className){ + var me = this, + i, + len, + v, + cls = []; + + 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(" "); + } } - - Date.parseRegexes[regexNum] = new RegExp("^" + regex.join('') + "$", "i"); - 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) + return me; }, - 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("|") +")" + + + removeClass : function(className){ + var me = this, + i, + idx, + len, + cls, + elClasses; + if (!Ext.isArray(className)){ + className = [className]; } - }, - l: function() { - return { - g:0, - c:null, - s:"(?:" + Date.dayNames.join("|") + ")" + 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; }, - N: { - g:0, - c:null, - s:"[1-7]" // ISO-8601 day number (1 (monday) - 7 (sunday)) + + + 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); }, - S: { - g:0, - c:null, - s:"(?:st|nd|rd|th)" + + + toggleClass : function(className){ + return this.hasClass(className) ? this.removeClass(className) : this.addClass(className); }, - w: { - g:0, - c:null, - s:"[0-6]" // javascript day number (0 (sunday) - 6 (saturday)) + + + hasClass : function(className){ + return className && (' '+this.dom.className+' ').indexOf(' '+className+' ') != -1; }, - z: { - g:1, - c:"z = parseInt(results[{0}], 10);\n", - s:"(\\d{1,3})" // day of the year (0 - 364 (365 in leap years)) + + + replaceClass : function(oldClassName, newClassName){ + return this.removeClass(oldClassName).addClass(newClassName); }, - W: { - g:0, - c:null, - s:"(?:\\d{2})" // ISO-8601 week number (with leading zero) + + isStyle : function(style, val) { + return this.getStyle(style) == val; }, - F: function() { - return { - g:1, - c:"m = parseInt(Date.getMonthNumber(results[{0}]), 10);\n", // get localised month number - s:"(" + Date.monthNames.join("|") + ")" + + + getStyle : function(){ + return view && view.getComputedStyle ? + function(prop){ + var el = this.dom, + v, + cs, + out, + display; + + if(el == document){ + return null; + } + prop = chkCache(prop); + out = (v = el.style[prop]) ? v : + (cs = view.getComputedStyle(el, "")) ? cs[prop] : null; + + + + if(prop == 'marginRight' && out != '0px' && !supports.correctRightMargin){ + display = el.style.display; + el.style.display = 'inline-block'; + out = view.getComputedStyle(el, '').marginRight; + el.style.display = display; + } + + if(prop == 'backgroundColor' && out == 'rgba(0, 0, 0, 0)' && !supports.correctTransparentColor){ + out = 'transparent'; + } + 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); + }; + }(), + + + 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); }, - 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"); + + + setStyle : function(prop, value){ + var tmp, style; + + 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; }, - Y: { - g:1, - c:"y = parseInt(results[{0}], 10);\n", - s:"(\\d{4})" // 4-digit year + + + 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; }, - 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})" + + + 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; }, - 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)" + + + 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; }, - 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)" + + + 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; }, - g: function() { - return $f("G"); + + + 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; }, - 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) + + + 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; }, - h: function() { - return $f("H"); + + + getBorderWidth : function(side){ + return this.addStyles(side, borders); }, - H: { - g:1, - c:"h = parseInt(results[{0}], 10);\n", - s:"(\\d{2})" // 24-hr format of an hour with leading zeroes (00 - 23) + + + getPadding : function(side){ + return this.addStyles(side, paddings); }, - i: { - g:1, - c:"i = parseInt(results[{0}], 10);\n", - s:"(\\d{2})" // minutes with leading zeros (00 - 59) + + + 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; }, - s: { - g:1, - c:"s = parseInt(results[{0}], 10);\n", - s:"(\\d{2})" // seconds with leading zeros (00 - 59) + + + 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; }, - 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) + + + 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; }, - 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 - } - } -}); + margins : margins + }; +}() +); -}()); +(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.apply(Date.prototype, { - // private - dateFormat : function(format) { - if (Date.formatFunctions[format] == null) { - Date.createFormat(format); - } - return Date.formatFunctions[format].call(this); +Ext.Element.addMethods({ + + getX : function(){ + return D.getX(this.dom); }, - /** - * 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, ""); + + getY : function(){ + return D.getY(this.dom); }, - /** - * 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"); + + getXY : function(){ + return D.getXY(this.dom); }, - /** - * 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; + + getOffsetsTo : function(el){ + var o = this.getXY(), + e = Ext.fly(el, '_internal').getXY(); + return [o[0]-e[0],o[1]-e[1]]; + }, - for (i = 0, d.setDate(1), d.setMonth(0); i < m; d.setMonth(++i)) { - num += d.getDaysInMonth(); - } - return num + this.getDate() - 1; + + setX : function(x, animate){ + return this.setXY([x, this.getY()], this.animTest(arguments, animate, 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 + + setY : function(y, animate){ + return this.setXY([this.getX(), y], this.animTest(arguments, animate, 1)); + }, - 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(); + + setLeft : function(left){ + this.setStyle(LEFT, this.addUnits(left)); + return this; + }, - return AWN - Math.floor(Date.UTC(Wyr, 0, 7) / ms7d) + 1; - } - }(), + + setTop : function(top){ + this.setStyle(TOP, this.addUnits(top)); + return this; + }, - /** - * 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))); + + setRight : function(right){ + this.setStyle(RIGHT, this.addUnits(right)); + return this; }, - /** - * 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: - *

-var dt = new Date('1/10/2007');
-document.write(Date.dayNames[dt.getFirstDayOfMonth()]); //output: 'Monday'
-
- * @return {Number} The day number (0-6). - */ - getFirstDayOfMonth : function() { - var day = (this.getDay() - (this.getDate() - 1)) % 7; - return (day < 0) ? (day + 7) : day; + + setBottom : function(bottom){ + this.setStyle(BOTTOM, this.addUnits(bottom)); + return this; }, - /** - * 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: - *

-var dt = new Date('1/10/2007');
-document.write(Date.dayNames[dt.getLastDayOfMonth()]); //output: 'Wednesday'
-
- * @return {Number} The day number (0-6). - */ - getLastDayOfMonth : function() { - return this.getLastDateOfMonth().getDay(); + + 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; }, + + setLocation : function(x, y, animate){ + return this.setXY([x, y], this.animTest(arguments, animate, 2)); + }, - /** - * 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); + + moveTo : function(x, y, animate){ + return this.setXY([x, y], this.animTest(arguments, animate, 2)); + }, + + + getLeft : function(local){ + return !local ? this.getX() : parseInt(this.getStyle(LEFT), 10) || 0; }, - /** - * 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()); + + getRight : function(local){ + var me = this; + return !local ? me.getX() + me.getWidth() : (me.getLeft(true) + me.getWidth()) || 0; }, - /** - * 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]; + + getTop : function(local) { + return !local ? this.getY() : parseInt(this.getStyle(TOP), 10) || 0; + }, - return function() { // return a closure for efficiency - var m = this.getMonth(); + + getBottom : function(local){ + var me = this; + return !local ? me.getY() + me.getHeight() : (me.getTop(true) + me.getHeight()) || 0; + }, - return m == 1 && this.isLeapYear() ? 29 : daysInMonth[m]; + + 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); } - }(), - - /** - * 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"; + if(zIndex){ + me.setStyle(ZINDEX, zIndex); } + if(x || y) me.setXY([x || false, y || false]); }, - /** - * 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: - *

-//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'
-
- * @return {Date} The new Date instance. - */ - clone : function() { - return new Date(this.getTime()); + + clearPositioning : function(value){ + value = value || ''; + this.setStyle({ + left : value, + right : value, + top : value, + bottom : value, + "z-index" : "", + position : STATIC + }); + return this; }, - /** - * 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(); + + 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) + }; }, + + + 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; + }, + + + 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); - /** - * 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(); + 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; + } +}); +})(); +Ext.Element.addMethods({ + + isScrollable : function(){ + var dom = this.dom; + return dom.scrollHeight > dom.clientHeight || dom.scrollWidth > dom.clientWidth; + }, + + + scrollTo : function(side, value){ + this.dom["scroll" + (/top/i.test(side) ? "Top" : "Left")] = value; + return this; + }, + + + 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; + } +}); - // get current date before clearing time - var d = this.getDate(); +Ext.Element.VISIBILITY = 1; - // clear time - this.setHours(0); - this.setMinutes(0); - this.setSeconds(0); - this.setMilliseconds(0); +Ext.Element.DISPLAY = 2; - 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)); +Ext.Element.OFFSETS = 3; - this.setDate(d); - this.setHours(c.getHours()); - } - return this; - }, +Ext.Element.ASCLASS = 4; - /** - * 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: - *

-// 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'
+Ext.Element.visibilityCls = 'x-hide-nosize';
 
-// 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'
-
- * - * @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; +Ext.Element.addMethods(function(){ + var El = Ext.Element, + OPACITY = "opacity", + VISIBILITY = "visibility", + DISPLAY = "display", + HIDDEN = "hidden", + OFFSETS = "offsets", + ASCLASS = "asclass", + NONE = "none", + NOSIZE = 'nosize', + ORIGINALDISPLAY = 'originalDisplay', + VISMODE = 'visibilityMode', + ISVISIBLE = 'isVisible', + data = El.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; + }; - 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; - }, + return { + + originalDisplay : "", + visibilityMode : 1, - /** - * 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(); - } -}); + + setVisibilityMode : function(visMode){ + data(this.dom, VISMODE, visMode); + return this; + }, + + animate : function(args, duration, onComplete, easing, animType){ + this.anim(args, {duration: duration, callback: onComplete, easing: easing}, animType); + return this; + }, -/** - * 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; + + 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; + }, + + 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]}); + }, -// private -if (Ext.isSafari && (navigator.userAgent.match(/WebKit\/(\d+)/)[1] || NaN) < 420) { - Ext.apply(Date.prototype, { - _xMonth : Date.prototype.setMonth, - _xDate : Date.prototype.setDate, + + isVisible : function() { + var me = this, + dom = me.dom, + visible = data(dom, ISVISIBLE); - // 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; + if(typeof visible == 'boolean'){ + return visible; + } + + visible = !me.isStyle(VISIBILITY, HIDDEN) && + !me.isStyle(DISPLAY, NONE) && + !((getVisMode(dom) == El.ASCLASS) && me.hasClass(me.visibilityCls || El.visibilityCls)); - this.setFullYear(this.getFullYear() - back_year); + data(dom, ISVISIBLE, visible); + return visible; + }, - return this._xMonth(month); - } else { - return this._xMonth(num); + + setVisible : function(visible, animate){ + var me = this, isDisplay, isVisibility, isOffsets, isNosize, + dom = me.dom, + visMode = getVisMode(dom); + + + + if (typeof animate == 'string'){ + switch (animate) { + case DISPLAY: + visMode = El.DISPLAY; + break; + case VISIBILITY: + visMode = El.VISIBILITY; + break; + case OFFSETS: + visMode = El.OFFSETS; + break; + case NOSIZE: + case ASCLASS: + visMode = El.ASCLASS; + break; + } + me.setVisibilityMode(visMode); + animate = false; } - }, - // 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); - } - }); -} + if (!animate || !me.anim) { + if(visMode == El.ASCLASS ){ + me[visible?'removeClass':'addClass'](me.visibilityCls || El.visibilityCls); + } else if (visMode == El.DISPLAY){ -/* 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.DelayedTask - *

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.

- *

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:


-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); 
-});
- * 
- *

Note that we are using a DelayedTask here to illustrate a point. The configuration - * option buffer for {@link Ext.util.Observable#addListener addListener/on} will - * also setup a delayed task for you to buffer events.

- * @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 this reference) in which the - * function is called. If not specified, this 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, this 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); - }; + return me.setDisplayed(visible); - /** - * Cancel the last queued timeout - */ - me.cancel = function(){ - if(id){ - clearInterval(id); - id = null; - } - }; -};/** - * @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 true if the {@link #addAll} - * function should add function references to the collection. Defaults to - * false. - * @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 true if the {@link #addAll} - * function should add function references to the collection. Defaults to - * false. - */ - allowFunctions : false, - - /** - * Adds an item to the collection. Fires the {@link #add} event when complete. - * @param {String} key

The key to associate with the item, or the new item.

- *

If a {@link #getKey} implementation was specified for this MixedCollection, - * or if the key of the stored items is in a property called id, - * the MixedCollection will be able to derive the key for the new item. - * In this case just pass the new item in this parameter.

- * @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 item.id but you can provide your own implementation - * to return a different value as in the following examples:

-// 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);
-     * 
- * @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

The key associated with the item to replace, or the replacement item.

- *

If you supplied a {@link #getKey} implementation for this MixedCollection, or if the key - * of your stored items is in a property called id, then the MixedCollection - * will be able to derive 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.

- * @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 {@link #allowFunctions} - * has been set to true. - */ - 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: - *
    - *
  • item : Mixed

    The collection item

  • - *
  • index : Number

    The item's index

  • - *
  • length : Number

    The total number of items in the collection

  • - *
- * 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 in which to execute the function. - */ - 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 in which to execute the function. - */ - 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 in which to execute the function. - * @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 undefined. - * If an item was found, but is a Class, returns null. - */ - item : function(key){ - var mk = this.map[key], - item = mk !== undefined ? mk : (typeof key == 'number') ? this.items[key] : undefined; - return !Ext.isFunction(item) || 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 - * @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, - c = [], k = this.keys, items = this.items; - - fn = fn || function(a, b){ - return a-b; - }; - for(i = 0, len = items.length; i < len; i++){ - c[c.length] = {key: k[i], value: items[i], index: i}; - } - 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; - }); - for(i = 0, len = c.length; i < len; i++){ - items[i] = c[i].value; - k[i] = c[i].key; - } - this.fireEvent('sort', this); - }, - - /** - * Sorts this collection by item 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); - }, - - /** - * Sorts this collection by keys. - * @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 objects 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 new 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 of the function (defaults to this) - * @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 true 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 of the function (defaults to this). - * @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; - }, - - // private - createValueMatcher : function(value, anyMatch, caseSensitive){ - if(!value.exec){ // not a regex - value = String(value); - value = new RegExp((anyMatch === true ? '' : '^') + Ext.escapeRe(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 undefined. If an item was found, but is a Class, - * returns null. - */ -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; + } else if (visMode == El.OFFSETS){ - return function() { - if (useNative === null) { - useNative = Ext.USE_NATIVE_JSON && window.JSON && JSON.toString() == '[object JSON]'; + 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: ''}); + delete me.hideModeStyles; + } + + }else{ + me.fixDisplay(); + dom.style.visibility = visible ? "visible" : HIDDEN; + } + }else{ + + if(visible){ + me.setOpacity(.01); + me.setVisible(true); } + me.anim({opacity: { to: (visible?1:0) }}, + me.preanim(arguments, 1), + null, + .35, + 'easeIn', + function(){ + visible || me.setVisible(false).setOpacity(1); + }); + } + data(dom, ISVISIBLE, visible); + return me; + }, + + - return useNative; - }; - }(), - pad = function(n) { - return n < 10 ? "0" + n : n; + hasMetrics : function(){ + var dom = this.dom; + return this.isVisible() || (getVisMode(dom) == El.VISIBILITY); }, - doDecode = function(json){ - return eval("(" + json + ')'); + + + toggle : function(animate){ + var me = this; + me.setVisible(!me.isVisible(), me.preanim(arguments, 0)); + return me; }, - 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(""); - } + + + setDisplayed : function(value) { + if(typeof value == "boolean"){ + value = value ? getDisplay(this.dom) : NONE; + } + this.setStyle(DISPLAY, value); + return this; }, - m = { - "\b": '\\b', - "\t": '\\t', - "\n": '\\n', - "\f": '\\f', - "\r": '\\r', - '"' : '\\"', - "\\": '\\\\' + + + fixDisplay : function(){ + var me = this; + if(me.isStyle(DISPLAY, NONE)){ + me.setStyle(VISIBILITY, HIDDEN); + me.setStyle(DISPLAY, getDisplay(this.dom)); + if(me.isStyle(DISPLAY, NONE)){ + me.setStyle(DISPLAY, "block"); + } + } }, - 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); - }) + '"'; + + + hide : function(animate){ + + if (typeof animate == 'string'){ + this.setVisible(false, animate); + return this; } - return '"' + s + '"'; + this.setVisible(false, this.preanim(arguments, 0)); + return this; }, - 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(""); - }; - this.encodeDate = function(o){ - return '"' + o.getFullYear() + "-" + - pad(o.getMonth() + 1) + "-" + - pad(o.getDate()) + "T" + - pad(o.getHours()) + ":" + - pad(o.getMinutes()) + ":" + - pad(o.getSeconds()) + '"'; + + show : function(animate){ + + if (typeof animate == 'string'){ + this.setVisible(true, animate); + return this; + } + this.setVisible(true, this.preanim(arguments, 0)); + return this; + } }; - - /** - * 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; +}());(function(){ + + 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", + + flyEl = new Ext.Element.Flyweight(), + queues = {}, + getObject = function(o){ + return o || {}; + }, + fly = function(dom){ + flyEl.dom = dom; + flyEl.id = Ext.id(dom); + return flyEl; + }, + + getQueue = function(id){ + if(!queues[id]){ + queues[id] = []; } - return ec(o); + return queues[id]; + }, + setQueue = function(id, value){ + queues[id] = value; }; - }(); + +Ext.enableFx = TRUE; - /** - * 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; + +Ext.Fx = { + + + + switchStatements : function(key, fn, argHash){ + return fn.apply(this, argHash[key]); + }, + + + 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(); + + fly(dom).fixDisplay(); + + + 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; + + + fly(dom).setWidth(b.width).setHeight(b.height); + + + wrap = fly(dom).fxWrap(r.pos, o, HIDDEN); + + st.visibility = VISIBLE; + st.position = ABSOLUTE; + + + function after(){ + fly(dom).fxUnwrap(wrap, r.pos, o); + st.width = r.width; + st.height = r.height; + fly(dom).afterFx(o); } - return dc(json); - }; - }(); + + + 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; + }; -})(); -/** - * 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; - 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); - var 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, "&").replace(/>/g, ">").replace(/, 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(/>/g, ">").replace(/</g, "<").replace(/"/g, '"').replace(/&/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('.'); - var whole = ps[0]; - var sub = ps[1] ? '.'+ ps[1] : '.00'; - var 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 parse() 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); - }; - }, - - // private - stripTagsRE : /<\/?[^>]+>/gi, - - /** - * 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(this.stripTagsRE, ""); - }, - - stripScriptsRe : /(?:)((\n|\r|.)*?)(?:<\/script>)/ig, - - /** - * 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(this.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:

-         * var tpl = new Ext.Template('{value} * 10 = {value:math("* 10")}');
-         * 
- * @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. - *
examples (123456.789): - *
- * 0 - (123456) show only digits, no precision
- * 0.00 - (123456.78) show only digits, 2 precision
- * 0.0000 - (123456.7890) show only digits, 4 precision
- * 0,000 - (123,456) show comma and digits, no precision
- * 0,000.00 - (123,456.78) show comma and digits, 2 precision
- * 0,0.00 - (123,456.78) shortcut method, show comma and digits, 2 precision
- * To reverse the grouping (,) and decimal (.) for international numbers, add /i to the end. - * For example: 0.000,00/i - *
- * @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(); - if(hasComma){ - psplit = fnum.split('.'); - - 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]; - } - } - - 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 <br/> - * @param {String} The string value to format. - * @return {String} The string with embedded <br/> tags in place of newlines. - */ - nl2br : function(v){ - return v === undefined || v === null ? '' : v.replace(/\n/g, '
'); - } - } -}();/** - * @class Ext.XTemplate - * @extends Ext.Template - *

A template class that supports advanced functionality like:

    - *
  • Autofilling arrays using templates and sub-templates
  • - *
  • Conditional processing with basic comparison operators
  • - *
  • Basic math function support
  • - *
  • Execute arbitrary inline code with special built-in template variables
  • - *
  • Custom member functions
  • - *
  • 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
  • - *

- *

XTemplate provides the templating mechanism built into:

    - *
  • {@link Ext.DataView}
  • - *
  • {@link Ext.ListView}
  • - *
  • {@link Ext.form.ComboBox}
  • - *
  • {@link Ext.grid.TemplateColumn}
  • - *
  • {@link Ext.grid.GroupingView}
  • - *
  • {@link Ext.menu.Item}
  • - *
  • {@link Ext.layout.MenuLayout}
  • - *
  • {@link Ext.ColorPalette}
  • - *

- * - *

For example usage {@link #XTemplate see the constructor}.

- * - * @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.

- * - *
    - * - *
  • Sample Data - *
    - *

    This is the data object used for reference in each code example:

    - *
    
    -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
    -    }]
    -};
    - * 
    - *
    - *
  • - * - * - *
  • Auto filling of arrays - *
    - *

    The tpl tag and the for operator are used - * to process the provided data object: - *

      - *
    • If the value specified in for is an array, it will auto-fill, - * repeating the template block inside the tpl tag for each item in the - * array.
    • - *
    • If for="." is specified, the data object provided is examined.
    • - *
    • While processing an array, the special variable {#} - * will provide the current array index + 1 (starts at 1, not 0).
    • - *
    - *

    - *
    
    -<tpl for=".">...</tpl>       // loop through array at root node
    -<tpl for="foo">...</tpl>     // loop through array at foo node
    -<tpl for="foo.bar">...</tpl> // loop through array at foo.bar node
    - * 
    - * Using the sample data above: - *
    
    -var tpl = new Ext.XTemplate(
    -    '<p>Kids: ',
    -    '<tpl for=".">',       // process the data.kids node
    -        '<p>{#}. {name}</p>',  // use current array index to autonumber
    -    '</tpl></p>'
    -);
    -tpl.overwrite(panel.body, data.kids); // pass the kids property of the data object
    - * 
    - *

    An example illustrating how the for property can be leveraged - * to access specified members of the provided data object to populate the template:

    - *
    
    -var tpl = new Ext.XTemplate(
    -    '<p>Name: {name}</p>',
    -    '<p>Title: {title}</p>',
    -    '<p>Company: {company}</p>',
    -    '<p>Kids: ',
    -    '<tpl for="kids">',     // interrogate the kids property within the data
    -        '<p>{name}</p>',
    -    '</tpl></p>'
    -);
    -tpl.overwrite(panel.body, data);  // pass the root node of the data object
    - * 
    - *

    Flat arrays that contain values (and not objects) can be auto-rendered - * using the special {.} variable inside a loop. This variable - * will represent the value of the array at the current index:

    - *
    
    -var tpl = new Ext.XTemplate(
    -    '<p>{name}\'s favorite beverages:</p>',
    -    '<tpl for="drinks">',
    -       '<div> - {.}</div>',
    -    '</tpl>'
    -);
    -tpl.overwrite(panel.body, data);
    - * 
    - *

    When processing a sub-template, for example while looping through a child array, - * you can access the parent object's members via the parent object:

    - *
    
    -var tpl = new Ext.XTemplate(
    -    '<p>Name: {name}</p>',
    -    '<p>Kids: ',
    -    '<tpl for="kids">',
    -        '<tpl if="age > 1">',
    -            '<p>{name}</p>',
    -            '<p>Dad: {parent.name}</p>',
    -        '</tpl>',
    -    '</tpl></p>'
    -);
    -tpl.overwrite(panel.body, data);
    - * 
    - *
    - *
  • - * - * - *
  • Conditional processing with basic comparison operators - *
    - *

    The tpl tag and the if operator are used - * to provide conditional checks for deciding whether or not to render specific - * parts of the template. Notes:

      - *
    • Double quotes must be encoded if used within the conditional
    • - *
    • There is no else operator — if needed, two opposite - * if statements should be used.
    • - *
    - *
    
    -<tpl if="age > 1 && age < 10">Child</tpl>
    -<tpl if="age >= 10 && age < 18">Teenager</tpl>
    -<tpl if="this.isGirl(name)">...</tpl>
    -<tpl if="id==\'download\'">...</tpl>
    -<tpl if="needsIcon"><img src="{icon}" class="{iconCls}"/></tpl>
    -// no good:
    -<tpl if="name == "Jack"">Hello</tpl>
    -// encode " if it is part of the condition, e.g.
    -<tpl if="name == &quot;Jack&quot;">Hello</tpl>
    - * 
    - * Using the sample data above: - *
    
    -var tpl = new Ext.XTemplate(
    -    '<p>Name: {name}</p>',
    -    '<p>Kids: ',
    -    '<tpl for="kids">',
    -        '<tpl if="age > 1">',
    -            '<p>{name}</p>',
    -        '</tpl>',
    -    '</tpl></p>'
    -);
    -tpl.overwrite(panel.body, data);
    - * 
    - *
    - *
  • - * - * - *
  • Basic math support - *
    - *

    The following basic math operators may be applied directly on numeric - * data values:

    - * + - * /
    - * 
    - * For example: - *
    
    -var tpl = new Ext.XTemplate(
    -    '<p>Name: {name}</p>',
    -    '<p>Kids: ',
    -    '<tpl for="kids">',
    -        '<tpl if="age &gt; 1">',  // <-- Note that the > is encoded
    -            '<p>{#}: {name}</p>',  // <-- Auto-number each item
    -            '<p>In 5 Years: {age+5}</p>',  // <-- Basic math
    -            '<p>Dad: {parent.name}</p>',
    -        '</tpl>',
    -    '</tpl></p>'
    -);
    -tpl.overwrite(panel.body, data);
    -
    - *
    - *
  • - * - * - *
  • Execute arbitrary inline code with special built-in template variables - *
    - *

    Anything between {[ ... ]} is considered code to be executed - * in the scope of the template. There are some special variables available in that code: - *

      - *
    • values: The values in the current scope. If you are using - * scope changing sub-templates, you can change what values is.
    • - *
    • parent: The scope (values) of the ancestor template.
    • - *
    • xindex: If you are in a looping template, the index of the - * loop you are in (1-based).
    • - *
    • xcount: If you are in a looping template, the total length - * of the array you are looping.
    • - *
    • fm: An alias for Ext.util.Format.
    • - *
    - * This example demonstrates basic row striping using an inline code block and the - * xindex variable:

    - *
    
    -var tpl = new Ext.XTemplate(
    -    '<p>Name: {name}</p>',
    -    '<p>Company: {[values.company.toUpperCase() + ", " + values.title]}</p>',
    -    '<p>Kids: ',
    -    '<tpl for="kids">',
    -       '<div class="{[xindex % 2 === 0 ? "even" : "odd"]}">',
    -        '{name}',
    -        '</div>',
    -    '</tpl></p>'
    -);
    -tpl.overwrite(panel.body, data);
    - * 
    - *
    - *
  • - * - *
  • Template member functions - *
    - *

    One or more member functions can be specified in a configuration - * object passed into the XTemplate constructor for more complex processing:

    - *
    
    -var tpl = new Ext.XTemplate(
    -    '<p>Name: {name}</p>',
    -    '<p>Kids: ',
    -    '<tpl for="kids">',
    -        '<tpl if="this.isGirl(name)">',
    -            '<p>Girl: {name} - {age}</p>',
    -        '</tpl>',
    -        // use opposite if statement to simulate 'else' processing:
    -        '<tpl if="this.isGirl(name) == false">',
    -            '<p>Boy: {name} - {age}</p>',
    -        '</tpl>',
    -        '<tpl if="this.isBaby(age)">',
    -            '<p>{name} is a baby!</p>',
    -        '</tpl>',
    -    '</tpl></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);
    - * 
    - *
    - *
  • - * - *
- * - * @param {Mixed} config - */ -Ext.XTemplate = function(){ - Ext.XTemplate.superclass.constructor.apply(this, arguments); + 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; + }, + + + 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"; - var me = this, - s = me.html, - re = /]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/, - nameRe = /^]*?for="(.*?)"/, - ifRe = /^]*?if="(.*?)"/, - execRe = /^]*?exec="(.*?)"/, - m, - id = 0, - tpls = [], - VALUES = 'values', - PARENT = 'parent', - XINDEX = 'xindex', - XCOUNT = 'xcount', - RETURN = 'return ', - WITHVALUES = 'with(values){ '; + me.queueFx(o, function(){ + + + 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; + + + fly(dom).setWidth(b.width).setHeight(b.height); - s = ['', s, ''].join(''); + + 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; + }, - 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] : ''; + + 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(); - 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]||'' + + 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); }); - s = s.replace(m[0], '{xtpl'+ id + '}'); - ++id; - } - Ext.each(tpls, function(t) { - me.compileTpl(t); - }); - 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, + return me; + }, - // private - applySubTemplate : function(id, values, parent, xindex, xcount){ + + switchOff : function(o){ + o = getObject(o); 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)){ - Ext.each(vs, function(v, i) { - buf[buf.length] = t.compiled.call(me, v, parent, i+1, len); - }); - return buf.join(''); - } - return t.compiled.call(me, vs, parent, xindex, xcount); + dom = me.dom, + st = dom.style, + r; + + me.queueFx(o, function(){ + fly(dom).clearOpacity(); + fly(dom).clip(); + + + 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; }, - // private - compileTpl : function(tpl){ - var fm = Ext.util.Format, - useF = this.disableFormats !== true, - sep = Ext.isGecko ? "+" : ",", - body; + + 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; + }, - 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"; + + 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, + border : '0px solid ' + color + } + }); + return proxy.queueFx({}, animFn); + }; + + + arguments.callee.anim = { + isAnimated: true, + stop: function() { + count = 0; + proxy.stopFx(); } - } 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 + "'"; - } + }; + + 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; + }, - // 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); + + 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; }, - /** - * 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); + + 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; }, - /** - * 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 - */ + + 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; + }, -}); -/** - * 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; + + scale : function(w, h, o){ + this.shift(Ext.apply({}, o, { + width: w, + height: h + })); + return this; + }, -/** - * Creates a template from the passed element's value (display:none 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(); + + 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; + }, - Ext.apply(this, config); + + 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"; - 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" - ); + me.queueFx(o, function(){ + + 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; + }, - if(!this.disabled){ - this.disabled = true; - this.enable(); - } + + syncFx : function(){ + var me = this; + me.fxDefaults = Ext.apply(me.fxDefaults || {}, { + block : FALSE, + concurrent : TRUE, + stopFx : FALSE + }); + return me; + }, - // allow inline handler - if(this.handler){ - this.on("click", this.handler, this.scope || this); - } + + sequenceFx : function(){ + var me = this; + me.fxDefaults = Ext.apply(me.fxDefaults || {}, { + block : FALSE, + concurrent : FALSE, + stopFx : FALSE + }); + return me; + }, - Ext.util.ClickRepeater.superclass.constructor.call(this); -}; + + nextFx : function(){ + var ef = getQueue(this.dom.id)[0]; + if(ef){ + ef.call(this); + } + }, -Ext.extend(Ext.util.ClickRepeater, Ext.util.Observable, { - interval : 20, - delay: 250, - preventDefault : true, - stopDefault : false, - timer : 0, + + hasActiveFx : function(){ + return getQueue(this.dom.id)[0]; + }, - /** - * Enables the repeater and allows events to fire. - */ - enable: function(){ - if(this.disabled){ - this.el.on('mousedown', this.handleMouseDown, this); - if(this.preventDefault || this.stopDefault){ - this.el.on('click', this.eventOptions, this); + + 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]); + cur.anim.stop(finish !== undefined ? finish : TRUE); + }else{ + setQueue(id, []); + } } } - this.disabled = false; + return me; }, + - /** - * 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); + beforeFx : function(o){ + if(this.hasActiveFx() && !o.concurrent){ + if(o.stopFx){ + this.stopFx(); + return TRUE; + } + return FALSE; + } + return TRUE; + }, + + + hasFxBlock : function(){ + var q = getQueue(this.dom.id); + return q && q[0] && q[0].block; + }, + + + 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); } - Ext.getDoc().un('mouseup', this.handleMouseUp, this); - this.el.removeAllListeners(); } - this.disabled = true; + return me; }, + - /** - * Convenience function for setting disabled/enabled by boolean. - * @param {Boolean} disabled - */ - setDisabled: function(disabled){ - this[disabled ? 'disable' : 'enable'](); + 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; }, + - eventOptions: function(e){ - if(this.preventDefault){ - e.preventDefault(); + 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(); } - if(this.stopDefault){ - e.stopEvent(); - } }, + - // private - destroy : function() { - this.disable(true); - Ext.destroy(this.el); - this.purgeListeners(); + getFxRestore : function(){ + var st = this.dom.style; + return {pos: this.getPositioning(), width: st.width, height : st.height}; }, + - // private - handleMouseDown : function(){ - clearTimeout(this.timer); - this.el.blur(); - if(this.pressClass){ - this.el.addClass(this.pressClass); + afterFx : function(o){ + var dom = this.dom, + id = dom.id; + if(o.afterStyle){ + fly(dom).setStyle(o.afterStyle); } - this.mousedownTime = new Date(); + 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(); + } + }, - Ext.getDoc().on("mouseup", this.handleMouseUp, this); - this.el.on("mouseout", this.handleMouseOut, this); + + 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; + } +}; - 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); - }, +Ext.Fx.resize = Ext.Fx.scale; - // 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); + + +Ext.Element.addMethods(Ext.Fx); +})(); + +Ext.CompositeElementLite = function(els, root){ + + this.elements = []; + this.add(els, root); + this.el = new Ext.Element.Flyweight(); +}; + +Ext.CompositeElementLite.prototype = { + isComposite: true, + + + getElement : function(el){ + + var e = this.el; + e.dom = el; + e.id = el.id; + return e; }, - easeOutExpo : function (t, b, c, d) { - return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b; + + transformElement : function(el){ + return Ext.getDom(el); }, - // private - handleMouseOut : function(){ - clearTimeout(this.timer); - if(this.pressClass){ - this.el.removeClass(this.pressClass); - } - this.el.on("mouseover", this.handleMouseReturn, this); + + getCount : function(){ + return this.elements.length; }, + + 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]; + } - // private - handleMouseReturn : function(){ - this.el.un("mouseover", this.handleMouseReturn, this); - if(this.pressClass){ - this.el.addClass(this.pressClass); + for(var i = 0, len = els.length; i < len; ++i){ + elements.push(me.transformElement(els[i])); } - this.click(); + return me; }, - // 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 - *

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.

- *

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:

-

-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
-});
-
- * @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, + invoke : function(fn, args){ + var me = this, + els = me.elements, + len = els.length, + e, + i; - // 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](); + for(i = 0; i < len; i++) { + e = els[i]; + if(e){ + Ext.Element.prototype[fn].apply(me.getElement(e), args); } } + return me; }, + + item : function(index){ + var me = this, + el = me.elements[index], + out = null; - // private - doRelay : function(e, h, hname){ - return h.call(this.scope || this, e); + if(el){ + out = me.getElement(el); + } + return out; }, - // 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(); + addListener : function(eventName, handler, scope, opt){ + var els = this.elements, + len = els.length, + i, e; - 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(); + for(i = 0; i - * Usage: -

-// 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.'); }
-    }
-]);
-
- * Note: A KeyMap starts enabled - * @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: - *
-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)
-
- * - * Usage: - *

-// 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
-});
-
- * @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 of the function - */ - 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); + 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); } - 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); + this.elements.splice(index, 1, replacement); } - }; -}(); - -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(); + return this; + }, - if(fixedWidth){ - ml.setWidth(fixedWidth); + + clear : function(){ + this.elements = []; } +}; - var instance = { - /** - * 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; - }, +Ext.CompositeElementLite.prototype.on = Ext.CompositeElementLite.prototype.addListener; - /** - * 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') - ); - }, - /** - * 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); - }, +Ext.CompositeElementLite.importElementMethods = function() { + var fnName, + ElProto = Ext.Element.prototype, + CelProto = Ext.CompositeElementLite.prototype; - /** - * 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; - }, + for (fnName in ElProto) { + if (typeof ElProto[fnName] == 'function'){ + (function(fnName) { + CelProto[fnName] = CelProto[fnName] || function() { + return this.invoke(fnName, arguments); + }; + }).call(CelProto, fnName); - /** - * 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); +Ext.CompositeElementLite.importElementMethods(); - return instance; -}; +if(Ext.DomQuery){ + Ext.Element.selectorFunction = Ext.DomQuery.select; +} -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); + +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"; } -}); -/** - * @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 ('/'). - * @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 false. 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, get() returns null. The following - * example retrieves the cookie called "valid" and stores the String value - * in the variable validStatus. - *

-     * var validStatus = Ext.util.Cookies.get("valid");
-     * 
- * @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; + return new Ext.CompositeElementLite(els); }; -/** - * @class Ext.Error - * @extends Error - *

A base error class. Future implementations are intended to provide more - * robust error handling throughout the framework (in the debug build only) - * 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.

- *

Some sample messages currently implemented:

-"DataProxy attempted to execute an API-action but found an undefined
-url / function. Please review your Proxy url/api-configuration."
- * 
-"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."
- * 
- *

An example of the code used for generating error messages:


-try {
-    generateError({
-        foo: 'bar'
-    });
-}
-catch (e) {
-    console.error(e);
-}
-function generateError(data) {
-    throw new Ext.Error('foo-error', data);
-}
- * 
- * @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: {}, +Ext.select = Ext.Element.select; +(function(){ + var BEFOREREQUEST = "beforerequest", + REQUESTCOMPLETE = "requestcomplete", + REQUESTEXCEPTION = "requestexception", + UNDEFINED = undefined, + LOAD = 'load', + POST = 'POST', + GET = 'GET', + WINDOW = window; - 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); - } -}); + + Ext.data.Connection = function(config){ + Ext.apply(this, config); + this.addEvents( + + BEFOREREQUEST, + + REQUESTCOMPLETE, + + REQUESTEXCEPTION + ); + Ext.data.Connection.superclass.constructor.call(this); + }; -/** - * @class Ext.ComponentMgr - *

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}).

- *

This object also provides a registry of available Component classes - * indexed by a mnemonic code known as the Component's {@link Ext.Component#xtype xtype}. - * The {@link Ext.Component#xtype xtype} provides a way to avoid instantiating child Components - * when creating a full, nested config object for a complete Ext page.

- *

A child Component may be specified simply as a config object - * as long as the correct {@link Ext.Component#xtype xtype} is specified so that if and when the Component - * needs rendering, the correct type can be looked up for lazy instantiation.

- *

For a list of all available {@link Ext.Component#xtype xtypes}, see {@link Ext.Component}.

- * @singleton - */ -Ext.ComponentMgr = function(){ - var all = new Ext.util.MixedCollection(); - var types = {}; - var ptypes = {}; + Ext.extend(Ext.data.Connection, Ext.util.Observable, { + + + + + + timeout : 30000, + + autoAbort:false, - return { - /** - * Registers a component. - * @param {Ext.Component} c The component - */ - register : function(c){ - all.add(c); - }, + + disableCaching: true, - /** - * Unregisters a component. - * @param {Ext.Component} c The component - */ - unregister : function(c){ - all.remove(c); - }, + + disableCachingParam: '_dc', - /** - * 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, undefined if not found, or null if a - * Class was found. - */ - get : function(id){ - return all.get(id); - }, + + request : function(o){ + var me = this; + if(me.fireEvent(BEFOREREQUEST, me, o)){ + if (o.el) { + if(!Ext.isEmpty(o.indicatorText)){ + me.indicatorText = '
'+o.indicatorText+"
"; + } + 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; + }); + } - /** - * Registers a function that will be called when a specified component is added to ComponentMgr - * @param {String} id The component {@link Ext.Component#id id} - * @param {Function} fn The callback function - * @param {Object} scope The scope of the callback - */ - 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); + var p = o.params, + url = o.url || me.url, + method, + cb = {success: me.handleResponse, + failure: me.handleFailure, + scope: me, + argument: {options: o}, + timeout : Ext.num(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; + } }, - /** - * 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, - /** - * 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; + isLoading : function(transId){ + return transId ? Ext.lib.Ajax.isCallInProgress(transId) : !! this.transId; }, - /** - *

Registers a new Component constructor, keyed by a new - * {@link Ext.Component#xtype}.

- *

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}

- * @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; + + abort : function(transId){ + if(transId || this.isLoading()){ + Ext.lib.Ajax.abort(transId || this.transId); + } }, - /** - * 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 xtype. (Optional if the config contains a xtype). - * @return {Ext.Component} The newly instantiated Component. - */ - create : function(config, defaultType){ - return config.render ? config : new types[config.xtype || defaultType](config); + + 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); + } }, - /** - *

Registers a new Plugin constructor, keyed by a new - * {@link Ext.Component#ptype}.

- *

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.

- * @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; + + 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); + } }, - /** - * 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 ptype. (Optional if the config contains a ptype). - * @return {Ext.Component} The newly instantiated Plugin. - */ - createPlugin : function(config, defaultType){ - return new ptypes[config.ptype || defaultType](config); - } - }; -}(); + + 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 + }; -/** - * 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 xtype. (Optional if the config contains a xtype). - * @return {Ext.Component} The newly instantiated Component. - * @member Ext - * @method create - */ -Ext.create = Ext.ComponentMgr.create;/** - * @class Ext.Component - * @extends Ext.util.Observable - *

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.

- *

The Component base class has built-in support for basic hide/show and enable/disable behavior.

- *

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}.

- *

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).

- *

See the Creating new UI controls tutorial for details on how - * and to either extend or augment ExtJs base classes to create custom Components.

- *

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:

- *
-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.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}
-
- * @constructor - * @param {Ext.Element/String/Object} config The configuration options may be specified as either: - *
    - *
  • an element : - *

    it is set as the internal element and its id used as the component id

  • - *
  • a string : - *

    it is assumed to be the id of an existing element and is used as the component id

  • - *
  • anything else : - *

    it is assumed to be a standard config object and is applied to the component

  • - *
- */ -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}; - } + + Ext.fly(frame).set({ + id: id, + name: id, + cls: 'x-hidden', + src: Ext.SSL_SECURE_URL + }); - /** - * This Component's initial configuration specification. Read-only. - * @type Object - * @property initialConfig - */ - this.initialConfig = config; + doc.body.appendChild(frame); - Ext.apply(this, config); - this.addEvents( - /** - * @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 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 - *

Fires after the component rendering is finished.

- *

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.

- * @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 applyState. 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 applyState. 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 - * getState() 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 - * getState() 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(Ext.isIE){ + document.frames[id].name = id; + } - if(this.baseAction){ - this.baseAction.addComponent(this); - } - this.initComponent(); + Ext.fly(form).set({ + target: id, + method: POST, + enctype: encoding, + encoding: encoding, + action: url || buf.action + }); - 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]); + + 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, + + 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)){ + r.responseText = firstChild.value; + }else{ + r.responseText = doc.body.innerHTML; + } + } + + 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); + } } - }else{ - this.plugins = this.initPlugin(this.plugins); - } - } - if(this.stateful !== false){ - this.initState(config); - } + Ext.EventManager.on(frame, LOAD, cb, this); + form.submit(); - if(this.applyTo){ - this.applyToMarkup(this.applyTo); - delete this.applyTo; - }else if(this.renderTo){ - this.render(this.renderTo); - delete this.renderTo; - } -}; + Ext.fly(form).set(buf); + Ext.each(hiddens, function(h) { + Ext.removeNode(h); + }); + } + }); +})(); -// 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

The label text to display next to this Component (defaults to '').

- *

Note: this config is only used when this Component is rendered by a Container which - * has been configured to use the {@link Ext.layout.FormLayout FormLayout} layout manager (e.g. - * {@link Ext.form.FormPanel} or specifying layout:'form').


- *

Also see {@link #hideLabel} and - * {@link Ext.layout.FormLayout}.{@link Ext.layout.FormLayout#fieldTpl fieldTpl}.

- * Example use:

-new Ext.FormPanel({
-    height: 100,
-    renderTo: Ext.getBody(),
-    items: [{
-        xtype: 'textfield',
-        fieldLabel: 'Name'
-    }]
-});
-
- */ - /** - * @cfg {String} labelStyle

A CSS style specification string to apply directly to this field's - * label. Defaults to the container's labelStyle value if set (e.g., - * {@link Ext.layout.FormLayout#labelStyle} , or '').

- *

Note: see the note for {@link #clearCls}.


- *

Also see {@link #hideLabel} and - * {@link Ext.layout.FormLayout}.{@link Ext.layout.FormLayout#fieldTpl fieldTpl}.

- * Example use:

-new Ext.FormPanel({
-    height: 100,
-    renderTo: Ext.getBody(),
-    items: [{
-        xtype: 'textfield',
-        fieldLabel: 'Name',
-        labelStyle: 'font-weight:bold;'
-    }]
-});
-
- */ - /** - * @cfg {String} labelSeparator

The separator to display after the text of each - * {@link #fieldLabel}. This property may be configured at various levels. - * The order of precedence is: - *

    - *
  • field / component level
  • - *
  • container level
  • - *
  • {@link Ext.layout.FormLayout#labelSeparator layout level} (defaults to colon ':')
  • - *
- * To display no separator for this field's label specify empty string ''.

- *

Note: see the note for {@link #clearCls}.


- *

Also see {@link #hideLabel} and - * {@link Ext.layout.FormLayout}.{@link Ext.layout.FormLayout#fieldTpl fieldTpl}.

- * Example use:

-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 '='
-    }]
-});
-
- */ - /** - * @cfg {Boolean} hideLabel

true to completely hide the label element - * ({@link #fieldLabel label} and {@link #labelSeparator separator}). Defaults to false. - * By default, even if you do not specify a {@link #fieldLabel} the space will still be - * reserved so that the field will line up with other fields that do have labels. - * Setting this to true will cause the field to not reserve that space.

- *

Note: see the note for {@link #clearCls}.


- * Example use:

-new Ext.FormPanel({
-    height: 100,
-    renderTo: Ext.getBody(),
-    items: [{
-        xtype: 'textfield'
-        hideLabel: true
-    }]
-});
-
- */ - /** - * @cfg {String} clearCls

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 - * 'x-form-clear-left').

- *

Note: this config is only used when this Component is rendered by a Container - * which has been configured to use the {@link Ext.layout.FormLayout FormLayout} layout - * manager (e.g. {@link Ext.form.FormPanel} or specifying layout:'form') and either a - * {@link #fieldLabel} is specified or isFormField=true is specified.


- *

See {@link Ext.layout.FormLayout}.{@link Ext.layout.FormLayout#fieldTpl fieldTpl} also.

- */ - /** - * @cfg {String} itemCls - *

Note: this config is only used when this Component is rendered by a Container which - * has been configured to use the {@link Ext.layout.FormLayout FormLayout} layout manager (e.g. - * {@link Ext.form.FormPanel} or specifying layout:'form').


- *

An additional CSS class to apply to the div wrapping the form item - * element of this field. If supplied, itemCls at the field level will override - * the default itemCls supplied at the container level. The value specified for - * itemCls will be added to the default class ('x-form-item').

- *

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.

- *

Note: see the note for {@link #fieldLabel}.


- * Example use:

-// Apply a style to the field's label:
-<style>
-    .required .x-form-item-label {font-weight:bold;color:red;}
-</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'
-    }]
+Ext.Ajax = new Ext.data.Connection({
+    
+    
+    
+    
+    
+    
+
+    
+
+    
+    
+    
+    
+    
+    
+
+    
+    autoAbort : false,
+
+    
+    serializeForm : function(form){
+        return Ext.lib.Ajax.serializeForm(form);
+    }
 });
-
- */ - // Configs below are used for all Components when rendered by AnchorLayout. - /** - * @cfg {String} anchor

Note: this config is only used when this Component is rendered - * by a Container which has been configured to use an {@link Ext.layout.AnchorLayout AnchorLayout} - * based layout manager, for example:

    - *
  • {@link Ext.form.FormPanel}
  • - *
  • specifying layout: 'anchor' // or 'form', or 'absolute'
  • - *

- *

See {@link Ext.layout.AnchorLayout}.{@link Ext.layout.AnchorLayout#anchor anchor} also.

- */ +Ext.util.JSON = new (function(){ + var useHasOwn = !!{}.hasOwnProperty, + isNative = function() { + var useNative = null; - /** - * @cfg {String} id - *

The unique 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}).

- *

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.

- *

Note: to avoid complications imposed by a unique id also see - * {@link #itemId} and {@link #ref}.

- *

Note: to access the container of an item see {@link #ownerCt}.

- */ - /** - * @cfg {String} itemId - *

An itemId can be used as an alternative way to get a reference to a component - * when no object reference is available. Instead of using an {@link #id} with - * {@link Ext}.{@link Ext#getCmp getCmp}, use itemId with - * {@link Ext.Container}.{@link Ext.Container#getComponent getComponent} which will retrieve - * itemId's or {@link #id}'s. Since itemId's are an index to the - * container's internal MixedCollection, the itemId is scoped locally to the container -- - * avoiding potential conflicts with {@link Ext.ComponentMgr} which requires a unique - * {@link #id}.

- *

-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
+            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;
         },
-        {
-            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
-     * 
- *

Also see {@link #id} and {@link #ref}.

- *

Note: to access the container of an item see {@link #ownerCt}.

- */ - /** - * @cfg {String} xtype - * The registered xtype 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 Component config - * object. The xtype will be looked up at render time up to determine what - * type of child Component to create.

- * The predefined xtypes are listed {@link Ext.Component here}. - *

- * 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 ptype 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 Component config - * object. The ptype will be looked up at render time up to determine what - * type of Plugin to create.

- * 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}. - *

-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'
+        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"){
+                
+                return isFinite(o) ? String(o) : "null";
+            }else if(Ext.isBoolean(o)){
+                return String(o);
+            }else {
+                var a = ["{"], b, i, v;
+                for (i in o) {
+                    
+                    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);
+                }) + '"';
             }
-        })
-    ]
-});
-     * 
- */ - /** - * @cfg {String} ctCls - *

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.

- *

Note: ctCls defaults to '' except for the following class - * which assigns a value by default: - *

    - *
  • {@link Ext.layout.Box Box Layout} : 'x-box-layout-ct'
  • - *
- * To configure the above Class with an extra CSS class append to the default. For example, - * for BoxLayout (Hbox and Vbox):

-     * ctCls: 'x-box-layout-ct custom-class'
-     * 
- *

- */ - /** - * @cfg {Boolean} disabled - * Render this component disabled (default is false). - */ - disabled : false, - /** - * @cfg {Boolean} hidden - * Render this component hidden (default is false). If true, 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 - *

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.

    - *
  • Description :
      - *
      When applyTo 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.
      - *
  • - *
  • Notes :
      - *
      When 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 component's container.
      - *
  • - *
- */ - /** - * @cfg {Mixed} renderTo - *

Specify the id of the element, a DOM element or an existing Element that this component - * will be rendered into.

    - *
  • Notes :
      - *
      Do not 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.
      - *
      When using this config, a call to render() is not required.
      - *
  • - *
- *

See {@link #render} also.

- */ - /** - * @cfg {Boolean} stateful - *

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 {@link #stateId} or {@link #id} 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.

- *

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.

- *

To set the state provider for the current page:

- *

-Ext.state.Manager.setProvider(new Ext.state.CookieProvider({
-    expires: new Date(new Date().getTime()+(1000*60*60*24*7)), //7 days from now
-}));
-     * 
- *

A stateful Component attempts to save state when one of the events - * listed in the {@link #stateEvents} configuration fires.

- *

To save state, a stateful Component first serializes its state by - * calling getState. By default, this function does - * nothing. The developer must provide an implementation which returns an - * object hash which represents the Component's restorable state.

- *

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 {@link stateId}, or, if that is not - * specified, its {@link #id}.

- *

During construction, a stateful Component attempts to restore - * its state by calling {@link Ext.state.Manager#get} passing the - * {@link #stateId}, or, if that is not specified, the - * {@link #id}.

- *

The resulting object is passed to applyState. - * The default implementation of applyState simply copies - * properties into the object, but a developer may override this to support - * more behaviour.

- *

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.

- */ - /** - * @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). - *

See {@link #stateful} for an explanation of saving and - * restoring Component state.

- */ - /** - * @cfg {Array} stateEvents - *

An array of events that, when fired, should trigger this component to - * save its state (defaults to none). stateEvents may be any type - * of event supported by this component, including browser or custom events - * (e.g., ['click', 'customerchange']).

- *

See {@link #stateful} for an explanation of saving and - * restoring Component state.

- */ - /** - * @cfg {Mixed} autoEl - *

A tag name or {@link Ext.DomHelper DomHelper} spec used to create the {@link #getEl Element} which will - * encapsulate this Component.

- *

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 'div'. The more complex Ext classes use a more complex - * DOM structure created by their own onRender methods.

- *

This is intended to allow the developer to create application-specific utility Components encapsulated by - * different DOM elements. Example usage:


-{
-    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'
-    }
-}
-
- */ - 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 - *

How this component should be hidden. Supported values are 'visibility' - * (css visibility), 'offsets' (negative offset position) and 'display' - * (css display).

- *

Note: the default of 'display' is generally preferred - * since items are automatically laid out when they are first shown (no sizing - * is done while hidden).

- */ - 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, - /** - *

The {@link Ext.Element} which encapsulates this Component. Read-only.

- *

This will usually be a <DIV> element created by the class's onRender method, but - * that may be overridden using the {@link #autoEl} config.

- *

Note: this element will not be available until this Component has been rendered.


- *

To add listeners for DOM events 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:


-new Ext.Panel({
-    title: 'The Clickable Panel',
-    listeners: {
-        render: function(p) {
-            // Append the Panel to the click handler's argument list.
-            p.getEl().on('click', handlePanelClick.createDelegate(null, [p], true));
+            return '"' + s + '"';
         },
-        single: true  // Remove the listener after first invocation
-    }
-});
-
- *

See also {@link #getEl getEl}

- * @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. - *

Note: to access items within the Container see {@link #itemId}.

- * @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, + 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(""); + }; - // private - ctype : 'Ext.Component', + + this.encodeDate = function(o){ + return '"' + o.getFullYear() + "-" + + pad(o.getMonth() + 1) + "-" + + pad(o.getDate()) + "T" + + pad(o.getHours()) + ":" + + pad(o.getMinutes()) + ":" + + pad(o.getSeconds()) + '"'; + }; - // private - actionMode : 'el', + + this.encode = function() { + var ec; + return function(o) { + if (!ec) { + + ec = isNative() ? JSON.stringify : doEncode; + } + return ec(o); + }; + }(); - // 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). - *

-// Traditional constructor:
-Ext.Foo = function(config){
-    // call superclass constructor:
-    Ext.Foo.superclass.constructor.call(this, config);
+    
+    this.decode = function() {
+        var dc;
+        return function(json) {
+            if (!dc) {
+                
+                dc = isNative() ? JSON.parse : doDecode;
+            }
+            return dc(json);
+        };
+    }();
 
-    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);
+Ext.encode = Ext.util.JSON.encode;
 
-        this.addEvents({
-            // add events
-        });
-    }
-}
-
- */ - initComponent : Ext.emptyFn, +Ext.decode = Ext.util.JSON.decode; - /** - *

Render this Component into the passed HTML element.

- *

If you are using a {@link Ext.Container Container} object to house this Component, then - * do not use the render method.

- *

A Container's child Components are rendered by that Container's - * {@link Ext.Container#layout layout} manager when the Container is first rendered.

- *

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}.

- *

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.

- *

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.

- *

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.

- * @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 before - * 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); +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)$/, + + specialElCache = []; + + function getId(el){ + var id = false, + i = 0, + len = specialElCache.length, + skip = false, + o; + + if (el) { + if (el.getElementById || el.navigator) { + + for(; i < len; ++i){ + o = specialElCache[i]; + if(o.el === el){ + id = o.id; + break; + } } - } - 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); - 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.initRef(); - this.fireEvent('afterrender', this); - } - return this; - }, - - initRef : function(){ - /** - * @cfg {String} ref - *

A path specification, relative to the Component's {@link #ownerCt} specifying into which - * ancestor Container to place a named reference to this Component.

- *

The ancestor axis can be traversed by using '/' characters in the path. - * For example, to put a reference to a Toolbar Button into the Panel which owns the Toolbar:


-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();
-        }
-    }
-});
-
- *

In the code above, if the ref had been 'saveButton' the reference would - * have been placed into the Toolbar. Each '/' in the ref moves up one level from the - * Component's {@link #ownerCt}.

- */ - if(this.ref){ - var levels = this.ref.split('/'); - var last = levels.length, i = 0; - var t = this; - while(i < last){ - if(t.ownerCt){ - t = t.ownerCt; + if(!id){ + + id = Ext.id(el); + specialElCache.push({ + id: id, + el: el + }); + skip = true; } - i++; + }else{ + id = Ext.id(el); } - t[levels[--i]] = this; - } - }, - - // private - initState : function(config){ - 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(state); - this.fireEvent('staterestore', this, state); - } + if(!Ext.elCache[id]){ + Ext.Element.addToCache(new Ext.Element(el), id); + if(skip){ + Ext.elCache[id].skipGC = true; } } } - }, + return id; + } - // private - getStateId : function(){ - return this.stateId || ((this.id.indexOf('ext-comp-') == 0 || this.id.indexOf('ext-gen') == 0) ? null : this.id); - }, + + function addListener(el, ename, fn, task, wrap, scope){ + el = Ext.getDom(el); + var id = getId(el), + es = Ext.elCache[id].events, + wfn; - // private - initStateEvents : function(){ - if(this.stateEvents){ - for(var i = 0, e; e = this.stateEvents[i]; i++){ - this.on(e, this.saveState, this, {delay:100}); - } + wfn = E.on(el, ename, wrap); + es[ename] = es[ename] || []; + + + es[ename].push([fn, wrap, scope, wfn, task]); + + + + + + 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); + }); } - }, - // private - applyState : function(state){ - if(state){ - Ext.apply(this, state); + + if(el == DOC && ename == "mousedown"){ + Ext.EventManager.stoppedMouseDownEvent.addListener(wrap); } - }, + } - // private - getState : function(){ - return null; - }, + function doScrollChk(){ + + if(window != top){ + return false; + } - // 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); - } - } + try{ + DOC.documentElement.doScroll('left'); + }catch(e){ + return false; } - }, - /** - * 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); - }, + fireDocReady(); + return true; + } + + function checkReadyState(e){ - /** - * 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; + if(Ext.isIE && doScrollChk()){ + return true; } - return this; - }, + if(DOC.readyState == COMPLETE){ + fireDocReady(); + return true; + } + docReadyState || (docReadyProcId = setTimeout(arguments.callee, 2)); + return false; + } - /** - * 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(' '); + var styles; + function checkStyleSheets(e){ + styles || (styles = Ext.query('style, link[rel=stylesheet]')); + if(styles.length == DOC.styleSheets.length){ + fireDocReady(); + return true; } - return this; - }, + docReadyState || (docReadyProcId = setTimeout(arguments.callee, 2)); + return false; + } - // 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; + function OperaDOMContentLoaded(e){ + DOC.removeEventListener(DOMCONTENTLOADED, arguments.callee, false); + checkStyleSheets(); + } + + function fireDocReady(e){ + if(!docReadyState){ + docReadyState = true; + + if(docReadyProcId){ + clearTimeout(docReadyProcId); } - if (!this.el.id) { - this.el.id = this.getId(); + if(DETECT_NATIVE) { + DOC.removeEventListener(DOMCONTENTLOADED, fireDocReady, false); } - } - if(this.el){ - this.el = Ext.get(this.el); - if(this.allowDomMove !== false){ - ct.dom.insertBefore(this.el.dom, position); + if(Ext.isIE && checkReadyState.bindIE){ + DOC.detachEvent('onreadystatechange', checkReadyState); } + E.un(WINDOW, "load", arguments.callee); + } + if(docReadyEvent && !Ext.isReady){ + Ext.isReady = true; + docReadyEvent.fire(); + docReadyEvent.listeners = []; } - }, - // private - getAutoCreate : function(){ - var cfg = Ext.isObject(this.autoCreate) ? - this.autoCreate : Ext.apply({}, this.defaultAutoCreate); - if(this.id && !cfg.id){ - cfg.id = this.id; + } + + function initDocReady(){ + docReadyEvent || (docReadyEvent = new Ext.util.Event()); + if (DETECT_NATIVE) { + DOC.addEventListener(DOMCONTENTLOADED, fireDocReady, false); } - return cfg; - }, + + if (Ext.isIE){ + + + if(!checkReadyState()){ + checkReadyState.bindIE = true; + DOC.attachEvent('onreadystatechange', checkReadyState); + } - // private - afterRender : Ext.emptyFn, + }else if(Ext.isOpera ){ + - /** - * 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.beforeDestroy(); - if(this.rendered){ - this.el.removeAllListeners(); - this.el.remove(); - if(this.actionMode == 'container' || this.removeMode == 'container'){ - this.container.remove(); - } - } - this.onDestroy(); - Ext.ComponentMgr.unregister(this); - this.fireEvent('destroy', this); - this.purgeListeners(); - this.isDestroyed = true; - } + + (DOC.readyState == COMPLETE && checkStyleSheets()) || + DOC.addEventListener(DOMCONTENTLOADED, OperaDOMContentLoaded, false); + + }else if (Ext.isWebKit){ + + checkReadyState(); } - }, + + E.on(WINDOW, "load", fireDocReady); + } - // private - beforeDestroy : Ext.emptyFn, + function createTargeted(h, o){ + return function(){ + var args = Ext.toArray(arguments); + if(o.target == Ext.EventObject.setEvent(args[0]).target){ + h.apply(this, args); + } + }; + } - // private - onDestroy : Ext.emptyFn, + function createBuffered(h, o, task){ + return function(e){ + + task.delay(o.buffer, h, null, [new Ext.EventObjectImpl(e)]); + }; + } - /** - *

Returns the {@link Ext.Element} which encapsulates this Component.

- *

This will usually be a <DIV> element created by the class's onRender method, but - * that may be overridden using the {@link #autoEl} config.

- *

Note: this element will not be available until this Component has been rendered.


- *

To add listeners for DOM events 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:


-new Ext.Panel({
-    title: 'The Clickable Panel',
-    listeners: {
-        render: function(p) {
-            // Append the Panel to the click handler's argument list.
-            p.getEl().on('click', handlePanelClick.createDelegate(null, [p], true));
-        },
-        single: true  // Remove the listener after first invocation
+    function createSingle(h, el, ename, fn, scope){
+        return function(e){
+            Ext.EventManager.removeListener(el, ename, fn, scope);
+            h(e);
+        };
     }
-});
-
- * @return {Ext.Element} The Element which encapsulates this Component. - */ - getEl : function(){ - return this.el; - }, - /** - * Returns the id of this component or automatically generates and - * returns an id if an id is not defined yet:

-     * 'ext-comp-' + (++Ext.Component.AUTO_ID)
-     * 
- * @return {String} id - */ - getId : function(){ - return this.id || (this.id = 'ext-comp-' + (++Ext.Component.AUTO_ID)); - }, + 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)]); + }; + } - /** - * Returns the {@link #itemId} of this component. If an - * {@link #itemId} was not assigned through configuration the - * id is returned using {@link #getId}. - * @return {String} - */ - getItemId : function(){ - return this.itemId || this.getId(); - }, + function listen(element, ename, opt, fn, scope){ + var o = (!opt || typeof opt == "boolean") ? {} : opt, + el = Ext.getDom(element), task; - /** - * 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.focus.defer(Ext.isNumber(delay) ? delay : 10, this, [selectText, false]); - return; + fn = fn || o.fn; + scope = scope || o.scope; + + if(!el){ + throw "Error listening for \"" + ename + '\". Element "' + element + '" doesn\'t exist.'; } - if(this.rendered){ - this.el.focus(); - if(selectText === true){ - this.el.dom.select(); + function h(e){ + + if(!Ext){ + 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 === false) { + e = e.browserEvent; } - } - return this; - }, - // private - blur : function(){ - if(this.rendered){ - this.el.blur(); + fn.call(scope || el, e, t, o); } - return this; - }, - - /** - * Disable this component and fire the 'disable' event. - * @return {Ext.Component} this - */ - disable : function(/* private */ silent){ - if(this.rendered){ - this.onDisable(); + if(o.target){ + h = createTargeted(h, o); } - this.disabled = true; - if(silent !== true){ - this.fireEvent('disable', this); + if(o.delay){ + h = createDelayed(h, o, fn); } - 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(); + if(o.single){ + h = createSingle(h, el, ename, fn, scope); + } + if(o.buffer){ + task = new Ext.util.DelayedTask(h); + h = createBuffered(h, o, task); } - 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'](); - }, + addListener(el, ename, fn, task, h, scope); + return h; + } - /** - * Show this component. Listen to the '{@link #beforeshow}' event and return - * false 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(); + var pub = { + + 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)){ + + listen(element, e, o, val, o.scope); + }else{ + + listen(element, e, val); + } + } + } + } else { + listen(element, eventName, options, fn, scope); } - this.fireEvent('show', this); - } - return this; - }, + }, - // private - onShow : function(){ - this.getVisibilityEl().removeClass('x-hide-' + this.hideMode); - }, + + 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; - /** - * Hide this component. Listen to the '{@link #beforehide}' event and return - * false 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 {@link #hidden}. - * @return {Ext.Component} this - */ - hide : function(){ - if(this.fireEvent('beforehide', this) !== false){ - this.doHide(); - this.fireEvent('hide', this); - } - return this; - }, + for (i = 0, len = f.length; i < len; i++) { - // private - doHide: function(){ - this.hidden = true; - if(this.rendered){ - this.onHide(); - } - }, + + 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); - // private - onHide : function(){ - this.getVisibilityEl().addClass('x-hide-' + this.hideMode); - }, + + if(wrap && el.addEventListener && eventName == "mousewheel"){ + el.removeEventListener("DOMMouseScroll", wrap, false); + } - // private - getVisibilityEl : function(){ - return this.hideParent ? this.container : this.getActionEl(); - }, + + if(wrap && el == DOC && eventName == "mousedown"){ + Ext.EventManager.stoppedMouseDownEvent.removeListener(wrap); + } - /** - * 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'](); - }, + 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; + } + } + }, - /** - * 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(); - }, + + 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; - /** - * 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); - }, + for(ename in es){ + if(es.hasOwnProperty(ename)){ + f = es[ename]; + + 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); - /** - * 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: - *

-var t = new Ext.form.TextField();
-alert(t.getXType());  // alerts 'textfield'
-
- * @return {String} The xtype - */ - getXType : function(){ - return this.constructor.xtype; - }, + + if(el.addEventListener && wrap && ename == "mousewheel"){ + el.removeEventListener("DOMMouseScroll", wrap, false); + } - /** - *

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).

- *

If using your own subclasses, be aware that a Component must register its own xtype - * to participate in determination of inherited xtypes.

- *

For a list of all available xtypes, see the {@link Ext.Component} header.

- *

Example usage:

- *

-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
-
- * @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 - } + + if(wrap && el == DOC && ename == "mousedown"){ + Ext.EventManager.stoppedMouseDownEvent.removeListener(wrap); + } + } + } + } + if (Ext.elCache[id]) { + Ext.elCache[id].events = {}; + } + }, - return !shallow ? ('/' + this.getXTypes() + '/').indexOf('/' + xtype + '/') != -1 : this.constructor.xtype == xtype; - }, + 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; + } + }, - /** - *

Returns this Component's xtype hierarchy as a slash-delimited string. For a list of all - * available xtypes, see the {@link Ext.Component} header.

- *

If using your own subclasses, be aware that a Component must register its own xtype - * to participate in determination of inherited xtypes.

- *

Example usage:

- *

-var t = new Ext.form.TextField();
-alert(t.getXTypes());  // alerts 'component/box/field/textfield'
-
- * @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; + 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); } - tc.xtypeChain = c; - tc.xtypes = c.join('/'); - } - return tc.xtypes; - }, + if (recurse && el && el.childNodes) { + for (i = 0, len = el.childNodes.length; i < len; i++) { + Ext.EventManager.purgeElement(el.childNodes[i], recurse, eventName); + } + } + }, - /** - * 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; - }, + _unload : function() { + var el; + for (el in Ext.elCache) { + Ext.EventManager.removeAll(el); + } + delete Ext.elCache; + delete Ext.Element._flyweights; - /** - * 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; - }); - }, + + 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}); + } + } + }, + + onDocumentReady : function(fn, scope, options){ + if (Ext.isReady) { + 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); + } + }, - getDomPositionEl : function(){ - return this.getPositionEl ? this.getPositionEl() : this.getEl(); - }, + + fireDocReady : fireDocReady + }; + + pub.on = pub.addListener; + + pub.un = pub.removeListener; - // private - purgeListeners : function(){ - Ext.Component.superclass.purgeListeners.call(this); - if(this.mons){ - this.on('beforedestroy', this.clearMons, this, {single: true}); - } - }, + pub.stoppedMouseDownEvent = new Ext.util.Event(); + return pub; +}(); - // 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}); - } - }, +Ext.onReady = Ext.EventManager.onDocumentReady; - // internal function for auto removal of assigned event handlers on destruction - 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); - }, +(function(){ + var initExtCss = function() { + + 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" : ""]; - // protected, opposite of mon - 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; - } + 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"); } - 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); - } + if (Ext.isMac) { + cls.push("ext-mac"); + } + if (Ext.isLinux) { + cls.push("ext-linux"); } - 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); + + if (Ext.isStrict || Ext.isBorderBox) { + var p = bd.parentNode; + if (p) { + Ext.fly(p, '_internal').addClass(((Ext.isStrict && Ext.isIE ) || (!Ext.enableForcedBoxModel && !Ext.isIE)) ? ' ext-strict' : ' ext-border-box'); } } - 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; + + + if (Ext.enableForcedBoxModel && !Ext.isIE) { + Ext.isForcedBorderBox = true; + cls.push("ext-forced-border-box"); + } + + Ext.fly(bd, '_internal').addClass(cls); + return true; + }; + + if (!initExtCss()) { + Ext.onReady(initExtCss); } -}); +})(); + -Ext.reg('component', Ext.Component); -/** - * @class Ext.Action - *

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).

- *

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).

- * Example usage:
- *

-// 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');
-
- * @constructor - * @param {Object} config The configuration options - */ -Ext.Action = function(config){ - this.initialConfig = config; - this.itemId = config.itemId = (config.itemId || config.id || Ext.id()); - this.items = []; -} - -Ext.Action.prototype = { - /** - * @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 ''). - *

An example of specifying a custom icon class would be something like: - *


-// 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; }
-
- */ - /** - * @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 in which the {@link #handler} function will execute. - */ - - // 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 {@link #hide} and {@link #show}. - * @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 in which the function will execute - */ - 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 in which the function will execute - */ - 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 {@link #setHandler}. 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 true - * to use css style 'display:none;' 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); + var supports = Ext.apply(Ext.supports, { + + correctRightMargin: true, + + + correctTransparentColor: true, + + + cssFloat: true + }); + + var supportTests = function(){ + var div = document.createElement('div'), + doc = document, + view, + last; + + div.innerHTML = '
'; + doc.body.appendChild(div); + last = div.lastChild; + + if((view = doc.defaultView)){ + if(view.getComputedStyle(div.firstChild.firstChild, null).marginRight != '0px'){ + supports.correctRightMargin = false; + } + if(view.getComputedStyle(last, null).backgroundColor != 'transparent'){ + supports.correctTransparentColor = false; + } + } + supports.cssFloat = !!last.style.cssFloat; + doc.body.removeChild(div); + }; + + if (Ext.isReady) { + supportTests(); + } else { + Ext.onReady(supportTests); } - 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; - }, +Ext.EventObject = function(){ + var E = Ext.lib.Event, + clickRe = /(dbl)?click/, + + safariKeys = { + 3 : 13, + 63234 : 37, + 63235 : 39, + 63232 : 38, + 63233 : 40, + 63276 : 33, + 63277 : 34, + 63272 : 46, + 63273 : 36, + 63275 : 35 + }, + + btnMap = Ext.isIE ? {1:0,4:1,2:2} : {0:0,1:1,2:2}; - 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); + Ext.EventObjectImpl = function(e){ + if(e){ + this.setEvent(e.browserEvent || e); } - 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; - } - }, + Ext.EventObjectImpl.prototype = { + + setEvent : function(e){ + var me = this; + if(e == me || (e && e.browserEvent)){ + return e; + } + me.browserEvent = e; + if(e){ + + me.button = e.button ? btnMap[e.button] : (e.which ? e.which - 1 : -1); + if(clickRe.test(e.type) && me.button == -1){ + me.button = 0; + } + me.type = e.type; + me.shiftKey = e.shiftKey; + + me.ctrlKey = e.ctrlKey || e.metaKey || false; + me.altKey = e.altKey; + + me.keyCode = e.keyCode; + me.charCode = e.charCode; + + me.target = E.getTarget(e); + + 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; + }, - disableShadow : function(){ - if(this.shadow){ - this.shadowDisabled = true; - this.shadow.hide(); - this.lastShadowOffset = this.shadowOffset; - this.shadowOffset = 0; - } - }, + + stopEvent : function(){ + var me = this; + if(me.browserEvent){ + if(me.browserEvent.type == 'mousedown'){ + Ext.EventManager.stoppedMouseDownEvent.fire(me); + } + E.stopEvent(me.browserEvent); + } + }, - enableShadow : function(show){ - if(this.shadow){ - this.shadowDisabled = false; - this.shadowOffset = this.lastShadowOffset; - delete this.lastShadowOffset; - if(show){ - this.sync(true); + + preventDefault : function(){ + if(this.browserEvent){ + E.preventDefault(this.browserEvent); } - } - }, + }, - // 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 sw = this.shadow; - if(!this.updating && this.isVisible() && (sw || this.useShim)){ - var sh = this.getShim(); + + stopPropagation : function(){ + var me = this; + if(me.browserEvent){ + if(me.browserEvent.type == 'mousedown'){ + Ext.EventManager.stoppedMouseDownEvent.fire(me); + } + E.stopPropagation(me.browserEvent); + } + }, - var w = this.getWidth(), - h = this.getHeight(); + + getCharCode : function(){ + return this.charCode || this.keyCode; + }, - var l = this.getLeft(true), - t = this.getTop(true); + + getKey : function(){ + return this.normalizeKey(this.keyCode || this.charCode); + }, - if(sw && !this.shadowDisabled){ - if(doShow && !sw.isVisible()){ - sw.show(this); - }else{ - sw.realign(l, t, w, h); - } - if(sh){ - if(doShow){ - sh.show(); - } - // fit the shim behind the shadow, so it is shimmed too - var a = sw.adjusts, s = sh.dom.style; - s.left = (Math.min(l, l+a.l))+'px'; - s.top = (Math.min(t, t+a.t))+'px'; - s.width = (w+a.w)+'px'; - s.height = (h+a.h)+'px'; - } - }else if(sh){ - if(doShow){ - sh.show(); - } - sh.setSize(w, h); - sh.setLeftTop(l, t); + + normalizeKey: function(k){ + return Ext.isSafari ? (safariKeys[k] || k) : k; + }, + + + getPageX : function(){ + return this.xy[0]; + }, + + + getPageY : function(){ + return this.xy[1]; + }, + + + getXY : function(){ + return this.xy; + }, + + + getTarget : function(selector, maxDepth, returnEl){ + return selector ? Ext.fly(this.target).findParent(selector, maxDepth, returnEl) : (returnEl ? Ext.get(this.target) : this.target); + }, + + + getRelatedTarget : function(){ + return this.browserEvent ? E.getRelatedTarget(this.browserEvent) : null; + }, + + + getWheelDelta : function(){ + var e = this.browserEvent; + var delta = 0; + if(e.wheelDelta){ + delta = e.wheelDelta/120; + }else if(e.detail){ + delta = -e.detail/3; } + return delta; + }, + + 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; } - }, + }; - // private - destroy : function(){ - this.hideShim(); - if(this.shadow){ - this.shadow.hide(); + return new Ext.EventObjectImpl(); +}(); + +Ext.Loader = Ext.apply({}, { + + load: function(fileList, callback, scope, preserveOrder) { + var scope = scope || this, + head = document.getElementsByTagName("head")[0], + fragment = document.createDocumentFragment(), + numFiles = fileList.length, + loadedFiles = 0, + me = this; + + + var loadFileIndex = function(index) { + head.appendChild( + me.buildScriptTag(fileList[index], onFileLoaded) + ); + }; + + + var onFileLoaded = function() { + loadedFiles ++; + + + if (numFiles == loadedFiles && typeof callback == 'function') { + callback.call(scope); + } else { + if (preserveOrder === true) { + loadFileIndex(loadedFiles); + } + } + }; + + if (preserveOrder === true) { + loadFileIndex.call(this, 0); + } else { + + Ext.each(fileList, function(file, index) { + fragment.appendChild( + this.buildScriptTag(file, onFileLoaded) + ); + }, this); + + head.appendChild(fragment); } - this.removeAllListeners(); - Ext.removeNode(this.dom); - Ext.Element.uncache(this.id); }, + + + buildScriptTag: function(filename, callback) { + var script = document.createElement('script'); + script.type = "text/javascript"; + script.src = filename; + + + if (script.readyState) { + script.onreadystatechange = function() { + if (script.readyState == "loaded" || script.readyState == "complete") { + script.onreadystatechange = null; + callback(); + } + }; + } else { + script.onload = callback; + } + + return script; + } +}); - remove : function(){ - this.destroy(); - }, - // private - beginUpdate : function(){ - this.updating = true; - }, +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"); + - // private - endUpdate : function(){ - this.updating = false; - this.sync(true); - }, +Ext.apply(Ext, function(){ + var E = Ext, + idSeed = 0, + scrollWidth = null; - // private - hideUnders : function(negOffset){ - if(this.shadow){ - this.shadow.hide(); - } - this.hideShim(); - }, + return { + + emptyFn : function(){}, - // private - constrainXY : function(){ - if(this.constrain){ - var vw = Ext.lib.Dom.getViewWidth(), - vh = Ext.lib.Dom.getViewHeight(); - var s = Ext.getDoc().getScroll(); + + BLANK_IMAGE_URL : Ext.isIE6 || Ext.isIE7 || Ext.isAir ? + 'http:/' + '/www.extjs.com/s.gif' : + 'data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==', - 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; + extendX : function(supr, fn){ + return Ext.extend(supr, fn(supr.prototype)); + }, + + + getDoc : function(){ + return Ext.get(document); + }, + + + 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; + }, + + + value : function(v, defaultValue, allowBlank){ + return Ext.isEmpty(v, allowBlank) ? defaultValue : v; + }, + + + escapeRe : function(s) { + return s.replace(/([-.*+?^${}()|[\]\/\\])/g, "\\$1"); + }, + + sequence : function(o, name, fn, scope){ + o[name] = o[name].createSequence(fn, scope); + }, + + + addBehaviors : function(o){ + if(!Ext.isReady){ + Ext.onReady(function(){ + Ext.addBehaviors(o); + }); + } else { + var cache = {}, + parts, + b, + s; + for (b in o) { + if ((parts = b.split('@'))[1]) { + s = parts[0]; + if(!cache[s]){ + cache[s] = Ext.select(s); + } + cache[s].on(parts[1], o[b]); + } + } + cache = null; } - if((y + h) > vh+s.top){ - y = vh - h - so; - moved = true; + }, + + + getScrollBarWidth: function(force){ + if(!Ext.isReady){ + return 0; } - // then make sure top/left isn't negative - if(x < s.left){ - x = s.left; - moved = true; + + if(force === true || scrollWidth === null){ + + var div = Ext.getBody().createChild('
'), + child = div.child('div', true); + var w1 = child.offsetWidth; + div.setStyle('overflow', (Ext.isWebKit || Ext.isGecko) ? 'auto' : 'scroll'); + var w2 = child.offsetWidth; + div.remove(); + + scrollWidth = w1 - w2 + 2; } - if(y < s.top){ - y = s.top; - moved = true; + return scrollWidth; + }, + + + + 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); + } } - if(moved){ - if(this.avoidY){ - var ay = this.avoidY; - if(y <= ay && (y+h) >= ay){ - y = ay-h-5; + return r; + }, + + + 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; + }, + + + 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(); } } - xy = [x, y]; - this.storeXY(xy); - supr.setXY.call(this, xy); - this.sync(); - } - } - return this; - }, + }, this); + }, - isVisible : function(){ - return this.visible; - }, + + 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]]; + } + }, - // 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]); - } - }, + + clean : function(arr){ + var ret = []; + Ext.each(arr, function(v){ + if(!!v){ + ret.push(v); + } + }); + return ret; + }, - // private - hideAction : function(){ - this.visible = false; - if(this.useDisplay === true){ - this.setDisplayed(false); - }else{ - this.setLeftTop(-10000,-10000); - } - }, + + unique : function(arr){ + var ret = [], + collect = {}; - // 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(); + Ext.each(arr, function(v) { + if(!collect[v]){ + ret.push(v); } - }.createDelegate(this); - supr.setVisible.call(this, true, true, d, cb, e); - }else{ - if(!v){ - this.hideUnders(true); + collect[v] = true; + }); + return ret; + }, + + + 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; } - var cb = c; - if(a){ - cb = function(){ - this.hideAction(); - if(c){ - c(); + return rFlatten(arr); + }, + + + 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; + }, + + + 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; + }, + + + mean : function(arr){ + return arr.length > 0 ? Ext.sum(arr) / arr.length : undefined; + }, + + + sum : function(arr){ + var ret = 0; + Ext.each(arr, function(v) { + ret += v; + }); + return ret; + }, + + + 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; + }, + + + 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; + }, + + + pluck : function(arr, prop){ + var ret = []; + Ext.each(arr, function(v) { + ret.push( v[prop] ); + }); + return ret; + }, + + + 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] ); } - }.createDelegate(this); + } } - supr.setVisible.call(this, v, a, d, cb, e); - if(v){ - this.sync(true); - }else if(!a){ - this.hideAction(); + return ret; + }, + + + getCmp : function(id){ + return Ext.ComponentMgr.get(id); + }, + + + useShims: E.isIE6 || (E.isMac && E.isGecko2), + + + + 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); + }, + + + callback : function(cb, scope, args, delay){ + if(typeof cb == 'function'){ + if(delay){ + cb.defer(delay, scope, args || []); + }else{ + cb.apply(scope, args || []); + } } } - return this; - }, + }; +}()); - storeXY : function(xy){ - delete this.lastLT; - this.lastXY = xy; - }, - storeLeftTop : function(left, top){ - delete this.lastXY; - this.lastLT = [left, top]; - }, +Ext.apply(Function.prototype, { + + 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; + }; + } +}); - // 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()); + +Ext.applyIf(String, { + + + escape : function(string) { + return string.replace(/('|\\)/g, "\\$1"); }, - // private - beforeAction : function(){ - if(!this.updating && this.shadow){ - this.shadow.hide(); + + leftPad : function (val, size, ch) { + var result = String(val); + if(!ch) { + ch = " "; } - }, + while (result.length < size) { + result = ch + result; + } + return result; + } +}); - // 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; - }, +String.prototype.toggle = function(value, other){ + return this == value ? other : value; +}; - // 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; - }, +String.prototype.trim = function(){ + var re = /^\s+|\s+$/g; + return function(){ return this.replace(re, ""); }; +}(); - // 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; - }, +Date.prototype.getElapsed = function(date) { + return Math.abs((date || new Date()).getTime()-this.getTime()); +}; - // 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; +Ext.applyIf(Number.prototype, { + + constrain : function(min, max){ + return Math.min(Math.max(this, min), max); } }); -})();/** - * @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; +Ext.lib.Dom.getRegion = function(el) { + return Ext.lib.Region.getRegion(el); +}; 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; }; - this.adjusts = a; -}; + 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 ); -Ext.Shadow.prototype = { - /** - * @cfg {String} mode - * The shadow display mode. Supports the following options:
    - *
  • sides : Shadow displays on both sides and bottom only
  • - *
  • frame : Shadow displays equally on all four sides
  • - *
  • drop : Traditional bottom-right drop shadow
  • - *
- */ - /** - * @cfg {String} offset - * The number of pixels to offset the shadow from the element (defaults to 4) - */ - offset: 4, + }, - // private - defaultMode: "drop", + getArea : function() { + var me = this; + return ( (me.bottom - me.top) * (me.right - me.left) ); + }, - /** - * 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); + 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; } - 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; - }, + 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]; - /** - * 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; + 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 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"; + 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(); + +Ext.apply(Ext.DomHelper, +function(){ + var pub, + afterbegin = 'afterbegin', + afterend = 'afterend', + beforebegin = 'beforebegin', + beforeend = 'beforeend', + confRe = /tag|children|cn|html$/i; + + + 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; + } - /** - * Hides this shadow - */ - hide : function(){ - if(this.el){ - this.el.dom.style.display = "none"; - Ext.Shadow.Pool.push(this.el); - delete this.el; - } - }, + + + function createDom(o, parentNode){ + var el, + doc = document, + useSet, + attr, + val, + cn; + + if (Ext.isArray(o)) { + el = doc.createDocumentFragment(); + for (var i = 0, l = o.length; i < l; i++) { + createDom(o[i], el); + } + } else if (typeof o == 'string') { + el = doc.createTextNode(o); + } else { + el = doc.createElement( o.tag || 'div' ); + useSet = !!el.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); - /** - * 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); + if ((cn = o.children || o.cn)) { + createDom(cn, el); + } else if (o.html) { + el.innerHTML = o.html; + } } + if(parentNode){ + parentNode.appendChild(el); + } + return el; } -}; -// Private utility class that manages the internal Shadow cache -Ext.Shadow.Pool = function(){ - var p = []; - var markup = Ext.isIE ? - '
' : - '
'; - 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; + pub = { + + createTemplate : function(o){ + var html = Ext.DomHelper.createHtml(o); + return new Ext.Template(html); }, - push : function(sh){ - p.push(sh); - } + + useDom : false, + + + insertBefore : function(el, o, returnElement){ + return doInsert(el, o, returnElement, beforebegin); + }, + + + insertAfter : function(el, o, returnElement){ + return doInsert(el, o, returnElement, afterend, 'nextSibling'); + }, + + + insertFirst : function(el, o, returnElement){ + return doInsert(el, o, returnElement, afterbegin, 'firstChild'); + }, + + + append: function(el, o, returnElement){ + return doInsert(el, o, returnElement, beforeend, '', true); + }, + + + createDom: createDom }; -}();/** - * @class Ext.BoxComponent - * @extends Ext.Component - *

Base class for any {@link Ext.Component Component} that is to be sized as a box, using width and height.

- *

BoxComponent provides automatic box model adjustments for sizing and positioning and will work correctly - * within the Component rendering model.

- *

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 BoxComponent in order to have its width and height managed.

- *

To use a pre-existing element as a BoxComponent, configure it so that you preset the el property to the - * element to reference:


-var pageHeader = new Ext.BoxComponent({
-    el: 'my-header-div'
-});
- * This may then be {@link Ext.Container#add added} to a {@link Ext.Container Container} as a child item.

- *

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:


-var myImage = new Ext.BoxComponent({
-    autoEl: {
-        tag: 'img',
-        src: '/images/my-image.jpg'
-    }
-});

- * @constructor - * @param {Ext.Element/String/Object} config The configuration options. - * @xtype box - */ -Ext.BoxComponent = Ext.extend(Ext.Component, { + return pub; +}()); - // tabTip config is used when a BoxComponent is a child of a TabPanel - /** - * @cfg {String} tabTip - *

Note: this config is only used when this BoxComponent is a child item of a TabPanel.

- * 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

Note: this config is only used when this BoxComponent is rendered - * by a Container which has been configured to use the {@link Ext.layout.BorderLayout BorderLayout} - * layout manager (e.g. specifying layout:'border').


- *

See {@link Ext.layout.BorderLayout} also.

- */ - // margins config is used when a BoxComponent is rendered by BorderLayout or BoxLayout. - /** - * @cfg {Object} margins

Note: this config is only used when this BoxComponent is rendered - * by a Container which has been configured to use the {@link Ext.layout.BorderLayout BorderLayout} - * or one of the two {@link Ext.layout.BoxLayout BoxLayout} subclasses.

- *

An object containing margins to apply to this BoxComponent in the - * format:


-{
-    top: (top margin),
-    right: (right margin),
-    bottom: (bottom margin),
-    left: (left margin)
-}
- *

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:

- *

    - *
  • If there is only one value, it applies to all sides.
  • - *
  • 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.
  • - *
  • 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.
  • - *
  • If there are four values, they apply to the top, right, bottom, and left, respectively.
  • - *

- *

Defaults to:


-     * {top:0, right:0, bottom:0, left:0}
-     * 
- */ - /** - * @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). - * Note 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). - * Note to express this dimension as a percentage or offset see {@link Ext.Component#anchor}. - */ - /** - * @cfg {Boolean} autoHeight - *

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.

- *

Note: 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.

- *

If the browser 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:


-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();
-
- */ - /** - * @cfg {Boolean} autoWidth - *

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.

- *

Note: 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.

- *

If the browser 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:


-<div id='grid-container' style='margin-left:25%;width:50%'></div>
-
- * 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:

-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'
-    }],
-});
-
- */ - - /* // 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' - ); - }, +Ext.apply(Ext.Template.prototype, { + + disableFormats : false, + - // private, set in afterRender to signify that the component has been rendered - boxReady : false, - // private, used to defer height settings to subclasses - deferHeight: false, + + re : /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g, + argsRe : /^\s*['"](.*)["']\s*$/, + compileARe : /\\/g, + compileBRe : /(\r\n|\n)/g, + compileCRe : /'/g, /** - * 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 {width:10, height:20}. - * @param {Mixed} width The new width to set. This may be one of:
    - *
  • A Number specifying the new width in the {@link #getEl Element}'s {@link Ext.Element#defaultUnit}s (by default, pixels).
  • - *
  • A String used to set the CSS width style.
  • - *
  • A size object in the format {width: widthValue, height: heightValue}.
  • - *
  • undefined to leave the width unchanged.
  • - *
- * @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:
    - *
  • A Number specifying the new height in the {@link #getEl Element}'s {@link Ext.Element#defaultUnit}s (by default, pixels).
  • - *
  • A String used to set the CSS height style. Animation may not be used.
  • - *
  • undefined to leave the height unchanged.
  • - *
- * @return {Ext.BoxComponent} this + * 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 */ - setSize : function(w, h){ - // support for standard size objects - if(typeof w == 'object'){ - h = w.height; - w = w.width; - } - // not rendered - if(!this.boxReady){ - this.width = w; - this.height = h; - return this; - } + applyTemplate : function(values){ + var me = this, + useF = me.disableFormats !== true, + fm = Ext.util.Format, + tpl = me; - // prevent recalcs when not needed - if(this.cacheSizes !== false && this.lastSize && this.lastSize.width == w && this.lastSize.height == h){ - return this; + if(me.compiled){ + return me.compiled(values); } - this.lastSize = {width: w, height: h}; - var adj = this.adjustSize(w, h); - var aw = adj.width, ah = adj.height; - if(aw !== undefined || ah !== undefined){ // this code is nasty but performs better with floaters - var 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); + 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] : ""; } - this.onResize(aw, ah, w, h); - this.fireEvent('resize', this, aw, ah, w, h); } - return this; + return me.html.replace(me.re, fn); }, /** - * Sets the width of the component. This method fires the {@link #resize} event. - * @param {Number} width The new width to setThis may be one of:
    - *
  • A Number specifying the new width in the {@link #getEl Element}'s {@link Ext.Element#defaultUnit}s (by default, pixels).
  • - *
  • A String used to set the CSS width style.
  • - *
- * @return {Ext.BoxComponent} this + * Compiles the template into an internal function, eliminating the RegEx overhead. + * @return {Ext.Template} this + * @hide repeat doc */ - setWidth : function(width){ - return this.setSize(width); - }, + compile : function(){ + var me = this, + fm = Ext.util.Format, + useF = me.disableFormats !== true, + sep = Ext.isGecko ? "+" : ",", + body; - /** - * Sets the height of the component. This method fires the {@link #resize} event. - * @param {Number} height The new height to set. This may be one of:
    - *
  • A Number specifying the new height in the {@link #getEl Element}'s {@link Ext.Element#defaultUnit}s (by default, pixels).
  • - *
  • A String used to set the CSS height style.
  • - *
  • undefined to leave the height unchanged.
  • - *
- * @return {Ext.BoxComponent} this - */ - setHeight : function(height){ - return this.setSize(undefined, height); - }, + 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+"'"; + } - /** - * 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(); + // 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; +/** + * @class Ext.util.Functions + * @singleton + */ +Ext.util.Functions = { /** - * Gets the current width of the component's underlying element. - * @return {Number} - */ - getWidth : function(){ - return this.getResizeEl().getWidth(); - }, + * 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: + *

+var sayHi = function(name){
+    alert('Hi, ' + name);
+}
 
-    /**
-     * Gets the current height of the component's underlying element.
-     * @return {Number}
-     */
-    getHeight : function(){
-        return this.getResizeEl().getHeight();
-    },
+sayHi('Fred'); // alerts "Hi, Fred"
 
-    /**
-     * 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')};
-    },
+// create a new function that validates input without
+// directly modifying the original function:
+var sayHiToFriend = Ext.createInterceptor(sayHi, function(name){
+    return name == 'Brian';
+});
 
-    /**
-     * 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])
+sayHiToFriend('Fred');  // no alert
+sayHiToFriend('Brian'); // alerts "Hi, Brian"
+       
+ * @param {Function} origFn The original function. + * @param {Function} newFn The function to call before the original + * @param {Object} scope (optional) The scope (this reference) in which the passed function is executed. + * If omitted, defaults to the scope in which the original function is called or the browser window. + * @return {Function} The new function */ - getPosition : function(local){ - var el = this.getPositionEl(); - if(local === true){ - return [el.getLeft(true), el.getTop(true)]; + createInterceptor: function(origFn, newFn, scope) { + var method = origFn; + if (!Ext.isFunction(newFn)) { + return origFn; + } + else { + return function() { + var me = this, + args = arguments; + newFn.target = me; + newFn.method = origFn; + return (newFn.apply(scope || me || window, args) !== false) ? + origFn.apply(me || window, args) : + null; + }; } - 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; - }, + * Creates a delegate (callback) that sets the scope to obj. + * Call directly on any function. Example: Ext.createDelegate(this.myFunction, this, [arg1, arg2]) + * Will create a function that is automatically scoped to obj so that the this variable inside the + * callback points to obj. Example usage: + *

+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.');
+}
 
-    /**
-     * 

Returns the outermost Element of this Component which defines the Components overall size.

- *

Usually this will return the same Element as {@link #getEl}, - * but in some cases, a Component may have some more wrapping Elements around its main - * active Element.

- *

An example is a ComboBox. It is encased in a wrapping Element which - * contains both the <input> Element (which is what would be returned - * by its {@link #getEl} method, and the trigger button Element. - * This Element is returned as the resizeEl. - */ - getResizeEl : function(){ - return this.resizeEl || this.el; - }, +var btn = new Ext.Button({ + text: 'Say Hi', + renderTo: Ext.getBody() +}); - // protected - getPositionEl : function(){ - return this.positionEl || this.el; +// 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', Ext.createDelegate(sayHi, btn, ['Fred'])); +

+ * @param {Function} fn The function to delegate. + * @param {Object} scope (optional) The scope (this reference) in which the function is executed. + * If omitted, defaults to the browser window. + * @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(fn, obj, args, appendArgs) { + if (!Ext.isFunction(fn)) { + return fn; + } + 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 fn.apply(obj || window, callArgs); + }; }, /** - * 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; + * Calls this function after the number of millseconds specified, optionally in a specific scope. Example usage: + *

+var sayHi = function(name){
+    alert('Hi, ' + name);
+}
 
-        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;
-    },
+// executes immediately:
+sayHi('Fred');
 
-    /**
-     * 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
+// executes after 2 seconds:
+Ext.defer(sayHi, 2000, this, ['Fred']);
+
+// this syntax is sometimes useful for deferring
+// execution of an anonymous function:
+Ext.defer(function(){
+    alert('Anonymous');
+}, 100);
+       
+ * @param {Function} fn The function to defer. + * @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 (this reference) in which the function is executed. + * If omitted, defaults to the browser window. + * @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 */ - 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; + defer: function(fn, millis, obj, args, appendArgs) { + fn = Ext.util.Functions.createDelegate(fn, obj, args, appendArgs); + if (millis > 0) { + return setTimeout(fn, millis); } - var p = this.getPositionEl().translatePoints(x, y); - this.setPosition(p.left, p.top); - return this; + fn(); + return 0; }, - // 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; - 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; - }, + * 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: + * - /* // 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){ +var sayHi = function(name){ + alert('Hi, ' + name); +} - }, +sayHi('Fred'); // alerts "Hi, Fred" - /* // 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){ +var sayGoodbye = Ext.createSequence(sayHi, function(name){ + alert('Bye, ' + name); +}); - }, +sayGoodbye('Fred'); // both alerts show - // private - adjustSize : function(w, h){ - if(this.autoWidth){ - w = 'auto'; + * @param {Function} origFn The original function. + * @param {Function} newFn The function to sequence + * @param {Object} scope (optional) The scope (this reference) in which the passed function is executed. + * If omitted, defaults to the scope in which the original function is called or the browser window. + * @return {Function} The new function + */ + createSequence: function(origFn, newFn, scope) { + if (!Ext.isFunction(newFn)) { + return origFn; } - if(this.autoHeight){ - h = 'auto'; + else { + return function() { + var retval = origFn.apply(this || window, arguments); + newFn.apply(scope || this || window, arguments); + return retval; + }; } - return {width : w, height: h}; - }, - - // private - adjustPosition : function(x, y){ - return {x : x, y: y}; } -}); -Ext.reg('box', Ext.BoxComponent); +}; + +/** + * Shorthand for {@link Ext.util.Functions#defer} + * @param {Function} fn The function to defer. + * @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 (this reference) in which the function is executed. + * If omitted, defaults to the browser window. + * @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 + * @member Ext + * @method defer + */ +Ext.defer = Ext.util.Functions.defer; /** - * @class Ext.Spacer - * @extends Ext.BoxComponent - *

Used to provide a sizable space in a layout.

- * @constructor - * @param {Object} config + * Shorthand for {@link Ext.util.Functions#createInterceptor} + * @param {Function} origFn The original function. + * @param {Function} newFn The function to call before the original + * @param {Object} scope (optional) The scope (this reference) in which the passed function is executed. + * If omitted, defaults to the scope in which the original function is called or the browser window. + * @return {Function} The new function + * @member Ext + * @method defer */ -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). - *

- * Usage: - *

-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);
-
- * @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 undefined, 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: " "}, 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")); - proxy.unselectable(); - var cls = 'x-splitbar-proxy'; - proxy.addClass(cls + ' ' + (dir == Ext.SplitBar.HORIZONTAL ? cls +'-h' : cls + '-v')); - document.body.appendChild(proxy.dom); - 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 - *

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.

- * - *

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 - * {@link Ext.Component#autoEl autoEl} config option. This is a useful technique when creating - * embedded {@link Ext.layout.ColumnLayout column} layouts inside {@link Ext.form.FormPanel FormPanels} - * for example.

- * - *

The code below illustrates both how to explicitly create a Container, and how to implicitly - * create one using the 'container' xtype:


-// 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 <DIV> element.
-    items: [{
-        items: {
-            xtype: 'datefield',
-            name: 'startDate',
-            fieldLabel: 'Start date'
-        }
-    }, {
-        items: {
-            xtype: 'datefield',
-            name: 'endDate',
-            fieldLabel: 'End date'
-        }
-    }]
-});

- * - *

Layout

- *

Container classes delegate the rendering of child Components to a layout - * manager class which must be configured into the Container using the - * {@link #layout} configuration property.

- *

When either specifying child {@link #items} 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 - * {@link #layout} 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 does not apply any sizing at all.

- *

A common mistake is when a developer neglects to specify a - * {@link #layout} (e.g. widgets like GridPanels or - * TreePanels are added to Containers for which no {@link #layout} - * 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.

- *

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:


-//  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);
- * 

- *

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. - *

Overnesting is a common problem. - * An example of overnesting occurs when a GridPanel is added to a TabPanel - * by wrapping the GridPanel inside a wrapping Panel (that has no - * {@link #layout} specified) and then add that wrapping Panel - * to the TabPanel. The point to realize is that a GridPanel is a - * Component which can be added directly to a Container. If the wrapping Panel - * has no {@link #layout} configuration, then the overnested - * GridPanel will not be sized as expected.

- * - *

Adding via remote configuration

- * - *

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: - *


-// 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");
-    }
-});
-
- *

The server script needs to return an executable Javascript statement which, when processed - * using eval(), will return either a config object with an {@link Ext.Component#xtype xtype}, - * or an instantiated Component. The server might return this for example:


-(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
-})();
-
- *

When the above code fragment is passed through the eval 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.

- *

Note: since the code above is generated by a server script, the baseParams 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.

- * - * @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 {@link #layout} and should not need - * to be set manually. - */ - /** - * @cfg {String/Object} layout - *

*Important: In order for child items to be correctly sized and - * positioned, typically a layout manager must be specified through - * the layout configuration option.

- *

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:


-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();
-     * 
- *

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 layout:'form'). Other specific - * purpose classes internally specify/manage their internal layout (e.g. - * GridPanel, TabPanel, TreePanel, Toolbar, Menu, etc.).

- *

layout may be specified as either as an Object or - * as a String:

    - * - *
  • Specify as an Object
  • - *
      - *
    • Example usage:
    • -
      
      -layout: {
      -    type: 'vbox',
      -    padding: '5',
      -    align: 'left'
      -}
      -
      - * - *
    • type
    • - *

      The layout type to be used for this container. If not specified, - * a default {@link Ext.layout.ContainerLayout} will be created and used.

      - *

      Valid layout type values are:

      - *
        - *
      • {@link Ext.layout.AbsoluteLayout absolute}
      • - *
      • {@link Ext.layout.AccordionLayout accordion}
      • - *
      • {@link Ext.layout.AnchorLayout anchor}
      • - *
      • {@link Ext.layout.ContainerLayout auto}     Default
      • - *
      • {@link Ext.layout.BorderLayout border}
      • - *
      • {@link Ext.layout.CardLayout card}
      • - *
      • {@link Ext.layout.ColumnLayout column}
      • - *
      • {@link Ext.layout.FitLayout fit}
      • - *
      • {@link Ext.layout.FormLayout form}
      • - *
      • {@link Ext.layout.HBoxLayout hbox}
      • - *
      • {@link Ext.layout.MenuLayout menu}
      • - *
      • {@link Ext.layout.TableLayout table}
      • - *
      • {@link Ext.layout.ToolbarLayout toolbar}
      • - *
      • {@link Ext.layout.VBoxLayout vbox}
      • - *
      - * - *
    • Layout specific configuration properties
    • - *

      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 type - * specified.

      - * - *
    - * - *
  • Specify as a String
  • - *
      - *
    • Example usage:
    • -
      
      -layout: 'vbox',
      -layoutConfig: {
      -    padding: '5',
      -    align: 'left'
      -}
      -
      - *
    • layout
    • - *

      The layout type to be used for this container (see list - * of valid layout type values above).


      - *
    • {@link #layoutConfig}
    • - *

      Additional layout specific configuration properties. For complete - * details regarding the valid config options for each layout type, see the - * layout class corresponding to the layout specified.

      - *
- */ - /** - * @cfg {Object} layoutConfig - * This is a config object containing properties specific to the chosen - * {@link #layout} if {@link #layout} - * has been specified as a string.

- */ - /** - * @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 50. - */ - 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 - *
** IMPORTANT: be sure to {@link #layout specify a layout} if needed ! **
- *

A single item, or an array of child Components to be added to this container, - * for example:

- *

-// specifying a single item
-items: {...},
-layout: 'fit',    // specify a layout!
-
-// specifying multiple items
-items: [{...}, {...}],
-layout: 'anchor', // specify a layout!
-     * 
- *

Each item may be:

- *
    - *
  • any type of object based on {@link Ext.Component}
  • - *
  • a fully instanciated object or
  • - *
  • an object literal that:
  • - *
      - *
    • has a specified {@link Ext.Component#xtype xtype}
    • - *
    • 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}.
    • - *
    • If an {@link Ext.Component#xtype xtype} is not explicitly - * specified, the {@link #defaultType} for that Container is used.
    • - *
    • will be "lazily instanciated", avoiding the overhead of constructing a fully - * instanciated Component object
    • - *
- *

Notes:

- *
    - *
  • 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.
  • - *
  • Do not specify {@link Ext.Panel#contentEl contentEl}/ - * {@link Ext.Panel#html html} with items.
  • - *
- */ - /** - * @cfg {Object} defaults - *

A config object that will be applied to all components added to this container either via the {@link #items} - * config or via the {@link #add} or {@link #insert} methods. The defaults config can contain any - * number of name/value property pairs to be added to each item, and should be valid for the types of items - * being added to the container. For example, to automatically apply padding to the body of each of a set of - * contained {@link Ext.Panel} items, you could pass: defaults: {bodyStyle:'padding:15px'}.


- *

Note: defaults will not be applied to config objects if the option is already specified. - * For example:


-defaults: {               // defaults are applied to items, not the container
-    autoScroll:true
-},
-items: [
-    {
-        xtype: 'panel',   // defaults do not 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 do have precedence over options
-        id: 'panel2',     // options in components, so the defaults
-        autoScroll: false // will be applied here, panel2 will be autoScroll:true.
-    })
-]
-     * 
- */ - - - /** @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 - *

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.

- *

Defaults to 'panel', except {@link Ext.menu.Menu} which defaults to 'menuitem', - * and {@link Ext.Toolbar} and {@link Ext.ButtonGroup} which default to 'button'.

- */ - defaultType : 'panel', - - /** @cfg {String} resizeEvent - * The event to listen to for resizing in layouts. Defaults to 'resize'. - */ - resizeEvent: 'resize', - - /** - * @cfg {Array} bubbleEvents - *

An array of events that, when fired, should be bubbled to any parent container. - * Defaults to ['add', 'remove']. - */ - 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' - ); - - this.enableBubble(this.bubbleEvents); - - /** - * 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.initItems(); - this.layout = layout; - layout.setContainer(this); - }, - - afterRender: function(){ - 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(this.activeItem !== undefined){ - var item = this.activeItem; - delete this.activeItem; - this.layout.setActiveItem(item); - } - if(!this.ownerCt){ - // force a layout if no ownerCt is set - this.doLayout(false, true); - } - if(this.monitorResize === true){ - Ext.EventManager.onWindowResize(this.doLayout, this, [false]); - } - }, - - /** - *

Returns the Element to be used to contain the child Components of this Container.

- *

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.

- * @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(); - }, - - /** - *

Adds {@link Ext.Component Component}(s) to this Container.

- *

Description : - *

    - *
  • Fires the {@link #beforeadd} event before adding
  • - *
  • The Container's {@link #defaults default config values} will be applied - * accordingly (see {@link #defaults} for details).
  • - *
  • Fires the {@link #add} event after the component has been added.
  • - *
- *

Notes : - *

    - *
  • If the Container is already rendered when add - * 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 - * add multiple child components if needed while only refreshing the layout - * once. For example:
    
    -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
    -     * 
  • - *
  • Warning: 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.
  • - *
- * @param {Object/Array} component - *

Either a single component or an Array of components to add. See - * {@link #items} for additional information.

- * @param {Object} (Optional) component_2 - * @param {Object} (Optional) component_n - * @return {Ext.Component} component The Component (or config object) that was added. - */ - add : function(comp){ - this.initItems(); - var args = arguments.length > 1; - if(args || Ext.isArray(comp)){ - Ext.each(args ? arguments : comp, function(c){ - this.add(c); - }, this); - return; - } - var c = this.lookupComponent(this.applyDefaults(comp)); - var pos = this.items.length; - if(this.fireEvent('beforeadd', this, c, pos) !== false && this.onBeforeAdd(c) !== false){ - this.items.add(c); - c.ownerCt = this; - this.onAdd(c); - this.fireEvent('add', this, c, pos); - } - return c; - }, - - onAdd : function(c){ - // Empty template method - }, - - /** - * 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.

- * Ext uses lazy rendering, and will only render the inserted Component should - * it become necessary.

- * 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.

- * 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){ - for(var i = len-1; i >= 1; --i) { - this.insert(index, a[i]); - } - return; - } - 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.ownerCt = this; - this.onAdd(c); - this.fireEvent('add', this, c, index); - } - return c; - }, - - // private - applyDefaults : function(c){ - if(this.defaults){ - if(Ext.isString(c)){ - c = Ext.ComponentMgr.get(c); - Ext.apply(c, this.defaults); - }else if(!c.events){ - Ext.applyIf(c, this.defaults); - }else{ - Ext.apply(c, this.defaults); - } - } - 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){ - delete c.ownerCt; - if(this.layout && this.rendered){ - this.layout.onRemove(c); - } - this.onRemove(c); - this.items.remove(c); - if(autoDestroy === true || (autoDestroy !== false && this.autoDestroy)){ - c.destroy(); - } - this.fireEvent('remove', this, c); - } - return c; - }, - - onRemove: function(c){ - // Empty template method - }, - - /** - * 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 {@link #items} property - * and gets a direct child component of this container. - * @param {String/Number} comp This parameter may be any of the following: - *
    - *
  • a String : representing the {@link Ext.Component#itemId itemId} - * or {@link Ext.Component#id id} of the child component
  • - *
  • a Number : representing the position of the child component - * within the {@link #items} property
  • - *
- *

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){ - return Ext.create(config, this.defaultType); - }, - - // private - canLayout: function() { - var el = this.getVisibilityEl(); - return el && !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.canLayout() || this.collapsed){ - 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; - }, - - //private - 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(){ - Ext.Container.superclass.onShow.call(this); - if(this.deferLayout !== undefined){ - 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.ContainerLayout(this.layoutConfig); - this.setLayout(layout); - } - return this.layout; - }, - - // private - beforeDestroy : function(){ - if(this.items){ - Ext.destroy.apply(Ext, this.items.items); - } - 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 (this) 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 (this) 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); + +Ext.createInterceptor = Ext.util.Functions.createInterceptor; + /** - * @class Ext.layout.ContainerLayout - *

The ContainerLayout class is the default layout manager delegated by {@link Ext.Container} to - * render any child Components when no {@link Ext.Container#layout layout} is configured into - * a {@link Ext.Container Container}. ContainerLayout provides the basic foundation for all other layout - * classes in Ext. It simply renders all child Components into the Container, performing no sizing or - * positioning services. To utilize a layout that provides sizing and positioning of child Components, - * specify an appropriate {@link Ext.Container#layout layout}.

- *

This class is intended to be extended or created via the {@link Ext.Container#layout layout} - * configuration property. See {@link Ext.Container#layout} for additional details.

+ * Shorthand for {@link Ext.util.Functions#createSequence} + * @param {Function} origFn The original function. + * @param {Function} newFn The function to sequence + * @param {Object} scope (optional) The scope (this reference) in which the passed function is executed. + * If omitted, defaults to the scope in which the original function is called or the browser window. + * @return {Function} The new function + * @member Ext + * @method defer */ -Ext.layout.ContainerLayout = function(config){ - Ext.apply(this, config); -}; -Ext.layout.ContainerLayout.prototype = { - /** - * @cfg {String} extraCls - *

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.

- *

Note: extraCls defaults to '' except for the following classes - * which assign a value by default: - *

    - *
  • {@link Ext.layout.AbsoluteLayout Absolute Layout} : 'x-abs-layout-item'
  • - *
  • {@link Ext.layout.Box Box Layout} : 'x-box-item'
  • - *
  • {@link Ext.layout.ColumnLayout Column Layout} : 'x-column'
  • - *
- * To configure the above Classes with an extra CSS class append to the default. For example, - * for ColumnLayout:

-     * extraCls: 'x-column custom-class'
-     * 
- *

- */ - /** - * @cfg {Boolean} renderHidden - * True to hide each contained item on render (defaults to false). - */ +Ext.createSequence = Ext.util.Functions.createSequence; - /** - * A reference to the {@link Ext.Component} that is active. For example,

-     * if(myPanel.layout.activeItem.id == 'item-1') { ... }
-     * 
- * 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}). Read-only. Related to {@link Ext.Container#activeItem}. - * @type {Ext.Component} - * @property activeItem - */ +/** + * Shorthand for {@link Ext.util.Functions#createDelegate} + * @param {Function} fn The function to delegate. + * @param {Object} scope (optional) The scope (this reference) in which the function is executed. + * If omitted, defaults to the browser window. + * @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 + * @member Ext + * @method defer + */ +Ext.createDelegate = Ext.util.Functions.createDelegate; +/** + * @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; + } + } + }; - // private - monitorResize:false, - // private - activeItem : null, + 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; + } + } - // private - layout : function(){ - var target = this.container.getLayoutTarget(); - this.onLayout(this.container, target); - this.container.fireEvent('afterlayout', this.container, this); - }, + if((v = e.originalFn.apply(obj, args)) !== undefined){ + returnValue = v; + } - // private - onLayout : function(ct, target){ - this.renderAll(ct, target); - }, + 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; + } - // private - isValidParent : function(c, target){ - return target && c.getDomPositionEl().dom.parentNode == (target.dom || target); - }, + 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 + }); + }, - // private - renderAll : function(ct, target){ - var items = ct.items.items; - for(var i = 0, len = items.length; i < len; i++) { - var c = items[i]; - if(c && (!c.rendered || !this.isValidParent(c, target))){ - this.renderItem(c, i, target); + // 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; + } + } + }, - // private - renderItem : function(c, position, target){ - if(c && !c.rendered){ - c.render(target, position); - this.configureItem(c, position); - }else if(c && !this.isValidParent(c, target)){ - if(Ext.isNumber(position)){ - position = target.dom.childNodes[position]; + /** + * Relays selected events from the specified Observable as if the events were fired by this. + * @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))); + }; } - target.dom.insertBefore(c.getDomPositionEl().dom, position || null); - c.container = target; - this.configureItem(c, position); - } - }, + 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); + } + }, + + /** + *

Enables events fired by this Observable to bubble up an owner hierarchy by calling + * this.getBubbleTarget() if present. There is no implementation in the Observable base class.

+ *

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.

+ *

Example:


+Ext.override(Ext.form.Field, {
     
-    // private
-    configureItem: function(c, position){
-        if(this.extraCls){
-            var t = c.getPositionEl ? c.getPositionEl() : c;
-            t.addClass(this.extraCls);
-        }
-        if (this.renderHidden && c != this.activeItem) {
-            c.hide();
-        }
-        if(c.doLayout && this.forceLayout){
-            c.doLayout(false, true);
-        }
-    },
+    initComponent : Ext.form.Field.prototype.initComponent.createSequence(function() {
+        this.enableBubble('change');
+    }),
+
     
-    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);
+    getBubbleTarget : function() {
+        if (!this.formPanel) {
+            this.formPanel = this.findParentByType('form');
         }
-    },
+        return this.formPanel;
+    }
+});
 
-    // private
-    onResize: function(){
-        var ct = this.container,
-            b;
+var myForm = new Ext.formPanel({
+    title: 'User Details',
+    items: [{
+        ...
+    }],
+    listeners: {
+        change: function() {
             
-        if(ct.collapsed){
-            return;
+            myForm.header.setStyle('color', 'red');
         }
-        if(b = ct.bufferResize){
-            // Only allow if we should buffer the layout
-            if(ct.shouldBufferLayout()){
-                if(!this.resizeTask){
-                    this.resizeTask = new Ext.util.DelayedTask(this.runLayout, this);
-                    this.resizeBuffer = Ext.isNumber(b) ? b : 50;
+    }
+});
+
+ * @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; } - ct.layoutPending = true; - this.resizeTask.delay(this.resizeBuffer); } - }else{ - ct.doLayout(); } - }, - - // private - runLayout: function(){ - var ct = this.container; - ct.doLayout(); - delete ct.layoutPending; - }, + }; +}()); - // private - setContainer : function(ct){ - 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; - }, - // private - parseMargins : function(v){ - if(Ext.isNumber(v)){ - v = v.toString(); - } - var ms = v.split(' '); - var len = ms.length; - if(len == 1){ - ms[1] = ms[0]; - ms[2] = ms[0]; - ms[3] = ms[0]; - } - if(len == 2){ - ms[2] = ms[0]; - ms[3] = ms[1]; - } - 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( - '
', - '', - '
', - '
', - '
' - ); - 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 : Ext.emptyFn +Ext.util.Observable.capture = function(o, fn, scope){ + o.fireEvent = o.fireEvent.createInterceptor(fn, scope); }; -Ext.Container.LAYOUTS['auto'] = Ext.layout.ContainerLayout;/** - * @class Ext.layout.FitLayout - * @extends Ext.layout.ContainerLayout - *

This is a base class for layouts that contain a single item that automatically expands to fill the layout's - * container. This class is intended to be extended or created via the layout:'fit' {@link Ext.Container#layout} - * config, and should generally not need to be created directly via the new keyword.

- *

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:

- *

-var p = new Ext.Panel({
-    title: 'Fit Layout',
-    layout:'fit',
-    items: {
-        title: 'Inner Panel',
-        html: '<p>This is the inner panel content</p>',
-        border: false
-    }
-});
-
- */ -Ext.layout.FitLayout = Ext.extend(Ext.layout.ContainerLayout, { - // private - monitorResize:true, - - // private - onLayout : function(ct, target){ - Ext.layout.FitLayout.superclass.onLayout.call(this, ct, target); - if(!this.container.collapsed){ - var sz = (Ext.isIE6 && Ext.isStrict && target.dom == document.body) ? target.getViewSize() : target.getStyleSize(); - this.setItemSize(this.activeItem || ct.items.itemAt(0), sz); - } - }, - - // 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 - *

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.

- *

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.

- *

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:

- *

-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: '<h1>Welcome to the Wizard!</h1><p>Step 1 of 3</p>'
-    },{
-        id: 'card-1',
-        html: '<p>Step 2 of 3</p>'
-    },{
-        id: 'card-2',
-        html: '<h1>Congratulations!</h1><p>Step 3 of 3 - Complete</p>'
-    }]
-});
-
- */ -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, - - constructor: function(config){ - Ext.layout.CardLayout.superclass.constructor.call(this, config); - this.forceLayout = (this.deferredRender === false); - }, - - /** - * 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){ - item = this.container.getComponent(item); - if(this.activeItem != item){ - if(this.activeItem){ - this.activeItem.hide(); - } - var layout = item.doLayout && (this.layoutOnCardChange || !item.rendered); - this.activeItem = item; - item.show(); - this.layout(); - if(layout){ - item.doLayout(); - } - } - }, - - // 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 - *

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 - * {@link #anchor} rules.

- *

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.

- *

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 anchorSize. - * 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:

- *

-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%'
-    }]
-});
- * 
- */ -Ext.layout.AnchorLayout = Ext.extend(Ext.layout.ContainerLayout, { - /** - * @cfg {String} anchor - *

This configuation option is to be applied to child items of a container managed by - * this layout (ie. configured with layout:'anchor').


- * - *

This value is what tells the layout how an item should be anchored to the container. items - * added to an AnchorLayout accept an anchoring-specific config property of anchor 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:

    - * - *
  • Percentage : Any value between 1 and 100, expressed as a percentage.
    - * 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:
    
    -// 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
    -     * 
  • - * - *
  • Offsets : Any positive or negative integer value.
    - * 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:
    
    -// 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
    -     * 
  • - * - *
  • Sides : Valid values are 'right' (or 'r') and 'bottom' - * (or 'b').
    - * 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.
  • - * - *
  • Mixed :
    - * 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: - *
    
    -anchor: '-50 75%' 
    -     * 
  • - * - * - *
- */ - - // private - monitorResize:true, - - // private - getAnchorViewSize : function(ct, target){ - return target.dom == document.body ? - target.getViewSize() : target.getStyleSize(); - }, - - // private - onLayout : function(ct, target){ - Ext.layout.AnchorLayout.superclass.onLayout.call(this, ct, target); - - var size = this.getAnchorViewSize(ct, target); - - 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 = ct.items.items, len = cs.length, i, c, a, cw, ch; - for(i = 0; i < len; i++){ - c = cs[i]; - if(c.anchor){ - a = c.anchorSpec; - if(!a){ // cache all anchor values - var 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), c) : undefined; - ch = a.bottom ? this.adjustHeightAnchor(a.bottom(h), c) : undefined; - - if(cw || ch){ - c.setSize(cw || undefined, ch || undefined); - } - } - } - }, - - // private - parseAnchor : function(a, start, cstart){ - if(a && a != 'none'){ - var last; - if(/^(r|right|b|bottom)$/i.test(a)){ // standard anchor - var diff = cstart - start; - return function(v){ - if(v !== last){ - last = v; - return v - diff; - } - } - }else if(a.indexOf('%') != -1){ - var ratio = parseFloat(a.replace('%', ''))*.01; // percentage - return function(v){ - if(v !== last){ - last = v; - return Math.floor(v*ratio); - } - } - }else{ - a = parseInt(a, 10); - if(!isNaN(a)){ // simple offset adjustment - 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 - *

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.

- *

ColumnLayout does not have any direct config options (other than inherited ones), but it does support a - * specific config property of columnWidth 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).

- *

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).

- *

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 remaining 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:

- *

-// 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
-    }]
-});
-
- */ -Ext.layout.ColumnLayout = Ext.extend(Ext.layout.ContainerLayout, { - // private - monitorResize:true, - - extraCls: 'x-column', - - scrollOffset : 0, - - // private - isValidParent : function(c, target){ - return (c.getPositionEl ? c.getPositionEl() : c.getEl()).dom.parentNode == this.innerCt.dom; - }, - - // private - onLayout : function(ct, target){ - var cs = ct.items.items, len = cs.length, c, i; - - if(!this.innerCt){ - target.addClass('x-column-layout-ct'); - - // 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'}); - } - this.renderAll(ct, this.innerCt); - - var size = Ext.isIE && target.dom != Ext.getBody().dom ? target.getStyleSize() : target.getViewSize(); - - if(size.width < 1 && size.height < 1){ // display none? - return; - } - - var w = size.width - target.getPadding('lr') - this.scrollOffset, - h = size.height - target.getPadding('tb'), - 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]; - if(!c.columnWidth){ - pw -= (c.getSize().width + c.getEl().getMargins('lr')); - } - } - - pw = pw < 0 ? 0 : pw; - - for(i = 0; i < len; i++){ - c = cs[i]; - if(c.columnWidth){ - c.setSize(Math.floor(c.columnWidth*pw) - c.getEl().getMargins('lr')); - } - } - } - - /** - * @property activeItem - * @hide - */ -}); - -Ext.Container.LAYOUTS['column'] = Ext.layout.ColumnLayout;/** - * @class Ext.layout.BorderLayout - * @extends Ext.layout.ContainerLayout - *

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.

- *

This class is intended to be extended or created via the layout:'border' - * {@link Ext.Container#layout} config, and should generally not need to be created directly - * via the new keyword.

- *

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.

- *

Example usage:

- *

-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'
-    }]
-});
-
- *

Notes:

    - *
  • Any container using the BorderLayout must have a child item with region:'center'. - * 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.
  • - *
  • Any child items with a region of west or east must have width defined - * (an integer representing the number of pixels that the region should take up).
  • - *
  • Any child items with a region of north or south must have height defined.
  • - *
  • The regions of a BorderLayout are fixed at render time and thereafter, its child Components may not be removed or added. 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: - *
    
    -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}();
    - * 
    - *
  • - *
  • To reference a {@link Ext.layout.BorderLayout.Region Region}: - *
    
    -wr = myBorderPanel.layout.west;
    - * 
    - *
  • - *
- */ -Ext.layout.BorderLayout = Ext.extend(Ext.layout.ContainerLayout, { - // private - monitorResize:true, - // private - rendered : false, - // private - onLayout : function(ct, target){ - var collapsed; - if(!this.rendered){ - target.addClass('x-border-layout-ct'); - var items = ct.items.items; - collapsed = []; - for(var i = 0, len = items.length; i < len; i++) { - var c = items[i]; - var pos = c.region; - if(c.collapsed){ - collapsed.push(c); - } - c.collapsed = false; - if(!c.rendered){ - c.render(target, i); - c.getDomPositionEl().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 = target.getViewSize(); - if(size.width < 20 || size.height < 20){ // display none? - if(collapsed){ - this.restoreCollapsed = collapsed; + +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; + } +}; + +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, + + + + useKeydown = Ext.isWebKit ? + Ext.num(navigator.userAgent.match(/AppleWebKit\/(\d+)/)[1]) >= 525 : + !((Ext.isGecko && !Ext.isWindows) || Ext.isOpera); + + return { + + doResizeEvent: function(){ + var h = D.getViewHeight(), + w = D.getViewWidth(); + + + if(curHeight != h || curWidth != w){ + resizeEvent.fire(curWidth = w, curHeight = h); } - return; - }else if(this.restoreCollapsed){ - collapsed = this.restoreCollapsed; - delete this.restoreCollapsed; - } + }, - var w = size.width, h = size.height; - var centerW = w, centerH = h, centerY = 0, centerX = 0; + + 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); + }, - var n = this.north, s = this.south, west = this.west, e = this.east, c = this.center; - if(!c && Ext.layout.BorderLayout.WARN !== false){ - throw 'No center region defined in BorderLayout ' + ct.id; - } + + fireWindowResize : function(){ + if(resizeEvent){ + resizeTask.delay(100); + } + }, - if(n && n.isVisible()){ - var b = n.getSize(); - var 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); + + 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); + }, + + + removeResizeListener : function(fn, scope){ + if(resizeEvent){ + resizeEvent.removeListener(fn, scope); + } + }, + + + fireResize : function(){ + if(resizeEvent){ + resizeEvent.fire(D.getViewWidth(), D.getViewHeight()); + } + }, + + + textResizeInterval : 50, + + + ieDeferSrc : false, + + + getKeyEvent : function(){ + return useKeydown ? 'keydown' : 'keypress'; + }, + + + + useKeydown: useKeydown + }; +}()); + +Ext.EventManager.on = Ext.EventManager.addListener; + + +Ext.apply(Ext.EventObjectImpl.prototype, { + + BACKSPACE: 8, + + TAB: 9, + + NUM_CENTER: 12, + + ENTER: 13, + + RETURN: 13, + + SHIFT: 16, + + CTRL: 17, + CONTROL : 17, + + ALT: 18, + + PAUSE: 19, + + CAPS_LOCK: 20, + + ESC: 27, + + SPACE: 32, + + PAGE_UP: 33, + PAGEUP : 33, + + PAGE_DOWN: 34, + PAGEDOWN : 34, + + END: 35, + + HOME: 36, + + LEFT: 37, + + UP: 38, + + RIGHT: 39, + + DOWN: 40, + + PRINT_SCREEN: 44, + + INSERT: 45, + + DELETE: 46, + + ZERO: 48, + + ONE: 49, + + TWO: 50, + + THREE: 51, + + FOUR: 52, + + FIVE: 53, + + SIX: 54, + + SEVEN: 55, + + EIGHT: 56, + + NINE: 57, + + A: 65, + + B: 66, + + C: 67, + + D: 68, + + E: 69, + + F: 70, + + G: 71, + + H: 72, + + I: 73, + + J: 74, + + K: 75, + + L: 76, + + M: 77, + + N: 78, + + O: 79, + + P: 80, + + Q: 81, + + R: 82, + + S: 83, + + T: 84, + + U: 85, + + V: 86, + + W: 87, + + X: 88, + + Y: 89, + + Z: 90, + + CONTEXT_MENU: 93, + + NUM_ZERO: 96, + + NUM_ONE: 97, + + NUM_TWO: 98, + + NUM_THREE: 99, + + NUM_FOUR: 100, + + NUM_FIVE: 101, + + NUM_SIX: 102, + + NUM_SEVEN: 103, + + NUM_EIGHT: 104, + + NUM_NINE: 105, + + NUM_MULTIPLY: 106, + + NUM_PLUS: 107, + + NUM_MINUS: 109, + + NUM_PERIOD: 110, + + NUM_DIVISION: 111, + + F1: 112, + + F2: 113, + + F3: 114, + + F4: 115, + + F5: 116, + + F6: 117, + + F7: 118, + + F8: 119, + + F9: 120, + + F10: 121, + + F11: 122, + + F12: 123, + + + isNavKeyPress : function(){ + var me = this, + k = this.normalizeKey(me.keyCode); + return (k >= 33 && k <= 40) || + 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) || + (k >= 16 && k <= 20) || + (k >= 44 && k <= 46); + }, + + getPoint : function(){ + return new Ext.lib.Point(this.xy[0], this.xy[1]); + }, + + + hasModifier : function(){ + return ((this.ctrlKey || this.altKey) || this.shiftKey); + } +}); +Ext.Element.addMethods({ + + swallowEvent : function(eventName, preventDefault) { + var me = this; + function fn(e) { + e.stopPropagation(); + if (preventDefault) { + e.preventDefault(); + } } - if(s && s.isVisible()){ - var b = s.getSize(); - var m = s.getMargins(); - b.width = w - (m.left+m.right); - b.x = m.left; - var totalHeight = (b.height + m.top + m.bottom); - b.y = h - totalHeight + m.top; - centerH -= totalHeight; - s.applyLayout(b); + + if (Ext.isArray(eventName)) { + Ext.each(eventName, function(e) { + me.on(e, fn); + }); + return me; } - if(west && west.isVisible()){ - var b = west.getSize(); - var m = west.getMargins(); - b.height = centerH - (m.top+m.bottom); - b.x = m.left; - b.y = centerY + m.top; - var totalWidth = (b.width + m.left + m.right); - centerX += totalWidth; - centerW -= totalWidth; - west.applyLayout(b); + me.on(eventName, fn); + return me; + }, + + + relayEvent : function(eventName, observable) { + this.on(eventName, function(e) { + observable.fireEvent(eventName, e); + }); + }, + + + clean : function(forceReclean) { + var me = this, + dom = me.dom, + n = dom.firstChild, + ni = -1; + + if (Ext.Element.data(dom, 'isCleaned') && forceReclean !== true) { + return me; } - if(e && e.isVisible()){ - var b = e.getSize(); - var m = e.getMargins(); - b.height = centerH - (m.top+m.bottom); - var totalWidth = (b.width + m.left + m.right); - b.x = w - totalWidth + m.left; - b.y = centerY + m.top; - centerW -= totalWidth; - e.applyLayout(b); + + while (n) { + var nx = n.nextSibling; + if (n.nodeType == 3 && !(/\S/.test(n.nodeValue))) { + dom.removeChild(n); + } else { + n.nodeIndex = ++ni; + } + n = nx; } - if(c){ - var 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); + + Ext.Element.data(dom, 'isCleaned', true); + return me; + }, + + + load : function() { + var updateManager = this.getUpdater(); + updateManager.update.apply(updateManager, arguments); + + return this; + }, + + + getUpdater : function() { + return this.updateManager || (this.updateManager = new Ext.Updater(this)); + }, + + + update : function(html, loadScripts, callback) { + if (!this.dom) { + return this; } - if(collapsed){ - for(var i = 0, len = collapsed.length; i < len; i++){ - collapsed[i].collapse(false); + html = html || ""; + + if (loadScripts !== true) { + this.dom.innerHTML = html; + if (typeof callback == 'function') { + callback(); } + return this; } - if(Ext.isIE && Ext.isStrict){ // workaround IE strict repainting issue - target.repaint(); - } - }, - destroy: function() { - var r = ['north', 'south', 'east', 'west']; - for (var i = 0; i < r.length; i++) { - var region = this[r[i]]; - if(region){ - if(region.destroy){ - region.destroy(); - }else if (region.split){ - region.split.destroy(true); + var id = Ext.id(), + dom = this.dom; + + html += ''; + + Ext.lib.Event.onAvailable(id, function() { + var DOC = document, + hd = DOC.getElementsByTagName("head")[0], + re = /(?:]*)?>)((\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]); + } } } - } - Ext.layout.BorderLayout.superclass.destroy.call(this); - } + + el = DOC.getElementById(id); + if (el) { + Ext.removeNode(el); + } + + if (typeof callback == 'function') { + callback(); + } + }); + dom.innerHTML = html.replace(/(?:)((\n|\r|.)*?)(?:<\/script>)/ig, ""); + return this; + }, - /** - * @property activeItem - * @hide - */ -}); + + removeAllListeners : function() { + this.removeAnchor(); + Ext.EventManager.removeAll(this.dom); + return this; + }, -/** - * @class Ext.layout.BorderLayout.Region - *

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}.

- *

Region size is managed automatically and cannot be changed by the user -- for - * {@link #split resizable regions}, see {@link Ext.layout.BorderLayout.SplitRegion}.

- * @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: north, south, - * east, west and center. Every {@link Ext.layout.BorderLayout BorderLayout} - * must have a center region 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); + + 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) { + proxy.setBox(me.getBox()); } + return proxy; } -}; +}); -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 - * {@link #autoHide} = false). Setting {@link #animFloat} = false will - * prevent the open and close of these floated panels from being animated (defaults to true). - */ - /** - * @cfg {Boolean} autoHide - * When a collapsed region's bar is clicked, the region's panel will be displayed as a floated - * panel. If autoHide = true, the panel will automatically hide after the user mouses - * out of the panel. If autoHide = false, the panel will continue to display until the - * user clicks outside of the panel (defaults to true). - */ - /** - * @cfg {String} collapseMode - * collapseMode supports two configuration values:
    - *
  • undefined (default)
    By default, {@link #collapsible} - * regions are collapsed by clicking the expand/collapse tool button that renders into the region's - * title bar.
  • - *
  • 'mini'
    Optionally, when collapseMode is set to - * 'mini' the region's split bar will also display a small collapse button in the center of - * the bar. In 'mini' mode the region will collapse to a thinner bar than in normal mode. - *
  • - *

- *

Note: if a collapsible region does not have a title bar, then set collapseMode = - * 'mini' and {@link #split} = true 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.

- *

See also {@link #cmargins}.

- */ - /** - * @cfg {Object} margins - * An object containing margins to apply to the region when in the expanded state in the - * format:

-{
-    top: (top margin),
-    right: (right margin),
-    bottom: (bottom margin),
-    left: (left margin)
-}
- *

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:

- *

    - *
  • If there is only one value, it applies to all sides.
  • - *
  • 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.
  • - *
  • 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.
  • - *
  • If there are four values, they apply to the top, right, bottom, and left, respectively.
  • - *

- *

Defaults to:


-     * {top:0, right:0, bottom:0, left:0}
-     * 
- */ - /** - * @cfg {Object} cmargins - * An object containing margins to apply to the region when in the collapsed state in the - * format:

-{
-    top: (top margin),
-    right: (right margin),
-    bottom: (bottom margin),
-    left: (left margin)
-}
- *

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.

- *

    - *
  • If there is only one value, it applies to all sides.
  • - *
  • 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.
  • - *
  • 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.
  • - *
  • If there are four values, they apply to the top, right, bottom, and left, respectively.
  • - *

- */ - /** - * @cfg {Boolean} collapsible - *

true to allow the user to collapse this region (defaults to false). If - * true, an expand/collapse tool button will automatically be rendered into the title - * bar of the region, otherwise the button will not be shown.

- *

Note: that a title bar is required to display the collapse/expand toggle button -- if - * no title is specified for the region's panel, the region will only be collapsible if - * {@link #collapseMode} = 'mini' and {@link #split} = true. - */ - collapsible : false, - /** - * @cfg {Boolean} split - *

true 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 false creating a - * {@link Ext.layout.BorderLayout.Region Region}.


- *

Notes:

    - *
  • this configuration option is ignored if region='center'
  • - *
  • when split == true, it is common to specify a - * {@link Ext.SplitBar#minSize minSize} and {@link Ext.SplitBar#maxSize maxSize} - * 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.
  • - *
  • if {@link #collapseMode} = 'mini' requires split = true to reserve space - * for the collapse tool
  • - *
- */ - split:false, - /** - * @cfg {Boolean} floatable - * true to allow clicking a collapsed region's bar to display the region's panel floated - * above the layout, false to force the user to fully expand a collapsed region by - * clicking the expand button to see it again (defaults to true). - */ - floatable: true, - /** - * @cfg {Number} minWidth - *

The minimum allowable width in pixels for this region (defaults to 50). - * maxWidth may also be specified.


- *

Note: setting the {@link Ext.SplitBar#minSize minSize} / - * {@link Ext.SplitBar#maxSize maxSize} supersedes any specified - * minWidth / maxWidth.

- */ - minWidth:50, - /** - * @cfg {Number} minHeight - * The minimum allowable height in pixels for this region (defaults to 50) - * maxHeight may also be specified.


- *

Note: setting the {@link Ext.SplitBar#minSize minSize} / - * {@link Ext.SplitBar#maxSize maxSize} supersedes any specified - * minHeight / maxHeight.

- */ - 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 - */ +Ext.Element.prototype.getUpdateManager = Ext.Element.prototype.getUpdater; - // private - render : function(ct, p){ - this.panel = p; - p.el.enableDisplayMode(); - this.targetEl = ct; - this.el = p.el; +Ext.Element.addMethods({ + + getAnchorXY : function(anchor, local, s){ + + + 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]; + }, - var gs = p.getState, ps = this.position; - p.getState = function(){ - return Ext.apply(gs.call(p) || {}, this.state); - }.createDelegate(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(); + + + this.removeAnchor(); + Ext.apply(anchor, { + fn: action, + scroll: scroll + }); - 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'); - } + Ext.EventManager.onWindowResize(action, null); + + if(scroll){ + Ext.EventManager.on(window, 'scroll', action, null, + {buffer: !isNaN(monitorScroll) ? monitorScroll : 50}); } + action.call(me); + return me; }, - - // private - getCollapsedEl : function(){ - if(!this.collapsedEl){ - if(!this.toolTemplate){ - var tt = new Ext.Template( - '
 
' - ); - 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: " " - }); - 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); - } + + + 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 this.collapsedEl; + return me; }, - - // private - onExpandClick : function(e){ - if(this.isSlid){ - this.afterSlideIn(); - this.panel.expand(false); - }else{ - this.panel.expand(); + + + 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; }, - // private - onCollapseClick : function(e){ - this.panel.collapse(); - }, - - // private - beforeCollapse : function(p, animate){ - this.lastAnim = animate; - if(this.splitEl){ - this.splitEl.hide(); + + getAlignToXY : function(el, p, o){ + el = Ext.get(el); + + if(!el || !el.dom){ + throw "Element.alignToXY with an element that doesn't exist"; } - this.getCollapsedEl().show(); - this.panel.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}); + + 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, + + w, + h, + r, + dw = Ext.lib.Dom.getViewWidth() -10, + dh = Ext.lib.Dom.getViewHeight()-10, + 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, + p1 = "", + p2 = "", + m = p.match(/^([a-z]+)-([a-z]+)(\?)?$/); + + if(!m){ + throw "Element.alignTo with an invalid alignment " + p; } - this.state.collapsed = true; - this.panel.saveState(); - }, + + p1 = m[1]; + p2 = m[2]; + c = !!m[3]; - // private - beforeExpand : function(animate){ - 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); - }, + + + a1 = me.getAnchorXY(p1, true); + a2 = el.getAnchorXY(p2, false); - // private - onExpand : function(){ - this.isCollapsed = false; - if(this.splitEl){ - this.splitEl.show(); - } - this.layout.layout(); - this.panel.el.setStyle('z-index', 1); - this.state.collapsed = false; - this.panel.saveState(); - }, + x = a2[0] - a1[0] + o[0]; + y = a2[1] - a1[1] + o[1]; - // private - collapseClick : function(e){ - if(this.isSlid){ - e.stopPropagation(); - this.slideIn(); - }else{ - e.stopPropagation(); - this.slideOut(); - } - }, + if(c){ + w = me.getWidth(); + h = me.getHeight(); + r = el.getRegion(); + + + + 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")); + - // private - onHide : function(){ - if(this.isCollapsed){ - this.getCollapsedEl().hide(); - }else if(this.splitEl){ - this.splitEl.hide(); + 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]; }, - // private - onShow : function(){ - if(this.isCollapsed){ - this.getCollapsedEl().show(); - }else if(this.splitEl){ - this.splitEl.show(); - } + + 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); }, - - /** - * True if this region is currently visible, else false. - * @return {Boolean} - */ - isVisible : function(){ - return !this.panel.hidden; + + + adjustForConstraints : function(xy, parent, offsets){ + return this.getConstrainToXY(parent || document, false, offsets, xy) || xy; }, - /** - * 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: {left: (left - * margin), top: (top margin), right: (right margin), bottom: (bottom margin)} - */ - getMargins : function(){ - return this.isCollapsed && this.cmargins ? this.cmargins : this.margins; - }, + + getConstrainToXY : function(el, local, offsets, proposedXY){ + var os = {top:0, left:0, bottom:0, right: 0}; - /** - * 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: {width: (element width), - * height: (element height)} - */ - getSize : function(){ - return this.isCollapsed ? this.getCollapsedEl().getSize() : this.panel.getSize(); - }, + return function(el, local, offsets, proposedXY){ + el = Ext.get(el); + offsets = offsets ? Ext.applyIf(offsets, os) : os; - /** - * 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; - }, + 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]; + } + } - /** - * Returns the minimum allowable height for this region. - * @return {Number} The minimum height - */ - getMinHeight: function(){ - return this.minHeight; - }, + var s = el.getScroll(); - // private - applyLayoutCollapsed : function(box){ - var ce = this.getCollapsedEl(); - ce.setLeftTop(box.x, box.y); - ce.setSize(box.width, box.height); - }, + vx += offsets.left + s.left; + vy += offsets.top + s.top; - // 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); - } - }, + vw -= offsets.right; + vh -= offsets.bottom; - // private - beforeSlide: function(){ - this.panel.beforeEffect(); - }, + var vr = vx + vw, + vb = vy + vh, + xy = proposedXY || (!local ? this.getXY() : [this.getLeft(true), this.getTop(true)]), + x = xy[0], y = xy[1], + offset = this.getConstrainOffset(), + w = this.dom.offsetWidth + offset, + h = this.dom.offsetHeight + offset; - // private - afterSlide : function(){ - this.panel.afterEffect(); - }, + + var moved = false; - // private - initAutoHide : function(){ - if(this.autoHide !== false){ - if(!this.autoHideHd){ - var st = new Ext.util.DelayedTask(this.slideIn, this); - this.autoHideHd = { - "mouseout": function(e){ - if(!e.within(this.el, true)){ - st.delay(500); - } - }, - "mouseover" : function(e){ - st.cancel(); - }, - scope : this - }; + + if((x + w) > vr){ + x = vr - w; + moved = true; } - this.el.on(this.autoHideHd); - } - }, + if((y + h) > vb){ + y = vb - h; + moved = true; + } + + if(x < vx){ + x = vx; + moved = true; + } + if(y < vy){ + y = vy; + moved = true; + } + return moved ? [x, y] : false; + }; + }(), + + + + + + + + + + + + + + + + + + - // private - clearAutoHide : function(){ - if(this.autoHide !== false){ - this.el.un("mouseout", this.autoHideHd.mouseout); - this.el.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 over the top - * of the center Region 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; - if(ts && ts.toggle){ - ts.toggle.hide(); - } - this.el.show(); - if(this.position == 'east' || this.position == 'west'){ - this.panel.setSize(undefined, this.collapsedEl.getHeight()); - }else{ - this.panel.setSize(this.collapsedEl.getWidth(), undefined); - } - 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; - } - } -}; -/** - * @class Ext.layout.BorderLayout.SplitRegion - * @extends Ext.layout.BorderLayout.Region - *

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}.

- * @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 "Drag to resize."). Only applies if - * {@link #useSplitTips} = true. - */ - 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 - * {@link #useSplitTips} = true. - */ - collapsibleSplitTip : "Drag to resize. Double click to hide.", - /** - * @cfg {Boolean} useSplitTips - * true to display a tooltip when the user hovers over a region's split bar - * (defaults to false). The tooltip text will be the value of either - * {@link #splitTip} or {@link #collapsibleSplitTip} 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: " ", - id: this.panel.id + '-xsplit' - }); - if(this.collapseMode == 'mini'){ - this.miniSplitEl = this.splitEl.createChild({ - cls: "x-layout-mini x-layout-mini-"+ps, html: " " - }); - 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.Container.LAYOUTS['border'] = Ext.layout.BorderLayout;/** - * @class Ext.layout.FormLayout - * @extends Ext.layout.AnchorLayout - *

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.

- * - *

This layout manager is used when a Container is configured with the layout:'form' - * {@link Ext.Container#layout layout} config option, and should generally not need to be created directly - * via the new keyword. See {@link Ext.Container#layout} for additional details.

- * - *

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.

- * - *

A {@link Ext.Container Container} using the FormLayout layout manager (e.g. - * {@link Ext.form.FormPanel} or specifying layout:'form') can also accept the following - * layout-specific config properties:

    - *
  • {@link Ext.form.FormPanel#hideLabels hideLabels}
  • - *
  • {@link Ext.form.FormPanel#labelAlign labelAlign}
  • - *
  • {@link Ext.form.FormPanel#labelPad labelPad}
  • - *
  • {@link Ext.form.FormPanel#labelSeparator labelSeparator}
  • - *
  • {@link Ext.form.FormPanel#labelWidth labelWidth}
  • - *

- * - *

Any Component (including Fields) managed by FormLayout accepts the following as a config option: - *

    - *
  • {@link Ext.Component#anchor anchor}
  • - *

- * - *

Any Component managed by FormLayout may be rendered as a form field (with an associated label) by - * configuring it with a non-null {@link Ext.Component#fieldLabel fieldLabel}. Components configured - * in this way may be configured with the following options which affect the way the FormLayout renders them: - *

    - *
  • {@link Ext.Component#clearCls clearCls}
  • - *
  • {@link Ext.Component#fieldLabel fieldLabel}
  • - *
  • {@link Ext.Component#hideLabel hideLabel}
  • - *
  • {@link Ext.Component#itemCls itemCls}
  • - *
  • {@link Ext.Component#labelSeparator labelSeparator}
  • - *
  • {@link Ext.Component#labelStyle labelStyle}
  • - *

- * - *

Example usage:

- *

-// 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
-});
-
- */ -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 container 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 false. - */ - trackLabels: false, - - onRemove: function(c){ - Ext.layout.FormLayout.superclass.onRemove.call(this, c); - if(this.trackLabels && !this.isHide(c)){ - 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){ - 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;' - }); - } - } - }, - isHide: function(c){ - return c.hideLabel || this.container.hideLabels; + getConstrainOffset : function(){ + return 0; }, - onFieldShow: function(c){ - c.getItemCt().removeClass('x-hide-' + c.hideMode); - }, - onFieldHide: function(c){ - c.getItemCt().addClass('x-hide-' + c.hideMode); + getCenterXY : function(){ + return this.getAlignToXY(document, 'c-c'); }, - //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; - }, + + center : function(centerIn){ + return this.alignTo(centerIn || document, 'c-c'); + } +}); - /** - * @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:


-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>'
-);
-
- *

This may be specified to produce a different DOM structure when rendering form Fields.

- *

A description of the properties within the template follows:

    - *
  • itemCls : String
    The CSS class applied to the outermost div wrapper - * that contains this field label and field element (the default class is 'x-form-item' and itemCls - * will be added to that). If supplied, itemCls at the field level will override the default itemCls - * supplied at the container level.
  • - *
  • id : String
    The id of the Field
  • - *
  • {@link #labelStyle} : String
    - * A CSS style specification string to add to the field label for this field (defaults to '' or the - * {@link #labelStyle layout's value for labelStyle}).
  • - *
  • label : String
    The text to display as the label for this - * field (defaults to '')
  • - *
  • {@link #labelSeparator} : String
    The separator to display after - * the text of the label for this field (defaults to a colon ':' or the - * {@link #labelSeparator layout's value for labelSeparator}). To hide the separator use empty string ''.
  • - *
  • elementStyle : String
    The styles text for the input element's wrapper.
  • - *
  • clearCls : String
    The CSS class to apply to the special clearing div - * rendered directly after each form field wrapper (defaults to 'x-form-clear-left')
  • - *
- *

Also see {@link #getTemplateArgs}

- */ +Ext.Element.addMethods({ + + select : function(selector, unique){ + return Ext.Element.select(selector, unique, this.dom); + } +}); +Ext.apply(Ext.Element.prototype, function() { + var GETDOM = Ext.getDom, + GET = Ext.get, + DH = Ext.DomHelper; + + return { + + 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; + } + }; +}()); - // 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; + +Ext.Element.boxMarkup = '
'; + +Ext.Element.addMethods(function(){ + var INTERNAL = "_internal", + pxMatch = /(\d+\.?\d+)px/; + return { + + applyStyles : function(style){ + Ext.DomHelper.applyStyles(this.dom, style); + return this; + }, + + + getStyles : function(){ + var ret = {}; + Ext.each(arguments, function(v) { + ret[v] = this.getStyle(v); + }, + this); + return ret; + }, + + + setOverflow : function(v){ + var dom = this.dom; + if(v=='auto' && Ext.isMac && Ext.isGecko2){ + dom.style.overflow = 'hidden'; + (function(){dom.style.overflow = 'auto';}).defer(1); + }else{ + dom.style.overflow = v; } - if(position){ - c.itemCt = this.fieldTpl.insertBefore(position, args, true); + }, + + + boxWrap : function(cls){ + cls = cls || 'x-box'; + var el = Ext.get(this.insertHtml("beforeBegin", "
" + String.format(Ext.Element.boxMarkup, cls) + "
")); + Ext.DomQuery.selectNode('.' + cls + '-mc', el.dom).appendChild(this.dom); + return el; + }, + + + setSize : function(width, height, animate){ + var me = this; + if(typeof width == 'object'){ + 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{ - c.itemCt = this.fieldTpl.append(target, args, true); + me.anim({width: {to: width}, height: {to: height}}, me.preanim(arguments, 2)); } - 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()); + return me; + }, + + + 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'); + } } - 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 - }); + return h; + }, + + + 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'); + } } - c.label = c.getItemCt().child('label.x-form-item-label'); - if(this.trackLabels && !this.isHide(c)){ - if(c.hidden){ - this.onFieldHide(c); + return w; + }, + + + getFrameWidth : function(sides, onlyContentBox){ + return onlyContentBox && this.isBorderBox() ? 0 : (this.getPadding(sides) + this.getBorderWidth(sides)); + }, + + + addClassOnOver : function(className){ + this.hover( + function(){ + Ext.fly(this, INTERNAL).addClass(className); + }, + function(){ + Ext.fly(this, INTERNAL).removeClass(className); } - c.on({ - scope: this, - show: this.onFieldShow, - hide: this.onFieldHide - }); + ); + return 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; + }, + + + 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; + }, + + + + getViewSize : function(){ + var doc = document, + d = this.dom, + isDoc = (d == doc || d == doc.body); + + + if (isDoc) { + var extdom = Ext.lib.Dom; + return { + width : extdom.getViewWidth(), + height : extdom.getViewHeight() + }; + + + } else { + return { + width : d.clientWidth, + height : d.clientHeight + }; + } + }, + + + + getStyleSize : function(){ + var me = this, + w, h, + doc = document, + d = this.dom, + isDoc = (d == doc || d == doc.body), + s = d.style; + + + if (isDoc) { + var extdom = Ext.lib.Dom; + return { + width : extdom.getViewWidth(), + height : extdom.getViewHeight() + }; + } + + if(s.width && s.width != 'auto'){ + w = parseFloat(s.width); + if(me.isBorderBox()){ + w -= me.getFrameWidth('lr'); + } + } + + if(s.height && s.height != 'auto'){ + h = parseFloat(s.height); + if(me.isBorderBox()){ + h -= me.getFrameWidth('tb'); + } + } + + return {width: w || me.getWidth(true), height: h || me.getHeight(true)}; + }, + + + getSize : function(contentSize){ + return {width: this.getWidth(contentSize), height: this.getHeight(contentSize)}; + }, + + + repaint : function(){ + var dom = this.dom; + this.addClass("x-repaint"); + setTimeout(function(){ + Ext.fly(dom).removeClass("x-repaint"); + }, 1); + return this; + }, + + + unselectable : function(){ + this.dom.unselectable = "on"; + return this.swallowEvent("selectstart", true). + applyStyles("-moz-user-select:none;-khtml-user-select:none;"). + addClass("x-unselectable"); + }, + + + 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); } - this.configureItem(c); - }else { - Ext.layout.FormLayout.superclass.renderItem.apply(this, arguments); } - }, + }; +}()); - /** - *

Provides template arguments for rendering the fully wrapped, labeled and styled form Field.

- *

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:

    - *
  • itemCls : String
    The CSS class applied to the outermost div wrapper - * that contains this field label and field element (the default class is 'x-form-item' and itemCls - * will be added to that). If supplied, itemCls at the field level will override the default itemCls - * supplied at the container level.
  • - *
  • id : String
    The id of the Field
  • - *
  • {@link #labelStyle} : String
    - * A CSS style specification string to add to the field label for this field (defaults to '' or the - * {@link #labelStyle layout's value for labelStyle}).
  • - *
  • label : String
    The text to display as the label for this - * field (defaults to '')
  • - *
  • {@link #labelSeparator} : String
    The separator to display after - * the text of the label for this field (defaults to a colon ':' or the - * {@link #labelSeparator layout's value for labelSeparator}). To hide the separator use empty string ''.
  • - *
  • elementStyle : String
    The styles text for the input element's wrapper.
  • - *
  • clearCls : String
    The CSS class to apply to the special clearing div - * rendered directly after each form field wrapper (defaults to 'x-form-clear-left')
  • - *
- * @param field The {@link Field Ext.form.Field} being rendered. - * @return 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, - labelStyle: this.getLabelStyle(field.labelStyle), - elementStyle: this.elementStyle||'', - labelSeparator: noLabelSep ? '' : (Ext.isDefined(field.labelSeparator) ? field.labelSeparator : this.labelSeparator), - itemCls: (field.itemCls||this.container.itemCls||'') + (field.hideLabel ? ' x-hide-label' : ''), - clearCls: field.clearCls || 'x-form-clear-left' - }; +Ext.Element.addMethods({ + + 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; }, - // 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); + + 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]; } - return value; + 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 : 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)); }, - adjustHeightAnchor : function(value, c){ - if(c.label && !this.isHide(c) && (this.container.labelAlign == 'top')){ - return value - c.label.getHeight(); + + setLeftTop : function(left, top){ + var me = this, + style = me.dom.style; + style.left = me.addUnits(left); + style.top = me.addUnits(top); + return me; + }, + + + getRegion : function(){ + return Ext.lib.Dom.getRegion(this.dom); + }, + + + 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 value; + return me; }, - // private - isValidParent : function(c, target){ - return target && this.container.getEl().contains(c.getDomPositionEl()); + + 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)); } +}); +Ext.Element.addMethods({ + + scrollTo : function(side, value, animate) { + + var top = /top/i.test(side), + me = this, + dom = me.dom, + prop; + if (!animate || !me.anim) { + + prop = 'scroll' + (top ? 'Top' : 'Left'); + dom[prop] = value; + } + else { + + prop = 'scroll' + (top ? 'Left' : 'Top'); + me.anim({scroll: {to: top ? [dom[prop], value] : [value, dom[prop]]}}, me.preanim(arguments, 2), 'scroll'); + } + return me; + }, + + + 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; - /** - * @property activeItem - * @hide - */ + if (el.offsetHeight > ch || t < ct) { + c.scrollTop = t; + } + else if (b > cb) { + c.scrollTop = b-ch; + } + + c.scrollTop = c.scrollTop; + + 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; + }, + + + scrollChildIntoView : function(child, hscroll) { + Ext.fly(child, '_scrollChildIntoView').scrollIntoView(this, hscroll); + }, + + + scroll : function(direction, distance, animate) { + if (!this.isScrollable()) { + return false; + } + 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; + } }); +Ext.Element.addMethods( + function() { + var VISIBILITY = "visibility", + DISPLAY = "display", + HIDDEN = "hidden", + NONE = "none", + XMASKED = "x-masked", + XMASKEDRELATIVE = "x-masked-relative", + data = Ext.Element.data; -Ext.Container.LAYOUTS['form'] = Ext.layout.FormLayout;/** - * @class Ext.layout.AccordionLayout - * @extends Ext.layout.FitLayout - *

This is a layout that manages multiple Panels in an expandable accordion style such that only - * one Panel can be expanded at any given time. Each Panel has built-in support for expanding and collapsing.

- *

Note: Only Ext.Panels and all subclasses of Ext.Panel may be used in an accordion layout Container.

- *

This class is intended to be extended or created via the {@link Ext.Container#layout layout} - * configuration property. See {@link Ext.Container#layout} for additional details.

- *

Example usage:

- *

-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: '<p>Panel content!</p>'
-    },{
-        title: 'Panel 2',
-        html: '<p>Panel content!</p>'
-    },{
-        title: 'Panel 3',
-        html: '<p>Panel content!</p>'
-    }]
-});
-
- */ -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 - * Experimental. 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. This is NOT compatible with "animate:true" (defaults to false). - */ - activeOnTop : false, - - 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.activeItem = c; - }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.activeItem = p; - if(this.activeOnTop){ - p.el.dom.parentNode.insertBefore(p.el.dom, p.el.dom.parentNode.firstChild); - } - this.layout(); - }, - - // private - setItemSize : function(item, size){ - if(this.fill && item){ - var hh = 0; - this.container.items.each(function(p){ - if(p != item){ - hh += p.header.getHeight(); - } - }); - size.height -= hh; - 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){ - item = this.container.getComponent(item); - if(this.activeItem != item){ - if(item.rendered && item.collapsed){ - item.expand(); - }else{ - this.activeItem = item; - } - } - - } -}); -Ext.Container.LAYOUTS.accordion = Ext.layout.AccordionLayout; - -//backwards compat -Ext.layout.Accordion = Ext.layout.AccordionLayout;/** - * @class Ext.layout.TableLayout - * @extends Ext.layout.ContainerLayout - *

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.

- *

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:

- *
    - *
  • rowspan Applied to the table cell containing the item.
  • - *
  • colspan Applied to the table cell containing the item.
  • - *
  • cellId An id applied to the table cell containing the item.
  • - *
  • cellCls A CSS class name added to the table cell containing the item.
  • - *
- *

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:

- *

-// 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: '<p>Cell A content</p>',
-        rowspan: 2
-    },{
-        html: '<p>Cell B content</p>',
-        colspan: 2
-    },{
-        html: '<p>Cell C content</p>',
-        cellCls: 'highlight'
-    },{
-        html: '<p>Cell D content</p>'
-    }]
-});
-
- */ -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, - - /** - * @cfg {Object} tableAttrs - *

An object containing properties which are added to the {@link Ext.DomHelper DomHelper} specification - * used to create the layout's <table> element. Example:


-{
-    xtype: 'panel',
-    layout: 'table',
-    layoutConfig: {
-        tableAttrs: {
-        	style: {
-        		width: '100%'
-        	}
-        },
-        columns: 3
-    }
-}
- */ - 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){ - 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.getDomPositionEl().dom, null); - c.container = Ext.get(container); - this.configureItem(c, position); - } - }, - - // private - isValidParent : function(c, target){ - return c.getDomPositionEl().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 - *

This is a layout that inherits the anchoring of {@link Ext.layout.AnchorLayout} and adds the - * ability for x/y positioning using the standard x and y component config options.

- *

This class is intended to be extended or created via the {@link Ext.Container#layout layout} - * configuration property. See {@link Ext.Container#layout} for additional details.

- *

Example usage:

- *

-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
-    }]
-});
-
- */ -Ext.layout.AbsoluteLayout = Ext.extend(Ext.layout.AnchorLayout, { - - extraCls: 'x-abs-layout-item', - - 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 - *

Base Class for HBoxLayout and VBoxLayout Classes. Generally it should not need to be used directly.

- */ -Ext.layout.BoxLayout = Ext.extend(Ext.layout.ContainerLayout, { - /** - * @cfg {Object} defaultMargins - *

If the individual contained items do not have a margins - * property specified, the default margins from this property will be - * applied to each item.

- *

This property may be specified as an object containing margins - * to apply in the format:


-{
-    top: (top margin),
-    right: (right margin),
-    bottom: (bottom margin),
-    left: (left margin)
-}
- *

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:

- *
    - *
  • If there is only one value, it applies to all sides.
  • - *
  • 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.
  • - *
  • 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.
  • - *
  • If there are four values, they apply to the top, right, bottom, and - * left, respectively.
  • - *
- *

Defaults to:


-     * {top:0, right:0, bottom:0, left:0}
-     * 
- */ - defaultMargins : {left:0,top:0,right:0,bottom:0}, - /** - * @cfg {String} padding - *

Sets the padding to be applied to all child items managed by this layout.

- *

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:

- *
    - *
  • If there is only one value, it applies to all sides.
  • - *
  • 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.
  • - *
  • 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.
  • - *
  • If there are four values, they apply to the top, right, bottom, and - * left, respectively.
  • - *
- *

Defaults to: "0"

- */ - padding : '0', - // documented in subclasses - pack : 'start', - - // private - monitorResize : true, - scrollOffset : 0, - extraCls : 'x-box-item', - ctCls : '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 - isValidParent : function(c, target){ - return c.getEl().dom.parentNode == this.innerCt.dom; - }, - - // private - onLayout : function(ct, target){ - var cs = ct.items.items, len = cs.length, c, i, last = len-1, cm; - - if(!this.innerCt){ - target.addClass(this.ctCls); - - // the innerCt prevents wrapping and shuffling while - // the container is resizing - this.innerCt = target.createChild({cls:this.innerCls}); - this.padding = this.parseMargins(this.padding); - } - this.renderAll(ct, this.innerCt); - }, - - // 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); - }, - - getTargetSize : function(target){ - return (Ext.isIE6 && Ext.isStrict && target.dom == document.body) ? target.getStyleSize() : target.getViewSize(); - }, - - getItems: function(ct){ - var items = []; - ct.items.each(function(c){ - if(c.isVisible()){ - items.push(c); - } - }); - return items; - } - - /** - * @property activeItem - * @hide - */ -}); - -/** - * @class Ext.layout.VBoxLayout - * @extends Ext.layout.BoxLayout - *

A layout that arranges items vertically down a Container. This layout optionally divides available vertical - * space between child items containing a numeric flex configuration.

- * 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: - *
    - *
  • left : Default
    child items are aligned horizontally - * at the left side of the container
  • - *
  • center :
    child items are aligned horizontally at the - * mid-width of the container
  • - *
  • stretch :
    child items are stretched horizontally to fill - * the width of the container
  • - *
  • stretchmax :
    child items are stretched horizontally to - * the size of the largest item.
  • - *
- */ - align : 'left', // left, center, stretch, strechmax - /** - * @cfg {String} pack - * Controls how the child items of the container are packed together. Acceptable configuration values - * for this property are: - *
    - *
  • start : Default
    child items are packed together at - * top side of container
  • - *
  • center :
    child items are packed together at - * mid-height of container
  • - *
  • end :
    child items are packed together at bottom - * side of container
  • - *
- */ - /** - * @cfg {Number} flex - * This configuation option is to be applied to child items of the container managed - * by this layout. Each child item with a flex property will be flexed vertically - * according to each item's relative flex value compared to the sum of all items with - * a flex value specified. Any child items that have either a flex = 0 or - * flex = undefined will not be 'flexed' (the initial size will not be changed). - */ - - // private - onLayout : function(ct, target){ - Ext.layout.VBoxLayout.superclass.onLayout.call(this, ct, target); - - - var cs = this.getItems(ct), cm, ch, margin, - size = this.getTargetSize(target), - w = size.width - target.getPadding('lr'), - h = size.height - target.getPadding('tb') - this.scrollOffset, - l = this.padding.left, t = this.padding.top, - isStart = this.pack == 'start', - isRestore = ['stretch', 'stretchmax'].indexOf(this.align) == -1, - stretchWidth = w - (this.padding.left + this.padding.right), - extraHeight = 0, - maxWidth = 0, - totalFlex = 0, - flexHeight = 0, - usedHeight = 0; - - Ext.each(cs, function(c){ - cm = c.margins; - totalFlex += c.flex || 0; - ch = c.getHeight(); - margin = cm.top + cm.bottom; - extraHeight += ch + margin; - flexHeight += margin + (c.flex ? 0 : ch); - maxWidth = Math.max(maxWidth, c.getWidth() + cm.left + cm.right); - }); - extraHeight = h - extraHeight - this.padding.top - this.padding.bottom; - - var innerCtWidth = maxWidth + this.padding.left + this.padding.right; - switch(this.align){ - case 'stretch': - this.innerCt.setSize(w, h); - break; - case 'stretchmax': - case 'left': - this.innerCt.setSize(innerCtWidth, h); - break; - case 'center': - this.innerCt.setSize(w = Math.max(w, innerCtWidth), h); - break; - } - - var availHeight = Math.max(0, h - this.padding.top - this.padding.bottom - flexHeight), - leftOver = availHeight, - heights = [], - restore = [], - idx = 0, - availableWidth = Math.max(0, w - this.padding.left - this.padding.right); - - - Ext.each(cs, function(c){ - if(isStart && c.flex){ - ch = Math.floor(availHeight * (c.flex / totalFlex)); - leftOver -= ch; - heights.push(ch); - } - }); - - if(this.pack == 'center'){ - t += extraHeight ? extraHeight / 2 : 0; - }else if(this.pack == 'end'){ - t += extraHeight; - } - Ext.each(cs, function(c){ - cm = c.margins; - t += cm.top; - c.setPosition(l + cm.left, t); - if(isStart && c.flex){ - ch = Math.max(0, heights[idx++] + (leftOver-- > 0 ? 1 : 0)); - if(isRestore){ - restore.push(c.getWidth()); - } - c.setSize(availableWidth, ch); - }else{ - ch = c.getHeight(); - } - t += ch + cm.bottom; - }); - - idx = 0; - Ext.each(cs, function(c){ - cm = c.margins; - if(this.align == 'stretch'){ - c.setWidth((stretchWidth - (cm.left + cm.right)).constrain( - c.minWidth || 0, c.maxWidth || 1000000)); - }else if(this.align == 'stretchmax'){ - c.setWidth((maxWidth - (cm.left + cm.right)).constrain( - c.minWidth || 0, c.maxWidth || 1000000)); - }else{ - if(this.align == 'center'){ - var diff = availableWidth - (c.getWidth() + cm.left + cm.right); - if(diff > 0){ - c.setPosition(l + cm.left + (diff/2), c.y); - } - } - if(isStart && c.flex){ - c.setWidth(restore[idx++]); - } - } - }, this); - } - /** - * @property activeItem - * @hide - */ -}); - -Ext.Container.LAYOUTS.vbox = Ext.layout.VBoxLayout; - -/** - * @class Ext.layout.HBoxLayout - * @extends Ext.layout.BoxLayout - *

A layout that arranges items horizontally across a Container. This layout optionally divides available horizontal - * space between child items containing a numeric flex configuration.

- * 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: - *
    - *
  • top : Default
    child items are aligned vertically - * at the left side of the container
  • - *
  • middle :
    child items are aligned vertically at the - * mid-height of the container
  • - *
  • stretch :
    child items are stretched vertically to fill - * the height of the container
  • - *
  • stretchmax :
    child items are stretched vertically to - * the size of the largest item.
  • - */ - align : 'top', // top, middle, stretch, strechmax - /** - * @cfg {String} pack - * Controls how the child items of the container are packed together. Acceptable configuration values - * for this property are: - *
      - *
    • start : Default
      child items are packed together at - * left side of container
    • - *
    • center :
      child items are packed together at - * mid-width of container
    • - *
    • end :
      child items are packed together at right - * side of container
    • - *
    - */ - /** - * @cfg {Number} flex - * This configuation option is to be applied to child items of the container managed - * by this layout. Each child item with a flex property will be flexed horizontally - * according to each item's relative flex value compared to the sum of all items with - * a flex value specified. Any child items that have either a flex = 0 or - * flex = undefined will not be 'flexed' (the initial size will not be changed). - */ - - // private - onLayout : function(ct, target){ - Ext.layout.HBoxLayout.superclass.onLayout.call(this, ct, target); - - var cs = this.getItems(ct), cm, cw, margin, - size = this.getTargetSize(target), - w = size.width - target.getPadding('lr') - this.scrollOffset, - h = size.height - target.getPadding('tb'), - l = this.padding.left, t = this.padding.top, - isStart = this.pack == 'start', - isRestore = ['stretch', 'stretchmax'].indexOf(this.align) == -1, - stretchHeight = h - (this.padding.top + this.padding.bottom), - extraWidth = 0, - maxHeight = 0, - totalFlex = 0, - flexWidth = 0, - usedWidth = 0; - - Ext.each(cs, function(c){ - cm = c.margins; - totalFlex += c.flex || 0; - cw = c.getWidth(); - margin = cm.left + cm.right; - extraWidth += cw + margin; - flexWidth += margin + (c.flex ? 0 : cw); - maxHeight = Math.max(maxHeight, c.getHeight() + cm.top + cm.bottom); - }); - extraWidth = w - extraWidth - this.padding.left - this.padding.right; - - var innerCtHeight = maxHeight + this.padding.top + this.padding.bottom; - switch(this.align){ - case 'stretch': - this.innerCt.setSize(w, h); - break; - case 'stretchmax': - case 'top': - this.innerCt.setSize(w, innerCtHeight); - break; - case 'middle': - this.innerCt.setSize(w, h = Math.max(h, innerCtHeight)); - break; - } - - - var availWidth = Math.max(0, w - this.padding.left - this.padding.right - flexWidth), - leftOver = availWidth, - widths = [], - restore = [], - idx = 0, - availableHeight = Math.max(0, h - this.padding.top - this.padding.bottom); - - - Ext.each(cs, function(c){ - if(isStart && c.flex){ - cw = Math.floor(availWidth * (c.flex / totalFlex)); - leftOver -= cw; - widths.push(cw); - } - }); - - if(this.pack == 'center'){ - l += extraWidth ? extraWidth / 2 : 0; - }else if(this.pack == 'end'){ - l += extraWidth; - } - Ext.each(cs, function(c){ - cm = c.margins; - l += cm.left; - c.setPosition(l, t + cm.top); - if(isStart && c.flex){ - cw = Math.max(0, widths[idx++] + (leftOver-- > 0 ? 1 : 0)); - if(isRestore){ - restore.push(c.getHeight()); - } - c.setSize(cw, availableHeight); - }else{ - cw = c.getWidth(); - } - l += cw + cm.right; - }); - - idx = 0; - Ext.each(cs, function(c){ - var cm = c.margins; - if(this.align == 'stretch'){ - c.setHeight((stretchHeight - (cm.top + cm.bottom)).constrain( - c.minHeight || 0, c.maxHeight || 1000000)); - }else if(this.align == 'stretchmax'){ - c.setHeight((maxHeight - (cm.top + cm.bottom)).constrain( - c.minHeight || 0, c.maxHeight || 1000000)); - }else{ - if(this.align == 'middle'){ - var diff = availableHeight - (c.getHeight() + cm.top + cm.bottom); - if(diff > 0){ - c.setPosition(c.x, t + cm.top + (diff/2)); - } - } - if(isStart && c.flex){ - c.setHeight(restore[idx++]); - } - } - }, this); - } - - /** - * @property activeItem - * @hide - */ -}); - -Ext.Container.LAYOUTS.hbox = Ext.layout.HBoxLayout; -/** - * @class Ext.Viewport - * @extends Ext.Container - *

    A specialized container representing the viewable application area (the browser viewport).

    - *

    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.

    - *

    The Viewport does not provide scrolling, so child Panels within the Viewport should provide - * for scrolling if needed using the {@link #autoScroll} config.

    - *

    An example showing a classic application border layout:

    
    -new Ext.Viewport({
    -    layout: 'border',
    -    items: [{
    -        region: 'north',
    -        html: '<h1 class="x-panel-header">Page Title</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'
    -        }
    -    }]
    -});
    -
    - * @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 - *

    Panel is a container that has specific functionality and structural components that make - * it the perfect building block for application-oriented user interfaces.

    - *

    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.

    - *

    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 {@link Ext.Container#layout layout} 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 does not apply any sizing - * at all.

    - *

    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).

    - *

    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}.

    - * @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. - *

    This Element is used to house the {@link #title} and {@link #tools}

    - *

    Note: see the Note for {@link Ext.Component#el el} also.

    - * @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. - *

    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.

    - *

    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. - *

    Note: see the Note for {@link Ext.Component#el el} also.

    - * @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 - *

    A {@link Ext.DomHelper DomHelper} element specification object may be specified for any - * Panel Element.

    - *

    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 (baseCls will be - * replaced by {@link #baseCls}):

    - *
    -     * 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
    -     * 
    - *

    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 <center> - * element:

    - *
    
    -new Ext.Panel({
    -    title: 'Message Title',
    -    renderTo: Ext.getBody(),
    -    width: 200, height: 130,
    -    bodyCfg: {
    -        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}
    -});
    -     * 
    - *

    The example above also explicitly creates a {@link #footer} with custom markup and - * styling applied.

    - */ - /** - * @cfg {Object} headerCfg - *

    A {@link Ext.DomHelper DomHelper} element specification object specifying the element structure - * of this Panel's {@link #header} Element. See {@link #bodyCfg} also.

    - */ - /** - * @cfg {Object} bwrapCfg - *

    A {@link Ext.DomHelper DomHelper} element specification object specifying the element structure - * of this Panel's {@link #bwrap} Element. See {@link #bodyCfg} also.

    - */ - /** - * @cfg {Object} tbarCfg - *

    A {@link Ext.DomHelper DomHelper} element specification object specifying the element structure - * of this Panel's {@link #tbar} Element. See {@link #bodyCfg} also.

    - */ - /** - * @cfg {Object} bbarCfg - *

    A {@link Ext.DomHelper DomHelper} element specification object specifying the element structure - * of this Panel's {@link #bbar} Element. See {@link #bodyCfg} also.

    - */ - /** - * @cfg {Object} footerCfg - *

    A {@link Ext.DomHelper DomHelper} element specification object specifying the element structure - * of this Panel's {@link #footer} Element. See {@link #bodyCfg} also.

    - */ - /** - * @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 true - * to enable closing in such situations. Defaults to false. - */ - /** - * The Panel's footer {@link Ext.Element Element}. Read-only. - *

    This Element is used to house the Panel's {@link #buttons} or {@link #fbar}.

    - *

    Note: see the Note for {@link Ext.Component#el el} also.

    - * @type Ext.Element - * @property footer - */ - /** - * @cfg {Mixed} applyTo - *

    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 applyTo 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.

    - *

    The following class names are supported (baseCls will be replaced by {@link #baseCls}):

    - *
    • baseCls + '-header'
    • - *
    • baseCls + '-header-text'
    • - *
    • baseCls + '-bwrap'
    • - *
    • baseCls + '-tbar'
    • - *
    • baseCls + '-body'
    • - *
    • baseCls + '-bbar'
    • - *
    • baseCls + '-footer'
    - *

    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.

    - */ - /** - * @cfg {Object/Array} tbar - *

    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}.

    - *

    Note: Although a Toolbar may contain Field components, these will not 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 will be submitted because form - * submission parameters are collected from the DOM tree.

    - */ - /** - * @cfg {Object/Array} bbar - *

    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}.

    - *

    Note: Although a Toolbar may contain Field components, these will not 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 will be submitted because form - * submission parameters are collected from the DOM tree.

    - */ - /** @cfg {Object/Array} fbar - *

    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.

    - *

    After render, the fbar property will be an {@link Ext.Toolbar Toolbar} instance.

    - *

    If {@link #buttons} are specified, they will supersede the fbar configuration property.

    - * The Panel's {@link #buttonAlign} configuration affects the layout of these items, for example: - *
    
    -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();
    -     * 
    - *

    Note: Although a Toolbar may contain Field components, these will not 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 will be submitted because form - * submission parameters are collected from the DOM tree.

    - */ - /** - * @cfg {Boolean} header - * true to create the Panel's header element explicitly, false to skip creating - * it. If a {@link #title} is set the header will be created automatically, otherwise it will not. - * If a {@link #title} is set but header is explicitly set to false, the header - * will not be rendered. - */ - /** - * @cfg {Boolean} footer - * true to create the footer element explicitly, false to skip creating it. The footer - * will be created automatically if {@link #buttons} or a {@link #fbar} have - * been configured. See {@link #bodyCfg} for an example. - */ - /** - * @cfg {String} title - * The title text to be used as innerHTML (html tags are accepted) to display in the panel - * {@link #header} (defaults to ''). When a title is specified the - * {@link #header} element will automatically be created and displayed unless - * {@link #header} is explicitly set to false. If you do not want to specify a - * title at config time, but you may want one later, you must either specify a non-empty - * title (a blank space ' ' will do) or header:true so that the container - * element will get created. - */ - /** - * @cfg {Array} buttons - * buttons will be used as {@link Ext.Container#items items} for the toolbar in - * the footer ({@link #fbar}). 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 minWidth or the Panel is configured with minButtonWidth, - * 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.

    - * 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.

    - */ - /** - * @cfg {Boolean} frame - * false by default to render with plain 1px square borders. true to render with - * 9 elements, complete with custom rounded corners (also see {@link Ext.Element#boxWrap}). - *

    The template generated for each condition is depicted below:

    
    -     *
    -// frame = false
    -<div id="developer-specified-id-goes-here" class="x-panel">
    -
    -    <div class="x-panel-header"><span class="x-panel-header-text">Title: (frame:false)</span></div>
    -
    -    <div class="x-panel-bwrap">
    -        <div class="x-panel-body"><p>html value goes here</p></div>
    -    </div>
    -</div>
    -
    -// frame = true (create 9 elements)
    -<div id="developer-specified-id-goes-here" class="x-panel">
    -    <div class="x-panel-tl"><div class="x-panel-tr"><div class="x-panel-tc">
    -        <div class="x-panel-header"><span class="x-panel-header-text">Title: (frame:true)</span></div>
    -    </div></div></div>
    -
    -    <div class="x-panel-bwrap">
    -        <div class="x-panel-ml"><div class="x-panel-mr"><div class="x-panel-mc">
    -            <div class="x-panel-body"><p>html value goes here</p></div>
    -        </div></div></div>
    -
    -        <div class="x-panel-bl"><div class="x-panel-br"><div class="x-panel-bc"/>
    -        </div></div></div>
    -</div>
    -     * 
    - */ - /** - * @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 ''). - *

    An example of specifying a custom icon class would be something like: - *

    
    -// 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; }
    -
    - */ - /** - * @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 tools.<tool-type> - *

    Each tool config may contain the following properties: - *

      - *
    • id : String
      Required. The type - * of tool to create. By default, this assigns a CSS class of the form x-tool-<tool-type> 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: - *
        - *
        toggle (Created by default when {@link #collapsible} is true)
        - *
        close
        - *
        minimize
        - *
        maximize
        - *
        restore
        - *
        gear
        - *
        pin
        - *
        unpin
        - *
        right
        - *
        left
        - *
        up
        - *
        down
        - *
        refresh
        - *
        minus
        - *
        plus
        - *
        help
        - *
        search
        - *
        save
        - *
        print
        - *
    • - *
    • handler : Function
      Required. The function to - * call when clicked. Arguments passed are:
        - *
      • event : Ext.EventObject
        The click event.
      • - *
      • toolEl : Ext.Element
        The tool Element.
      • - *
      • panel : Ext.Panel
        The host Panel
      • - *
      • tc : Ext.Panel
        The tool configuration object
      • - *
    • - *
    • stopEvent : Boolean
      Defaults to true. Specify as false to allow click event to propagate.
    • - *
    • scope : Object
      The scope in which to call the handler.
    • - *
    • qtip : String/Object
      A tip string, or - * a config argument to {@link Ext.QuickTip#register}
    • - *
    • hidden : Boolean
      True to initially render hidden.
    • - *
    • on : Object
      A listener config object specifiying - * event listeners in the format of an argument to {@link #addListener}
    • - *
    - *

    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.

    - *

    Example usage:

    - *
    
    -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
    -    }
    -}]
    -
    - *

    For the custom id of 'help' define two relevant css classes with a link to - * a 15x15 image:

    - *
    
    -.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;}
    -
    - */ - /** - * @cfg {Ext.Template/Ext.XTemplate} toolTemplate - *

    A Template used to create {@link #tools} in the {@link #header} Element. Defaults to:

    
    -new Ext.Template('<div class="x-tool x-tool-{id}">&#160;</div>')
    - *

    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 <a> tag is used to provide a - * visual indication when hovering over the tool:

    
    -var win = new Ext.Window({
    -    tools: [{
    -        id: 'download',
    -        href: '/MyPdfDoc.pdf'
    -    }],
    -    toolTemplate: new Ext.XTemplate(
    -        '<tpl if="id==\'download\'">',
    -            '<a class="x-tool x-tool-pdf" href="{href}"></a>',
    -        '</tpl>',
    -        '<tpl if="id!=\'download\'">',
    -            '<div class="x-tool x-tool-{id}">&#160;</div>',
    -        '</tpl>'
    -    ),
    -    width:500,
    -    height:300,
    -    closeAction:'hide'
    -});
    - *

    Note that the CSS class 'x-tool-pdf' should have an associated style rule which provides an - * appropriate background image, something like:

    -
    
    -    a.x-tool-pdf {background-image: url(../shared/extjs/images/pdf.gif)!important;}
    -    
    - */ - /** - * @cfg {Boolean} hideCollapseTool - * true to hide the expand/collapse toggle button when {@link #collapsible} == true, - * false to display it (defaults to false). - */ - /** - * @cfg {Boolean} titleCollapse - * true to allow expanding and collapsing the panel (when {@link #collapsible} = true) - * by clicking anywhere in the header bar, false) to allow it only by clicking to tool button - * (defaults to false)). If this panel is a child item of a border layout also see the - * {@link Ext.layout.BorderLayout.Region BorderLayout.Region} - * {@link Ext.layout.BorderLayout.Region#floatable floatable} config option. - */ - /** - * @cfg {Boolean} autoScroll - * true to use overflow:'auto' on the panel's body element and show scroll bars automatically when - * necessary, false to clip any overflowing content (defaults to false). - */ - /** - * @cfg {Mixed} floating - *

    This property is used to configure the underlying {@link Ext.Layer}. Acceptable values for this - * configuration property are:

      - *
    • false : Default.
      Display the panel inline where it is - * rendered.
    • - *
    • true :
      Float the panel (absolute position it with automatic - * shimming and shadow).
        - *
        Setting floating to true will create an Ext.Layer for this panel and display the - * panel at negative offsets so that it is hidden.
        - *
        Since the panel will be absolute positioned, the position must be set explicitly - * after render (e.g., myPanel.setPosition(100,100);).
        - *
        Note: 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.
        - *
    • - *
    • {@link Ext.Layer object} :
      The specified object will be used - * as the configuration object for the {@link Ext.Layer} that will be created.
    • - *
    - */ - /** - * @cfg {Boolean/String} shadow - * true (or a valid Ext.Shadow {@link Ext.Shadow#mode} value) to display a shadow behind the - * panel, false to display no shadow (defaults to 'sides'). Note that this option - * only applies when {@link #floating} = true. - */ - /** - * @cfg {Number} shadowOffset - * The number of pixels to offset the shadow if displayed (defaults to 4). Note that this - * option only applies when {@link #floating} = true. - */ - /** - * @cfg {Boolean} shim - * false to disable the iframe shim in browsers which need one (defaults to true). - * Note that this option only applies when {@link #floating} = true. - */ - /** - * @cfg {String/Object} html - * An HTML fragment, or a {@link Ext.DomHelper DomHelper} specification to use as the panel's body - * content (defaults to ''). The HTML content is added by the Panel's {@link #afterRender} method, - * and so the document will not contain this HTML at the time the {@link #render} event is fired. - * This content is inserted into the body before any configured {@link #contentEl} is appended. - */ - /** - * @cfg {String} contentEl - *

    Optional. Specify an existing HTML element, or the id of an existing HTML element to use as this Panel's - * {@link #body} content.

    - *
      - *
    • Description : - *
      This config option is used to take an existing HTML element and place it in the body - * of a new panel (it simply moves the specified DOM element into the body element of the Panel - * after the Panel is rendered to use as the content (it is not going to be the actual panel itself).
    • - *
    • Notes : - *
      The specified HTML element is appended to the Panel's {@link #body} Element by the - * Panel's afterRender method after any configured {@link #html HTML} has - * been inserted, and so the document will not contain this element at the time the - * {@link #render} event is fired.
      - *
      The specified HTML element used will not participate in any {@link Ext.Container#layout layout} - * scheme that the Panel may use. It is just HTML. Layouts operate on child {@link Ext.Container#items items}.
      - *
      Add either the x-hidden or the x-hide-display CSS class to - * prevent a brief flicker of the content before it is rendered to the panel.
    • - *
    - */ - /** - * @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 null). - */ - /** - * @cfg {Boolean/Object} draggable - *

    true to enable dragging of this Panel (defaults to false).

    - *

    For custom drag/drop implementations, an Ext.Panel.DD config could also be passed - * in this config instead of true. 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.: - *

    
    -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'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());
    -            }
    -        },
    +        return {
    +            
    +            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;
    +            },
     
    -//      Called on the mouseup event.
    -        endDrag : function(e){
    -            this.panel.setPosition(this.x, this.y);
    -        }
    -    }
    -}).show();
    -
    - */ - /** - * @cfg {Boolean} disabled - * Render this panel disabled (default is false). 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: - *
    
    -new Ext.Panel({
    -    ...
    -    listeners: {
    -        'afterlayout': {
    -            fn: function(p){
    -                p.disable();
    +            
    +            isDisplayed : function() {
    +                return !this.isStyle(DISPLAY, NONE);
    +            },
    +
    +            
    +            enableDisplayMode : function(display) {
    +                this.setVisibilityMode(Ext.Element.DISPLAY);
    +                
    +                if (!Ext.isEmpty(display)) {
    +                    data(this.dom, 'originalDisplay', display);
    +                }
    +                
    +                return this;
    +            },
    +
    +            
    +            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') {
    +                    mask.setSize(undefined, me.getHeight());
    +                }
    +                
    +                return 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]);
    +                }
                 },
    -            single: true // important, as many layouts can occur
    +
    +            
    +            isMasked : function() {
    +                var m = data(this.dom, 'mask');
    +                return m && m.isVisible();
    +            },
    +
    +            
    +            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;
    +            }
    +        };
    +    }()
    +);
    +Ext.Element.addMethods({
    +    
    +    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);
    +    },
    +
    +    
    +    addKeyMap : function(config){
    +        return new Ext.KeyMap(this, config);
         }
     });
    -
    - */ - /** - * @cfg {Boolean} autoHeight - * true to use height:'auto', false to use fixed height (defaults to false). - * Note: Setting autoHeight: true 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 (fit, border, etc.) then setting autoHeight: true - * 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 'x-panel'). - *

    Another option available by default is to specify 'x-plain' which strips all styling - * except for required attributes for Ext layouts to function (e.g. overflow:hidden). - * See {@link #unstyled} also.

    - */ - baseCls : 'x-panel', - /** - * @cfg {String} collapsedCls - * A CSS class to add to the panel's element after it has been collapsed (defaults to - * 'x-panel-collapsed'). - */ - collapsedCls : 'x-panel-collapsed', - /** - * @cfg {Boolean} maskDisabled - * true to mask the panel when it is {@link #disabled}, false to not mask it (defaults - * to true). 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 - * true to animate the transition when the panel is collapsed, false to skip the - * animation (defaults to true if the {@link Ext.Fx} class is available, otherwise false). - */ - animCollapse : Ext.enableFx, - /** - * @cfg {Boolean} headerAsText - * true to display the panel {@link #title} in the {@link #header}, - * false to hide it (defaults to true). - */ - headerAsText : true, - /** - * @cfg {String} buttonAlign - * The alignment of any {@link #buttons} added to this panel. Valid values are 'right', - * 'left' and 'center' (defaults to 'right'). - */ - buttonAlign : 'right', - /** - * @cfg {Boolean} collapsed - * true to render the panel collapsed, false to render it expanded (defaults to - * false). - */ - collapsed : 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 panel's title bar, false to render it last (defaults to true). - */ - collapseFirst : true, - /** - * @cfg {Number} minButtonWidth - * Minimum width in pixels of all {@link #buttons} in this panel (defaults to 75) - */ - minButtonWidth : 75, - /** - * @cfg {Boolean} unstyled - * Overrides the {@link #baseCls} setting to {@link #baseCls} = 'x-plain' 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
      - *
    • header
    • - *
    • tbar (top bar)
    • - *
    • body
    • - *
    • bbar (bottom bar)
    • - *
    • footer
    • - *
    - * Defaults to 'body'. - */ - elements : 'body', - /** - * @cfg {Boolean} preventBodyReset - * Defaults to false. When set to true, an extra css class 'x-panel-normal' - * 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 body element (not the header, - * footer, etc.). - */ - preventBodyReset : false, - - /** @cfg {String} resizeEvent - * The event to listen to for resizing in layouts. Defaults to 'bodyresize'. - */ - 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 : '', +Ext.CompositeElementLite.importElementMethods(); +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; + }, - // private, notify box this class will handle heights - deferHeight : true, - // private - expandDefaults: { - duration : 0.25 + + first : function(){ + return this.item(0); }, - // private - collapseDefaults : { - duration : 0.25 + + + last : function(){ + return this.item(this.getCount()-1); }, - // private - initComponent : function(){ - Ext.Panel.superclass.initComponent.call(this); + + contains : function(el){ + return this.indexOf(el) != -1; + }, - 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's new width. - * @param {Number} height The Panel'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' - ); + + 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; + } +}); - if(this.unstyled){ - this.baseCls = 'x-plain'; - } +Ext.CompositeElement = Ext.extend(Ext.CompositeElementLite, { + + constructor : function(els, root){ + this.elements = []; + this.add(els, root); + }, + + + getElement : function(el){ + + return el; + }, + + + transformElement : function(el){ + return Ext.get(el); + } - // shortcuts - if(this.tbar){ - this.elements += ',tbar'; - if(Ext.isObject(this.tbar)){ - this.topToolbar = this.tbar; - } - delete this.tbar; - } - if(this.bbar){ - this.elements += ',bbar'; - if(Ext.isObject(this.bbar)){ - this.bottomToolbar = this.bbar; - } - delete this.bbar; - } + - if(this.header === true){ - this.elements += ',header'; - delete this.header; - }else if(this.headerCfg || (this.title && this.header !== false)){ - this.elements += ',header'; - } + - if(this.footerCfg || this.footer === true){ - this.elements += ',footer'; - delete this.footer; - } + +}); - if(this.buttons){ - this.elements += ',footer'; - var btns = this.buttons; - /** - * This Panel's Array of buttons as created from the {@link #buttons} - * config property. Read only. - * @type Array - * @property buttons - */ - this.buttons = []; - Ext.each(btns, function(btn){ - if(btn.render){ // button instance - this.buttons.push(btn); - }else if(btn.xtype){ - this.buttons.push(Ext.create(btn, 'button')); - }else{ - this.addButton(btn); - } - }, this); - } - if(this.fbar){ - this.elements += ',footer'; + +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); +}; + + +Ext.select = Ext.Element.select; +Ext.UpdateManager = Ext.Updater = Ext.extend(Ext.util.Observable, +function() { + var BEFOREUPDATE = "beforeupdate", + UPDATE = "update", + FAILURE = "failure"; + + + function processSuccess(response){ + var me = this; + me.transaction = null; + if (response.argument.form && response.argument.reset) { + try { + response.argument.form.reset(); + } catch(e){} } - if(this.autoLoad){ - this.on('render', this.doAutoLoad, this, {delay:10}); + 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 - createElement : function(name, pnode){ - if(this[name]){ - pnode.appendChild(this[name].dom); - return; + + 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); } + } - 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']); + + 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; } - } - }, + + me.el = el; + + me.defaultUrl = null; - // private - onRender : function(ct, position){ - Ext.Panel.superclass.onRender.call(this, ct, position); - this.createClasses(); + me.addEvents( + + BEFOREUPDATE, + + UPDATE, + + FAILURE + ); - var el = this.el, - d = el.dom, - bw, - ts; + Ext.apply(me, Ext.Updater.defaults); + + + - 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'; - } + + me.transaction = null; + + me.refreshDelegate = me.refresh.createDelegate(me); + + me.updateDelegate = me.update.createDelegate(me); + + me.formUpdateDelegate = (me.formUpdate || function(){}).createDelegate(me); - // This block allows for maximum flexibility and performance when using existing markup + + me.renderer = me.renderer || me.getDefaultRenderer(); - // framing requires special markup - if(this.frame){ - el.insertHtml('afterBegin', String.format(Ext.Element.boxMarkup, this.baseCls)); + Ext.Updater.superclass.constructor.call(me); + }, - this.createElement('header', d.firstChild.firstChild.firstChild); - this.createElement('bwrap', d); + + setRenderer : function(renderer){ + this.renderer = renderer; + }, - // 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); + + getRenderer : function(){ + return this.renderer; + }, - 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); + + getDefaultRenderer: function() { + return new Ext.Updater.BasicRenderer(); + }, - 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(this.bwrap.dom.firstChild.firstChild.firstChild); - }else{ - this.createElement('header', d); - this.createElement('bwrap', d); + + setDefaultUrl : function(defaultUrl){ + this.defaultUrl = defaultUrl; + }, - // 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); + + getEl : function(){ + return this.el; + }, - if(!this.header){ - this.body.addClass(this.bodyCls + '-noheader'); - if(this.tbar){ - this.tbar.addClass(this.tbarCls + '-noheader'); + + update : function(url, params, callback, discardUrl){ + var me = this, + cfg, + callerScope; + + if(me.fireEvent(BEFOREUPDATE, me.el, url, params) !== false){ + if(Ext.isObject(url)){ + 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 = '
    '+cfg.text+"
    ";}; + if(!Ext.isEmpty(cfg.scripts)){me.loadScripts = cfg.scripts;}; + if(!Ext.isEmpty(cfg.timeout)){me.timeout = cfg.timeout;}; } - } - } + me.showLoading(); - if(Ext.isDefined(this.padding)){ - this.body.setStyle('padding', this.body.addUnits(this.padding)); - } + if(!discardUrl){ + me.defaultUrl = url; + } + if(Ext.isFunction(url)){ + url = url.call(me); + } - 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'); + 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); } - if(this.footer){ - this.footer.addClass(this.footerCls + '-noborder'); + }, + + + 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); } - if(this.tbar){ - this.tbar.addClass(this.tbarCls + '-noborder'); + }, + + + startAutoRefresh : function(interval, url, params, callback, refreshNow){ + var me = this; + if(refreshNow){ + me.update(url || me.defaultUrl, params, callback, true); } - if(this.bbar){ - this.bbar.addClass(this.bbarCls + '-noborder'); + if(me.autoRefreshProcId){ + clearInterval(me.autoRefreshProcId); } - } + me.autoRefreshProcId = setInterval(me.update.createDelegate(me, [url || me.defaultUrl, params, callback, true]), interval * 1000); + }, - if(this.bodyBorder === false){ - this.body.addClass(this.bodyCls + '-noborder'); - } + + stopAutoRefresh : function(){ + if(this.autoRefreshProcId){ + clearInterval(this.autoRefreshProcId); + delete this.autoRefreshProcId; + } + }, - this.bwrap.enableDisplayMode('block'); + + isAutoRefreshing : function(){ + return !!this.autoRefreshProcId; + }, - if(this.header){ - this.header.unselectable(); + + showLoading : function(){ + if(this.showLoadIndicator){ + this.el.dom.innerHTML = this.indicatorText; + } + }, - // for tools, we need to wrap any existing header markup - if(this.headerAsText){ - this.header.dom.innerHTML = - ''+this.header.dom.innerHTML+''; + + abort : function(){ + if(this.transaction){ + Ext.Ajax.abort(this.transaction); + } + }, - if(this.iconCls){ - this.setIconClass(this.iconCls); - } + + isUpdating : function(){ + return this.transaction ? Ext.Ajax.isLoading(this.transaction) : false; + }, + + + refresh : function(callback){ + if(this.defaultUrl){ + this.update(this.defaultUrl, null, callback, true); } } + }; +}()); - 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); - } +Ext.Updater.defaults = { + + timeout : 30, + + disableCaching : false, + + showLoadIndicator : true, + + indicatorText : '
    Loading...
    ', + + loadScripts : false, + + sslBlankUrl : Ext.SSL_SECURE_URL +}; - if(this.buttons && this.buttons.length > 0){ - this.fbar = new Ext.Toolbar({ - items: this.buttons, - toolbarCls: 'x-panel-fbar' - }); - } - this.toolbars = []; - if(this.fbar){ - this.fbar = Ext.create(this.fbar, 'toolbar'); - this.fbar.enableOverflow = false; - if(this.fbar.items){ - this.fbar.items.each(function(c){ - c.minWidth = c.minWidth || this.minButtonWidth; - }, this); - } - this.fbar.toolbarCls = 'x-panel-fbar'; - var bct = this.footer.createChild({cls: 'x-panel-btns x-panel-btns-'+this.buttonAlign}); - this.fbar.ownerCt = this; - this.fbar.render(bct); - bct.createChild({cls:'x-clear'}); - this.toolbars.push(this.fbar); - } - if(this.tbar && this.topToolbar){ - if(Ext.isArray(this.topToolbar)){ - this.topToolbar = new Ext.Toolbar(this.topToolbar); - }else if(!this.topToolbar.events){ - this.topToolbar = Ext.create(this.topToolbar, 'toolbar'); - } - this.topToolbar.ownerCt = this; - this.topToolbar.render(this.tbar); - this.toolbars.push(this.topToolbar); - } - if(this.bbar && this.bottomToolbar){ - if(Ext.isArray(this.bottomToolbar)){ - this.bottomToolbar = new Ext.Toolbar(this.bottomToolbar); - }else if(!this.bottomToolbar.events){ - this.bottomToolbar = Ext.create(this.bottomToolbar, 'toolbar'); - } - this.bottomToolbar.ownerCt = this; - this.bottomToolbar.render(this.bbar); - this.toolbars.push(this.bottomToolbar); - } - }, +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); +}; - /** - * 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{ - Ext.DomHelper.insertBefore(hd.dom.firstChild, { - 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.isObject(cfg) ? cfg : { - shadow: Ext.isDefined(this.shadow) ? this.shadow : 'sides', - shadowOffset: this.shadowOffset, - constrain:false, - shim: this.shim === false ? false : undefined - }, this.el - ); - }, +Ext.Updater.BasicRenderer = function(){}; - /** - * Returns the {@link Ext.Toolbar toolbar} from the top ({@link #tbar}) section of the panel. - * @return {Ext.Toolbar} The toolbar - */ - getTopToolbar : function(){ - return this.topToolbar; - }, +Ext.Updater.BasicRenderer.prototype = { + + render : function(el, response, updateManager, callback){ + el.update(response.responseText, updateManager.loadScripts, callback); + } +}; - /** - * Returns the {@link Ext.Toolbar toolbar} from the bottom ({@link #bbar}) section of the panel. - * @return {Ext.Toolbar} The toolbar - */ - getBottomToolbar : function(){ - return this.bottomToolbar; - }, - /** - * 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 to use for the button handler function - * @return {Ext.Button} The button that was added - */ - addButton : function(config, handler, scope){ - var bc = { - handler: handler, - scope: scope, - minWidth: this.minButtonWidth, - hideParent:true - }; - if(Ext.isString(config)){ - bc.text = config; - }else{ - Ext.apply(bc, config); - } - var btn = new Ext.Button(bc); - if(!this.buttons){ - this.buttons = []; - } - this.buttons.push(btn); - return btn; - }, - // 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( - '
     
    ' - ); - 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((tc.align !== 'left') ? this[this.toolTarget] : this[this.toolTarget].child('span'), 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); - } - } - }, +(function() { - onLayout : function(shallow, force){ - 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; - - if(this.autoHeight || !Ext.isDefined(lsh) || lsh == 'auto'){ - return; - } +Date.useStrict = false; + + + + + +function xf(format) { + var args = Array.prototype.slice.call(arguments, 1); + return format.replace(/\{(\d+)\}/g, function(m, i) { + return args[i]; + }); +} + + + +Date.formatCodeToRegex = function(character, currentGroup) { + + var p = Date.parseCodes[character]; + + if (p) { + p = typeof p == 'function'? p() : p; + Date.parseCodes[character] = p; + } + + return p ? Ext.applyIf({ + c: p.c ? xf(p.c, currentGroup || "{0}") : p.c + }, p) : { + g:0, + c:null, + s:Ext.escapeRe(character) + }; +}; + + +var $f = Date.formatCodeToRegex; + +Ext.apply(Date, { + + parseFunctions: { + "M$": function(input, strict) { - - if(h != this.getToolbarHeight()){ - h = Math.max(0, this.adjustBodyHeight(lsh - this.getFrameHeight())); - bd.setHeight(h); - sz = bd.getSize(); - this.toolbarHeight = this.getToolbarHeight(); - this.onBodyResize(sz.width, sz.height); + + var re = new RegExp('\\/Date\\(([-+])?(\\d+)(?:[+-]\\d{4})?\\)\\/'); + var r = (input || '').match(re); + return r? new Date(((r[1] || '') + r[2]) * 1) : null; } }, + parseRegexes: [], - // private - onShow : function(){ - if(this.floating){ - return this.el.show(); + + formatFunctions: { + "M$": function() { + + return '\\/Date(' + this.getTime() + ')\\/'; } - Ext.Panel.superclass.onShow.call(this); }, - // private - onHide : function(){ - if(this.floating){ - return this.el.hide(); - } - Ext.Panel.superclass.onHide.call(this); - }, + y2kYear : 50, - // 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); - } - }; + + MILLI : "ms", + + + SECOND : "s", + + + MINUTE : "mi", + + + HOUR : "h", + + + DAY : "d", + + + MONTH : "mo", + + + YEAR : "y", + + + defaults: {}, + + + dayNames : [ + "Sunday", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday" + ], + + + monthNames : [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December" + ], + + + 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 }, - // private - afterRender : function(){ - if(this.floating && !this.hidden){ - this.el.show(); - } - if(this.title){ - this.setTitle(this.title); - } - this.setAutoScroll(); - if(this.html){ - this.body.update(Ext.isObject(this.html) ? - Ext.DomHelper.markup(this.html) : - this.html); - delete this.html; - } - if(this.contentEl){ - var ce = Ext.getDom(this.contentEl); - Ext.fly(ce).removeClass(['x-hidden', 'x-hide-display']); - this.body.dom.appendChild(ce); - } - if(this.collapsed){ - this.collapsed = false; - this.collapse(false); - } - Ext.Panel.superclass.afterRender.call(this); // do sizing calcs last - this.initEvents(); + + getShortMonthName : function(month) { + return Date.monthNames[month].substring(0, 3); }, - // private - setAutoScroll : function(){ - if(this.rendered && this.autoScroll){ - var el = this.body || this.el; - if(el){ - el.setOverflow('auto'); - } - } + + getShortDayName : function(day) { + return Date.dayNames[day].substring(0, 3); }, - // private - getKeyMap : function(){ - if(!this.keyMap){ - this.keyMap = new Ext.KeyMap(this.el, this.keys); - } - return this.keyMap; + + getMonthNumber : function(name) { + + return Date.monthNumbers[name.substring(0, 1).toUpperCase() + name.substring(1, 3).toLowerCase()]; }, - // 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); - if(!this.ownerCt){ - this.syncHeight(); + + formatCodes : { + d: "String.leftPad(this.getDate(), 2, '0')", + D: "Date.getShortDayName(this.getDay())", + 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())", + 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: "String.leftPad(this.getFullYear(), 4, '0')", + 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() { + 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)); } - } - }, + return code.join(" + "); + }, + - // private - initDraggable : function(){ - /** - *

    If this Panel is configured {@link #draggable}, this property will contain - * an instance of {@link Ext.dd.DragSource} which handles dragging the Panel.

    - * 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); + U: "Math.round(this.getTime() / 1000)" }, - // private - beforeEffect : function(anim){ - if(this.floating){ - this.el.beforeAction(); - } - if(anim !== false){ - this.el.addClass('x-panel-animated'); - } - }, + + isValid : function(y, m, d, h, i, s, ms) { + + h = h || 0; + i = i || 0; + s = s || 0; + ms = ms || 0; - // private - afterEffect : function(anim){ - this.syncShadow(); - if(anim !== false){ - this.el.removeClass('x-panel-animated'); - } + + var dt = new Date(y < 100 ? 100 : y, m - 1, d, h, i, s, ms).add(Date.YEAR, y < 100 ? y - 100 : 0); + + return y == dt.getFullYear() && + m == dt.getMonth() + 1 && + d == dt.getDate() && + h == dt.getHours() && + i == dt.getMinutes() && + s == dt.getSeconds() && + ms == dt.getMilliseconds(); }, - // 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); - }; + + parseDate : function(input, format, strict) { + var p = Date.parseFunctions; + if (p[format] == null) { + Date.createParser(format); } - return Ext.applyIf(o, a); + return p[format](input, Ext.isDefined(strict) ? strict : Date.useStrict); }, - /** - * 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; + + getFormatCode : function(character) { + var f = Date.formatCodes[character]; + + if (f) { + f = typeof f == 'function'? f() : f; + Date.formatCodes[character] = f; } - var doAnim = animate === true || (animate !== false && this.animCollapse); - this.beforeEffect(doAnim); - this.onCollapse(doAnim, animate); - return this; + + + return f || ("'" + String.escape(character) + "'"); }, - // 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.afterCollapse(false); + + 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 - afterCollapse : function(anim){ - this.collapsed = true; - this.el.addClass(this.collapsedCls); - this.afterEffect(anim); - 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.afterExpand(false); - } - }, - - // private - afterExpand : function(anim){ - this.collapsed = false; - this.afterEffect(anim); - if(Ext.isDefined(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(w, h){ - if(Ext.isDefined(w) || Ext.isDefined(h)){ - if(!this.collapsed){ - if(Ext.isNumber(w)){ - w = this.adjustBodyWidth(w - this.getFrameWidth()); - 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); - } - } - if(this.fbar){ - var f = this.fbar, - fWidth = 1, - strict = Ext.isStrict; - if(this.buttonAlign == 'left'){ - fWidth = w - f.container.getFrameWidth('lr'); - }else{ - //center/right alignment off in webkit - if(Ext.isIE || Ext.isWebKit){ - //center alignment ok on webkit. - //right broken in both, center on IE - if(!(this.buttonAlign == 'center' && Ext.isWebKit) && (!strict || (!Ext.isIE8 && strict))){ - (function(){ - f.setWidth(f.getEl().child('.x-toolbar-ct').getWidth()); - }).defer(1); - }else{ - fWidth = 'auto'; - } - }else{ - fWidth = 'auto'; - } - } - f.setWidth(fWidth); - } - this.body.setWidth(w); - }else if(w == 'auto'){ - this.body.setWidth(w); - } - - if(Ext.isNumber(h)){ - h = Math.max(0, this.adjustBodyHeight(h - this.getFrameHeight())); - 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{ - 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.doLayout(); - }, this, {single:true}); - } - } - this.onBodyResize(w, h); - } - this.syncShadow(); - }, - - // 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; - }, + 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}]);", - // private - adjustBodyHeight : function(h){ - return h; - }, + "if(results){", + "{1}", - // private - adjustBodyWidth : function(w){ - return w; - }, + "if(u != null){", + "v = new Date(u * 1000);", + "}else{", + + + + "dt = (new Date()).clearTime();", - // private - onPosition : function(){ - this.syncShadow(); - }, + + "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()));", - /** - * 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'); + + "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(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; - }, + "if(z >= 0 && y >= 0){", + + - /** - * 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 = this.el.getFrameWidth('tb') + this.bwrap.getFrameWidth('tb'); - h += (this.tbar ? this.tbar.getHeight() : 0) + - (this.bbar ? this.bbar.getHeight() : 0); + + + "v = new Date(y < 100 ? 100 : y, 0, 1, h, i, s, ms).add(Date.YEAR, y < 100 ? y - 100 : 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; - }, + + "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)){", + "v = null;", + "}else{", + + + "v = new Date(y < 100 ? 100 : y, m, d, h, i, s, ms).add(Date.YEAR, y < 100 ? y - 100 : 0);", + "}", + "}", + "}", - /** - * 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(); - }, + "if(v){", + + "if(zz != null){", + + "v = v.add(Date.SECOND, -v.getTimezoneOffset() * 60 - zz);", + "}else if(o){", + + "v = v.add(Date.MINUTE, -v.getTimezoneOffset() + (sn == '+'? -1 : 1) * (hr * 60 + mn));", + "}", + "}", - /** - * 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.getSize().height - this.getFrameHeight(); - }, + "return v;" + ].join('\n'); - // private - syncShadow : function(){ - if(this.floating){ - this.el.sync(true); - } - }, + return function(format) { + var regexNum = Date.parseRegexes.length, + currentGroup = 1, + calc = [], + regex = [], + special = false, + ch = "", + i = 0, + obj, + last; - // private - getLayoutTarget : function(){ - return this.body; - }, + for (; i < format.length; ++i) { + ch = format.charAt(i); + if (!special && ch == "\\") { + special = true; + } else if (special) { + special = false; + regex.push(String.escape(ch)); + } else { + obj = $f(ch, currentGroup); + currentGroup += obj.g; + regex.push(obj.s); + if (obj.g && obj.c) { + if (obj.calcLast) { + last = obj.c; + } else { + calc.push(obj.c); + } + } + } + } + + if (last) { + calc.push(last); + } - /** - *

    Sets the title text for the panel and optionally the {@link #iconCls icon class}.

    - *

    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 {@link #title}, - * or configuring it with {@link #header}: true.

    - * @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; - }, + Date.parseRegexes[regexNum] = new RegExp("^" + regex.join('') + "$", 'i'); + Date.parseFunctions[format] = new Function("input", "strict", xf(code, regexNum, calc.join(''))); + }; + }(), - /** - * 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: -
    
    -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
    -});
    -
    - * 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; - }, + + parseCodes : { + + d: { + g:1, + c:"d = parseInt(results[{0}], 10);\n", + s:"(\\d{2})" + }, + j: { + g:1, + c:"d = parseInt(results[{0}], 10);\n", + s:"(\\d{1,2})" + }, + D: function() { + for (var a = [], i = 0; i < 7; a.push(Date.getShortDayName(i)), ++i); + 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]" + }, + S: { + g:0, + c:null, + s:"(?:st|nd|rd|th)" + }, + w: { + g:0, + c:null, + s:"[0-6]" + }, + z: { + g:1, + c:"z = parseInt(results[{0}], 10);\n", + s:"(\\d{1,3})" + }, + W: { + g:0, + c:null, + s:"(?:\\d{2})" + }, + F: function() { + return { + g:1, + c:"m = parseInt(Date.getMonthNumber(results[{0}]), 10);\n", + s:"(" + Date.monthNames.join("|") + ")" + }; + }, + M: function() { + for (var a = [], i = 0; i < 12; a.push(Date.getShortMonthName(i)), ++i); + return Ext.applyIf({ + s:"(" + a.join("|") + ")" + }, $f("F")); + }, + m: { + g:1, + c:"m = parseInt(results[{0}], 10) - 1;\n", + s:"(\\d{2})" + }, + n: { + g:1, + c:"m = parseInt(results[{0}], 10) - 1;\n", + s:"(\\d{1,2})" + }, + t: { + g:0, + c:null, + s:"(?:\\d{2})" + }, + 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})" + }, + y: { + g:1, + c:"var ty = parseInt(results[{0}], 10);\n" + + "y = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n", + s:"(\\d{1,2})" + }, + + a: function(){ + return $f("A"); + }, + A: { + + calcLast: true, + g:1, + c:"if (/(am)/i.test(results[{0}])) {\n" + + "if (!h || h == 12) { h = 0; }\n" + + "} else { if (!h || h < 12) { h = (h || 0) + 12; }}", + s:"(AM|PM|am|pm)" + }, + g: function() { + return $f("G"); + }, + G: { + g:1, + c:"h = parseInt(results[{0}], 10);\n", + s:"(\\d{1,2})" + }, + h: function() { + return $f("H"); + }, + H: { + g:1, + c:"h = parseInt(results[{0}], 10);\n", + s:"(\\d{2})" + }, + i: { + g:1, + c:"i = parseInt(results[{0}], 10);\n", + s:"(\\d{2})" + }, + s: { + g:1, + c:"s = parseInt(results[{0}], 10);\n", + s:"(\\d{2})" + }, + u: { + g:1, + c:"ms = results[{0}]; ms = parseInt(ms, 10)/Math.pow(10, ms.length - 3);\n", + s:"(\\d+)" + }, + O: { + g:1, + c:[ + "o = results[{0}];", + "var sn = o.substring(0,1),", + "hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60),", + "mn = o.substring(3,5) % 60;", + "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))? (sn + String.leftPad(hr, 2, '0') + String.leftPad(mn, 2, '0')) : null;\n" + ].join("\n"), + s: "([+\-]\\d{4})" + }, + P: { + g:1, + c:[ + "o = results[{0}];", + "var sn = o.substring(0,1),", + "hr = o.substring(1,3)*1 + Math.floor(o.substring(4,6) / 60),", + "mn = o.substring(4,6) % 60;", + "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))? (sn + String.leftPad(hr, 2, '0') + String.leftPad(mn, 2, '0')) : null;\n" + ].join("\n"), + s: "([+\-]\\d{2}:\\d{2})" + }, + T: { + g:0, + c:null, + s:"[A-Z]{1,4}" + }, + Z: { + g:1, + c:"zz = results[{0}] * 1;\n" + + "zz = (-43200 <= zz && zz <= 50400)? zz : null;\n", + s:"([+\-]?\\d{1,5})" + }, + c: function() { + var calc = [], + arr = [ + $f("Y", 1), + $f("m", 2), + $f("d", 3), + $f("h", 4), + $f("i", 5), + $f("s", 6), + {c:"ms = results[7] || '0'; ms = parseInt(ms, 10)/Math.pow(10, ms.length - 3);\n"}, + {c:[ + "if(results[8]) {", + "if(results[8] == 'Z'){", + "zz = 0;", + "}else if (results[8].indexOf(':') > -1){", + $f("P", 8).c, + "}else{", + $f("O", 8).c, + "}", + "}" + ].join('\n')} + ]; - // private - beforeDestroy : function(){ - if(this.header){ - this.header.removeAllListeners(); - if(this.headerAsText){ - Ext.Element.uncache(this.header.child('span')); - } - } - Ext.Element.uncache( - this.ft, - this.mc, - this.header, - this.tbar, - this.bbar, - this.footer, - this.body, - this.bwrap - ); - if(this.tools){ - for(var k in this.tools){ - Ext.destroy(this.tools[k]); - } - } - if(this.buttons){ - for(var b in this.buttons){ - Ext.destroy(this.buttons[b]); + 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, + "(?:", "-", arr[1].s, + "(?:", "-", arr[2].s, + "(?:", + "(?:T| )?", + arr[3].s, ":", arr[4].s, + "(?::", arr[5].s, ")?", + "(?:(?:\\.|,)(\\d+))?", + "(Z|(?:[-+]\\d{2}(?::)?\\d{2}))?", + ")?", + ")?", + ")?" + ].join("") + }; + }, + U: { + g:1, + c:"u = parseInt(results[{0}], 10);\n", + s:"(-?\\d+)" } - if(this.rendered){ - Ext.destroy(this.toolbars); - }else{ - Ext.destroy(this.topToolbar, this.bottomToolbar); + } +}); + +}()); + +Ext.apply(Date.prototype, { + + dateFormat : function(format) { + if (Date.formatFunctions[format] == null) { + Date.createFormat(format); } - Ext.Panel.superclass.beforeDestroy.call(this); + return Date.formatFunctions[format].call(this); }, - // 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'; + + getTimezone : function() { + + + + + + + + + + + + + return this.toString().replace(/^.* (?:\((.*)\)|([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?)$/, "$1$2").replace(/[^A-Z]/g, ""); }, - // 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); - } + + 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"); }, - // private - doAutoLoad : function(){ - var u = this.body.getUpdater(); - if(this.renderer){ - u.setRenderer(this.renderer); + + 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(); } - u.update(Ext.isObject(this.autoLoad) ? this.autoLoad : {url: this.autoLoad}); + return num + this.getDate() - 1; }, - /** - * Retrieve a tool by id. - * @param {String} id - * @return {Object} tool - */ - getTool : function(id) { - return this.tools[id]; - } + + getWeekOfYear : function() { + + var ms1d = 864e5, + ms7d = 7 * ms1d; -/** - * @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); -}; + return function() { + var DC3 = Date.UTC(this.getFullYear(), this.getMonth(), this.getDate() + 3) / ms1d, + AWN = Math.floor(DC3 / 7), + Wyr = new Date(AWN * ms7d).getUTCFullYear(); -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 false. - */ - /** - * @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 {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 true. - */ - completeOnEnter : true, - /** - * @cfg {Boolean} cancelOnEsc True to cancel the edit when the escape key is pressed. Defaults to true. - */ - cancelOnEsc : true, - /** - * @cfg {Boolean} updateEl True to update the innerHTML of the bound element when the update completes (defaults to false) - */ - updateEl : false, + return AWN - Math.floor(Date.UTC(Wyr, 0, 7) / ms7d) + 1; + }; + }(), - 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" - ); + + isLeapYear : function() { + var year = this.getFullYear(); + return !!((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year))); }, - // 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 - ]); - } + + getFirstDayOfMonth : function() { + var day = (this.getDay() - (this.getDate() - 1)) % 7; + return (day < 0) ? (day + 7) : day; }, - // 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); + + getLastDayOfMonth : function() { + return this.getLastDateOfMonth().getDay(); }, - /** - * 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.setValue(v); - this.doAutoSize(); - this.el.alignTo(this.boundEl, this.alignment); - this.editing = true; - this.show(); - } + + + getFirstDateOfMonth : function() { + return new Date(this.getFullYear(), this.getMonth(), 1); }, - // private - doAutoSize : function(){ - if(this.autoSize){ - var sz = this.boundEl.getSize(), - fs = this.field.getSize(); + + getLastDateOfMonth : function() { + return new Date(this.getFullYear(), this.getMonth(), this.getDaysInMonth()); + }, - 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); - } + + getDaysInMonth: function() { + var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + + return function() { + var m = this.getMonth(); + + return m == 1 && this.isLeapYear() ? 29 : daysInMonth[m]; + }; + }(), + + + 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"; } }, - /** - * 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(); - } + + clone : function() { + return new Date(this.getTime()); }, - /** - * Realigns the editor to the bound field based on the current alignment config value. - */ - realign : function(){ - this.el.alignTo(this.boundEl, this.alignment); + + isDST : function() { + + + return new Date(this.getFullYear(), 0, 1).getTimezoneOffset() != this.getTimezoneOffset(); }, - /** - * 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; - } - var v = this.getValue(); - if(!this.field.isValid()){ - if(this.revertInvalid !== false){ - this.cancelEdit(remainVisible); - } - return; + + clearTime : function(clone) { + if (clone) { + return this.clone().clearTime(); } - 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); - }, + + var d = this.getDate(); - /** - * 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); + + this.setHours(0); + this.setMinutes(0); + this.setSeconds(0); + this.setMilliseconds(0); + + if (this.getDate() != d) { + + + + + 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; }, + - // private - hideEdit: function(remainVisible){ - if(remainVisible !== true){ - this.editing = false; - this.hide(); - } - }, + add : function(interval, value) { + var d = this.clone(); + if (!interval || value === 0) return d; - // private - onBlur : function(){ - if(this.allowBlur !== true && this.editing){ - this.completeEdit(); + 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; }, - // 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(); + + between : function(start, end) { + var t = this.getTime(); + return start.getTime() <= t && t <= end.getTime(); + } +}); + + + +Date.prototype.format = Date.prototype.dateFormat; + + + +if (Ext.isSafari && (navigator.userAgent.match(/WebKit\/(\d+)/)[1] || NaN) < 420) { + Ext.apply(Date.prototype, { + _xMonth : Date.prototype.setMonth, + _xDate : Date.prototype.setDate, + + + + 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); + } + }, + + + + + setDate : function(d) { + + + return this.setTime(this.getTime() - (this.getDate() - d) * 864e5); } - }, + }); +} - /** - * 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.destroy(this.field); - this.field = null; - } -}); -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.
    - * Here's an example of typical usage: - *
    
    -var cp = new Ext.ColorPalette({value:'993300'});  // initial selected color
    -cp.render('my-div');
    -
    -cp.on('select', function(palette, selColor){
    -    // do something with selColor
    -});
    -
    - * @constructor - * Create a new ColorPalette - * @param {Object} config The config object - * @xtype colorpalette - */ -Ext.ColorPalette = function(config){ - Ext.ColorPalette.superclass.constructor.call(this, config); + + +Ext.util.MixedCollection = function(allowFunctions, keyFn){ + this.items = []; + this.map = {}; + this.keys = []; + this.length = 0; 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' + + 'clear', + + 'add', + + 'replace', + + 'remove', + 'sort' ); - - if(this.handler){ - this.on('select', this.handler, this.scope, true); + this.allowFunctions = allowFunctions === true; + if(keyFn){ + this.getKey = keyFn; } + Ext.util.MixedCollection.superclass.constructor.call(this); }; -Ext.extend(Ext.ColorPalette, 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, - 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, +Ext.extend(Ext.util.MixedCollection, Ext.util.Observable, { - /** - *

    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.

    - *

    You can override individual colors if needed:

    - *
    
    -var cp = new Ext.ColorPalette();
    -cp.colors[0] = 'FF0000';  // change the first box to red
    -
    + + allowFunctions : false, -Or you can provide a custom array of your own for complete control: -
    
    -var cp = new Ext.ColorPalette();
    -cp.colors = ['000000', '993300', '333300'];
    -
    - * @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' - ], + + 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; + }, - /** - * @cfg {Function} handler - * Optional. A function that will handle the select event of this palette. - * The handler is passed the following parameters:
      - *
    • palette : ColorPalette
      The {@link #palette Ext.ColorPalette}.
    • - *
    • color : String
      The 6-digit color hex code (without the # symbol).
    • - *
    - */ - /** - * @cfg {Object} scope - * The scope (this reference) in which the {@link #handler} - * function will be called. Defaults to this ColorPalette instance. - */ + + getKey : function(o){ + return o.id; + }, - // private - onRender : function(container, position){ - var t = this.tpl || new Ext.XTemplate( - ' ' - ); - var el = document.createElement('div'); - el.id = this.getId(); - el.className = this.itemCls; - t.overwrite(el, this.colors); - container.dom.insertBefore(el, position); - this.el = Ext.get(el); - 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}); + + 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; + }, + + + 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]); + } + } } }, - // private - afterRender : function(){ - Ext.ColorPalette.superclass.afterRender.call(this); - if(this.value){ - var s = this.value; - this.value = null; - this.select(s); + + each : function(fn, scope){ + var items = [].concat(this.items); + for(var i = 0, len = items.length; i < len; i++){ + if(fn.call(scope || items[i], items[i], i, len) === false){ + break; + } } }, - // private - handleClick : function(e, t){ - e.preventDefault(); - if(!this.disabled){ - var c = t.className.match(/(?:^|\s)color-(.{6})(?:\s|$)/)[1]; - this.select(c.toUpperCase()); + + 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); } }, - /** - * 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) - */ - select : function(color){ - 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'); + + 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]; } - el.child('a.color-'+color).addClass('x-color-palette-sel'); - this.value = color; - this.fireEvent('select', this, color); } - } - - /** - * @cfg {String} autoEl @hide - */ -}); -Ext.reg('colorpalette', Ext.ColorPalette); -/** - * @class Ext.DatePicker - * @extends Ext.Component - * Simple date picker class. - * @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 'Today') - */ - todayText : 'Today', - /** - * @cfg {String} okText - * The text to display on the ok button (defaults to ' OK ' to give the user extra clicking room) - */ - okText : ' OK ', - /** - * @cfg {String} cancelText - * The text to display on the cancel button (defaults to 'Cancel') - */ - cancelText : 'Cancel', - /** - * @cfg {Function} handler - * Optional. A function that will handle the select event of this picker. - * The handler is passed the following parameters:
      - *
    • picker : DatePicker
      The Ext.DatePicker.
    • - *
    • date : Date
      The selected date.
    • - *
    - */ - /** - * @cfg {Object} scope - * The scope (this reference) in which the {@link #handler} - * function will be called. Defaults to this DatePicker instance. - */ - /** - * @cfg {String} todayTip - * The tooltip to display for the button that selects the current date (defaults to '{current date} (Spacebar)') - */ - todayTip : '{0} (Spacebar)', - /** - * @cfg {String} minText - * The error text to display if the minDate validation fails (defaults to 'This date is before the minimum date') - */ - minText : 'This date is before the minimum date', - /** - * @cfg {String} maxText - * The error text to display if the maxDate validation fails (defaults to 'This date is after the maximum date') - */ - 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 'm/d/y'). - */ - format : 'm/d/y', - /** - * @cfg {String} disabledDaysText - * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled') - */ - disabledDaysText : 'Disabled', - /** - * @cfg {String} disabledDatesText - * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled') - */ - 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 'Next Month (Control+Right)') - */ - nextText : 'Next Month (Control+Right)', - /** - * @cfg {String} prevText - * The previous month navigation button tooltip (defaults to 'Previous Month (Control+Left)') - */ - prevText : 'Previous Month (Control+Left)', - /** - * @cfg {String} monthYearText - * The header month selector tooltip (defaults to 'Choose a month (Control+Up/Down to move years)') - */ - 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 true). - */ - 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: - *
      - *
    • ['03/08/2003', '09/16/2003'] would disable those exact dates
    • - *
    • ['03/08', '09/16'] would disable those days for every year
    • - *
    • ['^03/08'] would only match the beginning (useful if you are using short years)
    • - *
    • ['03/../2006'] would disable every day in March 2006
    • - *
    • ['^03'] would disable every day in every March
    • - *
    - * 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 - 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 - * @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 = [ - '', - '', - '', - this.showToday ? '' : '', - '
      
    '], - dn = this.dayNames, - i; - for(i = 0; i < 7; i++){ - var d = this.startDay+i; - if(d > 6){ - d = d-7; - } - m.push(''); - } - m[m.length] = ''; - for(i = 0; i < 42; i++) { - if(i % 7 === 0 && i !== 0){ - m[m.length] = ''; - } - m[m.length] = ''; - } - m.push('
    ', dn[d].substr(0,1), '
    '); - - 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: ' ', - 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 = ['']; - for(var i = 0; i < 6; i++){ - buf.push( - '', - '', - i === 0 ? - '' : - '' - ); - } - buf.push( - '', - '
    ', Date.getShortMonthName(i), '', Date.getShortMonthName(i + 6), '
    ' - ); - 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.setValue(new Date(t.dateValue)); - 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){ - Ext.fly(c.dom.firstChild).focus(50); - } - return false; - } - }); - 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 - day = 86400000, - d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime(), - 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.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){ - this.keyNav.disable(); - this.keyNav = null; - Ext.destroy( - this.leftClickRpt, - this.rightClickRpt, - this.monthPicker, - this.eventEl, - this.mbtn, - this.todayBtn - ); - } - } - - /** - * @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. - *

    Example usage:

    - *
    
    -// Basic mask:
    -var myMask = new Ext.LoadMask(Ext.getBody(), {msg:"Please wait..."});
    -myMask.show();
    -
    - * @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('beforeload', this.onBeforeLoad, this); - this.store.on('load', this.onLoad, this); - this.store.on('exception', this.onLoad, this); - this.removeMask = Ext.value(this.removeMask, false); - }else{ - var um = this.el.getUpdater(); - um.showLoadIndicator = false; // disable the default indicator - um.on('beforeupdate', this.onBeforeLoad, this); - um.on('update', this.onLoad, this); - um.on('failure', this.onLoad, this); - this.removeMask = Ext.value(this.removeMask, true); - } -}; + return null; + }, -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', + + 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; + }, - /** - * Read-only. True if the mask is currently disabled so that it will not be displayed (defaults to false) - * @type Boolean - */ - disabled: false, + + remove : function(o){ + return this.removeAt(this.indexOf(o)); + }, - /** - * Disables the mask to prevent it from being displayed - */ - disable : function(){ - this.disabled = true; + + 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; }, - /** - * Enables the mask so that it can be displayed - */ - enable : function(){ - this.disabled = false; + + removeKey : function(key){ + return this.removeAt(this.indexOfKey(key)); }, - // private - onLoad : function(){ - this.el.unmask(this.removeMask); + + getCount : function(){ + return this.length; }, - // private - onBeforeLoad : function(){ - if(!this.disabled){ - this.el.mask(this.msg, this.msgCls); - } + + indexOf : function(o){ + return this.items.indexOf(o); }, - /** - * Show this LoadMask over the configured Element. - */ - show: function(){ - this.onBeforeLoad(); + + indexOfKey : function(key){ + return this.keys.indexOf(key); }, - /** - * Hide this LoadMask. - */ - hide: function(){ - this.onLoad(); + + 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; }, - // 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); - } - } -};/** - * @class Ext.Slider - * @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: -
    
    -new Ext.Slider({
    -    renderTo: Ext.getBody(),
    -    width: 200,
    -    value: 50,
    -    increment: 10,
    -    minValue: 0,
    -    maxValue: 100
    -});
    -
    - */ -Ext.Slider = 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. - *

    The number of decimal places to which to round the Slider's value. Defaults to 0.

    - *

    To disable rounding, configure as false.

    - */ - 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 - 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, - - // private override - initComponent : function(){ - if(!Ext.isDefined(this.value)){ - this.value = this.minValue; - } - Ext.Slider.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. - */ - '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. - */ - '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' - ); - - if(this.vertical){ - Ext.apply(this, Ext.Slider.Vertical); - } - }, - - // 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:[{cls:'x-slider-thumb'},{tag:'a', cls:'x-slider-focus', href:"#", tabIndex: '-1', hidefocus:'on'}]}} - }; - Ext.Slider.superclass.onRender.apply(this, arguments); - this.endEl = this.el.first(); - this.innerEl = this.endEl.first(); - this.thumb = this.innerEl.first(); - this.halfThumb = (this.vertical ? this.thumb.getHeight() : this.thumb.getWidth())/2; - this.focusEl = this.thumb.next(); - this.initEvents(); - }, - - // private override - initEvents : function(){ - this.thumb.addClassOnOver('x-slider-thumb-over'); - this.mon(this.el, { - scope: this, - mousedown: this.onMouseDown, - keydown: this.onKeyDown - }); - - this.focusEl.swallowEvent("click", true); - - 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(this.thumb); - this.on('beforedestroy', this.tracker.destroy, this.tracker); - }, - - // private override - onMouseDown : function(e){ - if(this.disabled) {return;} - if(this.clickToChange && e.target != this.thumb.dom){ - var local = this.innerEl.translatePoints(e.getXY()); - this.onClickChange(local); - } - this.focus(); - }, - - // private - onClickChange : function(local){ - if(local.top > this.clickRange[0] && local.top < this.clickRange[1]){ - this.setValue(Ext.util.Format.round(this.reverseValue(local.left), this.decimalPrecision), undefined, true); - } - }, - - // private - onKeyDown : function(e){ - if(this.disabled){e.preventDefault();return;} - var k = e.getKey(); - switch(k){ - case e.UP: - case e.RIGHT: - e.stopEvent(); - if(e.ctrlKey){ - this.setValue(this.maxValue, undefined, true); - }else{ - this.setValue(this.value+this.keyIncrement, undefined, true); - } - break; - case e.DOWN: - case e.LEFT: - e.stopEvent(); - if(e.ctrlKey){ - this.setValue(this.minValue, undefined, true); - }else{ - this.setValue(this.value-this.keyIncrement, undefined, true); - } - break; - default: - e.preventDefault(); - } - }, - - // private - doSnap : function(value){ - if(!this.increment || this.increment == 1 || !value) { - return value; - } - var newValue = value, inc = this.increment; - var 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.superclass.afterRender.apply(this, arguments); - if(this.value !== undefined){ - var v = this.normalizeValue(this.value); - if(v !== this.value){ - delete this.value; - this.setValue(v, false); - }else{ - this.moveThumb(this.translateValue(v), false); - } - } - }, - - // private - getRatio : function(){ - var w = this.innerEl.getWidth(); - var v = this.maxValue - this.minValue; - return v == 0 ? w : (w/v); - }, - - // private - normalizeValue : function(v){ - v = this.doSnap(v); - v = Ext.util.Format.round(v, this.decimalPrecision); - v = v.constrain(this.minValue, this.maxValue); - return v; - }, - - /** - * 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(v, animate, changeComplete){ - v = this.normalizeValue(v); - if(v !== this.value && this.fireEvent('beforechange', this, v, this.value) !== false){ - this.value = v; - this.moveThumb(this.translateValue(v), animate !== false); - this.fireEvent('change', this, v); - if(changeComplete){ - this.fireEvent('changecomplete', this, v); - } - } - }, - - // private - translateValue : function(v){ - var ratio = this.getRatio(); - return (v * ratio)-(this.minValue * ratio)-this.halfThumb; - }, - - reverseValue : function(pos){ - var ratio = this.getRatio(); - return (pos+this.halfThumb+(this.minValue * ratio))/ratio; - }, - - // private - moveThumb: function(v, animate){ - if(!animate || this.animate === false){ - this.thumb.setLeft(v); - }else{ - this.thumb.shift({left: v, stopFx: true, duration:.35}); - } - }, - - // private - focus : function(){ - this.focusEl.focus(10); - }, - - // private - onBeforeDragStart : function(e){ - return !this.disabled; - }, - - // private - onDragStart: function(e){ - this.thumb.addClass('x-slider-thumb-drag'); - this.dragging = true; - this.dragStartValue = this.value; - this.fireEvent('dragstart', this, e); - }, - - // private - onDrag: function(e){ - var pos = this.innerEl.translatePoints(this.tracker.getXY()); - this.setValue(Ext.util.Format.round(this.reverseValue(pos.left), this.decimalPrecision), false); - this.fireEvent('drag', this, e); - }, - - // private - onDragEnd: function(e){ - this.thumb.removeClass('x-slider-thumb-drag'); - this.dragging = false; - this.fireEvent('dragend', this, e); - if(this.dragStartValue != this.value){ - this.fireEvent('changecomplete', this, this.value); - } - }, - - // private - onResize : function(w, h){ - this.innerEl.setWidth(w - (this.el.getPadding('l') + this.endEl.getPadding('r'))); - this.syncThumb(); - }, - - //private - onDisable: function(){ - Ext.Slider.superclass.onDisable.call(this); - this.thumb.addClass(this.disabledClass); - 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 = this.thumb.getXY(); - this.thumb.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.superclass.onEnable.call(this); - this.thumb.removeClass(this.disabledClass); - if(Ext.isIE){ - this.innerEl.removeClass(this.disabledClass).dom.disabled = false; - if (this.thumbHolder){ - this.thumbHolder.hide(); - } - this.thumb.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){ - this.moveThumb(this.translateValue(this.value)); - } - }, - - /** - * Returns the current value of the slider - * @return {Number} The current value of the slider - */ - getValue : function(){ - return this.value; - } -}); -Ext.reg('slider', Ext.Slider); - -// 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(); - var v = this.maxValue - this.minValue; - return h/v; - }, - - moveThumb: function(v, animate){ - if(!animate || this.animate === false){ - this.thumb.setBottom(v); - }else{ - this.thumb.shift({bottom: v, stopFx: true, duration:.35}); - } - }, - - onDrag: function(e){ - var pos = this.innerEl.translatePoints(this.tracker.getXY()); - var bottom = this.innerEl.getHeight()-pos.top; - this.setValue(this.minValue + Ext.util.Format.round(bottom/this.getRatio(), this.decimalPrecision), false); - this.fireEvent('drag', this, e); - }, - - onClickChange : function(local){ - if(local.left > this.clickRange[0] && local.left < this.clickRange[1]){ - var bottom = this.innerEl.getHeight()-local.top; - this.setValue(this.minValue + Ext.util.Format.round(bottom/this.getRatio(), this.decimalPrecision), undefined, true); - } - } -};/** - * @class Ext.ProgressBar - * @extends Ext.BoxComponent - *

    An updateable progress bar component. The progress bar supports two different modes: manual and automatic.

    - *

    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.

    - *

    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.

    - * @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( - '
    ', - '
    ', - '
    ', - '
    ', - '
     
    ', - '
    ', - '
    ', - '
    ', - '
     
    ', - '
    ', - '
    ', - '
    ' - ); - - 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){ - 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: - *
    -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).
    -
    - * - * Example usage: - *
    
    -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!');
    -});
    -
    - * @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 || ' '; - 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'); - } - if(this.waitTimer){ - this.waitTimer.onStop = null; //prevent recursion - Ext.TaskMgr.stop(this.waitTimer); - this.waitTimer = null; - } - if(hide === true){ - this.hide(); - } - return 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 - */ + + itemAt : function(index){ + return this.items[index]; + }, -(function() { + + key : function(key){ + return this.map[key]; + }, -var Event=Ext.EventManager; -var Dom=Ext.lib.Dom; + + contains : function(o){ + return this.indexOf(o) != -1; + }, -/** - * @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: - *
      - *
    • linked element: the element that is passed into the constructor. - * This is the element which defines the boundaries for interaction with - * other DragDrop objects.
    • - *
    • 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.
    • - *
    • 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}. - *
    • - *
    - * 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: - *
    - *  dd = new Ext.dd.DragDrop("div1", "group1");
    - * 
    - * 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... - *
    - *  dd.onDragDrop = function(e, id) {
    - *    alert("dd was dropped on " + id);
    - *  }
    - * 
    - * @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); - } -}; + + containsKey : function(key){ + return typeof this.map[key] != 'undefined'; + }, -Ext.dd.DragDrop.prototype = { + + clear : function(){ + this.length = 0; + this.items = []; + this.keys = []; + this.map = {}; + this.fireEvent('clear'); + }, - /** - * 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 - */ + + first : function(){ + return this.items[0]; + }, - /** - * 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, + + last : function(){ + return this.items[this.length-1]; + }, - /** - * Configuration attributes passed into the constructor - * @property config - * @type object - */ - config: null, + + _sort : function(property, dir, fn){ + var i, len, + dsc = String(dir).toUpperCase() == 'DESC' ? -1 : 1, - /** - * 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, + + c = [], + keys = this.keys, + items = this.items; - /** - * 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, + + fn = fn || function(a, b) { + return a - b; + }; - /** - * 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 <a> elements:
    
    -{
    -    A: "A"
    -}
    - * @property invalidHandleTypes - * @type Object - */ - invalidHandleTypes: null, + + for(i = 0, len = items.length; i < len; i++){ + c[c.length] = { + key : keys[i], + value: items[i], + index: i + }; + } - /** - * 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:
    
    -{
    -    foo: true
    -}
    - * @property invalidHandleIds - * @type Object - */ - invalidHandleIds: null, + + 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; + }); - /** - * An Array of CSS class names for elements to be considered in valid as drag handles. - * @property invalidHandleClasses - * @type Array - */ - invalidHandleClasses: null, + + for(i = 0, len = c.length; i < len; i++){ + items[i] = c[i].value; + keys[i] = c[i].key; + } - /** - * The linked element's absolute X position at the time the drag was - * started - * @property startPageX - * @type int - * @private - */ - startPageX: 0, + this.fireEvent('sort', this); + }, - /** - * 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, + + sort : function(dir, fn){ + this._sort('value', dir, fn); + }, - /** - * Individual drag/drop instances can be locked. This will prevent - * onmousedown start drag. - * @property locked - * @type boolean - * @private - */ - locked: false, + + reorder: function(mapping) { + this.suspendEvents(); - /** - * Lock this instance - * @method lock - */ - lock: function() { this.locked = true; }, + var items = this.items, + index = 0, + length = items.length, + order = [], + remaining = [], + oldIndex; - /** - * 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, + + for (oldIndex in mapping) { + order[mapping[oldIndex]] = items[oldIndex]; + } - /** - * Unlock this instace - * @method unlock - */ - unlock: function() { this.locked = false; }, + for (index = 0; index < length; index++) { + if (mapping[index] == undefined) { + remaining.push(items[index]); + } + } - /** - * By default, all instances can be a drop target. This can be disabled by - * setting isTarget to false. - * @property isTarget - * @type boolean - */ - isTarget: true, + for (index = 0; index < length; index++) { + if (order[index] == undefined) { + order[index] = remaining.shift(); + } + } - /** - * 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, + this.clear(); + this.addAll(order); - /** - * Cached reference to the linked element - * @property _domRef - * @private - */ - _domRef: null, + this.resumeEvents(); + this.fireEvent('sort', this); + }, - /** - * Internal typeof flag - * @property __ygDragDrop - * @private - */ - __ygDragDrop: true, + + 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); + }); + }, - /** - * Set to true when horizontal contraints are applied - * @property constrainX - * @type boolean - * @private - */ - constrainX: false, + + 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; + }, - /** - * Set to true when vertical contraints are applied - * @property constrainY - * @type boolean - * @private - */ - constrainY: false, + + 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]); + }); + }, - /** - * The left constraint - * @property minX - * @type int - * @private - */ - minX: 0, + + 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; + }, - /** - * The right constraint - * @property maxX - * @type int - * @private - */ - maxX: 0, + + 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); + }, - /** - * The up constraint - * @property minY - * @type int - * @type int - * @private - */ - minY: 0, + + 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; + }, - /** - * The down constraint - * @property maxY - * @type int - * @private - */ - maxY: 0, + + createValueMatcher : function(value, anyMatch, caseSensitive, exactMatch) { + if (!value.exec) { + var er = Ext.escapeRe; + value = String(value); - /** - * 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, + if (anyMatch === true) { + value = er(value); + } else { + value = '^' + er(value); + if (exactMatch === true) { + value += '$'; + } + } + value = new RegExp(value, caseSensitive ? '' : 'i'); + } + return value; + }, - /** - * 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, + + 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; + } +}); - /** - * 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, +Ext.util.MixedCollection.prototype.get = Ext.util.MixedCollection.prototype.item; - /** - * 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, +Ext.AbstractManager = Ext.extend(Object, { + typeName: 'type', + + constructor: function(config) { + Ext.apply(this, config || {}); + + + this.all = new Ext.util.MixedCollection(); + + this.types = {}; + }, + + + get : function(id){ + return this.all.get(id); + }, + + + register: function(item) { + this.all.add(item); + }, + + + unregister: function(item) { + this.all.remove(item); + }, + + + registerType : function(type, cls){ + this.types[type] = cls; + cls[this.typeName] = type; + }, + + + isRegistered : function(type){ + return this.types[type] !== undefined; + }, + + + create: function(config, defaultType) { + var type = config[this.typeName] || config.type || defaultType, + Constructor = this.types[type]; + + if (Constructor == undefined) { + throw new Error(String.format("The '{0}' type has not been registered with this manager", type)); + } + + return new Constructor(config); + }, + + + onAvailable : function(id, fn, scope){ + var all = this.all; + + all.on("add", function(index, o){ + if (o.id == id) { + fn.call(scope || o, o); + all.un("add", fn, scope); + } + }); + } +}); +Ext.util.Format = function() { + var trimRe = /^\s+|\s+$/g, + stripTagsRE = /<\/?[^>]+>/gi, + stripScriptsRe = /(?:)((\n|\r|.)*?)(?:<\/script>)/ig, + nl2brRe = /\r?\n/g; - /** - * The availabe property is false until the linked dom element is accessible. - * @property available - * @type boolean - */ - available: false, + return { + + 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; + }, - /** - * 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, + + undef : function(value) { + return value !== undefined ? value : ""; + }, - /** - * Code that executes immediately before the startDrag event - * @method b4StartDrag - * @private - */ - b4StartDrag: function(x, y) { }, + + defaultValue : function(value, defaultValue) { + return value !== undefined && value !== '' ? value : defaultValue; + }, - /** - * 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 */ }, + + htmlEncode : function(value) { + return !value ? value : String(value).replace(/&/g, "&").replace(/>/g, ">").replace(/").replace(/</g, "<").replace(/"/g, '"').replace(/&/g, "&"); + }, - /** - * Abstract method called during the onMouseMove event while dragging an - * object. - * @method onDrag - * @param {Event} e the mousemove event - */ - onDrag: function(e) { /* override this */ }, + + trim : function(value) { + return String(value).replace(trimRe, ""); + }, - /** - * 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 */ }, + + substr : function(value, start, length) { + return String(value).substr(start, length); + }, - /** - * Code that executes immediately before the onDragOver event - * @method b4DragOver - * @private - */ - b4DragOver: function(e) { }, + + lowercase : function(value) { + return String(value).toLowerCase(); + }, - /** - * 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 */ }, + + uppercase : function(value) { + return String(value).toUpperCase(); + }, - /** - * Code that executes immediately before the onDragOut event - * @method b4DragOut - * @private - */ - b4DragOut: function(e) { }, + + capitalize : function(value) { + return !value ? value : value.charAt(0).toUpperCase() + value.substr(1).toLowerCase(); + }, - /** - * 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 */ }, + + 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); + } + }, - /** - * Code that executes immediately before the onDragDrop event - * @method b4DragDrop - * @private - */ - b4DragDrop: function(e) { }, + + 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; + }, - /** - * 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 */ }, + + date : function(v, format) { + if (!v) { + return ""; + } + if (!Ext.isDate(v)) { + v = new Date(Date.parse(v)); + } + return v.dateFormat(format || "m/d/Y"); + }, - /** - * 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 */ }, + + dateRenderer : function(format) { + return function(v) { + return Ext.util.Format.date(v, format); + }; + }, - /** - * Code that executes immediately before the endDrag event - * @method b4EndDrag - * @private - */ - b4EndDrag: function(e) { }, + + stripTags : function(v) { + return !v ? v : String(v).replace(stripTagsRE, ""); + }, - /** - * Fired when we are done dragging the object - * @method endDrag - * @param {Event} e the mouseup event - */ - endDrag: function(e) { /* override this */ }, + + stripScripts : function(v) { + return !v ? v : String(v).replace(stripScriptsRe, ""); + }, - /** - * Code executed immediately before the onMouseDown event - * @method b4MouseDown - * @param {Event} e the mousedown event - * @private - */ - b4MouseDown: function(e) { }, + + 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"; + } + }, - /** - * 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 */ }, + + math : function(){ + var fns = {}; + + return function(v, a){ + if (!fns[a]) { + fns[a] = new Function('v', 'return v ' + a + ';'); + } + return fns[a](v); + }; + }(), - /** - * 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 */ }, + + 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; + }, - /** - * 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: -
    
    - var dd = new Ext.dd.DDProxy("dragDiv1", "proxytest",
    -                { dragElId: "existingProxyDiv" });
    - dd.startDrag = function(){
    -     this.constrainTo("parent-id");
    - };
    - 
    - * Or you can initalize it using the {@link Ext.Element} object: -
    
    - Ext.get("dragDiv1").initDDProxy("proxytest", {dragElId: "existingProxyDiv"}, {
    -     startDrag : function(){
    -         this.constrainTo("parent-id");
    -     }
    - });
    - 
    - * @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(typeof pad == "number"){ - pad = {left: pad, right:pad, top:pad, bottom:pad}; - } - pad = pad || this.defaultPadding; - var b = Ext.get(this.getEl()).getBox(); - var ce = Ext.get(constrainTo); - var s = ce.getScroll(); - var 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}; - } + + 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 topSpace = b.y - c.y; - var leftSpace = b.x - c.x; + var hasComma = format.indexOf(comma) != -1, + psplit = (i18n ? format.replace(/[^\d\,]/g, '') : format.replace(/[^\d\.]/g, '')).split(dec); - 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 - ); - }, + 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); + } - /** - * 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); - } + var fnum = v.toString(); - return this._domRef; - }, + psplit = fnum.split('.'); - /** - * 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); - }, + if (hasComma) { + var cnum = psplit[0], + parr = [], + j = cnum.length, + m = Math.floor(j / 3), + n = cnum.length % 3 || 3, + i; - /** - * 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); - }, + for (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]; + } + } - /** - * 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) { + return (neg ? '-' : '') + format.replace(/[\d,?\.?]+/, fnum); + }, - // configuration attributes - this.config = config || {}; + + numberRenderer : function(format) { + return function(v) { + return Ext.util.Format.number(v, format); + }; + }, - // create a local reference to the drag and drop manager - this.DDM = Ext.dd.DDM; - // initialize the groups array - this.groups = {}; + + plural : function(v, s, p) { + return v +' ' + (v == 1 ? s : (p ? p : s+'s')); + }, - // 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); + + nl2br : function(v) { + return Ext.isEmpty(v) ? '' : v.replace(nl2brRe, '
    '); } + }; +}(); - // set the id - this.id = id; - - // add to an interaction group - this.addToGroup((sGroup) ? sGroup : "default"); +Ext.XTemplate = function(){ + Ext.XTemplate.superclass.constructor.apply(this, arguments); - // 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; + var me = this, + s = me.html, + re = /]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/, + nameRe = /^]*?for="(.*?)"/, + ifRe = /^]*?if="(.*?)"/, + execRe = /^]*?exec="(.*?)"/, + m, + id = 0, + tpls = [], + VALUES = 'values', + PARENT = 'parent', + XINDEX = 'xindex', + XCOUNT = 'xcount', + RETURN = 'return ', + WITHVALUES = 'with(values){ '; - // the linked element is the element that gets dragged by default - this.setDragElId(id); + s = ['', s, ''].join(''); - // by default, clicked anchors will not start drag operations. - this.invalidHandleTypes = { A: "A" }; - this.invalidHandleIds = {}; - this.invalidHandleClasses = []; + 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] : ''; - this.applyConfig(); + 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, { + + re : /\{([\w-\.\#]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?(\s?[\+\-\*\\]\s?[\d\.\+\-\*\\\(\)]+)?\}/g, + + codeRe : /\{\[((?:\\\]|.|\n)*?)\]\}/g, - this.handleOnAvailable(); + + 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); }, - /** - * 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() { + + compileTpl : function(tpl){ + var fm = Ext.util.Format, + useF = this.disableFormats !== true, + sep = Ext.isGecko ? "+" : ",", + body; - // 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); + 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){ + + return "'" + sep + '(' + code.replace(/\\'/g, "'") + ')' + sep + "'"; + } - /** - * Executed when the linked element is available - * @method handleOnAvailable - * @private - */ - handleOnAvailable: function() { - this.available = true; - this.resetConstraints(); - this.onAvailable(); + + 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; }, - /** - * 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]; - } + + applyTemplate : function(values){ + return this.master.compiled.call(this, values, {}, 1, 1); }, - /** - * 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(); + + compile : function(){return this;} - if (!this.DDM.verifyEl(el)) { - return; - } + + + - var dx = diffX || 0; - var dy = diffY || 0; +}); - var p = Dom.getXY( el ); +Ext.XTemplate.prototype.apply = Ext.XTemplate.prototype.applyTemplate; - this.initPageX = p[0] - dx; - this.initPageY = p[1] - dy; - this.lastPageX = p[0]; - this.lastPageY = p[1]; +Ext.XTemplate.from = function(el){ + el = Ext.getDom(el); + return new Ext.XTemplate(el.value || el.innerHTML); +}; +Ext.util.CSS = function(){ + var rules = null; + var doc = document; - this.setStartPosition(p); - }, + var camelRe = /(-[a-z])/gi; + var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); }; - /** - * 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; + return { + + 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; + }, + + + removeStyleSheet : function(id){ + var existing = doc.getElementById(id); + if(existing){ + existing.parentNode.removeChild(existing); + } + }, + + + 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); + }, + + + refreshCache : function(){ + return this.getRules(true); + }, + + + cacheStyleSheet : function(ss){ + if(!rules){ + rules = {}; + } + try{ + var ssRules = ss.cssRules || ss.rules; + for(var j = ssRules.length-1; j >= 0; --j){ + rules[ssRules[j].selectorText.toLowerCase()] = ssRules[j]; + } + }catch(e){} + }, + + + 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; + }, + + + 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; + }, + + + + 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; + } + }; +}(); +Ext.util.ClickRepeater = Ext.extend(Ext.util.Observable, { + + constructor : function(el, config){ + this.el = Ext.get(el); + this.el.unselectable(); - this.startPageX = p[0]; - this.startPageY = p[1]; - }, + Ext.apply(this, config); - /** - * 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); - }, + this.addEvents( + + "mousedown", + + "click", + + "mouseup" + ); - /** - * 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]; + if(!this.disabled){ + this.disabled = true; + this.enable(); } - this.DDM.removeDDFromGroup(this, sGroup); - }, + + if(this.handler){ + this.on("click", this.handler, this.scope || this); + } - /** - * 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; + Ext.util.ClickRepeater.superclass.constructor.call(this); }, + + interval : 20, + delay: 250, + preventDefault : true, + stopDefault : false, + timer : 0, - /** - * 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); + + 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.handleElId = id; - this.DDM.regHandle(this.id, id); + this.disabled = false; }, - /** - * 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); + + disable: function( 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(); } - 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(); + this.disabled = true; }, - /** - * 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); + + setDisabled: function(disabled){ + this[disabled ? 'disable' : 'enable'](); }, - /** - * 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; + eventOptions: function(e){ + if(this.preventDefault){ + e.preventDefault(); } - - if (this.isLocked()) { - return; + if(this.stopDefault){ + e.stopEvent(); } + }, - 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(); + + destroy : function() { + this.disable(true); + Ext.destroy(this.el); + this.purgeListeners(); + }, + handleDblClick : function(e){ + clearTimeout(this.timer); + this.el.blur(); - this.b4MouseDown(e); - this.onMouseDown(e); + this.fireEvent("mousedown", this, e); + this.fireEvent("click", this, e); + }, - this.DDM.handleMouseDown(e, this); + + handleMouseDown : function(e){ + clearTimeout(this.timer); + this.el.blur(); + if(this.pressClass){ + this.el.addClass(this.pressClass); + } + this.mousedownTime = new Date(); - this.DDM.stopEvent(e); - } else { + Ext.getDoc().on("mouseup", this.handleMouseUp, this); + this.el.on("mouseout", this.handleMouseOut, this); + this.fireEvent("mousedown", this, e); + this.fireEvent("click", this, e); - } + + if (this.accelerate) { + this.delay = 400; } + this.timer = this.click.defer(this.delay || this.interval, this, [e]); }, - clickValidator: function(e) { - var target = e.getTarget(); - return ( this.isValidHandleChild(target) && - (this.id == this.handleElId || - this.DDM.handleWasClicked(target, this.id)) ); + + click : function(e){ + this.fireEvent("click", this, e); + this.timer = this.click.defer(this.accelerate ? + this.easeOutExpo(this.mousedownTime.getElapsed(), + 400, + -390, + 12000) : + this.interval, this, [e]); }, - /** - * 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; + easeOutExpo : function (t, b, c, d) { + return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b; }, - /** - * 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); + + handleMouseOut : function(){ + clearTimeout(this.timer); + if(this.pressClass){ + this.el.removeClass(this.pressClass); } - this.invalidHandleIds[id] = id; + this.el.on("mouseover", this.handleMouseReturn, this); }, - /** - * 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); + + handleMouseReturn : function(){ + this.el.un("mouseover", this.handleMouseReturn, this); + if(this.pressClass){ + this.el.addClass(this.pressClass); + } + this.click(); }, - /** - * 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]; - }, + + handleMouseUp : function(e){ + 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, e); + } +}); +Ext.KeyNav = function(el, config){ + this.el = Ext.get(el); + Ext.apply(this, config); + if(!this.disabled){ + this.disabled = true; + this.enable(); + } +}; - /** - * 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]; - }, +Ext.KeyNav.prototype = { + + disabled : false, + + defaultEventAction: "stopEvent", + + forceKeyDown : false, - /** - * 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= 37 && k <= 40) { + + + e.stopEvent(); + } + }, + + + destroy: function(){ + this.disable(); + }, - for (var i = this.initPageX; i >= this.minX; i = i - iTickSize) { - if (!tickMap[i]) { - this.xTicks[this.xTicks.length] = i; - tickMap[i] = true; + + enable: function() { + if (this.disabled) { + if (Ext.isSafari2) { + + this.el.on('keyup', this.stopKeyUp, this); } + + this.el.on(this.isKeydown()? 'keydown' : 'keypress', this.relay, this); + this.disabled = false; } + }, - for (i = this.initPageX; i <= this.maxX; i = i + iTickSize) { - if (!tickMap[i]) { - this.xTicks[this.xTicks.length] = i; - tickMap[i] = true; + + disable: function() { + if (!this.disabled) { + if (Ext.isSafari2) { + + this.el.un('keyup', this.stopKeyUp, this); } - } - this.xTicks.sort(this.DDM.numericSort) ; + this.el.un(this.isKeydown()? 'keydown' : 'keypress', this.relay, this); + this.disabled = true; + } }, + + + setDisabled : function(disabled){ + this[disabled ? "disable" : "enable"](); + }, + + + isKeydown: function(){ + return this.forceKeyDown || Ext.EventManager.useKeydown; + } +}; - /** - * 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; +Ext.KeyMap = function(el, config, eventName){ + this.el = Ext.get(el); + this.eventName = eventName || "keydown"; + this.bindings = []; + if(config){ + this.addBinding(config); + } + this.enable(); +}; - var tickMap = {}; +Ext.KeyMap.prototype = { + + stopEvent : false, - for (var i = this.initPageY; i >= this.minY; i = i - iTickSize) { - if (!tickMap[i]) { - this.yTicks[this.yTicks.length] = i; - tickMap[i] = true; - } + + 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; - for (i = this.initPageY; i <= this.maxY; i = i + iTickSize) { - if (!tickMap[i]) { - this.yTicks[this.yTicks.length] = i; - tickMap[i] = true; + 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; } - - 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; + 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); + }, + + + 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; }, - /** - * 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(); + + 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 + }); }, - /** - * Clears any tick interval defined for this instance - * @method clearTicks - */ - clearTicks: function() { - this.xTicks = null; - this.yTicks = null; - this.xTickSize = 0; - this.yTickSize = 0; - }, + + handleKeyDown : function(e){ + if(this.enabled){ + var b = this.bindings; + for(var i = 0, len = b.length; i < len; i++){ + b[i].call(this, e); + } + } + }, - /** - * 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; + + isEnabled : function(){ + return this.enabled; + }, - this.minY = this.initPageY - iUp; - this.maxY = this.initPageY + iDown; - if (iTickSize) { this.setYTicks(this.initPageY, iTickSize); } + + enable: function(){ + if(!this.enabled){ + this.el.on(this.eventName, this.handleKeyDown, this); + this.enabled = true; + } + }, - this.constrainY = true; + + disable: function(){ + if(this.enabled){ + this.el.removeListener(this.eventName, this.handleKeyDown, this); + this.enabled = false; + } + }, + + + setDisabled : function(disabled){ + this[disabled ? "disable" : "enable"](); + } +}; +Ext.util.TextMetrics = function(){ + var shared; + return { + + 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); + }, - }, + + createInstance : function(el, fixedWidth){ + return Ext.util.TextMetrics.Instance(el, fixedWidth); + } + }; +}(); - /** - * resetConstraints must be called if you manually reposition a dd element. - * @method resetConstraints - * @param {boolean} maintainOffset - */ - resetConstraints: function() { +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); + } - // 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; + var instance = { + + getSize : function(text){ + ml.update(text); + var s = ml.getSize(); + ml.update(''); + return s; + }, - this.setInitPosition(dx, dy); + + bind : function(el){ + ml.setStyle( + Ext.fly(el).getStyles('font-size','font-style', 'font-weight', 'font-family','line-height', 'text-transform', 'letter-spacing') + ); + }, - // This is the first time we have detected the element's position - } else { - this.setInitPosition(); - } + + setFixedWidth : function(width){ + ml.setWidth(width); + }, - if (this.constrainX) { - this.setXConstraint( this.leftConstraint, - this.rightConstraint, - this.xTickSize ); - } + + getWidth : function(text){ + ml.dom.style.width = 'auto'; + return this.getSize(text).width; + }, - if (this.constrainY) { - this.setYConstraint( this.topConstraint, - this.bottomConstraint, - this.yTickSize ); + + getHeight : function(text){ + return this.getSize(text).height; } - }, + }; - /** - * 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) { + instance.bind(bindTo); - 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= val) { - var diff1 = val - tickArray[i]; - var diff2 = tickArray[next] - val; - return (diff2 > diff1) ? tickArray[i] : tickArray[next]; - } - } + return instance; +}; - // The value is larger than the last tick, so we return the last - // tick. - return tickArray[tickArray.length - 1]; +Ext.Element.addMethods({ + + 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); + } +}); + +Ext.util.Cookies = { + + 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" : ""); + }, + + + 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; }, - /** - * toString method - * @method toString - * @return {string} string representation of the dd obj - */ - toString: function() { - return ("DragDrop " + this.id); + + clear : function(name){ + if(Ext.util.Cookies.get(name)){ + document.cookie = name + "=" + "; expires=Thu, 01-Jan-70 00:00:01 GMT"; + } + }, + + getCookieVal : function(offset){ + var endstr = document.cookie.indexOf(";", offset); + if(endstr == -1){ + endstr = document.cookie.length; + } + return unescape(document.cookie.substring(offset, endstr)); } - +}; +Ext.handleError = function(e) { + throw e; }; -})(); -/** - * 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: 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: 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, +Ext.Error = function(message) { + + this.message = (this.lang[message]) ? this.lang[message] : message; +}; - /** - * 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, +Ext.Error.prototype = new Error(); +Ext.apply(Ext.Error.prototype, { + + lang: {}, - /** - * Internal flag that is set to true when drag and drop has been - * intialized - * @property initialized - * @private - * @static - */ - initialized: false, + name: 'Ext.Error', + + getName : function() { + return this.name; + }, + + getMessage : function() { + return this.message; + }, + + toJson : function() { + return Ext.encode(this); + } +}); - /** - * All drag and drop can be disabled. - * @property locked - * @private - * @static - */ - locked: false, +Ext.ComponentMgr = function(){ + var all = new Ext.util.MixedCollection(); + var types = {}; + var ptypes = {}; - /** - * Called the first time an element is registered. - * @method init - * @private - * @static - */ - init: function() { - this.initialized = true; + return { + + register : function(c){ + all.add(c); }, - /** - * 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, + + unregister : function(c){ + all.remove(c); + }, - /** - * The current drag and drop mode. Default: POINT - * @property mode - * @type int - * @static - */ - mode: 0, + + get : function(id){ + return all.get(id); + }, - /** - * 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); + + 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); } - } + }); }, - /** - * Drag and drop initialization. Sets up the global event handlers - * @method _onLoad - * @private - * @static - */ - _onLoad: function() { - - this.init(); - + + all : all, + + + types : types, + + + ptypes: ptypes, + + + isRegistered : function(xtype){ + return types[xtype] !== undefined; + }, + + + isPluginRegistered : function(ptype){ + return ptypes[ptype] !== undefined; + }, - 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); + + registerType : function(xtype, cls){ + types[xtype] = cls; + cls.xtype = xtype; + }, + + create : function(config, defaultType){ + return config.render ? config : new types[config.xtype || defaultType](config); }, - /** - * Reset constraints on all drag and drop objs - * @method _onResize - * @private - * @static - */ - _onResize: function(e) { - this._execOnAll("resetConstraints", []); + + registerPlugin : function(ptype, cls){ + ptypes[ptype] = cls; + cls.ptype = ptype; }, - /** - * Lock all drag and drop functionality - * @method lock - * @static - */ - lock: function() { this.locked = true; }, + + createPlugin : function(config, defaultType){ + var PluginCls = ptypes[config.ptype || defaultType]; + if (PluginCls.init) { + return PluginCls; + } else { + return new PluginCls(config); + } + } + }; +}(); - /** - * 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; }, +Ext.reg = Ext.ComponentMgr.registerType; - /** - * 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: {}, +Ext.preg = Ext.ComponentMgr.registerPlugin; - /** - * 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, +Ext.create = Ext.ComponentMgr.create; +Ext.Component = function(config){ + config = config || {}; + if(config.initialConfig){ + if(config.isAction){ + this.baseAction = config; + } + config = config.initialConfig; + }else if(config.tagName || config.dom || Ext.isString(config)){ + config = {applyTo: config, id: config.id || config}; + } - /** - * 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=1000 - * @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, + + this.initialConfig = config; - /** - * 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(); } + Ext.apply(this, config); + this.addEvents( + + 'added', + + 'disable', + + 'enable', + + 'beforeshow', + + 'show', + + 'beforehide', + + 'hide', + + 'removed', + + 'beforerender', + + 'render', + + 'afterrender', + + 'beforedestroy', + + 'destroy', + + 'beforestaterestore', + + 'staterestore', + + 'beforestatesave', + + 'statesave' + ); + this.getId(); + Ext.ComponentMgr.register(this); + Ext.Component.superclass.constructor.call(this); - if (!this.ids[sGroup]) { - this.ids[sGroup] = {}; - } - this.ids[sGroup][oDD.id] = oDD; - }, + if(this.baseAction){ + this.baseAction.addComponent(this); + } - /** - * 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] = {}; - } + this.initComponent(); - var obj = this.ids[sGroup]; - if (obj && obj[oDD.id]) { - delete obj[oDD.id]; + 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); + } + } - /** - * 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]; - }, + if(this.stateful !== false){ + this.initState(); + } - /** - * 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; - }, + if(this.applyTo){ + this.applyToMarkup(this.applyTo); + delete this.applyTo; + }else if(this.renderTo){ + this.render(this.renderTo); + delete this.renderTo; + } +}; - /** - * 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; - } - } - } +Ext.Component.AUTO_ID = 1000; - return oDDs; - }, +Ext.extend(Ext.Component, Ext.util.Observable, { + + + + + + + - /** - * Returns true if the specified dd target is a legal target for - * the specifice drag obj - * @method isLegalTarget - * @param {DragDrop} the drag obj - * @param {DragDrop} 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
- * See {@link Ext.form.Checkbox#setValue} for additional information. - * @param {Mixed} id The checkbox to check, or as described by example shown. - * @param {Boolean} value (optional) The value to set the item. - * @return {Ext.form.CheckboxGroup} this - */ - setValue: function(){ - if(this.rendered){ - this.onSetValue.apply(this, arguments); - }else{ - this.buffered = true; - this.value = arguments; - } - return this; - }, - - onSetValue: function(id, value){ - if(arguments.length == 1){ - if(Ext.isArray(id)){ - // an array of boolean values - Ext.each(id, function(val, idx){ - var item = this.items.itemAt(idx); - if(item){ - item.setValue(val); - } - }, this); - }else if(Ext.isObject(id)){ - // set of name/value pairs - for(var i in id){ - var f = this.getBox(i); - if(f){ - f.setValue(id[i]); - } - } - }else{ - this.setValueForItem(id); - } - }else{ - var f = this.getBox(id); - if(f){ - f.setValue(value); - } - } - }, - - // private - onDestroy: function(){ - Ext.destroy(this.panel); - Ext.form.CheckboxGroup.superclass.onDestroy.call(this); - - }, - - setValueForItem : function(val){ - val = String(val).split(','); - this.eachItem(function(item){ - if(val.indexOf(item.inputValue)> -1){ - item.setValue(true); - } - }); - }, - - // private - getBox : function(id){ - var box = null; - this.eachItem(function(f){ - if(id == f || f.dataIndex == id || f.id == id || f.getName() == id){ - box = f; - return false; - } - }); - return box; - }, - - /** - * Gets an array of the selected {@link Ext.form.Checkbox} in the group. - * @return {Array} An array of the selected checkboxes. - */ - getValue : function(){ - var out = []; - this.eachItem(function(item){ - if(item.checked){ - out.push(item); - } - }); - return out; - }, - - // private - eachItem: function(fn){ - if(this.items && this.items.each){ - this.items.each(fn, this); - } - }, - - /** - * @cfg {String} name - * @hide - */ - - /** - * @method getRawValue - * @hide - */ - getRawValue : Ext.emptyFn, - - /** - * @method setRawValue - * @hide - */ - setRawValue : Ext.emptyFn - -}); - -Ext.reg('checkboxgroup', Ext.form.CheckboxGroup); -/** - * @class Ext.form.Radio - * @extends Ext.form.Checkbox - * Single radio field. Same as Checkbox, but provided as a convenience for automatically setting the input type. - * Radio grouping is handled automatically by the browser if you give each radio in a group the same name. - * @constructor - * Creates a new Radio - * @param {Object} config Configuration options - * @xtype radio - */ -Ext.form.Radio = Ext.extend(Ext.form.Checkbox, { - inputType: 'radio', - /** - * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide - * @method - */ - markInvalid : Ext.emptyFn, - /** - * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide - * @method - */ - clearInvalid : Ext.emptyFn, +Ext.reg('pivotgrid', Ext.grid.PivotGrid); - /** - * If this radio is part of a group, it will return the selected value - * @return {String} - */ - getGroupValue : function(){ - var p = this.el.up('form') || Ext.getBody(); - var c = p.child('input[name='+this.el.dom.name+']:checked', true); - return c ? c.value : null; - }, - // private - onClick : function(){ - if(this.el.dom.checked != this.checked){ - var els = this.getCheckEl().select('input[name=' + this.el.dom.name + ']'); - els.each(function(el){ - if(el.dom.id == this.id){ - this.setValue(true); - }else{ - Ext.getCmp(el.dom.id).setValue(false); - } - }, this); - } - }, +Ext.grid.PivotAggregatorMgr = new Ext.AbstractManager(); - /** - * Sets either the checked/unchecked status of this Radio, or, if a string value - * is passed, checks a sibling Radio of the same name whose value is the value specified. - * @param value {String/Boolean} Checked value, or the value of the sibling radio button to check. - * @return {Ext.form.Field} this - */ - setValue : function(v){ - if (typeof v == 'boolean') { - Ext.form.Radio.superclass.setValue.call(this, v); - } else { - var r = this.getCheckEl().child('input[name=' + this.el.dom.name + '][value=' + v + ']', true); - if(r){ - Ext.getCmp(r.id).setValue(true); - } - } - return this; - }, +Ext.grid.PivotAggregatorMgr.registerType('sum', function(records, measure) { + var length = records.length, + total = 0, + i; - // private - getCheckEl: function(){ - if(this.inGroup){ - return this.el.up('.x-form-radio-group') - } - return this.el.up('form') || Ext.getBody(); + for (i = 0; i < length; i++) { + total += records[i].get(measure); } + + return total; }); -Ext.reg('radio', Ext.form.Radio); -/** - * @class Ext.form.RadioGroup - * @extends Ext.form.CheckboxGroup - * A grouping container for {@link Ext.form.Radio} controls. - * @constructor - * Creates a new RadioGroup - * @param {Object} config Configuration options - * @xtype radiogroup - */ -Ext.form.RadioGroup = Ext.extend(Ext.form.CheckboxGroup, { - /** - * @cfg {Boolean} allowBlank True to allow every item in the group to be blank (defaults to true). - * If allowBlank = false and no items are selected at validation time, {@link @blankText} will - * be used as the error text. - */ - allowBlank : true, - /** - * @cfg {String} blankText Error text to display if the {@link #allowBlank} validation fails - * (defaults to 'You must select one item in this group') - */ - blankText : 'You must select one item in this group', - - // private - defaultType : 'radio', - - // private - groupCls : 'x-form-radio-group', - - /** - * @event change - * Fires when the state of a child radio changes. - * @param {Ext.form.RadioGroup} this - * @param {Ext.form.Radio} checked The checked radio - */ - - /** - * Gets the selected {@link Ext.form.Radio} in the group, if it exists. - * @return {Ext.form.Radio} The selected radio. - */ - getValue : function(){ - var out = null; - this.eachItem(function(item){ - if(item.checked){ - out = item; - return false; - } - }); - return out; - }, - - /** - * Sets the checked radio in the group. - * @param {String/Ext.form.Radio} id The radio to check. - * @param {Boolean} value The value to set the radio. - * @return {Ext.form.RadioGroup} this - */ - onSetValue : function(id, value){ - if(arguments.length > 1){ - var f = this.getBox(id); - if(f){ - f.setValue(value); - if(f.checked){ - this.eachItem(function(item){ - if (item !== f){ - item.setValue(false); - } - }); - } - } - }else{ - this.setValueForItem(id); - } - }, - - setValueForItem : function(val){ - val = String(val).split(',')[0]; - this.eachItem(function(item){ - item.setValue(val == item.inputValue); - }); - }, - - // private - fireChecked : function(){ - if(!this.checkTask){ - this.checkTask = new Ext.util.DelayedTask(this.bufferChecked, this); - } - this.checkTask.delay(10); - }, - - // private - bufferChecked : function(){ - var out = null; - this.eachItem(function(item){ - if(item.checked){ - out = item; - return false; - } - }); - this.fireEvent('change', this, out); - }, - - onDestroy : function(){ - if(this.checkTask){ - this.checkTask.cancel(); - this.checkTask = null; - } - Ext.form.RadioGroup.superclass.onDestroy.call(this); - } - -}); - -Ext.reg('radiogroup', Ext.form.RadioGroup); -/** - * @class Ext.form.Hidden - * @extends Ext.form.Field - * A basic hidden field for storing hidden values in forms that need to be passed in the form submit. - * @constructor - * Create a new Hidden field. - * @param {Object} config Configuration options - * @xtype hidden - */ -Ext.form.Hidden = Ext.extend(Ext.form.Field, { - // private - inputType : 'hidden', - - // private - onRender : function(){ - Ext.form.Hidden.superclass.onRender.apply(this, arguments); - }, - - // private - initEvents : function(){ - this.originalValue = this.getValue(); - }, - - // These are all private overrides - setSize : Ext.emptyFn, - setWidth : Ext.emptyFn, - setHeight : Ext.emptyFn, - setPosition : Ext.emptyFn, - setPagePosition : Ext.emptyFn, - markInvalid : Ext.emptyFn, - clearInvalid : Ext.emptyFn -}); -Ext.reg('hidden', Ext.form.Hidden);/** - * @class Ext.form.BasicForm - * @extends Ext.util.Observable - *

Encapsulates the DOM <form> element at the heart of the {@link Ext.form.FormPanel FormPanel} class, and provides - * input field management, validation, submission, and form loading services.

- *

By default, Ext Forms are submitted through Ajax, using an instance of {@link Ext.form.Action.Submit}. - * To enable normal browser submission of an Ext Form, use the {@link #standardSubmit} config option.

- *

File Uploads

- *

{@link #fileUpload File uploads} are not performed using Ajax submission, that - * is they are not performed using XMLHttpRequests. Instead the form is submitted in the standard - * manner with the DOM <form> element temporarily modified to have its - * target set to refer - * to a dynamically generated, hidden <iframe> which is inserted into the document - * but removed after the return data has been gathered.

- *

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 - * Content-Type header - * must be set to "text/html" in order to tell the browser to insert the text unchanged into the document body.

- *

Characters which are significant to an HTML parser must be sent as HTML entities, so encode - * "<" as "&lt;", "&" as "&amp;" etc.

- *

The response text is retrieved from the document, and a fake XMLHttpRequest object - * is created containing a responseText property in order to conform to the - * requirements of event handlers and callbacks.

- *

Be aware that file upload packets are sent with the content type multipart/form - * and some server technologies (notably JEE) may require some custom processing in order to - * retrieve parameter names and parameter values from the packet content.

- * @constructor - * @param {Mixed} el The form element or its id - * @param {Object} config Configuration options - */ -Ext.form.BasicForm = function(el, config){ - Ext.apply(this, config); - if(Ext.isString(this.paramOrder)){ - this.paramOrder = this.paramOrder.split(/[\s,|]/); + +Ext.grid.PivotAggregatorMgr.registerType('avg', function(records, measure) { + var length = records.length, + total = 0, + i; + + for (i = 0; i < length; i++) { + total += records[i].get(measure); } - /** - * @property items - * A {@link Ext.util.MixedCollection MixedCollection) containing all the Ext.form.Fields in this form. - * @type MixedCollection - */ - this.items = new Ext.util.MixedCollection(false, function(o){ - return o.getItemId(); - }); - this.addEvents( - /** - * @event beforeaction - * Fires before any action is performed. Return false to cancel the action. - * @param {Form} this - * @param {Action} action The {@link Ext.form.Action} to be performed - */ - 'beforeaction', - /** - * @event actionfailed - * Fires when an action fails. - * @param {Form} this - * @param {Action} action The {@link Ext.form.Action} that failed - */ - 'actionfailed', - /** - * @event actioncomplete - * Fires when an action is completed. - * @param {Form} this - * @param {Action} action The {@link Ext.form.Action} that completed - */ - 'actioncomplete' - ); + + return (total / length) || 'n/a'; +}); - if(el){ - this.initEl(el); +Ext.grid.PivotAggregatorMgr.registerType('min', function(records, measure) { + var data = [], + length = records.length, + i; + + for (i = 0; i < length; i++) { + data.push(records[i].get(measure)); } - Ext.form.BasicForm.superclass.constructor.call(this); -}; + + return Math.min.apply(this, data) || 'n/a'; +}); -Ext.extend(Ext.form.BasicForm, Ext.util.Observable, { - /** - * @cfg {String} method - * The request method to use (GET or POST) for form actions if one isn't supplied in the action options. - */ - /** - * @cfg {DataReader} reader - * An Ext.data.DataReader (e.g. {@link Ext.data.XmlReader}) to be used to read - * data when executing 'load' actions. This is optional as there is built-in - * support for processing JSON. For additional information on using an XMLReader - * see the example provided in examples/form/xml-form.html. - */ - /** - * @cfg {DataReader} errorReader - *

An Ext.data.DataReader (e.g. {@link Ext.data.XmlReader}) to be used to - * read field error messages returned from 'submit' actions. This is optional - * as there is built-in support for processing JSON.

- *

The Records which provide messages for the invalid Fields must use the - * Field name (or id) as the Record ID, and must contain a field called 'msg' - * which contains the error message.

- *

The errorReader does not have to be a full-blown implementation of a - * DataReader. It simply needs to implement a read(xhr) function - * which returns an Array of Records in an object with the following - * structure:


-{
-    records: recordArray
-}
-
- */ - /** - * @cfg {String} url - * The URL to use for form actions if one isn't supplied in the - * {@link #doAction doAction} options. - */ - /** - * @cfg {Boolean} fileUpload - * Set to true if this form is a file upload. - *

File uploads are not performed using normal 'Ajax' techniques, that is they are not - * performed using XMLHttpRequests. Instead the form is submitted in the standard manner with the - * DOM <form> element temporarily modified to have its - * target set to refer - * to a dynamically generated, hidden <iframe> which is inserted into the document - * but removed after the return data has been gathered.

- *

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 - * Content-Type header - * must be set to "text/html" in order to tell the browser to insert the text unchanged into the document body.

- *

Characters which are significant to an HTML parser must be sent as HTML entities, so encode - * "<" as "&lt;", "&" as "&amp;" etc.

- *

The response text is retrieved from the document, and a fake XMLHttpRequest object - * is created containing a responseText property in order to conform to the - * requirements of event handlers and callbacks.

- *

Be aware that file upload packets are sent with the content type multipart/form - * and some server technologies (notably JEE) may require some custom processing in order to - * retrieve parameter names and parameter values from the packet content.

- */ - /** - * @cfg {Object} baseParams - *

Parameters to pass with all requests. e.g. baseParams: {id: '123', foo: 'bar'}.

- *

Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.

- */ - /** - * @cfg {Number} timeout Timeout for form actions in seconds (default is 30 seconds). - */ - timeout: 30, +Ext.grid.PivotAggregatorMgr.registerType('max', function(records, measure) { + var data = [], + length = records.length, + i; + + for (i = 0; i < length; i++) { + data.push(records[i].get(measure)); + } + + return Math.max.apply(this, data) || 'n/a'; +}); - /** - * @cfg {Object} api (Optional) If specified load and submit actions will be handled - * with {@link Ext.form.Action.DirectLoad} and {@link Ext.form.Action.DirectSubmit}. - * Methods which have been imported by Ext.Direct can be specified here to load and submit - * forms. - * Such as the following:

-api: {
-    load: App.ss.MyProfile.load,
-    submit: App.ss.MyProfile.submit
-}
-
- *

Load actions can use {@link #paramOrder} or {@link #paramsAsHash} - * to customize how the load method is invoked. - * Submit actions will always use a standard form submit. The formHandler configuration must - * be set on the associated server-side method which has been imported by Ext.Direct

- */ +Ext.grid.PivotAggregatorMgr.registerType('count', function(records, measure) { + return records.length; +}); +Ext.grid.GridView = Ext.extend(Ext.util.Observable, { + + + + + + + + + + + + deferEmptyText : true, + + + scrollOffset : undefined, + + + autoFill : false, + + + forceFit : false, + + + sortClasses : ['sort-asc', 'sort-desc'], + + + sortAscText : 'Sort Ascending', + + + sortDescText : 'Sort Descending', + + + columnsText : 'Columns', + + + selectedRowClass : 'x-grid3-row-selected', + + + borderWidth : 2, + tdClass : 'x-grid3-cell', + hdCls : 'x-grid3-hd', + + + + markDirty : true, + + + cellSelectorDepth : 4, + + + rowSelectorDepth : 10, + + + rowBodySelectorDepth : 10, + + + cellSelector : 'td.x-grid3-cell', + + + rowSelector : 'div.x-grid3-row', + + + rowBodySelector : 'div.x-grid3-row-body', + + + firstRowCls: 'x-grid3-row-first', + lastRowCls: 'x-grid3-row-last', + rowClsRe: /(?:^|\s+)x-grid3-row-(first|last|alt)(?:\s+|$)/g, + + + headerMenuOpenCls: 'x-grid3-hd-menu-open', + + + rowOverCls: 'x-grid3-row-over', + + constructor : function(config) { + Ext.apply(this, config); + + + this.addEvents( + + 'beforerowremoved', + + + 'beforerowsinserted', + + + 'beforerefresh', + + + 'rowremoved', + + + 'rowsinserted', + + + 'rowupdated', + + + 'refresh' + ); + + Ext.grid.GridView.superclass.constructor.call(this); + }, + + + + + masterTpl: new Ext.Template( + '
', + '
', + '
', + '
', + '
{header}
', + '
', + '
', + '
', + '
', + '
{body}
', + '', + '
', + '
', + '
 
', + '
 
', + '
' + ), + + + headerTpl: new Ext.Template( + '', + '', + '{cells}', + '', + '
' + ), + + + bodyTpl: new Ext.Template('{rows}'), + + + cellTpl: new Ext.Template( + '', + '
{value}
', + '' + ), + + + initTemplates : function() { + var templates = this.templates || {}, + template, name, + + headerCellTpl = new Ext.Template( + '', + '
', + this.grid.enableHdMenu ? '' : '', + '{value}', + '', + '
', + '' + ), + + rowBodyText = [ + '', + '', + '
{body}
', + '', + '' + ].join(""), + + innerText = [ + '', + '', + '{cells}', + this.enableRowBody ? rowBodyText : '', + '', + '
' + ].join(""); + + Ext.applyIf(templates, { + hcell : headerCellTpl, + cell : this.cellTpl, + body : this.bodyTpl, + header : this.headerTpl, + master : this.masterTpl, + row : new Ext.Template('
' + innerText + '
'), + rowInner: new Ext.Template(innerText) + }); + + for (name in templates) { + template = templates[name]; + + if (template && Ext.isFunction(template.compile) && !template.compiled) { + template.disableFormats = true; + template.compile(); + } + } - /** - * @cfg {Array/String} paramOrder

A list of params to be executed server side. - * Defaults to undefined. Only used for the {@link #api} - * load configuration.

- *

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:


-paramOrder: ['param1','param2','param3']
-paramOrder: 'param1 param2 param3'
-paramOrder: 'param1,param2,param3'
-paramOrder: 'param1|param2|param'
-     
- */ - paramOrder: undefined, + this.templates = templates; + this.colRe = new RegExp('x-grid3-td-([^\\s]+)', ''); + }, - /** - * @cfg {Boolean} paramsAsHash Only used for the {@link #api} - * load configuration. Send parameters as a collection of named - * arguments (defaults to false). Providing a - * {@link #paramOrder} nullifies this configuration. - */ - paramsAsHash: false, + + fly : function(el) { + if (!this._flyweight) { + this._flyweight = new Ext.Element.Flyweight(document.body); + } + this._flyweight.dom = el; + return this._flyweight; + }, - /** - * @cfg {String} waitTitle - * The default title to show for the waiting message box (defaults to 'Please Wait...') - */ - waitTitle: 'Please Wait...', + + getEditorParent : function() { + return this.scroller.dom; + }, - // private - activeAction : null, + + initElements : function() { + var Element = Ext.Element, + el = Ext.get(this.grid.getGridEl().dom.firstChild), + mainWrap = new Element(el.child('div.x-grid3-viewport')), + mainHd = new Element(mainWrap.child('div.x-grid3-header')), + scroller = new Element(mainWrap.child('div.x-grid3-scroller')); + + if (this.grid.hideHeaders) { + mainHd.setDisplayed(false); + } + + if (this.forceFit) { + scroller.setStyle('overflow-x', 'hidden'); + } + + + + Ext.apply(this, { + el : el, + mainWrap: mainWrap, + scroller: scroller, + mainHd : mainHd, + innerHd : mainHd.child('div.x-grid3-header-inner').dom, + mainBody: new Element(Element.fly(scroller).child('div.x-grid3-body')), + focusEl : new Element(Element.fly(scroller).child('a')), + + resizeMarker: new Element(el.child('div.x-grid3-resize-marker')), + resizeProxy : new Element(el.child('div.x-grid3-resize-proxy')) + }); + + this.focusEl.swallowEvent('click', true); + }, - /** - * @cfg {Boolean} trackResetOnLoad If set to true, {@link #reset}() resets to the last loaded - * or {@link #setValues}() data instead of when the form was first created. Defaults to false. - */ - trackResetOnLoad : false, + + getRows : function() { + return this.hasRows() ? this.mainBody.dom.childNodes : []; + }, - /** - * @cfg {Boolean} standardSubmit - *

If set to true, standard HTML form submits are used instead - * of XHR (Ajax) style form submissions. Defaults to false.

- *

Note: When using standardSubmit, the - * options to {@link #submit} are ignored because - * Ext's Ajax infrastracture is bypassed. To pass extra parameters (e.g. - * baseParams and params), utilize hidden fields - * to submit extra data, for example:

- *

-new Ext.FormPanel({
-    standardSubmit: true,
-    baseParams: {
-        foo: 'bar'
+    
+
+    
+    findCell : function(el) {
+        if (!el) {
+            return false;
+        }
+        return this.fly(el).findParent(this.cellSelector, this.cellSelectorDepth);
     },
-    {@link url}: 'myProcess.php',
-    items: [{
-        xtype: 'textfield',
-        name: 'userName'
-    }],
-    buttons: [{
-        text: 'Save',
-        handler: function(){
-            var fp = this.ownerCt.ownerCt,
-                form = fp.getForm();
-            if (form.isValid()) {
-                // check if there are baseParams and if
-                // hiddent items have been added already
-                if (fp.baseParams && !fp.paramsAdded) {
-                    // add hidden items for all baseParams
-                    for (i in fp.baseParams) {
-                        fp.add({
-                            xtype: 'hidden',
-                            name: i,
-                            value: fp.baseParams[i]
-                        });
-                    }
-                    fp.doLayout();
-                    // set a custom flag to prevent re-adding
-                    fp.paramsAdded = true;
-                }
-                form.{@link #submit}();
+
+    
+    findCellIndex : function(el, requiredCls) {
+        var cell = this.findCell(el),
+            hasCls;
+        
+        if (cell) {
+            hasCls = this.fly(cell).hasClass(requiredCls);
+            if (!requiredCls || hasCls) {
+                return this.getCellIndex(cell);
             }
         }
-    }]
-});
-     * 
- */ - /** - * By default wait messages are displayed with Ext.MessageBox.wait. You can target a specific - * element by passing it or its id or mask the form itself by passing in true. - * @type Mixed - * @property waitMsgTarget - */ + return false; + }, - // private - initEl : function(el){ - this.el = Ext.get(el); - this.id = this.el.id || Ext.id(); - if(!this.standardSubmit){ - this.el.on('submit', this.onSubmit, this); + + getCellIndex : function(el) { + if (el) { + var match = el.className.match(this.colRe); + + if (match && match[1]) { + return this.cm.getIndexById(match[1]); + } } - this.el.addClass('x-form'); + return false; }, - /** - * Get the HTML form Element - * @return Ext.Element - */ - getEl: function(){ - return this.el; + + findHeaderCell : function(el) { + var cell = this.findCell(el); + return cell && this.fly(cell).hasClass(this.hdCls) ? cell : null; }, - // private - onSubmit : function(e){ - e.stopEvent(); + + findHeaderIndex : function(el){ + return this.findCellIndex(el, this.hdCls); }, - // private - destroy: function() { - this.items.each(function(f){ - Ext.destroy(f); - }); - if(this.el){ - this.el.removeAllListeners(); - this.el.remove(); + + findRow : function(el) { + if (!el) { + return false; } - this.purgeListeners(); + return this.fly(el).findParent(this.rowSelector, this.rowSelectorDepth); }, - /** - * Returns true if client-side validation on the form is successful. - * @return Boolean - */ - isValid : function(){ - var valid = true; - this.items.each(function(f){ - if(!f.validate()){ - valid = false; - } - }); - return valid; + + findRowIndex : function(el) { + var row = this.findRow(el); + return row ? row.rowIndex : false; }, - /** - *

Returns true if any fields in this form have changed from their original values.

- *

Note that if this BasicForm was configured with {@link #trackResetOnLoad} then the - * Fields' original values are updated when the values are loaded by {@link #setValues} - * or {@link #loadRecord}.

- * @return Boolean - */ - isDirty : function(){ - var dirty = false; - this.items.each(function(f){ - if(f.isDirty()){ - dirty = true; - return false; - } - }); - return dirty; + + findRowBody : function(el) { + if (!el) { + return false; + } + + return this.fly(el).findParent(this.rowBodySelector, this.rowBodySelectorDepth); }, - /** - * Performs a predefined action ({@link Ext.form.Action.Submit} or - * {@link Ext.form.Action.Load}) or a custom extension of {@link Ext.form.Action} - * to perform application-specific processing. - * @param {String/Object} actionName The name of the predefined action type, - * or instance of {@link Ext.form.Action} to perform. - * @param {Object} options (optional) The options to pass to the {@link Ext.form.Action}. - * All of the config options listed below are supported by both the - * {@link Ext.form.Action.Submit submit} and {@link Ext.form.Action.Load load} - * actions unless otherwise noted (custom actions could also accept - * other config options):
    - * - *
  • url : String
    The url for the action (defaults - * to the form's {@link #url}.)
  • - * - *
  • method : String
    The form method to use (defaults - * to the form's method, or POST if not defined)
  • - * - *
  • params : String/Object

    The params to pass - * (defaults to the form's baseParams, or none if not defined)

    - *

    Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.

  • - * - *
  • headers : Object
    Request headers to set for the action - * (defaults to the form's default headers)
  • - * - *
  • success : Function
    The callback that will - * be invoked after a successful response (see top of - * {@link Ext.form.Action.Submit submit} and {@link Ext.form.Action.Load load} - * for a description of what constitutes a successful response). - * The function is passed the following parameters:
      - *
    • form : Ext.form.BasicForm
      The form that requested the action
    • - *
    • action : The {@link Ext.form.Action Action} object which performed the operation. - *
      The action object contains these properties of interest:
        - *
      • {@link Ext.form.Action#response response}
      • - *
      • {@link Ext.form.Action#result result} : interrogate for custom postprocessing
      • - *
      • {@link Ext.form.Action#type type}
      • - *
  • - * - *
  • failure : Function
    The callback that will be invoked after a - * failed transaction attempt. The function is passed the following parameters:
      - *
    • form : The {@link Ext.form.BasicForm} that requested the action.
    • - *
    • action : The {@link Ext.form.Action Action} object which performed the operation. - *
      The action object contains these properties of interest:
        - *
      • {@link Ext.form.Action#failureType failureType}
      • - *
      • {@link Ext.form.Action#response response}
      • - *
      • {@link Ext.form.Action#result result} : interrogate for custom postprocessing
      • - *
      • {@link Ext.form.Action#type type}
      • - *
  • - * - *
  • scope : Object
    The scope in which to call the - * callback functions (The this reference for the callback functions).
  • - * - *
  • clientValidation : Boolean
    Submit Action only. - * Determines whether a Form's fields are validated in a final call to - * {@link Ext.form.BasicForm#isValid isValid} prior to submission. Set to false - * to prevent this. If undefined, pre-submission field validation is performed.
- * - * @return {BasicForm} this - */ - doAction : function(action, options){ - if(Ext.isString(action)){ - action = new Ext.form.Action.ACTION_TYPES[action](this, options); + + + + getRow : function(row) { + return this.getRows()[row]; + }, + + + getCell : function(row, col) { + return Ext.fly(this.getRow(row)).query(this.cellSelector)[col]; + }, + + + getHeaderCell : function(index) { + return this.mainHd.dom.getElementsByTagName('td')[index]; + }, + + + + + addRowClass : function(rowId, cls) { + var row = this.getRow(rowId); + if (row) { + this.fly(row).addClass(cls); } - if(this.fireEvent('beforeaction', this, action) !== false){ - this.beforeAction(action); - action.run.defer(100, action); + }, + + + removeRowClass : function(row, cls) { + var r = this.getRow(row); + if(r){ + this.fly(r).removeClass(cls); } - return this; }, - /** - * Shortcut to {@link #doAction do} a {@link Ext.form.Action.Submit submit action}. - * @param {Object} options The options to pass to the action (see {@link #doAction} for details).
- *

Note: this is ignored when using the {@link #standardSubmit} option.

- *

The following code:


-myFormPanel.getForm().submit({
-    clientValidation: true,
-    url: 'updateConsignment.php',
-    params: {
-        newStatus: 'delivered'
-    },
-    success: function(form, action) {
-       Ext.Msg.alert('Success', action.result.msg);
-    },
-    failure: function(form, action) {
-        switch (action.failureType) {
-            case Ext.form.Action.CLIENT_INVALID:
-                Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
-                break;
-            case Ext.form.Action.CONNECT_FAILURE:
-                Ext.Msg.alert('Failure', 'Ajax communication failed');
-                break;
-            case Ext.form.Action.SERVER_INVALID:
-               Ext.Msg.alert('Failure', action.result.msg);
-       }
-    }
-});
-
- * would process the following server response for a successful submission:

-{
-    "success":true, // note this is Boolean, not string
-    "msg":"Consignment updated"
-}
-
- * and the following server response for a failed submission:

-{
-    "success":false, // note this is Boolean, not string
-    "msg":"You do not have permission to perform this operation"
-}
-
- * @return {BasicForm} this - */ - submit : function(options){ - if(this.standardSubmit){ - var v = this.isValid(); - if(v){ - var el = this.el.dom; - if(this.url && Ext.isEmpty(el.action)){ - el.action = this.url; - } - el.submit(); - } - return v; + + removeRow : function(row) { + Ext.removeNode(this.getRow(row)); + this.syncFocusEl(row); + }, + + + removeRows : function(firstRow, lastRow) { + var bd = this.mainBody.dom, + rowIndex; + + for (rowIndex = firstRow; rowIndex <= lastRow; rowIndex++){ + Ext.removeNode(bd.childNodes[firstRow]); } - var submitAction = String.format('{0}submit', this.api ? 'direct' : ''); - this.doAction(submitAction, options); - return this; + + this.syncFocusEl(firstRow); }, - /** - * Shortcut to {@link #doAction do} a {@link Ext.form.Action.Load load action}. - * @param {Object} options The options to pass to the action (see {@link #doAction} for details) - * @return {BasicForm} this - */ - load : function(options){ - var loadAction = String.format('{0}load', this.api ? 'direct' : ''); - this.doAction(loadAction, options); - return this; + + + + getScrollState : function() { + var sb = this.scroller.dom; + + return { + left: sb.scrollLeft, + top : sb.scrollTop + }; }, - /** - * Persists the values in this form into the passed {@link Ext.data.Record} object in a beginEdit/endEdit block. - * @param {Record} record The record to edit - * @return {BasicForm} this - */ - updateRecord : function(record){ - record.beginEdit(); - var fs = record.fields; - fs.each(function(f){ - var field = this.findField(f.name); - if(field){ - record.set(f.name, field.getValue()); - } - }, this); - record.endEdit(); - return this; + + restoreScroll : function(state) { + var sb = this.scroller.dom; + sb.scrollLeft = state.left; + sb.scrollTop = state.top; }, - /** - * Loads an {@link Ext.data.Record} into this form by calling {@link #setValues} with the - * {@link Ext.data.Record#data record data}. - * See also {@link #trackResetOnLoad}. - * @param {Record} record The record to load - * @return {BasicForm} this - */ - loadRecord : function(record){ - this.setValues(record.data); - return this; + + scrollToTop : function() { + var dom = this.scroller.dom; + + dom.scrollTop = 0; + dom.scrollLeft = 0; }, - // private - beforeAction : function(action){ - var o = action.options; - if(o.waitMsg){ - if(this.waitMsgTarget === true){ - this.el.mask(o.waitMsg, 'x-mask-loading'); - }else if(this.waitMsgTarget){ - this.waitMsgTarget = Ext.get(this.waitMsgTarget); - this.waitMsgTarget.mask(o.waitMsg, 'x-mask-loading'); - }else{ - Ext.MessageBox.wait(o.waitMsg, o.waitTitle || this.waitTitle); + + syncScroll : function() { + this.syncHeaderScroll(); + var mb = this.scroller.dom; + this.grid.fireEvent('bodyscroll', mb.scrollLeft, mb.scrollTop); + }, + + + syncHeaderScroll : function() { + var innerHd = this.innerHd, + scrollLeft = this.scroller.dom.scrollLeft; + + innerHd.scrollLeft = scrollLeft; + innerHd.scrollLeft = scrollLeft; + }, + + + updateSortIcon : function(col, dir) { + var sortClasses = this.sortClasses, + sortClass = sortClasses[dir == "DESC" ? 1 : 0], + headers = this.mainHd.select('td').removeClass(sortClasses); + + headers.item(col).addClass(sortClass); + }, + + + updateAllColumnWidths : function() { + var totalWidth = this.getTotalWidth(), + colCount = this.cm.getColumnCount(), + rows = this.getRows(), + rowCount = rows.length, + widths = [], + row, rowFirstChild, trow, i, j; + + for (i = 0; i < colCount; i++) { + widths[i] = this.getColumnWidth(i); + this.getHeaderCell(i).style.width = widths[i]; + } + + this.updateHeaderWidth(); + + for (i = 0; i < rowCount; i++) { + row = rows[i]; + row.style.width = totalWidth; + rowFirstChild = row.firstChild; + + if (rowFirstChild) { + rowFirstChild.style.width = totalWidth; + trow = rowFirstChild.rows[0]; + + for (j = 0; j < colCount; j++) { + trow.childNodes[j].style.width = widths[j]; + } } } + + this.onAllColumnWidthsUpdated(widths, totalWidth); }, - // private - afterAction : function(action, success){ - this.activeAction = null; - var o = action.options; - if(o.waitMsg){ - if(this.waitMsgTarget === true){ - this.el.unmask(); - }else if(this.waitMsgTarget){ - this.waitMsgTarget.unmask(); - }else{ - Ext.MessageBox.updateProgress(1); - Ext.MessageBox.hide(); + + updateColumnWidth : function(column, width) { + var columnWidth = this.getColumnWidth(column), + totalWidth = this.getTotalWidth(), + headerCell = this.getHeaderCell(column), + nodes = this.getRows(), + nodeCount = nodes.length, + row, i, firstChild; + + this.updateHeaderWidth(); + headerCell.style.width = columnWidth; + + for (i = 0; i < nodeCount; i++) { + row = nodes[i]; + firstChild = row.firstChild; + + row.style.width = totalWidth; + if (firstChild) { + firstChild.style.width = totalWidth; + firstChild.rows[0].childNodes[column].style.width = columnWidth; } } - if(success){ - if(o.reset){ - this.reset(); + + this.onColumnWidthUpdated(column, columnWidth, totalWidth); + }, + + + updateColumnHidden : function(col, hidden) { + var totalWidth = this.getTotalWidth(), + display = hidden ? 'none' : '', + headerCell = this.getHeaderCell(col), + nodes = this.getRows(), + nodeCount = nodes.length, + row, rowFirstChild, i; + + this.updateHeaderWidth(); + headerCell.style.display = display; + + for (i = 0; i < nodeCount; i++) { + row = nodes[i]; + row.style.width = totalWidth; + rowFirstChild = row.firstChild; + + if (rowFirstChild) { + rowFirstChild.style.width = totalWidth; + rowFirstChild.rows[0].childNodes[col].style.display = display; } - Ext.callback(o.success, o.scope, [this, action]); - this.fireEvent('actioncomplete', this, action); - }else{ - Ext.callback(o.failure, o.scope, [this, action]); - this.fireEvent('actionfailed', this, action); } + + this.onColumnHiddenUpdated(col, hidden, totalWidth); + delete this.lastViewWidth; + this.layout(); }, - /** - * Find a {@link Ext.form.Field} in this form. - * @param {String} id The value to search for (specify either a {@link Ext.Component#id id}, - * {@link Ext.grid.Column#dataIndex dataIndex}, {@link Ext.form.Field#getName name or hiddenName}). - * @return Field - */ - findField : function(id){ - var field = this.items.get(id); - if(!Ext.isObject(field)){ - this.items.each(function(f){ - if(f.isFormField && (f.dataIndex == id || f.id == id || f.getName() == id)){ - field = f; - return false; - } - }); - } - return field || null; - }, + + doRender : function(columns, records, store, startRow, colCount, stripe) { + var templates = this.templates, + cellTemplate = templates.cell, + rowTemplate = templates.row, + last = colCount - 1, + tstyle = 'width:' + this.getTotalWidth() + ';', + + rowBuffer = [], + colBuffer = [], + rowParams = {tstyle: tstyle}, + meta = {}, + len = records.length, + alt, + column, + record, i, j, rowIndex; + + + for (j = 0; j < len; j++) { + record = records[j]; + colBuffer = []; + rowIndex = j + startRow; - /** - * Mark fields in this form invalid in bulk. - * @param {Array/Object} errors Either an array in the form [{id:'fieldId', msg:'The message'},...] or an object hash of {id: msg, id2: msg2} - * @return {BasicForm} this - */ - markInvalid : function(errors){ - if(Ext.isArray(errors)){ - for(var i = 0, len = errors.length; i < len; i++){ - var fieldError = errors[i]; - var f = this.findField(fieldError.id); - if(f){ - f.markInvalid(fieldError.msg); + + for (i = 0; i < colCount; i++) { + column = columns[i]; + + meta.id = column.id; + meta.css = i === 0 ? 'x-grid3-cell-first ' : (i == last ? 'x-grid3-cell-last ' : ''); + meta.attr = meta.cellAttr = ''; + meta.style = column.style; + meta.value = column.renderer.call(column.scope, record.data[column.name], meta, record, rowIndex, i, store); + + if (Ext.isEmpty(meta.value)) { + meta.value = ' '; } - } - }else{ - var field, id; - for(id in errors){ - if(!Ext.isFunction(errors[id]) && (field = this.findField(id))){ - field.markInvalid(errors[id]); + + if (this.markDirty && record.dirty && typeof record.modified[column.name] != 'undefined') { + meta.css += ' x-grid3-dirty-cell'; } + + colBuffer[colBuffer.length] = cellTemplate.apply(meta); + } + + alt = []; + + if (stripe && ((rowIndex + 1) % 2 === 0)) { + alt[0] = 'x-grid3-row-alt'; + } + + if (record.dirty) { + alt[1] = ' x-grid3-dirty-row'; + } + + rowParams.cols = colCount; + + if (this.getRowClass) { + alt[2] = this.getRowClass(record, rowIndex, rowParams, store); } + + rowParams.alt = alt.join(' '); + rowParams.cells = colBuffer.join(''); + + rowBuffer[rowBuffer.length] = rowTemplate.apply(rowParams); } - return this; + + return rowBuffer.join(''); }, - /** - * Set values for fields in this form in bulk. - * @param {Array/Object} values Either an array in the form:

-[{id:'clientName', value:'Fred. Olsen Lines'},
- {id:'portOfLoading', value:'FXT'},
- {id:'portOfDischarge', value:'OSL'} ]
- * or an object hash of the form:

-{
-    clientName: 'Fred. Olsen Lines',
-    portOfLoading: 'FXT',
-    portOfDischarge: 'OSL'
-}
- * @return {BasicForm} this - */ - setValues : function(values){ - if(Ext.isArray(values)){ // array of objects - for(var i = 0, len = values.length; i < len; i++){ - var v = values[i]; - var f = this.findField(v.id); - if(f){ - f.setValue(v.value); - if(this.trackResetOnLoad){ - f.originalValue = f.getValue(); - } - } - } - }else{ // object hash - var field, id; - for(id in values){ - if(!Ext.isFunction(values[id]) && (field = this.findField(id))){ - field.setValue(values[id]); - if(this.trackResetOnLoad){ - field.originalValue = field.getValue(); + + processRows : function(startRow, skipStripe) { + if (!this.ds || this.ds.getCount() < 1) { + return; + } + + var rows = this.getRows(), + length = rows.length, + row, i; + + skipStripe = skipStripe || !this.grid.stripeRows; + startRow = startRow || 0; + + for (i = 0; i < length; i++) { + row = rows[i]; + if (row) { + row.rowIndex = i; + if (!skipStripe) { + row.className = row.className.replace(this.rowClsRe, ' '); + if ((i + 1) % 2 === 0){ + row.className += ' x-grid3-row-alt'; } } } } - return this; - }, - /** - *

Returns the fields in this form as an object with key/value pairs as they would be submitted using a standard form submit. - * If multiple fields exist with the same name they are returned as an array.

- *

Note: The values are collected from all enabled HTML input elements within the form, not from - * the Ext Field objects. This means that all returned values are Strings (or Arrays of Strings) and that the - * value can potentially be the emptyText of a field.

- * @param {Boolean} asString (optional) Pass true to return the values as a string. (defaults to false, returning an Object) - * @return {String/Object} - */ - getValues : function(asString){ - var fs = Ext.lib.Ajax.serializeForm(this.el.dom); - if(asString === true){ - return fs; + + if (startRow === 0) { + Ext.fly(rows[0]).addClass(this.firstRowCls); } - return Ext.urlDecode(fs); - }, - getFieldValues : function(){ - var o = {}; - this.items.each(function(f){ - o[f.getName()] = f.getValue(); - }); - return o; + Ext.fly(rows[length - 1]).addClass(this.lastRowCls); }, + + + afterRender : function() { + if (!this.ds || !this.cm) { + return; + } + + this.mainBody.dom.innerHTML = this.renderBody() || ' '; + this.processRows(0, true); - /** - * Clears all invalid messages in this form. - * @return {BasicForm} this - */ - clearInvalid : function(){ - this.items.each(function(f){ - f.clearInvalid(); - }); - return this; + if (this.deferEmptyText !== true) { + this.applyEmptyText(); + } + + this.grid.fireEvent('viewready', this.grid); }, + + + afterRenderUI: function() { + var grid = this.grid; + + this.initElements(); - /** - * Resets this form. - * @return {BasicForm} this - */ - reset : function(){ - this.items.each(function(f){ - f.reset(); + + Ext.fly(this.innerHd).on('click', this.handleHdDown, this); + + this.mainHd.on({ + scope : this, + mouseover: this.handleHdOver, + mouseout : this.handleHdOut, + mousemove: this.handleHdMove }); - return this; - }, - /** - * Add Ext.form Components to this form's Collection. This does not result in rendering of - * the passed Component, it just enables the form to validate Fields, and distribute values to - * Fields. - *

You will not usually call this function. In order to be rendered, a Field must be added - * to a {@link Ext.Container Container}, usually an {@link Ext.form.FormPanel FormPanel}. - * The FormPanel to which the field is added takes care of adding the Field to the BasicForm's - * collection.

- * @param {Field} field1 - * @param {Field} field2 (optional) - * @param {Field} etc (optional) - * @return {BasicForm} this - */ - add : function(){ - this.items.addAll(Array.prototype.slice.call(arguments, 0)); - return this; - }, + this.scroller.on('scroll', this.syncScroll, this); + + if (grid.enableColumnResize !== false) { + this.splitZone = new Ext.grid.GridView.SplitDragZone(grid, this.mainHd.dom); + } + if (grid.enableColumnMove) { + this.columnDrag = new Ext.grid.GridView.ColumnDragZone(grid, this.innerHd); + this.columnDrop = new Ext.grid.HeaderDropZone(grid, this.mainHd.dom); + } - /** - * Removes a field from the items collection (does NOT remove its markup). - * @param {Field} field - * @return {BasicForm} this - */ - remove : function(field){ - this.items.remove(field); - return this; - }, + if (grid.enableHdMenu !== false) { + this.hmenu = new Ext.menu.Menu({id: grid.id + '-hctx'}); + this.hmenu.add( + {itemId:'asc', text: this.sortAscText, cls: 'xg-hmenu-sort-asc'}, + {itemId:'desc', text: this.sortDescText, cls: 'xg-hmenu-sort-desc'} + ); - /** - * Iterates through the {@link Ext.form.Field Field}s which have been {@link #add add}ed to this BasicForm, - * checks them for an id attribute, and calls {@link Ext.form.Field#applyToMarkup} on the existing dom element with that id. - * @return {BasicForm} this - */ - render : function(){ - this.items.each(function(f){ - if(f.isFormField && !f.rendered && document.getElementById(f.id)){ // if the element exists - f.applyToMarkup(f.id); + if (grid.enableColumnHide !== false) { + this.colMenu = new Ext.menu.Menu({id:grid.id + '-hcols-menu'}); + this.colMenu.on({ + scope : this, + beforeshow: this.beforeColMenuShow, + itemclick : this.handleHdMenuClick + }); + this.hmenu.add('-', { + itemId:'columns', + hideOnClick: false, + text: this.columnsText, + menu: this.colMenu, + iconCls: 'x-cols-icon' + }); } - }); - return this; - }, - /** - * Calls {@link Ext#apply} for all fields in this form with the passed object. - * @param {Object} values - * @return {BasicForm} this - */ - applyToFields : function(o){ - this.items.each(function(f){ - Ext.apply(f, o); - }); - return this; - }, + this.hmenu.on('itemclick', this.handleHdMenuClick, this); + } - /** - * Calls {@link Ext#applyIf} for all field in this form with the passed object. - * @param {Object} values - * @return {BasicForm} this - */ - applyIfToFields : function(o){ - this.items.each(function(f){ - Ext.applyIf(f, o); - }); - return this; + if (grid.trackMouseOver) { + this.mainBody.on({ + scope : this, + mouseover: this.onRowOver, + mouseout : this.onRowOut + }); + } + + if (grid.enableDragDrop || grid.enableDrag) { + this.dragZone = new Ext.grid.GridDragZone(grid, { + ddGroup : grid.ddGroup || 'GridDD' + }); + } + + this.updateHeaderSortState(); }, - callFieldMethod : function(fnName, args){ - args = args || []; - this.items.each(function(f){ - if(Ext.isFunction(f[fnName])){ - f[fnName].apply(f, args); - } + + renderUI : function() { + var templates = this.templates; + + return templates.master.apply({ + body : templates.body.apply({rows:' '}), + header: this.renderHeaders(), + ostyle: 'width:' + this.getOffsetWidth() + ';', + bstyle: 'width:' + this.getTotalWidth() + ';' }); - return this; - } -}); - -// back compat -Ext.BasicForm = Ext.form.BasicForm;/** - * @class Ext.form.FormPanel - * @extends Ext.Panel - *

Standard form container.

- * - *

Layout

- *

By default, FormPanel is configured with layout:'form' to use an {@link Ext.layout.FormLayout} - * layout manager, which styles and renders fields and labels correctly. When nesting additional Containers - * within a FormPanel, you should ensure that any descendant Containers which host input Fields use the - * {@link Ext.layout.FormLayout} layout manager.

- * - *

BasicForm

- *

Although not listed as configuration options of FormPanel, the FormPanel class accepts all - * of the config options required to configure its internal {@link Ext.form.BasicForm} for: - *

    - *
  • {@link Ext.form.BasicForm#fileUpload file uploads}
  • - *
  • functionality for {@link Ext.form.BasicForm#doAction loading, validating and submitting} the form
  • - *
- * - *

Note: If subclassing FormPanel, any configuration options for the BasicForm must be applied to - * the initialConfig property of the FormPanel. Applying {@link Ext.form.BasicForm BasicForm} - * configuration settings to this will not affect the BasicForm's configuration.

- * - *

Form Validation

- *

For information on form validation see the following:

- *
    - *
  • {@link Ext.form.TextField}
  • - *
  • {@link Ext.form.VTypes}
  • - *
  • {@link Ext.form.BasicForm#doAction BasicForm.doAction clientValidation notes}
  • - *
  • {@link Ext.form.FormPanel#monitorValid monitorValid}
  • - *
- * - *

Form Submission

- *

By default, Ext Forms are submitted through Ajax, using {@link Ext.form.Action}. To enable normal browser - * submission of the {@link Ext.form.BasicForm BasicForm} contained in this FormPanel, see the - * {@link Ext.form.BasicForm#standardSubmit standardSubmit} option.

- * - * @constructor - * @param {Object} config Configuration options - * @xtype form - */ -Ext.FormPanel = Ext.extend(Ext.Panel, { - /** - * @cfg {String} formId (optional) The id of the FORM tag (defaults to an auto-generated id). - */ - /** - * @cfg {Boolean} hideLabels - *

true to hide field labels by default (sets display:none). Defaults to - * false.

- *

Also see {@link Ext.Component}.{@link Ext.Component#hideLabel hideLabel}. - */ - /** - * @cfg {Number} labelPad - * The default padding in pixels for field labels (defaults to 5). labelPad only - * applies if {@link #labelWidth} is also specified, otherwise it will be ignored. - */ - /** - * @cfg {String} labelSeparator - * See {@link Ext.Component}.{@link Ext.Component#labelSeparator labelSeparator} - */ - /** - * @cfg {Number} labelWidth The width of labels in pixels. This property cascades to child containers - * and can be overridden on any child container (e.g., a fieldset can specify a different labelWidth - * for its fields) (defaults to 100). - */ - /** - * @cfg {String} itemCls A css class to apply to the x-form-item of fields. This property cascades to child containers. - */ - /** - * @cfg {Array} buttons - * An array of {@link Ext.Button}s or {@link Ext.Button} configs used to add buttons to the footer of this FormPanel.
- *

Buttons in the footer of a FormPanel may be configured with the option formBind: true. This causes - * the form's {@link #monitorValid valid state monitor task} to enable/disable those Buttons depending on - * the form's valid/invalid state.

- */ + }, + + processEvent : function(name, e) { + var target = e.getTarget(), + grid = this.grid, + header = this.findHeaderIndex(target), + row, cell, col, body; - /** - * @cfg {Number} minButtonWidth Minimum width of all buttons in pixels (defaults to 75). - */ - minButtonWidth : 75, + grid.fireEvent(name, e); - /** - * @cfg {String} labelAlign The label alignment value used for the text-align specification - * for the container. Valid values are "left", "top" or "right" - * (defaults to "left"). This property cascades to child containers and can be - * overridden on any child container (e.g., a fieldset can specify a different labelAlign - * for its fields). - */ - labelAlign : 'left', + if (header !== false) { + grid.fireEvent('header' + name, grid, header, e); + } else { + row = this.findRowIndex(target); - /** - * @cfg {Boolean} monitorValid If true, the form monitors its valid state client-side and - * regularly fires the {@link #clientvalidation} event passing that state.
- *

When monitoring valid state, the FormPanel enables/disables any of its configured - * {@link #buttons} which have been configured with formBind: true depending - * on whether the {@link Ext.form.BasicForm#isValid form is valid} or not. Defaults to false

- */ - monitorValid : false, - /** - * @cfg {Number} monitorPoll The milliseconds to poll valid state, ignored if monitorValid is not true (defaults to 200) - */ - monitorPoll : 200, - /** - * @cfg {String} layout Defaults to 'form'. Normally this configuration property should not be altered. - * For additional details see {@link Ext.layout.FormLayout} and {@link Ext.Container#layout Ext.Container.layout}. - */ - layout : 'form', - // private - initComponent : function(){ - this.form = this.createForm(); - Ext.FormPanel.superclass.initComponent.call(this); + if (row !== false) { + cell = this.findCellIndex(target); + if (cell !== false) { + col = grid.colModel.getColumnAt(cell); + if (grid.fireEvent('cell' + name, grid, row, cell, e) !== false) { + if (!col || (col.processEvent && (col.processEvent(name, e, grid, row, cell) !== false))) { + grid.fireEvent('row' + name, grid, row, e); + } + } + } else { + if (grid.fireEvent('row' + name, grid, row, e) !== false) { + (body = this.findRowBody(target)) && grid.fireEvent('rowbody' + name, grid, row, e); + } + } + } else { + grid.fireEvent('container' + name, grid, e); + } + } + }, - this.bodyCfg = { - tag: 'form', - cls: this.baseCls + '-body', - method : this.method || 'POST', - id : this.formId || Ext.id() - }; - if(this.fileUpload) { - this.bodyCfg.enctype = 'multipart/form-data'; + + layout : function(initial) { + if (!this.mainBody) { + return; + } + + var grid = this.grid, + gridEl = grid.getGridEl(), + gridSize = gridEl.getSize(true), + gridWidth = gridSize.width, + gridHeight = gridSize.height, + scroller = this.scroller, + scrollStyle, headerHeight, scrollHeight; + + if (gridWidth < 20 || gridHeight < 20) { + return; } - this.initItems(); - this.addEvents( - /** - * @event clientvalidation - * If the monitorValid config option is true, this event fires repetitively to notify of valid state - * @param {Ext.form.FormPanel} this - * @param {Boolean} valid true if the form has passed client-side validation - */ - 'clientvalidation' - ); + if (grid.autoHeight) { + scrollStyle = scroller.dom.style; + scrollStyle.overflow = 'visible'; + + if (Ext.isWebKit) { + scrollStyle.position = 'static'; + } + } else { + this.el.setSize(gridWidth, gridHeight); + + headerHeight = this.mainHd.getHeight(); + scrollHeight = gridHeight - headerHeight; + + scroller.setSize(gridWidth, scrollHeight); + + if (this.innerHd) { + this.innerHd.style.width = (gridWidth) + "px"; + } + } + + if (this.forceFit || (initial === true && this.autoFill)) { + if (this.lastViewWidth != gridWidth) { + this.fitColumns(false, false); + this.lastViewWidth = gridWidth; + } + } else { + this.autoExpand(); + this.syncHeaderScroll(); + } + + this.onLayout(gridWidth, scrollHeight); + }, - this.relayEvents(this.form, ['beforeaction', 'actionfailed', 'actioncomplete']); + + + onLayout : function(vw, vh) { + }, - // private - createForm : function(){ - var config = Ext.applyIf({listeners: {}}, this.initialConfig); - return new Ext.form.BasicForm(null, config); + onColumnWidthUpdated : function(col, w, tw) { + }, - // private - initFields : function(){ - var f = this.form; - var formPanel = this; - var fn = function(c){ - if(formPanel.isField(c)){ - f.add(c); - }else if(c.findBy && c != formPanel){ - formPanel.applySettings(c); - //each check required for check/radio groups. - if(c.items && c.items.each){ - c.items.each(fn, this); - } - } - }; - this.items.each(fn, this); + onAllColumnWidthsUpdated : function(ws, tw) { + }, - - // private - applySettings: function(c){ - var ct = c.ownerCt; - Ext.applyIf(c, { - labelAlign: ct.labelAlign, - labelWidth: ct.labelWidth, - itemCls: ct.itemCls - }); + + onColumnHiddenUpdated : function(col, hidden, tw) { + }, - // private - getLayoutTarget : function(){ - return this.form.el; + updateColumnText : function(col, text) { + }, - /** - * Provides access to the {@link Ext.form.BasicForm Form} which this Panel contains. - * @return {Ext.form.BasicForm} The {@link Ext.form.BasicForm Form} which this Panel contains. - */ - getForm : function(){ - return this.form; + afterMove : function(colIndex) { + }, - // private - onRender : function(ct, position){ - this.initFields(); - Ext.FormPanel.superclass.onRender.call(this, ct, position); - this.form.initEl(this.body); + + + init : function(grid) { + this.grid = grid; + + this.initTemplates(); + this.initData(grid.store, grid.colModel); + this.initUI(grid); }, + - // private - beforeDestroy : function(){ - this.stopMonitoring(); - Ext.FormPanel.superclass.beforeDestroy.call(this); - /* - * Clear the items here to prevent them being destroyed again. - * Don't move this behaviour to BasicForm because it can be used - * on it's own. - */ - this.form.items.clear(); - Ext.destroy(this.form); + getColumnId : function(index){ + return this.cm.getColumnId(index); }, - // Determine if a Component is usable as a form Field. - isField : function(c) { - return !!c.setValue && !!c.getValue && !!c.markInvalid && !!c.clearInvalid; + + getOffsetWidth : function() { + return (this.cm.getTotalWidth() + this.getScrollOffset()) + 'px'; }, - // private - initEvents : function(){ - Ext.FormPanel.superclass.initEvents.call(this); - // Listeners are required here to catch bubbling events from children. - this.on({ - scope: this, - add: this.onAddEvent, - remove: this.onRemoveEvent + + getScrollOffset: function() { + return Ext.num(this.scrollOffset, Ext.getScrollBarWidth()); + }, + + + renderHeaders : function() { + var colModel = this.cm, + templates = this.templates, + headerTpl = templates.hcell, + properties = {}, + colCount = colModel.getColumnCount(), + last = colCount - 1, + cells = [], + i, cssCls; + + for (i = 0; i < colCount; i++) { + if (i == 0) { + cssCls = 'x-grid3-cell-first '; + } else { + cssCls = i == last ? 'x-grid3-cell-last ' : ''; + } + + properties = { + id : colModel.getColumnId(i), + value : colModel.getColumnHeader(i) || '', + style : this.getColumnStyle(i, true), + css : cssCls, + tooltip: this.getColumnTooltip(i) + }; + + if (colModel.config[i].align == 'right') { + properties.istyle = 'padding-right: 16px;'; + } else { + delete properties.istyle; + } + + cells[i] = headerTpl.apply(properties); + } + + return templates.header.apply({ + cells : cells.join(""), + tstyle: String.format("width: {0};", this.getTotalWidth()) }); - if(this.monitorValid){ // initialize after render - this.startMonitoring(); + }, + + + getColumnTooltip : function(i) { + var tooltip = this.cm.getColumnTooltip(i); + if (tooltip) { + if (Ext.QuickTips.isEnabled()) { + return 'ext:qtip="' + tooltip + '"'; + } else { + return 'title="' + tooltip + '"'; + } } + + return ''; }, + - // private - onAdd: function(c){ - Ext.FormPanel.superclass.onAdd.call(this, c); - this.processAdd(c); + beforeUpdate : function() { + this.grid.stopEditing(true); }, + - // private - onAddEvent: function(ct, c){ - if(ct !== this){ - this.processAdd(c); - } + updateHeaders : function() { + this.innerHd.firstChild.innerHTML = this.renderHeaders(); + + this.updateHeaderWidth(false); }, - // private - processAdd : function(c){ - // If a single form Field, add it - if(this.isField(c)){ - this.form.add(c); - // If a Container, add any Fields it might contain - }else if(c.findBy){ - this.applySettings(c); - this.form.add.apply(this.form, c.findBy(this.isField)); + + updateHeaderWidth: function(updateMain) { + var innerHdChild = this.innerHd.firstChild, + totalWidth = this.getTotalWidth(); + + innerHdChild.style.width = this.getOffsetWidth(); + innerHdChild.firstChild.style.width = totalWidth; + + if (updateMain !== false) { + this.mainBody.dom.style.width = totalWidth; } }, + - // private - onRemove: function(c){ - Ext.FormPanel.superclass.onRemove.call(this, c); - this.processRemove(c); + focusRow : function(row) { + this.focusCell(row, 0, false); }, + - onRemoveEvent: function(ct, c){ - if(ct !== this){ - this.processRemove(c); + focusCell : function(row, col, hscroll) { + this.syncFocusEl(this.ensureVisible(row, col, hscroll)); + + var focusEl = this.focusEl; + + if (Ext.isGecko) { + focusEl.focus(); + } else { + focusEl.focus.defer(1, focusEl); } }, - - // private - processRemove : function(c){ - // If a single form Field, remove it - if(this.isField(c)){ - this.form.remove(c); - // If a Container, remove any Fields it might contain - }else if(c.findBy){ - Ext.each(c.findBy(this.isField), this.form.remove, this.form); + + + resolveCell : function(row, col, hscroll) { + if (!Ext.isNumber(row)) { + row = row.rowIndex; + } + + if (!this.ds) { + return null; + } + + if (row < 0 || row >= this.ds.getCount()) { + return null; + } + col = (col !== undefined ? col : 0); + + var rowEl = this.getRow(row), + colModel = this.cm, + colCount = colModel.getColumnCount(), + cellEl; + + if (!(hscroll === false && col === 0)) { + while (col < colCount && colModel.isHidden(col)) { + col++; + } + + cellEl = this.getCell(row, col); } + + return {row: rowEl, cell: cellEl}; }, - /** - * Starts monitoring of the valid state of this form. Usually this is done by passing the config - * option "monitorValid" - */ - startMonitoring : function(){ - if(!this.validTask){ - this.validTask = new Ext.util.TaskRunner(); - this.validTask.start({ - run : this.bindHandler, - interval : this.monitorPoll || 200, - scope: this - }); + + getResolvedXY : function(resolved) { + if (!resolved) { + return null; + } + + var cell = resolved.cell, + row = resolved.row; + + if (cell) { + return Ext.fly(cell).getXY(); + } else { + return [this.el.getX(), Ext.fly(row).getY()]; } }, - /** - * Stops monitoring of the valid state of this form - */ - stopMonitoring : function(){ - if(this.validTask){ - this.validTask.stopAll(); - this.validTask = null; + + syncFocusEl : function(row, col, hscroll) { + var xy = row; + + if (!Ext.isArray(xy)) { + row = Math.min(row, Math.max(0, this.getRows().length-1)); + + if (isNaN(row)) { + return; + } + + xy = this.getResolvedXY(this.resolveCell(row, col, hscroll)); + } + + this.focusEl.setXY(xy || this.scroller.getXY()); + }, + + + ensureVisible : function(row, col, hscroll) { + var resolved = this.resolveCell(row, col, hscroll); + + if (!resolved || !resolved.row) { + return null; + } + + var rowEl = resolved.row, + cellEl = resolved.cell, + c = this.scroller.dom, + p = rowEl, + ctop = 0, + stop = this.el.dom; + + while (p && p != stop) { + ctop += p.offsetTop; + p = p.offsetParent; } - }, - /** - * This is a proxy for the underlying BasicForm's {@link Ext.form.BasicForm#load} call. - * @param {Object} options The options to pass to the action (see {@link Ext.form.BasicForm#doAction} for details) - */ - load : function(){ - this.form.load.apply(this.form, arguments); - }, + ctop -= this.mainHd.dom.offsetHeight; + stop = parseInt(c.scrollTop, 10); - // private - onDisable : function(){ - Ext.FormPanel.superclass.onDisable.call(this); - if(this.form){ - this.form.items.each(function(){ - this.disable(); - }); + var cbot = ctop + rowEl.offsetHeight, + ch = c.clientHeight, + sbot = stop + ch; + + + if (ctop < stop) { + c.scrollTop = ctop; + } else if(cbot > sbot) { + c.scrollTop = cbot-ch; } - }, - // private - onEnable : function(){ - Ext.FormPanel.superclass.onEnable.call(this); - if(this.form){ - this.form.items.each(function(){ - this.enable(); - }); + if (hscroll !== false) { + var cleft = parseInt(cellEl.offsetLeft, 10), + cright = cleft + cellEl.offsetWidth, + sleft = parseInt(c.scrollLeft, 10), + sright = sleft + c.clientWidth; + + if (cleft < sleft) { + c.scrollLeft = cleft; + } else if(cright > sright) { + c.scrollLeft = cright-c.clientWidth; + } } + + return this.getResolvedXY(resolved); }, - // private - bindHandler : function(){ - var valid = true; - this.form.items.each(function(f){ - if(!f.isValid(true)){ - valid = false; - return false; + + insertRows : function(dm, firstRow, lastRow, isUpdate) { + var last = dm.getCount() - 1; + if( !isUpdate && firstRow === 0 && lastRow >= last) { + this.fireEvent('beforerowsinserted', this, firstRow, lastRow); + this.refresh(); + this.fireEvent('rowsinserted', this, firstRow, lastRow); + } else { + if (!isUpdate) { + this.fireEvent('beforerowsinserted', this, firstRow, lastRow); } - }); - if(this.fbar){ - var fitems = this.fbar.items.items; - for(var i = 0, len = fitems.length; i < len; i++){ - var btn = fitems[i]; - if(btn.formBind === true && btn.disabled === valid){ - btn.setDisabled(!valid); + var html = this.renderRows(firstRow, lastRow), + before = this.getRow(firstRow); + if (before) { + if(firstRow === 0){ + Ext.fly(this.getRow(0)).removeClass(this.firstRowCls); + } + Ext.DomHelper.insertHtml('beforeBegin', before, html); + } else { + var r = this.getRow(last - 1); + if(r){ + Ext.fly(r).removeClass(this.lastRowCls); } + Ext.DomHelper.insertHtml('beforeEnd', this.mainBody.dom, html); + } + if (!isUpdate) { + this.processRows(firstRow); + this.fireEvent('rowsinserted', this, firstRow, lastRow); + } else if (firstRow === 0 || firstRow >= last) { + + Ext.fly(this.getRow(firstRow)).addClass(firstRow === 0 ? this.firstRowCls : this.lastRowCls); } } - this.fireEvent('clientvalidation', this, valid); - } -}); -Ext.reg('form', Ext.FormPanel); + this.syncFocusEl(firstRow); + }, -Ext.form.FormPanel = Ext.FormPanel; + + deleteRows : function(dm, firstRow, lastRow) { + if (dm.getRowCount() < 1) { + this.refresh(); + } else { + this.fireEvent('beforerowsdeleted', this, firstRow, lastRow); -/** - * @class Ext.form.FieldSet - * @extends Ext.Panel - * Standard container used for grouping items within a {@link Ext.form.FormPanel form}. - *

-var form = new Ext.FormPanel({
-    title: 'Simple Form with FieldSets',
-    labelWidth: 75, // label settings here cascade unless overridden
-    url: 'save-form.php',
-    frame:true,
-    bodyStyle:'padding:5px 5px 0',
-    width: 700,
-    renderTo: document.body,
-    layout:'column', // arrange items in columns
-    defaults: {      // defaults applied to items
-        layout: 'form',
-        border: false,
-        bodyStyle: 'padding:4px'
-    },
-    items: [{
-        // Fieldset in Column 1
-        xtype:'fieldset',
-        columnWidth: 0.5,
-        title: 'Fieldset 1',
-        collapsible: true,
-        autoHeight:true,
-        defaults: {
-            anchor: '-20' // leave room for error icon
-        },
-        defaultType: 'textfield',
-        items :[{
-                fieldLabel: 'Field 1'
-            }, {
-                fieldLabel: 'Field 2'
-            }, {
-                fieldLabel: 'Field 3'
-            }
-        ]
-    },{
-        // Fieldset in Column 2 - Panel inside
-        xtype:'fieldset',
-        title: 'Show Panel', // title, header, or checkboxToggle creates fieldset header
-        autoHeight:true,
-        columnWidth: 0.5,
-        checkboxToggle: true,
-        collapsed: true, // fieldset initially collapsed
-        layout:'anchor',
-        items :[{
-            xtype: 'panel',
-            anchor: '100%',
-            title: 'Panel inside a fieldset',
-            frame: true,
-            height: 100
-        }]
-    }]
-});
- * 
- * @constructor - * @param {Object} config Configuration options - * @xtype fieldset - */ -Ext.form.FieldSet = Ext.extend(Ext.Panel, { - /** - * @cfg {Mixed} checkboxToggle true to render a checkbox into the fieldset frame just - * in front of the legend to expand/collapse the fieldset when the checkbox is toggled. (defaults - * to false). - *

A {@link Ext.DomHelper DomHelper} element spec may also be specified to create the checkbox. - * If true is specified, the default DomHelper config object used to create the element - * is:


-     * {tag: 'input', type: 'checkbox', name: this.checkboxName || this.id+'-checkbox'}
-     * 
- */ - /** - * @cfg {String} checkboxName The name to assign to the fieldset's checkbox if {@link #checkboxToggle} = true - * (defaults to '[checkbox id]-checkbox'). - */ - /** - * @cfg {Boolean} collapsible - * true to make the fieldset collapsible and have the expand/collapse toggle button automatically - * rendered into the legend element, false to keep the fieldset statically sized with no collapse - * button (defaults to false). Another option is to configure {@link #checkboxToggle}. - */ - /** - * @cfg {Number} labelWidth The width of labels. This property cascades to child containers. - */ - /** - * @cfg {String} itemCls A css class to apply to the x-form-item of fields (see - * {@link Ext.layout.FormLayout}.{@link Ext.layout.FormLayout#fieldTpl fieldTpl} for details). - * This property cascades to child containers. - */ - /** - * @cfg {String} baseCls The base CSS class applied to the fieldset (defaults to 'x-fieldset'). - */ - baseCls : 'x-fieldset', - /** - * @cfg {String} layout The {@link Ext.Container#layout} to use inside the fieldset (defaults to 'form'). - */ - layout : 'form', - /** - * @cfg {Boolean} animCollapse - * true to animate the transition when the panel is collapsed, false to skip the - * animation (defaults to false). - */ - animCollapse : false, - - // private - onRender : function(ct, position){ - if(!this.el){ - this.el = document.createElement('fieldset'); - this.el.id = this.id; - if (this.title || this.header || this.checkboxToggle) { - this.el.appendChild(document.createElement('legend')).className = 'x-fieldset-header'; - } - } - - Ext.form.FieldSet.superclass.onRender.call(this, ct, position); - - if(this.checkboxToggle){ - var o = typeof this.checkboxToggle == 'object' ? - this.checkboxToggle : - {tag: 'input', type: 'checkbox', name: this.checkboxName || this.id+'-checkbox'}; - this.checkbox = this.header.insertFirst(o); - this.checkbox.dom.checked = !this.collapsed; - this.mon(this.checkbox, 'click', this.onCheckClick, this); - } - }, - - // private - onCollapse : function(doAnim, animArg){ - if(this.checkbox){ - this.checkbox.dom.checked = false; - } - Ext.form.FieldSet.superclass.onCollapse.call(this, doAnim, animArg); - - }, - - // private - onExpand : function(doAnim, animArg){ - if(this.checkbox){ - this.checkbox.dom.checked = true; - } - Ext.form.FieldSet.superclass.onExpand.call(this, doAnim, animArg); - }, - - /** - * This function is called by the fieldset's checkbox when it is toggled (only applies when - * checkboxToggle = true). This method should never be called externally, but can be - * overridden to provide custom behavior when the checkbox is toggled if needed. - */ - onCheckClick : function(){ - this[this.checkbox.dom.checked ? 'expand' : 'collapse'](); - } - - /** - * @cfg {String/Number} activeItem - * @hide - */ - /** - * @cfg {Mixed} applyTo - * @hide - */ - /** - * @cfg {Boolean} bodyBorder - * @hide - */ - /** - * @cfg {Boolean} border - * @hide - */ - /** - * @cfg {Boolean/Number} bufferResize - * @hide - */ - /** - * @cfg {Boolean} collapseFirst - * @hide - */ - /** - * @cfg {String} defaultType - * @hide - */ - /** - * @cfg {String} disabledClass - * @hide - */ - /** - * @cfg {String} elements - * @hide - */ - /** - * @cfg {Boolean} floating - * @hide - */ - /** - * @cfg {Boolean} footer - * @hide - */ - /** - * @cfg {Boolean} frame - * @hide - */ - /** - * @cfg {Boolean} header - * @hide - */ - /** - * @cfg {Boolean} headerAsText - * @hide - */ - /** - * @cfg {Boolean} hideCollapseTool - * @hide - */ - /** - * @cfg {String} iconCls - * @hide - */ - /** - * @cfg {Boolean/String} shadow - * @hide - */ - /** - * @cfg {Number} shadowOffset - * @hide - */ - /** - * @cfg {Boolean} shim - * @hide - */ - /** - * @cfg {Object/Array} tbar - * @hide - */ - /** - * @cfg {Array} tools - * @hide - */ - /** - * @cfg {Ext.Template/Ext.XTemplate} toolTemplate - * @hide - */ - /** - * @cfg {String} xtype - * @hide - */ - /** - * @property header - * @hide - */ - /** - * @property footer - * @hide - */ - /** - * @method focus - * @hide - */ - /** - * @method getBottomToolbar - * @hide - */ - /** - * @method getTopToolbar - * @hide - */ - /** - * @method setIconClass - * @hide - */ - /** - * @event activate - * @hide - */ - /** - * @event beforeclose - * @hide - */ - /** - * @event bodyresize - * @hide - */ - /** - * @event close - * @hide - */ - /** - * @event deactivate - * @hide - */ -}); -Ext.reg('fieldset', Ext.form.FieldSet); -/** - * @class Ext.form.HtmlEditor - * @extends Ext.form.Field - * Provides a lightweight HTML Editor component. Some toolbar features are not supported by Safari and will be - * automatically hidden when needed. These are noted in the config options where appropriate. - *

The editor's toolbar buttons have tooltips defined in the {@link #buttonTips} property, but they are not - * enabled by default unless the global {@link Ext.QuickTips} singleton is {@link Ext.QuickTips#init initialized}. - *

Note: The focus/blur and validation marking functionality inherited from Ext.form.Field is NOT - * supported by this editor. - *

An Editor is a sensitive component that can't be used in all spots standard fields can be used. Putting an Editor within - * any element that has display set to 'none' can cause problems in Safari and Firefox due to their default iframe reloading bugs. - *

Example usage: - *

-// Simple example rendered with default options:
-Ext.QuickTips.init();  // enable tooltips
-new Ext.form.HtmlEditor({
-    renderTo: Ext.getBody(),
-    width: 800,
-    height: 300
-});
-
-// Passed via xtype into a container and with custom options:
-Ext.QuickTips.init();  // enable tooltips
-new Ext.Panel({
-    title: 'HTML Editor',
-    renderTo: Ext.getBody(),
-    width: 600,
-    height: 300,
-    frame: true,
-    layout: 'fit',
-    items: {
-        xtype: 'htmleditor',
-        enableColors: false,
-        enableAlignments: false
-    }
-});
-
- * @constructor - * Create a new HtmlEditor - * @param {Object} config - * @xtype htmleditor - */ - -Ext.form.HtmlEditor = Ext.extend(Ext.form.Field, { - /** - * @cfg {Boolean} enableFormat Enable the bold, italic and underline buttons (defaults to true) - */ - enableFormat : true, - /** - * @cfg {Boolean} enableFontSize Enable the increase/decrease font size buttons (defaults to true) - */ - enableFontSize : true, - /** - * @cfg {Boolean} enableColors Enable the fore/highlight color buttons (defaults to true) - */ - enableColors : true, - /** - * @cfg {Boolean} enableAlignments Enable the left, center, right alignment buttons (defaults to true) - */ - enableAlignments : true, - /** - * @cfg {Boolean} enableLists Enable the bullet and numbered list buttons. Not available in Safari. (defaults to true) - */ - enableLists : true, - /** - * @cfg {Boolean} enableSourceEdit Enable the switch to source edit button. Not available in Safari. (defaults to true) - */ - enableSourceEdit : true, - /** - * @cfg {Boolean} enableLinks Enable the create link button. Not available in Safari. (defaults to true) - */ - enableLinks : true, - /** - * @cfg {Boolean} enableFont Enable font selection. Not available in Safari. (defaults to true) - */ - enableFont : true, - /** - * @cfg {String} createLinkText The default text for the create link prompt - */ - createLinkText : 'Please enter the URL for the link:', - /** - * @cfg {String} defaultLinkValue The default value for the create link prompt (defaults to http:/ /) - */ - defaultLinkValue : 'http:/'+'/', - /** - * @cfg {Array} fontFamilies An array of available font families - */ - fontFamilies : [ - 'Arial', - 'Courier New', - 'Tahoma', - 'Times New Roman', - 'Verdana' - ], - defaultFont: 'tahoma', - /** - * @cfg {String} defaultValue A default value to be put into the editor to resolve focus issues (defaults to ​ (Zero-width space),   (Non-breaking space) in Opera and IE6). - */ - defaultValue: (Ext.isOpera || Ext.isIE6) ? ' ' : '​', - - // private properties - actionMode: 'wrap', - validationEvent : false, - deferHeight: true, - initialized : false, - activated : false, - sourceEditMode : false, - onFocus : Ext.emptyFn, - iframePad:3, - hideMode:'offsets', - defaultAutoCreate : { - tag: "textarea", - style:"width:500px;height:300px;", - autocomplete: "off" - }, - - // private - initComponent : function(){ - this.addEvents( - /** - * @event initialize - * Fires when the editor is fully initialized (including the iframe) - * @param {HtmlEditor} this - */ - 'initialize', - /** - * @event activate - * Fires when the editor is first receives the focus. Any insertion must wait - * until after this event. - * @param {HtmlEditor} this - */ - 'activate', - /** - * @event beforesync - * Fires before the textarea is updated with content from the editor iframe. Return false - * to cancel the sync. - * @param {HtmlEditor} this - * @param {String} html - */ - 'beforesync', - /** - * @event beforepush - * Fires before the iframe editor is updated with content from the textarea. Return false - * to cancel the push. - * @param {HtmlEditor} this - * @param {String} html - */ - 'beforepush', - /** - * @event sync - * Fires when the textarea is updated with content from the editor iframe. - * @param {HtmlEditor} this - * @param {String} html - */ - 'sync', - /** - * @event push - * Fires when the iframe editor is updated with content from the textarea. - * @param {HtmlEditor} this - * @param {String} html - */ - 'push', - /** - * @event editmodechange - * Fires when the editor switches edit modes - * @param {HtmlEditor} this - * @param {Boolean} sourceEdit True if source edit, false if standard editing. - */ - 'editmodechange' - ) - }, - - // private - createFontOptions : function(){ - var buf = [], fs = this.fontFamilies, ff, lc; - for(var i = 0, len = fs.length; i< len; i++){ - ff = fs[i]; - lc = ff.toLowerCase(); - buf.push( - '' - ); - } - return buf.join(''); - }, - - /* - * Protected method that will not generally be called directly. It - * is called when the editor creates its toolbar. Override this method if you need to - * add custom toolbar buttons. - * @param {HtmlEditor} editor - */ - createToolbar : function(editor){ - - var tipsEnabled = Ext.QuickTips && Ext.QuickTips.isEnabled(); - - function btn(id, toggle, handler){ - return { - itemId : id, - cls : 'x-btn-icon', - iconCls: 'x-edit-'+id, - enableToggle:toggle !== false, - scope: editor, - handler:handler||editor.relayBtnCmd, - clickEvent:'mousedown', - tooltip: tipsEnabled ? editor.buttonTips[id] || undefined : undefined, - overflowText: editor.buttonTips[id].title || undefined, - tabIndex:-1 - }; - } - - // build the toolbar - var tb = new Ext.Toolbar({ - renderTo:this.wrap.dom.firstChild - }); - - // stop form submits - this.mon(tb.el, 'click', function(e){ - e.preventDefault(); - }); - - if(this.enableFont && !Ext.isSafari2){ - this.fontSelect = tb.el.createChild({ - tag:'select', - cls:'x-font-select', - html: this.createFontOptions() - }); - this.mon(this.fontSelect, 'change', function(){ - var font = this.fontSelect.dom.value; - this.relayCmd('fontname', font); - this.deferFocus(); - }, this); - - tb.add( - this.fontSelect.dom, - '-' - ); - } - - if(this.enableFormat){ - tb.add( - btn('bold'), - btn('italic'), - btn('underline') - ); - } - - if(this.enableFontSize){ - tb.add( - '-', - btn('increasefontsize', false, this.adjustFont), - btn('decreasefontsize', false, this.adjustFont) - ); - } - - if(this.enableColors){ - tb.add( - '-', { - itemId:'forecolor', - cls:'x-btn-icon', - iconCls: 'x-edit-forecolor', - clickEvent:'mousedown', - tooltip: tipsEnabled ? editor.buttonTips.forecolor || undefined : undefined, - tabIndex:-1, - menu : new Ext.menu.ColorMenu({ - allowReselect: true, - focus: Ext.emptyFn, - value:'000000', - plain:true, - listeners: { - scope: this, - select: function(cp, color){ - this.execCmd('forecolor', Ext.isWebKit || Ext.isIE ? '#'+color : color); - this.deferFocus(); - } - }, - clickEvent:'mousedown' - }) - }, { - itemId:'backcolor', - cls:'x-btn-icon', - iconCls: 'x-edit-backcolor', - clickEvent:'mousedown', - tooltip: tipsEnabled ? editor.buttonTips.backcolor || undefined : undefined, - tabIndex:-1, - menu : new Ext.menu.ColorMenu({ - focus: Ext.emptyFn, - value:'FFFFFF', - plain:true, - allowReselect: true, - listeners: { - scope: this, - select: function(cp, color){ - if(Ext.isGecko){ - this.execCmd('useCSS', false); - this.execCmd('hilitecolor', color); - this.execCmd('useCSS', true); - this.deferFocus(); - }else{ - this.execCmd(Ext.isOpera ? 'hilitecolor' : 'backcolor', Ext.isWebKit || Ext.isIE ? '#'+color : color); - this.deferFocus(); - } - } - }, - clickEvent:'mousedown' - }) - } - ); - } - - if(this.enableAlignments){ - tb.add( - '-', - btn('justifyleft'), - btn('justifycenter'), - btn('justifyright') - ); - } - - if(!Ext.isSafari2){ - if(this.enableLinks){ - tb.add( - '-', - btn('createlink', false, this.createLink) - ); - } - - if(this.enableLists){ - tb.add( - '-', - btn('insertorderedlist'), - btn('insertunorderedlist') - ); - } - if(this.enableSourceEdit){ - tb.add( - '-', - btn('sourceedit', true, function(btn){ - this.toggleSourceEdit(!this.sourceEditMode); - }) - ); - } - } - - this.tb = tb; - }, - - /** - * Protected method that will not generally be called directly. It - * is called when the editor initializes the iframe with HTML contents. Override this method if you - * want to change the initialization markup of the iframe (e.g. to add stylesheets). - */ - getDocMarkup : function(){ - return ''; - }, - - // private - getEditorBody : function(){ - return this.doc.body || this.doc.documentElement; - }, - - // private - getDoc : function(){ - return Ext.isIE ? this.getWin().document : (this.iframe.contentDocument || this.getWin().document); - }, - - // private - getWin : function(){ - return Ext.isIE ? this.iframe.contentWindow : window.frames[this.iframe.name]; - }, - - // private - onRender : function(ct, position){ - Ext.form.HtmlEditor.superclass.onRender.call(this, ct, position); - this.el.dom.style.border = '0 none'; - this.el.dom.setAttribute('tabIndex', -1); - this.el.addClass('x-hidden'); - if(Ext.isIE){ // fix IE 1px bogus margin - this.el.applyStyles('margin-top:-1px;margin-bottom:-1px;') - } - this.wrap = this.el.wrap({ - cls:'x-html-editor-wrap', cn:{cls:'x-html-editor-tb'} - }); - - this.createToolbar(this); - - this.disableItems(true); - // is this needed? - // this.tb.doLayout(); - - this.createIFrame(); - - if(!this.width){ - var sz = this.el.getSize(); - this.setSize(sz.width, this.height || sz.height); - } - this.resizeEl = this.positionEl = this.wrap; - }, - - createIFrame: function(){ - var iframe = document.createElement('iframe'); - iframe.name = Ext.id(); - iframe.frameBorder = '0'; - iframe.src = Ext.SSL_SECURE_URL; - this.wrap.dom.appendChild(iframe); - - this.iframe = iframe; - - this.monitorTask = Ext.TaskMgr.start({ - run: this.checkDesignMode, - scope: this, - interval:100 - }); - }, - - initFrame : function(){ - Ext.TaskMgr.stop(this.monitorTask); - this.doc = this.getDoc(); - this.win = this.getWin(); - - this.doc.open(); - this.doc.write(this.getDocMarkup()); - this.doc.close(); - - var task = { // must defer to wait for browser to be ready - run : function(){ - if(this.doc.body || this.doc.readyState == 'complete'){ - Ext.TaskMgr.stop(task); - this.doc.designMode="on"; - this.initEditor.defer(10, this); - } - }, - interval : 10, - duration:10000, - scope: this - }; - Ext.TaskMgr.start(task); - }, - - - checkDesignMode : function(){ - if(this.wrap && this.wrap.dom.offsetWidth){ - var doc = this.getDoc(); - if(!doc){ - return; - } - if(!doc.editorInitialized || String(doc.designMode).toLowerCase() != 'on'){ - this.initFrame(); - } - } - }, - - disableItems: function(disabled){ - if(this.fontSelect){ - this.fontSelect.dom.disabled = disabled; - } - this.tb.items.each(function(item){ - if(item.getItemId() != 'sourceedit'){ - item.setDisabled(disabled); - } - }); - }, - - // private - onResize : function(w, h){ - Ext.form.HtmlEditor.superclass.onResize.apply(this, arguments); - if(this.el && this.iframe){ - if(Ext.isNumber(w)){ - var aw = w - this.wrap.getFrameWidth('lr'); - this.el.setWidth(aw); - this.tb.setWidth(aw); - this.iframe.style.width = Math.max(aw, 0) + 'px'; - } - if(Ext.isNumber(h)){ - var ah = h - this.wrap.getFrameWidth('tb') - this.tb.el.getHeight(); - this.el.setHeight(ah); - this.iframe.style.height = Math.max(ah, 0) + 'px'; - if(this.doc){ - this.getEditorBody().style.height = Math.max((ah - (this.iframePad*2)), 0) + 'px'; - } - } - } - }, - - /** - * Toggles the editor between standard and source edit mode. - * @param {Boolean} sourceEdit (optional) True for source edit, false for standard - */ - toggleSourceEdit : function(sourceEditMode){ - if(sourceEditMode === undefined){ - sourceEditMode = !this.sourceEditMode; - } - this.sourceEditMode = sourceEditMode === true; - var btn = this.tb.items.get('sourceedit'); - if(btn.pressed !== this.sourceEditMode){ - btn.toggle(this.sourceEditMode); - if(!btn.xtbHidden){ - return; - } - } - if(this.sourceEditMode){ - this.disableItems(true); - this.syncValue(); - this.iframe.className = 'x-hidden'; - this.el.removeClass('x-hidden'); - this.el.dom.removeAttribute('tabIndex'); - this.el.focus(); - }else{ - if(this.initialized){ - this.disableItems(false); - } - this.pushValue(); - this.iframe.className = ''; - this.el.addClass('x-hidden'); - this.el.dom.setAttribute('tabIndex', -1); - this.deferFocus(); - } - var lastSize = this.lastSize; - if(lastSize){ - delete this.lastSize; - this.setSize(lastSize); - } - this.fireEvent('editmodechange', this, this.sourceEditMode); - }, - - // private used internally - createLink : function(){ - var url = prompt(this.createLinkText, this.defaultLinkValue); - if(url && url != 'http:/'+'/'){ - this.relayCmd('createlink', url); - } - }, - - // private - initEvents : function(){ - this.originalValue = this.getValue(); - }, - - /** - * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide - * @method - */ - markInvalid : Ext.emptyFn, - - /** - * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide - * @method - */ - clearInvalid : Ext.emptyFn, - - // docs inherit from Field - setValue : function(v){ - Ext.form.HtmlEditor.superclass.setValue.call(this, v); - this.pushValue(); - return this; - }, - - /** - * Protected method that will not generally be called directly. If you need/want - * custom HTML cleanup, this is the method you should override. - * @param {String} html The HTML to be cleaned - * @return {String} The cleaned HTML - */ - cleanHtml: function(html) { - html = String(html); - if(Ext.isWebKit){ // strip safari nonsense - html = html.replace(/\sclass="(?:Apple-style-span|khtml-block-placeholder)"/gi, ''); - } - - /* - * Neat little hack. Strips out all the non-digit characters from the default - * value and compares it to the character code of the first character in the string - * because it can cause encoding issues when posted to the server. - */ - if(html.charCodeAt(0) == this.defaultValue.replace(/\D/g, '')){ - html = html.substring(1); - } - return html; - }, - - /** - * Protected method that will not generally be called directly. Syncs the contents - * of the editor iframe with the textarea. - */ - syncValue : function(){ - if(this.initialized){ - var bd = this.getEditorBody(); - var html = bd.innerHTML; - if(Ext.isWebKit){ - var bs = bd.getAttribute('style'); // Safari puts text-align styles on the body element! - var m = bs.match(/text-align:(.*?);/i); - if(m && m[1]){ - html = '
' + html + '
'; - } - } - html = this.cleanHtml(html); - if(this.fireEvent('beforesync', this, html) !== false){ - this.el.dom.value = html; - this.fireEvent('sync', this, html); - } - } - }, - - //docs inherit from Field - getValue : function() { - this[this.sourceEditMode ? 'pushValue' : 'syncValue'](); - return Ext.form.HtmlEditor.superclass.getValue.call(this); - }, - - /** - * Protected method that will not generally be called directly. Pushes the value of the textarea - * into the iframe editor. - */ - pushValue : function(){ - if(this.initialized){ - var v = this.el.dom.value; - if(!this.activated && v.length < 1){ - v = this.defaultValue; - } - if(this.fireEvent('beforepush', this, v) !== false){ - this.getEditorBody().innerHTML = v; - if(Ext.isGecko){ - // Gecko hack, see: https://bugzilla.mozilla.org/show_bug.cgi?id=232791#c8 - var d = this.doc, - mode = d.designMode.toLowerCase(); - - d.designMode = mode.toggle('on', 'off'); - d.designMode = mode; - } - this.fireEvent('push', this, v); - } - } - }, - - // private - deferFocus : function(){ - this.focus.defer(10, this); - }, - - // docs inherit from Field - focus : function(){ - if(this.win && !this.sourceEditMode){ - this.win.focus(); - }else{ - this.el.focus(); - } - }, - - // private - initEditor : function(){ - //Destroying the component during/before initEditor can cause issues. - try{ - var dbody = this.getEditorBody(); - var ss = this.el.getStyles('font-size', 'font-family', 'background-image', 'background-repeat'); - ss['background-attachment'] = 'fixed'; // w3c - dbody.bgProperties = 'fixed'; // ie - - Ext.DomHelper.applyStyles(dbody, ss); - - if(this.doc){ - try{ - Ext.EventManager.removeAll(this.doc); - }catch(e){} - } - - this.doc = this.getDoc(); - - Ext.EventManager.on(this.doc, { - 'mousedown': this.onEditorEvent, - 'dblclick': this.onEditorEvent, - 'click': this.onEditorEvent, - 'keyup': this.onEditorEvent, - buffer:100, - scope: this - }); - - if(Ext.isGecko){ - Ext.EventManager.on(this.doc, 'keypress', this.applyCommand, this); - } - if(Ext.isIE || Ext.isWebKit || Ext.isOpera){ - Ext.EventManager.on(this.doc, 'keydown', this.fixKeys, this); - } - this.initialized = true; - this.fireEvent('initialize', this); - this.doc.editorInitialized = true; - this.pushValue(); - }catch(e){} - }, - - // private - onDestroy : function(){ - if(this.monitorTask){ - Ext.TaskMgr.stop(this.monitorTask); - } - if(this.rendered){ - Ext.destroy(this.tb); - if(this.wrap){ - this.wrap.dom.innerHTML = ''; - this.wrap.remove(); - } - } - if(this.el){ - this.el.removeAllListeners(); - this.el.remove(); - } - - if(this.doc){ - try{ - Ext.EventManager.removeAll(this.doc); - for (var prop in this.doc){ - delete this.doc[prop]; - } - }catch(e){} - } - this.purgeListeners(); - }, - - // private - onFirstFocus : function(){ - this.activated = true; - this.disableItems(false); - if(Ext.isGecko){ // prevent silly gecko errors - this.win.focus(); - var s = this.win.getSelection(); - if(!s.focusNode || s.focusNode.nodeType != 3){ - var r = s.getRangeAt(0); - r.selectNodeContents(this.getEditorBody()); - r.collapse(true); - this.deferFocus(); - } - try{ - this.execCmd('useCSS', true); - this.execCmd('styleWithCSS', false); - }catch(e){} - } - this.fireEvent('activate', this); - }, - - // private - adjustFont: function(btn){ - var adjust = btn.getItemId() == 'increasefontsize' ? 1 : -1; - - var v = parseInt(this.doc.queryCommandValue('FontSize') || 2, 10); - if((Ext.isSafari && !Ext.isSafari2) || Ext.isChrome || Ext.isAir){ - // Safari 3 values - // 1 = 10px, 2 = 13px, 3 = 16px, 4 = 18px, 5 = 24px, 6 = 32px - if(v <= 10){ - v = 1 + adjust; - }else if(v <= 13){ - v = 2 + adjust; - }else if(v <= 16){ - v = 3 + adjust; - }else if(v <= 18){ - v = 4 + adjust; - }else if(v <= 24){ - v = 5 + adjust; - }else { - v = 6 + adjust; - } - v = v.constrain(1, 6); - }else{ - if(Ext.isSafari){ // safari - adjust *= 2; - } - v = Math.max(1, v+adjust) + (Ext.isSafari ? 'px' : 0); - } - this.execCmd('FontSize', v); - }, - - // private - onEditorEvent : function(e){ - this.updateToolbar(); - }, - - - /** - * Protected method that will not generally be called directly. It triggers - * a toolbar update by reading the markup state of the current selection in the editor. - */ - updateToolbar: function(){ - - if(!this.activated){ - this.onFirstFocus(); - return; - } - - var btns = this.tb.items.map, doc = this.doc; - - if(this.enableFont && !Ext.isSafari2){ - var name = (this.doc.queryCommandValue('FontName')||this.defaultFont).toLowerCase(); - if(name != this.fontSelect.dom.value){ - this.fontSelect.dom.value = name; - } - } - if(this.enableFormat){ - btns.bold.toggle(doc.queryCommandState('bold')); - btns.italic.toggle(doc.queryCommandState('italic')); - btns.underline.toggle(doc.queryCommandState('underline')); - } - if(this.enableAlignments){ - btns.justifyleft.toggle(doc.queryCommandState('justifyleft')); - btns.justifycenter.toggle(doc.queryCommandState('justifycenter')); - btns.justifyright.toggle(doc.queryCommandState('justifyright')); - } - if(!Ext.isSafari2 && this.enableLists){ - btns.insertorderedlist.toggle(doc.queryCommandState('insertorderedlist')); - btns.insertunorderedlist.toggle(doc.queryCommandState('insertunorderedlist')); - } - - Ext.menu.MenuMgr.hideAll(); - - this.syncValue(); - }, - - // private - relayBtnCmd : function(btn){ - this.relayCmd(btn.getItemId()); - }, - - /** - * Executes a Midas editor command on the editor document and performs necessary focus and - * toolbar updates. This should only be called after the editor is initialized. - * @param {String} cmd The Midas command - * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null) - */ - relayCmd : function(cmd, value){ - (function(){ - this.focus(); - this.execCmd(cmd, value); - this.updateToolbar(); - }).defer(10, this); - }, - - /** - * Executes a Midas editor command directly on the editor document. - * For visual commands, you should use {@link #relayCmd} instead. - * This should only be called after the editor is initialized. - * @param {String} cmd The Midas command - * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null) - */ - execCmd : function(cmd, value){ - this.doc.execCommand(cmd, false, value === undefined ? null : value); - this.syncValue(); - }, - - // private - applyCommand : function(e){ - if(e.ctrlKey){ - var c = e.getCharCode(), cmd; - if(c > 0){ - c = String.fromCharCode(c); - switch(c){ - case 'b': - cmd = 'bold'; - break; - case 'i': - cmd = 'italic'; - break; - case 'u': - cmd = 'underline'; - break; - } - if(cmd){ - this.win.focus(); - this.execCmd(cmd); - this.deferFocus(); - e.preventDefault(); - } - } - } - }, - - /** - * Inserts the passed text at the current cursor position. Note: the editor must be initialized and activated - * to insert text. - * @param {String} text - */ - insertAtCursor : function(text){ - if(!this.activated){ - return; - } - if(Ext.isIE){ - this.win.focus(); - var r = this.doc.selection.createRange(); - if(r){ - r.collapse(true); - r.pasteHTML(text); - this.syncValue(); - this.deferFocus(); - } - }else{ - this.win.focus(); - this.execCmd('InsertHTML', text); - this.deferFocus(); - } - }, - - // private - fixKeys : function(){ // load time branching for fastest keydown performance - if(Ext.isIE){ - return function(e){ - var k = e.getKey(), r; - if(k == e.TAB){ - e.stopEvent(); - r = this.doc.selection.createRange(); - if(r){ - r.collapse(true); - r.pasteHTML('    '); - this.deferFocus(); - } - }else if(k == e.ENTER){ - r = this.doc.selection.createRange(); - if(r){ - var target = r.parentElement(); - if(!target || target.tagName.toLowerCase() != 'li'){ - e.stopEvent(); - r.pasteHTML('
'); - r.collapse(false); - r.select(); - } - } - } - }; - }else if(Ext.isOpera){ - return function(e){ - var k = e.getKey(); - if(k == e.TAB){ - e.stopEvent(); - this.win.focus(); - this.execCmd('InsertHTML','    '); - this.deferFocus(); - } - }; - }else if(Ext.isWebKit){ - return function(e){ - var k = e.getKey(); - if(k == e.TAB){ - e.stopEvent(); - this.execCmd('InsertText','\t'); - this.deferFocus(); - }else if(k == e.ENTER){ - e.stopEvent(); - this.execCmd('InsertHtml','

'); - this.deferFocus(); - } - }; - } - }(), - - /** - * Returns the editor's toolbar. This is only available after the editor has been rendered. - * @return {Ext.Toolbar} - */ - getToolbar : function(){ - return this.tb; - }, - - /** - * Object collection of toolbar tooltips for the buttons in the editor. The key - * is the command id associated with that button and the value is a valid QuickTips object. - * For example: -

-{
-    bold : {
-        title: 'Bold (Ctrl+B)',
-        text: 'Make the selected text bold.',
-        cls: 'x-html-editor-tip'
-    },
-    italic : {
-        title: 'Italic (Ctrl+I)',
-        text: 'Make the selected text italic.',
-        cls: 'x-html-editor-tip'
-    },
-    ...
-
- * @type Object - */ - buttonTips : { - bold : { - title: 'Bold (Ctrl+B)', - text: 'Make the selected text bold.', - cls: 'x-html-editor-tip' - }, - italic : { - title: 'Italic (Ctrl+I)', - text: 'Make the selected text italic.', - cls: 'x-html-editor-tip' - }, - underline : { - title: 'Underline (Ctrl+U)', - text: 'Underline the selected text.', - cls: 'x-html-editor-tip' - }, - increasefontsize : { - title: 'Grow Text', - text: 'Increase the font size.', - cls: 'x-html-editor-tip' - }, - decreasefontsize : { - title: 'Shrink Text', - text: 'Decrease the font size.', - cls: 'x-html-editor-tip' - }, - backcolor : { - title: 'Text Highlight Color', - text: 'Change the background color of the selected text.', - cls: 'x-html-editor-tip' - }, - forecolor : { - title: 'Font Color', - text: 'Change the color of the selected text.', - cls: 'x-html-editor-tip' - }, - justifyleft : { - title: 'Align Text Left', - text: 'Align text to the left.', - cls: 'x-html-editor-tip' - }, - justifycenter : { - title: 'Center Text', - text: 'Center text in the editor.', - cls: 'x-html-editor-tip' - }, - justifyright : { - title: 'Align Text Right', - text: 'Align text to the right.', - cls: 'x-html-editor-tip' - }, - insertunorderedlist : { - title: 'Bullet List', - text: 'Start a bulleted list.', - cls: 'x-html-editor-tip' - }, - insertorderedlist : { - title: 'Numbered List', - text: 'Start a numbered list.', - cls: 'x-html-editor-tip' - }, - createlink : { - title: 'Hyperlink', - text: 'Make the selected text a hyperlink.', - cls: 'x-html-editor-tip' - }, - sourceedit : { - title: 'Source Edit', - text: 'Switch to source editing mode.', - cls: 'x-html-editor-tip' - } - } - - // hide stuff that is not compatible - /** - * @event blur - * @hide - */ - /** - * @event change - * @hide - */ - /** - * @event focus - * @hide - */ - /** - * @event specialkey - * @hide - */ - /** - * @cfg {String} fieldClass @hide - */ - /** - * @cfg {String} focusClass @hide - */ - /** - * @cfg {String} autoCreate @hide - */ - /** - * @cfg {String} inputType @hide - */ - /** - * @cfg {String} invalidClass @hide - */ - /** - * @cfg {String} invalidText @hide - */ - /** - * @cfg {String} msgFx @hide - */ - /** - * @cfg {String} validateOnBlur @hide - */ - /** - * @cfg {Boolean} allowDomMove @hide - */ - /** - * @cfg {String} applyTo @hide - */ - /** - * @cfg {String} autoHeight @hide - */ - /** - * @cfg {String} autoWidth @hide - */ - /** - * @cfg {String} cls @hide - */ - /** - * @cfg {String} disabled @hide - */ - /** - * @cfg {String} disabledClass @hide - */ - /** - * @cfg {String} msgTarget @hide - */ - /** - * @cfg {String} readOnly @hide - */ - /** - * @cfg {String} style @hide - */ - /** - * @cfg {String} validationDelay @hide - */ - /** - * @cfg {String} validationEvent @hide - */ - /** - * @cfg {String} tabIndex @hide - */ - /** - * @property disabled - * @hide - */ - /** - * @method applyToMarkup - * @hide - */ - /** - * @method disable - * @hide - */ - /** - * @method enable - * @hide - */ - /** - * @method validate - * @hide - */ - /** - * @event valid - * @hide - */ - /** - * @method setDisabled - * @hide - */ - /** - * @cfg keys - * @hide - */ -}); -Ext.reg('htmleditor', Ext.form.HtmlEditor);/** - * @class Ext.form.TimeField - * @extends Ext.form.ComboBox - * Provides a time input field with a time dropdown and automatic time validation. Example usage: - *

-new Ext.form.TimeField({
-    minValue: '9:00 AM',
-    maxValue: '6:00 PM',
-    increment: 30
-});
-
- * @constructor - * Create a new TimeField - * @param {Object} config - * @xtype timefield - */ -Ext.form.TimeField = Ext.extend(Ext.form.ComboBox, { - /** - * @cfg {Date/String} minValue - * The minimum allowed time. Can be either a Javascript date object with a valid time value or a string - * time in a valid format -- see {@link #format} and {@link #altFormats} (defaults to null). - */ - minValue : null, - /** - * @cfg {Date/String} maxValue - * The maximum allowed time. Can be either a Javascript date object with a valid time value or a string - * time in a valid format -- see {@link #format} and {@link #altFormats} (defaults to null). - */ - maxValue : null, - /** - * @cfg {String} minText - * The error text to display when the date in the cell is before minValue (defaults to - * 'The time in this field must be equal to or after {0}'). - */ - minText : "The time in this field must be equal to or after {0}", - /** - * @cfg {String} maxText - * The error text to display when the time is after maxValue (defaults to - * 'The time in this field must be equal to or before {0}'). - */ - maxText : "The time in this field must be equal to or before {0}", - /** - * @cfg {String} invalidText - * The error text to display when the time in the field is invalid (defaults to - * '{value} is not a valid time'). - */ - invalidText : "{0} is not a valid time", - /** - * @cfg {String} format - * The default time format string which can be overriden for localization support. The format must be - * valid according to {@link Date#parseDate} (defaults to 'g:i A', e.g., '3:15 PM'). For 24-hour time - * format try 'H:i' instead. - */ - format : "g:i A", - /** - * @cfg {String} altFormats - * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined - * format (defaults to 'g:ia|g:iA|g:i a|g:i A|h:i|g:i|H:i|ga|ha|gA|h a|g a|g A|gi|hi|gia|hia|g|H'). - */ - altFormats : "g:ia|g:iA|g:i a|g:i A|h:i|g:i|H:i|ga|ha|gA|h a|g a|g A|gi|hi|gia|hia|g|H", - /** - * @cfg {Number} increment - * The number of minutes between each time value in the list (defaults to 15). - */ - increment: 15, - - // private override - mode: 'local', - // private override - triggerAction: 'all', - // private override - typeAhead: false, - - // private - This is the date to use when generating time values in the absence of either minValue - // or maxValue. Using the current date causes DST issues on DST boundary dates, so this is an - // arbitrary "safe" date that can be any date aside from DST boundary dates. - initDate: '1/1/2008', - - // private - initComponent : function(){ - if(typeof this.minValue == "string"){ - this.minValue = this.parseDate(this.minValue); - } - if(typeof this.maxValue == "string"){ - this.maxValue = this.parseDate(this.maxValue); - } - - if(!this.store){ - var min = this.parseDate(this.minValue) || new Date(this.initDate).clearTime(); - var max = this.parseDate(this.maxValue) || new Date(this.initDate).clearTime().add('mi', (24 * 60) - 1); - var times = []; - while(min <= max){ - times.push(min.dateFormat(this.format)); - min = min.add('mi', this.increment); - } - this.store = times; - } - Ext.form.TimeField.superclass.initComponent.call(this); - }, - - // inherited docs - getValue : function(){ - var v = Ext.form.TimeField.superclass.getValue.call(this); - return this.formatDate(this.parseDate(v)) || ''; - }, - - // inherited docs - setValue : function(value){ - return Ext.form.TimeField.superclass.setValue.call(this, this.formatDate(this.parseDate(value))); - }, - - // private overrides - validateValue : Ext.form.DateField.prototype.validateValue, - parseDate : Ext.form.DateField.prototype.parseDate, - formatDate : Ext.form.DateField.prototype.formatDate, - - // private - beforeBlur : function(){ - var v = this.parseDate(this.getRawValue()); - if(v){ - this.setValue(v.dateFormat(this.format)); - } - Ext.form.TimeField.superclass.beforeBlur.call(this); - } - - /** - * @cfg {Boolean} grow @hide - */ - /** - * @cfg {Number} growMin @hide - */ - /** - * @cfg {Number} growMax @hide - */ - /** - * @hide - * @method autoSize - */ -}); -Ext.reg('timefield', Ext.form.TimeField);/** - * @class Ext.form.Label - * @extends Ext.BoxComponent - * Basic Label field. - * @constructor - * Creates a new Label - * @param {Ext.Element/String/Object} config The configuration options. If an element is passed, it is set as the internal - * element and its id used as the component id. If a string is passed, it is assumed to be the id of an existing element - * and is used as the component id. Otherwise, it is assumed to be a standard config object and is applied to the component. - * @xtype label - */ -Ext.form.Label = Ext.extend(Ext.BoxComponent, { - /** - * @cfg {String} text The plain text to display within the label (defaults to ''). If you need to include HTML - * tags within the label's innerHTML, use the {@link #html} config instead. - */ - /** - * @cfg {String} forId The id of the input element to which this label will be bound via the standard HTML 'for' - * attribute. If not specified, the attribute will not be added to the label. - */ - /** - * @cfg {String} html An HTML fragment that will be used as the label's innerHTML (defaults to ''). - * Note that if {@link #text} is specified it will take precedence and this value will be ignored. - */ + this.removeRows(firstRow, lastRow); - // private - onRender : function(ct, position){ - if(!this.el){ - this.el = document.createElement('label'); - this.el.id = this.getId(); - this.el.innerHTML = this.text ? Ext.util.Format.htmlEncode(this.text) : (this.html || ''); - if(this.forId){ - this.el.setAttribute('for', this.forId); - } + this.processRows(firstRow); + this.fireEvent('rowsdeleted', this, firstRow, lastRow); } - Ext.form.Label.superclass.onRender.call(this, ct, position); }, - /** - * Updates the label's innerHTML with the specified string. - * @param {String} text The new label text - * @param {Boolean} encode (optional) False to skip HTML-encoding the text when rendering it - * to the label (defaults to true which encodes the value). This might be useful if you want to include - * tags in the label's innerHTML rather than rendering them as string literals per the default logic. - * @return {Label} this - */ - setText : function(t, encode){ - var e = encode === false; - this[!e ? 'text' : 'html'] = t; - delete this[e ? 'text' : 'html']; - if(this.rendered){ - this.el.dom.innerHTML = encode !== false ? Ext.util.Format.htmlEncode(t) : t; + + getColumnStyle : function(colIndex, isHeader) { + var colModel = this.cm, + colConfig = colModel.config, + style = isHeader ? '' : colConfig[colIndex].css || '', + align = colConfig[colIndex].align; + + style += String.format("width: {0};", this.getColumnWidth(colIndex)); + + if (colModel.isHidden(colIndex)) { + style += 'display: none; '; } - return this; - } -}); - -Ext.reg('label', Ext.form.Label);/** - * @class Ext.form.Action - *

The subclasses of this class provide actions to perform upon {@link Ext.form.BasicForm Form}s.

- *

Instances of this class are only created by a {@link Ext.form.BasicForm Form} when - * the Form needs to perform an action such as submit or load. The Configuration options - * listed for this class are set through the Form's action methods: {@link Ext.form.BasicForm#submit submit}, - * {@link Ext.form.BasicForm#load load} and {@link Ext.form.BasicForm#doAction doAction}

- *

The instance of Action which performed the action is passed to the success - * and failure callbacks of the Form's action methods ({@link Ext.form.BasicForm#submit submit}, - * {@link Ext.form.BasicForm#load load} and {@link Ext.form.BasicForm#doAction doAction}), - * and to the {@link Ext.form.BasicForm#actioncomplete actioncomplete} and - * {@link Ext.form.BasicForm#actionfailed actionfailed} event handlers.

- */ -Ext.form.Action = function(form, options){ - this.form = form; - this.options = options || {}; -}; - -/** - * Failure type returned when client side validation of the Form fails - * thus aborting a submit action. Client side validation is performed unless - * {@link #clientValidation} is explicitly set to false. - * @type {String} - * @static - */ -Ext.form.Action.CLIENT_INVALID = 'client'; -/** - *

Failure type returned when server side processing fails and the {@link #result}'s - * success property is set to false.

- *

In the case of a form submission, field-specific error messages may be returned in the - * {@link #result}'s errors property.

- * @type {String} - * @static - */ -Ext.form.Action.SERVER_INVALID = 'server'; -/** - * Failure type returned when a communication error happens when attempting - * to send a request to the remote server. The {@link #response} may be examined to - * provide further information. - * @type {String} - * @static - */ -Ext.form.Action.CONNECT_FAILURE = 'connect'; -/** - * Failure type returned when the response's success - * property is set to false, or no field values are returned in the response's - * data property. - * @type {String} - * @static - */ -Ext.form.Action.LOAD_FAILURE = 'load'; - -Ext.form.Action.prototype = { -/** - * @cfg {String} url The URL that the Action is to invoke. - */ -/** - * @cfg {Boolean} reset When set to true, causes the Form to be - * {@link Ext.form.BasicForm.reset reset} on Action success. If specified, this happens - * before the {@link #success} callback is called and before the Form's - * {@link Ext.form.BasicForm.actioncomplete actioncomplete} event fires. - */ -/** - * @cfg {String} method The HTTP method to use to access the requested URL. Defaults to the - * {@link Ext.form.BasicForm}'s method, or if that is not specified, the underlying DOM form's method. - */ -/** - * @cfg {Mixed} params

Extra parameter values to pass. These are added to the Form's - * {@link Ext.form.BasicForm#baseParams} and passed to the specified URL along with the Form's - * input fields.

- *

Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.

- */ -/** - * @cfg {Number} timeout The number of seconds to wait for a server response before - * failing with the {@link #failureType} as {@link #Action.CONNECT_FAILURE}. If not specified, - * defaults to the configured {@link Ext.form.BasicForm#timeout timeout} of the - * {@link Ext.form.BasicForm form}. - */ -/** - * @cfg {Function} success The function to call when a valid success return packet is recieved. - * The function is passed the following parameters:
    - *
  • form : Ext.form.BasicForm
    The form that requested the action
  • - *
  • action : Ext.form.Action
    The Action class. The {@link #result} - * property of this object may be examined to perform custom postprocessing.
  • - *
- */ -/** - * @cfg {Function} failure The function to call when a failure packet was recieved, or when an - * error ocurred in the Ajax communication. - * The function is passed the following parameters:
    - *
  • form : Ext.form.BasicForm
    The form that requested the action
  • - *
  • action : Ext.form.Action
    The Action class. If an Ajax - * error ocurred, the failure type will be in {@link #failureType}. The {@link #result} - * property of this object may be examined to perform custom postprocessing.
  • - *
- */ -/** - * @cfg {Object} scope The scope in which to call the callback functions (The this reference - * for the callback functions). - */ -/** - * @cfg {String} waitMsg The message to be displayed by a call to {@link Ext.MessageBox#wait} - * during the time the action is being processed. - */ -/** - * @cfg {String} waitTitle The title to be displayed by a call to {@link Ext.MessageBox#wait} - * during the time the action is being processed. - */ - -/** - * The type of action this Action instance performs. - * Currently only "submit" and "load" are supported. - * @type {String} - */ - type : 'default', -/** - * The type of failure detected will be one of these: {@link #CLIENT_INVALID}, - * {@link #SERVER_INVALID}, {@link #CONNECT_FAILURE}, or {@link #LOAD_FAILURE}. Usage: - *

-var fp = new Ext.form.FormPanel({
-...
-buttons: [{
-    text: 'Save',
-    formBind: true,
-    handler: function(){
-        if(fp.getForm().isValid()){
-            fp.getForm().submit({
-                url: 'form-submit.php',
-                waitMsg: 'Submitting your data...',
-                success: function(form, action){
-                    // server responded with success = true
-                    var result = action.{@link #result};
-                },
-                failure: function(form, action){
-                    if (action.{@link #failureType} === Ext.form.Action.{@link #CONNECT_FAILURE}) {
-                        Ext.Msg.alert('Error',
-                            'Status:'+action.{@link #response}.status+': '+
-                            action.{@link #response}.statusText);
-                    }
-                    if (action.failureType === Ext.form.Action.{@link #SERVER_INVALID}){
-                        // server responded with success = false
-                        Ext.Msg.alert('Invalid', action.{@link #result}.errormsg);
-                    }
-                }
-            });
-        }
-    }
-},{
-    text: 'Reset',
-    handler: function(){
-        fp.getForm().reset();
-    }
-}]
- * 
- * @property failureType - * @type {String} - */ - /** - * The XMLHttpRequest object used to perform the action. - * @property response - * @type {Object} - */ - /** - * The decoded response object containing a boolean success property and - * other, action-specific properties. - * @property result - * @type {Object} - */ - - // interface method - run : function(options){ - - }, - - // interface method - success : function(response){ - - }, - - // interface method - handleResponse : function(response){ - - }, - - // default connection failure - failure : function(response){ - this.response = response; - this.failureType = Ext.form.Action.CONNECT_FAILURE; - this.form.afterAction(this, false); - }, - - // private - // shared code among all Actions to validate that there was a response - // with either responseText or responseXml - processResponse : function(response){ - this.response = response; - if(!response.responseText && !response.responseXML){ - return true; - } - this.result = this.handleResponse(response); - return this.result; - }, - - // utility functions used internally - getUrl : function(appendParams){ - var url = this.options.url || this.form.url || this.form.el.dom.action; - if(appendParams){ - var p = this.getParams(); - if(p){ - url = Ext.urlAppend(url, p); - } - } - return url; - }, - - // private - getMethod : function(){ - return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase(); - }, - - // private - getParams : function(){ - var bp = this.form.baseParams; - var p = this.options.params; - if(p){ - if(typeof p == "object"){ - p = Ext.urlEncode(Ext.applyIf(p, bp)); - }else if(typeof p == 'string' && bp){ - p += '&' + Ext.urlEncode(bp); - } - }else if(bp){ - p = Ext.urlEncode(bp); - } - return p; - }, - - // private - createCallback : function(opts){ - var opts = opts || {}; - return { - success: this.success, - failure: this.failure, - scope: this, - timeout: (opts.timeout*1000) || (this.form.timeout*1000), - upload: this.form.fileUpload ? this.success : undefined - }; - } -}; - -/** - * @class Ext.form.Action.Submit - * @extends Ext.form.Action - *

A class which handles submission of data from {@link Ext.form.BasicForm Form}s - * and processes the returned response.

- *

Instances of this class are only created by a {@link Ext.form.BasicForm Form} when - * {@link Ext.form.BasicForm#submit submit}ting.

- *

Response Packet Criteria

- *

A response packet may contain: - *

    - *
  • success property : Boolean - *
    The success property is required.
  • - *
  • errors property : Object - *
    The errors property, - * which is optional, contains error messages for invalid fields.
  • - *
- *

JSON Packets

- *

By default, response packets are assumed to be JSON, so a typical response - * packet may look like this:


-{
-    success: false,
-    errors: {
-        clientCode: "Client not found",
-        portOfLoading: "This field must not be null"
-    }
-}
- *

Other data may be placed into the response for processing by the {@link Ext.form.BasicForm}'s callback - * or event handler methods. The object decoded from this JSON is available in the - * {@link Ext.form.Action#result result} property.

- *

Alternatively, if an {@link #errorReader} is specified as an {@link Ext.data.XmlReader XmlReader}:


-    errorReader: new Ext.data.XmlReader({
-            record : 'field',
-            success: '@success'
-        }, [
-            'id', 'msg'
-        ]
-    )
-
- *

then the results may be sent back in XML format:


-<?xml version="1.0" encoding="UTF-8"?>
-<message success="false">
-<errors>
-    <field>
-        <id>clientCode</id>
-        <msg><![CDATA[Code not found. <br /><i>This is a test validation message from the server </i>]]></msg>
-    </field>
-    <field>
-        <id>portOfLoading</id>
-        <msg><![CDATA[Port not found. <br /><i>This is a test validation message from the server </i>]]></msg>
-    </field>
-</errors>
-</message>
-
- *

Other elements may be placed into the response XML for processing by the {@link Ext.form.BasicForm}'s callback - * or event handler methods. The XML document is available in the {@link #errorReader}'s {@link Ext.data.XmlReader#xmlData xmlData} property.

- */ -Ext.form.Action.Submit = function(form, options){ - Ext.form.Action.Submit.superclass.constructor.call(this, form, options); -}; - -Ext.extend(Ext.form.Action.Submit, Ext.form.Action, { - /** - * @cfg {Ext.data.DataReader} errorReader

Optional. JSON is interpreted with - * no need for an errorReader.

- *

A Reader which reads a single record from the returned data. The DataReader's - * success property specifies how submission success is determined. The Record's - * data provides the error messages to apply to any invalid form Fields.

- */ - /** - * @cfg {boolean} clientValidation Determines whether a Form's fields are validated - * in a final call to {@link Ext.form.BasicForm#isValid isValid} prior to submission. - * Pass false in the Form's submit options to prevent this. If not defined, pre-submission field validation - * is performed. - */ - type : 'submit', - - // private - run : function(){ - var o = this.options; - var method = this.getMethod(); - var isGet = method == 'GET'; - if(o.clientValidation === false || this.form.isValid()){ - Ext.Ajax.request(Ext.apply(this.createCallback(o), { - form:this.form.el.dom, - url:this.getUrl(isGet), - method: method, - headers: o.headers, - params:!isGet ? this.getParams() : null, - isUpload: this.form.fileUpload - })); - }else if (o.clientValidation !== false){ // client validation failed - this.failureType = Ext.form.Action.CLIENT_INVALID; - this.form.afterAction(this, false); - } - }, - - // private - success : function(response){ - var result = this.processResponse(response); - if(result === true || result.success){ - this.form.afterAction(this, true); - return; - } - if(result.errors){ - this.form.markInvalid(result.errors); - } - this.failureType = Ext.form.Action.SERVER_INVALID; - this.form.afterAction(this, false); - }, - - // private - handleResponse : function(response){ - if(this.form.errorReader){ - var rs = this.form.errorReader.read(response); - var errors = []; - if(rs.records){ - for(var i = 0, len = rs.records.length; i < len; i++) { - var r = rs.records[i]; - errors[i] = r.data; - } - } - if(errors.length < 1){ - errors = null; - } - return { - success : rs.success, - errors : errors - }; - } - return Ext.decode(response.responseText); - } -}); - - -/** - * @class Ext.form.Action.Load - * @extends Ext.form.Action - *

A class which handles loading of data from a server into the Fields of an {@link Ext.form.BasicForm}.

- *

Instances of this class are only created by a {@link Ext.form.BasicForm Form} when - * {@link Ext.form.BasicForm#load load}ing.

- *

Response Packet Criteria

- *

A response packet must contain: - *

    - *
  • success property : Boolean
  • - *
  • data property : Object
  • - *
    The data property contains the values of Fields to load. - * The individual value object for each Field is passed to the Field's - * {@link Ext.form.Field#setValue setValue} method.
    - *
- *

JSON Packets

- *

By default, response packets are assumed to be JSON, so for the following form load call:


-var myFormPanel = new Ext.form.FormPanel({
-    title: 'Client and routing info',
-    items: [{
-        fieldLabel: 'Client',
-        name: 'clientName'
-    }, {
-        fieldLabel: 'Port of loading',
-        name: 'portOfLoading'
-    }, {
-        fieldLabel: 'Port of discharge',
-        name: 'portOfDischarge'
-    }]
-});
-myFormPanel.{@link Ext.form.FormPanel#getForm getForm}().{@link Ext.form.BasicForm#load load}({
-    url: '/getRoutingInfo.php',
-    params: {
-        consignmentRef: myConsignmentRef
-    },
-    failure: function(form, action) {
-        Ext.Msg.alert("Load failed", action.result.errorMessage);
-    }
-});
-
- * a success response packet may look like this:


-{
-    success: true,
-    data: {
-        clientName: "Fred. Olsen Lines",
-        portOfLoading: "FXT",
-        portOfDischarge: "OSL"
-    }
-}
- * while a failure response packet may look like this:


-{
-    success: false,
-    errorMessage: "Consignment reference not found"
-}
- *

Other data may be placed into the response for processing the {@link Ext.form.BasicForm Form}'s - * callback or event handler methods. The object decoded from this JSON is available in the - * {@link Ext.form.Action#result result} property.

- */ -Ext.form.Action.Load = function(form, options){ - Ext.form.Action.Load.superclass.constructor.call(this, form, options); - this.reader = this.form.reader; -}; - -Ext.extend(Ext.form.Action.Load, Ext.form.Action, { - // private - type : 'load', - - // private - run : function(){ - Ext.Ajax.request(Ext.apply( - this.createCallback(this.options), { - method:this.getMethod(), - url:this.getUrl(false), - headers: this.options.headers, - params:this.getParams() - })); - }, - - // private - success : function(response){ - var result = this.processResponse(response); - if(result === true || !result.success || !result.data){ - this.failureType = Ext.form.Action.LOAD_FAILURE; - this.form.afterAction(this, false); - return; - } - this.form.clearInvalid(); - this.form.setValues(result.data); - this.form.afterAction(this, true); - }, - - // private - handleResponse : function(response){ - if(this.form.reader){ - var rs = this.form.reader.read(response); - var data = rs.records && rs.records[0] ? rs.records[0].data : null; - return { - success : rs.success, - data : data - }; - } - return Ext.decode(response.responseText); - } -}); - - - -/** - * @class Ext.form.Action.DirectLoad - * @extends Ext.form.Action.Load - *

Provides Ext.direct support for loading form data.

- *

This example illustrates usage of Ext.Direct to load a form through Ext.Direct.

- *

-var myFormPanel = new Ext.form.FormPanel({
-    // configs for FormPanel
-    title: 'Basic Information',
-    renderTo: document.body,
-    width: 300, height: 160,
-    padding: 10,
-
-    // configs apply to child items
-    defaults: {anchor: '100%'},
-    defaultType: 'textfield',
-    items: [{
-        fieldLabel: 'Name',
-        name: 'name'
-    },{
-        fieldLabel: 'Email',
-        name: 'email'
-    },{
-        fieldLabel: 'Company',
-        name: 'company'
-    }],
-
-    // configs for BasicForm
-    api: {
-        // The server-side method to call for load() requests
-        load: Profile.getBasicInfo,
-        // The server-side must mark the submit handler as a 'formHandler'
-        submit: Profile.updateBasicInfo
-    },
-    // specify the order for the passed params
-    paramOrder: ['uid', 'foo']
-});
-
-// load the form
-myFormPanel.getForm().load({
-    // pass 2 arguments to server side getBasicInfo method (len=2)
-    params: {
-        foo: 'bar',
-        uid: 34
-    }
-});
- * 
- * The data packet sent to the server will resemble something like: - *

-[
-    {
-        "action":"Profile","method":"getBasicInfo","type":"rpc","tid":2,
-        "data":[34,"bar"] // note the order of the params
-    }
-]
- * 
- * The form will process a data packet returned by the server that is similar - * to the following format: - *

-[
-    {
-        "action":"Profile","method":"getBasicInfo","type":"rpc","tid":2,
-        "result":{
-            "success":true,
-            "data":{
-                "name":"Fred Flintstone",
-                "company":"Slate Rock and Gravel",
-                "email":"fred.flintstone@slaterg.com"
-            }
-        }
-    }
-]
- * 
- */ -Ext.form.Action.DirectLoad = Ext.extend(Ext.form.Action.Load, { - constructor: function(form, opts) { - Ext.form.Action.DirectLoad.superclass.constructor.call(this, form, opts); - }, - type : 'directload', - - run : function(){ - var args = this.getParams(); - args.push(this.success, this); - this.form.api.load.apply(window, args); - }, - - getParams : function() { - var buf = [], o = {}; - var bp = this.form.baseParams; - var p = this.options.params; - Ext.apply(o, p, bp); - var paramOrder = this.form.paramOrder; - if(paramOrder){ - for(var i = 0, len = paramOrder.length; i < len; i++){ - buf.push(o[paramOrder[i]]); - } - }else if(this.form.paramsAsHash){ - buf.push(o); - } - return buf; - }, - // Direct actions have already been processed and therefore - // we can directly set the result; Direct Actions do not have - // a this.response property. - processResponse : function(result) { - this.result = result; - return result; - }, - - success : function(response, trans){ - if(trans.type == Ext.Direct.exceptions.SERVER){ - response = {}; - } - Ext.form.Action.DirectLoad.superclass.success.call(this, response); - } -}); - -/** - * @class Ext.form.Action.DirectSubmit - * @extends Ext.form.Action.Submit - *

Provides Ext.direct support for submitting form data.

- *

This example illustrates usage of Ext.Direct to submit a form through Ext.Direct.

- *

-var myFormPanel = new Ext.form.FormPanel({
-    // configs for FormPanel
-    title: 'Basic Information',
-    renderTo: document.body,
-    width: 300, height: 160,
-    padding: 10,
-    buttons:[{
-        text: 'Submit',
-        handler: function(){
-            myFormPanel.getForm().submit({
-                params: {
-                    foo: 'bar',
-                    uid: 34
-                }
-            });
-        }
-    }],
-
-    // configs apply to child items
-    defaults: {anchor: '100%'},
-    defaultType: 'textfield',
-    items: [{
-        fieldLabel: 'Name',
-        name: 'name'
-    },{
-        fieldLabel: 'Email',
-        name: 'email'
-    },{
-        fieldLabel: 'Company',
-        name: 'company'
-    }],
-
-    // configs for BasicForm
-    api: {
-        // The server-side method to call for load() requests
-        load: Profile.getBasicInfo,
-        // The server-side must mark the submit handler as a 'formHandler'
-        submit: Profile.updateBasicInfo
-    },
-    // specify the order for the passed params
-    paramOrder: ['uid', 'foo']
-});
- * 
- * The data packet sent to the server will resemble something like: - *

-{
-    "action":"Profile","method":"updateBasicInfo","type":"rpc","tid":"6",
-    "result":{
-        "success":true,
-        "id":{
-            "extAction":"Profile","extMethod":"updateBasicInfo",
-            "extType":"rpc","extTID":"6","extUpload":"false",
-            "name":"Aaron Conran","email":"aaron@extjs.com","company":"Ext JS, LLC"
-        }
-    }
-}
- * 
- * The form will process a data packet returned by the server that is similar - * to the following: - *

-// sample success packet (batched requests)
-[
-    {
-        "action":"Profile","method":"updateBasicInfo","type":"rpc","tid":3,
-        "result":{
-            "success":true
-        }
-    }
-]
-
-// sample failure packet (one request)
-{
-        "action":"Profile","method":"updateBasicInfo","type":"rpc","tid":"6",
-        "result":{
-            "errors":{
-                "email":"already taken"
-            },
-            "success":false,
-            "foo":"bar"
-        }
-}
- * 
- * Also see the discussion in {@link Ext.form.Action.DirectLoad}. - */ -Ext.form.Action.DirectSubmit = Ext.extend(Ext.form.Action.Submit, { - constructor : function(form, opts) { - Ext.form.Action.DirectSubmit.superclass.constructor.call(this, form, opts); - }, - type : 'directsubmit', - // override of Submit - run : function(){ - var o = this.options; - if(o.clientValidation === false || this.form.isValid()){ - // tag on any additional params to be posted in the - // form scope - this.success.params = this.getParams(); - this.form.api.submit(this.form.el.dom, this.success, this); - }else if (o.clientValidation !== false){ // client validation failed - this.failureType = Ext.form.Action.CLIENT_INVALID; - this.form.afterAction(this, false); - } - }, - - getParams : function() { - var o = {}; - var bp = this.form.baseParams; - var p = this.options.params; - Ext.apply(o, p, bp); - return o; - }, - // Direct actions have already been processed and therefore - // we can directly set the result; Direct Actions do not have - // a this.response property. - processResponse : function(result) { - this.result = result; - return result; - }, - - success : function(response, trans){ - if(trans.type == Ext.Direct.exceptions.SERVER){ - response = {}; - } - Ext.form.Action.DirectSubmit.superclass.success.call(this, response); - } -}); - -Ext.form.Action.ACTION_TYPES = { - 'load' : Ext.form.Action.Load, - 'submit' : Ext.form.Action.Submit, - 'directload' : Ext.form.Action.DirectLoad, - 'directsubmit' : Ext.form.Action.DirectSubmit -}; -/** - * @class Ext.form.VTypes - *

This is a singleton object which contains a set of commonly used field validation functions. - * The validations provided are basic and intended to be easily customizable and extended.

- *

To add custom VTypes specify the {@link Ext.form.TextField#vtype vtype} validation - * test function, and optionally specify any corresponding error text to display and any keystroke - * filtering mask to apply. For example:

- *

-// custom Vtype for vtype:'time'
-var timeTest = /^([1-9]|1[0-9]):([0-5][0-9])(\s[a|p]m)$/i;
-Ext.apply(Ext.form.VTypes, {
-    //  vtype validation function
-    time: function(val, field) {
-        return timeTest.test(val);
-    },
-    // vtype Text property: The error text to display when the validation function returns false
-    timeText: 'Not a valid time.  Must be in the format "12:34 PM".',
-    // vtype Mask property: The keystroke filter mask
-    timeMask: /[\d\s:amp]/i
-});
- * 
- * Another example: - *

-// custom Vtype for vtype:'IPAddress'
-Ext.apply(Ext.form.VTypes, {
-    IPAddress:  function(v) {
-        return /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(v);
-    },
-    IPAddressText: 'Must be a numeric IP address',
-    IPAddressMask: /[\d\.]/i
-});
- * 
- * @singleton - */ -Ext.form.VTypes = function(){ - // closure these in so they are only created once. - var alpha = /^[a-zA-Z_]+$/, - alphanum = /^[a-zA-Z0-9_]+$/, - email = /^(\w+)([\-+.][\w]+)*@(\w[\-\w]*\.){1,5}([A-Za-z]){2,4}$/, - url = /(((^https?)|(^ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i; + + if (align) { + style += String.format("text-align: {0};", align); + } + + return style; + }, - // All these messages and functions are configurable - return { - /** - * The function used to validate email addresses. Note that this is a very basic validation -- complete - * validation per the email RFC specifications is very complex and beyond the scope of this class, although - * this function can be overridden if a more comprehensive validation scheme is desired. See the validation - * section of the Wikipedia article on email addresses - * for additional information. This implementation is intended to validate the following emails: - * 'barney@example.de', 'barney.rubble@example.com', 'barney-rubble@example.coop', 'barney+rubble@example.com' - * . - * @param {String} value The email address - * @return {Boolean} true if the RegExp test passed, and false if not. - */ - 'email' : function(v){ - return email.test(v); - }, - /** - * The error text to display when the email validation function returns false. Defaults to: - * 'This field should be an e-mail address in the format "user@example.com"' - * @type String - */ - 'emailText' : 'This field should be an e-mail address in the format "user@example.com"', - /** - * The keystroke filter mask to be applied on email input. See the {@link #email} method for - * information about more complex email validation. Defaults to: - * /[a-z0-9_\.\-@]/i - * @type RegExp - */ - 'emailMask' : /[a-z0-9_\.\-@]/i, + + getColumnWidth : function(column) { + var columnWidth = this.cm.getColumnWidth(column), + borderWidth = this.borderWidth; + + if (Ext.isNumber(columnWidth)) { + if (Ext.isBorderBox || (Ext.isWebKit && !Ext.isSafari2)) { + return columnWidth + "px"; + } else { + return Math.max(columnWidth - borderWidth, 0) + "px"; + } + } else { + return columnWidth; + } + }, - /** - * The function used to validate URLs - * @param {String} value The URL - * @return {Boolean} true if the RegExp test passed, and false if not. - */ - 'url' : function(v){ - return url.test(v); - }, - /** - * The error text to display when the url validation function returns false. Defaults to: - * 'This field should be a URL in the format "http:/'+'/www.example.com"' - * @type String - */ - 'urlText' : 'This field should be a URL in the format "http:/'+'/www.example.com"', + + getTotalWidth : function() { + return this.cm.getTotalWidth() + 'px'; + }, + + + fitColumns : function(preventRefresh, onlyExpand, omitColumn) { + var grid = this.grid, + colModel = this.cm, + totalColWidth = colModel.getTotalWidth(false), + gridWidth = this.getGridInnerWidth(), + extraWidth = gridWidth - totalColWidth, + columns = [], + extraCol = 0, + width = 0, + colWidth, fraction, i; - /** - * The function used to validate alpha values - * @param {String} value The value - * @return {Boolean} true if the RegExp test passed, and false if not. - */ - 'alpha' : function(v){ - return alpha.test(v); - }, - /** - * The error text to display when the alpha validation function returns false. Defaults to: - * 'This field should only contain letters and _' - * @type String - */ - 'alphaText' : 'This field should only contain letters and _', - /** - * The keystroke filter mask to be applied on alpha input. Defaults to: - * /[a-z_]/i - * @type RegExp - */ - 'alphaMask' : /[a-z_]/i, + + if (gridWidth < 20 || extraWidth === 0) { + return false; + } + + var visibleColCount = colModel.getColumnCount(true), + totalColCount = colModel.getColumnCount(false), + adjCount = visibleColCount - (Ext.isNumber(omitColumn) ? 1 : 0); + + if (adjCount === 0) { + adjCount = 1; + omitColumn = undefined; + } + + + for (i = 0; i < totalColCount; i++) { + if (!colModel.isFixed(i) && i !== omitColumn) { + colWidth = colModel.getColumnWidth(i); + columns.push(i, colWidth); + + if (!colModel.isHidden(i)) { + extraCol = i; + width += colWidth; + } + } + } + + fraction = (gridWidth - colModel.getTotalWidth()) / width; + + while (columns.length) { + colWidth = columns.pop(); + i = columns.pop(); + + colModel.setColumnWidth(i, Math.max(grid.minColumnWidth, Math.floor(colWidth + colWidth * fraction)), true); + } + + + totalColWidth = colModel.getTotalWidth(false); + + if (totalColWidth > gridWidth) { + var adjustCol = (adjCount == visibleColCount) ? extraCol : omitColumn, + newWidth = Math.max(1, colModel.getColumnWidth(adjustCol) - (totalColWidth - gridWidth)); + + colModel.setColumnWidth(adjustCol, newWidth, true); + } + + if (preventRefresh !== true) { + this.updateAllColumnWidths(); + } + + return true; + }, - /** - * The function used to validate alphanumeric values - * @param {String} value The value - * @return {Boolean} true if the RegExp test passed, and false if not. - */ - 'alphanum' : function(v){ - return alphanum.test(v); - }, - /** - * The error text to display when the alphanumeric validation function returns false. Defaults to: - * 'This field should only contain letters, numbers and _' - * @type String - */ - 'alphanumText' : 'This field should only contain letters, numbers and _', - /** - * The keystroke filter mask to be applied on alphanumeric input. Defaults to: - * /[a-z0-9_]/i - * @type RegExp - */ - 'alphanumMask' : /[a-z0-9_]/i - }; -}();/** - * @class Ext.grid.GridPanel - * @extends Ext.Panel - *

This class represents the primary interface of a component based grid control to represent data - * in a tabular format of rows and columns. The GridPanel is composed of the following:

- *
    - *
  • {@link Ext.data.Store Store} : The Model holding the data records (rows) - *
  • - *
  • {@link Ext.grid.ColumnModel Column model} : Column makeup - *
  • - *
  • {@link Ext.grid.GridView View} : Encapsulates the user interface - *
  • - *
  • {@link Ext.grid.AbstractSelectionModel selection model} : Selection behavior - *
  • - *
- *

Example usage:

- *

-var grid = new Ext.grid.GridPanel({
-    {@link #store}: new {@link Ext.data.Store}({
-        {@link Ext.data.Store#autoDestroy autoDestroy}: true,
-        {@link Ext.data.Store#reader reader}: reader,
-        {@link Ext.data.Store#data data}: xg.dummyData
-    }),
-    {@link #colModel}: new {@link Ext.grid.ColumnModel}({
-        {@link Ext.grid.ColumnModel#defaults defaults}: {
-            width: 120,
-            sortable: true
-        },
-        {@link Ext.grid.ColumnModel#columns columns}: [
-            {id: 'company', header: 'Company', width: 200, sortable: true, dataIndex: 'company'},
-            {header: 'Price', renderer: Ext.util.Format.usMoney, dataIndex: 'price'},
-            {header: 'Change', dataIndex: 'change'},
-            {header: '% Change', dataIndex: 'pctChange'},
-            // instead of specifying renderer: Ext.util.Format.dateRenderer('m/d/Y') use xtype
-            {
-                header: 'Last Updated', width: 135, dataIndex: 'lastChange',
-                xtype: 'datecolumn', format: 'M d, Y'
-            }
-        ],
-    }),
-    {@link #viewConfig}: {
-        {@link Ext.grid.GridView#forceFit forceFit}: true,
-
-//      Return CSS class to apply to rows depending upon data values
-        {@link Ext.grid.GridView#getRowClass getRowClass}: function(record, index) {
-            var c = record.{@link Ext.data.Record#get get}('change');
-            if (c < 0) {
-                return 'price-fall';
-            } else if (c > 0) {
-                return 'price-rise';
-            }
-        }
-    },
-    {@link #sm}: new Ext.grid.RowSelectionModel({singleSelect:true}),
-    width: 600,
-    height: 300,
-    frame: true,
-    title: 'Framed with Row Selection and Horizontal Scrolling',
-    iconCls: 'icon-grid'
-});
- * 
- *

Notes:

- *
    - *
  • Although this class inherits many configuration options from base classes, some of them - * (such as autoScroll, autoWidth, layout, items, etc) are not used by this class, and will - * have no effect.
  • - *
  • A grid requires a width in which to scroll its columns, and a height in which to - * scroll its rows. These dimensions can either be set explicitly through the - * {@link Ext.BoxComponent#height height} and {@link Ext.BoxComponent#width width} - * configuration options or implicitly set by using the grid as a child item of a - * {@link Ext.Container Container} which will have a {@link Ext.Container#layout layout manager} - * provide the sizing of its child items (for example the Container of the Grid may specify - * {@link Ext.Container#layout layout}:'fit').
  • - *
  • To access the data in a Grid, it is necessary to use the data model encapsulated - * by the {@link #store Store}. See the {@link #cellclick} event for more details.
  • - *
- * @constructor - * @param {Object} config The config object - * @xtype grid - */ -Ext.grid.GridPanel = Ext.extend(Ext.Panel, { - /** - * @cfg {String} autoExpandColumn - *

The {@link Ext.grid.Column#id id} of a {@link Ext.grid.Column column} in - * this grid that should expand to fill unused space. This value specified here can not - * be 0.

- *

Note: If the Grid's {@link Ext.grid.GridView view} is configured with - * {@link Ext.grid.GridView#forceFit forceFit}=true the autoExpandColumn - * is ignored. See {@link Ext.grid.Column}.{@link Ext.grid.Column#width width} - * for additional details.

- *

See {@link #autoExpandMax} and {@link #autoExpandMin} also.

- */ - autoExpandColumn : false, - /** - * @cfg {Number} autoExpandMax The maximum width the {@link #autoExpandColumn} - * can have (if enabled). Defaults to 1000. - */ - autoExpandMax : 1000, - /** - * @cfg {Number} autoExpandMin The minimum width the {@link #autoExpandColumn} - * can have (if enabled). Defaults to 50. - */ - autoExpandMin : 50, - /** - * @cfg {Boolean} columnLines true to add css for column separation lines. - * Default is false. - */ - columnLines : false, - /** - * @cfg {Object} cm Shorthand for {@link #colModel}. - */ - /** - * @cfg {Object} colModel The {@link Ext.grid.ColumnModel} to use when rendering the grid (required). - */ - /** - * @cfg {Array} columns An array of {@link Ext.grid.Column columns} to auto create a - * {@link Ext.grid.ColumnModel}. The ColumnModel may be explicitly created via the - * {@link #colModel} configuration property. - */ - /** - * @cfg {String} ddGroup The DD group this GridPanel belongs to. Defaults to 'GridDD' if not specified. - */ - /** - * @cfg {String} ddText - * Configures the text in the drag proxy. Defaults to: - *

-     * ddText : '{0} selected row{1}'
-     * 
- * {0} is replaced with the number of selected rows. - */ - ddText : '{0} selected row{1}', - /** - * @cfg {Boolean} deferRowRender

Defaults to true to enable deferred row rendering.

- *

This allows the GridPanel to be initially rendered empty, with the expensive update of the row - * structure deferred so that layouts with GridPanels appear more quickly.

- */ - deferRowRender : true, - /** - * @cfg {Boolean} disableSelection

true to disable selections in the grid. Defaults to false.

- *

Ignored if a {@link #selModel SelectionModel} is specified.

- */ - /** - * @cfg {Boolean} enableColumnResize false to turn off column resizing for the whole grid. Defaults to true. - */ - /** - * @cfg {Boolean} enableColumnHide - * Defaults to true to enable {@link Ext.grid.Column#hidden hiding of columns} - * with the {@link #enableHdMenu header menu}. - */ - enableColumnHide : true, - /** - * @cfg {Boolean} enableColumnMove Defaults to true to enable drag and drop reorder of columns. false - * to turn off column reordering via drag drop. - */ - enableColumnMove : true, - /** - * @cfg {Boolean} enableDragDrop

Enables dragging of the selected rows of the GridPanel. Defaults to false.

- *

Setting this to true causes this GridPanel's {@link #getView GridView} to - * create an instance of {@link Ext.grid.GridDragZone}. Note: this is available only after - * the Grid has been rendered as the GridView's {@link Ext.grid.GridView#dragZone dragZone} - * property.

- *

A cooperating {@link Ext.dd.DropZone DropZone} must be created who's implementations of - * {@link Ext.dd.DropZone#onNodeEnter onNodeEnter}, {@link Ext.dd.DropZone#onNodeOver onNodeOver}, - * {@link Ext.dd.DropZone#onNodeOut onNodeOut} and {@link Ext.dd.DropZone#onNodeDrop onNodeDrop} are able - * to process the {@link Ext.grid.GridDragZone#getDragData data} which is provided.

- */ - enableDragDrop : false, - /** - * @cfg {Boolean} enableHdMenu Defaults to true to enable the drop down button for menu in the headers. - */ - enableHdMenu : true, - /** - * @cfg {Boolean} hideHeaders True to hide the grid's header. Defaults to false. - */ - /** - * @cfg {Object} loadMask An {@link Ext.LoadMask} config or true to mask the grid while - * loading. Defaults to false. - */ - loadMask : false, - /** - * @cfg {Number} maxHeight Sets the maximum height of the grid - ignored if autoHeight is not on. - */ - /** - * @cfg {Number} minColumnWidth The minimum width a column can be resized to. Defaults to 25. - */ - minColumnWidth : 25, - /** - * @cfg {Object} sm Shorthand for {@link #selModel}. - */ - /** - * @cfg {Object} selModel Any subclass of {@link Ext.grid.AbstractSelectionModel} that will provide - * the selection model for the grid (defaults to {@link Ext.grid.RowSelectionModel} if not specified). - */ - /** - * @cfg {Ext.data.Store} store The {@link Ext.data.Store} the grid should use as its data source (required). - */ - /** - * @cfg {Boolean} stripeRows true to stripe the rows. Default is false. - *

This causes the CSS class x-grid3-row-alt to be added to alternate rows of - * the grid. A default CSS rule is provided which sets a background colour, but you can override this - * with a rule which either overrides the background-color style using the '!important' - * modifier, or which uses a CSS selector of higher specificity.

- */ - stripeRows : false, - /** - * @cfg {Boolean} trackMouseOver True to highlight rows when the mouse is over. Default is true - * for GridPanel, but false for EditorGridPanel. - */ - trackMouseOver : true, - /** - * @cfg {Array} stateEvents - * An array of events that, when fired, should trigger this component to save its state. - * Defaults to:

-     * stateEvents: ['columnmove', 'columnresize', 'sortchange']
-     * 
- *

These can be any types of events supported by this component, including browser or - * custom events (e.g., ['click', 'customerchange']).

- *

See {@link Ext.Component#stateful} for an explanation of saving and restoring - * Component state.

- */ - stateEvents : ['columnmove', 'columnresize', 'sortchange'], - /** - * @cfg {Object} view The {@link Ext.grid.GridView} used by the grid. This can be set - * before a call to {@link Ext.Component#render render()}. - */ - view : null, - - /** - * @cfg {Array} bubbleEvents - *

An array of events that, when fired, should be bubbled to any parent container. - * Defaults to []. - */ - bubbleEvents: [], - - /** - * @cfg {Object} viewConfig A config object that will be applied to the grid's UI view. Any of - * the config options available for {@link Ext.grid.GridView} can be specified here. This option - * is ignored if {@link #view} is specified. - */ - - // private - rendered : false, - // private - viewReady : false, - - // private - initComponent : function(){ - Ext.grid.GridPanel.superclass.initComponent.call(this); - - if(this.columnLines){ - this.cls = (this.cls || '') + ' x-grid-with-col-lines'; - } - // override any provided value since it isn't valid - // and is causing too many bug reports ;) - this.autoScroll = false; - this.autoWidth = false; - - if(Ext.isArray(this.columns)){ - this.colModel = new Ext.grid.ColumnModel(this.columns); - delete this.columns; - } - - // check and correct shorthanded configs - if(this.ds){ - this.store = this.ds; - delete this.ds; - } - if(this.cm){ - this.colModel = this.cm; - delete this.cm; - } - if(this.sm){ - this.selModel = this.sm; - delete this.sm; - } - this.store = Ext.StoreMgr.lookup(this.store); - - this.addEvents( - // raw events - /** - * @event click - * The raw click event for the entire grid. - * @param {Ext.EventObject} e - */ - 'click', - /** - * @event dblclick - * The raw dblclick event for the entire grid. - * @param {Ext.EventObject} e - */ - 'dblclick', - /** - * @event contextmenu - * The raw contextmenu event for the entire grid. - * @param {Ext.EventObject} e - */ - 'contextmenu', - /** - * @event mousedown - * The raw mousedown event for the entire grid. - * @param {Ext.EventObject} e - */ - 'mousedown', - /** - * @event mouseup - * The raw mouseup event for the entire grid. - * @param {Ext.EventObject} e - */ - 'mouseup', - /** - * @event mouseover - * The raw mouseover event for the entire grid. - * @param {Ext.EventObject} e - */ - 'mouseover', - /** - * @event mouseout - * The raw mouseout event for the entire grid. - * @param {Ext.EventObject} e - */ - 'mouseout', - /** - * @event keypress - * The raw keypress event for the entire grid. - * @param {Ext.EventObject} e - */ - 'keypress', - /** - * @event keydown - * The raw keydown event for the entire grid. - * @param {Ext.EventObject} e - */ - 'keydown', - - // custom events - /** - * @event cellmousedown - * Fires before a cell is clicked - * @param {Grid} this - * @param {Number} rowIndex - * @param {Number} columnIndex - * @param {Ext.EventObject} e - */ - 'cellmousedown', - /** - * @event rowmousedown - * Fires before a row is clicked - * @param {Grid} this - * @param {Number} rowIndex - * @param {Ext.EventObject} e - */ - 'rowmousedown', - /** - * @event headermousedown - * Fires before a header is clicked - * @param {Grid} this - * @param {Number} columnIndex - * @param {Ext.EventObject} e - */ - 'headermousedown', - - /** - * @event cellclick - * Fires when a cell is clicked. - * The data for the cell is drawn from the {@link Ext.data.Record Record} - * for this row. To access the data in the listener function use the - * following technique: - *


-function(grid, rowIndex, columnIndex, e) {
-    var record = grid.getStore().getAt(rowIndex);  // Get the Record
-    var fieldName = grid.getColumnModel().getDataIndex(columnIndex); // Get field name
-    var data = record.get(fieldName);
-}
-
- * @param {Grid} this - * @param {Number} rowIndex - * @param {Number} columnIndex - * @param {Ext.EventObject} e - */ - 'cellclick', - /** - * @event celldblclick - * Fires when a cell is double clicked - * @param {Grid} this - * @param {Number} rowIndex - * @param {Number} columnIndex - * @param {Ext.EventObject} e - */ - 'celldblclick', - /** - * @event rowclick - * Fires when a row is clicked - * @param {Grid} this - * @param {Number} rowIndex - * @param {Ext.EventObject} e - */ - 'rowclick', - /** - * @event rowdblclick - * Fires when a row is double clicked - * @param {Grid} this - * @param {Number} rowIndex - * @param {Ext.EventObject} e - */ - 'rowdblclick', - /** - * @event headerclick - * Fires when a header is clicked - * @param {Grid} this - * @param {Number} columnIndex - * @param {Ext.EventObject} e - */ - 'headerclick', - /** - * @event headerdblclick - * Fires when a header cell is double clicked - * @param {Grid} this - * @param {Number} columnIndex - * @param {Ext.EventObject} e - */ - 'headerdblclick', - /** - * @event rowcontextmenu - * Fires when a row is right clicked - * @param {Grid} this - * @param {Number} rowIndex - * @param {Ext.EventObject} e - */ - 'rowcontextmenu', - /** - * @event cellcontextmenu - * Fires when a cell is right clicked - * @param {Grid} this - * @param {Number} rowIndex - * @param {Number} cellIndex - * @param {Ext.EventObject} e - */ - 'cellcontextmenu', - /** - * @event headercontextmenu - * Fires when a header is right clicked - * @param {Grid} this - * @param {Number} columnIndex - * @param {Ext.EventObject} e - */ - 'headercontextmenu', - /** - * @event bodyscroll - * Fires when the body element is scrolled - * @param {Number} scrollLeft - * @param {Number} scrollTop - */ - 'bodyscroll', - /** - * @event columnresize - * Fires when the user resizes a column - * @param {Number} columnIndex - * @param {Number} newSize - */ - 'columnresize', - /** - * @event columnmove - * Fires when the user moves a column - * @param {Number} oldIndex - * @param {Number} newIndex - */ - 'columnmove', - /** - * @event sortchange - * Fires when the grid's store sort changes - * @param {Grid} this - * @param {Object} sortInfo An object with the keys field and direction - */ - 'sortchange', - /** - * @event reconfigure - * Fires when the grid is reconfigured with a new store and/or column model. - * @param {Grid} this - * @param {Ext.data.Store} store The new store - * @param {Ext.grid.ColumnModel} colModel The new column model - */ - 'reconfigure' - ); - }, - - // private - onRender : function(ct, position){ - Ext.grid.GridPanel.superclass.onRender.apply(this, arguments); - - var c = this.getGridEl(); - - this.el.addClass('x-grid-panel'); - - this.mon(c, { - scope: this, - mousedown: this.onMouseDown, - click: this.onClick, - dblclick: this.onDblClick, - contextmenu: this.onContextMenu - }); - - this.relayEvents(c, ['mousedown','mouseup','mouseover','mouseout','keypress', 'keydown']); - - var view = this.getView(); - view.init(this); - view.render(); - this.getSelectionModel().init(this); - }, - - // private - initEvents : function(){ - Ext.grid.GridPanel.superclass.initEvents.call(this); - - if(this.loadMask){ - this.loadMask = new Ext.LoadMask(this.bwrap, - Ext.apply({store:this.store}, this.loadMask)); - } - }, - - initStateEvents : function(){ - Ext.grid.GridPanel.superclass.initStateEvents.call(this); - this.mon(this.colModel, 'hiddenchange', this.saveState, this, {delay: 100}); - }, - - applyState : function(state){ - var cm = this.colModel, - cs = state.columns; - if(cs){ - for(var i = 0, len = cs.length; i < len; i++){ - var s = cs[i]; - var c = cm.getColumnById(s.id); - if(c){ - c.hidden = s.hidden; - c.width = s.width; - var oldIndex = cm.getIndexById(s.id); - if(oldIndex != i){ - cm.moveColumn(oldIndex, i); - } - } - } - } - if(state.sort && this.store){ - this.store[this.store.remoteSort ? 'setDefaultSort' : 'sort'](state.sort.field, state.sort.direction); - } - var o = Ext.apply({}, state); - delete o.columns; - delete o.sort; - Ext.grid.GridPanel.superclass.applyState.call(this, o); - }, - - getState : function(){ - var o = {columns: []}; - for(var i = 0, c; (c = this.colModel.config[i]); i++){ - o.columns[i] = { - id: c.id, - width: c.width - }; - if(c.hidden){ - o.columns[i].hidden = true; - } - } - if(this.store){ - var ss = this.store.getSortState(); - if(ss){ - o.sort = ss; - } - } - return o; - }, - - // private - afterRender : function(){ - Ext.grid.GridPanel.superclass.afterRender.call(this); - var v = this.view; - this.on('bodyresize', v.layout, v); - v.layout(); - if(this.deferRowRender){ - v.afterRender.defer(10, this.view); - }else{ - v.afterRender(); - } - this.viewReady = true; - }, - - /** - *

Reconfigures the grid to use a different Store and Column Model - * and fires the 'reconfigure' event. The View will be bound to the new - * objects and refreshed.

- *

Be aware that upon reconfiguring a GridPanel, certain existing settings may become - * invalidated. For example the configured {@link #autoExpandColumn} may no longer exist in the - * new ColumnModel. Also, an existing {@link Ext.PagingToolbar PagingToolbar} will still be bound - * to the old Store, and will need rebinding. Any {@link #plugins} might also need reconfiguring - * with the new data.

- * @param {Ext.data.Store} store The new {@link Ext.data.Store} object - * @param {Ext.grid.ColumnModel} colModel The new {@link Ext.grid.ColumnModel} object - */ - reconfigure : function(store, colModel){ - if(this.loadMask){ - this.loadMask.destroy(); - this.loadMask = new Ext.LoadMask(this.bwrap, - Ext.apply({}, {store:store}, this.initialConfig.loadMask)); - } - this.view.initData(store, colModel); - this.store = store; - this.colModel = colModel; - if(this.rendered){ - this.view.refresh(true); - } - this.fireEvent('reconfigure', this, store, colModel); - }, - - // private - onDestroy : function(){ - if(this.rendered){ - var c = this.body; - c.removeAllListeners(); - c.update(''); - Ext.destroy(this.view, this.loadMask); - }else if(this.store && this.store.autoDestroy){ - this.store.destroy(); - } - Ext.destroy(this.colModel, this.selModel); - this.store = this.selModel = this.colModel = this.view = this.loadMask = null; - Ext.grid.GridPanel.superclass.onDestroy.call(this); - }, - - // private - processEvent : function(name, e){ - this.fireEvent(name, e); - var t = e.getTarget(); - var v = this.view; - var header = v.findHeaderIndex(t); - if(header !== false){ - this.fireEvent('header' + name, this, header, e); - }else{ - var row = v.findRowIndex(t); - var cell = v.findCellIndex(t); - if(row !== false){ - this.fireEvent('row' + name, this, row, e); - if(cell !== false){ - this.fireEvent('cell' + name, this, row, cell, e); - } - } - } - }, - - // private - onClick : function(e){ - this.processEvent('click', e); - }, - - // private - onMouseDown : function(e){ - this.processEvent('mousedown', e); - }, - - // private - onContextMenu : function(e, t){ - this.processEvent('contextmenu', e); - }, - - // private - onDblClick : function(e){ - this.processEvent('dblclick', e); - }, - - // private - walkCells : function(row, col, step, fn, scope){ - var cm = this.colModel, clen = cm.getColumnCount(); - var ds = this.store, rlen = ds.getCount(), first = true; - if(step < 0){ - if(col < 0){ - row--; - first = false; - } - while(row >= 0){ - if(!first){ - col = clen-1; - } - first = false; - while(col >= 0){ - if(fn.call(scope || this, row, col, cm) === true){ - return [row, col]; - } - col--; - } - row--; - } - } else { - if(col >= clen){ - row++; - first = false; - } - while(row < rlen){ - if(!first){ - col = 0; - } - first = false; - while(col < clen){ - if(fn.call(scope || this, row, col, cm) === true){ - return [row, col]; - } - col++; - } - row++; - } - } - return null; - }, - - // private - onResize : function(){ - Ext.grid.GridPanel.superclass.onResize.apply(this, arguments); - if(this.viewReady){ - this.view.layout(); - } - }, - - /** - * Returns the grid's underlying element. - * @return {Element} The element - */ - getGridEl : function(){ - return this.body; - }, - - // private for compatibility, overridden by editor grid - stopEditing : Ext.emptyFn, - - /** - * Returns the grid's selection model configured by the {@link #selModel} - * configuration option. If no selection model was configured, this will create - * and return a {@link Ext.grid.RowSelectionModel RowSelectionModel}. - * @return {SelectionModel} - */ - getSelectionModel : function(){ - if(!this.selModel){ - this.selModel = new Ext.grid.RowSelectionModel( - this.disableSelection ? {selectRow: Ext.emptyFn} : null); - } - return this.selModel; - }, - - /** - * Returns the grid's data store. - * @return {Ext.data.Store} The store - */ - getStore : function(){ - return this.store; - }, - - /** - * Returns the grid's ColumnModel. - * @return {Ext.grid.ColumnModel} The column model - */ - getColumnModel : function(){ - return this.colModel; - }, - - /** - * Returns the grid's GridView object. - * @return {Ext.grid.GridView} The grid view - */ - getView : function(){ - if(!this.view){ - this.view = new Ext.grid.GridView(this.viewConfig); - } - return this.view; - }, - /** - * Called to get grid's drag proxy text, by default returns this.ddText. - * @return {String} The text - */ - getDragDropText : function(){ - var count = this.selModel.getCount(); - return String.format(this.ddText, count, count == 1 ? '' : 's'); - } - - /** - * @cfg {String/Number} activeItem - * @hide - */ - /** - * @cfg {Boolean} autoDestroy - * @hide - */ - /** - * @cfg {Object/String/Function} autoLoad - * @hide - */ - /** - * @cfg {Boolean} autoWidth - * @hide - */ - /** - * @cfg {Boolean/Number} bufferResize - * @hide - */ - /** - * @cfg {String} defaultType - * @hide - */ - /** - * @cfg {Object} defaults - * @hide - */ - /** - * @cfg {Boolean} hideBorders - * @hide - */ - /** - * @cfg {Mixed} items - * @hide - */ - /** - * @cfg {String} layout - * @hide - */ - /** - * @cfg {Object} layoutConfig - * @hide - */ - /** - * @cfg {Boolean} monitorResize - * @hide - */ - /** - * @property items - * @hide - */ - /** - * @method add - * @hide - */ - /** - * @method cascade - * @hide - */ - /** - * @method doLayout - * @hide - */ - /** - * @method find - * @hide - */ - /** - * @method findBy - * @hide - */ - /** - * @method findById - * @hide - */ - /** - * @method findByType - * @hide - */ - /** - * @method getComponent - * @hide - */ - /** - * @method getLayout - * @hide - */ - /** - * @method getUpdater - * @hide - */ - /** - * @method insert - * @hide - */ - /** - * @method load - * @hide - */ - /** - * @method remove - * @hide - */ - /** - * @event add - * @hide - */ - /** - * @event afterLayout - * @hide - */ - /** - * @event beforeadd - * @hide - */ - /** - * @event beforeremove - * @hide - */ - /** - * @event remove - * @hide - */ - - - - /** - * @cfg {String} allowDomMove @hide - */ - /** - * @cfg {String} autoEl @hide - */ - /** - * @cfg {String} applyTo @hide - */ - /** - * @cfg {String} autoScroll @hide - */ - /** - * @cfg {String} bodyBorder @hide - */ - /** - * @cfg {String} bodyStyle @hide - */ - /** - * @cfg {String} contentEl @hide - */ - /** - * @cfg {String} disabledClass @hide - */ - /** - * @cfg {String} elements @hide - */ - /** - * @cfg {String} html @hide - */ - /** - * @cfg {Boolean} preventBodyReset - * @hide - */ - /** - * @property disabled - * @hide - */ - /** - * @method applyToMarkup - * @hide - */ - /** - * @method enable - * @hide - */ - /** - * @method disable - * @hide - */ - /** - * @method setDisabled - * @hide - */ -}); -Ext.reg('grid', Ext.grid.GridPanel);/** - * @class Ext.grid.GridView - * @extends Ext.util.Observable - *

This class encapsulates the user interface of an {@link Ext.grid.GridPanel}. - * Methods of this class may be used to access user interface elements to enable - * special display effects. Do not change the DOM structure of the user interface.

- *

This class does not provide ways to manipulate the underlying data. The data - * model of a Grid is held in an {@link Ext.data.Store}.

- * @constructor - * @param {Object} config - */ -Ext.grid.GridView = function(config){ - Ext.apply(this, config); - // These events are only used internally by the grid components - this.addEvents( - /** - * @event beforerowremoved - * Internal UI Event. Fired before a row is removed. - * @param {Ext.grid.GridView} view - * @param {Number} rowIndex The index of the row to be removed. - * @param {Ext.data.Record} record The Record to be removed - */ - 'beforerowremoved', - /** - * @event beforerowsinserted - * Internal UI Event. Fired before rows are inserted. - * @param {Ext.grid.GridView} view - * @param {Number} firstRow The index of the first row to be inserted. - * @param {Number} lastRow The index of the last row to be inserted. - */ - 'beforerowsinserted', - /** - * @event beforerefresh - * Internal UI Event. Fired before the view is refreshed. - * @param {Ext.grid.GridView} view - */ - 'beforerefresh', - /** - * @event rowremoved - * Internal UI Event. Fired after a row is removed. - * @param {Ext.grid.GridView} view - * @param {Number} rowIndex The index of the row that was removed. - * @param {Ext.data.Record} record The Record that was removed - */ - 'rowremoved', - /** - * @event rowsinserted - * Internal UI Event. Fired after rows are inserted. - * @param {Ext.grid.GridView} view - * @param {Number} firstRow The index of the first inserted. - * @param {Number} lastRow The index of the last row inserted. - */ - 'rowsinserted', - /** - * @event rowupdated - * Internal UI Event. Fired after a row has been updated. - * @param {Ext.grid.GridView} view - * @param {Number} firstRow The index of the row updated. - * @param {Ext.data.record} record The Record backing the row updated. - */ - 'rowupdated', - /** - * @event refresh - * Internal UI Event. Fired after the GridView's body has been refreshed. - * @param {Ext.grid.GridView} view - */ - 'refresh' - ); - Ext.grid.GridView.superclass.constructor.call(this); -}; + + autoExpand : function(preventUpdate) { + var grid = this.grid, + colModel = this.cm, + gridWidth = this.getGridInnerWidth(), + totalColumnWidth = colModel.getTotalWidth(false), + autoExpandColumn = grid.autoExpandColumn; + + if (!this.userResized && autoExpandColumn) { + if (gridWidth != totalColumnWidth) { + + var colIndex = colModel.getIndexById(autoExpandColumn), + currentWidth = colModel.getColumnWidth(colIndex), + desiredWidth = gridWidth - totalColumnWidth + currentWidth, + newWidth = Math.min(Math.max(desiredWidth, grid.autoExpandMin), grid.autoExpandMax); + + if (currentWidth != newWidth) { + colModel.setColumnWidth(colIndex, newWidth, true); + + if (preventUpdate !== true) { + this.updateColumnWidth(colIndex, newWidth); + } + } + } + } + }, + + + getGridInnerWidth: function() { + return this.grid.getGridEl().getWidth(true) - this.getScrollOffset(); + }, -Ext.extend(Ext.grid.GridView, Ext.util.Observable, { - /** - * Override this function to apply custom CSS classes to rows during rendering. You can also supply custom - * parameters to the row template for the current row to customize how it is rendered using the rowParams - * parameter. This function should return the CSS class name (or empty string '' for none) that will be added - * to the row's wrapping div. To apply multiple class names, simply return them space-delimited within the string - * (e.g., 'my-class another-class'). Example usage: -

-viewConfig: {
-    forceFit: true,
-    showPreview: true, // custom property
-    enableRowBody: true, // required to create a second, full-width row to show expanded Record data
-    getRowClass: function(record, rowIndex, rp, ds){ // rp = rowParams
-        if(this.showPreview){
-            rp.body = '<p>'+record.data.excerpt+'</p>';
-            return 'x-grid3-row-expanded';
-        }
-        return 'x-grid3-row-collapsed';
-    }
-},     
-    
- * @param {Record} record The {@link Ext.data.Record} corresponding to the current row. - * @param {Number} index The row index. - * @param {Object} rowParams A config object that is passed to the row template during rendering that allows - * customization of various aspects of a grid row. - *

If {@link #enableRowBody} is configured true, then the following properties may be set - * by this function, and will be used to render a full-width expansion row below each grid row:

- *
    - *
  • body : String
    An HTML fragment to be used as the expansion row's body content (defaults to '').
  • - *
  • bodyStyle : String
    A CSS style specification that will be applied to the expansion row's <tr> element. (defaults to '').
  • - *
- * The following property will be passed in, and may be appended to: - *
    - *
  • tstyle : String
    A CSS style specification that willl be applied to the <table> element which encapsulates - * both the standard grid row, and any expansion row.
  • - *
- * @param {Store} store The {@link Ext.data.Store} this grid is bound to - * @method getRowClass - * @return {String} a CSS class name to add to the row. - */ - /** - * @cfg {Boolean} enableRowBody True to add a second TR element per row that can be used to provide a row body - * that spans beneath the data row. Use the {@link #getRowClass} method's rowParams config to customize the row body. - */ - /** - * @cfg {String} emptyText Default text (html tags are accepted) to display in the grid body when no rows - * are available (defaults to ''). This value will be used to update the {@link #mainBody}: -

-    this.mainBody.update('<div class="x-grid-empty">' + this.emptyText + '</div>');
-    
- */ - /** - * @cfg {Boolean} headersDisabled True to disable the grid column headers (defaults to false). - * Use the {@link Ext.grid.ColumnModel ColumnModel} {@link Ext.grid.ColumnModel#menuDisabled menuDisabled} - * config to disable the menu for individual columns. While this config is true the - * following will be disabled:
    - *
  • clicking on header to sort
  • - *
  • the trigger to reveal the menu.
  • - *
- */ - /** - *

A customized implementation of a {@link Ext.dd.DragZone DragZone} which provides default implementations - * of the template methods of DragZone to enable dragging of the selected rows of a GridPanel. - * See {@link Ext.grid.GridDragZone} for details.

- *

This will only be present:

    - *
  • if the owning GridPanel was configured with {@link Ext.grid.GridPanel#enableDragDrop enableDragDrop}: true.
  • - *
  • after the owning GridPanel has been rendered.
  • - *
- * @property dragZone - * @type {Ext.grid.GridDragZone} - */ - /** - * @cfg {Boolean} deferEmptyText True to defer {@link #emptyText} being applied until the store's - * first load (defaults to true). - */ - deferEmptyText : true, - /** - * @cfg {Number} scrollOffset The amount of space to reserve for the vertical scrollbar - * (defaults to undefined). If an explicit value isn't specified, this will be automatically - * calculated. - */ - scrollOffset : undefined, - /** - * @cfg {Boolean} autoFill - * Defaults to false. Specify true to have the column widths re-proportioned - * when the grid is initially rendered. The - * {@link Ext.grid.Column#width initially configured width}
of each column will be adjusted - * to fit the grid width and prevent horizontal scrolling. If columns are later resized (manually - * or programmatically), the other columns in the grid will not be resized to fit the grid width. - * See {@link #forceFit} also. - */ - autoFill : false, - /** - * @cfg {Boolean} forceFit - * Defaults to false. Specify true to have the column widths re-proportioned - * at all times. The {@link Ext.grid.Column#width initially configured width} of each - * column will be adjusted to fit the grid width and prevent horizontal scrolling. If columns are - * later resized (manually or programmatically), the other columns in the grid will be resized - * to fit the grid width. See {@link #autoFill} also. - */ - forceFit : false, - /** - * @cfg {Array} sortClasses The CSS classes applied to a header when it is sorted. (defaults to ['sort-asc', 'sort-desc']) - */ - sortClasses : ['sort-asc', 'sort-desc'], - /** - * @cfg {String} sortAscText The text displayed in the 'Sort Ascending' menu item (defaults to 'Sort Ascending') - */ - sortAscText : 'Sort Ascending', - /** - * @cfg {String} sortDescText The text displayed in the 'Sort Descending' menu item (defaults to 'Sort Descending') - */ - sortDescText : 'Sort Descending', - /** - * @cfg {String} columnsText The text displayed in the 'Columns' menu item (defaults to 'Columns') - */ - columnsText : 'Columns', + + getColumnData : function() { + var columns = [], + colModel = this.cm, + colCount = colModel.getColumnCount(), + fields = this.ds.fields, + i, name; + + for (i = 0; i < colCount; i++) { + name = colModel.getDataIndex(i); + + columns[i] = { + name : Ext.isDefined(name) ? name : (fields.get(i) ? fields.get(i).name : undefined), + renderer: colModel.getRenderer(i), + scope : colModel.getRendererScope(i), + id : colModel.getColumnId(i), + style : this.getColumnStyle(i) + }; + } + + return columns; + }, - /** - * @cfg {String} selectedRowClass The CSS class applied to a selected row (defaults to 'x-grid3-row-selected'). An - * example overriding the default styling: -

-    .x-grid3-row-selected {background-color: yellow;}
-    
- * Note that this only controls the row, and will not do anything for the text inside it. To style inner - * facets (like text) use something like: -

-    .x-grid3-row-selected .x-grid3-cell-inner {
-        color: #FFCC00;
-    }
-    
- * @type String - */ - selectedRowClass : 'x-grid3-row-selected', + + renderRows : function(startRow, endRow) { + var grid = this.grid, + store = grid.store, + stripe = grid.stripeRows, + colModel = grid.colModel, + colCount = colModel.getColumnCount(), + rowCount = store.getCount(), + records; + + if (rowCount < 1) { + return ''; + } + + startRow = startRow || 0; + endRow = Ext.isDefined(endRow) ? endRow : rowCount - 1; + records = store.getRange(startRow, endRow); + + return this.doRender(this.getColumnData(), records, store, startRow, colCount, stripe); + }, - // private - borderWidth : 2, - tdClass : 'x-grid3-cell', - hdCls : 'x-grid3-hd', - markDirty : true, + + renderBody : function(){ + var markup = this.renderRows() || ' '; + return this.templates.body.apply({rows: markup}); + }, - /** - * @cfg {Number} cellSelectorDepth The number of levels to search for cells in event delegation (defaults to 4) - */ - cellSelectorDepth : 4, - /** - * @cfg {Number} rowSelectorDepth The number of levels to search for rows in event delegation (defaults to 10) - */ - rowSelectorDepth : 10, + + refreshRow: function(record) { + var store = this.ds, + colCount = this.cm.getColumnCount(), + columns = this.getColumnData(), + last = colCount - 1, + cls = ['x-grid3-row'], + rowParams = { + tstyle: String.format("width: {0};", this.getTotalWidth()) + }, + colBuffer = [], + cellTpl = this.templates.cell, + rowIndex, row, column, meta, css, i; + + if (Ext.isNumber(record)) { + rowIndex = record; + record = store.getAt(rowIndex); + } else { + rowIndex = store.indexOf(record); + } + + + if (!record || rowIndex < 0) { + return; + } + + + for (i = 0; i < colCount; i++) { + column = columns[i]; + + if (i == 0) { + css = 'x-grid3-cell-first'; + } else { + css = (i == last) ? 'x-grid3-cell-last ' : ''; + } + + meta = { + id : column.id, + style : column.style, + css : css, + attr : "", + cellAttr: "" + }; + + meta.value = column.renderer.call(column.scope, record.data[column.name], meta, record, rowIndex, i, store); + + if (Ext.isEmpty(meta.value)) { + meta.value = ' '; + } + + if (this.markDirty && record.dirty && typeof record.modified[column.name] != 'undefined') { + meta.css += ' x-grid3-dirty-cell'; + } + + colBuffer[i] = cellTpl.apply(meta); + } + + row = this.getRow(rowIndex); + row.className = ''; + + if (this.grid.stripeRows && ((rowIndex + 1) % 2 === 0)) { + cls.push('x-grid3-row-alt'); + } + + if (this.getRowClass) { + rowParams.cols = colCount; + cls.push(this.getRowClass(record, rowIndex, rowParams, store)); + } + + this.fly(row).addClass(cls).setStyle(rowParams.tstyle); + rowParams.cells = colBuffer.join(""); + row.innerHTML = this.templates.rowInner.apply(rowParams); + + this.fireEvent('rowupdated', this, rowIndex, record); + }, - /** - * @cfg {String} cellSelector The selector used to find cells internally (defaults to 'td.x-grid3-cell') - */ - cellSelector : 'td.x-grid3-cell', - /** - * @cfg {String} rowSelector The selector used to find rows internally (defaults to 'div.x-grid3-row') - */ - rowSelector : 'div.x-grid3-row', - // private - firstRowCls: 'x-grid3-row-first', - lastRowCls: 'x-grid3-row-last', - rowClsRe: /(?:^|\s+)x-grid3-row-(first|last|alt)(?:\s+|$)/g, - - /* -------------------------------- UI Specific ----------------------------- */ + refresh : function(headersToo) { + this.fireEvent('beforerefresh', this); + this.grid.stopEditing(true); - // private - initTemplates : function(){ - var ts = this.templates || {}; - if(!ts.master){ - ts.master = new Ext.Template( - '
', - '
', - '
{header}
', - '
{body}
', - '
', - '
 
', - '
 
', - '
' - ); + var result = this.renderBody(); + this.mainBody.update(result).setWidth(this.getTotalWidth()); + if (headersToo === true) { + this.updateHeaders(); + this.updateHeaderSortState(); } + this.processRows(0, true); + this.layout(); + this.applyEmptyText(); + this.fireEvent('refresh', this); + }, - if(!ts.header){ - ts.header = new Ext.Template( - '', - '{cells}', - '
' - ); + + applyEmptyText : function() { + if (this.emptyText && !this.hasRows()) { + this.mainBody.update('
' + this.emptyText + '
'); } + }, - if(!ts.hcell){ - ts.hcell = new Ext.Template( - '
', this.grid.enableHdMenu ? '' : '', - '{value}', - '
' - ); + + updateHeaderSortState : function() { + var state = this.ds.getSortState(); + if (!state) { + return; } - if(!ts.body){ - ts.body = new Ext.Template('{rows}'); + if (!this.sortState || (this.sortState.field != state.field || this.sortState.direction != state.direction)) { + this.grid.fireEvent('sortchange', this.grid, state); } - if(!ts.row){ - ts.row = new Ext.Template( - '
', - '{cells}', - (this.enableRowBody ? '' : ''), - '
{body}
' - ); - } + this.sortState = state; - if(!ts.cell){ - ts.cell = new Ext.Template( - '', - '
{value}
', - '' - ); + var sortColumn = this.cm.findColumnIndex(state.field); + if (sortColumn != -1) { + var sortDir = state.direction; + this.updateSortIcon(sortColumn, sortDir); } + }, - for(var k in ts){ - var t = ts[k]; - if(t && typeof t.compile == 'function' && !t.compiled){ - t.disableFormats = true; - t.compile(); - } + + clearHeaderSortState : function() { + if (!this.sortState) { + return; } - - this.templates = ts; - this.colRe = new RegExp('x-grid3-td-([^\\s]+)', ''); + this.grid.fireEvent('sortchange', this.grid, null); + this.mainHd.select('td').removeClass(this.sortClasses); + delete this.sortState; }, - // private - fly : function(el){ - if(!this._flyweight){ - this._flyweight = new Ext.Element.Flyweight(document.body); + + destroy : function() { + var me = this, + grid = me.grid, + gridEl = grid.getGridEl(), + dragZone = me.dragZone, + splitZone = me.splitZone, + columnDrag = me.columnDrag, + columnDrop = me.columnDrop, + scrollToTopTask = me.scrollToTopTask, + columnDragData, + columnDragProxy; + + if (scrollToTopTask && scrollToTopTask.cancel) { + scrollToTopTask.cancel(); } - this._flyweight.dom = el; - return this._flyweight; - }, + + Ext.destroyMembers(me, 'colMenu', 'hmenu'); - // private - getEditorParent : function(){ - return this.scroller.dom; - }, + me.initData(null, null); + me.purgeListeners(); + + Ext.fly(me.innerHd).un("click", me.handleHdDown, me); - // private - initElements : function(){ - var E = Ext.Element; + if (grid.enableColumnMove) { + columnDragData = columnDrag.dragData; + columnDragProxy = columnDrag.proxy; + Ext.destroy( + columnDrag.el, + columnDragProxy.ghost, + columnDragProxy.el, + columnDrop.el, + columnDrop.proxyTop, + columnDrop.proxyBottom, + columnDragData.ddel, + columnDragData.header + ); + + if (columnDragProxy.anim) { + Ext.destroy(columnDragProxy.anim); + } + + delete columnDragProxy.ghost; + delete columnDragData.ddel; + delete columnDragData.header; + columnDrag.destroy(); + + delete Ext.dd.DDM.locationCache[columnDrag.id]; + delete columnDrag._domRef; - var el = this.grid.getGridEl().dom.firstChild; - var cs = el.childNodes; + delete columnDrop.proxyTop; + delete columnDrop.proxyBottom; + columnDrop.destroy(); + delete Ext.dd.DDM.locationCache["gridHeader" + gridEl.id]; + delete columnDrop._domRef; + delete Ext.dd.DDM.ids[columnDrop.ddGroup]; + } - this.el = new E(el); + if (splitZone) { + splitZone.destroy(); + delete splitZone._domRef; + delete Ext.dd.DDM.ids["gridSplitters" + gridEl.id]; + } - this.mainWrap = new E(cs[0]); - this.mainHd = new E(this.mainWrap.dom.firstChild); + Ext.fly(me.innerHd).removeAllListeners(); + Ext.removeNode(me.innerHd); + delete me.innerHd; - if(this.grid.hideHeaders){ - this.mainHd.setDisplayed(false); - } + Ext.destroy( + me.el, + me.mainWrap, + me.mainHd, + me.scroller, + me.mainBody, + me.focusEl, + me.resizeMarker, + me.resizeProxy, + me.activeHdBtn, + me._flyweight, + dragZone, + splitZone + ); - this.innerHd = this.mainHd.dom.firstChild; - this.scroller = new E(this.mainWrap.dom.childNodes[1]); - if(this.forceFit){ - this.scroller.setStyle('overflow-x', 'hidden'); - } - /** - * Read-only. The GridView's body Element which encapsulates all rows in the Grid. - * This {@link Ext.Element Element} is only available after the GridPanel has been rendered. - * @type Ext.Element - * @property mainBody - */ - this.mainBody = new E(this.scroller.dom.firstChild); + delete grid.container; - this.focusEl = new E(this.scroller.dom.childNodes[1]); - this.focusEl.swallowEvent('click', true); + if (dragZone) { + dragZone.destroy(); + } - this.resizeMarker = new E(cs[1]); - this.resizeProxy = new E(cs[2]); - }, + Ext.dd.DDM.currentTarget = null; + delete Ext.dd.DDM.locationCache[gridEl.id]; - // private - getRows : function(){ - return this.hasRows() ? this.mainBody.dom.childNodes : []; + Ext.EventManager.removeResizeListener(me.onWindowResize, me); }, - // finder methods, used with delegation + + onDenyColumnHide : function() { - // private - findCell : function(el){ - if(!el){ - return false; - } - return this.fly(el).findParent(this.cellSelector, this.cellSelectorDepth); }, - /** - *

Return the index of the grid column which contains the passed HTMLElement.

- * See also {@link #findRowIndex} - * @param {HTMLElement} el The target element - * @return {Number} The column index, or false if the target element is not within a row of this GridView. - */ - findCellIndex : function(el, requiredCls){ - var cell = this.findCell(el); - if(cell && (!requiredCls || this.fly(cell).hasClass(requiredCls))){ - return this.getCellIndex(cell); + + render : function() { + if (this.autoFill) { + var ct = this.grid.ownerCt; + + if (ct && ct.getLayout()) { + ct.on('afterlayout', function() { + this.fitColumns(true, true); + this.updateHeaders(); + this.updateHeaderSortState(); + }, this, {single: true}); + } + } else if (this.forceFit) { + this.fitColumns(true, false); + } else if (this.grid.autoExpandColumn) { + this.autoExpand(true); } - return false; + + this.grid.getGridEl().dom.innerHTML = this.renderUI(); + + this.afterRenderUI(); }, - // private - getCellIndex : function(el){ - if(el){ - var m = el.className.match(this.colRe); - if(m && m[1]){ - return this.cm.getIndexById(m[1]); + + + + initData : function(newStore, newColModel) { + var me = this; + + if (me.ds) { + var oldStore = me.ds; + + oldStore.un('add', me.onAdd, me); + oldStore.un('load', me.onLoad, me); + oldStore.un('clear', me.onClear, me); + oldStore.un('remove', me.onRemove, me); + oldStore.un('update', me.onUpdate, me); + oldStore.un('datachanged', me.onDataChange, me); + + if (oldStore !== newStore && oldStore.autoDestroy) { + oldStore.destroy(); } } - return false; + + if (newStore) { + newStore.on({ + scope : me, + load : me.onLoad, + add : me.onAdd, + remove : me.onRemove, + update : me.onUpdate, + clear : me.onClear, + datachanged: me.onDataChange + }); + } + + if (me.cm) { + var oldColModel = me.cm; + + oldColModel.un('configchange', me.onColConfigChange, me); + oldColModel.un('widthchange', me.onColWidthChange, me); + oldColModel.un('headerchange', me.onHeaderChange, me); + oldColModel.un('hiddenchange', me.onHiddenChange, me); + oldColModel.un('columnmoved', me.onColumnMove, me); + } + + if (newColModel) { + delete me.lastViewWidth; + + newColModel.on({ + scope : me, + configchange: me.onColConfigChange, + widthchange : me.onColWidthChange, + headerchange: me.onHeaderChange, + hiddenchange: me.onHiddenChange, + columnmoved : me.onColumnMove + }); + } + + me.ds = newStore; + me.cm = newColModel; }, - // private - findHeaderCell : function(el){ - var cell = this.findCell(el); - return cell && this.fly(cell).hasClass(this.hdCls) ? cell : null; + + onDataChange : function(){ + this.refresh(true); + this.updateHeaderSortState(); + this.syncFocusEl(0); }, - // private - findHeaderIndex : function(el){ - return this.findCellIndex(el, this.hdCls); + + onClear : function() { + this.refresh(); + this.syncFocusEl(0); }, - /** - * Return the HtmlElement representing the grid row which contains the passed element. - * @param {HTMLElement} el The target HTMLElement - * @return {HTMLElement} The row element, or null if the target element is not within a row of this GridView. - */ - findRow : function(el){ - if(!el){ - return false; - } - return this.fly(el).findParent(this.rowSelector, this.rowSelectorDepth); + + onUpdate : function(store, record) { + this.refreshRow(record); }, - /** - *

Return the index of the grid row which contains the passed HTMLElement.

- * See also {@link #findCellIndex} - * @param {HTMLElement} el The target HTMLElement - * @return {Number} The row index, or false if the target element is not within a row of this GridView. - */ - findRowIndex : function(el){ - var r = this.findRow(el); - return r ? r.rowIndex : false; + + onAdd : function(store, records, index) { + this.insertRows(store, index, index + (records.length-1)); }, - // getter methods for fetching elements dynamically in the grid - - /** - * Return the <div> HtmlElement which represents a Grid row for the specified index. - * @param {Number} index The row index - * @return {HtmlElement} The div element. - */ - getRow : function(row){ - return this.getRows()[row]; + + onRemove : function(store, record, index, isUpdate) { + if (isUpdate !== true) { + this.fireEvent('beforerowremoved', this, index, record); + } + + this.removeRow(index); + + if (isUpdate !== true) { + this.processRows(index); + this.applyEmptyText(); + this.fireEvent('rowremoved', this, index, record); + } }, - /** - * Returns the grid's <td> HtmlElement at the specified coordinates. - * @param {Number} row The row index in which to find the cell. - * @param {Number} col The column index of the cell. - * @return {HtmlElement} The td at the specified coordinates. - */ - getCell : function(row, col){ - return this.getRow(row).getElementsByTagName('td')[col]; + + onLoad : function() { + if (Ext.isGecko) { + if (!this.scrollToTopTask) { + this.scrollToTopTask = new Ext.util.DelayedTask(this.scrollToTop, this); + } + this.scrollToTopTask.delay(1); + } else { + this.scrollToTop(); + } }, - /** - * Return the <td> HtmlElement which represents the Grid's header cell for the specified column index. - * @param {Number} index The column index - * @return {HtmlElement} The td element. - */ - getHeaderCell : function(index){ - return this.mainHd.dom.getElementsByTagName('td')[index]; + + onColWidthChange : function(cm, col, width) { + this.updateColumnWidth(col, width); }, - // manipulating elements + + onHeaderChange : function(cm, col, text) { + this.updateHeaders(); + }, - // private - use getRowClass to apply custom row classes - addRowClass : function(row, cls){ - var r = this.getRow(row); - if(r){ - this.fly(r).addClass(cls); - } + + onHiddenChange : function(cm, col, hidden) { + this.updateColumnHidden(col, hidden); }, - // private - removeRowClass : function(row, cls){ - var r = this.getRow(row); - if(r){ - this.fly(r).removeClass(cls); - } + + onColumnMove : function(cm, oldIndex, newIndex) { + this.indexMap = null; + this.refresh(true); + this.restoreScroll(this.getScrollState()); + + this.afterMove(newIndex); + this.grid.fireEvent('columnmove', oldIndex, newIndex); }, - // private - removeRow : function(row){ - Ext.removeNode(this.getRow(row)); - this.syncFocusEl(row); + + onColConfigChange : function() { + delete this.lastViewWidth; + this.indexMap = null; + this.refresh(true); }, + - // private - removeRows : function(firstRow, lastRow){ - var bd = this.mainBody.dom; - for(var rowIndex = firstRow; rowIndex <= lastRow; rowIndex++){ - Ext.removeNode(bd.childNodes[firstRow]); - } - this.syncFocusEl(firstRow); + + initUI : function(grid) { + grid.on('headerclick', this.onHeaderClick, this); }, - // scrolling stuff + + initEvents : Ext.emptyFn, - // private - getScrollState : function(){ - var sb = this.scroller.dom; - return {left: sb.scrollLeft, top: sb.scrollTop}; + + onHeaderClick : function(g, index) { + if (this.headersDisabled || !this.cm.isSortable(index)) { + return; + } + g.stopEditing(true); + g.store.sort(this.cm.getDataIndex(index)); }, - // private - restoreScroll : function(state){ - var sb = this.scroller.dom; - sb.scrollLeft = state.left; - sb.scrollTop = state.top; + + onRowOver : function(e, target) { + var row = this.findRowIndex(target); + + if (row !== false) { + this.addRowClass(row, this.rowOverCls); + } }, - /** - * Scrolls the grid to the top - */ - scrollToTop : function(){ - this.scroller.dom.scrollTop = 0; - this.scroller.dom.scrollLeft = 0; + + onRowOut : function(e, target) { + var row = this.findRowIndex(target); + + if (row !== false && !e.within(this.getRow(row), true)) { + this.removeRowClass(row, this.rowOverCls); + } }, - // private - syncScroll : function(){ - this.syncHeaderScroll(); - var mb = this.scroller.dom; - this.grid.fireEvent('bodyscroll', mb.scrollLeft, mb.scrollTop); + + onRowSelect : function(row) { + this.addRowClass(row, this.selectedRowClass); }, - // private - syncHeaderScroll : function(){ - var mb = this.scroller.dom; - this.innerHd.scrollLeft = mb.scrollLeft; - this.innerHd.scrollLeft = mb.scrollLeft; // second time for IE (1/2 time first fails, other browsers ignore) + + onRowDeselect : function(row) { + this.removeRowClass(row, this.selectedRowClass); }, - // private - updateSortIcon : function(col, dir){ - var sc = this.sortClasses; - var hds = this.mainHd.select('td').removeClass(sc); - hds.item(col).addClass(sc[dir == 'DESC' ? 1 : 0]); + + onCellSelect : function(row, col) { + var cell = this.getCell(row, col); + if (cell) { + this.fly(cell).addClass('x-grid3-cell-selected'); + } }, - // private - updateAllColumnWidths : function(){ - var tw = this.getTotalWidth(), - clen = this.cm.getColumnCount(), - ws = [], - len, - i; - for(i = 0; i < clen; i++){ - ws[i] = this.getColumnWidth(i); - } - this.innerHd.firstChild.style.width = this.getOffsetWidth(); - this.innerHd.firstChild.firstChild.style.width = tw; - this.mainBody.dom.style.width = tw; - for(i = 0; i < clen; i++){ - var hd = this.getHeaderCell(i); - hd.style.width = ws[i]; - } - - var ns = this.getRows(), row, trow; - for(i = 0, len = ns.length; i < len; i++){ - row = ns[i]; - row.style.width = tw; - if(row.firstChild){ - row.firstChild.style.width = tw; - trow = row.firstChild.rows[0]; - for (var j = 0; j < clen; j++) { - trow.childNodes[j].style.width = ws[j]; - } - } + + onCellDeselect : function(row, col) { + var cell = this.getCell(row, col); + if (cell) { + this.fly(cell).removeClass('x-grid3-cell-selected'); } + }, - this.onAllColumnWidthsUpdated(ws, tw); + + handleWheel : function(e) { + e.stopPropagation(); }, - // private - updateColumnWidth : function(col, width){ - var w = this.getColumnWidth(col); - var tw = this.getTotalWidth(); - this.innerHd.firstChild.style.width = this.getOffsetWidth(); - this.innerHd.firstChild.firstChild.style.width = tw; - this.mainBody.dom.style.width = tw; - var hd = this.getHeaderCell(col); - hd.style.width = w; - - var ns = this.getRows(), row; - for(var i = 0, len = ns.length; i < len; i++){ - row = ns[i]; - row.style.width = tw; - if(row.firstChild){ - row.firstChild.style.width = tw; - row.firstChild.rows[0].childNodes[col].style.width = w; - } + + onColumnSplitterMoved : function(cellIndex, width) { + this.userResized = true; + this.grid.colModel.setColumnWidth(cellIndex, width, true); + + if (this.forceFit) { + this.fitColumns(true, false, cellIndex); + this.updateAllColumnWidths(); + } else { + this.updateColumnWidth(cellIndex, width); + this.syncHeaderScroll(); } - this.onColumnWidthUpdated(col, w, tw); + this.grid.fireEvent('columnresize', cellIndex, width); }, - // private - updateColumnHidden : function(col, hidden){ - var tw = this.getTotalWidth(); - this.innerHd.firstChild.style.width = this.getOffsetWidth(); - this.innerHd.firstChild.firstChild.style.width = tw; - this.mainBody.dom.style.width = tw; - var display = hidden ? 'none' : ''; + + beforeColMenuShow : function() { + var colModel = this.cm, + colCount = colModel.getColumnCount(), + colMenu = this.colMenu, + i; - var hd = this.getHeaderCell(col); - hd.style.display = display; + colMenu.removeAll(); - var ns = this.getRows(), row; - for(var i = 0, len = ns.length; i < len; i++){ - row = ns[i]; - row.style.width = tw; - if(row.firstChild){ - row.firstChild.style.width = tw; - row.firstChild.rows[0].childNodes[col].style.display = display; + for (i = 0; i < colCount; i++) { + if (colModel.config[i].hideable !== false) { + colMenu.add(new Ext.menu.CheckItem({ + text : colModel.getColumnHeader(i), + itemId : 'col-' + colModel.getColumnId(i), + checked : !colModel.isHidden(i), + disabled : colModel.config[i].hideable === false, + hideOnClick: false + })); } } - - this.onColumnHiddenUpdated(col, hidden, tw); - delete this.lastViewWidth; // force recalc - this.layout(); }, + + + handleHdMenuClick : function(item) { + var store = this.ds, + dataIndex = this.cm.getDataIndex(this.hdCtxIndex); - // private - doRender : function(cs, rs, ds, startRow, colCount, stripe){ - var ts = this.templates, ct = ts.cell, rt = ts.row, last = colCount-1; - var tstyle = 'width:'+this.getTotalWidth()+';'; - // buffers - var buf = [], cb, c, p = {}, rp = {tstyle: tstyle}, r; - for(var j = 0, len = rs.length; j < len; j++){ - r = rs[j]; cb = []; - var rowIndex = (j+startRow); - for(var i = 0; i < colCount; i++){ - c = cs[i]; - p.id = c.id; - p.css = i === 0 ? 'x-grid3-cell-first ' : (i == last ? 'x-grid3-cell-last ' : ''); - p.attr = p.cellAttr = ''; - p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds); - p.style = c.style; - if(Ext.isEmpty(p.value)){ - p.value = ' '; - } - if(this.markDirty && r.dirty && typeof r.modified[c.name] !== 'undefined'){ - p.css += ' x-grid3-dirty-cell'; - } - cb[cb.length] = ct.apply(p); - } - var alt = []; - if(stripe && ((rowIndex+1) % 2 === 0)){ - alt[0] = 'x-grid3-row-alt'; - } - if(r.dirty){ - alt[1] = ' x-grid3-dirty-row'; - } - rp.cols = colCount; - if(this.getRowClass){ - alt[2] = this.getRowClass(r, rowIndex, rp, ds); + switch (item.getItemId()) { + case 'asc': + store.sort(dataIndex, 'ASC'); + break; + case 'desc': + store.sort(dataIndex, 'DESC'); + break; + default: + this.handleHdMenuClickDefault(item); + } + return true; + }, + + + handleHdMenuClickDefault: function(item) { + var colModel = this.cm, + itemId = item.getItemId(), + index = colModel.getIndexById(itemId.substr(4)); + + if (index != -1) { + if (item.checked && colModel.getColumnsBy(this.isHideableColumn, this).length <= 1) { + this.onDenyColumnHide(); + return; } - rp.alt = alt.join(' '); - rp.cells = cb.join(''); - buf[buf.length] = rt.apply(rp); + colModel.setHidden(index, item.checked); } - return buf.join(''); }, - // private - processRows : function(startRow, skipStripe){ - if(!this.ds || this.ds.getCount() < 1){ - return; + + handleHdDown : function(e, target) { + if (Ext.fly(target).hasClass('x-grid3-hd-btn')) { + e.stopEvent(); + + var colModel = this.cm, + header = this.findHeaderCell(target), + index = this.getCellIndex(header), + sortable = colModel.isSortable(index), + menu = this.hmenu, + menuItems = menu.items, + menuCls = this.headerMenuOpenCls; + + this.hdCtxIndex = index; + + Ext.fly(header).addClass(menuCls); + menuItems.get('asc').setDisabled(!sortable); + menuItems.get('desc').setDisabled(!sortable); + + menu.on('hide', function() { + Ext.fly(header).removeClass(menuCls); + }, this, {single:true}); + + menu.show(target, 'tl-bl?'); } - var rows = this.getRows(); - skipStripe = skipStripe || !this.grid.stripeRows; - startRow = startRow || 0; - Ext.each(rows, function(row, idx){ - row.rowIndex = idx; - if(!skipStripe){ - row.className = row.className.replace(this.rowClsRe, ' '); - if ((idx + 1) % 2 === 0){ - row.className += ' x-grid3-row-alt'; + }, + + + handleHdMove : function(e) { + var header = this.findHeaderCell(this.activeHdRef); + + if (header && !this.headersDisabled) { + var handleWidth = this.splitHandleWidth || 5, + activeRegion = this.activeHdRegion, + headerStyle = header.style, + colModel = this.cm, + cursor = '', + pageX = e.getPageX(); + + if (this.grid.enableColumnResize !== false) { + var activeHeaderIndex = this.activeHdIndex, + previousVisible = this.getPreviousVisible(activeHeaderIndex), + currentResizable = colModel.isResizable(activeHeaderIndex), + previousResizable = previousVisible && colModel.isResizable(previousVisible), + inLeftResizer = pageX - activeRegion.left <= handleWidth, + inRightResizer = activeRegion.right - pageX <= (!this.activeHdBtn ? handleWidth : 2); + + if (inLeftResizer && previousResizable) { + cursor = Ext.isAir ? 'move' : Ext.isWebKit ? 'e-resize' : 'col-resize'; + } else if (inRightResizer && currentResizable) { + cursor = Ext.isAir ? 'move' : Ext.isWebKit ? 'w-resize' : 'col-resize'; } } - }, this); - // add first/last-row classes - if(startRow === 0){ - Ext.fly(rows[0]).addClass(this.firstRowCls); + + headerStyle.cursor = cursor; } - Ext.fly(rows[rows.length - 1]).addClass(this.lastRowCls); }, - - afterRender : function(){ - if(!this.ds || !this.cm){ - return; + + + getPreviousVisible: function(index) { + while (index > 0) { + if (!this.cm.isHidden(index - 1)) { + return index; + } + index--; } - this.mainBody.dom.innerHTML = this.renderRows() || ' '; - this.processRows(0, true); + return undefined; + }, - if(this.deferEmptyText !== true){ - this.applyEmptyText(); + + handleHdOver : function(e, target) { + var header = this.findHeaderCell(target); + + if (header && !this.headersDisabled) { + var fly = this.fly(header); + + this.activeHdRef = target; + this.activeHdIndex = this.getCellIndex(header); + this.activeHdRegion = fly.getRegion(); + + if (!this.isMenuDisabled(this.activeHdIndex, fly)) { + fly.addClass('x-grid3-hd-over'); + this.activeHdBtn = fly.child('.x-grid3-hd-btn'); + + if (this.activeHdBtn) { + this.activeHdBtn.dom.style.height = (header.firstChild.offsetHeight - 1) + 'px'; + } + } } }, - // private - renderUI : function(){ + + handleHdOut : function(e, target) { + var header = this.findHeaderCell(target); + + if (header && (!Ext.isIE || !e.within(header, true))) { + this.activeHdRef = null; + this.fly(header).removeClass('x-grid3-hd-over'); + header.style.cursor = ''; + } + }, + + + isMenuDisabled: function(cellIndex, el) { + return this.cm.isMenuDisabled(cellIndex); + }, - var header = this.renderHeaders(); - var body = this.templates.body.apply({rows:' '}); + + hasRows : function() { + var fc = this.mainBody.dom.firstChild; + return fc && fc.nodeType == 1 && fc.className != 'x-grid-empty'; + }, + + + isHideableColumn : function(c) { + return !c.hidden; + }, + + bind : function(d, c) { + this.initData(d, c); + } +}); - var html = this.templates.master.apply({ - body: body, - header: header, - ostyle: 'width:'+this.getOffsetWidth()+';', - bstyle: 'width:'+this.getTotalWidth()+';' - }); - var g = this.grid; - g.getGridEl().dom.innerHTML = html; - this.initElements(); +Ext.grid.GridView.SplitDragZone = Ext.extend(Ext.dd.DDProxy, { - // get mousedowns early - Ext.fly(this.innerHd).on('click', this.handleHdDown, this); - this.mainHd.on({ - scope: this, - mouseover: this.handleHdOver, - mouseout: this.handleHdOut, - mousemove: this.handleHdMove + constructor: function(grid, hd){ + this.grid = grid; + this.view = grid.getView(); + this.marker = this.view.resizeMarker; + this.proxy = this.view.resizeProxy; + Ext.grid.GridView.SplitDragZone.superclass.constructor.call(this, hd, + 'gridSplitters' + this.grid.getGridEl().id, { + dragElId : Ext.id(this.proxy.dom), resizeFrame:false }); + this.scroll = false; + this.hw = this.view.splitHandleWidth || 5; + }, - this.scroller.on('scroll', this.syncScroll, this); - if(g.enableColumnResize !== false){ - this.splitZone = new Ext.grid.GridView.SplitDragZone(g, this.mainHd.dom); - } + b4StartDrag : function(x, y){ + this.dragHeadersDisabled = this.view.headersDisabled; + this.view.headersDisabled = true; + var h = this.view.mainWrap.getHeight(); + this.marker.setHeight(h); + this.marker.show(); + this.marker.alignTo(this.view.getHeaderCell(this.cellIndex), 'tl-tl', [-2, 0]); + this.proxy.setHeight(h); + var w = this.cm.getColumnWidth(this.cellIndex), + minw = Math.max(w-this.grid.minColumnWidth, 0); + this.resetConstraints(); + this.setXConstraint(minw, 1000); + this.setYConstraint(0, 0); + this.minX = x - minw; + this.maxX = x + 1000; + this.startPos = x; + Ext.dd.DDProxy.prototype.b4StartDrag.call(this, x, y); + }, - if(g.enableColumnMove){ - this.columnDrag = new Ext.grid.GridView.ColumnDragZone(g, this.innerHd); - this.columnDrop = new Ext.grid.HeaderDropZone(g, this.mainHd.dom); - } + allowHeaderDrag : function(e){ + return true; + }, - if(g.enableHdMenu !== false){ - this.hmenu = new Ext.menu.Menu({id: g.id + '-hctx'}); - this.hmenu.add( - {itemId:'asc', text: this.sortAscText, cls: 'xg-hmenu-sort-asc'}, - {itemId:'desc', text: this.sortDescText, cls: 'xg-hmenu-sort-desc'} - ); - if(g.enableColumnHide !== false){ - this.colMenu = new Ext.menu.Menu({id:g.id + '-hcols-menu'}); - this.colMenu.on({ - scope: this, - beforeshow: this.beforeColMenuShow, - itemclick: this.handleHdMenuClick - }); - this.hmenu.add('-', { - itemId:'columns', - hideOnClick: false, - text: this.columnsText, - menu: this.colMenu, - iconCls: 'x-cols-icon' - }); + handleMouseDown : function(e){ + var t = this.view.findHeaderCell(e.getTarget()); + if(t && this.allowHeaderDrag(e)){ + var xy = this.view.fly(t).getXY(), + x = xy[0], + exy = e.getXY(), + ex = exy[0], + w = t.offsetWidth, + adjust = false; + + if((ex - x) <= this.hw){ + adjust = -1; + }else if((x+w) - ex <= this.hw){ + adjust = 0; + } + if(adjust !== false){ + this.cm = this.grid.colModel; + var ci = this.view.getCellIndex(t); + if(adjust == -1){ + if (ci + adjust < 0) { + return; + } + while(this.cm.isHidden(ci+adjust)){ + --adjust; + if(ci+adjust < 0){ + return; + } + } + } + this.cellIndex = ci+adjust; + this.split = t.dom; + if(this.cm.isResizable(this.cellIndex) && !this.cm.isFixed(this.cellIndex)){ + Ext.grid.GridView.SplitDragZone.superclass.handleMouseDown.apply(this, arguments); + } + }else if(this.view.columnDrag){ + this.view.columnDrag.callHandleMouseDown(e); } - this.hmenu.on('itemclick', this.handleHdMenuClick, this); } + }, - if(g.trackMouseOver){ - this.mainBody.on({ - scope: this, - mouseover: this.onRowOver, - mouseout: this.onRowOut - }); - } + endDrag : function(e){ + this.marker.hide(); + var v = this.view, + endX = Math.max(this.minX, e.getPageX()), + diff = endX - this.startPos, + disabled = this.dragHeadersDisabled; + + v.onColumnSplitterMoved(this.cellIndex, this.cm.getColumnWidth(this.cellIndex)+diff); + setTimeout(function(){ + v.headersDisabled = disabled; + }, 50); + }, - if(g.enableDragDrop || g.enableDrag){ - this.dragZone = new Ext.grid.GridDragZone(g, { - ddGroup : g.ddGroup || 'GridDD' - }); - } + autoOffset : function(){ + this.setDelta(0,0); + } +}); - this.updateHeaderSortState(); +Ext.grid.PivotGridView = Ext.extend(Ext.grid.GridView, { + + + colHeaderCellCls: 'grid-hd-group-cell', + + + title: '', + + + + + getColumnHeaders: function() { + return this.grid.topAxis.buildHeaders();; + }, + + + getRowHeaders: function() { + return this.grid.leftAxis.buildHeaders(); + }, + + + renderRows : function(startRow, endRow) { + var grid = this.grid, + rows = grid.extractData(), + rowCount = rows.length, + templates = this.templates, + renderer = grid.renderer, + hasRenderer = typeof renderer == 'function', + getCellCls = this.getCellCls, + hasGetCellCls = typeof getCellCls == 'function', + cellTemplate = templates.cell, + rowTemplate = templates.row, + rowBuffer = [], + meta = {}, + tstyle = 'width:' + this.getGridInnerWidth() + 'px;', + colBuffer, column, i; + + startRow = startRow || 0; + endRow = Ext.isDefined(endRow) ? endRow : rowCount - 1; + + for (i = 0; i < rowCount; i++) { + row = rows[i]; + colCount = row.length; + colBuffer = []; + + rowIndex = startRow + i; + + + for (j = 0; j < colCount; j++) { + cell = row[j]; + + meta.css = j === 0 ? 'x-grid3-cell-first ' : (j == (colCount - 1) ? 'x-grid3-cell-last ' : ''); + meta.attr = meta.cellAttr = ''; + meta.value = cell; + + if (Ext.isEmpty(meta.value)) { + meta.value = ' '; + } + + if (hasRenderer) { + meta.value = renderer(meta.value); + } + + if (hasGetCellCls) { + meta.css += getCellCls(meta.value) + ' '; + } + colBuffer[colBuffer.length] = cellTemplate.apply(meta); + } + + rowBuffer[rowBuffer.length] = rowTemplate.apply({ + tstyle: tstyle, + cols : colCount, + cells : colBuffer.join(""), + alt : '' + }); + } + + return rowBuffer.join(""); + }, + + + masterTpl: new Ext.Template( + '
', + '
', + '
', + '
{title}
', + '
', + '
', + '
', + '
', + '
', + '
', + '
', + '
{body}
', + '', + '
', + '
', + '
 
', + '
 
', + '
' + ), + + + initTemplates: function() { + Ext.grid.PivotGridView.superclass.initTemplates.apply(this, arguments); + + var templates = this.templates || {}; + if (!templates.gcell) { + templates.gcell = new Ext.XTemplate( + '', + '
', + this.grid.enableHdMenu ? '' : '', '{value}', + '
', + '' + ); + } + + this.templates = templates; + this.hrowRe = new RegExp("ux-grid-hd-group-row-(\\d+)", ""); + }, + + + initElements: function() { + Ext.grid.PivotGridView.superclass.initElements.apply(this, arguments); + + + this.rowHeadersEl = new Ext.Element(this.scroller.child('div.x-grid3-row-headers')); + + + this.headerTitleEl = new Ext.Element(this.mainHd.child('div.x-grid3-header-title')); + }, + + + getGridInnerWidth: function() { + var previousWidth = Ext.grid.PivotGridView.superclass.getGridInnerWidth.apply(this, arguments); + + return previousWidth - this.getTotalRowHeaderWidth(); + }, + + + getTotalRowHeaderWidth: function() { + var headers = this.getRowHeaders(), + length = headers.length, + total = 0, + i; + + for (i = 0; i< length; i++) { + total += headers[i].width; + } + + return total; + }, + + + getTotalColumnHeaderHeight: function() { + return this.getColumnHeaders().length * 21; + }, + + + renderUI : function() { + var templates = this.templates, + innerWidth = this.getGridInnerWidth(); + + return templates.master.apply({ + body : templates.body.apply({rows:' '}), + ostyle: 'width:' + innerWidth + 'px', + bstyle: 'width:' + innerWidth + 'px' + }); + }, + + + onLayout: function(width, height) { + Ext.grid.PivotGridView.superclass.onLayout.apply(this, arguments); + + var width = this.getGridInnerWidth(); + + this.resizeColumnHeaders(width); + this.resizeAllRows(width); }, - - // private - layout : function(){ - if(!this.mainBody){ - return; // not rendered - } - var g = this.grid; - var c = g.getGridEl(); - var csize = c.getSize(true); - var vw = csize.width; - - if(!g.hideHeaders && (vw < 20 || csize.height < 20)){ // display: none? - return; - } + + + refresh : function(headersToo) { + this.fireEvent('beforerefresh', this); + this.grid.stopEditing(true); - if(g.autoHeight){ - this.scroller.dom.style.overflow = 'visible'; - if(Ext.isWebKit){ - this.scroller.dom.style.position = 'static'; - } - }else{ - this.el.setSize(csize.width, csize.height); - - var hdHeight = this.mainHd.getHeight(); - var vh = csize.height - (hdHeight); - - this.scroller.setSize(vw, vh); - if(this.innerHd){ - this.innerHd.style.width = (vw)+'px'; - } - } - if(this.forceFit){ - if(this.lastViewWidth != vw){ - this.fitColumns(false, false); - this.lastViewWidth = vw; - } - }else { - this.autoExpand(); - this.syncHeaderScroll(); + var result = this.renderBody(); + this.mainBody.update(result).setWidth(this.getGridInnerWidth()); + if (headersToo === true) { + this.updateHeaders(); + this.updateHeaderSortState(); } - this.onLayout(vw, vh); - }, - - // template functions for subclasses and plugins - // these functions include precalculated values - onLayout : function(vw, vh){ - // do nothing + this.processRows(0, true); + this.layout(); + this.applyEmptyText(); + this.fireEvent('refresh', this); }, - - onColumnWidthUpdated : function(col, w, tw){ - //template method + + + renderHeaders: Ext.emptyFn, + + + fitColumns: Ext.emptyFn, + + + resizeColumnHeaders: function(width) { + var topAxis = this.grid.topAxis; + + if (topAxis.rendered) { + topAxis.el.setWidth(width); + } }, - - onAllColumnWidthsUpdated : function(ws, tw){ - //template method + + + resizeRowHeaders: function() { + var rowHeaderWidth = this.getTotalRowHeaderWidth(), + marginStyle = String.format("margin-left: {0}px;", rowHeaderWidth); + + this.rowHeadersEl.setWidth(rowHeaderWidth); + this.mainBody.applyStyles(marginStyle); + Ext.fly(this.innerHd).applyStyles(marginStyle); + + this.headerTitleEl.setWidth(rowHeaderWidth); + this.headerTitleEl.setHeight(this.getTotalColumnHeaderHeight()); }, - - onColumnHiddenUpdated : function(col, hidden, tw){ - // template method + + + resizeAllRows: function(width) { + var rows = this.getRows(), + length = rows.length, + i; + + for (i = 0; i < length; i++) { + Ext.fly(rows[i]).setWidth(width); + Ext.fly(rows[i]).child('table').setWidth(width); + } }, - - updateColumnText : function(col, text){ - // template method + + + updateHeaders: function() { + this.renderGroupRowHeaders(); + this.renderGroupColumnHeaders(); }, - - afterMove : function(colIndex){ - // template method + + + renderGroupRowHeaders: function() { + var leftAxis = this.grid.leftAxis; + + this.resizeRowHeaders(); + leftAxis.rendered = false; + leftAxis.render(this.rowHeadersEl); + + this.setTitle(this.title); }, - - /* ----------------------------------- Core Specific -------------------------------------------*/ - // private - init : function(grid){ - this.grid = grid; - - this.initTemplates(); - this.initData(grid.store, grid.colModel); - this.initUI(grid); + + + setTitle: function(title) { + this.headerTitleEl.child('span').dom.innerHTML = title; }, - - // private - getColumnId : function(index){ - return this.cm.getColumnId(index); + + + renderGroupColumnHeaders: function() { + var topAxis = this.grid.topAxis; + + topAxis.rendered = false; + topAxis.render(this.innerHd.firstChild); }, - // private - getOffsetWidth : function() { - return (this.cm.getTotalWidth() + this.getScrollOffset()) + 'px'; + + isMenuDisabled: function(cellIndex, el) { + return true; + } +}); +Ext.grid.PivotAxis = Ext.extend(Ext.Component, { + + orientation: 'horizontal', + + + defaultHeaderWidth: 80, + + + paddingWidth: 7, + + + setDimensions: function(dimensions) { + this.dimensions = dimensions; }, - getScrollOffset: function(){ - return Ext.num(this.scrollOffset, Ext.getScrollBarWidth()); + + onRender: function(ct, position) { + var rows = this.orientation == 'horizontal' + ? this.renderHorizontalRows() + : this.renderVerticalRows(); + + this.el = Ext.DomHelper.overwrite(ct.dom, {tag: 'table', cn: rows}, true); }, + + + renderHorizontalRows: function() { + var headers = this.buildHeaders(), + rowCount = headers.length, + rows = [], + cells, cols, colCount, i, j; + + for (i = 0; i < rowCount; i++) { + cells = []; + cols = headers[i].items; + colCount = cols.length; + + for (j = 0; j < colCount; j++) { + cells.push({ + tag: 'td', + html: cols[j].header, + colspan: cols[j].span + }); + } - // private - renderHeaders : function(){ - var cm = this.cm, - ts = this.templates, - ct = ts.hcell, - cb = [], - p = {}, - len = cm.getColumnCount(), - last = len - 1; + rows[i] = { + tag: 'tr', + cn: cells + }; + } + + return rows; + }, + + + renderVerticalRows: function() { + var headers = this.buildHeaders(), + colCount = headers.length, + rowCells = [], + rows = [], + rowCount, col, row, colWidth, i, j; + + for (i = 0; i < colCount; i++) { + col = headers[i]; + colWidth = col.width || 80; + rowCount = col.items.length; - for(var i = 0; i < len; i++){ - p.id = cm.getColumnId(i); - p.value = cm.getColumnHeader(i) || ''; - p.style = this.getColumnStyle(i, true); - p.tooltip = this.getColumnTooltip(i); - p.css = i === 0 ? 'x-grid3-cell-first ' : (i == last ? 'x-grid3-cell-last ' : ''); - if(cm.config[i].align == 'right'){ - p.istyle = 'padding-right:16px'; - } else { - delete p.istyle; + for (j = 0; j < rowCount; j++) { + row = col.items[j]; + + rowCells[row.start] = rowCells[row.start] || []; + rowCells[row.start].push({ + tag : 'td', + html : row.header, + rowspan: row.span, + width : Ext.isBorderBox ? colWidth : colWidth - this.paddingWidth + }); } - cb[cb.length] = ct.apply(p); } - return ts.header.apply({cells: cb.join(''), tstyle:'width:'+this.getTotalWidth()+';'}); + + rowCount = rowCells.length; + for (i = 0; i < rowCount; i++) { + rows[i] = { + tag: 'tr', + cn : rowCells[i] + }; + } + + return rows; }, - - // private - getColumnTooltip : function(i){ - var tt = this.cm.getColumnTooltip(i); - if(tt){ - if(Ext.QuickTips.isEnabled()){ - return 'ext:qtip="'+tt+'"'; - }else{ - return 'title="'+tt+'"'; + + + getTuples: function() { + var newStore = new Ext.data.Store({}); + + newStore.data = this.store.data.clone(); + newStore.fields = this.store.fields; + + var sorters = [], + dimensions = this.dimensions, + length = dimensions.length, + i; + + for (i = 0; i < length; i++) { + sorters.push({ + field : dimensions[i].dataIndex, + direction: dimensions[i].direction || 'ASC' + }); + } + + newStore.sort(sorters); + + var records = newStore.data.items, + hashes = [], + tuples = [], + recData, hash, info, data, key; + + length = records.length; + + for (i = 0; i < length; i++) { + info = this.getRecordInfo(records[i]); + data = info.data; + hash = ""; + + for (key in data) { + hash += data[key] + '---'; + } + + if (hashes.indexOf(hash) == -1) { + hashes.push(hash); + tuples.push(info); } } - return ''; - }, - - // private - beforeUpdate : function(){ - this.grid.stopEditing(true); + + newStore.destroy(); + + return tuples; }, - - // private - updateHeaders : function(){ - this.innerHd.firstChild.innerHTML = this.renderHeaders(); - this.innerHd.firstChild.style.width = this.getOffsetWidth(); - this.innerHd.firstChild.firstChild.style.width = this.getTotalWidth(); + + + getRecordInfo: function(record) { + var dimensions = this.dimensions, + length = dimensions.length, + data = {}, + dimension, dataIndex, i; + + + for (i = 0; i < length; i++) { + dimension = dimensions[i]; + dataIndex = dimension.dataIndex; + + data[dataIndex] = record.get(dataIndex); + } + + + + var createMatcherFunction = function(data) { + return function(record) { + for (var dataIndex in data) { + if (record.get(dataIndex) != data[dataIndex]) { + return false; + } + } + + return true; + }; + }; + + return { + data: data, + matcher: createMatcherFunction(data) + }; }, + + + buildHeaders: function() { + var tuples = this.getTuples(), + rowCount = tuples.length, + dimensions = this.dimensions, + colCount = dimensions.length, + headers = [], + tuple, rows, currentHeader, previousHeader, span, start, isLast, changed, i, j; + + for (i = 0; i < colCount; i++) { + dimension = dimensions[i]; + rows = []; + span = 0; + start = 0; + + for (j = 0; j < rowCount; j++) { + tuple = tuples[j]; + isLast = j == (rowCount - 1); + currentHeader = tuple.data[dimension.dataIndex]; + + + changed = previousHeader != undefined && previousHeader != currentHeader; + if (i > 0 && j > 0) { + changed = changed || tuple.data[dimensions[i-1].dataIndex] != tuples[j-1].data[dimensions[i-1].dataIndex]; + } + + if (changed) { + rows.push({ + header: previousHeader, + span : span, + start : start + }); + + start += span; + span = 0; + } + + if (isLast) { + rows.push({ + header: currentHeader, + span : span + 1, + start : start + }); + + start += span; + span = 0; + } + + previousHeader = currentHeader; + span++; + } + + headers.push({ + items: rows, + width: dimension.width || this.defaultHeaderWidth + }); + + previousHeader = undefined; + } + + return headers; + } +}); - /** - * Focuses the specified row. - * @param {Number} row The row index - */ - focusRow : function(row){ - this.focusCell(row, 0, false); - }, - /** - * Focuses the specified cell. - * @param {Number} row The row index - * @param {Number} col The column index - */ - focusCell : function(row, col, hscroll){ - this.syncFocusEl(this.ensureVisible(row, col, hscroll)); - if(Ext.isGecko){ - this.focusEl.focus(); - }else{ - this.focusEl.focus.defer(1, this.focusEl); +Ext.grid.HeaderDragZone = Ext.extend(Ext.dd.DragZone, { + maxDragWidth: 120, + + constructor : function(grid, hd, hd2){ + this.grid = grid; + this.view = grid.getView(); + this.ddGroup = "gridHeader" + this.grid.getGridEl().id; + Ext.grid.HeaderDragZone.superclass.constructor.call(this, hd); + if(hd2){ + this.setHandleElId(Ext.id(hd)); + this.setOuterHandleElId(Ext.id(hd2)); } + this.scroll = false; }, - - resolveCell : function(row, col, hscroll){ - if(typeof row != "number"){ - row = row.rowIndex; - } - if(!this.ds){ - return null; - } - if(row < 0 || row >= this.ds.getCount()){ - return null; - } - col = (col !== undefined ? col : 0); - - var rowEl = this.getRow(row), - cm = this.cm, - colCount = cm.getColumnCount(), - cellEl; - if(!(hscroll === false && col === 0)){ - while(col < colCount && cm.isHidden(col)){ - col++; - } - cellEl = this.getCell(row, col); + + getDragData : function(e){ + var t = Ext.lib.Event.getTarget(e), + h = this.view.findHeaderCell(t); + if(h){ + return {ddel: h.firstChild, header:h}; } + return false; + }, - return {row: rowEl, cell: cellEl}; + onInitDrag : function(e){ + + this.dragHeadersDisabled = this.view.headersDisabled; + this.view.headersDisabled = true; + var clone = this.dragData.ddel.cloneNode(true); + clone.id = Ext.id(); + clone.style.width = Math.min(this.dragData.header.offsetWidth,this.maxDragWidth) + "px"; + this.proxy.update(clone); + return true; }, - getResolvedXY : function(resolved){ - if(!resolved){ - return null; - } - var s = this.scroller.dom, c = resolved.cell, r = resolved.row; - return c ? Ext.fly(c).getXY() : [this.el.getX(), Ext.fly(r).getY()]; + afterValidDrop : function(){ + this.completeDrop(); }, - syncFocusEl : function(row, col, hscroll){ - var xy = row; - if(!Ext.isArray(xy)){ - row = Math.min(row, Math.max(0, this.getRows().length-1)); - xy = this.getResolvedXY(this.resolveCell(row, col, hscroll)); - } - this.focusEl.setXY(xy||this.scroller.getXY()); + afterInvalidDrop : function(){ + this.completeDrop(); }, + + completeDrop: function(){ + var v = this.view, + disabled = this.dragHeadersDisabled; + setTimeout(function(){ + v.headersDisabled = disabled; + }, 50); + } +}); - ensureVisible : function(row, col, hscroll){ - var resolved = this.resolveCell(row, col, hscroll); - if(!resolved || !resolved.row){ - return; - } - var rowEl = resolved.row, - cellEl = resolved.cell, - c = this.scroller.dom, - ctop = 0, - p = rowEl, - stop = this.el.dom; - - while(p && p != stop){ - ctop += p.offsetTop; - p = p.offsetParent; - } + +Ext.grid.HeaderDropZone = Ext.extend(Ext.dd.DropZone, { + proxyOffsets : [-4, -9], + fly: Ext.Element.fly, + + constructor : function(grid, hd, hd2){ + this.grid = grid; + this.view = grid.getView(); - ctop -= this.mainHd.dom.offsetHeight; - stop = parseInt(c.scrollTop, 10); + this.proxyTop = Ext.DomHelper.append(document.body, { + cls:"col-move-top", html:" " + }, true); + this.proxyBottom = Ext.DomHelper.append(document.body, { + cls:"col-move-bottom", html:" " + }, true); + this.proxyTop.hide = this.proxyBottom.hide = function(){ + this.setLeftTop(-100,-100); + this.setStyle("visibility", "hidden"); + }; + this.ddGroup = "gridHeader" + this.grid.getGridEl().id; - var cbot = ctop + rowEl.offsetHeight, - ch = c.clientHeight, - sbot = stop + ch; + Ext.grid.HeaderDropZone.superclass.constructor.call(this, grid.getGridEl().dom); + }, - if(ctop < stop){ - c.scrollTop = ctop; - }else if(cbot > sbot){ - c.scrollTop = cbot-ch; + getTargetFromEvent : function(e){ + var t = Ext.lib.Event.getTarget(e), + cindex = this.view.findCellIndex(t); + if(cindex !== false){ + return this.view.getHeaderCell(cindex); } + }, - if(hscroll !== false){ - var cleft = parseInt(cellEl.offsetLeft, 10); - var cright = cleft + cellEl.offsetWidth; - - var sleft = parseInt(c.scrollLeft, 10); - var sright = sleft + c.clientWidth; - if(cleft < sleft){ - c.scrollLeft = cleft; - }else if(cright > sright){ - c.scrollLeft = cright-c.clientWidth; + nextVisible : function(h){ + var v = this.view, cm = this.grid.colModel; + h = h.nextSibling; + while(h){ + if(!cm.isHidden(v.getCellIndex(h))){ + return h; } + h = h.nextSibling; } - return this.getResolvedXY(resolved); + return null; }, - // private - insertRows : function(dm, firstRow, lastRow, isUpdate){ - var last = dm.getCount() - 1; - if(!isUpdate && firstRow === 0 && lastRow >= last){ - this.refresh(); - }else{ - if(!isUpdate){ - this.fireEvent('beforerowsinserted', this, firstRow, lastRow); - } - var html = this.renderRows(firstRow, lastRow), - before = this.getRow(firstRow); - if(before){ - if(firstRow === 0){ - Ext.fly(this.getRow(0)).removeClass(this.firstRowCls); - } - Ext.DomHelper.insertHtml('beforeBegin', before, html); - }else{ - var r = this.getRow(last - 1); - if(r){ - Ext.fly(r).removeClass(this.lastRowCls); - } - Ext.DomHelper.insertHtml('beforeEnd', this.mainBody.dom, html); - } - if(!isUpdate){ - this.fireEvent('rowsinserted', this, firstRow, lastRow); - this.processRows(firstRow); - }else if(firstRow === 0 || firstRow >= last){ - //ensure first/last row is kept after an update. - Ext.fly(this.getRow(firstRow)).addClass(firstRow === 0 ? this.firstRowCls : this.lastRowCls); + prevVisible : function(h){ + var v = this.view, cm = this.grid.colModel; + h = h.prevSibling; + while(h){ + if(!cm.isHidden(v.getCellIndex(h))){ + return h; } + h = h.prevSibling; } - this.syncFocusEl(firstRow); + return null; }, - // private - deleteRows : function(dm, firstRow, lastRow){ - if(dm.getRowCount()<1){ - this.refresh(); + positionIndicator : function(h, n, e){ + var x = Ext.lib.Event.getPageX(e), + r = Ext.lib.Dom.getRegion(n.firstChild), + px, + pt, + py = r.top + this.proxyOffsets[1]; + if((r.right - x) <= (r.right-r.left)/2){ + px = r.right+this.view.borderWidth; + pt = "after"; }else{ - this.fireEvent('beforerowsdeleted', this, firstRow, lastRow); + px = r.left; + pt = "before"; + } - this.removeRows(firstRow, lastRow); + if(this.grid.colModel.isFixed(this.view.getCellIndex(n))){ + return false; + } - this.processRows(firstRow); - this.fireEvent('rowsdeleted', this, firstRow, lastRow); + px += this.proxyOffsets[0]; + this.proxyTop.setLeftTop(px, py); + this.proxyTop.show(); + if(!this.bottomOffset){ + this.bottomOffset = this.view.mainHd.getHeight(); } + this.proxyBottom.setLeftTop(px, py+this.proxyTop.dom.offsetHeight+this.bottomOffset); + this.proxyBottom.show(); + return pt; }, - // private - getColumnStyle : function(col, isHeader){ - var style = !isHeader ? (this.cm.config[col].css || '') : ''; - style += 'width:'+this.getColumnWidth(col)+';'; - if(this.cm.isHidden(col)){ - style += 'display:none;'; - } - var align = this.cm.config[col].align; - if(align){ - style += 'text-align:'+align+';'; + onNodeEnter : function(n, dd, e, data){ + if(data.header != n){ + this.positionIndicator(data.header, n, e); } - return style; }, - // private - getColumnWidth : function(col){ - var w = this.cm.getColumnWidth(col); - if(typeof w == 'number'){ - return (Ext.isBorderBox || (Ext.isWebKit && !Ext.isSafari2) ? w : (w - this.borderWidth > 0 ? w - this.borderWidth : 0)) + 'px'; + onNodeOver : function(n, dd, e, data){ + var result = false; + if(data.header != n){ + result = this.positionIndicator(data.header, n, e); } - return w; + if(!result){ + this.proxyTop.hide(); + this.proxyBottom.hide(); + } + return result ? this.dropAllowed : this.dropNotAllowed; }, - // private - getTotalWidth : function(){ - return this.cm.getTotalWidth()+'px'; + onNodeOut : function(n, dd, e, data){ + this.proxyTop.hide(); + this.proxyBottom.hide(); }, - // private - fitColumns : function(preventRefresh, onlyExpand, omitColumn){ - var cm = this.cm, i; - var tw = cm.getTotalWidth(false); - var aw = this.grid.getGridEl().getWidth(true)-this.getScrollOffset(); - - if(aw < 20){ // not initialized, so don't screw up the default widths - return; - } - var extra = aw - tw; - - if(extra === 0){ - return false; - } - - var vc = cm.getColumnCount(true); - var ac = vc-(typeof omitColumn == 'number' ? 1 : 0); - if(ac === 0){ - ac = 1; - omitColumn = undefined; - } - var colCount = cm.getColumnCount(); - var cols = []; - var extraCol = 0; - var width = 0; - var w; - for (i = 0; i < colCount; i++){ - if(!cm.isHidden(i) && !cm.isFixed(i) && i !== omitColumn){ - w = cm.getColumnWidth(i); - cols.push(i); - extraCol = i; - cols.push(w); - width += w; + onNodeDrop : function(n, dd, e, data){ + var h = data.header; + if(h != n){ + var cm = this.grid.colModel, + x = Ext.lib.Event.getPageX(e), + r = Ext.lib.Dom.getRegion(n.firstChild), + pt = (r.right - x) <= ((r.right-r.left)/2) ? "after" : "before", + oldIndex = this.view.getCellIndex(h), + newIndex = this.view.getCellIndex(n); + if(pt == "after"){ + newIndex++; } + if(oldIndex < newIndex){ + newIndex--; + } + cm.moveColumn(oldIndex, newIndex); + return true; } - var frac = (aw - cm.getTotalWidth())/width; - while (cols.length){ - w = cols.pop(); - i = cols.pop(); - cm.setColumnWidth(i, Math.max(this.grid.minColumnWidth, Math.floor(w + w*frac)), true); - } + return false; + } +}); - if((tw = cm.getTotalWidth(false)) > aw){ - var adjustCol = ac != vc ? omitColumn : extraCol; - cm.setColumnWidth(adjustCol, Math.max(1, - cm.getColumnWidth(adjustCol)- (tw-aw)), true); - } +Ext.grid.GridView.ColumnDragZone = Ext.extend(Ext.grid.HeaderDragZone, { + + constructor : function(grid, hd){ + Ext.grid.GridView.ColumnDragZone.superclass.constructor.call(this, grid, hd, null); + this.proxy.el.addClass('x-grid3-col-dd'); + }, + + handleMouseDown : function(e){ + }, - if(preventRefresh !== true){ - this.updateAllColumnWidths(); - } + callHandleMouseDown : function(e){ + Ext.grid.GridView.ColumnDragZone.superclass.handleMouseDown.call(this, e); + } +}); +Ext.grid.SplitDragZone = Ext.extend(Ext.dd.DDProxy, { + fly: Ext.Element.fly, + + constructor : function(grid, hd, hd2){ + this.grid = grid; + this.view = grid.getView(); + this.proxy = this.view.resizeProxy; + Ext.grid.SplitDragZone.superclass.constructor.call(this, hd, + "gridSplitters" + this.grid.getGridEl().id, { + dragElId : Ext.id(this.proxy.dom), resizeFrame:false + }); + this.setHandleElId(Ext.id(hd)); + this.setOuterHandleElId(Ext.id(hd2)); + this.scroll = false; + }, - return true; + b4StartDrag : function(x, y){ + this.view.headersDisabled = true; + this.proxy.setHeight(this.view.mainWrap.getHeight()); + var w = this.cm.getColumnWidth(this.cellIndex); + var minw = Math.max(w-this.grid.minColumnWidth, 0); + this.resetConstraints(); + this.setXConstraint(minw, 1000); + this.setYConstraint(0, 0); + this.minX = x - minw; + this.maxX = x + 1000; + this.startPos = x; + Ext.dd.DDProxy.prototype.b4StartDrag.call(this, x, y); }, - // private - autoExpand : function(preventUpdate){ - var g = this.grid, cm = this.cm; - if(!this.userResized && g.autoExpandColumn){ - var tw = cm.getTotalWidth(false); - var aw = this.grid.getGridEl().getWidth(true)-this.getScrollOffset(); - if(tw != aw){ - var ci = cm.getIndexById(g.autoExpandColumn); - var currentWidth = cm.getColumnWidth(ci); - var cw = Math.min(Math.max(((aw-tw)+currentWidth), g.autoExpandMin), g.autoExpandMax); - if(cw != currentWidth){ - cm.setColumnWidth(ci, cw, true); - if(preventUpdate !== true){ - this.updateColumnWidth(ci, cw); - } - } + + handleMouseDown : function(e){ + var ev = Ext.EventObject.setEvent(e); + var t = this.fly(ev.getTarget()); + if(t.hasClass("x-grid-split")){ + this.cellIndex = this.view.getCellIndex(t.dom); + this.split = t.dom; + this.cm = this.grid.colModel; + if(this.cm.isResizable(this.cellIndex) && !this.cm.isFixed(this.cellIndex)){ + Ext.grid.SplitDragZone.superclass.handleMouseDown.apply(this, arguments); } } }, - // private - getColumnData : function(){ - // build a map for all the columns - var cs = [], cm = this.cm, colCount = cm.getColumnCount(); - for(var i = 0; i < colCount; i++){ - var name = cm.getDataIndex(i); - cs[i] = { - name : (typeof name == 'undefined' ? this.ds.fields.get(i).name : name), - renderer : cm.getRenderer(i), - id : cm.getColumnId(i), - style : this.getColumnStyle(i) - }; - } - return cs; + endDrag : function(e){ + this.view.headersDisabled = false; + var endX = Math.max(this.minX, Ext.lib.Event.getPageX(e)); + var diff = endX - this.startPos; + this.view.onColumnSplitterMoved(this.cellIndex, this.cm.getColumnWidth(this.cellIndex)+diff); }, - // private - renderRows : function(startRow, endRow){ - // pull in all the crap needed to render rows - var g = this.grid, cm = g.colModel, ds = g.store, stripe = g.stripeRows; - var colCount = cm.getColumnCount(); + autoOffset : function(){ + this.setDelta(0,0); + } +}); +Ext.grid.GridDragZone = function(grid, config){ + this.view = grid.getView(); + Ext.grid.GridDragZone.superclass.constructor.call(this, this.view.mainBody.dom, config); + this.scroll = false; + this.grid = grid; + this.ddel = document.createElement('div'); + this.ddel.className = 'x-grid-dd-wrap'; +}; - if(ds.getCount() < 1){ - return ''; - } +Ext.extend(Ext.grid.GridDragZone, Ext.dd.DragZone, { + ddGroup : "GridDD", - var cs = this.getColumnData(); + + getDragData : function(e){ + var t = Ext.lib.Event.getTarget(e); + var rowIndex = this.view.findRowIndex(t); + if(rowIndex !== false){ + var sm = this.grid.selModel; + if(!sm.isSelected(rowIndex) || e.hasModifier()){ + sm.handleMouseDown(this.grid, rowIndex, e); + } + return {grid: this.grid, ddel: this.ddel, rowIndex: rowIndex, selections:sm.getSelections()}; + } + return false; + }, - startRow = startRow || 0; - endRow = typeof endRow == "undefined"? ds.getCount()-1 : endRow; + + onInitDrag : function(e){ + var data = this.dragData; + this.ddel.innerHTML = this.grid.getDragDropText(); + this.proxy.update(this.ddel); + + }, - // records to render - var rs = ds.getRange(startRow, endRow); + + afterRepair : function(){ + this.dragging = false; + }, - return this.doRender(cs, rs, ds, startRow, colCount, stripe); + + getRepairXY : function(e, data){ + return false; }, - // private - renderBody : function(){ - var markup = this.renderRows() || ' '; - return this.templates.body.apply({rows: markup}); + onEndDrag : function(data, e){ + }, - // private - refreshRow : function(record){ - var ds = this.ds, index; - if(typeof record == 'number'){ - index = record; - record = ds.getAt(index); - if(!record){ - return; - } - }else{ - index = ds.indexOf(record); - if(index < 0){ - return; - } - } - this.insertRows(ds, index, index, true); - this.getRow(index).rowIndex = index; - this.onRemove(ds, record, index+1, true); - this.fireEvent('rowupdated', this, index, record); + onValidDrop : function(dd, e, id){ + + this.hideProxy(); }, - /** - * Refreshs the grid UI - * @param {Boolean} headersToo (optional) True to also refresh the headers - */ - refresh : function(headersToo){ - this.fireEvent('beforerefresh', this); - this.grid.stopEditing(true); + beforeInvalidDrop : function(e, id){ - var result = this.renderBody(); - this.mainBody.update(result).setWidth(this.getTotalWidth()); - if(headersToo === true){ - this.updateHeaders(); - this.updateHeaderSortState(); - } - this.processRows(0, true); - this.layout(); - this.applyEmptyText(); - this.fireEvent('refresh', this); - }, + } +}); - // private - applyEmptyText : function(){ - if(this.emptyText && !this.hasRows()){ - this.mainBody.update('
' + this.emptyText + '
'); - } - }, +Ext.grid.ColumnModel = Ext.extend(Ext.util.Observable, { + + defaultWidth: 100, - // private - updateHeaderSortState : function(){ - var state = this.ds.getSortState(); - if(!state){ - return; - } - if(!this.sortState || (this.sortState.field != state.field || this.sortState.direction != state.direction)){ - this.grid.fireEvent('sortchange', this.grid, state); - } - this.sortState = state; - var sortColumn = this.cm.findColumnIndex(state.field); - if(sortColumn != -1){ - var sortDir = state.direction; - this.updateSortIcon(sortColumn, sortDir); - } + + defaultSortable: false, + + + + + + constructor : function(config) { + + if (config.columns) { + Ext.apply(this, config); + this.setConfig(config.columns, true); + } else { + this.setConfig(config, true); + } + + this.addEvents( + + "widthchange", + + + "headerchange", + + + "hiddenchange", + + + "columnmoved", + + + "configchange" + ); + + Ext.grid.ColumnModel.superclass.constructor.call(this); }, - // private - destroy : function(){ - if(this.colMenu){ - Ext.menu.MenuMgr.unregister(this.colMenu); - this.colMenu.destroy(); - delete this.colMenu; - } - if(this.hmenu){ - Ext.menu.MenuMgr.unregister(this.hmenu); - this.hmenu.destroy(); - delete this.hmenu; - } + + getColumnId : function(index) { + return this.config[index].id; + }, - this.initData(null, null); - this.purgeListeners(); - Ext.fly(this.innerHd).un("click", this.handleHdDown, this); + getColumnAt : function(index) { + return this.config[index]; + }, - if(this.grid.enableColumnMove){ - Ext.destroy( - this.columnDrag.el, - this.columnDrag.proxy.ghost, - this.columnDrag.proxy.el, - this.columnDrop.el, - this.columnDrop.proxyTop, - this.columnDrop.proxyBottom, - this.columnDrag.dragData.ddel, - this.columnDrag.dragData.header - ); - if (this.columnDrag.proxy.anim) { - Ext.destroy(this.columnDrag.proxy.anim); + + setConfig : function(config, initial) { + var i, c, len; + + if (!initial) { + delete this.totalWidth; + + for (i = 0, len = this.config.length; i < len; i++) { + c = this.config[i]; + + if (c.setEditor) { + + c.setEditor(null); + } } - delete this.columnDrag.proxy.ghost; - delete this.columnDrag.dragData.ddel; - delete this.columnDrag.dragData.header; - this.columnDrag.destroy(); - delete Ext.dd.DDM.locationCache[this.columnDrag.id]; - delete this.columnDrag._domRef; - - delete this.columnDrop.proxyTop; - delete this.columnDrop.proxyBottom; - this.columnDrop.destroy(); - delete Ext.dd.DDM.locationCache["gridHeader" + this.grid.getGridEl().id]; - delete this.columnDrop._domRef; - delete Ext.dd.DDM.ids[this.columnDrop.ddGroup]; - } - - if (this.splitone){ // enableColumnResize - this.splitone.destroy(); - delete this.splitone._domRef; - delete Ext.dd.DDM.ids["gridSplitters" + this.grid.getGridEl().id]; } - Ext.fly(this.innerHd).removeAllListeners(); - Ext.removeNode(this.innerHd); - delete this.innerHd; - - Ext.destroy( - this.el, - this.mainWrap, - this.mainHd, - this.scroller, - this.mainBody, - this.focusEl, - this.resizeMarker, - this.resizeProxy, - this.activeHdBtn, - this.dragZone, - this.splitZone, - this._flyweight - ); + + this.defaults = Ext.apply({ + width: this.defaultWidth, + sortable: this.defaultSortable + }, this.defaults); - delete this.grid.container; + this.config = config; + this.lookup = {}; - if(this.dragZone){ - this.dragZone.destroy(); + for (i = 0, len = config.length; i < len; i++) { + c = Ext.applyIf(config[i], this.defaults); + + + if (Ext.isEmpty(c.id)) { + c.id = i; + } + + if (!c.isColumn) { + var Cls = Ext.grid.Column.types[c.xtype || 'gridcolumn']; + c = new Cls(c); + config[i] = c; + } + + this.lookup[c.id] = c; + } + + if (!initial) { + this.fireEvent('configchange', this); } - - Ext.dd.DDM.currentTarget = null; - delete Ext.dd.DDM.locationCache[this.grid.getGridEl().id]; - - Ext.EventManager.removeResizeListener(this.onWindowResize, this); }, - // private - onDenyColumnHide : function(){ - + + getColumnById : function(id) { + return this.lookup[id]; }, - // private - render : function(){ - if(this.autoFill){ - var ct = this.grid.ownerCt; - if (ct && ct.getLayout()){ - ct.on('afterlayout', function(){ - this.fitColumns(true, true); - this.updateHeaders(); - }, this, {single: true}); - }else{ - this.fitColumns(true, true); + + getIndexById : function(id) { + for (var i = 0, len = this.config.length; i < len; i++) { + if (this.config[i].id == id) { + return i; } - }else if(this.forceFit){ - this.fitColumns(true, false); - }else if(this.grid.autoExpandColumn){ - this.autoExpand(true); } + return -1; + }, - this.renderUI(); + + moveColumn : function(oldIndex, newIndex) { + var config = this.config, + c = config[oldIndex]; + + config.splice(oldIndex, 1); + config.splice(newIndex, 0, c); + this.dataMap = null; + this.fireEvent("columnmoved", this, oldIndex, newIndex); }, - /* --------------------------------- Model Events and Handlers --------------------------------*/ - // private - initData : function(ds, cm){ - if(this.ds){ - this.ds.un('load', this.onLoad, this); - this.ds.un('datachanged', this.onDataChange, this); - this.ds.un('add', this.onAdd, this); - this.ds.un('remove', this.onRemove, this); - this.ds.un('update', this.onUpdate, this); - this.ds.un('clear', this.onClear, this); - if(this.ds !== ds && this.ds.autoDestroy){ - this.ds.destroy(); - } - } - if(ds){ - ds.on({ - scope: this, - load: this.onLoad, - datachanged: this.onDataChange, - add: this.onAdd, - remove: this.onRemove, - update: this.onUpdate, - clear: this.onClear - }); + + getColumnCount : function(visibleOnly) { + var length = this.config.length, + c = 0, + i; + + if (visibleOnly === true) { + for (i = 0; i < length; i++) { + if (!this.isHidden(i)) { + c++; + } + } + + return c; } - this.ds = ds; + + return length; + }, - if(this.cm){ - this.cm.un('configchange', this.onColConfigChange, this); - this.cm.un('widthchange', this.onColWidthChange, this); - this.cm.un('headerchange', this.onHeaderChange, this); - this.cm.un('hiddenchange', this.onHiddenChange, this); - this.cm.un('columnmoved', this.onColumnMove, this); - } - if(cm){ - delete this.lastViewWidth; - cm.on({ - scope: this, - configchange: this.onColConfigChange, - widthchange: this.onColWidthChange, - headerchange: this.onHeaderChange, - hiddenchange: this.onHiddenChange, - columnmoved: this.onColumnMove - }); + + getColumnsBy : function(fn, scope) { + var config = this.config, + length = config.length, + result = [], + i, c; + + for (i = 0; i < length; i++){ + c = config[i]; + + if (fn.call(scope || this, c, i) === true) { + result[result.length] = c; + } } - this.cm = cm; + + return result; }, - // private - onDataChange : function(){ - this.refresh(); - this.updateHeaderSortState(); - this.syncFocusEl(0); + + isSortable : function(col) { + return !!this.config[col].sortable; }, - // private - onClear : function(){ - this.refresh(); - this.syncFocusEl(0); + + isMenuDisabled : function(col) { + return !!this.config[col].menuDisabled; }, - // private - onUpdate : function(ds, record){ - this.refreshRow(record); + + getRenderer : function(col) { + return this.config[col].renderer || Ext.grid.ColumnModel.defaultRenderer; }, - // private - onAdd : function(ds, records, index){ - this.insertRows(ds, index, index + (records.length-1)); + getRendererScope : function(col) { + return this.config[col].scope; }, - // private - onRemove : function(ds, record, index, isUpdate){ - if(isUpdate !== true){ - this.fireEvent('beforerowremoved', this, index, record); - } - this.removeRow(index); - if(isUpdate !== true){ - this.processRows(index); - this.applyEmptyText(); - this.fireEvent('rowremoved', this, index, record); - } + + setRenderer : function(col, fn) { + this.config[col].renderer = fn; }, - // private - onLoad : function(){ - this.scrollToTop.defer(Ext.isGecko ? 1 : 0, this); + + getColumnWidth : function(col) { + var width = this.config[col].width; + if(typeof width != 'number'){ + width = this.defaultWidth; + } + return width; }, - // private - onColWidthChange : function(cm, col, width){ - this.updateColumnWidth(col, width); + + setColumnWidth : function(col, width, suppressEvent) { + this.config[col].width = width; + this.totalWidth = null; + + if (!suppressEvent) { + this.fireEvent("widthchange", this, col, width); + } }, - // private - onHeaderChange : function(cm, col, text){ - this.updateHeaders(); + + getTotalWidth : function(includeHidden) { + if (!this.totalWidth) { + this.totalWidth = 0; + for (var i = 0, len = this.config.length; i < len; i++) { + if (includeHidden || !this.isHidden(i)) { + this.totalWidth += this.getColumnWidth(i); + } + } + } + return this.totalWidth; }, - // private - onHiddenChange : function(cm, col, hidden){ - this.updateColumnHidden(col, hidden); + + getColumnHeader : function(col) { + return this.config[col].header; }, - // private - onColumnMove : function(cm, oldIndex, newIndex){ - this.indexMap = null; - var s = this.getScrollState(); - this.refresh(true); - this.restoreScroll(s); - this.afterMove(newIndex); - this.grid.fireEvent('columnmove', oldIndex, newIndex); + + setColumnHeader : function(col, header) { + this.config[col].header = header; + this.fireEvent("headerchange", this, col, header); }, - // private - onColConfigChange : function(){ - delete this.lastViewWidth; - this.indexMap = null; - this.refresh(true); + + getColumnTooltip : function(col) { + return this.config[col].tooltip; + }, + + setColumnTooltip : function(col, tooltip) { + this.config[col].tooltip = tooltip; }, - /* -------------------- UI Events and Handlers ------------------------------ */ - // private - initUI : function(grid){ - grid.on('headerclick', this.onHeaderClick, this); + + getDataIndex : function(col) { + return this.config[col].dataIndex; }, - // private - initEvents : function(){ + + setDataIndex : function(col, dataIndex) { + this.config[col].dataIndex = dataIndex; }, - // private - onHeaderClick : function(g, index){ - if(this.headersDisabled || !this.cm.isSortable(index)){ - return; + + findColumnIndex : function(dataIndex) { + var c = this.config; + for(var i = 0, len = c.length; i < len; i++){ + if(c[i].dataIndex == dataIndex){ + return i; + } } - g.stopEditing(true); - g.store.sort(this.cm.getDataIndex(index)); + return -1; }, - // private - onRowOver : function(e, t){ - var row; - if((row = this.findRowIndex(t)) !== false){ - this.addRowClass(row, 'x-grid3-row-over'); - } + + isCellEditable : function(colIndex, rowIndex) { + var c = this.config[colIndex], + ed = c.editable; + + + return !!(ed || (!Ext.isDefined(ed) && c.editor)); }, - // private - onRowOut : function(e, t){ - var row; - if((row = this.findRowIndex(t)) !== false && !e.within(this.getRow(row), true)){ - this.removeRowClass(row, 'x-grid3-row-over'); - } + + getCellEditor : function(colIndex, rowIndex) { + return this.config[colIndex].getCellEditor(rowIndex); }, - // private - handleWheel : function(e){ - e.stopPropagation(); + + setEditable : function(col, editable) { + this.config[col].editable = editable; }, - // private - onRowSelect : function(row){ - this.addRowClass(row, this.selectedRowClass); + + isHidden : function(colIndex) { + return !!this.config[colIndex].hidden; }, - // private - onRowDeselect : function(row){ - this.removeRowClass(row, this.selectedRowClass); + + isFixed : function(colIndex) { + return !!this.config[colIndex].fixed; }, - // private - onCellSelect : function(row, col){ - var cell = this.getCell(row, col); - if(cell){ - this.fly(cell).addClass('x-grid3-cell-selected'); + + isResizable : function(colIndex) { + return colIndex >= 0 && this.config[colIndex].resizable !== false && this.config[colIndex].fixed !== true; + }, + + + setHidden : function(colIndex, hidden) { + var c = this.config[colIndex]; + if(c.hidden !== hidden){ + c.hidden = hidden; + this.totalWidth = null; + this.fireEvent("hiddenchange", this, colIndex, hidden); } }, - // private - onCellDeselect : function(row, col){ - var cell = this.getCell(row, col); - if(cell){ - this.fly(cell).removeClass('x-grid3-cell-selected'); - } + + setEditor : function(col, editor) { + this.config[col].setEditor(editor); }, - // private - onColumnSplitterMoved : function(i, w){ - this.userResized = true; - var cm = this.grid.colModel; - cm.setColumnWidth(i, w, true); + + destroy : function() { + var length = this.config.length, + i = 0; - if(this.forceFit){ - this.fitColumns(true, false, i); - this.updateAllColumnWidths(); - }else{ - this.updateColumnWidth(i, w); - this.syncHeaderScroll(); + for (; i < length; i++){ + this.config[i].destroy(); } - - this.grid.fireEvent('columnresize', i, w); + delete this.config; + delete this.lookup; + this.purgeListeners(); }, - // private - handleHdMenuClick : function(item){ - var index = this.hdCtxIndex, - cm = this.cm, - ds = this.ds, - id = item.getItemId(); - switch(id){ - case 'asc': - ds.sort(cm.getDataIndex(index), 'ASC'); - break; - case 'desc': - ds.sort(cm.getDataIndex(index), 'DESC'); - break; - default: - index = cm.getIndexById(id.substr(4)); - if(index != -1){ - if(item.checked && cm.getColumnsBy(this.isHideableColumn, this).length <= 1){ - this.onDenyColumnHide(); - return false; - } - cm.setHidden(index, item.checked); - } - } - return true; - }, + + setState : function(col, state) { + state = Ext.applyIf(state, this.defaults); + Ext.apply(this.config[col], state); + } +}); - // private - isHideableColumn : function(c){ - return !c.hidden && !c.fixed; - }, - // private - beforeColMenuShow : function(){ - var cm = this.cm, colCount = cm.getColumnCount(); - this.colMenu.removeAll(); - for(var i = 0; i < colCount; i++){ - if(cm.config[i].fixed !== true && cm.config[i].hideable !== false){ - this.colMenu.add(new Ext.menu.CheckItem({ - itemId: 'col-'+cm.getColumnId(i), - text: cm.getColumnHeader(i), - checked: !cm.isHidden(i), - hideOnClick:false, - disabled: cm.config[i].hideable === false - })); - } - } - }, +Ext.grid.ColumnModel.defaultRenderer = function(value) { + if (typeof value == "string" && value.length < 1) { + return " "; + } + return value; +}; +Ext.grid.AbstractSelectionModel = Ext.extend(Ext.util.Observable, { + - // private - handleHdDown : function(e, t){ - if(Ext.fly(t).hasClass('x-grid3-hd-btn')){ - e.stopEvent(); - var hd = this.findHeaderCell(t); - Ext.fly(hd).addClass('x-grid3-hd-menu-open'); - var index = this.getCellIndex(hd); - this.hdCtxIndex = index; - var ms = this.hmenu.items, cm = this.cm; - ms.get('asc').setDisabled(!cm.isSortable(index)); - ms.get('desc').setDisabled(!cm.isSortable(index)); - this.hmenu.on('hide', function(){ - Ext.fly(hd).removeClass('x-grid3-hd-menu-open'); - }, this, {single:true}); - this.hmenu.show(t, 'tl-bl?'); - } + constructor : function(){ + this.locked = false; + Ext.grid.AbstractSelectionModel.superclass.constructor.call(this); }, - // private - handleHdOver : function(e, t){ - var hd = this.findHeaderCell(t); - if(hd && !this.headersDisabled){ - this.activeHdRef = t; - this.activeHdIndex = this.getCellIndex(hd); - var fly = this.fly(hd); - this.activeHdRegion = fly.getRegion(); - if(!this.cm.isMenuDisabled(this.activeHdIndex)){ - fly.addClass('x-grid3-hd-over'); - this.activeHdBtn = fly.child('.x-grid3-hd-btn'); - if(this.activeHdBtn){ - this.activeHdBtn.dom.style.height = (hd.firstChild.offsetHeight-1)+'px'; - } - } + + init : function(grid){ + this.grid = grid; + if(this.lockOnInit){ + delete this.lockOnInit; + this.locked = false; + this.lock(); } + this.initEvents(); }, - // private - handleHdMove : function(e, t){ - var hd = this.findHeaderCell(this.activeHdRef); - if(hd && !this.headersDisabled){ - var hw = this.splitHandleWidth || 5, - r = this.activeHdRegion, - x = e.getPageX(), - ss = hd.style, - cur = ''; - if(this.grid.enableColumnResize !== false){ - if(x - r.left <= hw && this.cm.isResizable(this.activeHdIndex-1)){ - cur = Ext.isAir ? 'move' : Ext.isWebKit ? 'e-resize' : 'col-resize'; // col-resize not always supported - }else if(r.right - x <= (!this.activeHdBtn ? hw : 2) && this.cm.isResizable(this.activeHdIndex)){ - cur = Ext.isAir ? 'move' : Ext.isWebKit ? 'w-resize' : 'col-resize'; - } + + lock : function(){ + if(!this.locked){ + this.locked = true; + + var g = this.grid; + if(g){ + g.getView().on({ + scope: this, + beforerefresh: this.sortUnLock, + refresh: this.sortLock + }); + }else{ + this.lockOnInit = true; } - ss.cursor = cur; } }, - // private - handleHdOut : function(e, t){ - var hd = this.findHeaderCell(t); - if(hd && (!Ext.isIE || !e.within(hd, true))){ - this.activeHdRef = null; - this.fly(hd).removeClass('x-grid3-hd-over'); - hd.style.cursor = ''; + + sortLock : function() { + this.locked = true; + }, + + + sortUnLock : function() { + this.locked = false; + }, + + + unlock : function(){ + if(this.locked){ + this.locked = false; + var g = this.grid, + gv; + + + if(g){ + gv = g.getView(); + gv.un('beforerefresh', this.sortUnLock, this); + gv.un('refresh', this.sortLock, this); + }else{ + delete this.lockOnInit; + } } }, - // private - hasRows : function(){ - var fc = this.mainBody.dom.firstChild; - return fc && fc.nodeType == 1 && fc.className != 'x-grid-empty'; + + isLocked : function(){ + return this.locked; }, - // back compat - bind : function(d, c){ - this.initData(d, c); + destroy: function(){ + this.unlock(); + this.purgeListeners(); } }); +Ext.grid.RowSelectionModel = Ext.extend(Ext.grid.AbstractSelectionModel, { + + singleSelect : false, + + constructor : function(config){ + Ext.apply(this, config); + this.selections = new Ext.util.MixedCollection(false, function(o){ + return o.id; + }); + this.last = false; + this.lastActive = false; -// private -// This is a support class used internally by the Grid components -Ext.grid.GridView.SplitDragZone = function(grid, hd){ - this.grid = grid; - this.view = grid.getView(); - this.marker = this.view.resizeMarker; - this.proxy = this.view.resizeProxy; - Ext.grid.GridView.SplitDragZone.superclass.constructor.call(this, hd, - 'gridSplitters' + this.grid.getGridEl().id, { - dragElId : Ext.id(this.proxy.dom), resizeFrame:false - }); - this.scroll = false; - this.hw = this.view.splitHandleWidth || 5; -}; -Ext.extend(Ext.grid.GridView.SplitDragZone, Ext.dd.DDProxy, { - - b4StartDrag : function(x, y){ - this.view.headersDisabled = true; - var h = this.view.mainWrap.getHeight(); - this.marker.setHeight(h); - this.marker.show(); - this.marker.alignTo(this.view.getHeaderCell(this.cellIndex), 'tl-tl', [-2, 0]); - this.proxy.setHeight(h); - var w = this.cm.getColumnWidth(this.cellIndex); - var minw = Math.max(w-this.grid.minColumnWidth, 0); - this.resetConstraints(); - this.setXConstraint(minw, 1000); - this.setYConstraint(0, 0); - this.minX = x - minw; - this.maxX = x + 1000; - this.startPos = x; - Ext.dd.DDProxy.prototype.b4StartDrag.call(this, x, y); + this.addEvents( + + 'selectionchange', + + 'beforerowselect', + + 'rowselect', + + 'rowdeselect' + ); + Ext.grid.RowSelectionModel.superclass.constructor.call(this); }, + + + initEvents : function(){ - handleMouseDown : function(e){ - var t = this.view.findHeaderCell(e.getTarget()); - if(t){ - var xy = this.view.fly(t).getXY(), x = xy[0], y = xy[1]; - var exy = e.getXY(), ex = exy[0]; - var w = t.offsetWidth, adjust = false; - if((ex - x) <= this.hw){ - adjust = -1; - }else if((x+w) - ex <= this.hw){ - adjust = 0; - } - if(adjust !== false){ - this.cm = this.grid.colModel; - var ci = this.view.getCellIndex(t); - if(adjust == -1){ - if (ci + adjust < 0) { - return; - } - while(this.cm.isHidden(ci+adjust)){ - --adjust; - if(ci+adjust < 0){ - return; - } - } - } - this.cellIndex = ci+adjust; - this.split = t.dom; - if(this.cm.isResizable(this.cellIndex) && !this.cm.isFixed(this.cellIndex)){ - Ext.grid.GridView.SplitDragZone.superclass.handleMouseDown.apply(this, arguments); - } - }else if(this.view.columnDrag){ - this.view.columnDrag.callHandleMouseDown(e); + if(!this.grid.enableDragDrop && !this.grid.enableDrag){ + this.grid.on('rowmousedown', this.handleMouseDown, this); + } + + this.rowNav = new Ext.KeyNav(this.grid.getGridEl(), { + up: this.onKeyPress, + down: this.onKeyPress, + scope: this + }); + + this.grid.getView().on({ + scope: this, + refresh: this.onRefresh, + rowupdated: this.onRowUpdated, + rowremoved: this.onRemove + }); + }, + + onKeyPress : function(e, name){ + var up = name == 'up', + method = up ? 'selectPrevious' : 'selectNext', + add = up ? -1 : 1, + last; + if(!e.shiftKey || this.singleSelect){ + this[method](false); + }else if(this.last !== false && this.lastActive !== false){ + last = this.last; + this.selectRange(this.last, this.lastActive + add); + this.grid.getView().focusRow(this.lastActive); + if(last !== false){ + this.last = last; } + }else{ + this.selectFirstRow(); } }, - endDrag : function(e){ - this.marker.hide(); - var v = this.view; - var endX = Math.max(this.minX, e.getPageX()); - var diff = endX - this.startPos; - v.onColumnSplitterMoved(this.cellIndex, this.cm.getColumnWidth(this.cellIndex)+diff); - setTimeout(function(){ - v.headersDisabled = false; - }, 50); + + onRefresh : function(){ + var ds = this.grid.store, + s = this.getSelections(), + i = 0, + len = s.length, + index, r; + + this.silent = true; + this.clearSelections(true); + for(; i < len; i++){ + r = s[i]; + if((index = ds.indexOfId(r.id)) != -1){ + this.selectRow(index, true); + } + } + if(s.length != this.selections.getCount()){ + this.fireEvent('selectionchange', this); + } + this.silent = false; }, - autoOffset : function(){ - this.setDelta(0,0); - } -}); -// private -// This is a support class used internally by the Grid components -Ext.grid.HeaderDragZone = function(grid, hd, hd2){ - this.grid = grid; - this.view = grid.getView(); - this.ddGroup = "gridHeader" + this.grid.getGridEl().id; - Ext.grid.HeaderDragZone.superclass.constructor.call(this, hd); - if(hd2){ - this.setHandleElId(Ext.id(hd)); - this.setOuterHandleElId(Ext.id(hd2)); - } - this.scroll = false; -}; -Ext.extend(Ext.grid.HeaderDragZone, Ext.dd.DragZone, { - maxDragWidth: 120, - getDragData : function(e){ - var t = Ext.lib.Event.getTarget(e); - var h = this.view.findHeaderCell(t); - if(h){ - return {ddel: h.firstChild, header:h}; - } - return false; - }, - - onInitDrag : function(e){ - this.view.headersDisabled = true; - var clone = this.dragData.ddel.cloneNode(true); - clone.id = Ext.id(); - clone.style.width = Math.min(this.dragData.header.offsetWidth,this.maxDragWidth) + "px"; - this.proxy.update(clone); - return true; - }, - - afterValidDrop : function(){ - var v = this.view; - setTimeout(function(){ - v.headersDisabled = false; - }, 50); - }, - - afterInvalidDrop : function(){ - var v = this.view; - setTimeout(function(){ - v.headersDisabled = false; - }, 50); - } -}); - -// private -// This is a support class used internally by the Grid components -Ext.grid.HeaderDropZone = function(grid, hd, hd2){ - this.grid = grid; - this.view = grid.getView(); - // split the proxies so they don't interfere with mouse events - this.proxyTop = Ext.DomHelper.append(document.body, { - cls:"col-move-top", html:" " - }, true); - this.proxyBottom = Ext.DomHelper.append(document.body, { - cls:"col-move-bottom", html:" " - }, true); - this.proxyTop.hide = this.proxyBottom.hide = function(){ - this.setLeftTop(-100,-100); - this.setStyle("visibility", "hidden"); - }; - this.ddGroup = "gridHeader" + this.grid.getGridEl().id; - // temporarily disabled - //Ext.dd.ScrollManager.register(this.view.scroller.dom); - Ext.grid.HeaderDropZone.superclass.constructor.call(this, grid.getGridEl().dom); -}; -Ext.extend(Ext.grid.HeaderDropZone, Ext.dd.DropZone, { - proxyOffsets : [-4, -9], - fly: Ext.Element.fly, - - getTargetFromEvent : function(e){ - var t = Ext.lib.Event.getTarget(e); - var cindex = this.view.findCellIndex(t); - if(cindex !== false){ - return this.view.getHeaderCell(cindex); - } - }, - - nextVisible : function(h){ - var v = this.view, cm = this.grid.colModel; - h = h.nextSibling; - while(h){ - if(!cm.isHidden(v.getCellIndex(h))){ - return h; - } - h = h.nextSibling; - } - return null; - }, - - prevVisible : function(h){ - var v = this.view, cm = this.grid.colModel; - h = h.prevSibling; - while(h){ - if(!cm.isHidden(v.getCellIndex(h))){ - return h; - } - h = h.prevSibling; - } - return null; - }, - - positionIndicator : function(h, n, e){ - var x = Ext.lib.Event.getPageX(e); - var r = Ext.lib.Dom.getRegion(n.firstChild); - var px, pt, py = r.top + this.proxyOffsets[1]; - if((r.right - x) <= (r.right-r.left)/2){ - px = r.right+this.view.borderWidth; - pt = "after"; - }else{ - px = r.left; - pt = "before"; - } - - if(this.grid.colModel.isFixed(this.view.getCellIndex(n))){ - return false; - } - - px += this.proxyOffsets[0]; - this.proxyTop.setLeftTop(px, py); - this.proxyTop.show(); - if(!this.bottomOffset){ - this.bottomOffset = this.view.mainHd.getHeight(); - } - this.proxyBottom.setLeftTop(px, py+this.proxyTop.dom.offsetHeight+this.bottomOffset); - this.proxyBottom.show(); - return pt; - }, - - onNodeEnter : function(n, dd, e, data){ - if(data.header != n){ - this.positionIndicator(data.header, n, e); - } - }, - - onNodeOver : function(n, dd, e, data){ - var result = false; - if(data.header != n){ - result = this.positionIndicator(data.header, n, e); - } - if(!result){ - this.proxyTop.hide(); - this.proxyBottom.hide(); - } - return result ? this.dropAllowed : this.dropNotAllowed; - }, - - onNodeOut : function(n, dd, e, data){ - this.proxyTop.hide(); - this.proxyBottom.hide(); - }, - - onNodeDrop : function(n, dd, e, data){ - var h = data.header; - if(h != n){ - var cm = this.grid.colModel; - var x = Ext.lib.Event.getPageX(e); - var r = Ext.lib.Dom.getRegion(n.firstChild); - var pt = (r.right - x) <= ((r.right-r.left)/2) ? "after" : "before"; - var oldIndex = this.view.getCellIndex(h); - var newIndex = this.view.getCellIndex(n); - if(pt == "after"){ - newIndex++; - } - if(oldIndex < newIndex){ - newIndex--; - } - cm.moveColumn(oldIndex, newIndex); - return true; - } - return false; - } -}); - - -Ext.grid.GridView.ColumnDragZone = function(grid, hd){ - Ext.grid.GridView.ColumnDragZone.superclass.constructor.call(this, grid, hd, null); - this.proxy.el.addClass('x-grid3-col-dd'); -}; - -Ext.extend(Ext.grid.GridView.ColumnDragZone, Ext.grid.HeaderDragZone, { - handleMouseDown : function(e){ - - }, - - callHandleMouseDown : function(e){ - Ext.grid.GridView.ColumnDragZone.superclass.handleMouseDown.call(this, e); - } -});// private -// This is a support class used internally by the Grid components -Ext.grid.SplitDragZone = function(grid, hd, hd2){ - this.grid = grid; - this.view = grid.getView(); - this.proxy = this.view.resizeProxy; - Ext.grid.SplitDragZone.superclass.constructor.call(this, hd, - "gridSplitters" + this.grid.getGridEl().id, { - dragElId : Ext.id(this.proxy.dom), resizeFrame:false - }); - this.setHandleElId(Ext.id(hd)); - this.setOuterHandleElId(Ext.id(hd2)); - this.scroll = false; -}; -Ext.extend(Ext.grid.SplitDragZone, Ext.dd.DDProxy, { - fly: Ext.Element.fly, - - b4StartDrag : function(x, y){ - this.view.headersDisabled = true; - this.proxy.setHeight(this.view.mainWrap.getHeight()); - var w = this.cm.getColumnWidth(this.cellIndex); - var minw = Math.max(w-this.grid.minColumnWidth, 0); - this.resetConstraints(); - this.setXConstraint(minw, 1000); - this.setYConstraint(0, 0); - this.minX = x - minw; - this.maxX = x + 1000; - this.startPos = x; - Ext.dd.DDProxy.prototype.b4StartDrag.call(this, x, y); + + onRemove : function(v, index, r){ + if(this.selections.remove(r) !== false){ + this.fireEvent('selectionchange', this); + } }, + + onRowUpdated : function(v, index, r){ + if(this.isSelected(r)){ + v.onRowSelect(index); + } + }, - handleMouseDown : function(e){ - var ev = Ext.EventObject.setEvent(e); - var t = this.fly(ev.getTarget()); - if(t.hasClass("x-grid-split")){ - this.cellIndex = this.view.getCellIndex(t.dom); - this.split = t.dom; - this.cm = this.grid.colModel; - if(this.cm.isResizable(this.cellIndex) && !this.cm.isFixed(this.cellIndex)){ - Ext.grid.SplitDragZone.superclass.handleMouseDown.apply(this, arguments); - } + + selectRecords : function(records, keepExisting){ + if(!keepExisting){ + this.clearSelections(); + } + var ds = this.grid.store, + i = 0, + len = records.length; + for(; i < len; i++){ + this.selectRow(ds.indexOf(records[i]), true); } }, - endDrag : function(e){ - this.view.headersDisabled = false; - var endX = Math.max(this.minX, Ext.lib.Event.getPageX(e)); - var diff = endX - this.startPos; - this.view.onColumnSplitterMoved(this.cellIndex, this.cm.getColumnWidth(this.cellIndex)+diff); + + getCount : function(){ + return this.selections.length; }, - autoOffset : function(){ - this.setDelta(0,0); - } -});/** - * @class Ext.grid.GridDragZone - * @extends Ext.dd.DragZone - *

A customized implementation of a {@link Ext.dd.DragZone DragZone} which provides default implementations of two of the - * template methods of DragZone to enable dragging of the selected rows of a GridPanel.

- *

A cooperating {@link Ext.dd.DropZone DropZone} must be created who's template method implementations of - * {@link Ext.dd.DropZone#onNodeEnter onNodeEnter}, {@link Ext.dd.DropZone#onNodeOver onNodeOver}, - * {@link Ext.dd.DropZone#onNodeOut onNodeOut} and {@link Ext.dd.DropZone#onNodeDrop onNodeDrop}

are able - * to process the {@link #getDragData data} which is provided. - */ -Ext.grid.GridDragZone = function(grid, config){ - this.view = grid.getView(); - Ext.grid.GridDragZone.superclass.constructor.call(this, this.view.mainBody.dom, config); - this.scroll = false; - this.grid = grid; - this.ddel = document.createElement('div'); - this.ddel.className = 'x-grid-dd-wrap'; -}; + + selectFirstRow : function(){ + this.selectRow(0); + }, -Ext.extend(Ext.grid.GridDragZone, Ext.dd.DragZone, { - ddGroup : "GridDD", + + selectLastRow : function(keepExisting){ + this.selectRow(this.grid.store.getCount() - 1, keepExisting); + }, - /** - *

The provided implementation of the getDragData method which collects the data to be dragged from the GridPanel on mousedown.

- *

This data is available for processing in the {@link Ext.dd.DropZone#onNodeEnter onNodeEnter}, {@link Ext.dd.DropZone#onNodeOver onNodeOver}, - * {@link Ext.dd.DropZone#onNodeOut onNodeOut} and {@link Ext.dd.DropZone#onNodeDrop onNodeDrop} methods of a cooperating {@link Ext.dd.DropZone DropZone}.

- *

The data object contains the following properties:

    - *
  • grid : Ext.Grid.GridPanel
    The GridPanel from which the data is being dragged.
  • - *
  • ddel : htmlElement
    An htmlElement which provides the "picture" of the data being dragged.
  • - *
  • rowIndex : Number
    The index of the row which receieved the mousedown gesture which triggered the drag.
  • - *
  • selections : Array
    An Array of the selected Records which are being dragged from the GridPanel.
  • - *

- */ - getDragData : function(e){ - var t = Ext.lib.Event.getTarget(e); - var rowIndex = this.view.findRowIndex(t); - if(rowIndex !== false){ - var sm = this.grid.selModel; - if(!sm.isSelected(rowIndex) || e.hasModifier()){ - sm.handleMouseDown(this.grid, rowIndex, e); - } - return {grid: this.grid, ddel: this.ddel, rowIndex: rowIndex, selections:sm.getSelections()}; + + selectNext : function(keepExisting){ + if(this.hasNext()){ + this.selectRow(this.last+1, keepExisting); + this.grid.getView().focusRow(this.last); + return true; + } + return false; + }, + + + selectPrevious : function(keepExisting){ + if(this.hasPrevious()){ + this.selectRow(this.last-1, keepExisting); + this.grid.getView().focusRow(this.last); + return true; } return false; }, - /** - *

The provided implementation of the onInitDrag method. Sets the innerHTML of the drag proxy which provides the "picture" - * of the data being dragged.

- *

The innerHTML data is found by calling the owning GridPanel's {@link Ext.grid.GridPanel#getDragDropText getDragDropText}.

- */ - onInitDrag : function(e){ - var data = this.dragData; - this.ddel.innerHTML = this.grid.getDragDropText(); - this.proxy.update(this.ddel); - // fire start drag? + + hasNext : function(){ + return this.last !== false && (this.last+1) < this.grid.store.getCount(); }, - /** - * An empty immplementation. Implement this to provide behaviour after a repair of an invalid drop. An implementation might highlight - * the selected rows to show that they have not been dragged. - */ - afterRepair : function(){ - this.dragging = false; + + hasPrevious : function(){ + return !!this.last; }, - /** - *

An empty implementation. Implement this to provide coordinates for the drag proxy to slide back to after an invalid drop.

- *

Called before a repair of an invalid drop to get the XY to animate to.

- * @param {EventObject} e The mouse up event - * @return {Array} The xy location (e.g. [100, 200]) - */ - getRepairXY : function(e, data){ - return false; - }, - onEndDrag : function(data, e){ - // fire end drag? + + getSelections : function(){ + return [].concat(this.selections.items); }, - onValidDrop : function(dd, e, id){ - // fire drag drop? - this.hideProxy(); + + getSelected : function(){ + return this.selections.itemAt(0); }, - beforeInvalidDrop : function(e, id){ + + each : function(fn, scope){ + var s = this.getSelections(), + i = 0, + len = s.length; + + for(; i < len; i++){ + if(fn.call(scope || this, s[i], i) === false){ + return false; + } + } + return true; + }, - } -}); -/** - * @class Ext.grid.ColumnModel - * @extends Ext.util.Observable - *

After the data has been read into the client side cache ({@link Ext.data.Store Store}), - * the ColumnModel is used to configure how and what parts of that data will be displayed in the - * vertical slices (columns) of the grid. The Ext.grid.ColumnModel Class is the default implementation - * of a ColumnModel used by implentations of {@link Ext.grid.GridPanel GridPanel}.

- *

Data is mapped into the store's records and then indexed into the ColumnModel using the - * {@link Ext.grid.Column#dataIndex dataIndex}:

- *

-{data source} == mapping ==> {data store} == {@link Ext.grid.Column#dataIndex dataIndex} ==> {ColumnModel}
- * 
- *

Each {@link Ext.grid.Column Column} in the grid's ColumnModel is configured with a - * {@link Ext.grid.Column#dataIndex dataIndex} to specify how the data within - * each record in the store is indexed into the ColumnModel.

- *

There are two ways to initialize the ColumnModel class:

- *

Initialization Method 1: an Array

-

- var colModel = new Ext.grid.ColumnModel([
-    { header: "Ticker", width: 60, sortable: true},
-    { header: "Company Name", width: 150, sortable: true, id: 'company'},
-    { header: "Market Cap.", width: 100, sortable: true},
-    { header: "$ Sales", width: 100, sortable: true, renderer: money},
-    { header: "Employees", width: 100, sortable: true, resizable: false}
- ]);
- 
- *

The ColumnModel may be initialized with an Array of {@link Ext.grid.Column} column configuration - * objects to define the initial layout / display of the columns in the Grid. The order of each - * {@link Ext.grid.Column} column configuration object within the specified Array defines the initial - * order of the column display. A Column's display may be initially hidden using the - * {@link Ext.grid.Column#hidden hidden} config property (and then shown using the column - * header menu). Fields that are not included in the ColumnModel will not be displayable at all.

- *

How each column in the grid correlates (maps) to the {@link Ext.data.Record} field in the - * {@link Ext.data.Store Store} the column draws its data from is configured through the - * {@link Ext.grid.Column#dataIndex dataIndex}. If the - * {@link Ext.grid.Column#dataIndex dataIndex} is not explicitly defined (as shown in the - * example above) it will use the column configuration's index in the Array as the index.

- *

See {@link Ext.grid.Column} for additional configuration options for each column.

- *

Initialization Method 2: an Object

- *

In order to use configuration options from Ext.grid.ColumnModel, an Object may be used to - * initialize the ColumnModel. The column configuration Array will be specified in the {@link #columns} - * config property. The {@link #defaults} config property can be used to apply defaults - * for all columns, e.g.:


- var colModel = new Ext.grid.ColumnModel({
-    columns: [
-        { header: "Ticker", width: 60, menuDisabled: false},
-        { header: "Company Name", width: 150, id: 'company'},
-        { header: "Market Cap."},
-        { header: "$ Sales", renderer: money},
-        { header: "Employees", resizable: false}
-    ],
-    defaults: {
-        sortable: true,
-        menuDisabled: true,
-        width: 100
+    
+    clearSelections : function(fast){
+        if(this.isLocked()){
+            return;
+        }
+        if(fast !== true){
+            var ds = this.grid.store,
+                s = this.selections;
+            s.each(function(r){
+                this.deselectRow(ds.indexOfId(r.id));
+            }, this);
+            s.clear();
+        }else{
+            this.selections.clear();
+        }
+        this.last = false;
     },
-    listeners: {
-        {@link #hiddenchange}: function(cm, colIndex, hidden) {
-            saveConfig(colIndex, hidden);
+
+
+    
+    selectAll : function(){
+        if(this.isLocked()){
+            return;
         }
-    }
-});
- 
- *

In both examples above, the ability to apply a CSS class to all cells in a column (including the - * header) is demonstrated through the use of the {@link Ext.grid.Column#id id} config - * option. This column could be styled by including the following css:


- //add this css *after* the core css is loaded
-.x-grid3-td-company {
-    color: red; // entire column will have red font
-}
-// modify the header row only, adding an icon to the column header
-.x-grid3-hd-company {
-    background: transparent
-        url(../../resources/images/icons/silk/building.png)
-        no-repeat 3px 3px ! important;
-        padding-left:20px;
-}
- 
- * Note that the "Company Name" column could be specified as the - * {@link Ext.grid.GridPanel}.{@link Ext.grid.GridPanel#autoExpandColumn autoExpandColumn}. - * @constructor - * @param {Mixed} config Specify either an Array of {@link Ext.grid.Column} configuration objects or specify - * a configuration Object (see introductory section discussion utilizing Initialization Method 2 above). - */ -Ext.grid.ColumnModel = function(config){ - /** - * An Array of {@link Ext.grid.Column Column definition} objects representing the configuration - * of this ColumnModel. See {@link Ext.grid.Column} for the configuration properties that may - * be specified. - * @property config - * @type Array - */ - if(config.columns){ - Ext.apply(this, config); - this.setConfig(config.columns, true); - }else{ - this.setConfig(config, true); - } - this.addEvents( - /** - * @event widthchange - * Fires when the width of a column is programmaticially changed using - * {@link #setColumnWidth}. - * Note internal resizing suppresses the event from firing. See also - * {@link Ext.grid.GridPanel}.{@link #columnresize}. - * @param {ColumnModel} this - * @param {Number} columnIndex The column index - * @param {Number} newWidth The new width - */ - "widthchange", - /** - * @event headerchange - * Fires when the text of a header changes. - * @param {ColumnModel} this - * @param {Number} columnIndex The column index - * @param {String} newText The new header text - */ - "headerchange", - /** - * @event hiddenchange - * Fires when a column is hidden or "unhidden". - * @param {ColumnModel} this - * @param {Number} columnIndex The column index - * @param {Boolean} hidden true if hidden, false otherwise - */ - "hiddenchange", - /** - * @event columnmoved - * Fires when a column is moved. - * @param {ColumnModel} this - * @param {Number} oldIndex - * @param {Number} newIndex - */ - "columnmoved", - /** - * @event configchange - * Fires when the configuration is changed - * @param {ColumnModel} this - */ - "configchange" - ); - Ext.grid.ColumnModel.superclass.constructor.call(this); -}; -Ext.extend(Ext.grid.ColumnModel, Ext.util.Observable, { - /** - * @cfg {Number} defaultWidth (optional) The width of columns which have no {@link #width} - * specified (defaults to 100). This property shall preferably be configured through the - * {@link #defaults} config property. - */ - defaultWidth: 100, - /** - * @cfg {Boolean} defaultSortable (optional) Default sortable of columns which have no - * sortable specified (defaults to false). This property shall preferably be configured - * through the {@link #defaults} config property. - */ - defaultSortable: false, - /** - * @cfg {Array} columns An Array of object literals. The config options defined by - * {@link Ext.grid.Column} are the options which may appear in the object literal for each - * individual column definition. - */ - /** - * @cfg {Object} defaults Object literal which will be used to apply {@link Ext.grid.Column} - * configuration options to all {@link #columns}. Configuration options specified with - * individual {@link Ext.grid.Column column} configs will supersede these {@link #defaults}. - */ + this.selections.clear(); + for(var i = 0, len = this.grid.store.getCount(); i < len; i++){ + this.selectRow(i, true); + } + }, - /** - * Returns the id of the column at the specified index. - * @param {Number} index The column index - * @return {String} the id - */ - getColumnId : function(index){ - return this.config[index].id; + + hasSelection : function(){ + return this.selections.length > 0; }, - getColumnAt : function(index){ - return this.config[index]; + + isSelected : function(index){ + var r = Ext.isNumber(index) ? this.grid.store.getAt(index) : index; + return (r && this.selections.key(r.id) ? true : false); }, - /** - *

Reconfigures this column model according to the passed Array of column definition objects. - * For a description of the individual properties of a column definition object, see the - * Config Options.

- *

Causes the {@link #configchange} event to be fired. A {@link Ext.grid.GridPanel GridPanel} - * using this ColumnModel will listen for this event and refresh its UI automatically.

- * @param {Array} config Array of Column definition objects. - * @param {Boolean} initial Specify true to bypass cleanup which deletes the totalWidth - * and destroys existing editors. - */ - setConfig : function(config, initial){ - var i, c, len; - if(!initial){ // cleanup - delete this.totalWidth; - for(i = 0, len = this.config.length; i < len; i++){ - c = this.config[i]; - if(c.editor){ - c.editor.destroy(); - } + + isIdSelected : function(id){ + return (this.selections.key(id) ? true : false); + }, + + + handleMouseDown : function(g, rowIndex, e){ + if(e.button !== 0 || this.isLocked()){ + return; + } + var view = this.grid.getView(); + if(e.shiftKey && !this.singleSelect && this.last !== false){ + var last = this.last; + this.selectRange(last, rowIndex, e.ctrlKey); + this.last = last; + view.focusRow(rowIndex); + }else{ + var isSelected = this.isSelected(rowIndex); + if(e.ctrlKey && isSelected){ + this.deselectRow(rowIndex); + }else if(!isSelected || this.getCount() > 1){ + this.selectRow(rowIndex, e.ctrlKey || e.shiftKey); + view.focusRow(rowIndex); } } + }, - // backward compatibility - this.defaults = Ext.apply({ - width: this.defaultWidth, - sortable: this.defaultSortable - }, this.defaults); + + selectRows : function(rows, keepExisting){ + if(!keepExisting){ + this.clearSelections(); + } + for(var i = 0, len = rows.length; i < len; i++){ + this.selectRow(rows[i], true); + } + }, - this.config = config; - this.lookup = {}; + + selectRange : function(startRow, endRow, keepExisting){ + var i; + if(this.isLocked()){ + return; + } + if(!keepExisting){ + this.clearSelections(); + } + if(startRow <= endRow){ + for(i = startRow; i <= endRow; i++){ + this.selectRow(i, true); + } + }else{ + for(i = startRow; i >= endRow; i--){ + this.selectRow(i, true); + } + } + }, - for(i = 0, len = config.length; i < len; i++){ - c = Ext.applyIf(config[i], this.defaults); - // if no id, create one using column's ordinal position - if(typeof c.id == 'undefined'){ - c.id = i; + + deselectRange : function(startRow, endRow, preventViewNotify){ + if(this.isLocked()){ + return; + } + for(var i = startRow; i <= endRow; i++){ + this.deselectRow(i, preventViewNotify); + } + }, + + + selectRow : function(index, keepExisting, preventViewNotify){ + if(this.isLocked() || (index < 0 || index >= this.grid.store.getCount()) || (keepExisting && this.isSelected(index))){ + return; + } + var r = this.grid.store.getAt(index); + if(r && this.fireEvent('beforerowselect', this, index, keepExisting, r) !== false){ + if(!keepExisting || this.singleSelect){ + this.clearSelections(); } - if(!c.isColumn){ - var Cls = Ext.grid.Column.types[c.xtype || 'gridcolumn']; - c = new Cls(c); - config[i] = c; + this.selections.add(r); + this.last = this.lastActive = index; + if(!preventViewNotify){ + this.grid.getView().onRowSelect(index); + } + if(!this.silent){ + this.fireEvent('rowselect', this, index, r); + this.fireEvent('selectionchange', this); } - this.lookup[c.id] = c; } - if(!initial){ - this.fireEvent('configchange', this); + }, + + + deselectRow : function(index, preventViewNotify){ + if(this.isLocked()){ + return; + } + if(this.last == index){ + this.last = false; + } + if(this.lastActive == index){ + this.lastActive = false; + } + var r = this.grid.store.getAt(index); + if(r){ + this.selections.remove(r); + if(!preventViewNotify){ + this.grid.getView().onRowDeselect(index); + } + this.fireEvent('rowdeselect', this, index, r); + this.fireEvent('selectionchange', this); } }, - /** - * Returns the column for a specified id. - * @param {String} id The column id - * @return {Object} the column - */ - getColumnById : function(id){ - return this.lookup[id]; + + acceptsNav : function(row, col, cm){ + return !cm.isHidden(col) && cm.isCellEditable(col, row); }, - /** - * Returns the index for a specified column id. - * @param {String} id The column id - * @return {Number} the index, or -1 if not found - */ - getIndexById : function(id){ - for(var i = 0, len = this.config.length; i < len; i++){ - if(this.config[i].id == id){ - return i; + + onEditorKey : function(field, e){ + var k = e.getKey(), + newCell, + g = this.grid, + last = g.lastEdit, + ed = g.activeEditor, + shift = e.shiftKey, + ae, last, r, c; + + if(k == e.TAB){ + e.stopEvent(); + ed.completeEdit(); + if(shift){ + newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this); + }else{ + newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this); + } + }else if(k == e.ENTER){ + if(this.moveEditorOnEnter !== false){ + if(shift){ + newCell = g.walkCells(last.row - 1, last.col, -1, this.acceptsNav, this); + }else{ + newCell = g.walkCells(last.row + 1, last.col, 1, this.acceptsNav, this); + } } } - return -1; - }, + if(newCell){ + r = newCell[0]; + c = newCell[1]; - /** - * Moves a column from one position to another. - * @param {Number} oldIndex The index of the column to move. - * @param {Number} newIndex The position at which to reinsert the coolumn. - */ - moveColumn : function(oldIndex, newIndex){ - var c = this.config[oldIndex]; - this.config.splice(oldIndex, 1); - this.config.splice(newIndex, 0, c); - this.dataMap = null; - this.fireEvent("columnmoved", this, oldIndex, newIndex); - }, + this.onEditorSelect(r, last.row); - /** - * Returns the number of columns. - * @param {Boolean} visibleOnly Optional. Pass as true to only include visible columns. - * @return {Number} - */ - getColumnCount : function(visibleOnly){ - if(visibleOnly === true){ - var c = 0; - for(var i = 0, len = this.config.length; i < len; i++){ - if(!this.isHidden(i)){ - c++; + if(g.isEditor && g.editing){ + ae = g.activeEditor; + if(ae && ae.field.triggerBlur){ + + ae.field.triggerBlur(); } } - return c; + g.startEditing(r, c); } - return this.config.length; }, - - /** - * Returns the column configs that return true by the passed function that is called - * with (columnConfig, index) -

-// returns an array of column config objects for all hidden columns
-var columns = grid.getColumnModel().getColumnsBy(function(c){
-  return c.hidden;
-});
-
- * @param {Function} fn - * @param {Object} scope (optional) - * @return {Array} result - */ - getColumnsBy : function(fn, scope){ - var r = []; - for(var i = 0, len = this.config.length; i < len; i++){ - var c = this.config[i]; - if(fn.call(scope||this, c, i) === true){ - r[r.length] = c; - } + + onEditorSelect: function(row, lastRow){ + if(lastRow != row){ + this.selectRow(row); } - return r; }, + + destroy : function(){ + Ext.destroy(this.rowNav); + this.rowNav = null; + Ext.grid.RowSelectionModel.superclass.destroy.call(this); + } +}); - /** - * Returns true if the specified column is sortable. - * @param {Number} col The column index - * @return {Boolean} - */ - isSortable : function(col){ - return !!this.config[col].sortable; +Ext.grid.Column = Ext.extend(Ext.util.Observable, { + + + + + + + + + + + + + + + + + + + + + + + + + isColumn : true, + + constructor : function(config){ + Ext.apply(this, config); + + if(Ext.isString(this.renderer)){ + this.renderer = Ext.util.Format[this.renderer]; + }else if(Ext.isObject(this.renderer)){ + this.scope = this.renderer.scope; + this.renderer = this.renderer.fn; + } + if(!this.scope){ + this.scope = this; + } + + var ed = this.editor; + delete this.editor; + this.setEditor(ed); + this.addEvents( + + 'click', + + 'contextmenu', + + 'dblclick', + + 'mousedown' + ); + Ext.grid.Column.superclass.constructor.call(this); }, - /** - * Returns true if the specified column menu is disabled. - * @param {Number} col The column index - * @return {Boolean} - */ - isMenuDisabled : function(col){ - return !!this.config[col].menuDisabled; + + processEvent : function(name, e, grid, rowIndex, colIndex){ + return this.fireEvent(name, this, grid, rowIndex, e); }, - /** - * Returns the rendering (formatting) function defined for the column. - * @param {Number} col The column index. - * @return {Function} The function used to render the cell. See {@link #setRenderer}. - */ - getRenderer : function(col){ - if(!this.config[col].renderer){ - return Ext.grid.ColumnModel.defaultRenderer; + + destroy: function() { + if(this.setEditor){ + this.setEditor(null); } - return this.config[col].renderer; + this.purgeListeners(); }, - /** - * Sets the rendering (formatting) function for a column. See {@link Ext.util.Format} for some - * default formatting functions. - * @param {Number} col The column index - * @param {Function} fn The function to use to process the cell's raw data - * to return HTML markup for the grid view. The render function is called with - * the following parameters:
    - *
  • value : Object

    The data value for the cell.

  • - *
  • metadata : Object

    An object in which you may set the following attributes:

      - *
    • css : String

      A CSS class name to add to the cell's TD element.

    • - *
    • attr : String

      An HTML attribute definition string to apply to the data container element within the table cell - * (e.g. 'style="color:red;"').

  • - *
  • record : Ext.data.record

    The {@link Ext.data.Record} from which the data was extracted.

  • - *
  • rowIndex : Number

    Row index

  • - *
  • colIndex : Number

    Column index

  • - *
  • store : Ext.data.Store

    The {@link Ext.data.Store} object from which the Record was extracted.

- */ - setRenderer : function(col, fn){ - this.config[col].renderer = fn; + + renderer : function(value){ + return value; }, - /** - * Returns the width for the specified column. - * @param {Number} col The column index - * @return {Number} - */ - getColumnWidth : function(col){ - return this.config[col].width; + + getEditor: function(rowIndex){ + return this.editable !== false ? this.editor : null; }, - /** - * Sets the width for a column. - * @param {Number} col The column index - * @param {Number} width The new width - * @param {Boolean} suppressEvent True to suppress firing the {@link #widthchange} - * event. Defaults to false. - */ - setColumnWidth : function(col, width, suppressEvent){ - this.config[col].width = width; - this.totalWidth = null; - if(!suppressEvent){ - this.fireEvent("widthchange", this, col, width); + + setEditor : function(editor){ + var ed = this.editor; + if(ed){ + if(ed.gridEditor){ + ed.gridEditor.destroy(); + delete ed.gridEditor; + }else{ + ed.destroy(); + } + } + this.editor = null; + if(editor){ + + if(!editor.isXType){ + editor = Ext.create(editor, 'textfield'); + } + this.editor = editor; } }, - /** - * Returns the total width of all columns. - * @param {Boolean} includeHidden True to include hidden column widths - * @return {Number} - */ - getTotalWidth : function(includeHidden){ - if(!this.totalWidth){ - this.totalWidth = 0; - for(var i = 0, len = this.config.length; i < len; i++){ - if(includeHidden || !this.isHidden(i)){ - this.totalWidth += this.getColumnWidth(i); + + getCellEditor: function(rowIndex){ + var ed = this.getEditor(rowIndex); + if(ed){ + if(!ed.startEdit){ + if(!ed.gridEditor){ + ed.gridEditor = new Ext.grid.GridEditor(ed); } + ed = ed.gridEditor; } } - return this.totalWidth; - }, + return ed; + } +}); - /** - * Returns the header for the specified column. - * @param {Number} col The column index - * @return {String} - */ - getColumnHeader : function(col){ - return this.config[col].header; - }, - /** - * Sets the header for a column. - * @param {Number} col The column index - * @param {String} header The new header - */ - setColumnHeader : function(col, header){ - this.config[col].header = header; - this.fireEvent("headerchange", this, col, header); - }, +Ext.grid.BooleanColumn = Ext.extend(Ext.grid.Column, { + + trueText: 'true', + + falseText: 'false', + + undefinedText: ' ', - /** - * Returns the tooltip for the specified column. - * @param {Number} col The column index - * @return {String} - */ - getColumnTooltip : function(col){ - return this.config[col].tooltip; - }, - /** - * Sets the tooltip for a column. - * @param {Number} col The column index - * @param {String} tooltip The new tooltip - */ - setColumnTooltip : function(col, tooltip){ - this.config[col].tooltip = tooltip; - }, + constructor: function(cfg){ + Ext.grid.BooleanColumn.superclass.constructor.call(this, cfg); + var t = this.trueText, f = this.falseText, u = this.undefinedText; + this.renderer = function(v){ + if(v === undefined){ + return u; + } + if(!v || v === 'false'){ + return f; + } + return t; + }; + } +}); - /** - * Returns the dataIndex for the specified column. -

-// Get field name for the column
-var fieldName = grid.getColumnModel().getDataIndex(columnIndex);
-
- * @param {Number} col The column index - * @return {String} The column's dataIndex - */ - getDataIndex : function(col){ - return this.config[col].dataIndex; + +Ext.grid.NumberColumn = Ext.extend(Ext.grid.Column, { + + format : '0,000.00', + constructor: function(cfg){ + Ext.grid.NumberColumn.superclass.constructor.call(this, cfg); + this.renderer = Ext.util.Format.numberRenderer(this.format); + } +}); + + +Ext.grid.DateColumn = Ext.extend(Ext.grid.Column, { + + format : 'm/d/Y', + constructor: function(cfg){ + Ext.grid.DateColumn.superclass.constructor.call(this, cfg); + this.renderer = Ext.util.Format.dateRenderer(this.format); + } +}); + + +Ext.grid.TemplateColumn = Ext.extend(Ext.grid.Column, { + + constructor: function(cfg){ + Ext.grid.TemplateColumn.superclass.constructor.call(this, cfg); + var tpl = (!Ext.isPrimitive(this.tpl) && this.tpl.compile) ? this.tpl : new Ext.XTemplate(this.tpl); + this.renderer = function(value, p, r){ + return tpl.apply(r.data); + }; + this.tpl = tpl; + } +}); + + +Ext.grid.ActionColumn = Ext.extend(Ext.grid.Column, { + + + + + + + + + header: ' ', + + actionIdRe: /x-action-col-(\d+)/, + + + altText: '', + + constructor: function(cfg) { + var me = this, + items = cfg.items || (me.items = [me]), + l = items.length, + i, + item; + + Ext.grid.ActionColumn.superclass.constructor.call(me, cfg); + + + + me.renderer = function(v, meta) { + + v = Ext.isFunction(cfg.renderer) ? cfg.renderer.apply(this, arguments)||'' : ''; + + meta.css += ' x-action-col-cell'; + for (i = 0; i < l; i++) { + item = items[i]; + v += '' + me.altText + ''; + } + return v; + }; }, - /** - * Sets the dataIndex for a column. - * @param {Number} col The column index - * @param {String} dataIndex The new dataIndex - */ - setDataIndex : function(col, dataIndex){ - this.config[col].dataIndex = dataIndex; + destroy: function() { + delete this.items; + delete this.renderer; + return Ext.grid.ActionColumn.superclass.destroy.apply(this, arguments); }, - /** - * Finds the index of the first matching column for the given dataIndex. - * @param {String} col The dataIndex to find - * @return {Number} The column index, or -1 if no match was found - */ - findColumnIndex : function(dataIndex){ - var c = this.config; - for(var i = 0, len = c.length; i < len; i++){ - if(c[i].dataIndex == dataIndex){ - return i; + + processEvent : function(name, e, grid, rowIndex, colIndex){ + var m = e.getTarget().className.match(this.actionIdRe), + item, fn; + if (m && (item = this.items[parseInt(m[1], 10)])) { + if (name == 'click') { + (fn = item.handler || this.handler) && fn.call(item.scope||this.scope||this, grid, rowIndex, colIndex, item, e); + } else if ((name == 'mousedown') && (item.stopSelection !== false)) { + return false; } } - return -1; + return Ext.grid.ActionColumn.superclass.processEvent.apply(this, arguments); + } +}); + + +Ext.grid.Column.types = { + gridcolumn : Ext.grid.Column, + booleancolumn: Ext.grid.BooleanColumn, + numbercolumn: Ext.grid.NumberColumn, + datecolumn: Ext.grid.DateColumn, + templatecolumn: Ext.grid.TemplateColumn, + actioncolumn: Ext.grid.ActionColumn +}; +Ext.grid.RowNumberer = Ext.extend(Object, { + + header: "", + + width: 23, + + sortable: false, + + constructor : function(config){ + Ext.apply(this, config); + if(this.rowspan){ + this.renderer = this.renderer.createDelegate(this); + } }, - /** - * Returns true if the cell is editable. -

-var store = new Ext.data.Store({...});
-var colModel = new Ext.grid.ColumnModel({
-  columns: [...],
-  isCellEditable: function(col, row) {
-    var record = store.getAt(row);
-    if (record.get('readonly')) { // replace with your condition
-      return false;
+    
+    fixed:true,
+    hideable: false,
+    menuDisabled:true,
+    dataIndex: '',
+    id: 'numberer',
+    rowspan: undefined,
+
+    
+    renderer : function(v, p, record, rowIndex){
+        if(this.rowspan){
+            p.cellAttr = 'rowspan="'+this.rowspan+'"';
+        }
+        return rowIndex+1;
     }
-    return Ext.grid.ColumnModel.prototype.isCellEditable.call(this, col, row);
-  }
 });
-var grid = new Ext.grid.GridPanel({
-  store: store,
-  colModel: colModel,
-  ...
-});
-
- * @param {Number} colIndex The column index - * @param {Number} rowIndex The row index - * @return {Boolean} - */ - isCellEditable : function(colIndex, rowIndex){ - return (this.config[colIndex].editable || (typeof this.config[colIndex].editable == "undefined" && this.config[colIndex].editor)) ? true : false; - }, +Ext.grid.CheckboxSelectionModel = Ext.extend(Ext.grid.RowSelectionModel, { - /** - * Returns the editor defined for the cell/column. - * @param {Number} colIndex The column index - * @param {Number} rowIndex The row index - * @return {Ext.Editor} The {@link Ext.Editor Editor} that was created to wrap - * the {@link Ext.form.Field Field} used to edit the cell. - */ - getCellEditor : function(colIndex, rowIndex){ - return this.config[colIndex].getCellEditor(rowIndex); - }, + + + header : '
 
', + + width : 20, + + sortable : false, - /** - * Sets if a column is editable. - * @param {Number} col The column index - * @param {Boolean} editable True if the column is editable - */ - setEditable : function(col, editable){ - this.config[col].editable = editable; - }, + + menuDisabled : true, + fixed : true, + hideable: false, + dataIndex : '', + id : 'checker', + isColumn: true, - /** - * Returns true if the column is {@link Ext.grid.Column#hidden hidden}, - * false otherwise. - * @param {Number} colIndex The column index - * @return {Boolean} - */ - isHidden : function(colIndex){ - return !!this.config[colIndex].hidden; // ensure returns boolean + constructor : function(){ + Ext.grid.CheckboxSelectionModel.superclass.constructor.apply(this, arguments); + if(this.checkOnly){ + this.handleMouseDown = Ext.emptyFn; + } }, - /** - * Returns true if the column is {@link Ext.grid.Column#fixed fixed}, - * false otherwise. - * @param {Number} colIndex The column index - * @return {Boolean} - */ - isFixed : function(colIndex){ - return !!this.config[colIndex].fixed; + + initEvents : function(){ + Ext.grid.CheckboxSelectionModel.superclass.initEvents.call(this); + this.grid.on('render', function(){ + Ext.fly(this.grid.getView().innerHd).on('mousedown', this.onHdMouseDown, this); + }, this); }, - /** - * Returns true if the column can be resized - * @return {Boolean} - */ - isResizable : function(colIndex){ - return colIndex >= 0 && this.config[colIndex].resizable !== false && this.config[colIndex].fixed !== true; + + processEvent : function(name, e, grid, rowIndex, colIndex){ + if (name == 'mousedown') { + this.onMouseDown(e, e.getTarget()); + return false; + } else { + return Ext.grid.Column.prototype.processEvent.apply(this, arguments); + } }, - /** - * Sets if a column is hidden. -

-myGrid.getColumnModel().setHidden(0, true); // hide column 0 (0 = the first column).
-
- * @param {Number} colIndex The column index - * @param {Boolean} hidden True if the column is hidden - */ - setHidden : function(colIndex, hidden){ - var c = this.config[colIndex]; - if(c.hidden !== hidden){ - c.hidden = hidden; - this.totalWidth = null; - this.fireEvent("hiddenchange", this, colIndex, hidden); + + + onMouseDown : function(e, t){ + if(e.button === 0 && t.className == 'x-grid3-row-checker'){ + e.stopEvent(); + var row = e.getTarget('.x-grid3-row'); + if(row){ + var index = row.rowIndex; + if(this.isSelected(index)){ + this.deselectRow(index); + }else{ + this.selectRow(index, true); + this.grid.getView().focusRow(index); + } + } } }, - /** - * Sets the editor for a column and destroys the prior editor. - * @param {Number} col The column index - * @param {Object} editor The editor object - */ - setEditor : function(col, editor){ - Ext.destroy(this.config[col].editor); - this.config[col].editor = editor; + + onHdMouseDown : function(e, t) { + if(t.className == 'x-grid3-hd-checker'){ + e.stopEvent(); + var hd = Ext.fly(t.parentNode); + var isChecked = hd.hasClass('x-grid3-hd-checker-on'); + if(isChecked){ + hd.removeClass('x-grid3-hd-checker-on'); + this.clearSelections(); + }else{ + hd.addClass('x-grid3-hd-checker-on'); + this.selectAll(); + } + } }, - /** - * Destroys this column model by purging any event listeners, and removing any editors. - */ - destroy : function(){ - for(var i = 0, c = this.config, len = c.length; i < len; i++){ - Ext.destroy(c[i].editor); + + renderer : function(v, p, record){ + return '
 
'; + }, + + onEditorSelect: function(row, lastRow){ + if(lastRow != row && !this.checkOnly){ + this.selectRow(row); } - this.purgeListeners(); } }); +Ext.grid.CellSelectionModel = Ext.extend(Ext.grid.AbstractSelectionModel, { + + constructor : function(config){ + Ext.apply(this, config); -// private -Ext.grid.ColumnModel.defaultRenderer = function(value){ - if(typeof value == "string" && value.length < 1){ - return " "; - } - return value; -};/** - * @class Ext.grid.AbstractSelectionModel - * @extends Ext.util.Observable - * Abstract base class for grid SelectionModels. It provides the interface that should be - * implemented by descendant classes. This class should not be directly instantiated. - * @constructor - */ -Ext.grid.AbstractSelectionModel = function(){ - this.locked = false; - Ext.grid.AbstractSelectionModel.superclass.constructor.call(this); -}; - -Ext.extend(Ext.grid.AbstractSelectionModel, Ext.util.Observable, { - /** - * The GridPanel for which this SelectionModel is handling selection. Read-only. - * @type Object - * @property grid - */ - - /** @ignore Called by the grid automatically. Do not call directly. */ - init : function(grid){ - this.grid = grid; - this.initEvents(); - }, - - /** - * Locks the selections. - */ - lock : function(){ - this.locked = true; - }, - - /** - * Unlocks the selections. - */ - unlock : function(){ - this.locked = false; - }, - - /** - * Returns true if the selections are locked. - * @return {Boolean} - */ - isLocked : function(){ - return this.locked; - }, - - destroy: function(){ - this.purgeListeners(); - } -});/** - * @class Ext.grid.RowSelectionModel - * @extends Ext.grid.AbstractSelectionModel - * The default SelectionModel used by {@link Ext.grid.GridPanel}. - * It supports multiple selections and keyboard selection/navigation. The objects stored - * as selections and returned by {@link #getSelected}, and {@link #getSelections} are - * the {@link Ext.data.Record Record}s which provide the data for the selected rows. - * @constructor - * @param {Object} config - */ -Ext.grid.RowSelectionModel = function(config){ - Ext.apply(this, config); - this.selections = new Ext.util.MixedCollection(false, function(o){ - return o.id; - }); + this.selection = null; + + this.addEvents( + + "beforecellselect", + + "cellselect", + + "selectionchange" + ); + + Ext.grid.CellSelectionModel.superclass.constructor.call(this); + }, - this.last = false; - this.lastActive = false; + + initEvents : function(){ + this.grid.on('cellmousedown', this.handleMouseDown, this); + this.grid.on(Ext.EventManager.getKeyEvent(), this.handleKeyDown, this); + this.grid.getView().on({ + scope: this, + refresh: this.onViewChange, + rowupdated: this.onRowUpdated, + beforerowremoved: this.clearSelections, + beforerowsinserted: this.clearSelections + }); + if(this.grid.isEditor){ + this.grid.on('beforeedit', this.beforeEdit, this); + } + }, - this.addEvents( - /** - * @event selectionchange - * Fires when the selection changes - * @param {SelectionModel} this - */ - 'selectionchange', - /** - * @event beforerowselect - * Fires before a row is selected, return false to cancel the selection. - * @param {SelectionModel} this - * @param {Number} rowIndex The index to be selected - * @param {Boolean} keepExisting False if other selections will be cleared - * @param {Record} record The record to be selected - */ - 'beforerowselect', - /** - * @event rowselect - * Fires when a row is selected. - * @param {SelectionModel} this - * @param {Number} rowIndex The selected index - * @param {Ext.data.Record} r The selected record - */ - 'rowselect', - /** - * @event rowdeselect - * Fires when a row is deselected. To prevent deselection - * {@link Ext.grid.AbstractSelectionModel#lock lock the selections}. - * @param {SelectionModel} this - * @param {Number} rowIndex - * @param {Record} record - */ - 'rowdeselect' - ); + + beforeEdit : function(e){ + this.select(e.row, e.column, false, true, e.record); + }, - Ext.grid.RowSelectionModel.superclass.constructor.call(this); -}; + + onRowUpdated : function(v, index, r){ + if(this.selection && this.selection.record == r){ + v.onCellSelect(index, this.selection.cell[1]); + } + }, -Ext.extend(Ext.grid.RowSelectionModel, Ext.grid.AbstractSelectionModel, { - /** - * @cfg {Boolean} singleSelect - * true to allow selection of only one row at a time (defaults to false - * allowing multiple selections) - */ - singleSelect : false, + + onViewChange : function(){ + this.clearSelections(true); + }, - /** - * @cfg {Boolean} moveEditorOnEnter - * false to turn off moving the editor to the next row down when the enter key is pressed - * or the next row up when shift + enter keys are pressed. - */ - // private - initEvents : function(){ + + getSelectedCell : function(){ + return this.selection ? this.selection.cell : null; + }, - if(!this.grid.enableDragDrop && !this.grid.enableDrag){ - this.grid.on('rowmousedown', this.handleMouseDown, this); + + clearSelections : function(preventNotify){ + var s = this.selection; + if(s){ + if(preventNotify !== true){ + this.grid.view.onCellDeselect(s.cell[0], s.cell[1]); + } + this.selection = null; + this.fireEvent("selectionchange", this, null); } + }, - this.rowNav = new Ext.KeyNav(this.grid.getGridEl(), { - 'up' : function(e){ - if(!e.shiftKey || this.singleSelect){ - this.selectPrevious(false); - }else if(this.last !== false && this.lastActive !== false){ - var last = this.last; - this.selectRange(this.last, this.lastActive-1); - this.grid.getView().focusRow(this.lastActive); - if(last !== false){ - this.last = last; - } - }else{ - this.selectFirstRow(); - } - }, - 'down' : function(e){ - if(!e.shiftKey || this.singleSelect){ - this.selectNext(false); - }else if(this.last !== false && this.lastActive !== false){ - var last = this.last; - this.selectRange(this.last, this.lastActive+1); - this.grid.getView().focusRow(this.lastActive); - if(last !== false){ - this.last = last; - } - }else{ - this.selectFirstRow(); - } - }, - scope: this - }); + + hasSelection : function(){ + return this.selection ? true : false; + }, - this.grid.getView().on({ - scope: this, - refresh: this.onRefresh, - rowupdated: this.onRowUpdated, - rowremoved: this.onRemove - }); + + handleMouseDown : function(g, row, cell, e){ + if(e.button !== 0 || this.isLocked()){ + return; + } + this.select(row, cell); }, - // private - onRefresh : function(){ - var ds = this.grid.store, index; - var s = this.getSelections(); - this.clearSelections(true); - for(var i = 0, len = s.length; i < len; i++){ - var r = s[i]; - if((index = ds.indexOfId(r.id)) != -1){ - this.selectRow(index, true); + + select : function(rowIndex, colIndex, preventViewNotify, preventFocus, r){ + if(this.fireEvent("beforecellselect", this, rowIndex, colIndex) !== false){ + this.clearSelections(); + r = r || this.grid.store.getAt(rowIndex); + this.selection = { + record : r, + cell : [rowIndex, colIndex] + }; + if(!preventViewNotify){ + var v = this.grid.getView(); + v.onCellSelect(rowIndex, colIndex); + if(preventFocus !== true){ + v.focusCell(rowIndex, colIndex); + } } - } - if(s.length != this.selections.getCount()){ - this.fireEvent('selectionchange', this); + this.fireEvent("cellselect", this, rowIndex, colIndex); + this.fireEvent("selectionchange", this, this.selection); } }, - // private - onRemove : function(v, index, r){ - if(this.selections.remove(r) !== false){ - this.fireEvent('selectionchange', this); + + isSelectable : function(rowIndex, colIndex, cm){ + return !cm.isHidden(colIndex); + }, + + + onEditorKey: function(field, e){ + if(e.getKey() == e.TAB){ + this.handleKeyDown(e); } }, - // private - onRowUpdated : function(v, index, r){ - if(this.isSelected(r)){ - v.onRowSelect(index); + + handleKeyDown : function(e){ + if(!e.isNavKeyPress()){ + return; + } + + var k = e.getKey(), + g = this.grid, + s = this.selection, + sm = this, + walk = function(row, col, step){ + return g.walkCells( + row, + col, + step, + g.isEditor && g.editing ? sm.acceptsNav : sm.isSelectable, + sm + ); + }, + cell, newCell, r, c, ae; + + switch(k){ + case e.ESC: + case e.PAGE_UP: + case e.PAGE_DOWN: + + break; + default: + + e.stopEvent(); + break; + } + + if(!s){ + cell = walk(0, 0, 1); + if(cell){ + this.select(cell[0], cell[1]); + } + return; + } + + cell = s.cell; + r = cell[0]; + c = cell[1]; + + switch(k){ + case e.TAB: + if(e.shiftKey){ + newCell = walk(r, c - 1, -1); + }else{ + newCell = walk(r, c + 1, 1); + } + break; + case e.DOWN: + newCell = walk(r + 1, c, 1); + break; + case e.UP: + newCell = walk(r - 1, c, -1); + break; + case e.RIGHT: + newCell = walk(r, c + 1, 1); + break; + case e.LEFT: + newCell = walk(r, c - 1, -1); + break; + case e.ENTER: + if (g.isEditor && !g.editing) { + g.startEditing(r, c); + return; + } + break; } - }, - /** - * Select records. - * @param {Array} records The records to select - * @param {Boolean} keepExisting (optional) true to keep existing selections - */ - selectRecords : function(records, keepExisting){ - if(!keepExisting){ - this.clearSelections(); - } - var ds = this.grid.store; - for(var i = 0, len = records.length; i < len; i++){ - this.selectRow(ds.indexOf(records[i]), true); + if(newCell){ + + r = newCell[0]; + c = newCell[1]; + + this.select(r, c); + + if(g.isEditor && g.editing){ + ae = g.activeEditor; + if(ae && ae.field.triggerBlur){ + + ae.field.triggerBlur(); + } + g.startEditing(r, c); + } } }, - /** - * Gets the number of selected rows. - * @return {Number} - */ - getCount : function(){ - return this.selections.length; - }, + acceptsNav : function(row, col, cm){ + return !cm.isHidden(col) && cm.isCellEditable(col, row); + } +}); +Ext.grid.EditorGridPanel = Ext.extend(Ext.grid.GridPanel, { + + clicksToEdit: 2, - /** - * Selects the first row in the grid. - */ - selectFirstRow : function(){ - this.selectRow(0); - }, + + forceValidation: false, - /** - * Select the last row. - * @param {Boolean} keepExisting (optional) true to keep existing selections - */ - selectLastRow : function(keepExisting){ - this.selectRow(this.grid.store.getCount() - 1, keepExisting); - }, + + isEditor : true, + + detectEdit: false, - /** - * Selects the row immediately following the last selected row. - * @param {Boolean} keepExisting (optional) true to keep existing selections - * @return {Boolean} true if there is a next row, else false - */ - selectNext : function(keepExisting){ - if(this.hasNext()){ - this.selectRow(this.last+1, keepExisting); - this.grid.getView().focusRow(this.last); - return true; - } - return false; - }, + + autoEncode : false, - /** - * Selects the row that precedes the last selected row. - * @param {Boolean} keepExisting (optional) true to keep existing selections - * @return {Boolean} true if there is a previous row, else false - */ - selectPrevious : function(keepExisting){ - if(this.hasPrevious()){ - this.selectRow(this.last-1, keepExisting); - this.grid.getView().focusRow(this.last); - return true; - } - return false; - }, + + + trackMouseOver: false, - /** - * Returns true if there is a next record to select - * @return {Boolean} - */ - hasNext : function(){ - return this.last !== false && (this.last+1) < this.grid.store.getCount(); - }, + + initComponent : function(){ + Ext.grid.EditorGridPanel.superclass.initComponent.call(this); - /** - * Returns true if there is a previous record to select - * @return {Boolean} - */ - hasPrevious : function(){ - return !!this.last; - }, + if(!this.selModel){ + + this.selModel = new Ext.grid.CellSelectionModel(); + } + this.activeEditor = null; - /** - * Returns the selected records - * @return {Array} Array of selected records - */ - getSelections : function(){ - return [].concat(this.selections.items); + this.addEvents( + + "beforeedit", + + "afteredit", + + "validateedit" + ); }, - /** - * Returns the first selected record. - * @return {Record} - */ - getSelected : function(){ - return this.selections.itemAt(0); - }, + + initEvents : function(){ + Ext.grid.EditorGridPanel.superclass.initEvents.call(this); - /** - * Calls the passed function with each selection. If the function returns - * false, iteration is stopped and this function returns - * false. Otherwise it returns true. - * @param {Function} fn - * @param {Object} scope (optional) - * @return {Boolean} true if all selections were iterated - */ - each : function(fn, scope){ - var s = this.getSelections(); - for(var i = 0, len = s.length; i < len; i++){ - if(fn.call(scope || this, s[i], i) === false){ - return false; + this.getGridEl().on('mousewheel', this.stopEditing.createDelegate(this, [true]), this); + this.on('columnresize', this.stopEditing, this, [true]); + + if(this.clicksToEdit == 1){ + this.on("cellclick", this.onCellDblClick, this); + }else { + var view = this.getView(); + if(this.clicksToEdit == 'auto' && view.mainBody){ + view.mainBody.on('mousedown', this.onAutoEditClick, this); } + this.on('celldblclick', this.onCellDblClick, this); } - return true; }, - /** - * Clears all selections if the selection model - * {@link Ext.grid.AbstractSelectionModel#isLocked is not locked}. - * @param {Boolean} fast (optional) true to bypass the - * conditional checks and events described in {@link #deselectRow}. - */ - clearSelections : function(fast){ - if(this.isLocked()){ - return; - } - if(fast !== true){ - var ds = this.grid.store; - var s = this.selections; - s.each(function(r){ - this.deselectRow(ds.indexOfId(r.id)); - }, this); - s.clear(); - }else{ - this.selections.clear(); + onResize : function(){ + Ext.grid.EditorGridPanel.superclass.onResize.apply(this, arguments); + var ae = this.activeEditor; + if(this.editing && ae){ + ae.realign(true); } - this.last = false; }, + + onCellDblClick : function(g, row, col){ + this.startEditing(row, col); + }, - /** - * Selects all rows if the selection model - * {@link Ext.grid.AbstractSelectionModel#isLocked is not locked}. - */ - selectAll : function(){ - if(this.isLocked()){ + + onAutoEditClick : function(e, t){ + if(e.button !== 0){ return; } - this.selections.clear(); - for(var i = 0, len = this.grid.store.getCount(); i < len; i++){ - this.selectRow(i, true); + var row = this.view.findRowIndex(t), + col = this.view.findCellIndex(t); + if(row !== false && col !== false){ + this.stopEditing(); + if(this.selModel.getSelectedCell){ + var sc = this.selModel.getSelectedCell(); + if(sc && sc[0] === row && sc[1] === col){ + this.startEditing(row, col); + } + }else{ + if(this.selModel.isSelected(row)){ + this.startEditing(row, col); + } + } } }, - /** - * Returns true if there is a selection. - * @return {Boolean} - */ - hasSelection : function(){ - return this.selections.length > 0; - }, - - /** - * Returns true if the specified row is selected. - * @param {Number/Record} index The record or index of the record to check - * @return {Boolean} - */ - isSelected : function(index){ - var r = Ext.isNumber(index) ? this.grid.store.getAt(index) : index; - return (r && this.selections.key(r.id) ? true : false); - }, + + onEditComplete : function(ed, value, startValue){ + this.editing = false; + this.lastActiveEditor = this.activeEditor; + this.activeEditor = null; - /** - * Returns true if the specified record id is selected. - * @param {String} id The id of record to check - * @return {Boolean} - */ - isIdSelected : function(id){ - return (this.selections.key(id) ? true : false); + var r = ed.record, + field = this.colModel.getDataIndex(ed.col); + value = this.postEditValue(value, startValue, r, field); + if(this.forceValidation === true || String(value) !== String(startValue)){ + var e = { + grid: this, + record: r, + field: field, + originalValue: startValue, + value: value, + row: ed.row, + column: ed.col, + cancel:false + }; + if(this.fireEvent("validateedit", e) !== false && !e.cancel && String(value) !== String(startValue)){ + r.set(field, e.value); + delete e.cancel; + this.fireEvent("afteredit", e); + } + } + this.view.focusCell(ed.row, ed.col); }, - // private - handleMouseDown : function(g, rowIndex, e){ - if(e.button !== 0 || this.isLocked()){ - return; - } - var view = this.grid.getView(); - if(e.shiftKey && !this.singleSelect && this.last !== false){ - var last = this.last; - this.selectRange(last, rowIndex, e.ctrlKey); - this.last = last; // reset the last - view.focusRow(rowIndex); - }else{ - var isSelected = this.isSelected(rowIndex); - if(e.ctrlKey && isSelected){ - this.deselectRow(rowIndex); - }else if(!isSelected || this.getCount() > 1){ - this.selectRow(rowIndex, e.ctrlKey || e.shiftKey); - view.focusRow(rowIndex); + + startEditing : function(row, col){ + this.stopEditing(); + if(this.colModel.isCellEditable(col, row)){ + this.view.ensureVisible(row, col, true); + var r = this.store.getAt(row), + field = this.colModel.getDataIndex(col), + e = { + grid: this, + record: r, + field: field, + value: r.data[field], + row: row, + column: col, + cancel:false + }; + if(this.fireEvent("beforeedit", e) !== false && !e.cancel){ + this.editing = true; + var ed = this.colModel.getCellEditor(col, row); + if(!ed){ + return; + } + if(!ed.rendered){ + ed.parentEl = this.view.getEditorParent(ed); + ed.on({ + scope: this, + render: { + fn: function(c){ + c.field.focus(false, true); + }, + single: true, + scope: this + }, + specialkey: function(field, e){ + this.getSelectionModel().onEditorKey(field, e); + }, + complete: this.onEditComplete, + canceledit: this.stopEditing.createDelegate(this, [true]) + }); + } + Ext.apply(ed, { + row : row, + col : col, + record : r + }); + this.lastEdit = { + row: row, + col: col + }; + this.activeEditor = ed; + + + ed.selectSameEditor = (this.activeEditor == this.lastActiveEditor); + var v = this.preEditValue(r, field); + ed.startEdit(this.view.getCell(row, col).firstChild, Ext.isDefined(v) ? v : ''); + + + (function(){ + delete ed.selectSameEditor; + }).defer(50); } } }, - /** - * Selects multiple rows. - * @param {Array} rows Array of the indexes of the row to select - * @param {Boolean} keepExisting (optional) true to keep - * existing selections (defaults to false) - */ - selectRows : function(rows, keepExisting){ - if(!keepExisting){ - this.clearSelections(); - } - for(var i = 0, len = rows.length; i < len; i++){ - this.selectRow(rows[i], true); - } + + preEditValue : function(r, field){ + var value = r.data[field]; + return this.autoEncode && Ext.isString(value) ? Ext.util.Format.htmlDecode(value) : value; }, - /** - * Selects a range of rows if the selection model - * {@link Ext.grid.AbstractSelectionModel#isLocked is not locked}. - * All rows in between startRow and endRow are also selected. - * @param {Number} startRow The index of the first row in the range - * @param {Number} endRow The index of the last row in the range - * @param {Boolean} keepExisting (optional) True to retain existing selections - */ - selectRange : function(startRow, endRow, keepExisting){ - var i; - if(this.isLocked()){ - return; - } - if(!keepExisting){ - this.clearSelections(); - } - if(startRow <= endRow){ - for(i = startRow; i <= endRow; i++){ - this.selectRow(i, true); - } - }else{ - for(i = startRow; i >= endRow; i--){ - this.selectRow(i, true); - } - } + + postEditValue : function(value, originalValue, r, field){ + return this.autoEncode && Ext.isString(value) ? Ext.util.Format.htmlEncode(value) : value; }, - /** - * Deselects a range of rows if the selection model - * {@link Ext.grid.AbstractSelectionModel#isLocked is not locked}. - * All rows in between startRow and endRow are also deselected. - * @param {Number} startRow The index of the first row in the range - * @param {Number} endRow The index of the last row in the range - */ - deselectRange : function(startRow, endRow, preventViewNotify){ - if(this.isLocked()){ - return; - } - for(var i = startRow; i <= endRow; i++){ - this.deselectRow(i, preventViewNotify); + + stopEditing : function(cancel){ + if(this.editing){ + + var ae = this.lastActiveEditor = this.activeEditor; + if(ae){ + ae[cancel === true ? 'cancelEdit' : 'completeEdit'](); + this.view.focusCell(ae.row, ae.col); + } + this.activeEditor = null; } - }, + this.editing = false; + } +}); +Ext.reg('editorgrid', Ext.grid.EditorGridPanel); - /** - * Selects a row. Before selecting a row, checks if the selection model - * {@link Ext.grid.AbstractSelectionModel#isLocked is locked} and fires the - * {@link #beforerowselect} event. If these checks are satisfied the row - * will be selected and followed up by firing the {@link #rowselect} and - * {@link #selectionchange} events. - * @param {Number} row The index of the row to select - * @param {Boolean} keepExisting (optional) true to keep existing selections - * @param {Boolean} preventViewNotify (optional) Specify true to - * prevent notifying the view (disables updating the selected appearance) - */ - selectRow : function(index, keepExisting, preventViewNotify){ - if(this.isLocked() || (index < 0 || index >= this.grid.store.getCount()) || (keepExisting && this.isSelected(index))){ - return; +Ext.grid.GridEditor = function(field, config){ + Ext.grid.GridEditor.superclass.constructor.call(this, field, config); + field.monitorTab = false; +}; + +Ext.extend(Ext.grid.GridEditor, Ext.Editor, { + alignment: "tl-tl", + autoSize: "width", + hideEl : false, + cls: "x-small-editor x-grid-editor", + shim:false, + shadow:false +}); +Ext.grid.PropertyRecord = Ext.data.Record.create([ + {name:'name',type:'string'}, 'value' +]); + + +Ext.grid.PropertyStore = Ext.extend(Ext.util.Observable, { + + constructor : function(grid, source){ + this.grid = grid; + this.store = new Ext.data.Store({ + recordType : Ext.grid.PropertyRecord + }); + this.store.on('update', this.onUpdate, this); + if(source){ + this.setSource(source); } - var r = this.grid.store.getAt(index); - if(r && this.fireEvent('beforerowselect', this, index, keepExisting, r) !== false){ - if(!keepExisting || this.singleSelect){ - this.clearSelections(); - } - this.selections.add(r); - this.last = this.lastActive = index; - if(!preventViewNotify){ - this.grid.getView().onRowSelect(index); + Ext.grid.PropertyStore.superclass.constructor.call(this); + }, + + + setSource : function(o){ + this.source = o; + this.store.removeAll(); + var data = []; + for(var k in o){ + if(this.isEditableValue(o[k])){ + data.push(new Ext.grid.PropertyRecord({name: k, value: o[k]}, k)); } - this.fireEvent('rowselect', this, index, r); - this.fireEvent('selectionchange', this); } + this.store.loadRecords({records: data}, {}, true); }, - /** - * Deselects a row. Before deselecting a row, checks if the selection model - * {@link Ext.grid.AbstractSelectionModel#isLocked is locked}. - * If this check is satisfied the row will be deselected and followed up by - * firing the {@link #rowdeselect} and {@link #selectionchange} events. - * @param {Number} row The index of the row to deselect - * @param {Boolean} preventViewNotify (optional) Specify true to - * prevent notifying the view (disables updating the selected appearance) - */ - deselectRow : function(index, preventViewNotify){ - if(this.isLocked()){ - return; - } - if(this.last == index){ - this.last = false; - } - if(this.lastActive == index){ - this.lastActive = false; - } - var r = this.grid.store.getAt(index); - if(r){ - this.selections.remove(r); - if(!preventViewNotify){ - this.grid.getView().onRowDeselect(index); + + onUpdate : function(ds, record, type){ + if(type == Ext.data.Record.EDIT){ + var v = record.data.value; + var oldValue = record.modified.value; + if(this.grid.fireEvent('beforepropertychange', this.source, record.id, v, oldValue) !== false){ + this.source[record.id] = v; + record.commit(); + this.grid.fireEvent('propertychange', this.source, record.id, v, oldValue); + }else{ + record.reject(); } - this.fireEvent('rowdeselect', this, index, r); - this.fireEvent('selectionchange', this); } }, - // private - restoreLast : function(){ - if(this._last){ - this.last = this._last; - } + + getProperty : function(row){ + return this.store.getAt(row); }, - // private - acceptsNav : function(row, col, cm){ - return !cm.isHidden(col) && cm.isCellEditable(col, row); + + isEditableValue: function(val){ + return Ext.isPrimitive(val) || Ext.isDate(val); }, - // private - onEditorKey : function(field, e){ - var k = e.getKey(), - newCell, - g = this.grid, - last = g.lastEdit, - ed = g.activeEditor, - ae, last, r, c; - var shift = e.shiftKey; - if(k == e.TAB){ - e.stopEvent(); - ed.completeEdit(); - if(shift){ - newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this); - }else{ - newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this); - } - }else if(k == e.ENTER){ - if(this.moveEditorOnEnter !== false){ - if(shift){ - newCell = g.walkCells(last.row - 1, last.col, -1, this.acceptsNav, this); - }else{ - newCell = g.walkCells(last.row + 1, last.col, 1, this.acceptsNav, this); - } - } - } - if(newCell){ - r = newCell[0]; - c = newCell[1]; - - if(last.row != r){ - this.selectRow(r); // *** highlight newly-selected cell and update selection - } + + setValue : function(prop, value, create){ + var r = this.getRec(prop); + if(r){ + r.set('value', value); + this.source[prop] = value; + }else if(create){ + + this.source[prop] = value; + r = new Ext.grid.PropertyRecord({name: prop, value: value}, prop); + this.store.add(r); - if(g.isEditor && g.editing){ // *** handle tabbing while editorgrid is in edit mode - ae = g.activeEditor; - if(ae && ae.field.triggerBlur){ - // *** if activeEditor is a TriggerField, explicitly call its triggerBlur() method - ae.field.triggerBlur(); - } - } - g.startEditing(r, c); } }, - destroy : function(){ - if(this.rowNav){ - this.rowNav.disable(); - this.rowNav = null; - } - Ext.grid.RowSelectionModel.superclass.destroy.call(this); - } -});/** - * @class Ext.grid.Column - *

This class encapsulates column configuration data to be used in the initialization of a - * {@link Ext.grid.ColumnModel ColumnModel}.

- *

While subclasses are provided to render data in different ways, this class renders a passed - * data field unchanged and is usually used for textual columns.

- */ -Ext.grid.Column = function(config){ - Ext.apply(this, config); - - if(Ext.isString(this.renderer)){ - this.renderer = Ext.util.Format[this.renderer]; - } else if(Ext.isObject(this.renderer)){ - this.scope = this.renderer.scope; - this.renderer = this.renderer.fn; - } - this.renderer = this.renderer.createDelegate(this.scope || config); - - if(this.editor){ - this.editor = Ext.create(this.editor, 'textfield'); - } -}; - -Ext.grid.Column.prototype = { - /** - * @cfg {Boolean} editable Optional. Defaults to true, enabling the configured - * {@link #editor}. Set to false to initially disable editing on this column. - * The initial configuration may be dynamically altered using - * {@link Ext.grid.ColumnModel}.{@link Ext.grid.ColumnModel#setEditable setEditable()}. - */ - /** - * @cfg {String} id Optional. A name which identifies this column (defaults to the column's initial - * ordinal position.) The id is used to create a CSS class name which is applied to all - * table cells (including headers) in that column (in this context the id does not need to be - * unique). The class name takes the form of
x-grid3-td-id
- * Header cells will also receive this class name, but will also have the class
x-grid3-hd
- * So, to target header cells, use CSS selectors such as:
.x-grid3-hd-row .x-grid3-td-id
- * The {@link Ext.grid.GridPanel#autoExpandColumn} grid config option references the column via this - * unique identifier. - */ - /** - * @cfg {String} header Optional. The header text to be used as innerHTML - * (html tags are accepted) to display in the Grid view. Note: to - * have a clickable header with no text displayed use ' '. - */ - /** - * @cfg {Boolean} groupable Optional. If the grid is being rendered by an {@link Ext.grid.GroupingView}, this option - * may be used to disable the header menu item to group by the column selected. Defaults to true, - * which enables the header menu group option. Set to false to disable (but still show) the - * group option in the header menu for the column. See also {@link #groupName}. - */ - /** - * @cfg {String} groupName Optional. If the grid is being rendered by an {@link Ext.grid.GroupingView}, this option - * may be used to specify the text with which to prefix the group field value in the group header line. - * See also {@link #groupRenderer} and - * {@link Ext.grid.GroupingView}.{@link Ext.grid.GroupingView#showGroupName showGroupName}. - */ - /** - * @cfg {Function} groupRenderer

Optional. If the grid is being rendered by an {@link Ext.grid.GroupingView}, this option - * may be used to specify the function used to format the grouping field value for display in the group - * {@link #groupName header}. If a groupRenderer is not specified, the configured - * {@link #renderer} will be called; if a {@link #renderer} is also not specified - * the new value of the group field will be used.

- *

The called function (either the groupRenderer or {@link #renderer}) will be - * passed the following parameters: - *

    - *
  • v : Object

    The new value of the group field.

  • - *
  • unused : undefined

    Unused parameter.

  • - *
  • r : Ext.data.Record

    The Record providing the data - * for the row which caused group change.

  • - *
  • rowIndex : Number

    The row index of the Record which caused group change.

  • - *
  • colIndex : Number

    The column index of the group field.

  • - *
  • ds : Ext.data.Store

    The Store which is providing the data Model.

  • - *

- *

The function should return a string value.

- */ - /** - * @cfg {String} emptyGroupText Optional. If the grid is being rendered by an {@link Ext.grid.GroupingView}, this option - * may be used to specify the text to display when there is an empty group value. Defaults to the - * {@link Ext.grid.GroupingView}.{@link Ext.grid.GroupingView#emptyGroupText emptyGroupText}. - */ - /** - * @cfg {String} dataIndex

Required. The name of the field in the - * grid's {@link Ext.data.Store}'s {@link Ext.data.Record} definition from - * which to draw the column's value.

- */ - /** - * @cfg {Number} width - * Optional. The initial width in pixels of the column. - * The width of each column can also be affected if any of the following are configured: - *
    - *
  • {@link Ext.grid.GridPanel}.{@link Ext.grid.GridPanel#autoExpandColumn autoExpandColumn}
  • - *
  • {@link Ext.grid.GridView}.{@link Ext.grid.GridView#forceFit forceFit} - *
    - *

    By specifying forceFit:true, {@link #fixed non-fixed width} columns will be - * re-proportioned (based on the relative initial widths) to fill the width of the grid so - * that no horizontal scrollbar is shown.

    - *
  • - *
  • {@link Ext.grid.GridView}.{@link Ext.grid.GridView#autoFill autoFill}
  • - *
  • {@link Ext.grid.GridPanel}.{@link Ext.grid.GridPanel#minColumnWidth minColumnWidth}
  • - *

    Note: when the width of each column is determined, a space on the right side - * is reserved for the vertical scrollbar. The - * {@link Ext.grid.GridView}.{@link Ext.grid.GridView#scrollOffset scrollOffset} - * can be modified to reduce or eliminate the reserved offset.

    - */ - /** - * @cfg {Boolean} sortable Optional. true if sorting is to be allowed on this column. - * Defaults to the value of the {@link Ext.grid.ColumnModel#defaultSortable} property. - * Whether local/remote sorting is used is specified in {@link Ext.data.Store#remoteSort}. - */ - /** - * @cfg {Boolean} fixed Optional. true if the column width cannot be changed. Defaults to false. - */ - /** - * @cfg {Boolean} resizable Optional. false to disable column resizing. Defaults to true. - */ - /** - * @cfg {Boolean} menuDisabled Optional. true to disable the column menu. Defaults to false. - */ - /** - * @cfg {Boolean} hidden - * Optional. true to initially hide this column. Defaults to false. - * A hidden column {@link Ext.grid.GridPanel#enableColumnHide may be shown via the header row menu}. - * If a column is never to be shown, simply do not include this column in the Column Model at all. - */ - /** - * @cfg {String} tooltip Optional. A text string to use as the column header's tooltip. If Quicktips - * are enabled, this value will be used as the text of the quick tip, otherwise it will be set as the - * header's HTML title attribute. Defaults to ''. - */ - /** - * @cfg {Mixed} renderer - *

    For an alternative to specifying a renderer see {@link #xtype}

    - *

    Optional. A renderer is an 'interceptor' method which can be used transform data (value, - * appearance, etc.) before it is rendered). This may be specified in either of three ways: - *

      - *
    • A renderer function used to return HTML markup for a cell given the cell's data value.
    • - *
    • A string which references a property name of the {@link Ext.util.Format} class which - * provides a renderer function.
    • - *
    • An object specifying both the renderer function, and its execution scope (this - * reference) e.g.:
      
      -{
      -    fn: this.gridRenderer,
      -    scope: this
      -}
      -
    - * If not specified, the default renderer uses the raw data value.

    - *

    For information about the renderer function (passed parameters, etc.), see - * {@link Ext.grid.ColumnModel#setRenderer}. An example of specifying renderer function inline:

    
    -var companyColumn = {
    -   header: 'Company Name',
    -   dataIndex: 'company',
    -   renderer: function(value, metaData, record, rowIndex, colIndex, store) {
    -      // provide the logic depending on business rules
    -      // name of your own choosing to manipulate the cell depending upon
    -      // the data in the underlying Record object.
    -      if (value == 'whatever') {
    -          //metaData.css : String : A CSS class name to add to the TD element of the cell.
    -          //metaData.attr : String : An html attribute definition string to apply to
    -          //                         the data container element within the table
    -          //                         cell (e.g. 'style="color:red;"').
    -          metaData.css = 'name-of-css-class-you-will-define';
    -      }
    -      return value;
    -   }
    -}
    -     * 
    - * See also {@link #scope}. - */ - /** - * @cfg {String} xtype Optional. A String which references a predefined {@link Ext.grid.Column} subclass - * type which is preconfigured with an appropriate {@link #renderer} to be easily - * configured into a ColumnModel. The predefined {@link Ext.grid.Column} subclass types are: - *
      - *
    • gridcolumn : {@link Ext.grid.Column} (Default)

    • - *
    • booleancolumn : {@link Ext.grid.BooleanColumn}

    • - *
    • numbercolumn : {@link Ext.grid.NumberColumn}

    • - *
    • datecolumn : {@link Ext.grid.DateColumn}

    • - *
    • templatecolumn : {@link Ext.grid.TemplateColumn}

    • - *
    - *

    Configuration properties for the specified xtype may be specified with - * the Column configuration properties, for example:

    - *
    
    -var grid = new Ext.grid.GridPanel({
    -    ...
    -    columns: [{
    -        header: 'Last Updated',
    -        dataIndex: 'lastChange',
    -        width: 85,
    -        sortable: true,
    -        //renderer: Ext.util.Format.dateRenderer('m/d/Y'),
    -        xtype: 'datecolumn', // use xtype instead of renderer
    -        format: 'M/d/Y' // configuration property for {@link Ext.grid.DateColumn}
    -    }, {
    -        ...
    -    }]
    -});
    -     * 
    - */ - /** - * @cfg {Object} scope Optional. The scope (this reference) in which to execute the - * renderer. Defaults to the Column configuration object. - */ - /** - * @cfg {String} align Optional. Set the CSS text-align property of the column. Defaults to undefined. - */ - /** - * @cfg {String} css Optional. An inline style definition string which is applied to all table cells in the column - * (excluding headers). Defaults to undefined. - */ - /** - * @cfg {Boolean} hideable Optional. Specify as false to prevent the user from hiding this column - * (defaults to true). To disallow column hiding globally for all columns in the grid, use - * {@link Ext.grid.GridPanel#enableColumnHide} instead. - */ - /** - * @cfg {Ext.form.Field} editor Optional. The {@link Ext.form.Field} to use when editing values in this column - * if editing is supported by the grid. See {@link #editable} also. - */ - - /** - * @private - * @cfg {Boolean} isColumn - * Used by ColumnModel setConfig method to avoid reprocessing a Column - * if isColumn is not set ColumnModel will recreate a new Ext.grid.Column - * Defaults to true. - */ - isColumn : true, - - /** - * Optional. A function which returns displayable data when passed the following parameters: - *
      - *
    • value : Object

      The data value for the cell.

    • - *
    • metadata : Object

      An object in which you may set the following attributes:

        - *
      • css : String

        A CSS class name to add to the cell's TD element.

      • - *
      • attr : String

        An HTML attribute definition string to apply to the data container - * element within the table cell (e.g. 'style="color:red;"').

    • - *
    • record : Ext.data.record

      The {@link Ext.data.Record} from which the data was - * extracted.

    • - *
    • rowIndex : Number

      Row index

    • - *
    • colIndex : Number

      Column index

    • - *
    • store : Ext.data.Store

      The {@link Ext.data.Store} object from which the Record - * was extracted.

    • - *
    - * @property renderer - * @type Function - */ - renderer : function(value){ - if(Ext.isString(value) && value.length < 1){ - return ' '; - } - return value; - }, - - // private - getEditor: function(rowIndex){ - return this.editable !== false ? this.editor : null; - }, - - /** - * Returns the {@link Ext.Editor editor} defined for this column that was created to wrap the {@link Ext.form.Field Field} - * used to edit the cell. - * @param {Number} rowIndex The row index - * @return {Ext.Editor} - */ - getCellEditor: function(rowIndex){ - var editor = this.getEditor(rowIndex); - if(editor){ - if(!editor.startEdit){ - if(!editor.gridEditor){ - editor.gridEditor = new Ext.grid.GridEditor(editor); - } - return editor.gridEditor; - }else if(editor.startEdit){ - return editor; - } - } - return null; - } -}; - -/** - * @class Ext.grid.BooleanColumn - * @extends Ext.grid.Column - *

    A Column definition class which renders boolean data fields. See the {@link Ext.grid.Column#xtype xtype} - * config option of {@link Ext.grid.Column} for more details.

    - */ -Ext.grid.BooleanColumn = Ext.extend(Ext.grid.Column, { - /** - * @cfg {String} trueText - * The string returned by the renderer when the column value is not falsey (defaults to 'true'). - */ - trueText: 'true', - /** - * @cfg {String} falseText - * The string returned by the renderer when the column value is falsey (but not undefined) (defaults to - * 'false'). - */ - falseText: 'false', - /** - * @cfg {String} undefinedText - * The string returned by the renderer when the column value is undefined (defaults to ' '). - */ - undefinedText: ' ', - - constructor: function(cfg){ - Ext.grid.BooleanColumn.superclass.constructor.call(this, cfg); - var t = this.trueText, f = this.falseText, u = this.undefinedText; - this.renderer = function(v){ - if(v === undefined){ - return u; - } - if(!v || v === 'false'){ - return f; - } - return t; - }; - } -}); - -/** - * @class Ext.grid.NumberColumn - * @extends Ext.grid.Column - *

    A Column definition class which renders a numeric data field according to a {@link #format} string. See the - * {@link Ext.grid.Column#xtype xtype} config option of {@link Ext.grid.Column} for more details.

    - */ -Ext.grid.NumberColumn = Ext.extend(Ext.grid.Column, { - /** - * @cfg {String} format - * A formatting string as used by {@link Ext.util.Format#number} to format a numeric value for this Column - * (defaults to '0,000.00'). - */ - format : '0,000.00', - constructor: function(cfg){ - Ext.grid.NumberColumn.superclass.constructor.call(this, cfg); - this.renderer = Ext.util.Format.numberRenderer(this.format); - } -}); - -/** - * @class Ext.grid.DateColumn - * @extends Ext.grid.Column - *

    A Column definition class which renders a passed date according to the default locale, or a configured - * {@link #format}. See the {@link Ext.grid.Column#xtype xtype} config option of {@link Ext.grid.Column} - * for more details.

    - */ -Ext.grid.DateColumn = Ext.extend(Ext.grid.Column, { - /** - * @cfg {String} format - * A formatting string as used by {@link Date#format} to format a Date for this Column - * (defaults to 'm/d/Y'). - */ - format : 'm/d/Y', - constructor: function(cfg){ - Ext.grid.DateColumn.superclass.constructor.call(this, cfg); - this.renderer = Ext.util.Format.dateRenderer(this.format); - } -}); - -/** - * @class Ext.grid.TemplateColumn - * @extends Ext.grid.Column - *

    A Column definition class which renders a value by processing a {@link Ext.data.Record Record}'s - * {@link Ext.data.Record#data data} using a {@link #tpl configured} {@link Ext.XTemplate XTemplate}. - * See the {@link Ext.grid.Column#xtype xtype} config option of {@link Ext.grid.Column} for more - * details.

    - */ -Ext.grid.TemplateColumn = Ext.extend(Ext.grid.Column, { - /** - * @cfg {String/XTemplate} tpl - * An {@link Ext.XTemplate XTemplate}, or an XTemplate definition string to use to process a - * {@link Ext.data.Record Record}'s {@link Ext.data.Record#data data} to produce a column's rendered value. - */ - constructor: function(cfg){ - Ext.grid.TemplateColumn.superclass.constructor.call(this, cfg); - var tpl = Ext.isObject(this.tpl) ? this.tpl : new Ext.XTemplate(this.tpl); - this.renderer = function(value, p, r){ - return tpl.apply(r.data); - }; - this.tpl = tpl; - } -}); - -/* - * @property types - * @type Object - * @member Ext.grid.Column - * @static - *

    An object containing predefined Column classes keyed by a mnemonic code which may be referenced - * by the {@link Ext.grid.ColumnModel#xtype xtype} config option of ColumnModel.

    - *

    This contains the following properties

      - *
    • gridcolumn : {@link Ext.grid.Column Column constructor}
    • - *
    • booleancolumn : {@link Ext.grid.BooleanColumn BooleanColumn constructor}
    • - *
    • numbercolumn : {@link Ext.grid.NumberColumn NumberColumn constructor}
    • - *
    • datecolumn : {@link Ext.grid.DateColumn DateColumn constructor}
    • - *
    • templatecolumn : {@link Ext.grid.TemplateColumn TemplateColumn constructor}
    • - *
    - */ -Ext.grid.Column.types = { - gridcolumn : Ext.grid.Column, - booleancolumn: Ext.grid.BooleanColumn, - numbercolumn: Ext.grid.NumberColumn, - datecolumn: Ext.grid.DateColumn, - templatecolumn: Ext.grid.TemplateColumn -};/** - * @class Ext.grid.RowNumberer - * This is a utility class that can be passed into a {@link Ext.grid.ColumnModel} as a column config that provides - * an automatic row numbering column. - *
    Usage:
    -
    
    - // This is a typical column config with the first column providing row numbers
    - var colModel = new Ext.grid.ColumnModel([
    -    new Ext.grid.RowNumberer(),
    -    {header: "Name", width: 80, sortable: true},
    -    {header: "Code", width: 50, sortable: true},
    -    {header: "Description", width: 200, sortable: true}
    - ]);
    - 
    - * @constructor - * @param {Object} config The configuration options - */ -Ext.grid.RowNumberer = function(config){ - Ext.apply(this, config); - if(this.rowspan){ - this.renderer = this.renderer.createDelegate(this); - } -}; - -Ext.grid.RowNumberer.prototype = { - /** - * @cfg {String} header Any valid text or HTML fragment to display in the header cell for the row - * number column (defaults to ''). - */ - header: "", - /** - * @cfg {Number} width The default width in pixels of the row number column (defaults to 23). - */ - width: 23, - /** - * @cfg {Boolean} sortable True if the row number column is sortable (defaults to false). - * @hide - */ - sortable: false, - - // private - fixed:true, - menuDisabled:true, - dataIndex: '', - id: 'numberer', - rowspan: undefined, - - // private - renderer : function(v, p, record, rowIndex){ - if(this.rowspan){ - p.cellAttr = 'rowspan="'+this.rowspan+'"'; + + remove : function(prop){ + var r = this.getRec(prop); + if(r){ + this.store.remove(r); + delete this.source[prop]; } - return rowIndex+1; - } -};/** - * @class Ext.grid.CheckboxSelectionModel - * @extends Ext.grid.RowSelectionModel - * A custom selection model that renders a column of checkboxes that can be toggled to select or deselect rows. - * @constructor - * @param {Object} config The configuration options - */ -Ext.grid.CheckboxSelectionModel = Ext.extend(Ext.grid.RowSelectionModel, { - - /** - * @cfg {Boolean} checkOnly true if rows can only be selected by clicking on the - * checkbox column (defaults to false). - */ - /** - * @cfg {String} header Any valid text or HTML fragment to display in the header cell for the - * checkbox column. Defaults to:
    
    -     * '<div class="x-grid3-hd-checker">&#160;</div>'
    -     * 
    - * The default CSS class of 'x-grid3-hd-checker' displays a checkbox in the header - * and provides support for automatic check all/none behavior on header click. This string - * can be replaced by any valid HTML fragment, including a simple text string (e.g., - * 'Select Rows'), but the automatic check all/none behavior will only work if the - * 'x-grid3-hd-checker' class is supplied. - */ - header : '
     
    ', - /** - * @cfg {Number} width The default width in pixels of the checkbox column (defaults to 20). - */ - width : 20, - /** - * @cfg {Boolean} sortable true if the checkbox column is sortable (defaults to - * false). - */ - sortable : false, - - // private - menuDisabled : true, - fixed : true, - dataIndex : '', - id : 'checker', - - constructor : function(){ - Ext.grid.CheckboxSelectionModel.superclass.constructor.apply(this, arguments); - - if(this.checkOnly){ - this.handleMouseDown = Ext.emptyFn; - } - }, - - // private - initEvents : function(){ - Ext.grid.CheckboxSelectionModel.superclass.initEvents.call(this); - this.grid.on('render', function(){ - var view = this.grid.getView(); - view.mainBody.on('mousedown', this.onMouseDown, this); - Ext.fly(view.innerHd).on('mousedown', this.onHdMouseDown, this); - - }, this); - }, - - // private - onMouseDown : function(e, t){ - if(e.button === 0 && t.className == 'x-grid3-row-checker'){ // Only fire if left-click - e.stopEvent(); - var row = e.getTarget('.x-grid3-row'); - if(row){ - var index = row.rowIndex; - if(this.isSelected(index)){ - this.deselectRow(index); - }else{ - this.selectRow(index, true); - } - } - } - }, - - // private - onHdMouseDown : function(e, t){ - if(t.className == 'x-grid3-hd-checker'){ - e.stopEvent(); - var hd = Ext.fly(t.parentNode); - var isChecked = hd.hasClass('x-grid3-hd-checker-on'); - if(isChecked){ - hd.removeClass('x-grid3-hd-checker-on'); - this.clearSelections(); - }else{ - hd.addClass('x-grid3-hd-checker-on'); - this.selectAll(); - } - } - }, - - // private - renderer : function(v, p, record){ - return '
     
    '; - } -});/** - * @class Ext.grid.CellSelectionModel - * @extends Ext.grid.AbstractSelectionModel - * This class provides the basic implementation for single cell selection in a grid. - * The object stored as the selection contains the following properties: - *
      - *
    • cell : see {@link #getSelectedCell} - *
    • record : Ext.data.record The {@link Ext.data.Record Record} - * which provides the data for the row containing the selection
    • - *
    - * @constructor - * @param {Object} config The object containing the configuration of this model. - */ -Ext.grid.CellSelectionModel = function(config){ - Ext.apply(this, config); - - this.selection = null; + }, + + + getRec : function(prop){ + return this.store.getById(prop); + }, - this.addEvents( - /** - * @event beforecellselect - * Fires before a cell is selected, return false to cancel the selection. - * @param {SelectionModel} this - * @param {Number} rowIndex The selected row index - * @param {Number} colIndex The selected cell index - */ - "beforecellselect", - /** - * @event cellselect - * Fires when a cell is selected. - * @param {SelectionModel} this - * @param {Number} rowIndex The selected row index - * @param {Number} colIndex The selected cell index - */ - "cellselect", - /** - * @event selectionchange - * Fires when the active selection changes. - * @param {SelectionModel} this - * @param {Object} selection null for no selection or an object with two properties - *
      - *
    • cell : see {@link #getSelectedCell} - *
    • record : Ext.data.record

      The {@link Ext.data.Record Record} - * which provides the data for the row containing the selection

    • - *
    - */ - "selectionchange" - ); + + getSource : function(){ + return this.source; + } +}); - Ext.grid.CellSelectionModel.superclass.constructor.call(this); -}; -Ext.extend(Ext.grid.CellSelectionModel, Ext.grid.AbstractSelectionModel, { +Ext.grid.PropertyColumnModel = Ext.extend(Ext.grid.ColumnModel, { + + nameText : 'Name', + valueText : 'Value', + dateFormat : 'm/j/Y', + trueText: 'true', + falseText: 'false', + + constructor : function(grid, store){ + var g = Ext.grid, + f = Ext.form; + + this.grid = grid; + g.PropertyColumnModel.superclass.constructor.call(this, [ + {header: this.nameText, width:50, sortable: true, dataIndex:'name', id: 'name', menuDisabled:true}, + {header: this.valueText, width:50, resizable:false, dataIndex: 'value', id: 'value', menuDisabled:true} + ]); + this.store = store; + + var bfield = new f.Field({ + autoCreate: {tag: 'select', children: [ + {tag: 'option', value: 'true', html: this.trueText}, + {tag: 'option', value: 'false', html: this.falseText} + ]}, + getValue : function(){ + return this.el.dom.value == 'true'; + } + }); + this.editors = { + 'date' : new g.GridEditor(new f.DateField({selectOnFocus:true})), + 'string' : new g.GridEditor(new f.TextField({selectOnFocus:true})), + 'number' : new g.GridEditor(new f.NumberField({selectOnFocus:true, style:'text-align:left;'})), + 'boolean' : new g.GridEditor(bfield, { + autoSize: 'both' + }) + }; + this.renderCellDelegate = this.renderCell.createDelegate(this); + this.renderPropDelegate = this.renderProp.createDelegate(this); + }, - /** @ignore */ - initEvents : function(){ - this.grid.on('cellmousedown', this.handleMouseDown, this); - this.grid.on(Ext.EventManager.useKeydown ? 'keydown' : 'keypress', this.handleKeyDown, this); - this.grid.getView().on({ - scope: this, - refresh: this.onViewChange, - rowupdated: this.onRowUpdated, - beforerowremoved: this.clearSelections, - beforerowsinserted: this.clearSelections - }); - if(this.grid.isEditor){ - this.grid.on('beforeedit', this.beforeEdit, this); - } + + renderDate : function(dateVal){ + return dateVal.dateFormat(this.dateFormat); }, - //private - beforeEdit : function(e){ - this.select(e.row, e.column, false, true, e.record); + + renderBool : function(bVal){ + return this[bVal ? 'trueText' : 'falseText']; }, - //private - onRowUpdated : function(v, index, r){ - if(this.selection && this.selection.record == r){ - v.onCellSelect(index, this.selection.cell[1]); - } + + isCellEditable : function(colIndex, rowIndex){ + return colIndex == 1; }, - //private - onViewChange : function(){ - this.clearSelections(true); + + getRenderer : function(col){ + return col == 1 ? + this.renderCellDelegate : this.renderPropDelegate; }, - /** - * Returns an array containing the row and column indexes of the currently selected cell - * (e.g., [0, 0]), or null if none selected. The array has elements: - *
      - *
    • rowIndex : Number

      The index of the selected row

    • - *
    • cellIndex : Number

      The index of the selected cell. - * Due to possible column reordering, the cellIndex should not be used as an - * index into the Record's data. Instead, use the cellIndex to determine the name - * of the selected cell and use the field name to retrieve the data value from the record:

      
      -// get name
      -var fieldName = grid.getColumnModel().getDataIndex(cellIndex);
      -// get data value based on name
      -var data = record.get(fieldName);
      -     * 

    • - *
    - * @return {Array} An array containing the row and column indexes of the selected cell, or null if none selected. - */ - getSelectedCell : function(){ - return this.selection ? this.selection.cell : null; + + renderProp : function(v){ + return this.getPropertyName(v); }, - /** - * If anything is selected, clears all selections and fires the selectionchange event. - * @param {Boolean} preventNotify true to prevent the gridview from - * being notified about the change. - */ - clearSelections : function(preventNotify){ - var s = this.selection; - if(s){ - if(preventNotify !== true){ - this.grid.view.onCellDeselect(s.cell[0], s.cell[1]); - } - this.selection = null; - this.fireEvent("selectionchange", this, null); + + renderCell : function(val, meta, rec){ + var renderer = this.grid.customRenderers[rec.get('name')]; + if(renderer){ + return renderer.apply(this, arguments); + } + var rv = val; + if(Ext.isDate(val)){ + rv = this.renderDate(val); + }else if(typeof val == 'boolean'){ + rv = this.renderBool(val); } + return Ext.util.Format.htmlEncode(rv); }, - /** - * Returns true if there is a selection. - * @return {Boolean} - */ - hasSelection : function(){ - return this.selection ? true : false; + + getPropertyName : function(name){ + var pn = this.grid.propertyNames; + return pn && pn[name] ? pn[name] : name; }, - /** @ignore */ - handleMouseDown : function(g, row, cell, e){ - if(e.button !== 0 || this.isLocked()){ - return; + + getCellEditor : function(colIndex, rowIndex){ + var p = this.store.getProperty(rowIndex), + n = p.data.name, + val = p.data.value; + if(this.grid.customEditors[n]){ + return this.grid.customEditors[n]; } - this.select(row, cell); - }, - - /** - * Selects a cell. Before selecting a cell, fires the - * {@link #beforecellselect} event. If this check is satisfied the cell - * will be selected and followed up by firing the {@link #cellselect} and - * {@link #selectionchange} events. - * @param {Number} rowIndex The index of the row to select - * @param {Number} colIndex The index of the column to select - * @param {Boolean} preventViewNotify (optional) Specify true to - * prevent notifying the view (disables updating the selected appearance) - * @param {Boolean} preventFocus (optional) Whether to prevent the cell at - * the specified rowIndex / colIndex from being focused. - * @param {Ext.data.Record} r (optional) The record to select - */ - select : function(rowIndex, colIndex, preventViewNotify, preventFocus, /*internal*/ r){ - if(this.fireEvent("beforecellselect", this, rowIndex, colIndex) !== false){ - this.clearSelections(); - r = r || this.grid.store.getAt(rowIndex); - this.selection = { - record : r, - cell : [rowIndex, colIndex] - }; - if(!preventViewNotify){ - var v = this.grid.getView(); - v.onCellSelect(rowIndex, colIndex); - if(preventFocus !== true){ - v.focusCell(rowIndex, colIndex); - } - } - this.fireEvent("cellselect", this, rowIndex, colIndex); - this.fireEvent("selectionchange", this, this.selection); + if(Ext.isDate(val)){ + return this.editors.date; + }else if(typeof val == 'number'){ + return this.editors.number; + }else if(typeof val == 'boolean'){ + return this.editors['boolean']; + }else{ + return this.editors.string; } }, - //private - isSelectable : function(rowIndex, colIndex, cm){ - return !cm.isHidden(colIndex); + + destroy : function(){ + Ext.grid.PropertyColumnModel.superclass.destroy.call(this); + this.destroyEditors(this.editors); + this.destroyEditors(this.grid.customEditors); }, - // private - onEditorKey: function(field, e){ - if(e.getKey() == e.TAB){ - this.handleKeyDown(e); + destroyEditors: function(editors){ + for(var ed in editors){ + Ext.destroy(editors[ed]); } - }, + } +}); - /** @ignore */ - handleKeyDown : function(e){ - if(!e.isNavKeyPress()){ - return; - } - - var k = e.getKey(), - g = this.grid, - s = this.selection, - sm = this, - walk = function(row, col, step){ - return g.walkCells( - row, - col, - step, - g.isEditor && g.editing ? sm.acceptsNav : sm.isSelectable, // *** handle tabbing while editorgrid is in edit mode - sm - ); - }, - cell, newCell, r, c, ae; - switch(k){ - case e.ESC: - case e.PAGE_UP: - case e.PAGE_DOWN: - // do nothing - break; - default: - // *** call e.stopEvent() only for non ESC, PAGE UP/DOWN KEYS - e.stopEvent(); - break; - } +Ext.grid.PropertyGrid = Ext.extend(Ext.grid.EditorGridPanel, { + + + + + - if(!s){ - cell = walk(0, 0, 1); // *** use private walk() function defined above - if(cell){ - this.select(cell[0], cell[1]); - } - return; - } + + enableColumnMove:false, + stripeRows:false, + trackMouseOver: false, + clicksToEdit:1, + enableHdMenu : false, + viewConfig : { + forceFit:true + }, - cell = s.cell; // currently selected cell - r = cell[0]; // current row - c = cell[1]; // current column - - switch(k){ - case e.TAB: - if(e.shiftKey){ - newCell = walk(r, c - 1, -1); - }else{ - newCell = walk(r, c + 1, 1); - } - break; - case e.DOWN: - newCell = walk(r + 1, c, 1); - break; - case e.UP: - newCell = walk(r - 1, c, -1); - break; - case e.RIGHT: - newCell = walk(r, c + 1, 1); - break; - case e.LEFT: - newCell = walk(r, c - 1, -1); - break; - case e.ENTER: - if (g.isEditor && !g.editing) { - g.startEditing(r, c); - return; - } - break; - } + + initComponent : function(){ + this.customRenderers = this.customRenderers || {}; + this.customEditors = this.customEditors || {}; + this.lastEditRow = null; + var store = new Ext.grid.PropertyStore(this); + this.propStore = store; + var cm = new Ext.grid.PropertyColumnModel(this, store); + store.store.sort('name', 'ASC'); + this.addEvents( + + 'beforepropertychange', + + 'propertychange' + ); + this.cm = cm; + this.ds = store.store; + Ext.grid.PropertyGrid.superclass.initComponent.call(this); - if(newCell){ - // *** reassign r & c variables to newly-selected cell's row and column - r = newCell[0]; - c = newCell[1]; + this.mon(this.selModel, 'beforecellselect', function(sm, rowIndex, colIndex){ + if(colIndex === 0){ + this.startEditing.defer(200, this, [rowIndex, 1]); + return false; + } + }, this); + }, + + + onRender : function(){ + Ext.grid.PropertyGrid.superclass.onRender.apply(this, arguments); - this.select(r, c); // *** highlight newly-selected cell and update selection + this.getGridEl().addClass('x-props-grid'); + }, - if(g.isEditor && g.editing){ // *** handle tabbing while editorgrid is in edit mode - ae = g.activeEditor; - if(ae && ae.field.triggerBlur){ - // *** if activeEditor is a TriggerField, explicitly call its triggerBlur() method - ae.field.triggerBlur(); - } - g.startEditing(r, c); - } + + afterRender: function(){ + Ext.grid.PropertyGrid.superclass.afterRender.apply(this, arguments); + if(this.source){ + this.setSource(this.source); } }, - acceptsNav : function(row, col, cm){ - return !cm.isHidden(col) && cm.isCellEditable(col, row); + + setSource : function(source){ + this.propStore.setSource(source); + }, + + + getSource : function(){ + return this.propStore.getSource(); + }, + + + setProperty : function(prop, value, create){ + this.propStore.setValue(prop, value, create); + }, + + + removeProperty : function(prop){ + this.propStore.remove(prop); } -});/** - * @class Ext.grid.EditorGridPanel - * @extends Ext.grid.GridPanel - *

    This class extends the {@link Ext.grid.GridPanel GridPanel Class} to provide cell editing - * on selected {@link Ext.grid.Column columns}. The editable columns are specified by providing - * an {@link Ext.grid.ColumnModel#editor editor} in the {@link Ext.grid.Column column configuration}.

    - *

    Editability of columns may be controlled programatically by inserting an implementation - * of {@link Ext.grid.ColumnModel#isCellEditable isCellEditable} into the - * {@link Ext.grid.ColumnModel ColumnModel}.

    - *

    Editing is performed on the value of the field specified by the column's - * {@link Ext.grid.ColumnModel#dataIndex dataIndex} in the backing {@link Ext.data.Store Store} - * (so if you are using a {@link Ext.grid.ColumnModel#setRenderer renderer} in order to display - * transformed data, this must be accounted for).

    - *

    If a value-to-description mapping is used to render a column, then a {@link Ext.form.Field#ComboBox ComboBox} - * which uses the same {@link Ext.form.Field#valueField value}-to-{@link Ext.form.Field#displayFieldField description} - * mapping would be an appropriate editor.

    - * If there is a more complex mismatch between the visible data in the grid, and the editable data in - * the {@link Edt.data.Store Store}, then code to transform the data both before and after editing can be - * injected using the {@link #beforeedit} and {@link #afteredit} events. - * @constructor - * @param {Object} config The config object - * @xtype editorgrid - */ -Ext.grid.EditorGridPanel = Ext.extend(Ext.grid.GridPanel, { - /** - * @cfg {Number} clicksToEdit - *

    The number of clicks on a cell required to display the cell's editor (defaults to 2).

    - *

    Setting this option to 'auto' means that mousedown on the selected cell starts - * editing that cell.

    - */ - clicksToEdit: 2, + - /** - * @cfg {Boolean} forceValidation - * True to force validation even if the value is unmodified (defaults to false) - */ - forceValidation: false, + + + +}); +Ext.reg("propertygrid", Ext.grid.PropertyGrid); - // private - isEditor : true, - // private - detectEdit: false, +Ext.grid.GroupingView = Ext.extend(Ext.grid.GridView, { - /** - * @cfg {Boolean} autoEncode - * True to automatically HTML encode and decode values pre and post edit (defaults to false) - */ - autoEncode : false, + + groupByText : 'Group By This Field', + + showGroupsText : 'Show in Groups', + + hideGroupedColumn : false, + + showGroupName : true, + + startCollapsed : false, + + enableGrouping : true, + + enableGroupingMenu : true, + + enableNoGroups : true, + + emptyGroupText : '(None)', + + ignoreAdd : false, + + groupTextTpl : '{text}', - /** - * @cfg {Boolean} trackMouseOver @hide - */ - // private - trackMouseOver: false, // causes very odd FF errors + + groupMode: 'value', - // private - initComponent : function(){ - Ext.grid.EditorGridPanel.superclass.initComponent.call(this); + + + + cancelEditOnToggle: true, - if(!this.selModel){ - /** - * @cfg {Object} selModel Any subclass of AbstractSelectionModel that will provide the selection model for - * the grid (defaults to {@link Ext.grid.CellSelectionModel} if not specified). - */ - this.selModel = new Ext.grid.CellSelectionModel(); + + initTemplates : function(){ + Ext.grid.GroupingView.superclass.initTemplates.call(this); + this.state = {}; + + var sm = this.grid.getSelectionModel(); + sm.on(sm.selectRow ? 'beforerowselect' : 'beforecellselect', + this.onBeforeRowSelect, this); + + if(!this.startGroup){ + this.startGroup = new Ext.XTemplate( + '
    ', + '
    ', this.groupTextTpl ,'
    ', + '
    ' + ); } + this.startGroup.compile(); - this.activeEditor = null; + if (!this.endGroup) { + this.endGroup = '
    '; + } + }, - this.addEvents( - /** - * @event beforeedit - * Fires before cell editing is triggered. The edit event object has the following properties
    - *
      - *
    • grid - This grid
    • - *
    • record - The record being edited
    • - *
    • field - The field name being edited
    • - *
    • value - The value for the field being edited.
    • - *
    • row - The grid row index
    • - *
    • column - The grid column index
    • - *
    • cancel - Set this to true to cancel the edit or return false from your handler.
    • - *
    - * @param {Object} e An edit event (see above for description) - */ - "beforeedit", - /** - * @event afteredit - * Fires after a cell is edited. The edit event object has the following properties
    - *
      - *
    • grid - This grid
    • - *
    • record - The record being edited
    • - *
    • field - The field name being edited
    • - *
    • value - The value being set
    • - *
    • originalValue - The original value for the field, before the edit.
    • - *
    • row - The grid row index
    • - *
    • column - The grid column index
    • - *
    - * - *
     
    -grid.on('afteredit', afterEdit, this );
    -
    -function afterEdit(e) {
    -    // execute an XHR to send/commit data to the server, in callback do (if successful):
    -    e.record.commit();
    -}; 
    -             * 
    - * @param {Object} e An edit event (see above for description) - */ - "afteredit", - /** - * @event validateedit - * Fires after a cell is edited, but before the value is set in the record. Return false - * to cancel the change. The edit event object has the following properties
    - *
      - *
    • grid - This grid
    • - *
    • record - The record being edited
    • - *
    • field - The field name being edited
    • - *
    • value - The value being set
    • - *
    • originalValue - The original value for the field, before the edit.
    • - *
    • row - The grid row index
    • - *
    • column - The grid column index
    • - *
    • cancel - Set this to true to cancel the edit or return false from your handler.
    • - *
    - * Usage example showing how to remove the red triangle (dirty record indicator) from some - * records (not all). By observing the grid's validateedit event, it can be cancelled if - * the edit occurs on a targeted row (for example) and then setting the field's new value - * in the Record directly: - *
     
    -grid.on('validateedit', function(e) {
    -  var myTargetRow = 6;
    - 
    -  if (e.row == myTargetRow) {
    -    e.cancel = true;
    -    e.record.data[e.field] = e.value;
    -  }
    -});
    -             * 
    - * @param {Object} e An edit event (see above for description) - */ - "validateedit" - ); + + findGroup : function(el){ + return Ext.fly(el).up('.x-grid-group', this.mainBody.dom); }, - // private - initEvents : function(){ - Ext.grid.EditorGridPanel.superclass.initEvents.call(this); + + getGroups : function(){ + return this.hasRows() ? this.mainBody.dom.childNodes : []; + }, - this.getGridEl().on('mousewheel', this.stopEditing.createDelegate(this, [true]), this); - this.on('columnresize', this.stopEditing, this, [true]); + + onAdd : function(ds, records, index) { + if (this.canGroup() && !this.ignoreAdd) { + var ss = this.getScrollState(); + this.fireEvent('beforerowsinserted', ds, index, index + (records.length-1)); + this.refresh(); + this.restoreScroll(ss); + this.fireEvent('rowsinserted', ds, index, index + (records.length-1)); + } else if (!this.canGroup()) { + Ext.grid.GroupingView.superclass.onAdd.apply(this, arguments); + } + }, - if(this.clicksToEdit == 1){ - this.on("cellclick", this.onCellDblClick, this); - }else { - var view = this.getView(); - if(this.clicksToEdit == 'auto' && view.mainBody){ - view.mainBody.on('mousedown', this.onAutoEditClick, this); - } - this.on('celldblclick', this.onCellDblClick, this); + + onRemove : function(ds, record, index, isUpdate){ + Ext.grid.GroupingView.superclass.onRemove.apply(this, arguments); + var g = document.getElementById(record._groupId); + if(g && g.childNodes[1].childNodes.length < 1){ + Ext.removeNode(g); } + this.applyEmptyText(); }, - // private - onCellDblClick : function(g, row, col){ - this.startEditing(row, col); + + refreshRow : function(record){ + if(this.ds.getCount()==1){ + this.refresh(); + }else{ + this.isUpdating = true; + Ext.grid.GroupingView.superclass.refreshRow.apply(this, arguments); + this.isUpdating = false; + } }, - // private - onAutoEditClick : function(e, t){ - if(e.button !== 0){ - return; + + beforeMenuShow : function(){ + var item, items = this.hmenu.items, disabled = this.cm.config[this.hdCtxIndex].groupable === false; + if((item = items.get('groupBy'))){ + item.setDisabled(disabled); } - var row = this.view.findRowIndex(t); - var col = this.view.findCellIndex(t); - if(row !== false && col !== false){ - this.stopEditing(); - if(this.selModel.getSelectedCell){ // cell sm - var sc = this.selModel.getSelectedCell(); - if(sc && sc[0] === row && sc[1] === col){ - this.startEditing(row, col); - } - }else{ - if(this.selModel.isSelected(row)){ - this.startEditing(row, col); - } - } + if((item = items.get('showGroups'))){ + item.setDisabled(disabled); + item.setChecked(this.canGroup(), true); } }, - // private - onEditComplete : function(ed, value, startValue){ - this.editing = false; - this.activeEditor = null; - - var r = ed.record; - var field = this.colModel.getDataIndex(ed.col); - value = this.postEditValue(value, startValue, r, field); - if(this.forceValidation === true || String(value) !== String(startValue)){ - var e = { - grid: this, - record: r, - field: field, - originalValue: startValue, - value: value, - row: ed.row, - column: ed.col, - cancel:false - }; - if(this.fireEvent("validateedit", e) !== false && !e.cancel && String(value) !== String(startValue)){ - r.set(field, e.value); - delete e.cancel; - this.fireEvent("afteredit", e); + + renderUI : function(){ + var markup = Ext.grid.GroupingView.superclass.renderUI.call(this); + + if(this.enableGroupingMenu && this.hmenu){ + this.hmenu.add('-',{ + itemId:'groupBy', + text: this.groupByText, + handler: this.onGroupByClick, + scope: this, + iconCls:'x-group-by-icon' + }); + if(this.enableNoGroups){ + this.hmenu.add({ + itemId:'showGroups', + text: this.showGroupsText, + checked: true, + checkHandler: this.onShowGroupsClick, + scope: this + }); } + this.hmenu.on('beforeshow', this.beforeMenuShow, this); } - this.view.focusCell(ed.row, ed.col); + return markup; }, - /** - * Starts editing the specified for the specified row/column - * @param {Number} rowIndex - * @param {Number} colIndex - */ - startEditing : function(row, col){ - this.stopEditing(); - if(this.colModel.isCellEditable(col, row)){ - this.view.ensureVisible(row, col, true); - var r = this.store.getAt(row); - var field = this.colModel.getDataIndex(col); - var e = { - grid: this, - record: r, - field: field, - value: r.data[field], - row: row, - column: col, - cancel:false - }; - if(this.fireEvent("beforeedit", e) !== false && !e.cancel){ - this.editing = true; - var ed = this.colModel.getCellEditor(col, row); - if(!ed){ - return; - } - if(!ed.rendered){ - ed.parentEl = this.view.getEditorParent(ed); - ed.on({ - scope: this, - render: { - fn: function(c){ - c.field.focus(false, true); - }, - single: true, - scope: this - }, - specialkey: function(field, e){ - this.getSelectionModel().onEditorKey(field, e); - }, - complete: this.onEditComplete, - canceledit: this.stopEditing.createDelegate(this, [true]) - }); - } - Ext.apply(ed, { - row : row, - col : col, - record : r - }); - this.lastEdit = { - row: row, - col: col - }; - this.activeEditor = ed; - var v = this.preEditValue(r, field); - ed.startEdit(this.view.getCell(row, col).firstChild, Ext.isDefined(v) ? v : ''); + processEvent: function(name, e){ + Ext.grid.GroupingView.superclass.processEvent.call(this, name, e); + var hd = e.getTarget('.x-grid-group-hd', this.mainBody); + if(hd){ + + var field = this.getGroupField(), + prefix = this.getPrefix(field), + groupValue = hd.id.substring(prefix.length), + emptyRe = new RegExp('gp-' + Ext.escapeRe(field) + '--hd'); + + + groupValue = groupValue.substr(0, groupValue.length - 3); + + + if(groupValue || emptyRe.test(hd.id)){ + this.grid.fireEvent('group' + name, this.grid, field, groupValue, e); + } + if(name == 'mousedown' && e.button == 0){ + this.toggleGroup(hd.parentNode); } } - }, - // private - preEditValue : function(r, field){ - var value = r.data[field]; - return this.autoEncode && Ext.isString(value) ? Ext.util.Format.htmlDecode(value) : value; }, - // private - postEditValue : function(value, originalValue, r, field){ - return this.autoEncode && Ext.isString(value) ? Ext.util.Format.htmlEncode(value) : value; - }, + + onGroupByClick : function(){ + var grid = this.grid; + this.enableGrouping = true; + grid.store.groupBy(this.cm.getDataIndex(this.hdCtxIndex)); + grid.fireEvent('groupchange', grid, grid.store.getGroupState()); + this.beforeMenuShow(); + this.refresh(); + }, - /** - * Stops any active editing - * @param {Boolean} cancel (optional) True to cancel any changes - */ - stopEditing : function(cancel){ - if(this.editing){ - var ae = this.activeEditor; - if(ae){ - ae[cancel === true ? 'cancelEdit' : 'completeEdit'](); - this.view.focusCell(ae.row, ae.col); - } - this.activeEditor = null; + + onShowGroupsClick : function(mi, checked){ + this.enableGrouping = checked; + if(checked){ + this.onGroupByClick(); + }else{ + this.grid.store.clearGrouping(); + this.grid.fireEvent('groupchange', this, null); } - this.editing = false; - } -}); -Ext.reg('editorgrid', Ext.grid.EditorGridPanel);// private -// This is a support class used internally by the Grid components -Ext.grid.GridEditor = function(field, config){ - Ext.grid.GridEditor.superclass.constructor.call(this, field, config); - field.monitorTab = false; -}; + }, -Ext.extend(Ext.grid.GridEditor, Ext.Editor, { - alignment: "tl-tl", - autoSize: "width", - hideEl : false, - cls: "x-small-editor x-grid-editor", - shim:false, - shadow:false -});/** - * @class Ext.grid.PropertyRecord - * A specific {@link Ext.data.Record} type that represents a name/value pair and is made to work with the - * {@link Ext.grid.PropertyGrid}. Typically, PropertyRecords do not need to be created directly as they can be - * created implicitly by simply using the appropriate data configs either via the {@link Ext.grid.PropertyGrid#source} - * config property or by calling {@link Ext.grid.PropertyGrid#setSource}. However, if the need arises, these records - * can also be created explicitly as shwon below. Example usage: - *
    
    -var rec = new Ext.grid.PropertyRecord({
    -    name: 'Birthday',
    -    value: new Date(Date.parse('05/26/1972'))
    -});
    -// Add record to an already populated grid
    -grid.store.addSorted(rec);
    -
    - * @constructor - * @param {Object} config A data object in the format: {name: [name], value: [value]}. The specified value's type - * will be read automatically by the grid to determine the type of editor to use when displaying it. - */ -Ext.grid.PropertyRecord = Ext.data.Record.create([ - {name:'name',type:'string'}, 'value' -]); + + toggleRowIndex : function(rowIndex, expanded){ + if(!this.canGroup()){ + return; + } + var row = this.getRow(rowIndex); + if(row){ + this.toggleGroup(this.findGroup(row), expanded); + } + }, -/** - * @class Ext.grid.PropertyStore - * @extends Ext.util.Observable - * A custom wrapper for the {@link Ext.grid.PropertyGrid}'s {@link Ext.data.Store}. This class handles the mapping - * between the custom data source objects supported by the grid and the {@link Ext.grid.PropertyRecord} format - * required for compatibility with the underlying store. Generally this class should not need to be used directly -- - * the grid's data should be accessed from the underlying store via the {@link #store} property. - * @constructor - * @param {Ext.grid.Grid} grid The grid this store will be bound to - * @param {Object} source The source data config object - */ -Ext.grid.PropertyStore = function(grid, source){ - this.grid = grid; - this.store = new Ext.data.Store({ - recordType : Ext.grid.PropertyRecord - }); - this.store.on('update', this.onUpdate, this); - if(source){ - this.setSource(source); - } - Ext.grid.PropertyStore.superclass.constructor.call(this); -}; -Ext.extend(Ext.grid.PropertyStore, Ext.util.Observable, { - // protected - should only be called by the grid. Use grid.setSource instead. - setSource : function(o){ - this.source = o; - this.store.removeAll(); - var data = []; - for(var k in o){ - if(this.isEditableValue(o[k])){ - data.push(new Ext.grid.PropertyRecord({name: k, value: o[k]}, k)); + + toggleGroup : function(group, expanded){ + var gel = Ext.get(group); + expanded = Ext.isDefined(expanded) ? expanded : gel.hasClass('x-grid-group-collapsed'); + if(this.state[gel.id] !== expanded){ + if (this.cancelEditOnToggle !== false) { + this.grid.stopEditing(true); } + this.state[gel.id] = expanded; + gel[expanded ? 'removeClass' : 'addClass']('x-grid-group-collapsed'); } - this.store.loadRecords({records: data}, {}, true); }, - // private - onUpdate : function(ds, record, type){ - if(type == Ext.data.Record.EDIT){ - var v = record.data.value; - var oldValue = record.modified.value; - if(this.grid.fireEvent('beforepropertychange', this.source, record.id, v, oldValue) !== false){ - this.source[record.id] = v; - record.commit(); - this.grid.fireEvent('propertychange', this.source, record.id, v, oldValue); - }else{ - record.reject(); - } + + toggleAllGroups : function(expanded){ + var groups = this.getGroups(); + for(var i = 0, len = groups.length; i < len; i++){ + this.toggleGroup(groups[i], expanded); } }, - // private - getProperty : function(row){ - return this.store.getAt(row); + + expandAllGroups : function(){ + this.toggleAllGroups(true); }, - // private - isEditableValue: function(val){ - if(Ext.isDate(val)){ - return true; + + collapseAllGroups : function(){ + this.toggleAllGroups(false); + }, + + + getGroup : function(v, r, groupRenderer, rowIndex, colIndex, ds){ + var column = this.cm.config[colIndex], + g = groupRenderer ? groupRenderer.call(column.scope, v, {}, r, rowIndex, colIndex, ds) : String(v); + if(g === '' || g === ' '){ + g = column.emptyGroupText || this.emptyGroupText; } - return !(Ext.isObject(val) || Ext.isFunction(val)); + return g; }, - // private - setValue : function(prop, value){ - this.source[prop] = value; - this.store.getById(prop).set('value', value); + + getGroupField : function(){ + return this.grid.store.getGroupState(); }, - // protected - should only be called by the grid. Use grid.getSource instead. - getSource : function(){ - return this.source; - } -}); + + afterRender : function(){ + if(!this.ds || !this.cm){ + return; + } + Ext.grid.GroupingView.superclass.afterRender.call(this); + if(this.grid.deferRowRender){ + this.updateGroupWidths(); + } + }, + + afterRenderUI: function () { + Ext.grid.GroupingView.superclass.afterRenderUI.call(this); + + if (this.enableGroupingMenu && this.hmenu) { + this.hmenu.add('-',{ + itemId:'groupBy', + text: this.groupByText, + handler: this.onGroupByClick, + scope: this, + iconCls:'x-group-by-icon' + }); + + if (this.enableNoGroups) { + this.hmenu.add({ + itemId:'showGroups', + text: this.showGroupsText, + checked: true, + checkHandler: this.onShowGroupsClick, + scope: this + }); + } + + this.hmenu.on('beforeshow', this.beforeMenuShow, this); + } + }, -/** - * @class Ext.grid.PropertyColumnModel - * @extends Ext.grid.ColumnModel - * A custom column model for the {@link Ext.grid.PropertyGrid}. Generally it should not need to be used directly. - * @constructor - * @param {Ext.grid.Grid} grid The grid this store will be bound to - * @param {Object} source The source data config object - */ -Ext.grid.PropertyColumnModel = function(grid, store){ - var g = Ext.grid, - f = Ext.form; + + renderRows : function(){ + var groupField = this.getGroupField(); + var eg = !!groupField; - this.grid = grid; - g.PropertyColumnModel.superclass.constructor.call(this, [ - {header: this.nameText, width:50, sortable: true, dataIndex:'name', id: 'name', menuDisabled:true}, - {header: this.valueText, width:50, resizable:false, dataIndex: 'value', id: 'value', menuDisabled:true} - ]); - this.store = store; - - var bfield = new f.Field({ - autoCreate: {tag: 'select', children: [ - {tag: 'option', value: 'true', html: 'true'}, - {tag: 'option', value: 'false', html: 'false'} - ]}, - getValue : function(){ - return this.el.dom.value == 'true'; + if(this.hideGroupedColumn) { + var colIndex = this.cm.findColumnIndex(groupField), + hasLastGroupField = Ext.isDefined(this.lastGroupField); + if(!eg && hasLastGroupField){ + this.mainBody.update(''); + this.cm.setHidden(this.cm.findColumnIndex(this.lastGroupField), false); + delete this.lastGroupField; + }else if (eg && !hasLastGroupField){ + this.lastGroupField = groupField; + this.cm.setHidden(colIndex, true); + }else if (eg && hasLastGroupField && groupField !== this.lastGroupField) { + this.mainBody.update(''); + var oldIndex = this.cm.findColumnIndex(this.lastGroupField); + this.cm.setHidden(oldIndex, false); + this.lastGroupField = groupField; + this.cm.setHidden(colIndex, true); + } + } + return Ext.grid.GroupingView.superclass.renderRows.apply( + this, arguments); + }, + + + doRender : function(cs, rs, ds, startRow, colCount, stripe){ + if(rs.length < 1){ + return ''; } - }); - this.editors = { - 'date' : new g.GridEditor(new f.DateField({selectOnFocus:true})), - 'string' : new g.GridEditor(new f.TextField({selectOnFocus:true})), - 'number' : new g.GridEditor(new f.NumberField({selectOnFocus:true, style:'text-align:left;'})), - 'boolean' : new g.GridEditor(bfield, { - autoSize: 'both' - }) - }; - this.renderCellDelegate = this.renderCell.createDelegate(this); - this.renderPropDelegate = this.renderProp.createDelegate(this); -}; -Ext.extend(Ext.grid.PropertyColumnModel, Ext.grid.ColumnModel, { - // private - strings used for locale support - nameText : 'Name', - valueText : 'Value', - dateFormat : 'm/j/Y', + if(!this.canGroup() || this.isUpdating){ + return Ext.grid.GroupingView.superclass.doRender.apply(this, arguments); + } - // private - renderDate : function(dateVal){ - return dateVal.dateFormat(this.dateFormat); + var groupField = this.getGroupField(), + colIndex = this.cm.findColumnIndex(groupField), + g, + gstyle = 'width:' + this.getTotalWidth() + ';', + cfg = this.cm.config[colIndex], + groupRenderer = cfg.groupRenderer || cfg.renderer, + prefix = this.showGroupName ? (cfg.groupName || cfg.header)+': ' : '', + groups = [], + curGroup, i, len, gid; + + for(i = 0, len = rs.length; i < len; i++){ + var rowIndex = startRow + i, + r = rs[i], + gvalue = r.data[groupField]; + + g = this.getGroup(gvalue, r, groupRenderer, rowIndex, colIndex, ds); + if(!curGroup || curGroup.group != g){ + gid = this.constructId(gvalue, groupField, colIndex); + + + this.state[gid] = !(Ext.isDefined(this.state[gid]) ? !this.state[gid] : this.startCollapsed); + curGroup = { + group: g, + gvalue: gvalue, + text: prefix + g, + groupId: gid, + startRow: rowIndex, + rs: [r], + cls: this.state[gid] ? '' : 'x-grid-group-collapsed', + style: gstyle + }; + groups.push(curGroup); + }else{ + curGroup.rs.push(r); + } + r._groupId = gid; + } + + var buf = []; + for(i = 0, len = groups.length; i < len; i++){ + g = groups[i]; + this.doGroupStart(buf, g, cs, ds, colCount); + buf[buf.length] = Ext.grid.GroupingView.superclass.doRender.call( + this, cs, g.rs, ds, g.startRow, colCount, stripe); + + this.doGroupEnd(buf, g, cs, ds, colCount); + } + return buf.join(''); }, - // private - renderBool : function(bVal){ - return bVal ? 'true' : 'false'; + + getGroupId : function(value){ + var field = this.getGroupField(); + return this.constructId(value, field, this.cm.findColumnIndex(field)); }, - // private - isCellEditable : function(colIndex, rowIndex){ - return colIndex == 1; + + constructId : function(value, field, idx){ + var cfg = this.cm.config[idx], + groupRenderer = cfg.groupRenderer || cfg.renderer, + val = (this.groupMode == 'value') ? value : this.getGroup(value, {data:{}}, groupRenderer, 0, idx, this.ds); + + return this.getPrefix(field) + Ext.util.Format.htmlEncode(val); }, - // private - getRenderer : function(col){ - return col == 1 ? - this.renderCellDelegate : this.renderPropDelegate; + + canGroup : function(){ + return this.enableGrouping && !!this.getGroupField(); }, - // private - renderProp : function(v){ - return this.getPropertyName(v); + + getPrefix: function(field){ + return this.grid.getGridEl().id + '-gp-' + field + '-'; }, - // private - renderCell : function(val){ - var rv = val; - if(Ext.isDate(val)){ - rv = this.renderDate(val); - }else if(typeof val == 'boolean'){ - rv = this.renderBool(val); - } - return Ext.util.Format.htmlEncode(rv); + + doGroupStart : function(buf, g, cs, ds, colCount){ + buf[buf.length] = this.startGroup.apply(g); }, - // private - getPropertyName : function(name){ - var pn = this.grid.propertyNames; - return pn && pn[name] ? pn[name] : name; + + doGroupEnd : function(buf, g, cs, ds, colCount){ + buf[buf.length] = this.endGroup; }, - // private - getCellEditor : function(colIndex, rowIndex){ - var p = this.store.getProperty(rowIndex), - n = p.data.name, - val = p.data.value; - if(this.grid.customEditors[n]){ - return this.grid.customEditors[n]; - } - if(Ext.isDate(val)){ - return this.editors.date; - }else if(typeof val == 'number'){ - return this.editors.number; - }else if(typeof val == 'boolean'){ - return this.editors['boolean']; - }else{ - return this.editors.string; + + getRows : function(){ + if(!this.canGroup()){ + return Ext.grid.GroupingView.superclass.getRows.call(this); + } + var r = [], + gs = this.getGroups(), + g, + i = 0, + len = gs.length, + j, + jlen; + for(; i < len; ++i){ + g = gs[i].childNodes[1]; + if(g){ + g = g.childNodes; + for(j = 0, jlen = g.length; j < jlen; ++j){ + r[r.length] = g[j]; + } + } } + return r; }, - // inherit docs - destroy : function(){ - Ext.grid.PropertyColumnModel.superclass.destroy.call(this); - for(var ed in this.editors){ - Ext.destroy(ed); + + updateGroupWidths : function(){ + if(!this.canGroup() || !this.hasRows()){ + return; + } + var tw = Math.max(this.cm.getTotalWidth(), this.el.dom.offsetWidth-this.getScrollOffset()) +'px'; + var gs = this.getGroups(); + for(var i = 0, len = gs.length; i < len; i++){ + gs[i].firstChild.style.width = tw; } - } -}); - -/** - * @class Ext.grid.PropertyGrid - * @extends Ext.grid.EditorGridPanel - * A specialized grid implementation intended to mimic the traditional property grid as typically seen in - * development IDEs. Each row in the grid represents a property of some object, and the data is stored - * as a set of name/value pairs in {@link Ext.grid.PropertyRecord}s. Example usage: - *
    
    -var grid = new Ext.grid.PropertyGrid({
    -    title: 'Properties Grid',
    -    autoHeight: true,
    -    width: 300,
    -    renderTo: 'grid-ct',
    -    source: {
    -        "(name)": "My Object",
    -        "Created": new Date(Date.parse('10/15/2006')),
    -        "Available": false,
    -        "Version": .01,
    -        "Description": "A test object"
    -    }
    -});
    -
    - * @constructor - * @param {Object} config The grid config object - */ -Ext.grid.PropertyGrid = Ext.extend(Ext.grid.EditorGridPanel, { - /** - * @cfg {Object} propertyNames An object containing property name/display name pairs. - * If specified, the display name will be shown in the name column instead of the property name. - */ - /** - * @cfg {Object} source A data object to use as the data source of the grid (see {@link #setSource} for details). - */ - /** - * @cfg {Object} customEditors An object containing name/value pairs of custom editor type definitions that allow - * the grid to support additional types of editable fields. By default, the grid supports strongly-typed editing - * of strings, dates, numbers and booleans using built-in form editors, but any custom type can be supported and - * associated with a custom input control by specifying a custom editor. The name of the editor - * type should correspond with the name of the property that will use the editor. Example usage: - *
    
    -var grid = new Ext.grid.PropertyGrid({
    -    ...
    -    customEditors: {
    -        'Start Time': new Ext.grid.GridEditor(new Ext.form.TimeField({selectOnFocus:true}))
    -    },
    -    source: {
    -        'Start Time': '10:00 AM'
    -    }
    -});
    -
    - */ - - // private config overrides - enableColumnMove:false, - stripeRows:false, - trackMouseOver: false, - clicksToEdit:1, - enableHdMenu : false, - viewConfig : { - forceFit:true }, - // private - initComponent : function(){ - this.customEditors = this.customEditors || {}; - this.lastEditRow = null; - var store = new Ext.grid.PropertyStore(this); - this.propStore = store; - var cm = new Ext.grid.PropertyColumnModel(this, store); - store.store.sort('name', 'ASC'); - this.addEvents( - /** - * @event beforepropertychange - * Fires before a property value changes. Handlers can return false to cancel the property change - * (this will internally call {@link Ext.data.Record#reject} on the property's record). - * @param {Object} source The source data object for the grid (corresponds to the same object passed in - * as the {@link #source} config property). - * @param {String} recordId The record's id in the data store - * @param {Mixed} value The current edited property value - * @param {Mixed} oldValue The original property value prior to editing - */ - 'beforepropertychange', - /** - * @event propertychange - * Fires after a property value has changed. - * @param {Object} source The source data object for the grid (corresponds to the same object passed in - * as the {@link #source} config property). - * @param {String} recordId The record's id in the data store - * @param {Mixed} value The current edited property value - * @param {Mixed} oldValue The original property value prior to editing - */ - 'propertychange' - ); - this.cm = cm; - this.ds = store.store; - Ext.grid.PropertyGrid.superclass.initComponent.call(this); - - this.mon(this.selModel, 'beforecellselect', function(sm, rowIndex, colIndex){ - if(colIndex === 0){ - this.startEditing.defer(200, this, [rowIndex, 1]); - return false; - } - }, this); + + onColumnWidthUpdated : function(col, w, tw){ + Ext.grid.GroupingView.superclass.onColumnWidthUpdated.call(this, col, w, tw); + this.updateGroupWidths(); }, - // private - onRender : function(){ - Ext.grid.PropertyGrid.superclass.onRender.apply(this, arguments); - - this.getGridEl().addClass('x-props-grid'); + + onAllColumnWidthsUpdated : function(ws, tw){ + Ext.grid.GroupingView.superclass.onAllColumnWidthsUpdated.call(this, ws, tw); + this.updateGroupWidths(); }, - // private - afterRender: function(){ - Ext.grid.PropertyGrid.superclass.afterRender.apply(this, arguments); - if(this.source){ - this.setSource(this.source); - } + + onColumnHiddenUpdated : function(col, hidden, tw){ + Ext.grid.GroupingView.superclass.onColumnHiddenUpdated.call(this, col, hidden, tw); + this.updateGroupWidths(); }, - /** - * Sets the source data object containing the property data. The data object can contain one or more name/value - * pairs representing all of the properties of an object to display in the grid, and this data will automatically - * be loaded into the grid's {@link #store}. The values should be supplied in the proper data type if needed, - * otherwise string type will be assumed. If the grid already contains data, this method will replace any - * existing data. See also the {@link #source} config value. Example usage: - *
    
    -grid.setSource({
    -    "(name)": "My Object",
    -    "Created": new Date(Date.parse('10/15/2006')),  // date type
    -    "Available": false,  // boolean type
    -    "Version": .01,      // decimal type
    -    "Description": "A test object"
    -});
    -
    - * @param {Object} source The data object - */ - setSource : function(source){ - this.propStore.setSource(source); + + onLayout : function(){ + this.updateGroupWidths(); }, - /** - * Gets the source data object containing the property data. See {@link #setSource} for details regarding the - * format of the data object. - * @return {Object} The data object - */ - getSource : function(){ - return this.propStore.getSource(); + + onBeforeRowSelect : function(sm, rowIndex){ + this.toggleRowIndex(rowIndex, true); } }); -Ext.reg("propertygrid", Ext.grid.PropertyGrid); -/** - * @class Ext.grid.GroupingView - * @extends Ext.grid.GridView - * Adds the ability for single level grouping to the grid. A {@link Ext.data.GroupingStore GroupingStore} - * must be used to enable grouping. Some grouping characteristics may also be configured at the - * {@link Ext.grid.Column Column level}
      - *
    • {@link Ext.grid.Column#emptyGroupText emptyGroupText}
    • - *
    • {@link Ext.grid.Column#groupable groupable}
    • - *
    • {@link Ext.grid.Column#groupName groupName}
    • - *
    • {@link Ext.grid.Column#groupRender groupRender}
    • - *
    - *

    Sample usage:

    - *
    
    -var grid = new Ext.grid.GridPanel({
    -    // A groupingStore is required for a GroupingView
    -    store: new {@link Ext.data.GroupingStore}({
    -        autoDestroy: true,
    -        reader: reader,
    -        data: xg.dummyData,
    -        sortInfo: {field: 'company', direction: 'ASC'},
    -        {@link Ext.data.GroupingStore#groupOnSort groupOnSort}: true,
    -        {@link Ext.data.GroupingStore#remoteGroup remoteGroup}: true,
    -        {@link Ext.data.GroupingStore#groupField groupField}: 'industry'
    -    }),
    -    colModel: new {@link Ext.grid.ColumnModel}({
    -        columns:[
    -            {id:'company',header: 'Company', width: 60, dataIndex: 'company'},
    -            // {@link Ext.grid.Column#groupable groupable}, {@link Ext.grid.Column#groupName groupName}, {@link Ext.grid.Column#groupRender groupRender} are also configurable at column level
    -            {header: 'Price', renderer: Ext.util.Format.usMoney, dataIndex: 'price', {@link Ext.grid.Column#groupable groupable}: false},
    -            {header: 'Change', dataIndex: 'change', renderer: Ext.util.Format.usMoney},
    -            {header: 'Industry', dataIndex: 'industry'},
    -            {header: 'Last Updated', renderer: Ext.util.Format.dateRenderer('m/d/Y'), dataIndex: 'lastChange'}
    -        ],
    -        defaults: {
    -            sortable: true,
    -            menuDisabled: false,
    -            width: 20
    -        }
    -    }),
    -
    -    view: new Ext.grid.GroupingView({
    -        {@link Ext.grid.GridView#forceFit forceFit}: true,
    -        // custom grouping text template to display the number of items per group
    -        {@link #groupTextTpl}: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})'
    -    }),
    -
    -    frame:true,
    -    width: 700,
    -    height: 450,
    -    collapsible: true,
    -    animCollapse: false,
    -    title: 'Grouping Example',
    -    iconCls: 'icon-grid',
    -    renderTo: document.body
    -});
    - * 
    - * @constructor - * @param {Object} config - */ -Ext.grid.GroupingView = Ext.extend(Ext.grid.GridView, { - - /** - * @cfg {String} groupByText Text displayed in the grid header menu for grouping by a column - * (defaults to 'Group By This Field'). - */ - groupByText : 'Group By This Field', - /** - * @cfg {String} showGroupsText Text displayed in the grid header for enabling/disabling grouping - * (defaults to 'Show in Groups'). - */ - showGroupsText : 'Show in Groups', - /** - * @cfg {Boolean} hideGroupedColumn true to hide the column that is currently grouped (defaults to false) - */ - hideGroupedColumn : false, - /** - * @cfg {Boolean} showGroupName If true will display a prefix plus a ': ' before the group field value - * in the group header line. The prefix will consist of the {@link Ext.grid.Column#groupName groupName} - * (or the configured {@link Ext.grid.Column#header header} if not provided) configured in the - * {@link Ext.grid.Column} for each set of grouped rows (defaults to true). - */ - showGroupName : true, - /** - * @cfg {Boolean} startCollapsed true to start all groups collapsed (defaults to false) - */ - startCollapsed : false, - /** - * @cfg {Boolean} enableGrouping false to disable grouping functionality (defaults to true) - */ - enableGrouping : true, - /** - * @cfg {Boolean} enableGroupingMenu true to enable the grouping control in the column menu (defaults to true) - */ - enableGroupingMenu : true, - /** - * @cfg {Boolean} enableNoGroups true to allow the user to turn off grouping (defaults to true) - */ - enableNoGroups : true, - /** - * @cfg {String} emptyGroupText The text to display when there is an empty group value (defaults to '(None)'). - * May also be specified per column, see {@link Ext.grid.Column}.{@link Ext.grid.Column#emptyGroupText emptyGroupText}. - */ - emptyGroupText : '(None)', - /** - * @cfg {Boolean} ignoreAdd true to skip refreshing the view when new rows are added (defaults to false) - */ - ignoreAdd : false, - /** - * @cfg {String} groupTextTpl The template used to render the group header (defaults to '{text}'). - * This is used to format an object which contains the following properties: - *
      - *
    • group : String

      The rendered value of the group field. - * By default this is the unchanged value of the group field. If a {@link Ext.grid.Column#groupRenderer groupRenderer} - * is specified, it is the result of a call to that function.

    • - *
    • gvalue : Object

      The raw value of the group field.

    • - *
    • text : String

      The configured header (as described in {@link #showGroupName}) - * if {@link #showGroupName} is true) plus the rendered group field value.

    • - *
    • groupId : String

      A unique, generated ID which is applied to the - * View Element which contains the group.

    • - *
    • startRow : Number

      The row index of the Record which caused group change.

    • - *
    • rs : Array

      Contains a single element: The Record providing the data - * for the row which caused group change.

    • - *
    • cls : String

      The generated class name string to apply to the group header Element.

    • - *
    • style : String

      The inline style rules to apply to the group header Element.

    • - *

    - * See {@link Ext.XTemplate} for information on how to format data using a template. Possible usage:
    
    -var grid = new Ext.grid.GridPanel({
    -    ...
    -    view: new Ext.grid.GroupingView({
    -        groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})'
    -    }),
    -});
    -     * 
    - */ - groupTextTpl : '{text}', - - /** - * @cfg {String} groupMode Indicates how to construct the group identifier. 'value' constructs the id using - * raw value, 'display' constructs the id using the rendered value. Defaults to 'value'. - */ - groupMode: 'value', - - /** - * @cfg {Function} groupRenderer This property must be configured in the {@link Ext.grid.Column} for - * each column. - */ - - // private - gidSeed : 1000, - - // private - initTemplates : function(){ - Ext.grid.GroupingView.superclass.initTemplates.call(this); - this.state = {}; - - var sm = this.grid.getSelectionModel(); - sm.on(sm.selectRow ? 'beforerowselect' : 'beforecellselect', - this.onBeforeRowSelect, this); - - if(!this.startGroup){ - this.startGroup = new Ext.XTemplate( - '
    ', - '
    ', this.groupTextTpl ,'
    ', - '
    ' - ); - } - this.startGroup.compile(); - this.endGroup = '
    '; - }, - - // private - findGroup : function(el){ - return Ext.fly(el).up('.x-grid-group', this.mainBody.dom); - }, - - // private - getGroups : function(){ - return this.hasRows() ? this.mainBody.dom.childNodes : []; - }, - - // private - onAdd : function(){ - if(this.enableGrouping && !this.ignoreAdd){ - var ss = this.getScrollState(); - this.refresh(); - this.restoreScroll(ss); - }else if(!this.enableGrouping){ - Ext.grid.GroupingView.superclass.onAdd.apply(this, arguments); - } - }, - - // private - onRemove : function(ds, record, index, isUpdate){ - Ext.grid.GroupingView.superclass.onRemove.apply(this, arguments); - var g = document.getElementById(record._groupId); - if(g && g.childNodes[1].childNodes.length < 1){ - Ext.removeNode(g); - } - this.applyEmptyText(); - }, - - // private - refreshRow : function(record){ - if(this.ds.getCount()==1){ - this.refresh(); - }else{ - this.isUpdating = true; - Ext.grid.GroupingView.superclass.refreshRow.apply(this, arguments); - this.isUpdating = false; - } - }, - - // private - beforeMenuShow : function(){ - var item, items = this.hmenu.items, disabled = this.cm.config[this.hdCtxIndex].groupable === false; - if((item = items.get('groupBy'))){ - item.setDisabled(disabled); - } - if((item = items.get('showGroups'))){ - item.setDisabled(disabled); - item.setChecked(!!this.getGroupField(), true); - } - }, - - // private - renderUI : function(){ - Ext.grid.GroupingView.superclass.renderUI.call(this); - this.mainBody.on('mousedown', this.interceptMouse, this); - - if(this.enableGroupingMenu && this.hmenu){ - this.hmenu.add('-',{ - itemId:'groupBy', - text: this.groupByText, - handler: this.onGroupByClick, - scope: this, - iconCls:'x-group-by-icon' - }); - if(this.enableNoGroups){ - this.hmenu.add({ - itemId:'showGroups', - text: this.showGroupsText, - checked: true, - checkHandler: this.onShowGroupsClick, - scope: this - }); - } - this.hmenu.on('beforeshow', this.beforeMenuShow, this); - } - }, - - // private - onGroupByClick : function(){ - this.grid.store.groupBy(this.cm.getDataIndex(this.hdCtxIndex)); - this.beforeMenuShow(); // Make sure the checkboxes get properly set when changing groups - }, - - // private - onShowGroupsClick : function(mi, checked){ - if(checked){ - this.onGroupByClick(); - }else{ - this.grid.store.clearGrouping(); - } - }, - - /** - * Toggles the specified group if no value is passed, otherwise sets the expanded state of the group to the value passed. - * @param {String} groupId The groupId assigned to the group (see getGroupId) - * @param {Boolean} expanded (optional) - */ - toggleGroup : function(group, expanded){ - this.grid.stopEditing(true); - group = Ext.getDom(group); - var gel = Ext.fly(group); - expanded = expanded !== undefined ? - expanded : gel.hasClass('x-grid-group-collapsed'); - - this.state[gel.dom.id] = expanded; - gel[expanded ? 'removeClass' : 'addClass']('x-grid-group-collapsed'); - }, - - /** - * Toggles all groups if no value is passed, otherwise sets the expanded state of all groups to the value passed. - * @param {Boolean} expanded (optional) - */ - toggleAllGroups : function(expanded){ - var groups = this.getGroups(); - for(var i = 0, len = groups.length; i < len; i++){ - this.toggleGroup(groups[i], expanded); - } - }, - - /** - * Expands all grouped rows. - */ - expandAllGroups : function(){ - this.toggleAllGroups(true); - }, - - /** - * Collapses all grouped rows. - */ - collapseAllGroups : function(){ - this.toggleAllGroups(false); - }, - - // private - interceptMouse : function(e){ - var hd = e.getTarget('.x-grid-group-hd', this.mainBody); - if(hd){ - e.stopEvent(); - this.toggleGroup(hd.parentNode); - } - }, - - // private - getGroup : function(v, r, groupRenderer, rowIndex, colIndex, ds){ - var g = groupRenderer ? groupRenderer(v, {}, r, rowIndex, colIndex, ds) : String(v); - if(g === '' || g === ' '){ - g = this.cm.config[colIndex].emptyGroupText || this.emptyGroupText; - } - return g; - }, - - // private - getGroupField : function(){ - return this.grid.store.getGroupState(); - }, - - // private - afterRender : function(){ - Ext.grid.GroupingView.superclass.afterRender.call(this); - if(this.grid.deferRowRender){ - this.updateGroupWidths(); - } - }, - - // private - renderRows : function(){ - var groupField = this.getGroupField(); - var eg = !!groupField; - // if they turned off grouping and the last grouped field is hidden - if(this.hideGroupedColumn) { - var colIndex = this.cm.findColumnIndex(groupField); - if(!eg && this.lastGroupField !== undefined) { - this.mainBody.update(''); - this.cm.setHidden(this.cm.findColumnIndex(this.lastGroupField), false); - delete this.lastGroupField; - }else if (eg && this.lastGroupField === undefined) { - this.lastGroupField = groupField; - this.cm.setHidden(colIndex, true); - }else if (eg && this.lastGroupField !== undefined && groupField !== this.lastGroupField) { - this.mainBody.update(''); - var oldIndex = this.cm.findColumnIndex(this.lastGroupField); - this.cm.setHidden(oldIndex, false); - this.lastGroupField = groupField; - this.cm.setHidden(colIndex, true); - } - } - return Ext.grid.GroupingView.superclass.renderRows.apply( - this, arguments); - }, - - // private - doRender : function(cs, rs, ds, startRow, colCount, stripe){ - if(rs.length < 1){ - return ''; - } - var groupField = this.getGroupField(), - colIndex = this.cm.findColumnIndex(groupField), - g; - - this.enableGrouping = !!groupField; - - if(!this.enableGrouping || this.isUpdating){ - return Ext.grid.GroupingView.superclass.doRender.apply( - this, arguments); - } - var gstyle = 'width:' + this.getTotalWidth() + ';', - gidPrefix = this.grid.getGridEl().id, - cfg = this.cm.config[colIndex], - groupRenderer = cfg.groupRenderer || cfg.renderer, - prefix = this.showGroupName ? (cfg.groupName || cfg.header)+': ' : '', - groups = [], - curGroup, i, len, gid; - - for(i = 0, len = rs.length; i < len; i++){ - var rowIndex = startRow + i, - r = rs[i], - gvalue = r.data[groupField]; - - g = this.getGroup(gvalue, r, groupRenderer, rowIndex, colIndex, ds); - if(!curGroup || curGroup.group != g){ - gid = this.constructId(gvalue, gidPrefix, groupField, colIndex); - // if state is defined use it, however state is in terms of expanded - // so negate it, otherwise use the default. - var isCollapsed = typeof this.state[gid] !== 'undefined' ? !this.state[gid] : this.startCollapsed; - var gcls = isCollapsed ? 'x-grid-group-collapsed' : ''; - curGroup = { - group: g, - gvalue: gvalue, - text: prefix + g, - groupId: gid, - startRow: rowIndex, - rs: [r], - cls: gcls, - style: gstyle - }; - groups.push(curGroup); - }else{ - curGroup.rs.push(r); - } - r._groupId = gid; - } - - var buf = []; - for(i = 0, len = groups.length; i < len; i++){ - g = groups[i]; - this.doGroupStart(buf, g, cs, ds, colCount); - buf[buf.length] = Ext.grid.GroupingView.superclass.doRender.call( - this, cs, g.rs, ds, g.startRow, colCount, stripe); - - this.doGroupEnd(buf, g, cs, ds, colCount); - } - return buf.join(''); - }, - - /** - * Dynamically tries to determine the groupId of a specific value - * @param {String} value - * @return {String} The group id - */ - getGroupId : function(value){ - var field = this.getGroupField(); - return this.constructId(value, this.grid.getGridEl().id, field, this.cm.findColumnIndex(field)); - }, - - // private - constructId : function(value, prefix, field, idx){ - var cfg = this.cm.config[idx], - groupRenderer = cfg.groupRenderer || cfg.renderer, - val = (this.groupMode == 'value') ? value : this.getGroup(value, {data:{}}, groupRenderer, 0, idx, this.ds); - - return prefix + '-gp-' + field + '-' + Ext.util.Format.htmlEncode(val); - }, - - // private - doGroupStart : function(buf, g, cs, ds, colCount){ - buf[buf.length] = this.startGroup.apply(g); - }, - - // private - doGroupEnd : function(buf, g, cs, ds, colCount){ - buf[buf.length] = this.endGroup; - }, - - // private - getRows : function(){ - if(!this.enableGrouping){ - return Ext.grid.GroupingView.superclass.getRows.call(this); - } - var r = []; - var g, gs = this.getGroups(); - for(var i = 0, len = gs.length; i < len; i++){ - g = gs[i].childNodes[1].childNodes; - for(var j = 0, jlen = g.length; j < jlen; j++){ - r[r.length] = g[j]; - } - } - return r; - }, - - // private - updateGroupWidths : function(){ - if(!this.enableGrouping || !this.hasRows()){ - return; - } - var tw = Math.max(this.cm.getTotalWidth(), this.el.dom.offsetWidth-this.getScrollOffset()) +'px'; - var gs = this.getGroups(); - for(var i = 0, len = gs.length; i < len; i++){ - gs[i].firstChild.style.width = tw; - } - }, - - // private - onColumnWidthUpdated : function(col, w, tw){ - Ext.grid.GroupingView.superclass.onColumnWidthUpdated.call(this, col, w, tw); - this.updateGroupWidths(); - }, - - // private - onAllColumnWidthsUpdated : function(ws, tw){ - Ext.grid.GroupingView.superclass.onAllColumnWidthsUpdated.call(this, ws, tw); - this.updateGroupWidths(); - }, - - // private - onColumnHiddenUpdated : function(col, hidden, tw){ - Ext.grid.GroupingView.superclass.onColumnHiddenUpdated.call(this, col, hidden, tw); - this.updateGroupWidths(); - }, - - // private - onLayout : function(){ - this.updateGroupWidths(); - }, - - // private - onBeforeRowSelect : function(sm, rowIndex){ - if(!this.enableGrouping){ - return; - } - var row = this.getRow(rowIndex); - if(row && !row.offsetParent){ - var g = this.findGroup(row); - this.toggleGroup(g, true); - } - } -}); -// private -Ext.grid.GroupingView.GROUP_ID = 1000; \ No newline at end of file + +Ext.grid.GroupingView.GROUP_ID = 1000;