diff --git a/source/LexicalParser.js b/source/LexicalParser.js index e710efa..2a33ac5 100644 --- a/source/LexicalParser.js +++ b/source/LexicalParser.js @@ -1,4 +1,5 @@ -var lex = + +var lex = { InputElementDiv:"||||||||", InputElementRegExp:"||||||||", @@ -101,4 +102,4 @@ function LexicalParser() inputElementRegExp.lastIndex = inputElement.lastIndex; return token; }; -} \ No newline at end of file +} diff --git a/source/Parser.js b/source/Parser.js index d3f8af9..1d20870 100644 --- a/source/Parser.js +++ b/source/Parser.js @@ -1,4 +1,5 @@ -function Parser() + +function Parser() { this.lexicalParser = new LexicalParser(); this.syntacticalParser = new SyntacticalParser(); diff --git a/source/SyntacticalParser.js b/source/SyntacticalParser.js index 426a5b3..1c3532b 100644 --- a/source/SyntacticalParser.js +++ b/source/SyntacticalParser.js @@ -1,4 +1,5 @@ -var rules = + +var rules = { "IdentifierName":[["Identifier"], ["break"], ["do"], ["instanceof"], ["typeof"], ["case"], ["else"], ["new"], ["var"], ["catch"], ["finally"], ["return"], ["void"], ["continue"], ["for"], ["switch"], ["while"], ["debugger"], ["function"], ["this"], ["with"], ["default"], ["if"], ["throw"], ["delete"], ["in"], ["try"]], "Literal":[["NullLiteral"], ["BooleanLiteral"], ["NumericLiteral"], ["StringLiteral"], ["RegularExpressionLiteral"]], @@ -80,24 +81,26 @@ "SourceElements":[["SourceElement"], ["SourceElements", "SourceElement"]], "SourceElement":[["Statement"], ["FunctionDeclaration"]] }; + function Symbol(symbolName, token) { this.name = symbolName; this.token = token; - this.childNodes = []; - this. toString = - function(indent) - { - if(!indent) - indent = ""; - if(this.childNodes.length == 1) - return this.childNodes[0]. toString (indent); - var str = indent + this.name + (this.token != undefined && this.name != this.token ? ":" + this.token:"") + "\n"; - for(var i = 0;i < this.childNodes.length;i++) - str += this.childNodes[i]. toString (indent + " "); - return str; - }; + this.childNodes = []; } + +Symbol.prototype.toString = function(indent) +{ + if(!indent) + indent = ""; + if(this.childNodes.length == 1) + return this.childNodes[0]. toString (indent); + var str = indent + this.name + (this.token != undefined && this.name != this.token ? ":" + this.token:"") + "\n"; + for(var i = 0;i < this.childNodes.length;i++) + str += this.childNodes[i]. toString (indent + " "); + return str; +}; + function SyntacticalParser() { var currentRule; diff --git a/test/JSinJS-all.js b/test/JSinJS-all.js new file mode 100644 index 0000000..03b23f4 --- /dev/null +++ b/test/JSinJS-all.js @@ -0,0 +1,424 @@ + +var lex = +{ + InputElementDiv:"||||||||", + InputElementRegExp:"||||||||", + ReservedWord:"|||", + WhiteSpace:/[\t\v\f\u0020\u00A0\u1680\u180E\u2000-\u200A\u202F\u205f\u3000\uFEFF]/, + LineTerminator:/[\n\r\u2028\u2029]/, + Comment:"|", + SingleLineComment:/\/\/[^\n\r\u2028\u2029]*/, + MultiLineComment:/\/\*(?:[^*]|\*[^\/])*\*?\*\//, + Keyword:/break(?![_$a-zA-Z0-9])|else(?![_$a-zA-Z0-9])|new(?![_$a-zA-Z0-9])|var(?![_$a-zA-Z0-9])|case(?![_$a-zA-Z0-9])|finally(?![_$a-zA-Z0-9])|return(?![_$a-zA-Z0-9])|void(?![_$a-zA-Z0-9])|catch(?![_$a-zA-Z0-9])|for(?![_$a-zA-Z0-9])|switch(?![_$a-zA-Z0-9])|while(?![_$a-zA-Z0-9])|continue(?![_$a-zA-Z0-9])|function(?![_$a-zA-Z0-9])|this(?![_$a-zA-Z0-9])|with(?![_$a-zA-Z0-9])|default(?![_$a-zA-Z0-9])|if(?![_$a-zA-Z0-9])|throw(?![_$a-zA-Z0-9])|delete(?![_$a-zA-Z0-9])|in(?![_$a-zA-Z0-9])|try(?![_$a-zA-Z0-9])|do(?![_$a-zA-Z0-9])|instanceof(?![_$a-zA-Z0-9])|typeof(?![_$a-zA-Z0-9])/, + FutureReservedWord:/abstract(?![_$a-zA-Z0-9])|enum(?![_$a-zA-Z0-9])|int(?![_$a-zA-Z0-9])|short(?![_$a-zA-Z0-9])|boolean(?![_$a-zA-Z0-9])|export(?![_$a-zA-Z0-9])|interface(?![_$a-zA-Z0-9])|static(?![_$a-zA-Z0-9])|byte(?![_$a-zA-Z0-9])|extends(?![_$a-zA-Z0-9])|long(?![_$a-zA-Z0-9])|super(?![_$a-zA-Z0-9])|char(?![_$a-zA-Z0-9])|final(?![_$a-zA-Z0-9])|native(?![_$a-zA-Z0-9])|synchronized(?![_$a-zA-Z0-9])|class(?![_$a-zA-Z0-9])|float(?![_$a-zA-Z0-9])|package(?![_$a-zA-Z0-9])|throws(?![_$a-zA-Z0-9])|const(?![_$a-zA-Z0-9])|goto|(?![_$a-zA-Z0-9])private(?![_$a-zA-Z0-9])|transient(?![_$a-zA-Z0-9])|debugger(?![_$a-zA-Z0-9])|implements(?![_$a-zA-Z0-9])|(?![_$a-zA-Z0-9])protected(?![_$a-zA-Z0-9])|volatile(?![_$a-zA-Z0-9])|double(?![_$a-zA-Z0-9])|import(?![_$a-zA-Z0-9])|public(?![_$a-zA-Z0-9])/, + NullLiteral:/null(?![_$a-zA-Z0-9])/, + BooleanLiteral:/(?:true|false)(?![_$a-zA-Z0-9])/, + Identifier:/[_$a-zA-Z][_$a-zA-Z0-9]*/, + Punctuator:/>>>=|>>=|<<=|===|!==|>>>|<<|%=|\*=|-=|\+=|<=|>=|==|!=|\^=|\|=|\|\||&&|&=|>>|\+\+|--|\:|}|\*|&|\||\^|!|~|-|\+|\?|%|=|>|<|,|;|\.(?![0-9])|\]|\[|\)|\(|{/, + DivPunctuator:/\/=|\//, + NumericLiteral:/(?:0[xX][0-9a-fA-F]*|\.[0-9]+|(?:[1-9]+[0-9]*|0)(?:\.[0-9]*|\.)?)(?:[eE][+-]{0,1}[0-9]+)?(?![_$a-zA-Z0-9])/, + StringLiteral:/"(?:[^"\n\\\r\u2028\u2029]|\\(?:['"\\bfnrtv\n\r\u2028\u2029]|\r\n)|\\x[0-9a-fA-F]{2}|\\u[0-9a-fA-F]{4}|\\[^0-9ux'"\\bfnrtv\n\\\r\u2028\u2029])*"|'(?:[^'\n\\\r\u2028\u2029]|\\(?:['"\\bfnrtv\n\r\u2028\u2029]|\r\n)|\\x[0-9a-fA-F]{2}|\\u[0-9a-fA-F]{4}|\\[^0-9ux'"\\bfnrtv\n\\\r\u2028\u2029])*'/, RegularExpressionLiteral:/\/(?:\[(?:\\[\s\S]|[^\]])*\]|[^*\/\\\n\r\u2028\u2029]|\\[^\n\r\u2028\u2029])(?:\[(?:\\[\s\S]|[^\]])*\]|[^\/\\\n\r\u2028\u2029]|\\[^\n\r\u2028\u2029])*\/[0-9a-zA-Z]*/ +}; +function XRegExp(xregexps, rootname, flag) +{ + var expnames = [rootname]; + function buildRegExp(source) + { + var regexp = new RegExp; + regexp.compile(source.replace(/<([^>]+)>/g, + function(all, expname) + { + if(!xregexps[expname]) + return ""; + expnames.push(expname); + if(xregexps[expname]instanceof RegExp) + return "(" + xregexps[expname].source + ")"; + return "(" + buildRegExp(xregexps[expname]).source + ")"; + }), flag); + return regexp; + } + var regexp = buildRegExp(xregexps[rootname]); + this.exec = + function(string) + { + var matches = regexp.exec(string); + if(matches == null) + return null; + var result = new String(matches[0]); + for(var i = 0;i < expnames.length;i++) + if(matches[i]) + result[expnames[i]] = matches[i]; + return result; + }; + Object.defineProperty(this, "lastIndex", + { + "get": + function() + { + return regexp.lastIndex; + }, "set": + function(v) + { + regexp.lastIndex = v; + } + + }); +} +function LexicalParser() +{ + var inputElementDiv = new XRegExp(lex, "InputElementDiv", "g"); + var inputElementRegExp = new XRegExp(lex, "InputElementRegExp", "g"); + var source; + Object.defineProperty(this, "source", + { + "get": + function() + { + return source; + }, "set": + function(v) + { + source = v; + inputElementDiv.lastIndex = 0; + inputElementRegExp.lastIndex = 0; + } + + }); + this.getNextToken = + function(useDiv) + { + var lastIndex = inputElementDiv.lastIndex; + var inputElement; + if(useDiv) + inputElement = inputElementDiv; + else + inputElement = inputElementRegExp; + var token = inputElement.exec(source); + if(token && inputElement.lastIndex - lastIndex > token.length) + { + throw new SyntaxError("Unexpected token ILLEGAL"); + } + inputElementDiv.lastIndex = inputElement.lastIndex; + inputElementRegExp.lastIndex = inputElement.lastIndex; + return token; + }; +} + + +var rules = +{ + "IdentifierName":[["Identifier"], ["break"], ["do"], ["instanceof"], ["typeof"], ["case"], ["else"], ["new"], ["var"], ["catch"], ["finally"], ["return"], ["void"], ["continue"], ["for"], ["switch"], ["while"], ["debugger"], ["function"], ["this"], ["with"], ["default"], ["if"], ["throw"], ["delete"], ["in"], ["try"]], + "Literal":[["NullLiteral"], ["BooleanLiteral"], ["NumericLiteral"], ["StringLiteral"], ["RegularExpressionLiteral"]], + "PrimaryExpression":[["this"], ["Identifier"], ["Literal"], ["ArrayLiteral"], ["ObjectLiteral"], ["(", "Expression", ")"]], + "ArrayLiteral":[["[", "]"], ["[", "Elision", "]"], ["[", "ElementList", "]"], ["[", "ElementList", ",", "]"], ["[", "ElementList", ",", "Elision", "]"]], + "ElementList":[["AssignmentExpression"], ["Elision", "AssignmentExpression"], ["ElementList", ",", "AssignmentExpression"], ["ElementList", ",", "Elision", "AssignmentExpression"]], + "Elision":[[","], ["Elision", ","]], + "ObjectLiteral":[["{", "}"], ["{", "PropertyNameAndValueList", "}"], ["{", "PropertyNameAndValueList", ",", "}"]], + "PropertyNameAndValueList":[["PropertyAssignment"], ["PropertyNameAndValueList", ",", "PropertyAssignment"]], + "PropertyAssignment":[["PropertyName", ":", "AssignmentExpression"], ["get", "PropertyName", "(", ")", "{", "FunctionBody", "}"], ["set", "PropertyName", "(", "PropertySetParameterList", ")", "{", "FunctionBody", "}"]], + "PropertyName":[["IdentifierName"], ["StringLiteral"], ["NumericLiteral"]], + "PropertySetParameterList":[["Identifier"]], + "MemberExpression":[["PrimaryExpression"], ["FunctionExpression"], ["MemberExpression", "[", "Expression", "]"], ["MemberExpression", ".", "IdentifierName"], ["new", "MemberExpression", "Arguments"]], + "NewExpression":[["MemberExpression"], ["new", "NewExpression"]], + "CallExpression":[["MemberExpression", "Arguments"], ["CallExpression", "Arguments"], ["CallExpression", "[", "Expression", "]"], ["CallExpression", ".", "IdentifierName"]], + "Arguments":[["(", ")"], ["(", "ArgumentList", ")"]], + "ArgumentList":[["AssignmentExpression"], ["ArgumentList", ",", "AssignmentExpression"]], + "LeftHandSideExpression":[["NewExpression"], ["CallExpression"]], + "PostfixExpression":[["LeftHandSideExpression"], ["LeftHandSideExpression", "[noLineTerminator]", "++"], ["LeftHandSideExpression", "[noLineTerminator]", "--"]], + "UnaryExpression":[["PostfixExpression"], ["delete", "UnaryExpression"], ["void", "UnaryExpression"], ["typeof", "UnaryExpression"], ["++", "UnaryExpression"], ["--", "UnaryExpression"], ["+", "UnaryExpression"], ["-", "UnaryExpression"], ["~", "UnaryExpression"], ["!", "UnaryExpression"]], + "MultiplicativeExpression":[["MultiplicativeExpression", "[div]", "/", "UnaryExpression"], ["UnaryExpression"], ["MultiplicativeExpression", "*", "UnaryExpression"], ["MultiplicativeExpression", "%", "UnaryExpression"]], + "AdditiveExpression":[["MultiplicativeExpression"], ["AdditiveExpression", "+", "MultiplicativeExpression"], ["AdditiveExpression", "-", "MultiplicativeExpression"]], + "ShiftExpression":[["AdditiveExpression"], ["ShiftExpression", "<<", "AdditiveExpression"], ["ShiftExpression", ">>", "AdditiveExpression"], ["ShiftExpression", ">>>", "AdditiveExpression"]], + "RelationalExpression":[["ShiftExpression"], ["RelationalExpression", "<", "ShiftExpression"], ["RelationalExpression", ">", "ShiftExpression"], ["RelationalExpression", "<=", "ShiftExpression"], ["RelationalExpression", ">=", "ShiftExpression"], ["RelationalExpression", "instanceof", "ShiftExpression"], ["RelationalExpression", "in", "ShiftExpression"]], + "RelationalExpressionNoIn":[["ShiftExpression"], ["RelationalExpressionNoIn", "<", "ShiftExpression"], ["RelationalExpressionNoIn", ">", "ShiftExpression"], ["RelationalExpressionNoIn", "<=", "ShiftExpression"], ["RelationalExpressionNoIn", ">=", "ShiftExpression"], ["RelationalExpressionNoIn", "instanceof", "ShiftExpression"]], + "EqualityExpression":[["RelationalExpression"], ["EqualityExpression", "==", "RelationalExpression"], ["EqualityExpression", "!=", "RelationalExpression"], ["EqualityExpression", "===", "RelationalExpression"], ["EqualityExpression", "!==", "RelationalExpression"]], + "EqualityExpressionNoIn":[["RelationalExpressionNoIn"], ["EqualityExpressionNoIn", "==", "RelationalExpressionNoIn"], ["EqualityExpressionNoIn", "!=", "RelationalExpressionNoIn"], ["EqualityExpressionNoIn", "===", "RelationalExpressionNoIn"], ["EqualityExpressionNoIn", "!==", "RelationalExpressionNoIn"]], + "BitwiseANDExpression":[["EqualityExpression"], ["BitwiseANDExpression", "&", "EqualityExpression"]], + "BitwiseANDExpressionNoIn":[["EqualityExpressionNoIn"], ["BitwiseANDExpressionNoIn", "&", "EqualityExpressionNoIn"]], + "BitwiseXORExpression":[["BitwiseANDExpression"], ["BitwiseXORExpression", "^", "BitwiseANDExpression"]], + "BitwiseXORExpressionNoIn":[["BitwiseANDExpressionNoIn"], ["BitwiseXORExpressionNoIn", "^", "BitwiseANDExpressionNoIn"]], + "BitwiseORExpression":[["BitwiseXORExpression"], ["BitwiseORExpression", "|", "BitwiseXORExpression"]], + "BitwiseORExpressionNoIn":[["BitwiseXORExpressionNoIn"], ["BitwiseORExpressionNoIn", "|", "BitwiseXORExpressionNoIn"]], + "LogicalANDExpression":[["BitwiseORExpression"], ["LogicalANDExpression", "&&", "BitwiseORExpression"]], + "LogicalANDExpressionNoIn":[["BitwiseORExpressionNoIn"], ["LogicalANDExpressionNoIn", "&&", "BitwiseORExpressionNoIn"]], + "LogicalORExpression":[["LogicalANDExpression"], ["LogicalORExpression", "||", "LogicalANDExpression"]], + "LogicalORExpressionNoIn":[["LogicalANDExpressionNoIn"], ["LogicalORExpressionNoIn", "||", "LogicalANDExpressionNoIn"]], + "ConditionalExpression":[["LogicalORExpression"], ["LogicalORExpression", "?", "AssignmentExpression", ":", "AssignmentExpression"]], + "ConditionalExpressionNoIn":[["LogicalORExpressionNoIn"], ["LogicalORExpressionNoIn", "?", "AssignmentExpressionNoIn", ":", "AssignmentExpressionNoIn"]], + "AssignmentExpression":[["ConditionalExpression"], ["LeftHandSideExpression", "[div]", "AssignmentOperator", "AssignmentExpression"]], + "AssignmentExpressionNoIn":[["LeftHandSideExpression", "[div]", "AssignmentOperator", "AssignmentExpressionNoIn"], ["ConditionalExpressionNoIn"]], + "AssignmentOperator":[["="], ["*="], ["/="], ["%="], ["+="], ["-="], ["<<="], [">>="], [">>>="], ["&="], ["^="], ["|="]], + "Expression":[["AssignmentExpression"], ["Expression", ",", "AssignmentExpression"]], + "ExpressionNoIn":[["AssignmentExpressionNoIn"], ["ExpressionNoIn", ",", "AssignmentExpressionNoIn"]], + "Statement":[["Block"], ["VariableStatement"], ["EmptyStatement"], ["ExpressionStatement"], ["IfStatement"], ["IterationStatement"], ["ContinueStatement"], ["BreakStatement"], ["ReturnStatement"], ["WithStatement"], ["LabelledStatement"], ["SwitchStatement"], ["ThrowStatement"], ["TryStatement"], ["DebuggerStatement"]], + "Block":[["{", "}"], ["{", "StatementList", "}"]], + "StatementList":[["FunctionDeclaration"], ["Statement"], ["StatementList", "Statement"], ["StatementList", "FunctionDeclaration"]], + "VariableStatement":[["var", "VariableDeclarationList", ";"]], + "VariableDeclarationList":[["VariableDeclaration"], ["VariableDeclarationList", ",", "VariableDeclaration"]], + "VariableDeclarationListNoIn":[["VariableDeclarationNoIn"], ["VariableDeclarationListNoIn", ",", "VariableDeclarationNoIn"]], + "VariableDeclaration":[["Identifier"], ["Identifier", "Initialiser"]], + "VariableDeclarationNoIn":[["Identifier"], ["Identifier", "InitialiserNoIn"]], + "Initialiser":[["=", "AssignmentExpression"]], + "InitialiserNoIn":[["=", "AssignmentExpressionNoIn"]], + "EmptyStatement":[[";"]], + "ExpressionStatement":[["Expression", "[lookaheadno{{,function}]", ";"]], + "IfStatement":[["if", "(", "Expression", ")", "Statement", "else", "Statement"], ["if", "(", "Expression", ")", "Statement"]], + "IterationStatement":[["do", "Statement", "while", "(", "Expression", ")", ";"], ["while", "(", "Expression", ")", "Statement"], ["for", "(", "ExpressionNoIn", ";", "Expression", ";", "Expression", ")", "Statement"], ["for", "(", ";", "Expression", ";", "Expression", ")", "Statement"], ["for", "(", "ExpressionNoIn", ";", ";", "Expression", ")", "Statement"], ["for", "(", ";", ";", "Expression", ")", "Statement"], ["for", "(", "ExpressionNoIn", ";", "Expression", ";", ")", "Statement"], ["for", "(", ";", "Expression", ";", ")", "Statement"], ["for", "(", "ExpressionNoIn", ";", ";", ")", "Statement"], ["for", "(", ";", ";", ")", "Statement"], ["for", "(", "var", "VariableDeclarationListNoIn", ";", "Expression", ";", "Expression", ")", "Statement"], ["for", "(", "var", "VariableDeclarationListNoIn", ";", ";", "Expression", ")", "Statement"], ["for", "(", "var", "VariableDeclarationListNoIn", ";", "Expression", ";", ")", "Statement"], ["for", "(", "var", "VariableDeclarationListNoIn", ";", ";", ")", "Statement"], ["for", "(", "LeftHandSideExpression", "in", "Expression", ")", "Statement"], ["for", "(", "var", "VariableDeclarationNoIn", "in", "Expression", ")", "Statement"]], + "ContinueStatement":[["continue", ";"], ["continue", "[noLineTerminator]", "Identifier", ";"]], + "BreakStatement":[["break", ";"], ["break", "[noLineTerminator]", "Identifier", ";"]], + "ReturnStatement":[["return", ";"], ["return", "[noLineTerminator]", "Expression", ";"]], + "WithStatement":[["with", "(", "Expression", ")", "Statement"]], + "SwitchStatement":[["switch", "(", "Expression", ")", "CaseBlock"]], + "CaseBlock":[["{", "}"], ["{", "CaseClauses", "}"], ["{", "CaseClauses", "DefaultClause", "}"], ["{", "DefaultClause", "}"], ["{", "CaseClauses", "DefaultClause", "CaseClauses", "}"], ["{", "DefaultClause", "CaseClauses", "}"]], + "CaseClauses":[["CaseClause"], ["CaseClauses", "CaseClause"]], + "CaseClause":[["case", "Expression", ":", "StatementList"], ["case", "Expression", ":"]], + "DefaultClause":[["default", ":", "StatementList"], ["default", ":"]], + "LabelledStatement":[["Identifier", ":", "Statement"]], + "ThrowStatement":[["throw", "[noLineTerminator]", "Expression", ";"]], + "TryStatement":[["try", "Block", "Catch"], ["try", "Block", "Finally"], ["try", "Block", "Catch", "Finally"]], + "Catch":[["catch", "(", "Identifier", ")", "Block"]], + "Finally":[["finally", "Block"]], + "DebuggerStatement":[["debugger", ";"]], + "FunctionDeclaration":[["function", "Identifier", "(", "FormalParameterList", ")", "{", "FunctionBody", "}"], ["function", "Identifier", "(", ")", "{", "FunctionBody", "}"]], + "FunctionExpression":[["function", "Identifier", "(", "FormalParameterList", ")", "{", "FunctionBody", "}"], ["function", "(", "FormalParameterList", ")", "{", "FunctionBody", "}"], ["function", "Identifier", "(", ")", "{", "FunctionBody", "}"], ["function", "(", ")", "{", "FunctionBody", "}"]], + "FormalParameterList":[["Identifier"], ["FormalParameterList", ",", "Identifier"]], + "FunctionBody":[["SourceElements"], [""]], + "Program":[["SourceElements"], [""]], + "SourceElements":[["SourceElement"], ["SourceElements", "SourceElement"]], "SourceElement":[["Statement"], ["FunctionDeclaration"]] + +}; + +function Symbol(symbolName, token) +{ + this.name = symbolName; + this.token = token; + this.childNodes = []; +} + +Symbol.prototype.toString = function(indent) +{ + if(!indent) + indent = ""; + if(this.childNodes.length == 1) + return this.childNodes[0]. toString (indent); + var str = indent + this.name + (this.token != undefined && this.name != this.token ? ":" + this.token:"") + "\n"; + for(var i = 0;i < this.childNodes.length;i++) + str += this.childNodes[i]. toString (indent + " "); + return str; +}; + +function SyntacticalParser() +{ + var currentRule; + var root = + {Program:"$" + + }; + var hash = + { + + }; + function visitNode(node) + { + hash[JSON.stringify(node)] = node; + node.$closure = true; + var queue = Object.getOwnPropertyNames(node); + while(queue.length) + { + var symbolName = queue.shift(); + if(!rules[symbolName]) + continue; + rules[symbolName].forEach( + function(rule) + { + if(node[symbolName].$lookahead && node[symbolName].$lookahead.some( + function(e) + { + return e == rule[0]; + })) + return; + if(!node[rule[0]]) + queue.push(rule[0]); + var rulenode = node; + var lastnode = null; + rule.forEach( + function(symbol) + { + if(symbol.match(/\[([^\]]+)\]/)) + { + if(RegExp.$1 == "lookaheadno{{,function}") + { + rulenode["$lookahead"] = ["{", "function"]; + } + else + rulenode["$" + RegExp.$1] = true; + return; + } + if(!rulenode[symbol]) + rulenode[symbol] = + { + + }; + lastnode = rulenode; + rulenode = rulenode[symbol]; + }); + if(node[symbolName].$lookahead) + node[rule[0]].$lookahead = node[symbolName].$lookahead; + if(node[symbolName].$div) + rulenode.$div = true; + rulenode.$reduce = symbolName; + rulenode.$count = rule.filter( + function(e) + { + return!e.match(/\[([^\]]+)\]/); + }).length; + }); + } + for(var p in node) + { + if(typeof node[p] != "object" || p.charAt(0) == "$" || node[p].$closure) + continue; + if(hash[JSON.stringify(node[p])]) + node[p] = hash[JSON.stringify(node[p])]; + else + { + visitNode(node[p]); + } + } + } + visitNode(root); + var symbolStack = []; + var statusStack = [root]; + var current = root; + this.insertSymbol = + function insertSymbol(symbol, haveLineTerminator) + { + while(!current[symbol.name] && current["$reduce"]) + { + var count = current["$count"]; + var newsymbol = new Symbol(current["$reduce"]); + while(count--) + newsymbol.childNodes.push(symbolStack.pop()), statusStack.pop(); + current = statusStack[statusStack.length - 1]; + this.insertSymbol(newsymbol); + } + if(current.$noLineTerminator && haveLineTerminator) + { + this.insertSymbol(new Symbol(";", ";")); + return this.insertSymbol(symbol); + } + if(!current[symbol.name] && current[";"] && current[";"]["$reduce"] && (haveLineTerminator || symbol.name == "}")) + { + this.insertSymbol(new Symbol(";", ";")); + return this.insertSymbol(symbol); + } + current = current[symbol.name]; + symbolStack.push(symbol), statusStack.push(current); + if(!current) + throw new Error(); + return current.$div; + }; + this.reset = + function() + { + current = root; + symbolStack = []; + statusStack = [root]; + }; + Object.defineProperty(this, "grammarTree", + {"get": + function() + { + try + { + while(current["$reduce"]) + { + var count = current["$count"]; + var newsymbol = new Symbol(current["$reduce"]); + while(count--) + newsymbol.childNodes.push(symbolStack.pop()), statusStack.pop(); + current = statusStack[statusStack.length - 1]; + this.insertSymbol(newsymbol); + } + if(symbolStack.length > 0 && current[";"]) + { + this.insertSymbol(new Symbol(";", ";")); + return this.grammarTree; + } + if(symbolStack.length != 1 || symbolStack[0].name != "Program") + throw new Error(); + }catch(e) + { + throw new SyntaxError("Unexpected end of input"); + } + return symbolStack[0]; + } + + }); +} + + +function Parser() +{ + this.lexicalParser = new LexicalParser(); + this.syntacticalParser = new SyntacticalParser(); + var terminalSymbols = ["NullLiteral", "BooleanLiteral", "NumericLiteral", "StringLiteral", "RegularExpressionLiteral", "RegularExpressionLiteral", "Identifier", "{", "}", "(", ")", "[", "]", ".", ";", ",", "<", ">", "<=", ">=", "==", "!=", "===", "!==", "+", "-", "*", "%", "++", "--", "<<", ">>", ">>>", "&", "|", "^", "!", "~", "&&", "||", "?", ":", "=", "+=", "-=", "*=", "%=", "<<=", ">>=", ">>>=", "&=", "|=", "^=", "/", "/=", "break", "do", "instanceof", "typeof", "case", "else", "new", "var", "catch", "finally", "return", "void", "continue", "for", "switch", "while", "debugger", "function", "this", "with", "default", "if", "throw", "delete", "in", "try", "get", "set"]; + var terminalSymbolIndex = {}; + terminalSymbols.forEach( + function(e) + { + Object.defineProperty(terminalSymbolIndex, e, {}); + }); + + this.parse = + function(source, onInputElement) + { + var token; + var haveLineTerminator = false; + this.lexicalParser.source = source; + var useDiv = false; + while(token = this.lexicalParser.getNextToken(useDiv)) + { + if(onInputElement) + onInputElement(token); + try + { + if((token.Comment && token.Comment.match(/[\n\r\u2028\u2029]/)) || token.LineTerminator) + { + haveLineTerminator = true; + continue; + } + with(this) + if(Object.getOwnPropertyNames(token).some( + function(e) + { + if(terminalSymbolIndex.hasOwnProperty (e)) + { + useDiv = syntacticalParser.insertSymbol(new Symbol(e, token), haveLineTerminator); + haveLineTerminator = false; + return true; + } + else + return false; + })) + continue; + if((token["Keyword"] || token["Punctuator"] || token["DivPunctuator"]) && terminalSymbolIndex.hasOwnProperty (token.toString())) + { + useDiv = this.syntacticalParser.insertSymbol(new Symbol(token.toString(), token), haveLineTerminator); + haveLineTerminator = false; + } + }catch(e) + { + throw new SyntaxError("Unexpected token " + token); + } + } + return this.syntacticalParser.grammarTree; + }; +} + + + +module.exports={ + Parser : Parser +} + diff --git a/test/build-4-node.js b/test/build-4-node.js new file mode 100644 index 0000000..b473d4b --- /dev/null +++ b/test/build-4-node.js @@ -0,0 +1,16 @@ + +var fs = require('fs'); + + +var rootPath='../source'; + +var LexicalParser = fs.readFileSync(rootPath+'/LexicalParser.js','utf-8'); +var SyntacticalParser = fs.readFileSync(rootPath+'/SyntacticalParser.js','utf-8'); +var Parser = fs.readFileSync(rootPath+'/Parser.js','utf-8'); +var patch = fs.readFileSync('./node-patch.js','utf-8'); + +var breakLine='\r\n'; + +var data=[LexicalParser,SyntacticalParser,Parser,patch].join(breakLine); + +fs.writeFileSync('./JSinJS-all.js',data,'utf-8'); diff --git a/test/node-patch.js b/test/node-patch.js new file mode 100644 index 0000000..c1185e7 --- /dev/null +++ b/test/node-patch.js @@ -0,0 +1,6 @@ + + +module.exports={ + Parser : Parser +} + diff --git a/test/parse-test.js b/test/parse-test.js new file mode 100644 index 0000000..279391e --- /dev/null +++ b/test/parse-test.js @@ -0,0 +1,53 @@ + +var fs = require('fs'); + +var Parser=require("./JSinJS-all").Parser; + + +var fileList=[ + "my-code.js", + "backbone-0.5.3.js", + "mootools-1.4.1.js", + "prototype-1.7.0.0.js", + "ext.js", + "jquery-1.7.1.js", + "ext-core-3.1.0.js", + "ext-debug.js", + "ext-dev.js", + "ext-all.js", + "ext-all-debug.js", + "ext-all-dev.js" +] + +var testcase="./testcase"; + +function parseFile( idx ){ + + var filePath=testcase+"/"+fileList[idx||0]; + + var code = fs.readFileSync(filePath, "UTF-8"); + + var count=0; + var start=Date.now(); + var parser = new Parser(); + var lastToken; + var tree ; + try{ + tree= parser.parse(code ,function(token){ + count++; + lastToken=token; + }); + }catch(e){ + console.log(count, lastToken); + throw e; + } + var end=Date.now(); + console.log( "token count : "+count); + console.log( "time cost : "+ (end-start) ); + + return tree; +} + +var testFileIdx= process.argv[2]||0; +parseFile(testFileIdx); + diff --git a/test/testcase/backbone-0.5.3.js b/test/testcase/backbone-0.5.3.js new file mode 100644 index 0000000..b2e4932 --- /dev/null +++ b/test/testcase/backbone-0.5.3.js @@ -0,0 +1,1158 @@ +// Backbone.js 0.5.3 +// (c) 2010 Jeremy Ashkenas, DocumentCloud Inc. +// Backbone may be freely distributed under the MIT license. +// For all details and documentation: +// http://documentcloud.github.com/backbone + +(function(){ + + // Initial Setup + // ------------- + + // Save a reference to the global object. + var root = this; + + // Save the previous value of the `Backbone` variable. + var previousBackbone = root.Backbone; + + // The top-level namespace. All public Backbone classes and modules will + // be attached to this. Exported for both CommonJS and the browser. + var Backbone; + if (typeof exports !== 'undefined') { + Backbone = exports; + } else { + Backbone = root.Backbone = {}; + } + + // Current version of the library. Keep in sync with `package.json`. + Backbone.VERSION = '0.5.3'; + + // Require Underscore, if we're on the server, and it's not already present. + var _ = root._; + if (!_ && (typeof require !== 'undefined')) _ = require('underscore')._; + + // For Backbone's purposes, jQuery or Zepto owns the `$` variable. + var $ = root.jQuery || root.Zepto; + + // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable + // to its previous owner. Returns a reference to this Backbone object. + Backbone.noConflict = function() { + root.Backbone = previousBackbone; + return this; + }; + + // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option will + // fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and set a + // `X-Http-Method-Override` header. + Backbone.emulateHTTP = false; + + // Turn on `emulateJSON` to support legacy servers that can't deal with direct + // `application/json` requests ... will encode the body as + // `application/x-www-form-urlencoded` instead and will send the model in a + // form param named `model`. + Backbone.emulateJSON = false; + + // Backbone.Events + // ----------------- + + // A module that can be mixed in to *any object* in order to provide it with + // custom events. You may `bind` or `unbind` a callback function to an event; + // `trigger`-ing an event fires all callbacks in succession. + // + // var object = {}; + // _.extend(object, Backbone.Events); + // object.bind('expand', function(){ alert('expanded'); }); + // object.trigger('expand'); + // + Backbone.Events = { + + // Bind an event, specified by a string name, `ev`, to a `callback` function. + // Passing `"all"` will bind the callback to all events fired. + bind : function(ev, callback, context) { + var calls = this._callbacks || (this._callbacks = {}); + var list = calls[ev] || (calls[ev] = []); + list.push([callback, context]); + return this; + }, + + // Remove one or many callbacks. If `callback` is null, removes all + // callbacks for the event. If `ev` is null, removes all bound callbacks + // for all events. + unbind : function(ev, callback) { + var calls; + if (!ev) { + this._callbacks = {}; + } else if (calls = this._callbacks) { + if (!callback) { + calls[ev] = []; + } else { + var list = calls[ev]; + if (!list) return this; + for (var i = 0, l = list.length; i < l; i++) { + if (list[i] && callback === list[i][0]) { + list[i] = null; + break; + } + } + } + } + return this; + }, + + // Trigger an event, firing all bound callbacks. Callbacks are passed the + // same arguments as `trigger` is, apart from the event name. + // Listening for `"all"` passes the true event name as the first argument. + trigger : function(eventName) { + var list, calls, ev, callback, args; + var both = 2; + if (!(calls = this._callbacks)) return this; + while (both--) { + ev = both ? eventName : 'all'; + if (list = calls[ev]) { + for (var i = 0, l = list.length; i < l; i++) { + if (!(callback = list[i])) { + list.splice(i, 1); i--; l--; + } else { + args = both ? Array.prototype.slice.call(arguments, 1) : arguments; + callback[0].apply(callback[1] || this, args); + } + } + } + } + return this; + } + + }; + + // Backbone.Model + // -------------- + + // Create a new model, with defined attributes. A client id (`cid`) + // is automatically generated and assigned for you. + Backbone.Model = function(attributes, options) { + var defaults; + attributes || (attributes = {}); + if (defaults = this.defaults) { + if (_.isFunction(defaults)) defaults = defaults.call(this); + attributes = _.extend({}, defaults, attributes); + } + this.attributes = {}; + this._escapedAttributes = {}; + this.cid = _.uniqueId('c'); + this.set(attributes, {silent : true}); + this._changed = false; + this._previousAttributes = _.clone(this.attributes); + if (options && options.collection) this.collection = options.collection; + this.initialize(attributes, options); + }; + + // Attach all inheritable methods to the Model prototype. + _.extend(Backbone.Model.prototype, Backbone.Events, { + + // A snapshot of the model's previous attributes, taken immediately + // after the last `"change"` event was fired. + _previousAttributes : null, + + // Has the item been changed since the last `"change"` event? + _changed : false, + + // The default name for the JSON `id` attribute is `"id"`. MongoDB and + // CouchDB users may want to set this to `"_id"`. + idAttribute : 'id', + + // Initialize is an empty function by default. Override it with your own + // initialization logic. + initialize : function(){}, + + // Return a copy of the model's `attributes` object. + toJSON : function() { + return _.clone(this.attributes); + }, + + // Get the value of an attribute. + get : function(attr) { + return this.attributes[attr]; + }, + + // Get the HTML-escaped value of an attribute. + escape : function(attr) { + var html; + if (html = this._escapedAttributes[attr]) return html; + var val = this.attributes[attr]; + return this._escapedAttributes[attr] = escapeHTML(val == null ? '' : '' + val); + }, + + // Returns `true` if the attribute contains a value that is not null + // or undefined. + has : function(attr) { + return this.attributes[attr] != null; + }, + + // Set a hash of model attributes on the object, firing `"change"` unless you + // choose to silence it. + set : function(attrs, options) { + + // Extract attributes and options. + options || (options = {}); + if (!attrs) return this; + if (attrs.attributes) attrs = attrs.attributes; + var now = this.attributes, escaped = this._escapedAttributes; + + // Run validation. + if (!options.silent && this.validate && !this._performValidation(attrs, options)) return false; + + // Check for changes of `id`. + if (this.idAttribute in attrs) this.id = attrs[this.idAttribute]; + + // We're about to start triggering change events. + var alreadyChanging = this._changing; + this._changing = true; + + // Update attributes. + for (var attr in attrs) { + var val = attrs[attr]; + if (!_.isEqual(now[attr], val)) { + now[attr] = val; + delete escaped[attr]; + this._changed = true; + if (!options.silent) this.trigger('change:' + attr, this, val, options); + } + } + + // Fire the `"change"` event, if the model has been changed. + if (!alreadyChanging && !options.silent && this._changed) this.change(options); + this._changing = false; + return this; + }, + + // Remove an attribute from the model, firing `"change"` unless you choose + // to silence it. `unset` is a noop if the attribute doesn't exist. + unset : function(attr, options) { + if (!(attr in this.attributes)) return this; + options || (options = {}); + var value = this.attributes[attr]; + + // Run validation. + var validObj = {}; + validObj[attr] = void 0; + if (!options.silent && this.validate && !this._performValidation(validObj, options)) return false; + + // Remove the attribute. + delete this.attributes[attr]; + delete this._escapedAttributes[attr]; + if (attr == this.idAttribute) delete this.id; + this._changed = true; + if (!options.silent) { + this.trigger('change:' + attr, this, void 0, options); + this.change(options); + } + return this; + }, + + // Clear all attributes on the model, firing `"change"` unless you choose + // to silence it. + clear : function(options) { + options || (options = {}); + var attr; + var old = this.attributes; + + // Run validation. + var validObj = {}; + for (attr in old) validObj[attr] = void 0; + if (!options.silent && this.validate && !this._performValidation(validObj, options)) return false; + + this.attributes = {}; + this._escapedAttributes = {}; + this._changed = true; + if (!options.silent) { + for (attr in old) { + this.trigger('change:' + attr, this, void 0, options); + } + this.change(options); + } + return this; + }, + + // Fetch the model from the server. If the server's representation of the + // model differs from its current attributes, they will be overriden, + // triggering a `"change"` event. + fetch : function(options) { + options || (options = {}); + var model = this; + var success = options.success; + options.success = function(resp, status, xhr) { + if (!model.set(model.parse(resp, xhr), options)) return false; + if (success) success(model, resp); + }; + options.error = wrapError(options.error, model, options); + return (this.sync || Backbone.sync).call(this, 'read', this, options); + }, + + // Set a hash of model attributes, and sync the model to the server. + // If the server returns an attributes hash that differs, the model's + // state will be `set` again. + save : function(attrs, options) { + options || (options = {}); + if (attrs && !this.set(attrs, options)) return false; + var model = this; + var success = options.success; + options.success = function(resp, status, xhr) { + if (!model.set(model.parse(resp, xhr), options)) return false; + if (success) success(model, resp, xhr); + }; + options.error = wrapError(options.error, model, options); + var method = this.isNew() ? 'create' : 'update'; + return (this.sync || Backbone.sync).call(this, method, this, options); + }, + + // Destroy this model on the server if it was already persisted. Upon success, the model is removed + // from its collection, if it has one. + destroy : function(options) { + options || (options = {}); + if (this.isNew()) return this.trigger('destroy', this, this.collection, options); + var model = this; + var success = options.success; + options.success = function(resp) { + model.trigger('destroy', model, model.collection, options); + if (success) success(model, resp); + }; + options.error = wrapError(options.error, model, options); + return (this.sync || Backbone.sync).call(this, 'delete', this, options); + }, + + // Default URL for the model's representation on the server -- if you're + // using Backbone's restful methods, override this to change the endpoint + // that will be called. + url : function() { + var base = getUrl(this.collection) || this.urlRoot || urlError(); + if (this.isNew()) return base; + return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + encodeURIComponent(this.id); + }, + + // **parse** converts a response into the hash of attributes to be `set` on + // the model. The default implementation is just to pass the response along. + parse : function(resp, xhr) { + return resp; + }, + + // Create a new model with identical attributes to this one. + clone : function() { + return new this.constructor(this); + }, + + // A model is new if it has never been saved to the server, and lacks an id. + isNew : function() { + return this.id == null; + }, + + // Call this method to manually fire a `change` event for this model. + // Calling this will cause all objects observing the model to update. + change : function(options) { + this.trigger('change', this, options); + this._previousAttributes = _.clone(this.attributes); + this._changed = false; + }, + + // Determine if the model has changed since the last `"change"` event. + // If you specify an attribute name, determine if that attribute has changed. + hasChanged : function(attr) { + if (attr) return this._previousAttributes[attr] != this.attributes[attr]; + return this._changed; + }, + + // Return an object containing all the attributes that have changed, or false + // if there are no changed attributes. Useful for determining what parts of a + // view need to be updated and/or what attributes need to be persisted to + // the server. + changedAttributes : function(now) { + now || (now = this.attributes); + var old = this._previousAttributes; + var changed = false; + for (var attr in now) { + if (!_.isEqual(old[attr], now[attr])) { + changed = changed || {}; + changed[attr] = now[attr]; + } + } + return changed; + }, + + // Get the previous value of an attribute, recorded at the time the last + // `"change"` event was fired. + previous : function(attr) { + if (!attr || !this._previousAttributes) return null; + return this._previousAttributes[attr]; + }, + + // Get all of the attributes of the model at the time of the previous + // `"change"` event. + previousAttributes : function() { + return _.clone(this._previousAttributes); + }, + + // Run validation against a set of incoming attributes, returning `true` + // if all is well. If a specific `error` callback has been passed, + // call that instead of firing the general `"error"` event. + _performValidation : function(attrs, options) { + var error = this.validate(attrs); + if (error) { + if (options.error) { + options.error(this, error, options); + } else { + this.trigger('error', this, error, options); + } + return false; + } + return true; + } + + }); + + // Backbone.Collection + // ------------------- + + // Provides a standard collection class for our sets of models, ordered + // or unordered. If a `comparator` is specified, the Collection will maintain + // its models in sort order, as they're added and removed. + Backbone.Collection = function(models, options) { + options || (options = {}); + if (options.comparator) this.comparator = options.comparator; + _.bindAll(this, '_onModelEvent', '_removeReference'); + this._reset(); + if (models) this.reset(models, {silent: true}); + this.initialize.apply(this, arguments); + }; + + // Define the Collection's inheritable methods. + _.extend(Backbone.Collection.prototype, Backbone.Events, { + + // The default model for a collection is just a **Backbone.Model**. + // This should be overridden in most cases. + model : Backbone.Model, + + // Initialize is an empty function by default. Override it with your own + // initialization logic. + initialize : function(){}, + + // The JSON representation of a Collection is an array of the + // models' attributes. + toJSON : function() { + return this.map(function(model){ return model.toJSON(); }); + }, + + // Add a model, or list of models to the set. Pass **silent** to avoid + // firing the `added` event for every new model. + add : function(models, options) { + if (_.isArray(models)) { + for (var i = 0, l = models.length; i < l; i++) { + this._add(models[i], options); + } + } else { + this._add(models, options); + } + return this; + }, + + // Remove a model, or a list of models from the set. Pass silent to avoid + // firing the `removed` event for every model removed. + remove : function(models, options) { + if (_.isArray(models)) { + for (var i = 0, l = models.length; i < l; i++) { + this._remove(models[i], options); + } + } else { + this._remove(models, options); + } + return this; + }, + + // Get a model from the set by id. + get : function(id) { + if (id == null) return null; + return this._byId[id.id != null ? id.id : id]; + }, + + // Get a model from the set by client id. + getByCid : function(cid) { + return cid && this._byCid[cid.cid || cid]; + }, + + // Get the model at the given index. + at: function(index) { + return this.models[index]; + }, + + // Force the collection to re-sort itself. You don't need to call this under normal + // circumstances, as the set will maintain sort order as each item is added. + sort : function(options) { + options || (options = {}); + if (!this.comparator) throw new Error('Cannot sort a set without a comparator'); + this.models = this.sortBy(this.comparator); + if (!options.silent) this.trigger('reset', this, options); + return this; + }, + + // Pluck an attribute from each model in the collection. + pluck : function(attr) { + return _.map(this.models, function(model){ return model.get(attr); }); + }, + + // When you have more items than you want to add or remove individually, + // you can reset the entire set with a new list of models, without firing + // any `added` or `removed` events. Fires `reset` when finished. + reset : function(models, options) { + models || (models = []); + options || (options = {}); + this.each(this._removeReference); + this._reset(); + this.add(models, {silent: true}); + if (!options.silent) this.trigger('reset', this, options); + return this; + }, + + // Fetch the default set of models for this collection, resetting the + // collection when they arrive. If `add: true` is passed, appends the + // models to the collection instead of resetting. + fetch : function(options) { + options || (options = {}); + var collection = this; + var success = options.success; + options.success = function(resp, status, xhr) { + collection[options.add ? 'add' : 'reset'](collection.parse(resp, xhr), options); + if (success) success(collection, resp); + }; + options.error = wrapError(options.error, collection, options); + return (this.sync || Backbone.sync).call(this, 'read', this, options); + }, + + // Create a new instance of a model in this collection. After the model + // has been created on the server, it will be added to the collection. + // Returns the model, or 'false' if validation on a new model fails. + create : function(model, options) { + var coll = this; + options || (options = {}); + model = this._prepareModel(model, options); + if (!model) return false; + var success = options.success; + options.success = function(nextModel, resp, xhr) { + coll.add(nextModel, options); + if (success) success(nextModel, resp, xhr); + }; + model.save(null, options); + return model; + }, + + // **parse** converts a response into a list of models to be added to the + // collection. The default implementation is just to pass it through. + parse : function(resp, xhr) { + return resp; + }, + + // Proxy to _'s chain. Can't be proxied the same way the rest of the + // underscore methods are proxied because it relies on the underscore + // constructor. + chain: function () { + return _(this.models).chain(); + }, + + // Reset all internal state. Called when the collection is reset. + _reset : function(options) { + this.length = 0; + this.models = []; + this._byId = {}; + this._byCid = {}; + }, + + // Prepare a model to be added to this collection + _prepareModel: function(model, options) { + if (!(model instanceof Backbone.Model)) { + var attrs = model; + model = new this.model(attrs, {collection: this}); + if (model.validate && !model._performValidation(attrs, options)) model = false; + } else if (!model.collection) { + model.collection = this; + } + return model; + }, + + // Internal implementation of adding a single model to the set, updating + // hash indexes for `id` and `cid` lookups. + // Returns the model, or 'false' if validation on a new model fails. + _add : function(model, options) { + options || (options = {}); + model = this._prepareModel(model, options); + if (!model) return false; + var already = this.getByCid(model); + if (already) throw new Error(["Can't add the same model to a set twice", already.id]); + this._byId[model.id] = model; + this._byCid[model.cid] = model; + var index = options.at != null ? options.at : + this.comparator ? this.sortedIndex(model, this.comparator) : + this.length; + this.models.splice(index, 0, model); + model.bind('all', this._onModelEvent); + this.length++; + if (!options.silent) model.trigger('add', model, this, options); + return model; + }, + + // Internal implementation of removing a single model from the set, updating + // hash indexes for `id` and `cid` lookups. + _remove : function(model, options) { + options || (options = {}); + model = this.getByCid(model) || this.get(model); + if (!model) return null; + delete this._byId[model.id]; + delete this._byCid[model.cid]; + this.models.splice(this.indexOf(model), 1); + this.length--; + if (!options.silent) model.trigger('remove', model, this, options); + this._removeReference(model); + return model; + }, + + // Internal method to remove a model's ties to a collection. + _removeReference : function(model) { + if (this == model.collection) { + delete model.collection; + } + model.unbind('all', this._onModelEvent); + }, + + // Internal method called every time a model in the set fires an event. + // Sets need to update their indexes when models change ids. All other + // events simply proxy through. "add" and "remove" events that originate + // in other collections are ignored. + _onModelEvent : function(ev, model, collection, options) { + if ((ev == 'add' || ev == 'remove') && collection != this) return; + if (ev == 'destroy') { + this._remove(model, options); + } + if (model && ev === 'change:' + model.idAttribute) { + delete this._byId[model.previous(model.idAttribute)]; + this._byId[model.id] = model; + } + this.trigger.apply(this, arguments); + } + + }); + + // Underscore methods that we want to implement on the Collection. + var methods = ['forEach', 'each', 'map', 'reduce', 'reduceRight', 'find', 'detect', + 'filter', 'select', 'reject', 'every', 'all', 'some', 'any', 'include', + 'contains', 'invoke', 'max', 'min', 'sortBy', 'sortedIndex', 'toArray', 'size', + 'first', 'rest', 'last', 'without', 'indexOf', 'lastIndexOf', 'isEmpty', 'groupBy']; + + // Mix in each Underscore method as a proxy to `Collection#models`. + _.each(methods, function(method) { + Backbone.Collection.prototype[method] = function() { + return _[method].apply(_, [this.models].concat(_.toArray(arguments))); + }; + }); + + // Backbone.Router + // ------------------- + + // Routers map faux-URLs to actions, and fire events when routes are + // matched. Creating a new one sets its `routes` hash, if not set statically. + Backbone.Router = function(options) { + options || (options = {}); + if (options.routes) this.routes = options.routes; + this._bindRoutes(); + this.initialize.apply(this, arguments); + }; + + // Cached regular expressions for matching named param parts and splatted + // parts of route strings. + var namedParam = /:([\w\d]+)/g; + var splatParam = /\*([\w\d]+)/g; + var escapeRegExp = /[-[\]{}()+?.,\\^$|#\s]/g; + + // Set up all inheritable **Backbone.Router** properties and methods. + _.extend(Backbone.Router.prototype, Backbone.Events, { + + // Initialize is an empty function by default. Override it with your own + // initialization logic. + initialize : function(){}, + + // Manually bind a single named route to a callback. For example: + // + // this.route('search/:query/p:num', 'search', function(query, num) { + // ... + // }); + // + route : function(route, name, callback) { + Backbone.history || (Backbone.history = new Backbone.History); + if (!_.isRegExp(route)) route = this._routeToRegExp(route); + Backbone.history.route(route, _.bind(function(fragment) { + var args = this._extractParameters(route, fragment); + callback.apply(this, args); + this.trigger.apply(this, ['route:' + name].concat(args)); + }, this)); + }, + + // Simple proxy to `Backbone.history` to save a fragment into the history. + navigate : function(fragment, triggerRoute) { + Backbone.history.navigate(fragment, triggerRoute); + }, + + // Bind all defined routes to `Backbone.history`. We have to reverse the + // order of the routes here to support behavior where the most general + // routes can be defined at the bottom of the route map. + _bindRoutes : function() { + if (!this.routes) return; + var routes = []; + for (var route in this.routes) { + routes.unshift([route, this.routes[route]]); + } + for (var i = 0, l = routes.length; i < l; i++) { + this.route(routes[i][0], routes[i][1], this[routes[i][1]]); + } + }, + + // Convert a route string into a regular expression, suitable for matching + // against the current location hash. + _routeToRegExp : function(route) { + route = route.replace(escapeRegExp, "\\$&") + .replace(namedParam, "([^\/]*)") + .replace(splatParam, "(.*?)"); + return new RegExp('^' + route + '$'); + }, + + // Given a route, and a URL fragment that it matches, return the array of + // extracted parameters. + _extractParameters : function(route, fragment) { + return route.exec(fragment).slice(1); + } + + }); + + // Backbone.History + // ---------------- + + // Handles cross-browser history management, based on URL fragments. If the + // browser does not support `onhashchange`, falls back to polling. + Backbone.History = function() { + this.handlers = []; + _.bindAll(this, 'checkUrl'); + }; + + // Cached regex for cleaning hashes. + var hashStrip = /^#*/; + + // Cached regex for detecting MSIE. + var isExplorer = /msie [\w.]+/; + + // Has the history handling already been started? + var historyStarted = false; + + // Set up all inheritable **Backbone.History** properties and methods. + _.extend(Backbone.History.prototype, { + + // The default interval to poll for hash changes, if necessary, is + // twenty times a second. + interval: 50, + + // Get the cross-browser normalized URL fragment, either from the URL, + // the hash, or the override. + getFragment : function(fragment, forcePushState) { + if (fragment == null) { + if (this._hasPushState || forcePushState) { + fragment = window.location.pathname; + var search = window.location.search; + if (search) fragment += search; + if (fragment.indexOf(this.options.root) == 0) fragment = fragment.substr(this.options.root.length); + } else { + fragment = window.location.hash; + } + } + return decodeURIComponent(fragment.replace(hashStrip, '')); + }, + + // Start the hash change handling, returning `true` if the current URL matches + // an existing route, and `false` otherwise. + start : function(options) { + + // Figure out the initial configuration. Do we need an iframe? + // Is pushState desired ... is it available? + if (historyStarted) throw new Error("Backbone.history has already been started"); + this.options = _.extend({}, {root: '/'}, this.options, options); + this._wantsPushState = !!this.options.pushState; + this._hasPushState = !!(this.options.pushState && window.history && window.history.pushState); + var fragment = this.getFragment(); + var docMode = document.documentMode; + var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7)); + if (oldIE) { + this.iframe = $('', + '{afterIFrameTpl}', + { + disableFormats: true + } + ], + + subTplInsertions: [ + + 'beforeTextAreaTpl', + + + 'afterTextAreaTpl', + + + 'beforeIFrameTpl', + + + 'afterIFrameTpl', + + + 'iframeAttrTpl', + + + 'inputAttrTpl' + ], + + + enableFormat : true, + + enableFontSize : true, + + enableColors : true, + + enableAlignments : true, + + enableLists : true, + + enableSourceEdit : true, + + enableLinks : true, + + enableFont : true, + + + createLinkText : 'Please enter the URL for the link:', + + + defaultLinkValue : 'http:/'+'/', + + fontFamilies : [ + 'Arial', + 'Courier New', + 'Tahoma', + 'Times New Roman', + 'Verdana' + ], + defaultFont: 'tahoma', + + defaultValue: (Ext.isOpera || Ext.isIE6) ? ' ' : '​', + + fieldBodyCls: Ext.baseCSSPrefix + 'html-editor-wrap', + + componentLayout: 'htmleditor', + + + initialized : false, + activated : false, + sourceEditMode : false, + iframePad:3, + hideMode:'offsets', + + maskOnDisable: true, + + + initComponent : function(){ + var me = this; + + me.addEvents( + + 'initialize', + + 'activate', + + 'beforesync', + + 'beforepush', + + 'sync', + + 'push', + + 'editmodechange' + ); + + me.callParent(arguments); + me.createToolbar(me); + + + me.initLabelable(); + me.initField(); + }, + + + getRefItems: function() { + return [ this.toolbar ]; + }, + + + createToolbar : function(editor){ + var me = this, + items = [], i, + tipsEnabled = Ext.tip.QuickTipManager && Ext.tip.QuickTipManager.isEnabled(), + baseCSSPrefix = Ext.baseCSSPrefix, + fontSelectItem, toolbar, undef; + + function btn(id, toggle, handler){ + return { + itemId : id, + cls : baseCSSPrefix + 'btn-icon', + iconCls: baseCSSPrefix + 'edit-'+id, + enableToggle:toggle !== false, + scope: editor, + handler:handler||editor.relayBtnCmd, + clickEvent: 'mousedown', + tooltip: tipsEnabled ? editor.buttonTips[id] || undef : undef, + overflowText: editor.buttonTips[id].title || undef, + tabIndex: -1 + }; + } + + + if (me.enableFont && !Ext.isSafari2) { + fontSelectItem = Ext.widget('component', { + renderTpl: [ + '' + ], + renderData: { + cls: baseCSSPrefix + 'font-select', + fonts: me.fontFamilies, + defaultFont: me.defaultFont + }, + childEls: ['selectEl'], + afterRender: function() { + me.fontSelect = this.selectEl; + Ext.Component.prototype.afterRender.apply(this, arguments); + }, + onDisable: function() { + var selectEl = this.selectEl; + if (selectEl) { + selectEl.dom.disabled = true; + } + Ext.Component.prototype.onDisable.apply(this, arguments); + }, + onEnable: function() { + var selectEl = this.selectEl; + if (selectEl) { + selectEl.dom.disabled = false; + } + Ext.Component.prototype.onEnable.apply(this, arguments); + }, + listeners: { + change: function() { + me.relayCmd('fontname', me.fontSelect.dom.value); + me.deferFocus(); + }, + element: 'selectEl' + } + }); + + items.push( + fontSelectItem, + '-' + ); + } + + if (me.enableFormat) { + items.push( + btn('bold'), + btn('italic'), + btn('underline') + ); + } + + if (me.enableFontSize) { + items.push( + '-', + btn('increasefontsize', false, me.adjustFont), + btn('decreasefontsize', false, me.adjustFont) + ); + } + + if (me.enableColors) { + items.push( + '-', { + itemId: 'forecolor', + cls: baseCSSPrefix + 'btn-icon', + iconCls: baseCSSPrefix + 'edit-forecolor', + overflowText: editor.buttonTips.forecolor.title, + tooltip: tipsEnabled ? editor.buttonTips.forecolor || undef : undef, + tabIndex:-1, + menu : Ext.widget('menu', { + plain: true, + items: [{ + xtype: 'colorpicker', + allowReselect: true, + focus: Ext.emptyFn, + value: '000000', + plain: true, + clickEvent: 'mousedown', + handler: function(cp, color) { + me.execCmd('forecolor', Ext.isWebKit || Ext.isIE ? '#'+color : color); + me.deferFocus(); + this.up('menu').hide(); + } + }] + }) + }, { + itemId: 'backcolor', + cls: baseCSSPrefix + 'btn-icon', + iconCls: baseCSSPrefix + 'edit-backcolor', + overflowText: editor.buttonTips.backcolor.title, + tooltip: tipsEnabled ? editor.buttonTips.backcolor || undef : undef, + tabIndex:-1, + menu : Ext.widget('menu', { + plain: true, + items: [{ + xtype: 'colorpicker', + focus: Ext.emptyFn, + value: 'FFFFFF', + plain: true, + allowReselect: true, + clickEvent: 'mousedown', + handler: function(cp, color) { + if (Ext.isGecko) { + me.execCmd('useCSS', false); + me.execCmd('hilitecolor', color); + me.execCmd('useCSS', true); + me.deferFocus(); + } else { + me.execCmd(Ext.isOpera ? 'hilitecolor' : 'backcolor', Ext.isWebKit || Ext.isIE ? '#'+color : color); + me.deferFocus(); + } + this.up('menu').hide(); + } + }] + }) + } + ); + } + + if (me.enableAlignments) { + items.push( + '-', + btn('justifyleft'), + btn('justifycenter'), + btn('justifyright') + ); + } + + if (!Ext.isSafari2) { + if (me.enableLinks) { + items.push( + '-', + btn('createlink', false, me.createLink) + ); + } + + if (me.enableLists) { + items.push( + '-', + btn('insertorderedlist'), + btn('insertunorderedlist') + ); + } + if (me.enableSourceEdit) { + items.push( + '-', + btn('sourceedit', true, function(btn){ + me.toggleSourceEdit(!me.sourceEditMode); + }) + ); + } + } + + + for (i = 0; i < items.length; i++) { + if (items[i].itemId !== 'sourceedit') { + items[i].disabled = true; + } + } + + + + toolbar = Ext.widget('toolbar', { + id: me.id + '-toolbar', + ownerCt: me, + cls: Ext.baseCSSPrefix + 'html-editor-tb', + enableOverflow: true, + items: items, + ownerLayout: me.getComponentLayout(), + + + listeners: { + click: function(e){ + e.preventDefault(); + }, + element: 'el' + } + }); + + me.toolbar = toolbar; + }, + + getMaskTarget: function(){ + return this.bodyEl; + }, + + + setReadOnly: function(readOnly) { + var me = this, + textareaEl = me.textareaEl, + iframeEl = me.iframeEl, + body; + + me.readOnly = readOnly; + + if (textareaEl) { + textareaEl.dom.readOnly = readOnly; + } + + if (me.initialized) { + body = me.getEditorBody(); + if (Ext.isIE) { + + iframeEl.setDisplayed(false); + body.contentEditable = !readOnly; + iframeEl.setDisplayed(true); + } else { + me.setDesignMode(!readOnly); + } + if (body) { + body.style.cursor = readOnly ? 'default' : 'text'; + } + me.disableItems(readOnly); + } + }, + + + getDocMarkup: function() { + var me = this, + h = me.iframeEl.getHeight() - me.iframePad * 2; + return Ext.String.format('', me.iframePad, h); + }, + + + getEditorBody: function() { + var doc = this.getDoc(); + return doc.body || doc.documentElement; + }, + + + getDoc: function() { + return (!Ext.isIE && this.iframeEl.dom.contentDocument) || this.getWin().document; + }, + + + getWin: function() { + return Ext.isIE ? this.iframeEl.dom.contentWindow : window.frames[this.iframeEl.dom.name]; + }, + + + + finishRenderChildren: function () { + this.callParent(); + this.toolbar.finishRender(); + }, + + + onRender: function() { + var me = this; + + me.callParent(arguments); + + + + me.inputEl = me.iframeEl; + + + me.monitorTask = Ext.TaskManager.start({ + run: me.checkDesignMode, + scope: me, + interval: 100 + }); + }, + + initRenderTpl: function() { + var me = this; + if (!me.hasOwnProperty('renderTpl')) { + me.renderTpl = me.getTpl('labelableRenderTpl'); + } + return me.callParent(); + }, + + initRenderData: function() { + return Ext.applyIf(this.callParent(), this.getLabelableRenderData()); + }, + + getSubTplData: function() { + return { + $comp : this, + cmpId : this.id, + id : this.getInputId(), + textareaCls : Ext.baseCSSPrefix + 'hidden', + value : this.value, + iframeName : Ext.id(), + iframeSrc : Ext.SSL_SECURE_URL, + size : 'height:100px;width:100%' + }; + }, + + getSubTplMarkup: function() { + return this.getTpl('fieldSubTpl').apply(this.getSubTplData()); + }, + + initFrameDoc: function() { + var me = this, + doc, task; + + Ext.TaskManager.stop(me.monitorTask); + + doc = me.getDoc(); + me.win = me.getWin(); + + doc.open(); + doc.write(me.getDocMarkup()); + doc.close(); + + task = { + run: function() { + var doc = me.getDoc(); + if (doc.body || doc.readyState === 'complete') { + Ext.TaskManager.stop(task); + me.setDesignMode(true); + Ext.defer(me.initEditor, 10, me); + } + }, + interval : 10, + duration:10000, + scope: me + }; + Ext.TaskManager.start(task); + }, + + checkDesignMode: function() { + var me = this, + doc = me.getDoc(); + if (doc && (!doc.editorInitialized || me.getDesignMode() !== 'on')) { + me.initFrameDoc(); + } + }, + + + setDesignMode: function(mode) { + var me = this, + doc = me.getDoc(); + if (doc) { + if (me.readOnly) { + mode = false; + } + doc.designMode = (/on|true/i).test(String(mode).toLowerCase()) ?'on':'off'; + } + }, + + + getDesignMode: function() { + var doc = this.getDoc(); + return !doc ? '' : String(doc.designMode).toLowerCase(); + }, + + disableItems: function(disabled) { + var items = this.getToolbar().items.items, + i, + iLen = items.length, + item; + + for (i = 0; i < iLen; i++) { + item = items[i]; + + if (item.getItemId() !== 'sourceedit') { + item.setDisabled(disabled); + } + } + }, + + + toggleSourceEdit: function(sourceEditMode) { + var me = this, + iframe = me.iframeEl, + textarea = me.textareaEl, + hiddenCls = Ext.baseCSSPrefix + 'hidden', + btn = me.getToolbar().getComponent('sourceedit'); + + if (!Ext.isBoolean(sourceEditMode)) { + sourceEditMode = !me.sourceEditMode; + } + me.sourceEditMode = sourceEditMode; + + if (btn.pressed !== sourceEditMode) { + btn.toggle(sourceEditMode); + } + if (sourceEditMode) { + me.disableItems(true); + me.syncValue(); + iframe.addCls(hiddenCls); + textarea.removeCls(hiddenCls); + textarea.dom.removeAttribute('tabIndex'); + textarea.focus(); + me.inputEl = textarea; + } + else { + if (me.initialized) { + me.disableItems(me.readOnly); + } + me.pushValue(); + iframe.removeCls(hiddenCls); + textarea.addCls(hiddenCls); + textarea.dom.setAttribute('tabIndex', -1); + me.deferFocus(); + me.inputEl = iframe; + } + me.fireEvent('editmodechange', me, sourceEditMode); + me.updateLayout(); + }, + + + createLink : function() { + var url = prompt(this.createLinkText, this.defaultLinkValue); + if (url && url !== 'http:/'+'/') { + this.relayCmd('createlink', url); + } + }, + + clearInvalid: Ext.emptyFn, + + + setValue: function(value) { + var me = this, + textarea = me.textareaEl; + me.mixins.field.setValue.call(me, value); + if (value === null || value === undefined) { + value = ''; + } + if (textarea) { + textarea.dom.value = value; + } + me.pushValue(); + return this; + }, + + + cleanHtml: function(html) { + html = String(html); + if (Ext.isWebKit) { + html = html.replace(/\sclass="(?:Apple-style-span|khtml-block-placeholder)"/gi, ''); + } + + + if (html.charCodeAt(0) === parseInt(this.defaultValue.replace(/\D/g, ''), 10)) { + html = html.substring(1); + } + return html; + }, + + + syncValue : function(){ + var me = this, + body, changed, html, bodyStyle, match, oldValue; + + if (me.initialized) { + body = me.getEditorBody(); + html = body.innerHTML; + if (Ext.isWebKit) { + bodyStyle = body.getAttribute('style'); + match = bodyStyle.match(/text-align:(.*?);/i); + if (match && match[1]) { + html = '
' + html + '
'; + } + } + html = me.cleanHtml(html); + if (me.fireEvent('beforesync', me, html) !== false) { + if (me.textareaEl.dom.value != html) { + me.textareaEl.dom.value = html; + changed = true; + } + + me.fireEvent('sync', me, html); + + if (changed) { + + + me.checkChange(); + } + } + } + }, + + + getValue : function() { + var me = this, + value; + if (!me.sourceEditMode) { + me.syncValue(); + } + value = me.rendered ? me.textareaEl.dom.value : me.value; + me.value = value; + return value; + }, + + + pushValue: function() { + var me = this, + v; + if(me.initialized){ + v = me.textareaEl.dom.value || ''; + if (!me.activated && v.length < 1) { + v = me.defaultValue; + } + if (me.fireEvent('beforepush', me, v) !== false) { + me.getEditorBody().innerHTML = v; + if (Ext.isGecko) { + + me.setDesignMode(false); + me.setDesignMode(true); + } + me.fireEvent('push', me, v); + } + } + }, + + + deferFocus : function(){ + this.focus(false, true); + }, + + getFocusEl: function() { + var me = this, + win = me.win; + return win && !me.sourceEditMode ? win : me.textareaEl; + }, + + + initEditor : function(){ + + try { + var me = this, + dbody = me.getEditorBody(), + ss = me.textareaEl.getStyles('font-size', 'font-family', 'background-image', 'background-repeat', 'background-color', 'color'), + doc, + fn; + + ss['background-attachment'] = 'fixed'; + dbody.bgProperties = 'fixed'; + + Ext.DomHelper.applyStyles(dbody, ss); + + doc = me.getDoc(); + + if (doc) { + try { + Ext.EventManager.removeAll(doc); + } catch(e) {} + } + + + fn = Ext.Function.bind(me.onEditorEvent, me); + Ext.EventManager.on(doc, { + mousedown: fn, + dblclick: fn, + click: fn, + keyup: fn, + buffer:100 + }); + + + + + + + fn = me.onRelayedEvent; + Ext.EventManager.on(doc, { + mousedown: fn, + mousemove: fn, + mouseup: fn, + click: fn, + dblclick: fn, + scope: me + }); + + if (Ext.isGecko) { + Ext.EventManager.on(doc, 'keypress', me.applyCommand, me); + } + if (me.fixKeys) { + Ext.EventManager.on(doc, 'keydown', me.fixKeys, me); + } + + + Ext.EventManager.on(window, 'unload', me.beforeDestroy, me); + doc.editorInitialized = true; + + me.initialized = true; + me.pushValue(); + me.setReadOnly(me.readOnly); + me.fireEvent('initialize', me); + } catch(ex) { + + } + }, + + + beforeDestroy : function(){ + var me = this, + monitorTask = me.monitorTask, + doc, prop; + + if (monitorTask) { + Ext.TaskManager.stop(monitorTask); + } + if (me.rendered) { + try { + doc = me.getDoc(); + if (doc) { + Ext.EventManager.removeAll(doc); + for (prop in doc) { + if (doc.hasOwnProperty && doc.hasOwnProperty(prop)) { + delete doc[prop]; + } + } + } + } catch(e) { + + } + Ext.destroyMembers(me, 'toolbar', 'iframeEl', 'textareaEl'); + } + me.callParent(); + }, + + + onRelayedEvent: function (event) { + + + var iframeEl = this.iframeEl, + iframeXY = iframeEl.getXY(), + eventXY = event.getXY(); + + + + event.xy = [iframeXY[0] + eventXY[0], iframeXY[1] + eventXY[1]]; + + event.injectEvent(iframeEl); + + event.xy = eventXY; + }, + + + onFirstFocus : function(){ + var me = this, + selection, range; + me.activated = true; + me.disableItems(me.readOnly); + if (Ext.isGecko) { + me.win.focus(); + selection = me.win.getSelection(); + if (!selection.focusNode || selection.focusNode.nodeType !== 3) { + range = selection.getRangeAt(0); + range.selectNodeContents(me.getEditorBody()); + range.collapse(true); + me.deferFocus(); + } + try { + me.execCmd('useCSS', true); + me.execCmd('styleWithCSS', false); + } catch(e) { + + } + } + me.fireEvent('activate', me); + }, + + + adjustFont: function(btn) { + var adjust = btn.getItemId() === 'increasefontsize' ? 1 : -1, + size = this.getDoc().queryCommandValue('FontSize') || '2', + isPxSize = Ext.isString(size) && size.indexOf('px') !== -1, + isSafari; + size = parseInt(size, 10); + if (isPxSize) { + + + if (size <= 10) { + size = 1 + adjust; + } + else if (size <= 13) { + size = 2 + adjust; + } + else if (size <= 16) { + size = 3 + adjust; + } + else if (size <= 18) { + size = 4 + adjust; + } + else if (size <= 24) { + size = 5 + adjust; + } + else { + size = 6 + adjust; + } + size = Ext.Number.constrain(size, 1, 6); + } else { + isSafari = Ext.isSafari; + if (isSafari) { + adjust *= 2; + } + size = Math.max(1, size + adjust) + (isSafari ? 'px' : 0); + } + this.execCmd('FontSize', size); + }, + + + onEditorEvent: function(e) { + this.updateToolbar(); + }, + + + updateToolbar: function() { + var me = this, + btns, doc, name, fontSelect; + + if (me.readOnly) { + return; + } + + if (!me.activated) { + me.onFirstFocus(); + return; + } + + btns = me.getToolbar().items.map; + doc = me.getDoc(); + + if (me.enableFont && !Ext.isSafari2) { + name = (doc.queryCommandValue('FontName') || me.defaultFont).toLowerCase(); + fontSelect = me.fontSelect.dom; + if (name !== fontSelect.value) { + fontSelect.value = name; + } + } + + function updateButtons() { + for (var i = 0, l = arguments.length, name; i < l; i++) { + name = arguments[i]; + btns[name].toggle(doc.queryCommandState(name)); + } + } + if(me.enableFormat){ + updateButtons('bold', 'italic', 'underline'); + } + if(me.enableAlignments){ + updateButtons('justifyleft', 'justifycenter', 'justifyright'); + } + if(!Ext.isSafari2 && me.enableLists){ + updateButtons('insertorderedlist', 'insertunorderedlist'); + } + + Ext.menu.Manager.hideAll(); + + me.syncValue(); + }, + + + relayBtnCmd: function(btn) { + this.relayCmd(btn.getItemId()); + }, + + + relayCmd: function(cmd, value) { + Ext.defer(function() { + var me = this; + me.focus(); + me.execCmd(cmd, value); + me.updateToolbar(); + }, 10, this); + }, + + + execCmd : function(cmd, value){ + var me = this, + doc = me.getDoc(), + undef; + doc.execCommand(cmd, false, value === undef ? null : value); + me.syncValue(); + }, + + + applyCommand : function(e){ + if (e.ctrlKey) { + var me = this, + 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) { + me.win.focus(); + me.execCmd(cmd); + me.deferFocus(); + e.preventDefault(); + } + } + } + }, + + + insertAtCursor : function(text){ + var me = this, + range; + + if (me.activated) { + me.win.focus(); + if (Ext.isIE) { + range = me.getDoc().selection.createRange(); + if (range) { + range.pasteHTML(text); + me.syncValue(); + me.deferFocus(); + } + }else{ + me.execCmd('InsertHTML', text); + me.deferFocus(); + } + } + }, + + + fixKeys: (function() { + if (Ext.isIE) { + return function(e){ + var me = this, + k = e.getKey(), + doc = me.getDoc(), + readOnly = me.readOnly, + range, target; + + if (k === e.TAB) { + e.stopEvent(); + if (!readOnly) { + range = doc.selection.createRange(); + if(range){ + range.collapse(true); + range.pasteHTML('    '); + me.deferFocus(); + } + } + } + else if (k === e.ENTER) { + if (!readOnly) { + range = doc.selection.createRange(); + if (range) { + target = range.parentElement(); + if(!target || target.tagName.toLowerCase() !== 'li'){ + e.stopEvent(); + range.pasteHTML('
'); + range.collapse(false); + range.select(); + } + } + } + } + }; + } + + if (Ext.isOpera) { + return function(e){ + var me = this; + if (e.getKey() === e.TAB) { + e.stopEvent(); + if (!me.readOnly) { + me.win.focus(); + me.execCmd('InsertHTML','    '); + me.deferFocus(); + } + } + }; + } + + if (Ext.isWebKit) { + return function(e){ + var me = this, + k = e.getKey(), + readOnly = me.readOnly; + + if (k === e.TAB) { + e.stopEvent(); + if (!readOnly) { + me.execCmd('InsertText','\t'); + me.deferFocus(); + } + } + else if (k === e.ENTER) { + e.stopEvent(); + if (!readOnly) { + me.execCmd('InsertHtml','

'); + me.deferFocus(); + } + } + }; + } + + return null; + }()), + + + getToolbar : function(){ + return this.toolbar; + }, + + + + buttonTips : { + bold : { + title: 'Bold (Ctrl+B)', + text: 'Make the selected text bold.', + cls: Ext.baseCSSPrefix + 'html-editor-tip' + }, + italic : { + title: 'Italic (Ctrl+I)', + text: 'Make the selected text italic.', + cls: Ext.baseCSSPrefix + 'html-editor-tip' + }, + underline : { + title: 'Underline (Ctrl+U)', + text: 'Underline the selected text.', + cls: Ext.baseCSSPrefix + 'html-editor-tip' + }, + increasefontsize : { + title: 'Grow Text', + text: 'Increase the font size.', + cls: Ext.baseCSSPrefix + 'html-editor-tip' + }, + decreasefontsize : { + title: 'Shrink Text', + text: 'Decrease the font size.', + cls: Ext.baseCSSPrefix + 'html-editor-tip' + }, + backcolor : { + title: 'Text Highlight Color', + text: 'Change the background color of the selected text.', + cls: Ext.baseCSSPrefix + 'html-editor-tip' + }, + forecolor : { + title: 'Font Color', + text: 'Change the color of the selected text.', + cls: Ext.baseCSSPrefix + 'html-editor-tip' + }, + justifyleft : { + title: 'Align Text Left', + text: 'Align text to the left.', + cls: Ext.baseCSSPrefix + 'html-editor-tip' + }, + justifycenter : { + title: 'Center Text', + text: 'Center text in the editor.', + cls: Ext.baseCSSPrefix + 'html-editor-tip' + }, + justifyright : { + title: 'Align Text Right', + text: 'Align text to the right.', + cls: Ext.baseCSSPrefix + 'html-editor-tip' + }, + insertunorderedlist : { + title: 'Bullet List', + text: 'Start a bulleted list.', + cls: Ext.baseCSSPrefix + 'html-editor-tip' + }, + insertorderedlist : { + title: 'Numbered List', + text: 'Start a numbered list.', + cls: Ext.baseCSSPrefix + 'html-editor-tip' + }, + createlink : { + title: 'Hyperlink', + text: 'Make the selected text a hyperlink.', + cls: Ext.baseCSSPrefix + 'html-editor-tip' + }, + sourceedit : { + title: 'Source Edit', + text: 'Switch to source editing mode.', + cls: Ext.baseCSSPrefix + 'html-editor-tip' + } + } + + + + + + + + + + + + + + + + + + +}); + + +Ext.define('Ext.panel.Tool', { + extend: 'Ext.Component', + requires: ['Ext.tip.QuickTipManager'], + alias: 'widget.tool', + + baseCls: Ext.baseCSSPrefix + 'tool', + disabledCls: Ext.baseCSSPrefix + 'tool-disabled', + toolPressedCls: Ext.baseCSSPrefix + 'tool-pressed', + toolOverCls: Ext.baseCSSPrefix + 'tool-over', + ariaRole: 'button', + + childEls: [ + 'toolEl' + ], + + renderTpl: [ + '' + ], + + + + + + + + + + + tooltipType: 'qtip', + + + stopEvent: true, + + height: 15, + width: 15, + + + initComponent: function() { + var me = this; + me.addEvents( + + 'click' + ); + + + me.type = me.type || me.id; + + Ext.applyIf(me.renderData, { + baseCls: me.baseCls, + blank: Ext.BLANK_IMAGE_URL, + type: me.type + }); + + + me.tooltip = me.tooltip || me.qtip; + me.callParent(); + me.on({ + element: 'toolEl', + click: me.onClick, + mousedown: me.onMouseDown, + mouseover: me.onMouseOver, + mouseout: me.onMouseOut, + scope: me + }); + }, + + + afterRender: function() { + var me = this, + attr; + + me.callParent(arguments); + if (me.tooltip) { + if (Ext.isObject(me.tooltip)) { + Ext.tip.QuickTipManager.register(Ext.apply({ + target: me.id + }, me.tooltip)); + } + else { + attr = me.tooltipType == 'qtip' ? 'data-qtip' : 'title'; + me.toolEl.dom.setAttribute(attr, me.tooltip); + } + } + }, + + getFocusEl: function() { + return this.el; + }, + + + setType: function(type) { + var me = this; + + me.type = type; + if (me.rendered) { + me.toolEl.dom.className = me.baseCls + '-' + type; + } + return me; + }, + + + bindTo: function(component) { + this.owner = component; + }, + + + onClick: function(e, target) { + var me = this, + owner; + + if (me.disabled) { + return false; + } + owner = me.owner || me.ownerCt; + + + me.el.removeCls(me.toolPressedCls); + me.el.removeCls(me.toolOverCls); + + if (me.stopEvent !== false) { + e.stopEvent(); + } + + Ext.callback(me.handler, me.scope || me, [e, target, owner, me]); + me.fireEvent('click', me, e); + return true; + }, + + + onDestroy: function(){ + if (Ext.isObject(this.tooltip)) { + Ext.tip.QuickTipManager.unregister(this.id); + } + this.callParent(); + }, + + + onMouseDown: function() { + if (this.disabled) { + return false; + } + + this.el.addCls(this.toolPressedCls); + }, + + + onMouseOver: function() { + if (this.disabled) { + return false; + } + this.el.addCls(this.toolOverCls); + }, + + + onMouseOut: function() { + this.el.removeCls(this.toolOverCls); + } +}); + + +Ext.define('Ext.toolbar.Paging', { + extend: 'Ext.toolbar.Toolbar', + alias: 'widget.pagingtoolbar', + alternateClassName: 'Ext.PagingToolbar', + requires: ['Ext.toolbar.TextItem', 'Ext.form.field.Number'], + mixins: { + bindable: 'Ext.util.Bindable' + }, + + + + displayInfo: false, + + + prependButtons: false, + + + + displayMsg : 'Displaying {0} - {1} of {2}', + + + + + emptyMsg : 'No data to display', + + + + + beforePageText : 'Page', + + + + + afterPageText : 'of {0}', + + + + + firstText : 'First Page', + + + + + prevText : 'Previous Page', + + + + + nextText : 'Next Page', + + + + + lastText : 'Last Page', + + + + + refreshText : 'Refresh', + + + + inputItemWidth : 30, + + + getPagingItems: function() { + var me = this; + + return [{ + itemId: 'first', + tooltip: me.firstText, + overflowText: me.firstText, + iconCls: Ext.baseCSSPrefix + 'tbar-page-first', + disabled: true, + handler: me.moveFirst, + scope: me + },{ + itemId: 'prev', + tooltip: me.prevText, + overflowText: me.prevText, + iconCls: Ext.baseCSSPrefix + 'tbar-page-prev', + disabled: true, + handler: me.movePrevious, + scope: me + }, + '-', + me.beforePageText, + { + xtype: 'numberfield', + itemId: 'inputItem', + name: 'inputItem', + cls: Ext.baseCSSPrefix + 'tbar-page-number', + allowDecimals: false, + minValue: 1, + hideTrigger: true, + enableKeyEvents: true, + keyNavEnabled: false, + selectOnFocus: true, + submitValue: false, + + isFormField: false, + width: me.inputItemWidth, + margins: '-1 2 3 2', + listeners: { + scope: me, + keydown: me.onPagingKeyDown, + blur: me.onPagingBlur + } + },{ + xtype: 'tbtext', + itemId: 'afterTextItem', + text: Ext.String.format(me.afterPageText, 1) + }, + '-', + { + itemId: 'next', + tooltip: me.nextText, + overflowText: me.nextText, + iconCls: Ext.baseCSSPrefix + 'tbar-page-next', + disabled: true, + handler: me.moveNext, + scope: me + },{ + itemId: 'last', + tooltip: me.lastText, + overflowText: me.lastText, + iconCls: Ext.baseCSSPrefix + 'tbar-page-last', + disabled: true, + handler: me.moveLast, + scope: me + }, + '-', + { + itemId: 'refresh', + tooltip: me.refreshText, + overflowText: me.refreshText, + iconCls: Ext.baseCSSPrefix + 'tbar-loading', + handler: me.doRefresh, + scope: me + }]; + }, + + initComponent : function(){ + var me = this, + pagingItems = me.getPagingItems(), + userItems = me.items || me.buttons || []; + + if (me.prependButtons) { + me.items = userItems.concat(pagingItems); + } else { + me.items = pagingItems.concat(userItems); + } + delete me.buttons; + + if (me.displayInfo) { + me.items.push('->'); + me.items.push({xtype: 'tbtext', itemId: 'displayItem'}); + } + + me.callParent(); + + me.addEvents( + + 'change', + + + 'beforechange' + ); + me.on('beforerender', me.onLoad, me, {single: true}); + + me.bindStore(me.store || 'ext-empty-store', true); + }, + + updateInfo : function(){ + var me = this, + displayItem = me.child('#displayItem'), + store = me.store, + pageData = me.getPageData(), + count, msg; + + if (displayItem) { + count = store.getCount(); + if (count === 0) { + msg = me.emptyMsg; + } else { + msg = Ext.String.format( + me.displayMsg, + pageData.fromRecord, + pageData.toRecord, + pageData.total + ); + } + displayItem.setText(msg); + } + }, + + + onLoad : function(){ + var me = this, + pageData, + currPage, + pageCount, + afterText, + count, + isEmpty; + + count = me.store.getCount(); + isEmpty = count === 0; + if (!isEmpty) { + pageData = me.getPageData(); + currPage = pageData.currentPage; + pageCount = pageData.pageCount; + afterText = Ext.String.format(me.afterPageText, isNaN(pageCount) ? 1 : pageCount); + } else { + currPage = 0; + pageCount = 0; + afterText = Ext.String.format(me.afterPageText, 0); + } + + Ext.suspendLayouts(); + me.child('#afterTextItem').setText(afterText); + me.child('#inputItem').setDisabled(isEmpty).setValue(currPage); + me.child('#first').setDisabled(currPage === 1 || isEmpty); + me.child('#prev').setDisabled(currPage === 1 || isEmpty); + me.child('#next').setDisabled(currPage === pageCount || isEmpty); + me.child('#last').setDisabled(currPage === pageCount || isEmpty); + me.child('#refresh').enable(); + me.updateInfo(); + Ext.resumeLayouts(true); + + if (me.rendered) { + me.fireEvent('change', me, pageData); + } + }, + + + getPageData : function(){ + var store = this.store, + totalCount = store.getTotalCount(); + + return { + total : totalCount, + currentPage : store.currentPage, + pageCount: Math.ceil(totalCount / store.pageSize), + fromRecord: ((store.currentPage - 1) * store.pageSize) + 1, + toRecord: Math.min(store.currentPage * store.pageSize, totalCount) + + }; + }, + + + onLoadError : function(){ + if (!this.rendered) { + return; + } + this.child('#refresh').enable(); + }, + + + readPageFromInput : function(pageData){ + var v = this.child('#inputItem').getValue(), + pageNum = parseInt(v, 10); + + if (!v || isNaN(pageNum)) { + this.child('#inputItem').setValue(pageData.currentPage); + return false; + } + return pageNum; + }, + + onPagingFocus : function(){ + this.child('#inputItem').select(); + }, + + + onPagingBlur : function(e){ + var curPage = this.getPageData().currentPage; + this.child('#inputItem').setValue(curPage); + }, + + + onPagingKeyDown : function(field, e){ + var me = this, + k = e.getKey(), + pageData = me.getPageData(), + increment = e.shiftKey ? 10 : 1, + pageNum; + + if (k == e.RETURN) { + e.stopEvent(); + pageNum = me.readPageFromInput(pageData); + if (pageNum !== false) { + pageNum = Math.min(Math.max(1, pageNum), pageData.pageCount); + if(me.fireEvent('beforechange', me, pageNum) !== false){ + me.store.loadPage(pageNum); + } + } + } else if (k == e.HOME || k == e.END) { + e.stopEvent(); + pageNum = k == e.HOME ? 1 : pageData.pageCount; + field.setValue(pageNum); + } else if (k == e.UP || k == e.PAGE_UP || k == e.DOWN || k == e.PAGE_DOWN) { + e.stopEvent(); + pageNum = me.readPageFromInput(pageData); + if (pageNum) { + if (k == e.DOWN || k == e.PAGE_DOWN) { + increment *= -1; + } + pageNum += increment; + if (pageNum >= 1 && pageNum <= pageData.pageCount) { + field.setValue(pageNum); + } + } + } + }, + + + beforeLoad : function(){ + if(this.rendered && this.refresh){ + this.refresh.disable(); + } + }, + + + moveFirst : function(){ + if (this.fireEvent('beforechange', this, 1) !== false){ + this.store.loadPage(1); + } + }, + + + movePrevious : function(){ + var me = this, + prev = me.store.currentPage - 1; + + if (prev > 0) { + if (me.fireEvent('beforechange', me, prev) !== false) { + me.store.previousPage(); + } + } + }, + + + moveNext : function(){ + var me = this, + total = me.getPageData().pageCount, + next = me.store.currentPage + 1; + + if (next <= total) { + if (me.fireEvent('beforechange', me, next) !== false) { + me.store.nextPage(); + } + } + }, + + + moveLast : function(){ + var me = this, + last = me.getPageData().pageCount; + + if (me.fireEvent('beforechange', me, last) !== false) { + me.store.loadPage(last); + } + }, + + + doRefresh : function(){ + var me = this, + current = me.store.currentPage; + + if (me.fireEvent('beforechange', me, current) !== false) { + me.store.loadPage(current); + } + }, + + getStoreListeners: function() { + return { + beforeload: this.beforeLoad, + load: this.onLoad, + exception: this.onLoadError + }; + }, + + + unbind : function(store){ + this.bindStore(null); + }, + + + bind : function(store){ + this.bindStore(store); + }, + + + onDestroy : function(){ + this.unbind(); + this.callParent(); + } +}); + + +Ext.define('Ext.tree.Column', { + extend: 'Ext.grid.column.Column', + alias: 'widget.treecolumn', + + tdCls: Ext.baseCSSPrefix + 'grid-cell-treecolumn', + + initComponent: function() { + var origRenderer = this.renderer || this.defaultRenderer, + origScope = this.scope || window; + + this.renderer = function(value, metaData, record, rowIdx, colIdx, store, view) { + var buf = [], + format = Ext.String.format, + depth = record.getDepth(), + treePrefix = Ext.baseCSSPrefix + 'tree-', + elbowPrefix = treePrefix + 'elbow-', + expanderCls = treePrefix + 'expander', + imgText = '', + checkboxText= '', + formattedValue = origRenderer.apply(origScope, arguments), + href = record.get('href'), + target = record.get('hrefTarget'), + cls = record.get('cls'); + + while (record) { + if (!record.isRoot() || (record.isRoot() && view.rootVisible)) { + if (record.getDepth() === depth) { + buf.unshift(format(imgText, + treePrefix + 'icon ' + + treePrefix + 'icon' + (record.get('icon') ? '-inline ' : (record.isLeaf() ? '-leaf ' : '-parent ')) + + (record.get('iconCls') || ''), + record.get('icon') || Ext.BLANK_IMAGE_URL + )); + if (record.get('checked') !== null) { + buf.unshift(format( + checkboxText, + (treePrefix + 'checkbox') + (record.get('checked') ? ' ' + treePrefix + 'checkbox-checked' : ''), + record.get('checked') ? 'aria-checked="true"' : '' + )); + if (record.get('checked')) { + metaData.tdCls += (' ' + treePrefix + 'checked'); + } + } + if (record.isLast()) { + if (record.isExpandable()) { + buf.unshift(format(imgText, (elbowPrefix + 'end-plus ' + expanderCls), Ext.BLANK_IMAGE_URL)); + } else { + buf.unshift(format(imgText, (elbowPrefix + 'end'), Ext.BLANK_IMAGE_URL)); + } + + } else { + if (record.isExpandable()) { + buf.unshift(format(imgText, (elbowPrefix + 'plus ' + expanderCls), Ext.BLANK_IMAGE_URL)); + } else { + buf.unshift(format(imgText, (treePrefix + 'elbow'), Ext.BLANK_IMAGE_URL)); + } + } + } else { + if (record.isLast() || record.getDepth() === 0) { + buf.unshift(format(imgText, (elbowPrefix + 'empty'), Ext.BLANK_IMAGE_URL)); + } else if (record.getDepth() !== 0) { + buf.unshift(format(imgText, (elbowPrefix + 'line'), Ext.BLANK_IMAGE_URL)); + } + } + } + record = record.parentNode; + } + if (href) { + buf.push('', formattedValue, ''); + } else { + buf.push(formattedValue); + } + if (cls) { + metaData.tdCls += ' ' + cls; + } + return buf.join(''); + }; + this.callParent(arguments); + }, + + defaultRenderer: function(value) { + return value; + } +}); + +Ext.define('Ext.view.DragZone', { + extend: 'Ext.dd.DragZone', + containerScroll: false, + + constructor: function(config) { + var me = this; + + Ext.apply(me, config); + + + + + + + if (!me.ddGroup) { + me.ddGroup = 'view-dd-zone-' + me.view.id; + } + + + + + + + + + me.callParent([me.view.el.dom.parentNode]); + + me.ddel = Ext.get(document.createElement('div')); + me.ddel.addCls(Ext.baseCSSPrefix + 'grid-dd-wrap'); + }, + + init: function(id, sGroup, config) { + this.initTarget(id, sGroup, config); + this.view.mon(this.view, { + itemmousedown: this.onItemMouseDown, + scope: this + }); + }, + + onItemMouseDown: function(view, record, item, index, e) { + if (!this.isPreventDrag(e, record, item, index)) { + this.handleMouseDown(e); + + + + if (view.getSelectionModel().selectionMode == 'MULTI' && !e.ctrlKey && view.getSelectionModel().isSelected(record)) { + return false; + } + } + }, + + + isPreventDrag: function(e) { + return false; + }, + + getDragData: function(e) { + var view = this.view, + item = e.getTarget(view.getItemSelector()); + + if (item) { + return { + copy: view.copy || (view.allowCopy && e.ctrlKey), + event: new Ext.EventObjectImpl(e), + view: view, + ddel: this.ddel, + item: item, + records: view.getSelectionModel().getSelection(), + fromPosition: Ext.fly(item).getXY() + }; + } + }, + + onInitDrag: function(x, y) { + var me = this, + data = me.dragData, + view = data.view, + selectionModel = view.getSelectionModel(), + record = view.getRecord(data.item), + e = data.event; + + + + if (!selectionModel.isSelected(record) || e.hasModifier()) { + selectionModel.selectWithEvent(record, e, true); + } + data.records = selectionModel.getSelection(); + + me.ddel.update(me.getDragText()); + me.proxy.update(me.ddel.dom); + me.onStartDrag(x, y); + return true; + }, + + getDragText: function() { + var count = this.dragData.records.length; + return Ext.String.format(this.dragText, count, count == 1 ? '' : 's'); + }, + + getRepairXY : function(e, data){ + return data ? data.fromPosition : false; + } +}); + +Ext.define('Ext.tree.ViewDragZone', { + extend: 'Ext.view.DragZone', + + isPreventDrag: function(e, record) { + return (record.get('allowDrag') === false) || !!e.getTarget(this.view.expanderSelector); + }, + + afterRepair: function() { + var me = this, + view = me.view, + selectedRowCls = view.selectedItemCls, + records = me.dragData.records, + r, + rLen = records.length, + fly = Ext.fly, + item; + + if (Ext.enableFx && me.repairHighlight) { + + for (r = 0; r < rLen; r++) { + + + item = view.getNode(records[r]); + + + + fly(item.firstChild).highlight(me.repairHighlightColor, { + listeners: { + beforeanimate: function() { + if (view.isSelected(item)) { + fly(item).removeCls(selectedRowCls); + } + }, + afteranimate: function() { + if (view.isSelected(item)) { + fly(item).addCls(selectedRowCls); + } + } + } + }); + } + + } + me.dragging = false; + } +}); + +Ext.define('Ext.view.DropZone', { + extend: 'Ext.dd.DropZone', + + indicatorHtml: '
', + indicatorCls: Ext.baseCSSPrefix + 'grid-drop-indicator', + + constructor: function(config) { + var me = this; + Ext.apply(me, config); + + + + + + + if (!me.ddGroup) { + me.ddGroup = 'view-dd-zone-' + me.view.id; + } + + + + + me.callParent([me.view.el]); + }, + + + + fireViewEvent: function() { + var me = this, + result; + + me.lock(); + result = me.view.fireEvent.apply(me.view, arguments); + me.unlock(); + return result; + }, + + getTargetFromEvent : function(e) { + var node = e.getTarget(this.view.getItemSelector()), + mouseY, nodeList, testNode, i, len, box; + + + + if (!node) { + mouseY = e.getPageY(); + for (i = 0, nodeList = this.view.getNodes(), len = nodeList.length; i < len; i++) { + testNode = nodeList[i]; + box = Ext.fly(testNode).getBox(); + if (mouseY <= box.bottom) { + return testNode; + } + } + } + return node; + }, + + getIndicator: function() { + var me = this; + + if (!me.indicator) { + me.indicator = new Ext.Component({ + html: me.indicatorHtml, + cls: me.indicatorCls, + ownerCt: me.view, + floating: true, + shadow: false + }); + } + return me.indicator; + }, + + getPosition: function(e, node) { + var y = e.getXY()[1], + region = Ext.fly(node).getRegion(), + pos; + + if ((region.bottom - y) >= (region.bottom - region.top) / 2) { + pos = "before"; + } else { + pos = "after"; + } + return pos; + }, + + + containsRecordAtOffset: function(records, record, offset) { + if (!record) { + return false; + } + var view = this.view, + recordIndex = view.indexOf(record), + nodeBefore = view.getNode(recordIndex + offset), + recordBefore = nodeBefore ? view.getRecord(nodeBefore) : null; + + return recordBefore && Ext.Array.contains(records, recordBefore); + }, + + positionIndicator: function(node, data, e) { + var me = this, + view = me.view, + pos = me.getPosition(e, node), + overRecord = view.getRecord(node), + draggingRecords = data.records, + indicatorY; + + if (!Ext.Array.contains(draggingRecords, overRecord) && ( + pos == 'before' && !me.containsRecordAtOffset(draggingRecords, overRecord, -1) || + pos == 'after' && !me.containsRecordAtOffset(draggingRecords, overRecord, 1) + )) { + me.valid = true; + + if (me.overRecord != overRecord || me.currentPosition != pos) { + + indicatorY = Ext.fly(node).getY() - view.el.getY() - 1; + if (pos == 'after') { + indicatorY += Ext.fly(node).getHeight(); + } + me.getIndicator().setWidth(Ext.fly(view.el).getWidth()).showAt(0, indicatorY); + + + me.overRecord = overRecord; + me.currentPosition = pos; + } + } else { + me.invalidateDrop(); + } + }, + + invalidateDrop: function() { + if (this.valid) { + this.valid = false; + this.getIndicator().hide(); + } + }, + + + onNodeOver: function(node, dragZone, e, data) { + var me = this; + + if (!Ext.Array.contains(data.records, me.view.getRecord(node))) { + me.positionIndicator(node, data, e); + } + return me.valid ? me.dropAllowed : me.dropNotAllowed; + }, + + + + notifyOut: function(node, dragZone, e, data) { + var me = this; + + me.callParent(arguments); + delete me.overRecord; + delete me.currentPosition; + if (me.indicator) { + me.indicator.hide(); + } + }, + + + onContainerOver : function(dd, e, data) { + var me = this, + view = me.view, + count = view.store.getCount(); + + + if (count) { + me.positionIndicator(view.getNode(count - 1), data, e); + } + + + else { + delete me.overRecord; + delete me.currentPosition; + me.getIndicator().setWidth(Ext.fly(view.el).getWidth()).showAt(0, 0); + me.valid = true; + } + return me.dropAllowed; + }, + + onContainerDrop : function(dd, e, data) { + return this.onNodeDrop(dd, null, e, data); + }, + + onNodeDrop: function(node, dragZone, e, data) { + var me = this, + dropHandled = false, + + + + + + + dropHandlers = { + wait: false, + processDrop: function () { + me.invalidateDrop(); + me.handleNodeDrop(data, me.overRecord, me.currentPosition); + dropHandled = true; + me.fireViewEvent('drop', node, data, me.overRecord, me.currentPosition); + }, + + cancelDrop: function() { + me.invalidateDrop(); + dropHandled = true; + } + }, + performOperation = false; + + if (me.valid) { + performOperation = me.fireViewEvent('beforedrop', node, data, me.overRecord, me.currentPosition, dropHandlers); + if (dropHandlers.wait) { + return; + } + + if (performOperation !== false) { + + if (!dropHandled) { + dropHandlers.processDrop(); + } + } + } + return performOperation; + }, + + destroy: function(){ + Ext.destroy(this.indicator); + delete this.indicator; + this.callParent(); + } +}); + + +Ext.define('Ext.grid.ViewDropZone', { + extend: 'Ext.view.DropZone', + + indicatorHtml: '
', + indicatorCls: Ext.baseCSSPrefix + 'grid-drop-indicator', + + handleNodeDrop : function(data, record, position) { + var view = this.view, + store = view.getStore(), + index, records, i, len; + + + if (data.copy) { + records = data.records; + data.records = []; + for (i = 0, len = records.length; i < len; i++) { + data.records.push(records[i].copy(records[i].getId())); + } + } else { + + data.view.store.remove(data.records, data.view === view); + } + + index = store.indexOf(record); + + + if (position !== 'before') { + index++; + } + store.insert(index, data.records); + view.getSelectionModel().select(data.records); + } +}); + +Ext.define('Ext.tree.ViewDropZone', { + extend: 'Ext.view.DropZone', + + + allowParentInserts: false, + + + allowContainerDrops: false, + + + appendOnly: false, + + + expandDelay : 500, + + indicatorCls: Ext.baseCSSPrefix + 'tree-ddindicator', + + + expandNode : function(node) { + var view = this.view; + if (!node.isLeaf() && !node.isExpanded()) { + view.expand(node); + this.expandProcId = false; + } + }, + + + queueExpand : function(node) { + this.expandProcId = Ext.Function.defer(this.expandNode, this.expandDelay, this, [node]); + }, + + + cancelExpand : function() { + if (this.expandProcId) { + clearTimeout(this.expandProcId); + this.expandProcId = false; + } + }, + + getPosition: function(e, node) { + var view = this.view, + record = view.getRecord(node), + y = e.getPageY(), + noAppend = record.isLeaf(), + noBelow = false, + region = Ext.fly(node).getRegion(), + fragment; + + + if (record.isRoot()) { + return 'append'; + } + + + if (this.appendOnly) { + return noAppend ? false : 'append'; + } + + if (!this.allowParentInsert) { + noBelow = record.hasChildNodes() && record.isExpanded(); + } + + fragment = (region.bottom - region.top) / (noAppend ? 2 : 3); + if (y >= region.top && y < (region.top + fragment)) { + return 'before'; + } + else if (!noBelow && (noAppend || (y >= (region.bottom - fragment) && y <= region.bottom))) { + return 'after'; + } + else { + return 'append'; + } + }, + + isValidDropPoint : function(node, position, dragZone, e, data) { + if (!node || !data.item) { + return false; + } + + var view = this.view, + targetNode = view.getRecord(node), + draggedRecords = data.records, + dataLength = draggedRecords.length, + ln = draggedRecords.length, + i, record; + + + if (!(targetNode && position && dataLength)) { + return false; + } + + + for (i = 0; i < ln; i++) { + record = draggedRecords[i]; + if (record.isNode && record.contains(targetNode)) { + return false; + } + } + + + if (position === 'append' && targetNode.get('allowDrop') === false) { + return false; + } + else if (position != 'append' && targetNode.parentNode.get('allowDrop') === false) { + return false; + } + + + if (Ext.Array.contains(draggedRecords, targetNode)) { + return false; + } + + + + return true; + }, + + onNodeOver : function(node, dragZone, e, data) { + var position = this.getPosition(e, node), + returnCls = this.dropNotAllowed, + view = this.view, + targetNode = view.getRecord(node), + indicator = this.getIndicator(), + indicatorX = 0, + indicatorY = 0; + + + this.cancelExpand(); + if (position == 'append' && !this.expandProcId && !Ext.Array.contains(data.records, targetNode) && !targetNode.isLeaf() && !targetNode.isExpanded()) { + this.queueExpand(targetNode); + } + + + if (this.isValidDropPoint(node, position, dragZone, e, data)) { + this.valid = true; + this.currentPosition = position; + this.overRecord = targetNode; + + indicator.setWidth(Ext.fly(node).getWidth()); + indicatorY = Ext.fly(node).getY() - Ext.fly(view.el).getY() - 1; + + + if (position == 'before') { + returnCls = targetNode.isFirst() ? Ext.baseCSSPrefix + 'tree-drop-ok-above' : Ext.baseCSSPrefix + 'tree-drop-ok-between'; + indicator.showAt(0, indicatorY); + dragZone.proxy.show(); + } else if (position == 'after') { + returnCls = targetNode.isLast() ? Ext.baseCSSPrefix + 'tree-drop-ok-below' : Ext.baseCSSPrefix + 'tree-drop-ok-between'; + indicatorY += Ext.fly(node).getHeight(); + indicator.showAt(0, indicatorY); + dragZone.proxy.show(); + } else { + returnCls = Ext.baseCSSPrefix + 'tree-drop-ok-append'; + + indicator.hide(); + } + } else { + this.valid = false; + } + + this.currentCls = returnCls; + return returnCls; + }, + + onContainerOver : function(dd, e, data) { + return e.getTarget('.' + this.indicatorCls) ? this.currentCls : this.dropNotAllowed; + }, + + notifyOut: function() { + this.callParent(arguments); + this.cancelExpand(); + }, + + handleNodeDrop : function(data, targetNode, position) { + var me = this, + view = me.view, + parentNode = targetNode.parentNode, + store = view.getStore(), + recordDomNodes = [], + records, i, len, + insertionMethod, argList, + needTargetExpand, + transferData, + processDrop; + + + if (data.copy) { + records = data.records; + data.records = []; + for (i = 0, len = records.length; i < len; i++) { + data.records.push(Ext.apply({}, records[i].data)); + } + } + + + me.cancelExpand(); + + + + + + if (position == 'before') { + insertionMethod = parentNode.insertBefore; + argList = [null, targetNode]; + targetNode = parentNode; + } + else if (position == 'after') { + if (targetNode.nextSibling) { + insertionMethod = parentNode.insertBefore; + argList = [null, targetNode.nextSibling]; + } + else { + insertionMethod = parentNode.appendChild; + argList = [null]; + } + targetNode = parentNode; + } + else { + if (!targetNode.isExpanded()) { + needTargetExpand = true; + } + insertionMethod = targetNode.appendChild; + argList = [null]; + } + + + transferData = function() { + var node, + r, rLen, color, n; + for (i = 0, len = data.records.length; i < len; i++) { + argList[0] = data.records[i]; + node = insertionMethod.apply(targetNode, argList); + + if (Ext.enableFx && me.dropHighlight) { + recordDomNodes.push(view.getNode(node)); + } + } + + + + if (Ext.enableFx && me.dropHighlight) { + + + rLen = recordDomNodes.length; + color = me.dropHighlightColor; + + for (r = 0; r < rLen; r++) { + n = recordDomNodes[r]; + + if (n) { + Ext.fly(n.firstChild ? n.firstChild : n).highlight(color); + } + } + } + }; + + + if (needTargetExpand) { + targetNode.expand(false, transferData); + } + + else { + transferData(); + } + } +}); + +Ext.define('Ext.view.TableChunker', { + singleton: true, + requires: ['Ext.XTemplate'], + metaTableTpl: [ + '{%if (this.openTableWrap)out.push(this.openTableWrap())%}', + '', + '', + '', + '', + '', + '', + '', + '{[this.openRows()]}', + '{row}', + '', + '{[this.embedFeature(values, parent, xindex, xcount)]}', + '', + '{[this.closeRows()]}', + '', + '
', + '{%if (this.closeTableWrap)out.push(this.closeTableWrap())%}' + ], + + constructor: function() { + Ext.XTemplate.prototype.recurse = function(values, reference) { + return this.apply(reference ? values[reference] : values); + }; + }, + + embedFeature: function(values, parent, x, xcount) { + var tpl = ''; + if (!values.disabled) { + tpl = values.getFeatureTpl(values, parent, x, xcount); + } + return tpl; + }, + + embedFullWidth: function(values) { + var result = 'style="width:{fullWidth}px;'; + + + + if (!values.rowCount) { + result += 'height:1px;'; + } + return result + '"'; + }, + + openRows: function() { + return ''; + }, + + closeRows: function() { + return ''; + }, + + metaRowTpl: [ + '', + '', + '', + '
{{id}}
', + '', + '
', + '' + ], + + firstOrLastCls: function(xindex, xcount) { + if (xindex === 1) { + return Ext.view.Table.prototype.firstCls; + } else if (xindex === xcount) { + return Ext.view.Table.prototype.lastCls; + } + }, + + embedRowCls: function() { + return '{rowCls}'; + }, + + embedRowAttr: function() { + return '{rowAttr}'; + }, + + openTableWrap: undefined, + + closeTableWrap: undefined, + + getTableTpl: function(cfg, textOnly) { + var tpl, + tableTplMemberFns = { + openRows: this.openRows, + closeRows: this.closeRows, + embedFeature: this.embedFeature, + embedFullWidth: this.embedFullWidth, + openTableWrap: this.openTableWrap, + closeTableWrap: this.closeTableWrap + }, + tplMemberFns = {}, + features = cfg.features || [], + ln = features.length, + i = 0, + memberFns = { + embedRowCls: this.embedRowCls, + embedRowAttr: this.embedRowAttr, + firstOrLastCls: this.firstOrLastCls, + unselectableAttr: cfg.enableTextSelection ? '' : 'unselectable="on"', + unselectableCls: cfg.enableTextSelection ? '' : Ext.baseCSSPrefix + 'unselectable' + }, + + metaRowTpl = Array.prototype.slice.call(this.metaRowTpl, 0), + metaTableTpl; + + for (; i < ln; i++) { + if (!features[i].disabled) { + features[i].mutateMetaRowTpl(metaRowTpl); + Ext.apply(memberFns, features[i].getMetaRowTplFragments()); + Ext.apply(tplMemberFns, features[i].getFragmentTpl()); + Ext.apply(tableTplMemberFns, features[i].getTableFragments()); + } + } + + metaRowTpl = new Ext.XTemplate(metaRowTpl.join(''), memberFns); + cfg.row = metaRowTpl.applyTemplate(cfg); + + metaTableTpl = new Ext.XTemplate(this.metaTableTpl.join(''), tableTplMemberFns); + + tpl = metaTableTpl.applyTemplate(cfg); + + + if (!textOnly) { + tpl = new Ext.XTemplate(tpl, tplMemberFns); + } + return tpl; + + } +}); + + +Ext.define('Ext.view.View', { + extend: 'Ext.view.AbstractView', + alternateClassName: 'Ext.DataView', + alias: 'widget.dataview', + + inheritableStatics: { + EventMap: { + mousedown: 'MouseDown', + mouseup: 'MouseUp', + click: 'Click', + dblclick: 'DblClick', + contextmenu: 'ContextMenu', + mouseover: 'MouseOver', + mouseout: 'MouseOut', + mouseenter: 'MouseEnter', + mouseleave: 'MouseLeave', + keydown: 'KeyDown', + focus: 'Focus' + } + }, + + addCmpEvents: function() { + this.addEvents( + + 'beforeitemmousedown', + + 'beforeitemmouseup', + + 'beforeitemmouseenter', + + 'beforeitemmouseleave', + + 'beforeitemclick', + + 'beforeitemdblclick', + + 'beforeitemcontextmenu', + + 'beforeitemkeydown', + + 'itemmousedown', + + 'itemmouseup', + + 'itemmouseenter', + + 'itemmouseleave', + + 'itemclick', + + 'itemdblclick', + + 'itemcontextmenu', + + 'itemkeydown', + + 'beforecontainermousedown', + + 'beforecontainermouseup', + + 'beforecontainermouseover', + + 'beforecontainermouseout', + + 'beforecontainerclick', + + 'beforecontainerdblclick', + + 'beforecontainercontextmenu', + + 'beforecontainerkeydown', + + 'containermouseup', + + 'containermouseover', + + 'containermouseout', + + 'containerclick', + + 'containerdblclick', + + 'containercontextmenu', + + 'containerkeydown', + + + 'selectionchange', + + 'beforeselect', + + + 'highlightitem', + + + 'unhighlightitem' + ); + }, + + getFocusEl: function() { + return this.getTargetEl(); + }, + + + afterRender: function(){ + var me = this; + me.callParent(); + me.mon(me.getTargetEl(), { + scope: me, + + freezeEvent: true, + click: me.handleEvent, + mousedown: me.handleEvent, + mouseup: me.handleEvent, + dblclick: me.handleEvent, + contextmenu: me.handleEvent, + mouseover: me.handleEvent, + mouseout: me.handleEvent, + keydown: me.handleEvent + }); + }, + + handleEvent: function(e) { + var key = e.type == 'keydown' && e.getKey(); + + if (this.processUIEvent(e) !== false) { + this.processSpecialEvent(e); + } + + + + + if (key === e.SPACE) { + e.stopEvent(); + } + }, + + + processItemEvent: Ext.emptyFn, + processContainerEvent: Ext.emptyFn, + processSpecialEvent: Ext.emptyFn, + + + stillOverItem: function (event, overItem) { + var nowOver; + + + + + + + + if (overItem && typeof(overItem.offsetParent) === "object") { + + + nowOver = (event.type == 'mouseout') ? event.getRelatedTarget() : event.getTarget(); + return Ext.fly(overItem).contains(nowOver); + } + + return false; + }, + + processUIEvent: function(e) { + var me = this, + item = e.getTarget(me.getItemSelector(), me.getTargetEl()), + map = this.statics().EventMap, + index, record, + type = e.type, + overItem = me.mouseOverItem, + newType; + + if (!item) { + if (type == 'mouseover' && me.stillOverItem(e, overItem)) { + item = overItem; + } + + + if (type == 'keydown') { + record = me.getSelectionModel().getLastSelected(); + if (record) { + item = me.getNode(record); + } + } + } + + if (item) { + index = me.indexOf(item); + if (!record) { + record = me.getRecord(item); + } + + + + + if (!record || me.processItemEvent(record, item, index, e) === false) { + return false; + } + + newType = me.isNewItemEvent(item, e); + if (newType === false) { + return false; + } + + if ( + (me['onBeforeItem' + map[newType]](record, item, index, e) === false) || + (me.fireEvent('beforeitem' + newType, me, record, item, index, e) === false) || + (me['onItem' + map[newType]](record, item, index, e) === false) + ) { + return false; + } + + me.fireEvent('item' + newType, me, record, item, index, e); + } + else { + if ( + (me.processContainerEvent(e) === false) || + (me['onBeforeContainer' + map[type]](e) === false) || + (me.fireEvent('beforecontainer' + type, me, e) === false) || + (me['onContainer' + map[type]](e) === false) + ) { + return false; + } + + me.fireEvent('container' + type, me, e); + } + + return true; + }, + + isNewItemEvent: function (item, e) { + var me = this, + overItem = me.mouseOverItem, + type = e.type; + + switch (type) { + case 'mouseover': + if (item === overItem) { + return false; + } + me.mouseOverItem = item; + return 'mouseenter'; + + case 'mouseout': + + if (me.stillOverItem(e, overItem)) { + return false; + } + me.mouseOverItem = null; + return 'mouseleave'; + } + return type; + }, + + + onItemMouseEnter: function(record, item, index, e) { + if (this.trackOver) { + this.highlightItem(item); + } + }, + + + onItemMouseLeave : function(record, item, index, e) { + if (this.trackOver) { + this.clearHighlight(); + } + }, + + + onItemMouseDown: Ext.emptyFn, + onItemMouseUp: Ext.emptyFn, + onItemFocus: Ext.emptyFn, + onItemClick: Ext.emptyFn, + onItemDblClick: Ext.emptyFn, + onItemContextMenu: Ext.emptyFn, + onItemKeyDown: Ext.emptyFn, + onBeforeItemMouseDown: Ext.emptyFn, + onBeforeItemMouseUp: Ext.emptyFn, + onBeforeItemFocus: Ext.emptyFn, + onBeforeItemMouseEnter: Ext.emptyFn, + onBeforeItemMouseLeave: Ext.emptyFn, + onBeforeItemClick: Ext.emptyFn, + onBeforeItemDblClick: Ext.emptyFn, + onBeforeItemContextMenu: Ext.emptyFn, + onBeforeItemKeyDown: Ext.emptyFn, + + + onContainerMouseDown: Ext.emptyFn, + onContainerMouseUp: Ext.emptyFn, + onContainerMouseOver: Ext.emptyFn, + onContainerMouseOut: Ext.emptyFn, + onContainerClick: Ext.emptyFn, + onContainerDblClick: Ext.emptyFn, + onContainerContextMenu: Ext.emptyFn, + onContainerKeyDown: Ext.emptyFn, + onBeforeContainerMouseDown: Ext.emptyFn, + onBeforeContainerMouseUp: Ext.emptyFn, + onBeforeContainerMouseOver: Ext.emptyFn, + onBeforeContainerMouseOut: Ext.emptyFn, + onBeforeContainerClick: Ext.emptyFn, + onBeforeContainerDblClick: Ext.emptyFn, + onBeforeContainerContextMenu: Ext.emptyFn, + onBeforeContainerKeyDown: Ext.emptyFn, + + + highlightItem: function(item) { + var me = this; + me.clearHighlight(); + me.highlightedItem = item; + Ext.fly(item).addCls(me.overItemCls); + me.fireEvent('highlightitem', me, item); + }, + + + clearHighlight: function() { + var me = this, + highlighted = me.highlightedItem; + + if (highlighted) { + Ext.fly(highlighted).removeCls(me.overItemCls); + me.fireEvent('unhighlightitem', me, highlighted); + delete me.highlightedItem; + } + }, + + onUpdate: function(store, record){ + var me = this, + node, + newNode, + highlighted; + + if (me.rendered) { + node = me.getNode(record); + newNode = me.callParent(arguments); + highlighted = me.highlightedItem; + + if (highlighted && highlighted === node) { + delete me.highlightedItem; + if (newNode) { + me.highlightItem(newNode); + } + } + } + }, + + refresh: function() { + this.clearHighlight(); + this.callParent(arguments); + } +}); + +Ext.define('Ext.view.BoundList', { + extend: 'Ext.view.View', + alias: 'widget.boundlist', + alternateClassName: 'Ext.BoundList', + requires: ['Ext.layout.component.BoundList', 'Ext.toolbar.Paging'], + + + pageSize: 0, + + + + + + + baseCls: Ext.baseCSSPrefix + 'boundlist', + itemCls: Ext.baseCSSPrefix + 'boundlist-item', + listItemCls: '', + shadow: false, + trackOver: true, + refreshed: 0, + + + deferInitialRefresh: false, + + componentLayout: 'boundlist', + + childEls: [ + 'listEl' + ], + + renderTpl: [ + '
', + '{%', + 'var me=values.$comp, pagingToolbar=me.pagingToolbar;', + 'if (pagingToolbar) {', + 'pagingToolbar.ownerLayout = me.componentLayout;', + 'Ext.DomHelper.generateMarkup(pagingToolbar.getRenderTree(), out);', + '}', + '%}', + { + disableFormats: true + } + ], + + + + initComponent: function() { + var me = this, + baseCls = me.baseCls, + itemCls = me.itemCls; + + me.selectedItemCls = baseCls + '-selected'; + me.overItemCls = baseCls + '-item-over'; + me.itemSelector = "." + itemCls; + + if (me.floating) { + me.addCls(baseCls + '-floating'); + } + + if (!me.tpl) { + + + me.tpl = new Ext.XTemplate( + '
    ', + '
  • ' + me.getInnerTpl(me.displayField) + '
  • ', + '
' + ); + } else if (Ext.isString(me.tpl)) { + me.tpl = new Ext.XTemplate(me.tpl); + } + + if (me.pageSize) { + me.pagingToolbar = me.createPagingToolbar(); + } + + me.callParent(); + }, + + + up: function(selector) { + var result = this.pickerField; + if (selector) { + for (; result; result = result.ownerCt) { + if (Ext.ComponentQuery.is(result, selector)) { + return result; + } + } + } + return result; + }, + + createPagingToolbar: function() { + return Ext.widget('pagingtoolbar', { + id: this.id + '-paging-toolbar', + pageSize: this.pageSize, + store: this.store, + border: false + }); + }, + + + + finishRenderChildren: function () { + var toolbar = this.pagingToolbar; + + this.callParent(arguments); + + if (toolbar) { + toolbar.finishRender(); + } + }, + + refresh: function(){ + var me = this, + toolbar = me.pagingToolbar; + + me.callParent(); + + + if (me.rendered && toolbar && !me.preserveScrollOnRefresh) { + me.el.appendChild(toolbar.el); + } + }, + + bindStore : function(store, initial) { + var toolbar = this.pagingToolbar; + + this.callParent(arguments); + if (toolbar) { + toolbar.bindStore(this.store, initial); + } + }, + + getTargetEl: function() { + return this.listEl || this.el; + }, + + + getInnerTpl: function(displayField) { + return '{' + displayField + '}'; + }, + + onDestroy: function() { + Ext.destroyMembers(this, 'pagingToolbar', 'listEl'); + this.callParent(); + } +}); + + +Ext.define('Ext.picker.Time', { + extend: 'Ext.view.BoundList', + alias: 'widget.timepicker', + requires: ['Ext.data.Store', 'Ext.Date'], + + + + + + + increment: 15, + + + + format : "g:i A", + + + + displayField: 'disp', + + + initDate: [2008,0,1], + + componentCls: Ext.baseCSSPrefix + 'timepicker', + + + loadMask: false, + + initComponent: function() { + var me = this, + dateUtil = Ext.Date, + clearTime = dateUtil.clearTime, + initDate = me.initDate; + + + me.absMin = clearTime(new Date(initDate[0], initDate[1], initDate[2])); + me.absMax = dateUtil.add(clearTime(new Date(initDate[0], initDate[1], initDate[2])), 'mi', (24 * 60) - 1); + + me.store = me.createStore(); + me.updateList(); + + me.callParent(); + }, + + + setMinValue: function(value) { + this.minValue = value; + this.updateList(); + }, + + + setMaxValue: function(value) { + this.maxValue = value; + this.updateList(); + }, + + + normalizeDate: function(date) { + var initDate = this.initDate; + date.setFullYear(initDate[0], initDate[1], initDate[2]); + return date; + }, + + + updateList: function() { + var me = this, + min = me.normalizeDate(me.minValue || me.absMin), + max = me.normalizeDate(me.maxValue || me.absMax); + + me.store.filterBy(function(record) { + var date = record.get('date'); + return date >= min && date <= max; + }); + }, + + + createStore: function() { + var me = this, + utilDate = Ext.Date, + times = [], + min = me.absMin, + max = me.absMax; + + while(min <= max){ + times.push({ + disp: utilDate.dateFormat(min, me.format), + date: min + }); + min = utilDate.add(min, 'mi', me.increment); + } + + return new Ext.data.Store({ + fields: ['disp', 'date'], + data: times + }); + } + +}); + + +Ext.define('Ext.view.BoundListKeyNav', { + extend: 'Ext.util.KeyNav', + requires: 'Ext.view.BoundList', + + + + constructor: function(el, config) { + var me = this; + me.boundList = config.boundList; + me.callParent([el, Ext.apply({}, config, me.defaultHandlers)]); + }, + + defaultHandlers: { + up: function() { + var me = this, + boundList = me.boundList, + allItems = boundList.all, + oldItem = boundList.highlightedItem, + oldItemIdx = oldItem ? boundList.indexOf(oldItem) : -1, + newItemIdx = oldItemIdx > 0 ? oldItemIdx - 1 : allItems.getCount() - 1; + me.highlightAt(newItemIdx); + }, + + down: function() { + var me = this, + boundList = me.boundList, + allItems = boundList.all, + oldItem = boundList.highlightedItem, + oldItemIdx = oldItem ? boundList.indexOf(oldItem) : -1, + newItemIdx = oldItemIdx < allItems.getCount() - 1 ? oldItemIdx + 1 : 0; + me.highlightAt(newItemIdx); + }, + + pageup: function() { + + }, + + pagedown: function() { + + }, + + home: function() { + this.highlightAt(0); + }, + + end: function() { + var me = this; + me.highlightAt(me.boundList.all.getCount() - 1); + }, + + enter: function(e) { + this.selectHighlighted(e); + } + }, + + + highlightAt: function(index) { + var boundList = this.boundList, + item = boundList.all.item(index); + if (item) { + item = item.dom; + boundList.highlightItem(item); + boundList.getTargetEl().scrollChildIntoView(item, false); + } + }, + + + selectHighlighted: function(e) { + var me = this, + boundList = me.boundList, + highlighted = boundList.highlightedItem, + selModel = boundList.getSelectionModel(); + if (highlighted) { + selModel.selectWithEvent(boundList.getRecord(highlighted), e); + } + } + +}); + +Ext.define('Ext.form.field.ComboBox', { + extend:'Ext.form.field.Picker', + requires: ['Ext.util.DelayedTask', 'Ext.EventObject', 'Ext.view.BoundList', 'Ext.view.BoundListKeyNav', 'Ext.data.StoreManager', 'Ext.layout.component.field.ComboBox'], + alternateClassName: 'Ext.form.ComboBox', + alias: ['widget.combobox', 'widget.combo'], + mixins: { + bindable: 'Ext.util.Bindable' + }, + + componentLayout: 'combobox', + + + triggerCls: Ext.baseCSSPrefix + 'form-arrow-trigger', + + + hiddenName: '', + + + hiddenDataCls: Ext.baseCSSPrefix + 'hide-display ' + Ext.baseCSSPrefix + 'form-data-hidden', + + + fieldSubTpl: [ + '', + ' value="{[Ext.util.Format.htmlEncode(values.value)]}"', + ' name="{name}"', + ' placeholder="{placeholder}"', + ' size="{size}"', + ' maxlength="{maxLength}"', + ' readonly="readonly"', + ' disabled="disabled"', + ' tabIndex="{tabIdx}"', + ' style="{fieldStyle}"', + '/>', + { + compiled: true, + disableFormats: true + } + ], + + getSubTplData: function(){ + var me = this; + Ext.applyIf(me.subTplData, { + hiddenDataCls: me.hiddenDataCls + }); + return me.callParent(arguments); + }, + + afterRender: function(){ + var me = this; + me.callParent(arguments); + me.setHiddenValue(me.value); + }, + + + + + multiSelect: false, + + + + delimiter: ', ', + + + + displayField: 'text', + + + + + triggerAction: 'all', + + + allQuery: '', + + + queryParam: 'query', + + + queryMode: 'remote', + + + queryCaching: true, + + + pageSize: 0, + + + + + + + autoSelect: true, + + + typeAhead: false, + + + typeAheadDelay: 250, + + + selectOnTab: true, + + + forceSelection: false, + + + growToLongestValue: true, + + + + + + + defaultListConfig: { + loadingHeight: 70, + minWidth: 70, + maxHeight: 300, + shadow: 'sides' + }, + + + + + + + ignoreSelection: 0, + + + removingRecords: null, + + + resizeComboToGrow: function () { + var me = this; + return me.grow && me.growToLongestValue; + }, + + initComponent: function() { + var me = this, + isDefined = Ext.isDefined, + store = me.store, + transform = me.transform, + transformSelect, isLocalMode; + + Ext.applyIf(me.renderSelectors, { + hiddenDataEl: '.' + me.hiddenDataCls.split(' ').join('.') + }); + + + this.addEvents( + + 'beforequery', + + + 'select', + + + 'beforeselect', + + + 'beforedeselect' + ); + + + if (transform) { + transformSelect = Ext.getDom(transform); + if (transformSelect) { + if (!me.store) { + store = Ext.Array.map(Ext.Array.from(transformSelect.options), function(option){ + return [option.value, option.text]; + }); + } + if (!me.name) { + me.name = transformSelect.name; + } + if (!('value' in me)) { + me.value = transformSelect.value; + } + } + } + + me.bindStore(store || 'ext-empty-store', true); + store = me.store; + if (store.autoCreated) { + me.queryMode = 'local'; + me.valueField = me.displayField = 'field1'; + if (!store.expanded) { + me.displayField = 'field2'; + } + } + + + if (!isDefined(me.valueField)) { + me.valueField = me.displayField; + } + + isLocalMode = me.queryMode === 'local'; + if (!isDefined(me.queryDelay)) { + me.queryDelay = isLocalMode ? 10 : 500; + } + if (!isDefined(me.minChars)) { + me.minChars = isLocalMode ? 0 : 4; + } + + if (!me.displayTpl) { + me.displayTpl = new Ext.XTemplate( + '' + + '{[typeof values === "string" ? values : values["' + me.displayField + '"]]}' + + '' + me.delimiter + '' + + '' + ); + } else if (Ext.isString(me.displayTpl)) { + me.displayTpl = new Ext.XTemplate(me.displayTpl); + } + + me.callParent(); + + me.doQueryTask = new Ext.util.DelayedTask(me.doRawQuery, me); + + + if (me.store.getCount() > 0) { + me.setValue(me.value); + } + + + if (transformSelect) { + me.render(transformSelect.parentNode, transformSelect); + Ext.removeNode(transformSelect); + delete me.renderTo; + } + }, + + + getStore : function(){ + return this.store; + }, + + beforeBlur: function() { + this.doQueryTask.cancel(); + this.assertValue(); + }, + + + assertValue: function() { + var me = this, + value = me.getRawValue(), + rec; + + if (me.forceSelection) { + if (me.multiSelect) { + + + if (value !== me.getDisplayValue()) { + me.setValue(me.lastSelection); + } + } else { + + + rec = me.findRecordByDisplay(value); + if (rec) { + me.select(rec); + } else { + me.setValue(me.lastSelection); + } + } + } + me.collapse(); + }, + + onTypeAhead: function() { + var me = this, + displayField = me.displayField, + record = me.store.findRecord(displayField, me.getRawValue()), + boundList = me.getPicker(), + newValue, len, selStart; + + if (record) { + newValue = record.get(displayField); + len = newValue.length; + selStart = me.getRawValue().length; + + boundList.highlightItem(boundList.getNode(record)); + + if (selStart !== 0 && selStart !== len) { + me.setRawValue(newValue); + me.selectText(selStart, newValue.length); + } + } + }, + + + + resetToDefault: function() { + + }, + + onUnbindStore: function(store) { + var picker = this.picker; + if (!store && picker) { + picker.bindStore(null); + } + }, + + onBindStore: function(store, initial) { + var picker = this.picker; + if (!initial) { + this.resetToDefault(); + } + if (picker) { + picker.bindStore(store); + } + }, + + getStoreListeners: function() { + var me = this; + + return { + beforeload: me.onBeforeLoad, + clear: me.onClear, + datachanged: me.onDataChanged, + load: me.onLoad, + exception: me.onException, + remove: me.onRemove + }; + }, + + onBeforeLoad: function(){ + + + + ++this.ignoreSelection; + }, + + onDataChanged: function() { + var me = this; + + if (me.resizeComboToGrow()) { + me.updateLayout(); + } + }, + + onClear: function() { + var me = this; + + if (me.resizeComboToGrow()) { + me.removingRecords = true; + me.onDataChanged(); + } + }, + + onRemove: function() { + var me = this; + + if (me.resizeComboToGrow()) { + me.removingRecords = true; + } + }, + + onException: function(){ + if (this.ignoreSelection > 0) { + --this.ignoreSelection; + } + this.collapse(); + }, + + onLoad: function() { + var me = this, + value = me.value; + + if (me.ignoreSelection > 0) { + --me.ignoreSelection; + } + + if (me.rawQuery) { + me.rawQuery = false; + me.syncSelection(); + if (me.picker && !me.picker.getSelectionModel().hasSelection()) { + me.doAutoSelect(); + } + } + + else { + + if (me.value || me.value === 0) { + me.setValue(me.value); + } else { + + + if (me.store.getCount()) { + me.doAutoSelect(); + } else { + + me.setValue(me.value); + } + } + } + }, + + + doRawQuery: function() { + this.doQuery(this.getRawValue(), false, true); + }, + + + doQuery: function(queryString, forceAll, rawQuery) { + queryString = queryString || ''; + + + + var me = this, + qe = { + query: queryString, + forceAll: forceAll, + combo: me, + cancel: false + }, + store = me.store, + isLocalMode = me.queryMode === 'local', + needsRefresh; + + if (me.fireEvent('beforequery', qe) === false || qe.cancel) { + return false; + } + + + queryString = qe.query; + forceAll = qe.forceAll; + + + if (forceAll || (queryString.length >= me.minChars)) { + + me.expand(); + + + if (!me.queryCaching || me.lastQuery !== queryString) { + me.lastQuery = queryString; + + if (isLocalMode) { + + store.suspendEvents(); + needsRefresh = me.clearFilter(); + if (queryString || !forceAll) { + me.activeFilter = new Ext.util.Filter({ + root: 'data', + property: me.displayField, + value: queryString + }); + store.filter(me.activeFilter); + needsRefresh = true; + } else { + delete me.activeFilter; + } + store.resumeEvents(); + if (me.rendered && needsRefresh) { + me.getPicker().refresh(); + } + } else { + + me.rawQuery = rawQuery; + + + + if (me.pageSize) { + + me.loadPage(1); + } else { + store.load({ + params: me.getParams(queryString) + }); + } + } + } + + + if (me.getRawValue() !== me.getDisplayValue()) { + me.ignoreSelection++; + me.picker.getSelectionModel().deselectAll(); + me.ignoreSelection--; + } + + if (isLocalMode) { + me.doAutoSelect(); + } + if (me.typeAhead) { + me.doTypeAhead(); + } + } + return true; + }, + + + clearFilter: function() { + var store = this.store, + filters = store.filters, + filter = this.activeFilter, + remaining; + + if (filter) { + if (filters.getCount() > 1) { + + filters.remove(filter); + remaining = filters.getRange(); + } + store.clearFilter(true); + if (remaining) { + store.filter(remaining); + } + } + return !!filter; + }, + + loadPage: function(pageNum){ + this.store.loadPage(pageNum, { + params: this.getParams(this.lastQuery) + }); + }, + + onPageChange: function(toolbar, newPage){ + + this.loadPage(newPage); + return false; + }, + + + getParams: function(queryString) { + var params = {}, + param = this.queryParam; + + if (param) { + params[param] = queryString; + } + return params; + }, + + + doAutoSelect: function() { + var me = this, + picker = me.picker, + lastSelected, itemNode; + if (picker && me.autoSelect && me.store.getCount() > 0) { + + lastSelected = picker.getSelectionModel().lastSelected; + itemNode = picker.getNode(lastSelected || 0); + if (itemNode) { + picker.highlightItem(itemNode); + picker.listEl.scrollChildIntoView(itemNode, false); + } + } + }, + + doTypeAhead: function() { + if (!this.typeAheadTask) { + this.typeAheadTask = new Ext.util.DelayedTask(this.onTypeAhead, this); + } + if (this.lastKey != Ext.EventObject.BACKSPACE && this.lastKey != Ext.EventObject.DELETE) { + this.typeAheadTask.delay(this.typeAheadDelay); + } + }, + + onTriggerClick: function() { + var me = this; + if (!me.readOnly && !me.disabled) { + if (me.isExpanded) { + me.collapse(); + } else { + me.onFocus({}); + if (me.triggerAction === 'all') { + me.doQuery(me.allQuery, true); + } else { + me.doQuery(me.getRawValue(), false, true); + } + } + me.inputEl.focus(); + } + }, + + + + onKeyUp: function(e, t) { + var me = this, + key = e.getKey(); + + if (!me.readOnly && !me.disabled && me.editable) { + me.lastKey = key; + + + + + if (!e.isSpecialKey() || key == e.BACKSPACE || key == e.DELETE) { + me.doQueryTask.delay(me.queryDelay); + } + } + + if (me.enableKeyEvents) { + me.callParent(arguments); + } + }, + + initEvents: function() { + var me = this; + me.callParent(); + + + if (!me.enableKeyEvents) { + me.mon(me.inputEl, 'keyup', me.onKeyUp, me); + } + }, + + onDestroy: function() { + this.bindStore(null); + this.callParent(); + }, + + + + onAdded: function() { + var me = this; + me.callParent(arguments); + if (me.picker) { + me.picker.ownerCt = me.up('[floating]'); + me.picker.registerWithOwnerCt(); + } + }, + + createPicker: function() { + var me = this, + picker, + menuCls = Ext.baseCSSPrefix + 'menu', + pickerCfg = Ext.apply({ + xtype: 'boundlist', + pickerField: me, + selModel: { + mode: me.multiSelect ? 'SIMPLE' : 'SINGLE' + }, + floating: true, + hidden: true, + + + + ownerCt: me.up('[floating]'), + cls: me.el && me.el.up('.' + menuCls) ? menuCls : '', + store: me.store, + displayField: me.displayField, + focusOnToFront: false, + pageSize: me.pageSize, + tpl: me.tpl + }, me.listConfig, me.defaultListConfig); + + picker = me.picker = Ext.widget(pickerCfg); + if (me.pageSize) { + picker.pagingToolbar.on('beforechange', me.onPageChange, me); + } + + me.mon(picker, { + itemclick: me.onItemClick, + refresh: me.onListRefresh, + scope: me + }); + + me.mon(picker.getSelectionModel(), { + beforeselect: me.onBeforeSelect, + beforedeselect: me.onBeforeDeselect, + selectionchange: me.onListSelectionChange, + scope: me + }); + + return picker; + }, + + alignPicker: function(){ + var me = this, + picker = me.getPicker(), + heightAbove = me.getPosition()[1] - Ext.getBody().getScroll().top, + heightBelow = Ext.Element.getViewHeight() - heightAbove - me.getHeight(), + space = Math.max(heightAbove, heightBelow); + + + if (picker.height) { + delete picker.height; + picker.updateLayout(); + } + + if (picker.getHeight() > space - 5) { + picker.setHeight(space - 5); + } + me.callParent(); + }, + + onListRefresh: function() { + this.alignPicker(); + this.syncSelection(); + }, + + onItemClick: function(picker, record){ + + var me = this, + selection = me.picker.getSelectionModel().getSelection(), + valueField = me.valueField; + + if (!me.multiSelect && selection.length) { + if (record.get(valueField) === selection[0].get(valueField)) { + + me.displayTplData = [record.data]; + me.setRawValue(me.getDisplayValue()); + me.collapse(); + } + } + }, + + onBeforeSelect: function(list, record) { + return this.fireEvent('beforeselect', this, record, record.index); + }, + + onBeforeDeselect: function(list, record) { + return this.fireEvent('beforedeselect', this, record, record.index); + }, + + onListSelectionChange: function(list, selectedRecords) { + var me = this, + isMulti = me.multiSelect, + hasRecords = selectedRecords.length > 0; + + + if (!me.ignoreSelection && me.isExpanded) { + if (!isMulti) { + Ext.defer(me.collapse, 1, me); + } + + if (isMulti || hasRecords) { + me.setValue(selectedRecords, false); + } + if (hasRecords) { + me.fireEvent('select', me, selectedRecords); + } + me.inputEl.focus(); + } + }, + + + onExpand: function() { + var me = this, + keyNav = me.listKeyNav, + selectOnTab = me.selectOnTab, + picker = me.getPicker(); + + + if (keyNav) { + keyNav.enable(); + } else { + keyNav = me.listKeyNav = new Ext.view.BoundListKeyNav(this.inputEl, { + boundList: picker, + forceKeyDown: true, + tab: function(e) { + if (selectOnTab) { + this.selectHighlighted(e); + me.triggerBlur(); + } + + return true; + } + }); + } + + + if (selectOnTab) { + me.ignoreMonitorTab = true; + } + + Ext.defer(keyNav.enable, 1, keyNav); + me.inputEl.focus(); + }, + + + onCollapse: function() { + var me = this, + keyNav = me.listKeyNav; + if (keyNav) { + keyNav.disable(); + me.ignoreMonitorTab = false; + } + }, + + + select: function(r) { + this.setValue(r, true); + }, + + + findRecord: function(field, value) { + var ds = this.store, + idx = ds.findExact(field, value); + return idx !== -1 ? ds.getAt(idx) : false; + }, + + + findRecordByValue: function(value) { + return this.findRecord(this.valueField, value); + }, + + + findRecordByDisplay: function(value) { + return this.findRecord(this.displayField, value); + }, + + + setValue: function(value, doSelect) { + var me = this, + valueNotFoundText = me.valueNotFoundText, + inputEl = me.inputEl, + i, len, record, + dataObj, + matchedRecords = [], + displayTplData = [], + processedValue = []; + + if (me.store.loading) { + + me.value = value; + me.setHiddenValue(me.value); + return me; + } + + + value = Ext.Array.from(value); + + + for (i = 0, len = value.length; i < len; i++) { + record = value[i]; + if (!record || !record.isModel) { + record = me.findRecordByValue(record); + } + + if (record) { + matchedRecords.push(record); + displayTplData.push(record.data); + processedValue.push(record.get(me.valueField)); + } + + + else { + + + if (!me.forceSelection) { + processedValue.push(value[i]); + dataObj = {}; + dataObj[me.displayField] = value[i]; + displayTplData.push(dataObj); + + } + + else if (Ext.isDefined(valueNotFoundText)) { + displayTplData.push(valueNotFoundText); + } + } + } + + + me.setHiddenValue(processedValue); + me.value = me.multiSelect ? processedValue : processedValue[0]; + if (!Ext.isDefined(me.value)) { + me.value = null; + } + me.displayTplData = displayTplData; + me.lastSelection = me.valueModels = matchedRecords; + + if (inputEl && me.emptyText && !Ext.isEmpty(value)) { + inputEl.removeCls(me.emptyCls); + } + + + me.setRawValue(me.getDisplayValue()); + me.checkChange(); + + if (doSelect !== false) { + me.syncSelection(); + } + me.applyEmptyText(); + + return me; + }, + + + setHiddenValue: function(values){ + var me = this, + name = me.hiddenName, + i, + dom, childNodes, input, valueCount, childrenCount; + + if (!me.hiddenDataEl || !name) { + return; + } + values = Ext.Array.from(values); + dom = me.hiddenDataEl.dom; + childNodes = dom.childNodes; + input = childNodes[0]; + valueCount = values.length; + childrenCount = childNodes.length; + + if (!input && valueCount > 0) { + me.hiddenDataEl.update(Ext.DomHelper.markup({ + tag: 'input', + type: 'hidden', + name: name + })); + childrenCount = 1; + input = dom.firstChild; + } + while (childrenCount > valueCount) { + dom.removeChild(childNodes[0]); + -- childrenCount; + } + while (childrenCount < valueCount) { + dom.appendChild(input.cloneNode(true)); + ++ childrenCount; + } + for (i = 0; i < valueCount; i++) { + childNodes[i].value = values[i]; + } + }, + + + getDisplayValue: function() { + return this.displayTpl.apply(this.displayTplData); + }, + + getValue: function() { + + + + var me = this, + picker = me.picker, + rawValue = me.getRawValue(), + value = me.value; + + if (me.getDisplayValue() !== rawValue) { + value = rawValue; + me.value = me.displayTplData = me.valueModels = null; + if (picker) { + me.ignoreSelection++; + picker.getSelectionModel().deselectAll(); + me.ignoreSelection--; + } + } + + return value; + }, + + getSubmitValue: function() { + return this.getValue(); + }, + + isEqual: function(v1, v2) { + var fromArray = Ext.Array.from, + i, len; + + v1 = fromArray(v1); + v2 = fromArray(v2); + len = v1.length; + + if (len !== v2.length) { + return false; + } + + for(i = 0; i < len; i++) { + if (v2[i] !== v1[i]) { + return false; + } + } + + return true; + }, + + + clearValue: function() { + this.setValue([]); + }, + + + syncSelection: function() { + var me = this, + picker = me.picker, + selection, selModel, + values = me.valueModels || [], + vLen = values.length, v, value; + + if (picker) { + + selection = []; + for (v = 0; v < vLen; v++) { + value = values[v]; + + if (value && value.isModel && me.store.indexOf(value) >= 0) { + selection.push(value); + } + } + + + me.ignoreSelection++; + selModel = picker.getSelectionModel(); + selModel.deselectAll(); + if (selection.length) { + selModel.select(selection); + } + me.ignoreSelection--; + } + }, + + onEditorTab: function(e){ + var keyNav = this.listKeyNav; + + if (this.selectOnTab && keyNav) { + keyNav.selectHighlighted(e); + } + } +}); + + +Ext.define('Ext.form.field.Time', { + extend:'Ext.form.field.ComboBox', + alias: 'widget.timefield', + requires: ['Ext.form.field.Date', 'Ext.picker.Time', 'Ext.view.BoundListKeyNav', 'Ext.Date'], + alternateClassName: ['Ext.form.TimeField', 'Ext.form.Time'], + + + triggerCls: Ext.baseCSSPrefix + 'form-time-trigger', + + + + + + + + minText : "The time in this field must be equal to or after {0}", + + + + + maxText : "The time in this field must be equal to or before {0}", + + + + + invalidText : "{0} is not a valid time", + + + + + format : "g:i A", + + + + + submitFormat: 'g:i A', + + + + + altFormats : "g:ia|g:iA|g:i a|g:i A|h:i|g:i|H:i|ga|ha|gA|h a|g a|g A|gi|hi|gia|hia|g|H|gi a|hi a|giA|hiA|gi A|hi A", + + + + increment: 15, + + + pickerMaxHeight: 300, + + + selectOnTab: true, + + + snapToIncrement: false, + + + initDate: '1/1/2008', + initDateFormat: 'j/n/Y', + + ignoreSelection: 0, + + queryMode: 'local', + + displayField: 'disp', + + valueField: 'date', + + initComponent: function() { + var me = this, + min = me.minValue, + max = me.maxValue; + if (min) { + me.setMinValue(min); + } + if (max) { + me.setMaxValue(max); + } + me.displayTpl = new Ext.XTemplate( + '' + + '{[typeof values === "string" ? values : this.formatDate(values["' + me.displayField + '"])]}' + + '' + me.delimiter + '' + + '', { + formatDate: Ext.Function.bind(me.formatDate, me) + }); + this.callParent(); + }, + + + setMinValue: function(value) { + var me = this, + picker = me.picker; + me.setLimit(value, true); + if (picker) { + picker.setMinValue(me.minValue); + } + }, + + + setMaxValue: function(value) { + var me = this, + picker = me.picker; + me.setLimit(value, false); + if (picker) { + picker.setMaxValue(me.maxValue); + } + }, + + + setLimit: function(value, isMin) { + var me = this, + d, val; + if (Ext.isString(value)) { + d = me.parseDate(value); + } + else if (Ext.isDate(value)) { + d = value; + } + if (d) { + val = Ext.Date.clearTime(new Date(me.initDate)); + val.setHours(d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds()); + } + + else { + val = null; + } + me[isMin ? 'minValue' : 'maxValue'] = val; + }, + + rawToValue: function(rawValue) { + return this.parseDate(rawValue) || rawValue || null; + }, + + valueToRaw: function(value) { + return this.formatDate(this.parseDate(value)); + }, + + + getErrors: function(value) { + var me = this, + format = Ext.String.format, + errors = me.callParent(arguments), + minValue = me.minValue, + maxValue = me.maxValue, + date; + + value = me.formatDate(value || me.processRawValue(me.getRawValue())); + + if (value === null || value.length < 1) { + return errors; + } + + date = me.parseDate(value); + if (!date) { + errors.push(format(me.invalidText, value, Ext.Date.unescapeFormat(me.format))); + return errors; + } + + if (minValue && date < minValue) { + errors.push(format(me.minText, me.formatDate(minValue))); + } + + if (maxValue && date > maxValue) { + errors.push(format(me.maxText, me.formatDate(maxValue))); + } + + return errors; + }, + + formatDate: function() { + return Ext.form.field.Date.prototype.formatDate.apply(this, arguments); + }, + + + parseDate: function(value) { + var me = this, + val = value, + altFormats = me.altFormats, + altFormatsArray = me.altFormatsArray, + i = 0, + len; + + if (value && !Ext.isDate(value)) { + val = me.safeParse(value, me.format); + + if (!val && altFormats) { + altFormatsArray = altFormatsArray || altFormats.split('|'); + len = altFormatsArray.length; + for (; i < len && !val; ++i) { + val = me.safeParse(value, altFormatsArray[i]); + } + } + } + + + if (val && me.snapToIncrement) { + val = new Date(Ext.Number.snap(val.getTime(), me.increment * 60 * 1000)); + } + return val; + }, + + safeParse: function(value, format){ + var me = this, + utilDate = Ext.Date, + parsedDate, + result = null; + + if (utilDate.formatContainsDateInfo(format)) { + + result = utilDate.parse(value, format); + } else { + + parsedDate = utilDate.parse(me.initDate + ' ' + value, me.initDateFormat + ' ' + format); + if (parsedDate) { + result = parsedDate; + } + } + return result; + }, + + + getSubmitValue: function() { + var me = this, + format = me.submitFormat || me.format, + value = me.getValue(); + + return value ? Ext.Date.format(value, format) : null; + }, + + + createPicker: function() { + var me = this, + picker; + + me.listConfig = Ext.apply({ + xtype: 'timepicker', + selModel: { + mode: 'SINGLE' + }, + cls: undefined, + minValue: me.minValue, + maxValue: me.maxValue, + increment: me.increment, + format: me.format, + maxHeight: me.pickerMaxHeight + }, me.listConfig); + picker = me.callParent(); + me.store = picker.store; + return picker; + }, + + onItemClick: function(picker, record){ + + var me = this, + selected = picker.getSelectionModel().getSelection(); + + if (selected.length > 0) { + selected = selected[0]; + if (selected && Ext.Date.isEqual(record.get('date'), selected.get('date'))) { + me.collapse(); + } + } + }, + + + onListSelectionChange: function(list, recordArray) { + var me = this, + record = recordArray[0], + val = record ? record.get('date') : null; + + if (!me.ignoreSelection) { + me.skipSync = true; + me.setValue(val); + me.skipSync = false; + me.fireEvent('select', me, val); + me.picker.clearHighlight(); + me.collapse(); + me.inputEl.focus(); + } + }, + + + syncSelection: function() { + var me = this, + picker = me.picker, + toSelect, + selModel, + value, + data, d, dLen, rec; + + if (picker && !me.skipSync) { + picker.clearHighlight(); + value = me.getValue(); + selModel = picker.getSelectionModel(); + + me.ignoreSelection++; + if (value === null) { + selModel.deselectAll(); + } else if(Ext.isDate(value)) { + + data = picker.store.data.items; + dLen = data.length; + + for (d = 0; d < dLen; d++) { + rec = data[d]; + + if (Ext.Date.isEqual(rec.get('date'), value)) { + toSelect = rec; + break; + } + } + + selModel.select(toSelect); + } + me.ignoreSelection--; + } + }, + + postBlur: function() { + var me = this; + + me.callParent(arguments); + me.setRawValue(me.formatDate(me.getValue())); + }, + + setValue: function(v) { + + + this.getPicker(); + + this.callParent([this.parseDate(v)]); + }, + + getValue: function() { + var val = this.callParent(arguments); + return this.parseDate(val); + } +}); + +Ext.define('Ext.view.Table', { + extend: 'Ext.view.View', + alias: 'widget.tableview', + uses: [ + 'Ext.view.TableChunker', + 'Ext.util.DelayedTask', + 'Ext.util.MixedCollection' + ], + + baseCls: Ext.baseCSSPrefix + 'grid-view', + + + itemSelector: 'tr.' + Ext.baseCSSPrefix + 'grid-row', + + cellSelector: 'td.' + Ext.baseCSSPrefix + 'grid-cell', + + + rowSelector: 'tr.' + Ext.baseCSSPrefix + 'grid-row', + + + firstCls: Ext.baseCSSPrefix + 'grid-cell-first', + + + lastCls: Ext.baseCSSPrefix + 'grid-cell-last', + + headerRowSelector: 'tr.' + Ext.baseCSSPrefix + 'grid-header-row', + + selectedItemCls: Ext.baseCSSPrefix + 'grid-row-selected', + selectedCellCls: Ext.baseCSSPrefix + 'grid-cell-selected', + focusedItemCls: Ext.baseCSSPrefix + 'grid-row-focused', + overItemCls: Ext.baseCSSPrefix + 'grid-row-over', + altRowCls: Ext.baseCSSPrefix + 'grid-row-alt', + rowClsRe: new RegExp('(?:^|\\s*)' + Ext.baseCSSPrefix + 'grid-row-(first|last|alt)(?:\\s+|$)', 'g'), + cellRe: new RegExp(Ext.baseCSSPrefix + 'grid-cell-([^\\s]+) ', ''), + + + trackOver: true, + + + getRowClass: null, + + + stripeRows: true, + + + markDirty : true, + + + + initComponent: function() { + var me = this, + scroll = me.scroll; + + + + me.autoScroll = undefined; + + + if (scroll === true || scroll === 'both') { + me.style = Ext.apply(me.style||{}, { + overflow: 'auto' + }); + } else if (scroll === 'horizontal') { + me.style = Ext.apply(me.style||{}, { + "overflow-x": 'auto', + "overflow-y": 'hidden' + }); + } else if (scroll === 'vertical') { + me.style = Ext.apply(me.style||{}, { + "overflow-x": 'hidden', + "overflow-y": 'auto' + }); + } else { + me.style = Ext.apply(me.style||{}, { + overflow: 'hidden' + }); + } + me.selModel.view = me; + me.headerCt.view = me; + me.headerCt.markDirty = me.markDirty; + + + me.initFeatures(me.grid); + delete me.grid; + + me.tpl = '
'; + me.callParent(); + }, + + + moveColumn: function(fromIdx, toIdx, colsToMove) { + var me = this, + fragment = (colsToMove > 1) ? document.createDocumentFragment() : undefined, + destinationCellIdx = toIdx, + colCount = me.getGridColumns().length, + lastIdx = colCount - 1, + doFirstLastClasses = (me.firstCls || me.lastCls) && (toIdx == 0 || toIdx == colCount || fromIdx == 0 || fromIdx == lastIdx), + i, + j, + rows, len, tr, headerRows; + + if (me.rendered) { + + + headerRows = me.el.query(me.headerRowSelector); + rows = me.el.query(me.rowSelector); + + if (toIdx > fromIdx && fragment) { + destinationCellIdx -= colsToMove; + } + + + for (i = 0, len = headerRows.length; i < len; ++i) { + tr = headerRows[i]; + if (fragment) { + for (j = 0; j < colsToMove; j++) { + fragment.appendChild(tr.cells[fromIdx]); + } + tr.insertBefore(fragment, tr.cells[destinationCellIdx] || null); + } else { + tr.insertBefore(tr.cells[fromIdx], tr.cells[destinationCellIdx] || null); + } + } + + for (i = 0, len = rows.length; i < len; i++) { + tr = rows[i]; + + + if (doFirstLastClasses) { + + if (fromIdx === 0) { + Ext.fly(tr.cells[0]).removeCls(me.firstCls); + Ext.fly(tr.cells[1]).addCls(me.firstCls); + } else if (fromIdx === lastIdx) { + Ext.fly(tr.cells[lastIdx]).removeCls(me.lastCls); + Ext.fly(tr.cells[lastIdx - 1]).addCls(me.lastCls); + } + if (toIdx === 0) { + Ext.fly(tr.cells[0]).removeCls(me.firstCls); + Ext.fly(tr.cells[fromIdx]).addCls(me.firstCls); + } else if (toIdx === colCount) { + Ext.fly(tr.cells[lastIdx]).removeCls(me.lastCls); + Ext.fly(tr.cells[fromIdx]).addCls(me.lastCls); + } + } + + if (fragment) { + for (j = 0; j < colsToMove; j++) { + fragment.appendChild(tr.cells[fromIdx]); + } + tr.insertBefore(fragment, tr.cells[destinationCellIdx] || null); + } else { + tr.insertBefore(tr.cells[fromIdx], tr.cells[destinationCellIdx] || null); + } + } + me.setNewTemplate(); + } + }, + + + scrollToTop: Ext.emptyFn, + + + addElListener: function(eventName, fn, scope){ + this.mon(this, eventName, fn, scope, { + element: 'el' + }); + }, + + + getGridColumns: function() { + return this.headerCt.getGridColumns(); + }, + + + getHeaderAtIndex: function(index) { + return this.headerCt.getHeaderAtIndex(index); + }, + + + getCell: function(record, column) { + var row = this.getNode(record); + return Ext.fly(row).down(column.getCellSelector()); + }, + + + getFeature: function(id) { + var features = this.featuresMC; + if (features) { + return features.get(id); + } + }, + + + initFeatures: function(grid) { + var me = this, + i, + features, + feature, + len; + + me.featuresMC = new Ext.util.MixedCollection(); + features = me.features = me.prepareFeatures(); + len = features ? features.length : 0; + for (i = 0; i < len; i++) { + feature = features[i]; + + + feature.view = me; + feature.grid = grid; + me.featuresMC.add(feature); + feature.init(); + } + }, + + + prepareFeatures: function() { + var me = this, + features = me.features, + feature, + result, + i = 0, len; + + if (features) { + result = []; + len = features.length; + for (; i < len; i++) { + feature = features[i]; + if (!feature.isFeature) { + feature = Ext.create('feature.' + feature.ftype, feature); + } + result[i] = feature; + } + } + return result; + }, + + + attachEventsForFeatures: function() { + var features = this.features, + ln = features.length, + i = 0; + + for (; i < ln; i++) { + if (features[i].isFeature) { + features[i].attachEvents(); + } + } + }, + + afterRender: function() { + var me = this; + me.callParent(); + + if (!me.enableTextSelection) { + me.el.unselectable(); + } + me.attachEventsForFeatures(); + }, + + + onViewScroll: function(e, t) { + this.callParent(arguments); + this.fireEvent('bodyscroll', e, t); + }, + + + prepareData: function(data, idx, record) { + var me = this, + result = me.headerCt.prepareData(data, idx, record, me, me.ownerCt), + features = me.features, + ln = features.length, + i = 0, + feature; + + for (; i < ln; i++) { + feature = features[i]; + if (feature.isFeature) { + Ext.apply(result, feature.getAdditionalData(data, idx, record, result, me)); + } + } + + return result; + }, + + + collectData: function(records, startIndex) { + var preppedRecords = this.callParent(arguments), + headerCt = this.headerCt, + fullWidth = headerCt.getFullWidth(), + features = this.features, + ln = features.length, + o = { + rows: preppedRecords, + fullWidth: fullWidth + }, + i = 0, + feature, + j = 0, + jln, + rowParams, + rec, + cls; + + jln = preppedRecords.length; + + + if (this.getRowClass) { + for (; j < jln; j++) { + rowParams = {}; + rec = preppedRecords[j]; + cls = rec.rowCls || ''; + rec.rowCls = this.getRowClass(records[j], j, rowParams, this.store) + ' ' + cls; + } + } + + + for (; i < ln; i++) { + feature = features[i]; + if (feature.isFeature && feature.collectData && !feature.disabled) { + o = feature.collectData(records, preppedRecords, startIndex, fullWidth, o); + break; + } + } + return o; + }, + + + forceReflow: Ext.isGecko10 + ? function() { + var el = this.el.down('table'), + width; + if (el) { + width = el.getWidth(); + } + } + : Ext.emptyFn, + + + onHeaderResize: function(header, w, suppressFocus) { + var me = this, + el = me.el; + + if (el) { + + + + el.select('th.' + Ext.baseCSSPrefix + 'grid-col-resizer-'+header.id).setWidth(w); + el.select('table.' + Ext.baseCSSPrefix + 'grid-table-resizer').setWidth(me.headerCt.getFullWidth()); + if (!me.ignoreTemplate) { + me.setNewTemplate(); + } + if (!suppressFocus) { + me.el.focus(); + } + me.forceReflow(); + } + }, + + + onHeaderShow: function(headerCt, header, suppressFocus) { + var me = this; + me.ignoreTemplate = true; + + if (header.oldWidth) { + me.onHeaderResize(header, header.oldWidth, suppressFocus); + delete header.oldWidth; + + + + } else if (header.width && !header.flex) { + me.onHeaderResize(header, header.width, suppressFocus); + } else if (header.el) { + me.onHeaderResize(header, header.el.getWidth(), suppressFocus); + } + delete me.ignoreTemplate; + me.setNewTemplate(); + }, + + + onHeaderHide: function(headerCt, header, suppressFocus) { + this.onHeaderResize(header, 0, suppressFocus); + }, + + + + + + + refreshSize: function() { + var me = this, + cmp; + + if (!me.hasLoadingHeight) { + cmp = me.up('tablepanel'); + + + + Ext.suspendLayouts(); + + me.callParent(); + + if (cmp && Ext.getScrollbarSize().width) { + cmp.updateLayout(); + } + + Ext.resumeLayouts(true); + } + }, + + + setNewTemplate: function() { + var me = this, + columns = me.headerCt.getColumnsForTpl(true); + + + me.tpl = me.getTableChunker().getTableTpl({ + rowCount: me.store.getCount(), + columns: columns, + features: me.features, + enableTextSelection: me.enableTextSelection + }); + }, + + + getTableChunker: function() { + return this.chunker || Ext.view.TableChunker; + }, + + + addRowCls: function(rowInfo, cls) { + var row = this.getNode(rowInfo); + if (row) { + Ext.fly(row).addCls(cls); + } + }, + + + removeRowCls: function(rowInfo, cls) { + var row = this.getNode(rowInfo); + if (row) { + Ext.fly(row).removeCls(cls); + } + }, + + + onRowSelect : function(rowIdx) { + this.addRowCls(rowIdx, this.selectedItemCls); + }, + + + onRowDeselect : function(rowIdx) { + var me = this; + + me.removeRowCls(rowIdx, me.selectedItemCls); + me.removeRowCls(rowIdx, me.focusedItemCls); + }, + + onCellSelect: function(position) { + var cell = this.getCellByPosition(position); + if (cell) { + cell.addCls(this.selectedCellCls); + } + }, + + onCellDeselect: function(position) { + var cell = this.getCellByPosition(position); + if (cell) { + cell.removeCls(this.selectedCellCls); + } + + }, + + onCellFocus: function(position) { + this.focusCell(position); + }, + + getCellByPosition: function(position) { + if (position) { + var node = this.getNode(position.row), + header = this.headerCt.getHeaderAtIndex(position.column); + + if (header && node) { + return Ext.fly(node).down(header.getCellSelector()); + } + } + return false; + }, + + + + onRowFocus: function(rowIdx, highlight, supressFocus) { + var me = this; + + if (highlight) { + me.addRowCls(rowIdx, me.focusedItemCls); + if (!supressFocus) { + me.focusRow(rowIdx); + } + + } else { + me.removeRowCls(rowIdx, me.focusedItemCls); + } + }, + + + focusRow: function(rowIdx) { + var me = this, + row = me.getNode(rowIdx), + el = me.el, + adjustment = 0, + panel = me.ownerCt, + rowRegion, + elTop, + elBottom, + record; + + if (row && el) { + + + elTop = el.getY(); + elBottom = elTop + el.dom.clientHeight; + rowRegion = Ext.fly(row).getRegion(); + + if (rowRegion.top < elTop) { + adjustment = rowRegion.top - elTop; + + } else if (rowRegion.bottom > elBottom) { + adjustment = rowRegion.bottom - elBottom; + } + record = me.getRecord(row); + rowIdx = me.store.indexOf(record); + + if (adjustment) { + panel.scrollByDeltaY(adjustment); + } + me.fireEvent('rowfocus', record, row, rowIdx); + } + }, + + focusCell: function(position) { + var me = this, + cell = me.getCellByPosition(position), + el = me.el, + adjustmentY = 0, + adjustmentX = 0, + elRegion = el.getRegion(), + panel = me.ownerCt, + cellRegion, + record; + + + + elRegion.bottom = elRegion.top + el.dom.clientHeight; + elRegion.right = elRegion.left + el.dom.clientWidth; + if (cell) { + cellRegion = cell.getRegion(); + + if (cellRegion.top < elRegion.top) { + adjustmentY = cellRegion.top - elRegion.top; + + } else if (cellRegion.bottom > elRegion.bottom) { + adjustmentY = cellRegion.bottom - elRegion.bottom; + } + + + if (cellRegion.left < elRegion.left) { + adjustmentX = cellRegion.left - elRegion.left; + + } else if (cellRegion.right > elRegion.right) { + adjustmentX = cellRegion.right - elRegion.right; + } + + if (adjustmentY) { + panel.scrollByDeltaY(adjustmentY); + } + if (adjustmentX) { + panel.scrollByDeltaX(adjustmentX); + } + el.focus(); + me.fireEvent('cellfocus', record, cell, position); + } + }, + + + scrollByDelta: function(delta, dir) { + dir = dir || 'scrollTop'; + var elDom = this.el.dom; + elDom[dir] = (elDom[dir] += delta); + }, + + + onUpdate : function(store, record, operation, changedFieldNames) { + var me = this, + index, + newRow, oldRow, + oldCells, newCells, len, i, + columns, overItemCls, + isHovered, row; + + if (me.rendered) { + + index = me.store.indexOf(record); + columns = me.headerCt.getGridColumns(); + overItemCls = me.overItemCls; + + + + if (columns.length && index > -1) { + newRow = me.bufferRender([record], index)[0]; + oldRow = me.all.item(index); + isHovered = oldRow.hasCls(overItemCls); + oldRow.dom.className = newRow.className; + if(isHovered) { + oldRow.addCls(overItemCls); + } + + + oldCells = oldRow.query(this.cellSelector); + newCells = Ext.fly(newRow).query(this.cellSelector); + len = newCells.length; + + row = oldCells[0].parentNode; + for (i = 0; i < len; i++) { + + if (me.shouldUpdateCell(columns[i], changedFieldNames)) { + row.insertBefore(newCells[i], oldCells[i]); + row.removeChild(oldCells[i]); + } + } + + + + me.selModel.refresh(); + me.doStripeRows(index, index); + me.fireEvent('itemupdate', record, index, newRow); + } + } + + }, + + shouldUpdateCell: function(column, changedFieldNames){ + + + if (column.hasCustomRenderer) { + return true; + } + return !changedFieldNames || Ext.Array.contains(changedFieldNames, column.dataIndex); + }, + + + refresh: function() { + this.setNewTemplate(); + this.callParent(arguments); + this.doStripeRows(0); + }, + + processItemEvent: function(record, row, rowIndex, e) { + var me = this, + cell = e.getTarget(me.cellSelector, row), + cellIndex = cell ? cell.cellIndex : -1, + map = me.statics().EventMap, + selModel = me.getSelectionModel(), + type = e.type, + result; + + if (type == 'keydown' && !cell && selModel.getCurrentPosition) { + + cell = me.getCellByPosition(selModel.getCurrentPosition()); + if (cell) { + cell = cell.dom; + cellIndex = cell.cellIndex; + } + } + + result = me.fireEvent('uievent', type, me, cell, rowIndex, cellIndex, e, record, row); + + if (result === false || me.callParent(arguments) === false) { + return false; + } + + + if (type == 'mouseover' || type == 'mouseout') { + return true; + } + + if(!cell) { + + + return true; + } + + return !( + + (me['onBeforeCell' + map[type]](cell, cellIndex, record, row, rowIndex, e) === false) || + (me.fireEvent('beforecell' + type, me, cell, cellIndex, record, row, rowIndex, e) === false) || + (me['onCell' + map[type]](cell, cellIndex, record, row, rowIndex, e) === false) || + (me.fireEvent('cell' + type, me, cell, cellIndex, record, row, rowIndex, e) === false) + ); + }, + + processSpecialEvent: function(e) { + var me = this, + map = me.statics().EventMap, + features = me.features, + ln = features.length, + type = e.type, + i, feature, prefix, featureTarget, + beforeArgs, args, + panel = me.ownerCt; + + me.callParent(arguments); + + if (type == 'mouseover' || type == 'mouseout') { + return; + } + + for (i = 0; i < ln; i++) { + feature = features[i]; + if (feature.hasFeatureEvent) { + featureTarget = e.getTarget(feature.eventSelector, me.getTargetEl()); + if (featureTarget) { + prefix = feature.eventPrefix; + + + beforeArgs = feature.getFireEventArgs('before' + prefix + type, me, featureTarget, e); + args = feature.getFireEventArgs(prefix + type, me, featureTarget, e); + + if ( + + (me.fireEvent.apply(me, beforeArgs) === false) || + + (panel.fireEvent.apply(panel, beforeArgs) === false) || + + (me.fireEvent.apply(me, args) === false) || + + (panel.fireEvent.apply(panel, args) === false) + ) { + return false; + } + } + } + } + return true; + }, + + onCellMouseDown: Ext.emptyFn, + onCellMouseUp: Ext.emptyFn, + onCellClick: Ext.emptyFn, + onCellDblClick: Ext.emptyFn, + onCellContextMenu: Ext.emptyFn, + onCellKeyDown: Ext.emptyFn, + onBeforeCellMouseDown: Ext.emptyFn, + onBeforeCellMouseUp: Ext.emptyFn, + onBeforeCellClick: Ext.emptyFn, + onBeforeCellDblClick: Ext.emptyFn, + onBeforeCellContextMenu: Ext.emptyFn, + onBeforeCellKeyDown: Ext.emptyFn, + + + expandToFit: function(header) { + if (header) { + var maxWidth = this.getMaxContentWidth(header); + delete header.flex; + header.setWidth(maxWidth); + } + }, + + + getMaxContentWidth: function(header) { + var cellSelector = header.getCellInnerSelector(), + cells = this.el.query(cellSelector), + i = 0, + ln = cells.length, + maxWidth = header.el.dom.scrollWidth, + scrollWidth; + + for (; i < ln; i++) { + scrollWidth = cells[i].scrollWidth; + if (scrollWidth > maxWidth) { + maxWidth = scrollWidth; + } + } + return maxWidth; + }, + + getPositionByEvent: function(e) { + var me = this, + cellNode = e.getTarget(me.cellSelector), + rowNode = e.getTarget(me.itemSelector), + record = me.getRecord(rowNode), + header = me.getHeaderByCell(cellNode); + + return me.getPosition(record, header); + }, + + getHeaderByCell: function(cell) { + if (cell) { + var m = cell.className.match(this.cellRe); + if (m && m[1]) { + return Ext.getCmp(m[1]); + } + } + return false; + }, + + + walkCells: function(pos, direction, e, preventWrap, verifierFn, scope) { + + + + if (!pos) { + return; + } + + var me = this, + row = pos.row, + column = pos.column, + rowCount = me.store.getCount(), + firstCol = me.getFirstVisibleColumnIndex(), + lastCol = me.getLastVisibleColumnIndex(), + newPos = {row: row, column: column}, + activeHeader = me.headerCt.getHeaderAtIndex(column); + + + if (!activeHeader || activeHeader.hidden) { + return false; + } + + e = e || {}; + direction = direction.toLowerCase(); + switch (direction) { + case 'right': + + if (column === lastCol) { + + if (preventWrap || row === rowCount - 1) { + return false; + } + if (!e.ctrlKey) { + + newPos.row = row + 1; + newPos.column = firstCol; + } + + } else { + if (!e.ctrlKey) { + newPos.column = column + me.getRightGap(activeHeader); + } else { + newPos.column = lastCol; + } + } + break; + + case 'left': + + if (column === firstCol) { + + if (preventWrap || row === 0) { + return false; + } + if (!e.ctrlKey) { + + newPos.row = row - 1; + newPos.column = lastCol; + } + + } else { + if (!e.ctrlKey) { + newPos.column = column + me.getLeftGap(activeHeader); + } else { + newPos.column = firstCol; + } + } + break; + + case 'up': + + if (row === 0) { + return false; + + } else { + if (!e.ctrlKey) { + newPos.row = row - 1; + } else { + newPos.row = 0; + } + } + break; + + case 'down': + + if (row === rowCount - 1) { + return false; + + } else { + if (!e.ctrlKey) { + newPos.row = row + 1; + } else { + newPos.row = rowCount - 1; + } + } + break; + } + + if (verifierFn && verifierFn.call(scope || window, newPos) !== true) { + return false; + } else { + return newPos; + } + }, + getFirstVisibleColumnIndex: function() { + var firstVisibleHeader = this.getHeaderCt().getVisibleGridColumns()[0]; + + return firstVisibleHeader ? firstVisibleHeader.getIndex() : -1; + }, + + getLastVisibleColumnIndex: function() { + var visHeaders = this.getHeaderCt().getVisibleGridColumns(), + lastHeader = visHeaders[visHeaders.length - 1]; + + return lastHeader.getIndex(); + }, + + getHeaderCt: function() { + return this.headerCt; + }, + + + getPosition: function(record, header) { + var me = this, + store = me.store, + gridCols = me.headerCt.getGridColumns(); + + return { + row: store.indexOf(record), + column: Ext.Array.indexOf(gridCols, header) + }; + }, + + + getRightGap: function(activeHeader) { + var headerCt = this.getHeaderCt(), + headers = headerCt.getGridColumns(), + activeHeaderIdx = Ext.Array.indexOf(headers, activeHeader), + i = activeHeaderIdx + 1, + nextIdx; + + for (; i <= headers.length; i++) { + if (!headers[i].hidden) { + nextIdx = i; + break; + } + } + + return nextIdx - activeHeaderIdx; + }, + + beforeDestroy: function() { + if (this.rendered) { + this.el.removeAllListeners(); + } + this.callParent(arguments); + }, + + + getLeftGap: function(activeHeader) { + var headerCt = this.getHeaderCt(), + headers = headerCt.getGridColumns(), + activeHeaderIdx = Ext.Array.indexOf(headers, activeHeader), + i = activeHeaderIdx - 1, + prevIdx; + + for (; i >= 0; i--) { + if (!headers[i].hidden) { + prevIdx = i; + break; + } + } + + return prevIdx - activeHeaderIdx; + }, + + + onAdd: function(ds, records, index) { + this.callParent(arguments); + this.doStripeRows(index); + }, + + + onRemove: function(ds, records, index) { + this.callParent(arguments); + this.doStripeRows(index); + }, + + + doStripeRows: function(startRow, endRow) { + var me = this, + rows, + rowsLn, + i, + row; + + + if (me.rendered && me.stripeRows) { + rows = me.getNodes(startRow, endRow); + + for (i = 0, rowsLn = rows.length; i < rowsLn; i++) { + row = rows[i]; + + row.className = row.className.replace(me.rowClsRe, ' '); + startRow++; + + if (startRow % 2 === 0) { + row.className += (' ' + me.altRowCls); + } + } + } + } + +}); + + +Ext.define('Ext.grid.Lockable', { + + requires: [ + 'Ext.grid.LockingView', + 'Ext.view.Table' + ], + + + syncRowHeight: true, + + + + + + + + headerCounter: 0, + + + scrollDelta: 40, + + + + + + + + unlockText: 'Unlock', + + + lockText: 'Lock', + + + determineXTypeToCreate: function() { + var me = this, + typeToCreate, + xtypes, xtypesLn, xtype, superxtype; + + if (me.subGridXType) { + typeToCreate = me.subGridXType; + } else { + xtypes = this.getXTypes().split('/'); + xtypesLn = xtypes.length; + xtype = xtypes[xtypesLn - 1]; + superxtype = xtypes[xtypesLn - 2]; + + if (superxtype !== 'tablepanel') { + typeToCreate = superxtype; + } else { + typeToCreate = xtype; + } + } + + return typeToCreate; + }, + + + + injectLockable: function() { + + this.lockable = true; + + + this.hasView = true; + + var me = this, + + scrollLocked = Ext.getScrollbarSize().width === 0, + store = me.store = Ext.StoreManager.lookup(me.store), + + + + xtype = me.determineXTypeToCreate(), + + selModel = me.getSelectionModel(), + lockedFeatures = me.prepareFeatures(), + normalFeatures = me.prepareFeatures(), + lockedGrid, + normalGrid, + i = 0, len, + columns, + lockedHeaderCt, + normalHeaderCt, + lockedView, + normalView, + listeners; + + + for (i = 0, len = (lockedFeatures ? lockedFeatures.length : 0); i < len; i++) { + lockedFeatures[i].lockingPartner = normalFeatures[i]; + normalFeatures[i].lockingPartner = lockedFeatures[i]; + } + + lockedGrid = Ext.apply({ + xtype: xtype, + store: store, + scrollerOwner: false, + + enableAnimations: false, + scroll: scrollLocked ? 'vertical' : false, + selModel: selModel, + border: false, + cls: Ext.baseCSSPrefix + 'grid-inner-locked', + isLayoutRoot: function() { + return false; + }, + features: lockedFeatures + }, me.lockedGridConfig); + + normalGrid = Ext.apply({ + xtype: xtype, + store: store, + scrollerOwner: false, + enableAnimations: false, + selModel: selModel, + border: false, + isLayoutRoot: function() { + return false; + }, + features: normalFeatures + }, me.normalGridConfig); + + me.addCls(Ext.baseCSSPrefix + 'grid-locked'); + + + + + Ext.copyTo(normalGrid, me, me.bothCfgCopy); + Ext.copyTo(lockedGrid, me, me.bothCfgCopy); + Ext.copyTo(normalGrid, me, me.normalCfgCopy); + Ext.copyTo(lockedGrid, me, me.lockedCfgCopy); + for (i = 0; i < me.normalCfgCopy.length; i++) { + delete me[me.normalCfgCopy[i]]; + } + for (i = 0; i < me.lockedCfgCopy.length; i++) { + delete me[me.lockedCfgCopy[i]]; + } + + me.addEvents( + + 'lockcolumn', + + + 'unlockcolumn' + ); + + me.addStateEvents(['lockcolumn', 'unlockcolumn']); + + me.lockedHeights = []; + me.normalHeights = []; + + columns = me.processColumns(me.columns); + + lockedGrid.width = columns.lockedWidth + Ext.num(selModel.headerWidth, 0); + lockedGrid.columns = columns.locked; + normalGrid.columns = columns.normal; + + + normalGrid.flex = 1; + lockedGrid.viewConfig = me.lockedViewConfig || {}; + lockedGrid.viewConfig.loadingUseMsg = false; + normalGrid.viewConfig = me.normalViewConfig || {}; + + Ext.applyIf(lockedGrid.viewConfig, me.viewConfig); + Ext.applyIf(normalGrid.viewConfig, me.viewConfig); + + me.normalGrid = Ext.ComponentManager.create(normalGrid); + me.lockedGrid = Ext.ComponentManager.create(lockedGrid); + + me.view = new Ext.grid.LockingView({ + locked: me.lockedGrid, + normal: me.normalGrid, + panel: me + }); + + lockedView = me.lockedGrid.getView(); + normalView = me.normalGrid.getView(); + + + + + if (scrollLocked) { + listeners = { + scroll: { + fn: me.onLockedViewScroll, + element: 'el', + scope: me + } + }; + } + + else { + listeners = { + mousewheel: { + fn: me.onLockedViewMouseWheel, + element: 'el', + scope: me + } + }; + } + if (me.syncRowHeight) { + listeners.refresh = me.onLockedViewRefresh; + listeners.itemupdate = me.onLockedViewItemUpdate; + listeners.scope = me; + } + lockedView.on(listeners); + + + listeners = { + scroll: { + fn: me.onNormalViewScroll, + element: 'el', + scope: me + }, + refresh: me.syncRowHeight ? me.onNormalViewRefresh : me.updateSpacer, + scope: me + }; + normalView.on(listeners); + + lockedHeaderCt = me.lockedGrid.headerCt; + normalHeaderCt = me.normalGrid.headerCt; + + lockedHeaderCt.lockedCt = true; + lockedHeaderCt.lockableInjected = true; + normalHeaderCt.lockableInjected = true; + + lockedHeaderCt.on({ + columnshow: me.onLockedHeaderShow, + columnhide: me.onLockedHeaderHide, + columnmove: me.onLockedHeaderMove, + sortchange: me.onLockedHeaderSortChange, + columnresize: me.onLockedHeaderResize, + scope: me + }); + + normalHeaderCt.on({ + columnmove: me.onNormalHeaderMove, + sortchange: me.onNormalHeaderSortChange, + scope: me + }); + + me.modifyHeaderCt(); + me.items = [me.lockedGrid, me.normalGrid]; + + me.relayHeaderCtEvents(lockedHeaderCt); + me.relayHeaderCtEvents(normalHeaderCt); + + me.layout = { + type: 'hbox', + align: 'stretch' + }; + }, + + processColumns: function(columns){ + + var i = 0, + len = columns.length, + lockedWidth = 0, + lockedHeaders = [], + normalHeaders = [], + column; + + for (; i < len; ++i) { + column = columns[i]; + + + if (!column.isComponent) { + column = Ext.apply({}, columns[i]); + } + + + + column.processed = true; + if (column.locked) { + if (!column.hidden) { + lockedWidth += column.width || Ext.grid.header.Container.prototype.defaultWidth; + } + lockedHeaders.push(column); + } else { + normalHeaders.push(column); + } + if (!column.headerId) { + column.headerId = (column.initialConfig || column).id || ('L' + (++this.headerCounter)); + } + } + return { + lockedWidth: lockedWidth, + locked: { + items: lockedHeaders, + itemId: 'lockedHeaderCt', + stretchMaxPartner: '^^>>#normalHeaderCt' + }, + normal: { + items: normalHeaders, + itemId: 'normalHeaderCt', + stretchMaxPartner: '^^>>#lockedHeaderCt' + } + }; + }, + + + onLockedViewMouseWheel: function(e) { + var me = this, + scrollDelta = -me.scrollDelta, + deltaY = scrollDelta * e.getWheelDeltas().y, + vertScrollerEl = me.lockedGrid.getView().el.dom, + verticalCanScrollDown, verticalCanScrollUp; + + if (vertScrollerEl) { + verticalCanScrollDown = vertScrollerEl.scrollTop !== vertScrollerEl.scrollHeight - vertScrollerEl.clientHeight; + verticalCanScrollUp = vertScrollerEl.scrollTop !== 0; + } + + if ((deltaY < 0 && verticalCanScrollUp) || (deltaY > 0 && verticalCanScrollDown)) { + e.stopEvent(); + + + + + me.scrolling = true; + vertScrollerEl.scrollTop += deltaY; + me.normalGrid.getView().el.dom.scrollTop = vertScrollerEl.scrollTop; + me.scrolling = false; + + + me.onNormalViewScroll(); + } + }, + + onLockedViewScroll: function() { + var me = this, + lockedView = me.lockedGrid.getView(), + normalView = me.normalGrid.getView(), + normalTable, + lockedTable; + + + if (!me.scrolling) { + me.scrolling = true; + normalView.el.dom.scrollTop = lockedView.el.dom.scrollTop; + + + if (me.store.buffered) { + lockedTable = lockedView.el.child('table', true); + normalTable = normalView.el.child('table', true); + lockedTable.style.position = 'absolute'; + } + me.scrolling = false; + } + }, + + onNormalViewScroll: function() { + var me = this, + lockedView = me.lockedGrid.getView(), + normalView = me.normalGrid.getView(), + normalTable, + lockedTable; + + + if (!me.scrolling) { + me.scrolling = true; + lockedView.el.dom.scrollTop = normalView.el.dom.scrollTop; + + + if (me.store.buffered) { + lockedTable = lockedView.el.child('table', true); + normalTable = normalView.el.child('table', true); + lockedTable.style.position = 'absolute'; + lockedTable.style.top = normalTable.style.top; + } + me.scrolling = false; + } + }, + + + onLockedHeaderMove: function() { + if (this.syncRowHeight) { + this.onNormalViewRefresh(); + } + }, + + + onNormalHeaderMove: function() { + if (this.syncRowHeight) { + this.onLockedViewRefresh(); + } + }, + + + + + + updateSpacer: function() { + var me = this, + + + lockedViewEl = me.lockedGrid.getView().el, + normalViewEl = me.normalGrid.getView().el.dom, + spacerId = lockedViewEl.dom.id + '-spacer', + spacerHeight = (normalViewEl.offsetHeight - normalViewEl.clientHeight) + 'px'; + + me.spacerEl = Ext.getDom(spacerId); + if (me.spacerEl) { + me.spacerEl.style.height = spacerHeight; + } else { + Ext.core.DomHelper.append(lockedViewEl, { + id: spacerId, + style: 'height: ' + spacerHeight + }); + } + }, + + + onLockedViewRefresh: function() { + + + if (this.normalGrid.headerCt.getGridColumns().length) { + var me = this, + view = me.lockedGrid.getView(), + el = view.el, + rowEls = el.query(view.getItemSelector()), + ln = rowEls.length, + i = 0; + + + me.lockedHeights = []; + + for (; i < ln; i++) { + me.lockedHeights[i] = rowEls[i].clientHeight; + } + me.syncRowHeights(); + } + }, + + + onNormalViewRefresh: function() { + + + if (this.lockedGrid.headerCt.getGridColumns().length) { + var me = this, + view = me.normalGrid.getView(), + el = view.el, + rowEls = el.query(view.getItemSelector()), + ln = rowEls.length, + i = 0; + + + me.normalHeights = []; + + for (; i < ln; i++) { + me.normalHeights[i] = rowEls[i].clientHeight; + } + me.syncRowHeights(); + me.updateSpacer(); + } + }, + + + onLockedViewItemUpdate: function(record, index, node) { + + + if (this.normalGrid.headerCt.getGridColumns().length) { + this.lockedHeights[index] = node.clientHeight; + this.syncRowHeights(); + } + }, + + + onNormalViewItemUpdate: function(record, index, node) { + + + if (this.lockedGrid.headerCt.getGridColumns().length) { + this.normalHeights[index] = node.clientHeight; + this.syncRowHeights(); + } + }, + + + syncRowHeights: function() { + var me = this, + lockedHeights = me.lockedHeights, + normalHeights = me.normalHeights, + calcHeights = [], + ln = lockedHeights.length, + i = 0, + lockedView, normalView, + lockedRowEls, normalRowEls, + scrollTop; + + + + if (lockedHeights.length && normalHeights.length) { + lockedView = me.lockedGrid.getView(); + normalView = me.normalGrid.getView(); + lockedRowEls = lockedView.el.query(lockedView.getItemSelector()); + normalRowEls = normalView.el.query(normalView.getItemSelector()); + + + for (; i < ln; i++) { + + if (!isNaN(lockedHeights[i]) && !isNaN(normalHeights[i])) { + if (lockedHeights[i] > normalHeights[i]) { + Ext.fly(normalRowEls[i]).setHeight(lockedHeights[i]); + } else if (lockedHeights[i] < normalHeights[i]) { + Ext.fly(lockedRowEls[i]).setHeight(normalHeights[i]); + } + } + } + + + + + + scrollTop = normalView.el.dom.scrollTop; + normalView.el.dom.scrollTop = scrollTop; + lockedView.el.dom.scrollTop = scrollTop; + + + me.lockedHeights = []; + me.normalHeights = []; + } + }, + + + modifyHeaderCt: function() { + var me = this; + me.lockedGrid.headerCt.getMenuItems = me.getMenuItems(true); + me.normalGrid.headerCt.getMenuItems = me.getMenuItems(false); + }, + + onUnlockMenuClick: function() { + this.unlock(); + }, + + onLockMenuClick: function() { + this.lock(); + }, + + getMenuItems: function(locked) { + var me = this, + unlockText = me.unlockText, + lockText = me.lockText, + unlockCls = Ext.baseCSSPrefix + 'hmenu-unlock', + lockCls = Ext.baseCSSPrefix + 'hmenu-lock', + unlockHandler = Ext.Function.bind(me.onUnlockMenuClick, me), + lockHandler = Ext.Function.bind(me.onLockMenuClick, me); + + + return function() { + var o = Ext.grid.header.Container.prototype.getMenuItems.call(this); + o.push('-',{ + cls: unlockCls, + text: unlockText, + handler: unlockHandler, + disabled: !locked + }); + o.push({ + cls: lockCls, + text: lockText, + handler: lockHandler, + disabled: locked + }); + return o; + }; + }, + + + + lock: function(activeHd, toIdx) { + var me = this, + normalGrid = me.normalGrid, + lockedGrid = me.lockedGrid, + normalHCt = normalGrid.headerCt, + lockedHCt = lockedGrid.headerCt; + + activeHd = activeHd || normalHCt.getMenu().activeHeader; + + + + if (activeHd.flex) { + activeHd.width = activeHd.getWidth(); + delete activeHd.flex; + } + + Ext.suspendLayouts(); + normalHCt.remove(activeHd, false); + activeHd.locked = true; + if (Ext.isDefined(toIdx)) { + lockedHCt.insert(toIdx, activeHd); + } else { + lockedHCt.add(activeHd); + } + me.syncLockedSection(); + Ext.resumeLayouts(true); + me.updateSpacer(); + + me.fireEvent('lockcolumn', me, activeHd); + }, + + syncLockedSection: function() { + var me = this; + me.syncLockedWidth(); + me.lockedGrid.getView().refresh(); + me.normalGrid.getView().refresh(); + }, + + + + syncLockedWidth: function() { + var me = this, + locked = me.lockedGrid, + width = locked.headerCt.getFullWidth(true); + + Ext.suspendLayouts(); + if (width > 0) { + locked.setWidth(width); + locked.show(); + } else { + locked.hide(); + } + Ext.resumeLayouts(true); + + return width > 0; + }, + + onLockedHeaderResize: function() { + this.syncLockedWidth(); + }, + + onLockedHeaderHide: function() { + this.syncLockedWidth(); + }, + + onLockedHeaderShow: function() { + this.syncLockedWidth(); + }, + + onLockedHeaderSortChange: function(headerCt, header, sortState) { + if (sortState) { + + + this.normalGrid.headerCt.clearOtherSortStates(null, true); + } + }, + + onNormalHeaderSortChange: function(headerCt, header, sortState) { + if (sortState) { + + + this.lockedGrid.headerCt.clearOtherSortStates(null, true); + } + }, + + + + unlock: function(activeHd, toIdx) { + var me = this, + normalGrid = me.normalGrid, + lockedGrid = me.lockedGrid, + normalHCt = normalGrid.headerCt, + lockedHCt = lockedGrid.headerCt, + refreshLocked = false; + + if (!Ext.isDefined(toIdx)) { + toIdx = 0; + } + activeHd = activeHd || lockedHCt.getMenu().activeHeader; + + Ext.suspendLayouts(); + lockedHCt.remove(activeHd, false); + if (me.syncLockedWidth()) { + refreshLocked = true; + } + activeHd.locked = false; + + + normalHCt.insert(toIdx, activeHd); + me.normalGrid.getView().refresh(); + + if (refreshLocked) { + me.lockedGrid.getView().refresh(); + } + Ext.resumeLayouts(true); + + me.fireEvent('unlockcolumn', me, activeHd); + }, + + applyColumnsState: function (columns) { + var me = this, + lockedGrid = me.lockedGrid, + lockedHeaderCt = lockedGrid.headerCt, + normalHeaderCt = me.normalGrid.headerCt, + lockedCols = Ext.Array.toMap(lockedHeaderCt.items, 'headerId'), + normalCols = Ext.Array.toMap(normalHeaderCt.items, 'headerId'), + locked = [], + normal = [], + lockedWidth = 1, + length = columns.length, + i, existing, + lockedDefault, + col; + + for (i = 0; i < length; i++) { + col = columns[i]; + + lockedDefault = lockedCols[col.id]; + existing = lockedDefault || normalCols[col.id]; + + if (existing) { + if (existing.applyColumnState) { + existing.applyColumnState(col); + } + if (existing.locked === undefined) { + existing.locked = !!lockedDefault; + } + if (existing.locked) { + locked.push(existing); + if (!existing.hidden && typeof existing.width == 'number') { + lockedWidth += existing.width; + } + } else { + normal.push(existing); + } + } + } + + + if (locked.length + normal.length == lockedHeaderCt.items.getCount() + normalHeaderCt.items.getCount()) { + lockedHeaderCt.removeAll(false); + normalHeaderCt.removeAll(false); + + lockedHeaderCt.add(locked); + normalHeaderCt.add(normal); + + lockedGrid.setWidth(lockedWidth); + } + }, + + getColumnsState: function () { + var me = this, + locked = me.lockedGrid.headerCt.getColumnsState(), + normal = me.normalGrid.headerCt.getColumnsState(); + + return locked.concat(normal); + }, + + + reconfigureLockable: function(store, columns) { + var me = this, + lockedGrid = me.lockedGrid, + normalGrid = me.normalGrid; + + if (columns) { + Ext.suspendLayouts(); + lockedGrid.headerCt.removeAll(); + normalGrid.headerCt.removeAll(); + + columns = me.processColumns(columns); + lockedGrid.setWidth(columns.lockedWidth); + lockedGrid.headerCt.add(columns.locked.items); + normalGrid.headerCt.add(columns.normal.items); + Ext.resumeLayouts(true); + } + + if (store) { + store = Ext.data.StoreManager.lookup(store); + me.store = store; + lockedGrid.bindStore(store); + normalGrid.bindStore(store); + } else { + lockedGrid.getView().refresh(); + normalGrid.getView().refresh(); + } + } +}, function() { + this.borrow(Ext.view.Table, ['prepareFeatures']); +}); + + +Ext.define('Ext.grid.View', { + extend: 'Ext.view.Table', + alias: 'widget.gridview', + + + stripeRows: true, + + autoScroll: true +}); + + +Ext.define('Ext.grid.Panel', { + extend: 'Ext.panel.Table', + requires: ['Ext.grid.View'], + alias: ['widget.gridpanel', 'widget.grid'], + alternateClassName: ['Ext.list.ListView', 'Ext.ListView', 'Ext.grid.GridPanel'], + viewType: 'gridview', + + lockable: false, + + + + bothCfgCopy: [ + 'invalidateScrollerOnRefresh', + 'hideHeaders', + 'enableColumnHide', + 'enableColumnMove', + 'enableColumnResize', + 'sortableColumns' + ], + normalCfgCopy: [ + 'verticalScroller', + 'verticalScrollDock', + 'verticalScrollerType', + 'scroll' + ], + lockedCfgCopy: [], + + + rowLines: true + + + + + + + +}); + +Ext.define('Ext.grid.property.Grid', { + + extend: 'Ext.grid.Panel', + + alias: 'widget.propertygrid', + + alternateClassName: 'Ext.grid.PropertyGrid', + + uses: [ + 'Ext.grid.plugin.CellEditing', + 'Ext.grid.property.Store', + 'Ext.grid.property.HeaderContainer', + 'Ext.XTemplate', + 'Ext.grid.CellEditor', + 'Ext.form.field.Date', + 'Ext.form.field.Text', + 'Ext.form.field.Number', + 'Ext.form.field.ComboBox' + ], + + + + + + + + + + + valueField: 'value', + + + nameField: 'name', + + + + + enableColumnMove: false, + columnLines: true, + stripeRows: false, + trackMouseOver: false, + clicksToEdit: 1, + enableHdMenu: false, + + + initComponent : function(){ + var me = this; + + me.addCls(Ext.baseCSSPrefix + 'property-grid'); + me.plugins = me.plugins || []; + + + me.plugins.push(new Ext.grid.plugin.CellEditing({ + clicksToEdit: me.clicksToEdit, + + + startEdit: function(record, column) { + + return this.self.prototype.startEdit.call(this, record, me.headerCt.child('#' + me.valueField)); + } + })); + + me.selModel = { + selType: 'cellmodel', + onCellSelect: function(position) { + if (position.column != 1) { + position.column = 1; + } + return this.self.prototype.onCellSelect.call(this, position); + } + }; + me.customRenderers = me.customRenderers || {}; + me.customEditors = me.customEditors || {}; + + + if (!me.store) { + me.propStore = me.store = new Ext.grid.property.Store(me, me.source); + } + + if (me.sortableColumns) { + me.store.sort('name', 'ASC'); + } + me.columns = new Ext.grid.property.HeaderContainer(me, me.store); + + me.addEvents( + + 'beforepropertychange', + + 'propertychange' + ); + me.callParent(); + + + me.getView().walkCells = this.walkCells; + + + me.editors = { + 'date' : new Ext.grid.CellEditor({ field: new Ext.form.field.Date({selectOnFocus: true})}), + 'string' : new Ext.grid.CellEditor({ field: new Ext.form.field.Text({selectOnFocus: true})}), + 'number' : new Ext.grid.CellEditor({ field: new Ext.form.field.Number({selectOnFocus: true})}), + 'boolean' : new Ext.grid.CellEditor({ field: new Ext.form.field.ComboBox({ + editable: false, + store: [[ true, me.headerCt.trueText ], [false, me.headerCt.falseText ]] + })}) + }; + + + me.store.on('update', me.onUpdate, me); + }, + + + onUpdate : function(store, record, operation) { + var me = this, + v, oldValue; + + if (me.rendered && operation == Ext.data.Model.EDIT) { + v = record.get(me.valueField); + oldValue = record.modified.value; + if (me.fireEvent('beforepropertychange', me.source, record.getId(), v, oldValue) !== false) { + if (me.source) { + me.source[record.getId()] = v; + } + record.commit(); + me.fireEvent('propertychange', me.source, record.getId(), v, oldValue); + } else { + record.reject(); + } + } + }, + + + walkCells: function(pos, direction, e, preventWrap, verifierFn, scope) { + if (direction == 'left') { + direction = 'up'; + } else if (direction == 'right') { + direction = 'down'; + } + pos = Ext.view.Table.prototype.walkCells.call(this, pos, direction, e, preventWrap, verifierFn, scope); + if (!pos.column) { + pos.column = 1; + } + return pos; + }, + + + + getCellEditor : function(record, column) { + var me = this, + propName = record.get(me.nameField), + val = record.get(me.valueField), + editor = me.customEditors[propName]; + + + + if (editor) { + if (!(editor instanceof Ext.grid.CellEditor)) { + if (!(editor instanceof Ext.form.field.Base)) { + editor = Ext.ComponentManager.create(editor, 'textfield'); + } + editor = me.customEditors[propName] = new Ext.grid.CellEditor({ field: editor }); + } + } else if (Ext.isDate(val)) { + editor = me.editors.date; + } else if (Ext.isNumber(val)) { + editor = me.editors.number; + } else if (Ext.isBoolean(val)) { + editor = me.editors['boolean']; + } else { + editor = me.editors.string; + } + + + editor.editorId = propName; + return editor; + }, + + beforeDestroy: function() { + var me = this; + me.callParent(); + me.destroyEditors(me.editors); + me.destroyEditors(me.customEditors); + delete me.source; + }, + + destroyEditors: function (editors) { + for (var ed in editors) { + if (editors.hasOwnProperty(ed)) { + Ext.destroy(editors[ed]); + } + } + }, + + + setSource: function(source) { + this.source = 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); + } + + + +}); + +Ext.define('Ext.tree.View', { + extend: 'Ext.view.Table', + alias: 'widget.treeview', + + requires: [ + 'Ext.data.NodeStore' + ], + + loadingCls: Ext.baseCSSPrefix + 'grid-tree-loading', + expandedCls: Ext.baseCSSPrefix + 'grid-tree-node-expanded', + leafCls: Ext.baseCSSPrefix + 'grid-tree-node-leaf', + + expanderSelector: '.' + Ext.baseCSSPrefix + 'tree-expander', + checkboxSelector: '.' + Ext.baseCSSPrefix + 'tree-checkbox', + expanderIconOverCls: Ext.baseCSSPrefix + 'tree-expander-over', + + + + + nodeAnimWrapCls: Ext.baseCSSPrefix + 'tree-animator-wrap', + + blockRefresh: true, + + + rootVisible: true, + + + deferInitialRefresh: false, + + + + expandDuration: 250, + collapseDuration: 250, + + toggleOnDblClick: true, + + stripeRows: false, + + + uiFields: ['expanded', 'loaded', 'checked', 'expandable', 'leaf', 'icon', 'iconCls', 'loading'], + + initComponent: function() { + var me = this, + treeStore = me.panel.getStore(); + + if (me.initialConfig.animate === undefined) { + me.animate = Ext.enableFx; + } + + me.store = new Ext.data.NodeStore({ + treeStore: treeStore, + recursive: true, + rootVisible: me.rootVisible, + listeners: { + beforeexpand: me.onBeforeExpand, + expand: me.onExpand, + beforecollapse: me.onBeforeCollapse, + collapse: me.onCollapse, + write: me.onStoreWrite, + datachanged: me.onStoreDataChanged, + scope: me + } + }); + + if (me.node) { + me.setRootNode(me.node); + } + me.animQueue = {}; + me.animWraps = {}; + me.addEvents( + + 'afteritemexpand', + + 'afteritemcollapse' + ); + me.callParent(arguments); + me.on({ + element: 'el', + scope: me, + delegate: me.expanderSelector, + mouseover: me.onExpanderMouseOver, + mouseout: me.onExpanderMouseOut + }); + me.on({ + element: 'el', + scope: me, + delegate: me.checkboxSelector, + click: me.onCheckboxChange + }); + }, + + afterComponentLayout: function(){ + this.callParent(arguments); + var stretcher = this.stretcher; + if (stretcher) { + stretcher.setWidth((this.getWidth() - Ext.getScrollbarSize().width)); + } + }, + + processUIEvent: function(e) { + + + + if (e.getTarget('.' + this.nodeAnimWrapCls, this.el)) { + return false; + } + return this.callParent(arguments); + }, + + onClear: function(){ + this.store.removeAll(); + }, + + setRootNode: function(node) { + var me = this; + me.store.setNode(node); + me.node = node; + }, + + onCheckboxChange: function(e, t) { + var me = this, + item = e.getTarget(me.getItemSelector(), me.getTargetEl()); + + if (item) { + me.onCheckChange(me.getRecord(item)); + } + }, + + onCheckChange: function(record){ + var checked = record.get('checked'); + if (Ext.isBoolean(checked)) { + checked = !checked; + record.set('checked', checked); + this.fireEvent('checkchange', record, checked); + } + }, + + getChecked: function() { + var checked = []; + this.node.cascadeBy(function(rec){ + if (rec.get('checked')) { + checked.push(rec); + } + }); + return checked; + }, + + isItemChecked: function(rec){ + return rec.get('checked'); + }, + + createAnimWrap: function(record, index) { + var thHtml = '', + headerCt = this.panel.headerCt, + headers = headerCt.getGridColumns(), + i = 0, len = headers.length, item, + node = this.getNode(record), + tmpEl, nodeEl; + + for (; i < len; i++) { + item = headers[i]; + thHtml += ''; + } + + nodeEl = Ext.get(node); + tmpEl = nodeEl.insertSibling({ + tag: 'tr', + html: [ + '', + '
', + '', + thHtml, + '
', + '
', + '' + ].join('') + }, 'after'); + + return { + record: record, + node: node, + el: tmpEl, + expanding: false, + collapsing: false, + animating: false, + animateEl: tmpEl.down('div'), + targetEl: tmpEl.down('tbody') + }; + }, + + + getAnimWrap: function(parent, bubble) { + if (!this.animate) { + return null; + } + + var wraps = this.animWraps, + wrap = wraps[parent.internalId]; + + if (bubble !== false) { + while (!wrap && parent) { + parent = parent.parentNode; + if (parent) { + wrap = wraps[parent.internalId]; + } + } + } + return wrap; + }, + + doAdd: function(nodes, records, index) { + + + var me = this, + record = records[0], + parent = record.parentNode, + a = me.all.elements, + relativeIndex = 0, + animWrap = me.getAnimWrap(parent), + targetEl, children, len; + + if (!animWrap || !animWrap.expanding) { + return me.callParent(arguments); + } + + + parent = animWrap.record; + + + targetEl = animWrap.targetEl; + children = targetEl.dom.childNodes; + + + len = children.length - 1; + + + relativeIndex = index - me.indexOf(parent) - 1; + + + + if (!len || relativeIndex >= len) { + targetEl.appendChild(nodes); + } + + + else { + + Ext.fly(children[relativeIndex + 1]).insertSibling(nodes, 'before', true); + } + + + Ext.Array.insert(a, index, nodes); + + + + if (animWrap.isAnimating) { + me.onExpand(parent); + } + }, + + beginBulkUpdate: function(){ + this.bulkUpdate = true; + this.ownerCt.changingScrollbars = true; + }, + + endBulkUpdate: function(){ + this.bulkUpdate = false; + this.ownerCt.changingScrollbars = true; + }, + + onRemove : function(ds, record, index) { + var me = this, + bulk = me.bulkUpdate; + + if (me.rendered) { + me.doRemove(record, index); + if (!bulk) { + me.updateIndexes(index); + } + if (me.store.getCount() === 0){ + me.refresh(); + } + if (!bulk) { + me.fireEvent('itemremove', record, index); + } + } + }, + + doRemove: function(record, index) { + + + var me = this, + all = me.all, + animWrap = me.getAnimWrap(record), + node = all.item(index).dom; + + if (!animWrap || !animWrap.collapsing) { + return me.callParent(arguments); + } + + animWrap.targetEl.appendChild(node); + all.removeElement(index); + }, + + onBeforeExpand: function(parent, records, index) { + var me = this, + animWrap; + + if (!me.rendered || !me.animate) { + return; + } + + if (me.getNode(parent)) { + animWrap = me.getAnimWrap(parent, false); + if (!animWrap) { + animWrap = me.animWraps[parent.internalId] = me.createAnimWrap(parent); + animWrap.animateEl.setHeight(0); + } + else if (animWrap.collapsing) { + + + animWrap.targetEl.select(me.itemSelector).remove(); + } + animWrap.expanding = true; + animWrap.collapsing = false; + } + }, + + onExpand: function(parent) { + var me = this, + queue = me.animQueue, + id = parent.getId(), + node = me.getNode(parent), + index = node ? me.indexOf(node) : -1, + animWrap, + animateEl, + targetEl; + + if (me.singleExpand) { + me.ensureSingleExpand(parent); + } + + + if (index === -1) { + return; + } + + animWrap = me.getAnimWrap(parent, false); + + if (!animWrap) { + me.isExpandingOrCollapsing = false; + me.fireEvent('afteritemexpand', parent, index, node); + return; + } + + animateEl = animWrap.animateEl; + targetEl = animWrap.targetEl; + + animateEl.stopAnimation(); + + queue[id] = true; + animateEl.slideIn('t', { + duration: me.expandDuration, + listeners: { + scope: me, + lastframe: function() { + + animWrap.el.insertSibling(targetEl.query(me.itemSelector), 'before'); + animWrap.el.remove(); + delete me.animWraps[animWrap.record.internalId]; + delete queue[id]; + } + }, + callback: function() { + me.isExpandingOrCollapsing = false; + me.fireEvent('afteritemexpand', parent, index, node); + } + }); + + animWrap.isAnimating = true; + }, + + onBeforeCollapse: function(parent, records, index) { + var me = this, + animWrap; + + if (!me.rendered || !me.animate) { + return; + } + + if (me.getNode(parent)) { + animWrap = me.getAnimWrap(parent); + if (!animWrap) { + animWrap = me.animWraps[parent.internalId] = me.createAnimWrap(parent, index); + } + else if (animWrap.expanding) { + + + animWrap.targetEl.select(this.itemSelector).remove(); + } + animWrap.expanding = false; + animWrap.collapsing = true; + } + }, + + onCollapse: function(parent) { + var me = this, + queue = me.animQueue, + id = parent.getId(), + node = me.getNode(parent), + index = node ? me.indexOf(node) : -1, + animWrap = me.getAnimWrap(parent), + animateEl, targetEl; + + + if (index === -1) { + return; + } + + if (!animWrap) { + me.isExpandingOrCollapsing = false; + me.fireEvent('afteritemcollapse', parent, index, node); + return; + } + + animateEl = animWrap.animateEl; + targetEl = animWrap.targetEl; + + queue[id] = true; + + + animateEl.stopAnimation(); + animateEl.slideOut('t', { + duration: me.collapseDuration, + listeners: { + scope: me, + lastframe: function() { + animWrap.el.remove(); + delete me.animWraps[animWrap.record.internalId]; + delete queue[id]; + } + }, + callback: function() { + me.isExpandingOrCollapsing = false; + me.fireEvent('afteritemcollapse', parent, index, node); + } + }); + animWrap.isAnimating = true; + }, + + + isAnimating: function(node) { + return !!this.animQueue[node.getId()]; + }, + + collectData: function(records) { + var data = this.callParent(arguments), + rows = data.rows, + len = rows.length, + i = 0, + row, record; + + for (; i < len; i++) { + row = rows[i]; + record = records[i]; + if (record.get('qtip')) { + row.rowAttr = 'data-qtip="' + record.get('qtip') + '"'; + if (record.get('qtitle')) { + row.rowAttr += ' ' + 'data-qtitle="' + record.get('qtitle') + '"'; + } + } + if (record.isExpanded()) { + row.rowCls = (row.rowCls || '') + ' ' + this.expandedCls; + } + if (record.isLeaf()) { + row.rowCls = (row.rowCls || '') + ' ' + this.leafCls; + } + if (record.isLoading()) { + row.rowCls = (row.rowCls || '') + ' ' + this.loadingCls; + } + } + + return data; + }, + + + expand: function(record, deep, callback, scope) { + return record.expand(deep, callback, scope); + }, + + + collapse: function(record, deep, callback, scope) { + return record.collapse(deep, callback, scope); + }, + + + toggle: function(record, deep, callback, scope) { + var me = this, + doAnimate = !!this.animate; + + + if (!doAnimate || !this.isExpandingOrCollapsing) { + if (!record.isLeaf()) { + this.isExpandingOrCollapsing = doAnimate; + } + if (record.isExpanded()) { + me.collapse(record, deep, callback, scope); + } else { + me.expand(record, deep, callback, scope); + } + } + }, + + onItemDblClick: function(record, item, index) { + var editingPlugin = this.editingPlugin; + this.callParent(arguments); + if (this.toggleOnDblClick && !(editingPlugin && editingPlugin.clicksToEdit === 2)) { + this.toggle(record); + } + }, + + onBeforeItemMouseDown: function(record, item, index, e) { + if (e.getTarget(this.expanderSelector, item)) { + return false; + } + return this.callParent(arguments); + }, + + onItemClick: function(record, item, index, e) { + if (e.getTarget(this.expanderSelector, item)) { + this.toggle(record, e.ctrlKey); + return false; + } + return this.callParent(arguments); + }, + + onExpanderMouseOver: function(e, t) { + e.getTarget(this.cellSelector, 10, true).addCls(this.expanderIconOverCls); + }, + + onExpanderMouseOut: function(e, t) { + e.getTarget(this.cellSelector, 10, true).removeCls(this.expanderIconOverCls); + }, + + + getTreeStore: function() { + return this.panel.store; + }, + + ensureSingleExpand: function(node) { + var parent = node.parentNode; + if (parent) { + parent.eachChild(function(child) { + if (child !== node && child.isExpanded()) { + child.collapse(); + } + }); + } + }, + + shouldUpdateCell: function(column, changedFieldNames){ + return Ext.Array.contains(this.uiFields, column.dataIndex) || this.callParent(arguments); + }, + + + onStoreWrite: function(store, operation) { + var treeStore = this.panel.store; + treeStore.fireEvent('write', treeStore, operation); + }, + + + onStoreDataChanged: function(store, operation) { + var treeStore = this.panel.store; + treeStore.fireEvent('datachanged', treeStore); + } +}); + + +Ext.define('Ext.tree.Panel', { + extend: 'Ext.panel.Table', + alias: 'widget.treepanel', + alternateClassName: ['Ext.tree.TreePanel', 'Ext.TreePanel'], + requires: ['Ext.tree.View', 'Ext.selection.TreeModel', 'Ext.tree.Column', 'Ext.data.TreeStore'], + viewType: 'treeview', + selType: 'treemodel', + + treeCls: Ext.baseCSSPrefix + 'tree-panel', + + deferRowRender: false, + + + rowLines: false, + + + lines: true, + + + useArrows: false, + + + singleExpand: false, + + ddConfig: { + enableDrag: true, + enableDrop: true + }, + + + + + rootVisible: true, + + + displayField: 'text', + + + root: null, + + + + normalCfgCopy: ['displayField', 'root', 'singleExpand', 'useArrows', 'lines', 'rootVisible', 'scroll'], + lockedCfgCopy: ['displayField', 'root', 'singleExpand', 'useArrows', 'lines', 'rootVisible'], + + isTree: true, + + + + + + + + constructor: function(config) { + config = config || {}; + if (config.animate === undefined) { + config.animate = Ext.isDefined(this.animate) ? this.animate : Ext.enableFx; + } + this.enableAnimations = config.animate; + delete config.animate; + + this.callParent([config]); + }, + + initComponent: function() { + var me = this, + cls = [me.treeCls], + view; + + if (me.useArrows) { + cls.push(Ext.baseCSSPrefix + 'tree-arrows'); + me.lines = false; + } + + if (me.lines) { + cls.push(Ext.baseCSSPrefix + 'tree-lines'); + } else if (!me.useArrows) { + cls.push(Ext.baseCSSPrefix + 'tree-no-lines'); + } + + if (Ext.isString(me.store)) { + me.store = Ext.StoreMgr.lookup(me.store); + } else if (!me.store || Ext.isObject(me.store) && !me.store.isStore) { + me.store = new Ext.data.TreeStore(Ext.apply({}, me.store || {}, { + root: me.root, + fields: me.fields, + model: me.model, + folderSort: me.folderSort + })); + } else if (me.root) { + me.store = Ext.data.StoreManager.lookup(me.store); + me.store.setRootNode(me.root); + if (me.folderSort !== undefined) { + me.store.folderSort = me.folderSort; + me.store.sort(); + } + } + + + + + + + me.viewConfig = Ext.apply({}, me.viewConfig); + me.viewConfig = Ext.applyIf(me.viewConfig, { + rootVisible: me.rootVisible, + animate: me.enableAnimations, + singleExpand: me.singleExpand, + node: me.store.getRootNode(), + hideHeaders: me.hideHeaders + }); + + me.mon(me.store, { + scope: me, + rootchange: me.onRootChange, + clear: me.onClear + }); + + me.relayEvents(me.store, [ + + 'beforeload', + + + 'load' + ]); + + me.store.on({ + + append: me.createRelayer('itemappend'), + + + remove: me.createRelayer('itemremove'), + + + move: me.createRelayer('itemmove', [0, 4]), + + + insert: me.createRelayer('iteminsert'), + + + beforeappend: me.createRelayer('beforeitemappend'), + + + beforeremove: me.createRelayer('beforeitemremove'), + + + beforemove: me.createRelayer('beforeitemmove'), + + + beforeinsert: me.createRelayer('beforeiteminsert'), + + + expand: me.createRelayer('itemexpand', [0, 1]), + + + collapse: me.createRelayer('itemcollapse', [0, 1]), + + + beforeexpand: me.createRelayer('beforeitemexpand', [0, 1]), + + + beforecollapse: me.createRelayer('beforeitemcollapse', [0, 1]) + }); + + + if (!me.columns) { + if (me.initialConfig.hideHeaders === undefined) { + me.hideHeaders = true; + } + me.addCls(Ext.baseCSSPrefix + 'autowidth-table'); + me.columns = [{ + xtype : 'treecolumn', + text : 'Name', + width : Ext.isIE6 ? null : 10000, + dataIndex: me.displayField + }]; + } + + if (me.cls) { + cls.push(me.cls); + } + me.cls = cls.join(' '); + me.callParent(); + + view = me.getView(); + + me.relayEvents(view, [ + + 'checkchange', + + 'afteritemexpand', + + 'afteritemcollapse' + ]); + + + if (!view.rootVisible && !me.getRootNode()) { + me.setRootNode({ + expanded: true + }); + } + }, + + onClear: function(){ + this.view.onClear(); + }, + + + setRootNode: function() { + return this.store.setRootNode.apply(this.store, arguments); + }, + + + getRootNode: function() { + return this.store.getRootNode(); + }, + + onRootChange: function(root) { + this.view.setRootNode(root); + }, + + + getChecked: function() { + return this.getView().getChecked(); + }, + + isItemChecked: function(rec) { + return rec.get('checked'); + }, + + + expandAll : function(callback, scope) { + var root = this.getRootNode(), + animate = this.enableAnimations, + view = this.getView(); + if (root) { + if (!animate) { + view.beginBulkUpdate(); + } + root.expand(true, callback, scope); + if (!animate) { + view.endBulkUpdate(); + } + } + }, + + + collapseAll : function(callback, scope) { + var root = this.getRootNode(), + animate = this.enableAnimations, + view = this.getView(); + + if (root) { + if (!animate) { + view.beginBulkUpdate(); + } + if (view.rootVisible) { + root.collapse(true, callback, scope); + } else { + root.collapseChildren(true, callback, scope); + } + if (!animate) { + view.endBulkUpdate(); + } + } + }, + + + expandPath: function(path, field, separator, callback, scope) { + var me = this, + current = me.getRootNode(), + index = 1, + view = me.getView(), + keys, + expander; + + field = field || me.getRootNode().idProperty; + separator = separator || '/'; + + if (Ext.isEmpty(path)) { + Ext.callback(callback, scope || me, [false, null]); + return; + } + + keys = path.split(separator); + if (current.get(field) != keys[1]) { + + Ext.callback(callback, scope || me, [false, current]); + return; + } + + expander = function(){ + if (++index === keys.length) { + Ext.callback(callback, scope || me, [true, current]); + return; + } + var node = current.findChild(field, keys[index]); + if (!node) { + Ext.callback(callback, scope || me, [false, current]); + return; + } + current = node; + current.expand(false, expander); + }; + current.expand(false, expander); + }, + + + selectPath: function(path, field, separator, callback, scope) { + var me = this, + keys, + last; + + field = field || me.getRootNode().idProperty; + separator = separator || '/'; + + keys = path.split(separator); + last = keys.pop(); + + me.expandPath(keys.join(separator), field, separator, function(success, node){ + var doSuccess = false; + if (success && node) { + node = node.findChild(field, last); + if (node) { + me.getSelectionModel().select(node); + Ext.callback(callback, scope || me, [true, node]); + doSuccess = true; + } + } else if (node === me.getRootNode()) { + doSuccess = true; + } + Ext.callback(callback, scope || me, [doSuccess, node]); + }, me); + } +}); + + +Ext.define('Ext.window.Window', { + extend: 'Ext.panel.Panel', + + alternateClassName: 'Ext.Window', + + requires: ['Ext.util.ComponentDragger', 'Ext.util.Region', 'Ext.EventManager'], + + alias: 'widget.window', + + + + + + + + + + + + + + + + + + + baseCls: Ext.baseCSSPrefix + 'window', + + + resizable: true, + + + draggable: true, + + + constrain: false, + + + constrainHeader: false, + + + + + plain: false, + + + minimizable: false, + + + maximizable: false, + + + minHeight: 50, + + + minWidth: 50, + + + expandOnShow: true, + + + collapsible: false, + + + closable: true, + + + hidden: true, + + + autoRender: true, + + + hideMode: 'offsets', + + + floating: true, + + ariaRole: 'alertdialog', + + itemCls: Ext.baseCSSPrefix + 'window-item', + + overlapHeader: true, + + ignoreHeaderBorderManagement: true, + + + alwaysFramed: true, + + + isWindow: true, + + + initComponent: function() { + var me = this; + me.callParent(); + me.addEvents( + + + + + + 'resize', + + + 'maximize', + + + 'minimize', + + + 'restore' + ); + + if (me.plain) { + me.addClsWithUI('plain'); + } + + if (me.modal) { + me.ariaRole = 'dialog'; + } + + + if (me.floating) { + me.on({ + element: 'el', + mousedown: me.onMouseDown, + scope: me + }); + } + + me.addStateEvents(['maximize', 'restore', 'resize', 'dragend']); + }, + + getElConfig: function () { + var me = this, + elConfig; + + elConfig = me.callParent(); + elConfig.tabIndex = -1; + return elConfig; + }, + + + + + getState: function() { + var me = this, + state = me.callParent() || {}, + maximized = !!me.maximized; + + state.maximized = maximized; + Ext.apply(state, { + size: maximized ? me.restoreSize : me.getSize(), + pos: maximized ? me.restorePos : me.getPosition() + }); + return state; + }, + + applyState: function(state){ + var me = this; + + if (state) { + me.maximized = state.maximized; + if (me.maximized) { + me.hasSavedRestore = true; + me.restoreSize = state.size; + me.restorePos = state.pos; + } else { + Ext.apply(me, { + width: state.size.width, + height: state.size.height, + x: state.pos[0], + y: state.pos[1] + }); + } + } + }, + + + onMouseDown: function (e) { + var preventFocus; + + if (this.floating) { + if (Ext.fly(e.getTarget()).focusable()) { + preventFocus = true; + } + this.toFront(preventFocus); + } + }, + + + onRender: function(ct, position) { + var me = this; + me.callParent(arguments); + me.focusEl = me.el; + + + if (me.maximizable) { + me.header.on({ + scope: me, + dblclick: me.toggleMaximize + }); + } + }, + + + afterRender: function() { + var me = this, + keyMap; + + me.callParent(); + + + if (me.maximized) { + me.maximized = false; + me.maximize(); + } + + if (me.closable) { + keyMap = me.getKeyMap(); + keyMap.on(27, me.onEsc, me); + + + keyMap.disable(); + + } + }, + + + initDraggable: function() { + var me = this, + ddConfig; + + if (!me.header) { + me.updateHeader(true); + } + + + if (me.header) { + ddConfig = Ext.applyIf({ + el: me.el, + delegate: '#' + Ext.escapeId(me.header.id) + }, me.draggable); + + + if (me.constrain || me.constrainHeader) { + ddConfig.constrain = me.constrain; + ddConfig.constrainDelegate = me.constrainHeader; + ddConfig.constrainTo = me.constrainTo || me.container; + } + + + me.dd = new Ext.util.ComponentDragger(this, ddConfig); + me.relayEvents(me.dd, ['dragstart', 'drag', 'dragend']); + } + }, + + + onEsc: function(k, e) { + + if (!Ext.FocusManager || !Ext.FocusManager.enabled || Ext.FocusManager.focusedCmp === this) { + e.stopEvent(); + this.close(); + } + }, + + + beforeDestroy: function() { + var me = this; + if (me.rendered) { + delete this.animateTarget; + me.hide(); + Ext.destroy( + me.keyMap + ); + } + me.callParent(); + }, + + + addTools: function() { + var me = this; + + + me.callParent(); + + if (me.minimizable) { + me.addTool({ + type: 'minimize', + handler: Ext.Function.bind(me.minimize, me, []) + }); + } + if (me.maximizable) { + me.addTool({ + type: 'maximize', + handler: Ext.Function.bind(me.maximize, me, []) + }); + me.addTool({ + type: 'restore', + handler: Ext.Function.bind(me.restore, me, []), + hidden: true + }); + } + }, + + + getFocusEl: function() { + return this.getDefaultFocus(); + }, + + + getDefaultFocus: function() { + var me = this, + result, + defaultComp = me.defaultButton || me.defaultFocus, + selector; + + if (defaultComp !== undefined) { + + if (Ext.isNumber(defaultComp)) { + result = me.query('button')[defaultComp]; + } + + else if (Ext.isString(defaultComp)) { + selector = defaultComp; + if (selector.substr(0, 1) !== '#') { + selector = '#' + selector; + } + result = me.down(selector); + } + + else if (defaultComp.focus) { + result = defaultComp; + } + } + return result || me.el; + }, + + + onFocus: function() { + var me = this, + focusDescendant; + + + if ((Ext.FocusManager && Ext.FocusManager.enabled) || ((focusDescendant = me.getDefaultFocus()) === me)) { + me.callParent(arguments); + } else { + focusDescendant.focus(); + } + }, + + + afterShow: function(animateTarget) { + var me = this, + animating = animateTarget || me.animateTarget; + + if (this.expandOnShow) { + this.expand(false); + } + + + + + + me.callParent(arguments); + + if (me.maximized) { + me.fitContainer(); + } + + me.syncMonitorWindowResize(); + if (!animating) { + me.doConstrain(); + } + + if (me.keyMap) { + me.keyMap.enable(); + } + }, + + + doClose: function() { + var me = this; + + + if (me.hidden) { + me.fireEvent('close', me); + if (me.closeAction == 'destroy') { + this.destroy(); + } + } else { + + me.hide(me.animateTarget, me.doClose, me); + } + }, + + + afterHide: function() { + var me = this; + + + me.syncMonitorWindowResize(); + + + if (me.keyMap) { + me.keyMap.disable(); + } + + + me.callParent(arguments); + }, + + + onWindowResize: function() { + if (this.maximized) { + this.fitContainer(); + } + this.doConstrain(); + }, + + + minimize: function() { + this.fireEvent('minimize', this); + return this; + }, + + afterCollapse: function() { + var me = this; + + if (me.maximizable) { + me.tools.maximize.hide(); + me.tools.restore.hide(); + } + if (me.resizer) { + me.resizer.disable(); + } + me.callParent(arguments); + }, + + afterExpand: function() { + var me = this; + + if (me.maximized) { + me.tools.restore.show(); + } else if (me.maximizable) { + me.tools.maximize.show(); + } + if (me.resizer) { + me.resizer.enable(); + } + me.callParent(arguments); + }, + + + maximize: function() { + var me = this; + + if (!me.maximized) { + me.expand(false); + if (!me.hasSavedRestore) { + me.restoreSize = me.getSize(); + me.restorePos = me.getPosition(true); + } + if (me.maximizable) { + me.tools.maximize.hide(); + me.tools.restore.show(); + } + me.maximized = true; + me.el.disableShadow(); + + if (me.dd) { + me.dd.disable(); + } + if (me.resizer) { + me.resizer.disable(); + } + if (me.collapseTool) { + me.collapseTool.hide(); + } + me.el.addCls(Ext.baseCSSPrefix + 'window-maximized'); + me.container.addCls(Ext.baseCSSPrefix + 'window-maximized-ct'); + + me.syncMonitorWindowResize(); + me.setPosition(0, 0); + me.fitContainer(); + me.fireEvent('maximize', me); + } + return me; + }, + + + restore: function() { + var me = this, + tools = me.tools; + + if (me.maximized) { + delete me.hasSavedRestore; + me.removeCls(Ext.baseCSSPrefix + 'window-maximized'); + + + if (tools.restore) { + tools.restore.hide(); + } + if (tools.maximize) { + tools.maximize.show(); + } + if (me.collapseTool) { + me.collapseTool.show(); + } + + + me.setPosition(me.restorePos); + me.setSize(me.restoreSize); + + + delete me.restorePos; + delete me.restoreSize; + + me.maximized = false; + + me.el.enableShadow(true); + + + if (me.dd) { + me.dd.enable(); + } + + if (me.resizer) { + me.resizer.enable(); + } + + me.container.removeCls(Ext.baseCSSPrefix + 'window-maximized-ct'); + + me.syncMonitorWindowResize(); + me.doConstrain(); + me.fireEvent('restore', me); + } + return me; + }, + + + syncMonitorWindowResize: function () { + var me = this, + currentlyMonitoring = me._monitoringResize, + + yes = me.monitorResize || me.constrain || me.constrainHeader || me.maximized, + + veto = me.hidden || me.destroying || me.isDestroyed; + + if (yes && !veto) { + + if (!currentlyMonitoring) { + + Ext.EventManager.onWindowResize(me.onWindowResize, me); + me._monitoringResize = true; + } + } else if (currentlyMonitoring) { + + Ext.EventManager.removeResizeListener(me.onWindowResize, me); + me._monitoringResize = false; + } + }, + + + toggleMaximize: function() { + return this[this.maximized ? 'restore': 'maximize'](); + } + +}); + + +Ext.define('Ext.window.MessageBox', { + extend: 'Ext.window.Window', + + requires: [ + 'Ext.toolbar.Toolbar', + 'Ext.form.field.Text', + 'Ext.form.field.TextArea', + 'Ext.form.field.Display', + 'Ext.button.Button', + 'Ext.layout.container.Anchor', + 'Ext.layout.container.HBox', + 'Ext.ProgressBar' + ], + + alias: 'widget.messagebox', + + + OK : 1, + + YES : 2, + + NO : 4, + + CANCEL : 8, + + OKCANCEL : 9, + + YESNO : 6, + + YESNOCANCEL : 14, + + INFO : Ext.baseCSSPrefix + 'message-box-info', + + WARNING : Ext.baseCSSPrefix + 'message-box-warning', + + QUESTION : Ext.baseCSSPrefix + 'message-box-question', + + ERROR : Ext.baseCSSPrefix + 'message-box-error', + + + hideMode: 'offsets', + closeAction: 'hide', + resizable: false, + title: ' ', + + width: 600, + height: 500, + minWidth: 250, + maxWidth: 600, + minHeight: 110, + maxHeight: 500, + constrain: true, + + cls: Ext.baseCSSPrefix + 'message-box', + + layout: { + type: 'vbox', + align: 'stretch' + }, + + + defaultTextHeight : 75, + + minProgressWidth : 250, + + minPromptWidth: 250, + + + buttonText: { + ok: 'OK', + yes: 'Yes', + no: 'No', + cancel: 'Cancel' + }, + + + buttonIds: [ + 'ok', 'yes', 'no', 'cancel' + ], + + + titleText: { + confirm: 'Confirm', + prompt: 'Prompt', + wait: 'Loading...', + alert: 'Attention' + }, + + + iconHeight: 35, + + makeButton: function(btnIdx) { + var btnId = this.buttonIds[btnIdx]; + return new Ext.button.Button({ + handler: this.btnCallback, + itemId: btnId, + scope: this, + text: this.buttonText[btnId], + minWidth: 75 + }); + }, + + btnCallback: function(btn) { + var me = this, + value, + field; + + if (me.cfg.prompt || me.cfg.multiline) { + if (me.cfg.multiline) { + field = me.textArea; + } else { + field = me.textField; + } + value = field.getValue(); + field.reset(); + } + + + btn.blur(); + me.hide(); + me.userCallback(btn.itemId, value, me.cfg); + }, + + hide: function() { + var me = this; + me.dd.endDrag(); + me.progressBar.reset(); + me.removeCls(me.cfg.cls); + me.callParent(arguments); + }, + + initComponent: function() { + var me = this, + baseId = me.id, + i, button, + tbLayout; + + me.title = ' '; + + me.topContainer = new Ext.container.Container({ + layout: 'hbox', + style: { + padding: '10px', + overflow: 'hidden' + }, + items: [ + me.iconComponent = new Ext.Component({ + cls: me.baseCls + '-icon', + width: 50, + height: me.iconHeight + }), + me.promptContainer = new Ext.container.Container({ + flex: 1, + layout: { + type: 'anchor' + }, + items: [ + me.msg = new Ext.form.field.Display({ + id: baseId + '-displayfield', + cls: me.baseCls + '-text' + }), + me.textField = new Ext.form.field.Text({ + id: baseId + '-testfield', + anchor: '100%', + enableKeyEvents: true, + listeners: { + keydown: me.onPromptKey, + scope: me + } + }), + me.textArea = new Ext.form.field.TextArea({ + id: baseId + '-textarea', + anchor: '100%', + height: 75 + }) + ] + }) + ] + }); + me.progressBar = new Ext.ProgressBar({ + id: baseId + '-progressbar', + margins: '0 10 0 10' + }); + + me.items = [me.topContainer, me.progressBar]; + + + me.msgButtons = []; + for (i = 0; i < 4; i++) { + button = me.makeButton(i); + me.msgButtons[button.itemId] = button; + me.msgButtons.push(button); + } + me.bottomTb = new Ext.toolbar.Toolbar({ + id: baseId + '-toolbar', + ui: 'footer', + dock: 'bottom', + layout: { + pack: 'center' + }, + items: [ + me.msgButtons[0], + me.msgButtons[1], + me.msgButtons[2], + me.msgButtons[3] + ] + }); + me.dockedItems = [me.bottomTb]; + + + tbLayout = me.bottomTb.getLayout(); + tbLayout.finishedLayout = Ext.Function.createInterceptor(tbLayout.finishedLayout, function(ownerContext) { + me.tbWidth = ownerContext.getProp('contentWidth'); + }); + me.on('close', me.onClose, me); + + me.callParent(); + }, + + onClose: function(){ + var btn = this.header.child('[type=close]'); + + btn.itemId = 'cancel'; + this.btnCallback(btn); + delete btn.itemId; + }, + + onPromptKey: function(textField, e) { + var me = this, + blur; + + if (e.keyCode === Ext.EventObject.RETURN || e.keyCode === 10) { + if (me.msgButtons.ok.isVisible()) { + blur = true; + me.msgButtons.ok.handler.call(me, me.msgButtons.ok); + } else if (me.msgButtons.yes.isVisible()) { + me.msgButtons.yes.handler.call(me, me.msgButtons.yes); + blur = true; + } + + if (blur) { + me.textField.blur(); + } + } + }, + + reconfigure: function(cfg) { + var me = this, + buttons = 0, + hideToolbar = true, + initialWidth = me.maxWidth, + oldButtonText = me.buttonText, + i; + + + me.updateButtonText(); + + cfg = cfg || {}; + me.cfg = cfg; + if (cfg.width) { + initialWidth = cfg.width; + } + + + delete me.defaultFocus; + + + me.animateTarget = cfg.animateTarget || undefined; + + + me.modal = cfg.modal !== false; + + + if (cfg.title) { + me.setTitle(cfg.title||' '); + } + + + if (Ext.isObject(cfg.buttons)) { + me.buttonText = cfg.buttons; + buttons = 0; + } else { + me.buttonText = cfg.buttonText || me.buttonText; + buttons = Ext.isNumber(cfg.buttons) ? cfg.buttons : 0; + } + + + + buttons = buttons | me.updateButtonText(); + + + me.buttonText = oldButtonText; + + + + Ext.suspendLayouts(); + me.hidden = false; + if (!me.rendered) { + me.width = initialWidth; + me.render(Ext.getBody()); + } else { + me.setSize(initialWidth, me.maxHeight); + } + + + me.closable = cfg.closable && !cfg.wait; + me.header.child('[type=close]').setVisible(cfg.closable !== false); + + + if (!cfg.title && !me.closable) { + me.header.hide(); + } else { + me.header.show(); + } + + + me.liveDrag = !cfg.proxyDrag; + + + me.userCallback = Ext.Function.bind(cfg.callback ||cfg.fn || Ext.emptyFn, cfg.scope || Ext.global); + + + me.setIcon(cfg.icon); + + + if (cfg.msg) { + me.msg.setValue(cfg.msg); + me.msg.show(); + } else { + me.msg.hide(); + } + + + + Ext.resumeLayouts(true); + Ext.suspendLayouts(); + + + if (cfg.prompt || cfg.multiline) { + me.multiline = cfg.multiline; + if (cfg.multiline) { + me.textArea.setValue(cfg.value); + me.textArea.setHeight(cfg.defaultTextHeight || me.defaultTextHeight); + me.textArea.show(); + me.textField.hide(); + me.defaultFocus = me.textArea; + } else { + me.textField.setValue(cfg.value); + me.textArea.hide(); + me.textField.show(); + me.defaultFocus = me.textField; + } + } else { + me.textArea.hide(); + me.textField.hide(); + } + + + if (cfg.progress || cfg.wait) { + me.progressBar.show(); + me.updateProgress(0, cfg.progressText); + if(cfg.wait === true){ + me.progressBar.wait(cfg.waitConfig); + } + } else { + me.progressBar.hide(); + } + + + for (i = 0; i < 4; i++) { + if (buttons & Math.pow(2, i)) { + + + if (!me.defaultFocus) { + me.defaultFocus = me.msgButtons[i]; + } + me.msgButtons[i].show(); + hideToolbar = false; + } else { + me.msgButtons[i].hide(); + } + } + + + if (hideToolbar) { + me.bottomTb.hide(); + } else { + me.bottomTb.show(); + } + Ext.resumeLayouts(true); + }, + + + updateButtonText: function() { + var me = this, + buttonText = me.buttonText, + buttons = 0, + btnId, + btn; + + for (btnId in buttonText) { + if (buttonText.hasOwnProperty(btnId)) { + btn = me.msgButtons[btnId]; + if (btn) { + if (me.cfg && me.cfg.buttonText) { + buttons = buttons | Math.pow(2, Ext.Array.indexOf(me.buttonIds, btnId)); + } + if (btn.text != buttonText[btnId]) { + btn.setText(buttonText[btnId]); + } + } + } + } + return buttons; + }, + + + show: function(cfg) { + var me = this; + + me.reconfigure(cfg); + me.addCls(cfg.cls); + me.doAutoSize(); + + + + me.hidden = true; + me.callParent(); + return me; + }, + + onShow: function() { + this.callParent(arguments); + this.center(); + }, + + doAutoSize: function() { + var me = this, + headerVisible = me.header.rendered && me.header.isVisible(), + footerVisible = me.bottomTb.rendered && me.bottomTb.isVisible(), + width, + height; + + if (!Ext.isDefined(me.frameWidth)) { + me.frameWidth = me.el.getWidth() - me.body.getWidth(); + } + + + me.minWidth = me.cfg.minWidth || Ext.getClass(this).prototype.minWidth; + + + width = Math.max( + headerVisible ? me.header.getMinWidth() : 0, + me.cfg.width || me.msg.getWidth() + me.iconComponent.getWidth() + 25, + (footerVisible ? me.tbWidth : 0) + ); + + height = (headerVisible ? me.header.getHeight() : 0) + + me.topContainer.getHeight() + + me.progressBar.getHeight() + + (footerVisible ? me.bottomTb.getHeight() + me.bottomTb.el.getMargin('tb') : 0); + + me.setSize(width + me.frameWidth, height + me.frameWidth); + return me; + }, + + updateText: function(text) { + this.msg.setValue(text); + return this.doAutoSize(true); + }, + + + setIcon : function(icon) { + var me = this; + me.iconComponent.removeCls(me.messageIconCls); + if (icon) { + me.iconComponent.show(); + me.iconComponent.addCls(Ext.baseCSSPrefix + 'dlg-icon'); + me.iconComponent.addCls(me.messageIconCls = icon); + } else { + me.iconComponent.removeCls(Ext.baseCSSPrefix + 'dlg-icon'); + me.iconComponent.hide(); + } + return me; + }, + + + updateProgress : function(value, progressText, msg){ + this.progressBar.updateProgress(value, progressText); + if (msg){ + this.updateText(msg); + } + return this; + }, + + onEsc: function() { + if (this.closable !== false) { + this.callParent(arguments); + } + }, + + + confirm: function(cfg, msg, fn, scope) { + if (Ext.isString(cfg)) { + cfg = { + title: cfg, + icon: this.QUESTION, + msg: msg, + buttons: this.YESNO, + callback: fn, + scope: scope + }; + } + return this.show(cfg); + }, + + + prompt : function(cfg, msg, fn, scope, multiline, value){ + if (Ext.isString(cfg)) { + cfg = { + prompt: true, + title: cfg, + minWidth: this.minPromptWidth, + msg: msg, + buttons: this.OKCANCEL, + callback: fn, + scope: scope, + multiline: multiline, + value: value + }; + } + return this.show(cfg); + }, + + + wait : function(cfg, title, config){ + if (Ext.isString(cfg)) { + cfg = { + title : title, + msg : cfg, + closable: false, + wait: true, + modal: true, + minWidth: this.minProgressWidth, + waitConfig: config + }; + } + return this.show(cfg); + }, + + + alert: function(cfg, msg, fn, scope) { + if (Ext.isString(cfg)) { + cfg = { + title : cfg, + msg : msg, + buttons: this.OK, + fn: fn, + scope : scope, + minWidth: this.minWidth + }; + } + return this.show(cfg); + }, + + + progress : function(cfg, msg, progressText){ + if (Ext.isString(cfg)) { + cfg = { + title: cfg, + msg: msg, + progress: true, + progressText: progressText + }; + } + return this.show(cfg); + } +}, function() { + + Ext.MessageBox = Ext.Msg = new this(); +}); + +Ext.define('Ext.form.Basic', { + extend: 'Ext.util.Observable', + alternateClassName: 'Ext.form.BasicForm', + requires: ['Ext.util.MixedCollection', 'Ext.form.action.Load', 'Ext.form.action.Submit', + 'Ext.window.MessageBox', 'Ext.data.Errors', 'Ext.util.DelayedTask'], + + + constructor: function(owner, config) { + var me = this, + onItemAddOrRemove = me.onItemAddOrRemove, + api, + fn; + + + me.owner = owner; + + + me.mon(owner, { + add: onItemAddOrRemove, + remove: onItemAddOrRemove, + scope: me + }); + + Ext.apply(me, config); + + + if (Ext.isString(me.paramOrder)) { + me.paramOrder = me.paramOrder.split(/[\s,|]/); + } + + if (me.api) { + api = me.api = Ext.apply({}, me.api); + for (fn in api) { + if (api.hasOwnProperty(fn)) { + api[fn] = Ext.direct.Manager.parseMethod(api[fn]); + } + } + } + + me.checkValidityTask = new Ext.util.DelayedTask(me.checkValidity, me); + + me.addEvents( + + 'beforeaction', + + 'actionfailed', + + 'actioncomplete', + + 'validitychange', + + 'dirtychange' + ); + me.callParent(); + }, + + + initialize : function() { + var me = this; + me.initialized = true; + me.onValidityChange(!me.hasInvalidField()); + }, + + + + + + + + + + + + + + timeout: 30, + + + + + + + paramsAsHash: false, + + + + waitTitle: 'Please Wait...', + + + + trackResetOnLoad: false, + + + + + + + + wasDirty: false, + + + + destroy: function() { + this.clearListeners(); + this.checkValidityTask.cancel(); + }, + + + onItemAddOrRemove: function(parent, child) { + var me = this, + isAdding = !!child.ownerCt, + isContainer = child.isContainer; + + function handleField(field) { + + me[isAdding ? 'mon' : 'mun'](field, { + validitychange: me.checkValidity, + dirtychange: me.checkDirty, + scope: me, + buffer: 100 + }); + + delete me._fields; + } + + if (child.isFormField) { + handleField(child); + } else if (isContainer) { + + if (child.isDestroyed) { + + + delete me._fields; + } else { + Ext.Array.forEach(child.query('[isFormField]'), handleField); + } + } + + + delete this._boundItems; + + + + if (me.initialized) { + me.checkValidityTask.delay(10); + } + }, + + + getFields: function() { + var fields = this._fields; + if (!fields) { + fields = this._fields = new Ext.util.MixedCollection(); + fields.addAll(this.owner.query('[isFormField]')); + } + return fields; + }, + + + getBoundItems: function() { + var boundItems = this._boundItems; + + if (!boundItems || boundItems.getCount() === 0) { + boundItems = this._boundItems = new Ext.util.MixedCollection(); + boundItems.addAll(this.owner.query('[formBind]')); + } + + return boundItems; + }, + + + hasInvalidField: function() { + return !!this.getFields().findBy(function(field) { + var preventMark = field.preventMark, + isValid; + field.preventMark = true; + isValid = field.isValid(); + field.preventMark = preventMark; + return !isValid; + }); + }, + + + isValid: function() { + var me = this, + invalid; + Ext.suspendLayouts(); + invalid = me.getFields().filterBy(function(field) { + return !field.validate(); + }); + Ext.resumeLayouts(true); + return invalid.length < 1; + }, + + + checkValidity: function() { + var me = this, + valid = !me.hasInvalidField(); + if (valid !== me.wasValid) { + me.onValidityChange(valid); + me.fireEvent('validitychange', me, valid); + me.wasValid = valid; + } + }, + + + onValidityChange: function(valid) { + var boundItems = this.getBoundItems(), + items, i, iLen, cmp; + + if (boundItems) { + items = boundItems.items; + iLen = items.length; + + for (i = 0; i < iLen; i++) { + cmp = items[i]; + + if (cmp.disabled === valid) { + cmp.setDisabled(!valid); + } + } + } + }, + + + isDirty: function() { + return !!this.getFields().findBy(function(f) { + return f.isDirty(); + }); + }, + + + checkDirty: function() { + var dirty = this.isDirty(); + if (dirty !== this.wasDirty) { + this.fireEvent('dirtychange', this, dirty); + this.wasDirty = dirty; + } + }, + + + hasUpload: function() { + return !!this.getFields().findBy(function(f) { + return f.isFileUpload(); + }); + }, + + + doAction: function(action, options) { + if (Ext.isString(action)) { + action = Ext.ClassManager.instantiateByAlias('formaction.' + action, Ext.apply({}, options, {form: this})); + } + if (this.fireEvent('beforeaction', this, action) !== false) { + this.beforeAction(action); + Ext.defer(action.run, 100, action); + } + return this; + }, + + + submit: function(options) { + return this.doAction(this.standardSubmit ? 'standardsubmit' : this.api ? 'directsubmit' : 'submit', options); + }, + + + load: function(options) { + return this.doAction(this.api ? 'directload' : 'load', options); + }, + + + updateRecord: function(record) { + record = record || this._record; + var fields = record.fields.items, + values = this.getFieldValues(), + obj = {}, + i = 0, + len = fields.length, + name; + + for (; i < len; ++i) { + name = fields[i].name; + + if (values.hasOwnProperty(name)) { + obj[name] = values[name]; + } + } + + record.beginEdit(); + record.set(obj); + record.endEdit(); + + return this; + }, + + + loadRecord: function(record) { + this._record = record; + return this.setValues(record.data); + }, + + + getRecord: function() { + return this._record; + }, + + + beforeAction: function(action) { + var waitMsg = action.waitMsg, + maskCls = Ext.baseCSSPrefix + 'mask-loading', + fields = this.getFields().items, + f, + fLen = fields.length, + field, waitMsgTarget; + + + for (f = 0; f < fLen; f++) { + field = fields[f]; + + if (field.isFormField && field.syncValue) { + field.syncValue(); + } + } + + if (waitMsg) { + waitMsgTarget = this.waitMsgTarget; + if (waitMsgTarget === true) { + this.owner.el.mask(waitMsg, maskCls); + } else if (waitMsgTarget) { + waitMsgTarget = this.waitMsgTarget = Ext.get(waitMsgTarget); + waitMsgTarget.mask(waitMsg, maskCls); + } else { + Ext.MessageBox.wait(waitMsg, action.waitTitle || this.waitTitle); + } + } + }, + + + afterAction: function(action, success) { + if (action.waitMsg) { + var MessageBox = Ext.MessageBox, + waitMsgTarget = this.waitMsgTarget; + if (waitMsgTarget === true) { + this.owner.el.unmask(); + } else if (waitMsgTarget) { + waitMsgTarget.unmask(); + } else { + MessageBox.updateProgress(1); + MessageBox.hide(); + } + } + if (success) { + if (action.reset) { + this.reset(); + } + Ext.callback(action.success, action.scope || action, [this, action]); + this.fireEvent('actioncomplete', this, action); + } else { + Ext.callback(action.failure, action.scope || action, [this, action]); + this.fireEvent('actionfailed', this, action); + } + }, + + + + findField: function(id) { + return this.getFields().findBy(function(f) { + return f.id === id || f.getName() === id; + }); + }, + + + + markInvalid: function(errors) { + var me = this, + e, eLen, error, value, + key; + + function mark(fieldId, msg) { + var field = me.findField(fieldId); + if (field) { + field.markInvalid(msg); + } + } + + if (Ext.isArray(errors)) { + eLen = errors.length; + + for (e = 0; e < eLen; e++) { + error = errors[e]; + mark(error.id, error.msg); + } + } else if (errors instanceof Ext.data.Errors) { + eLen = errors.items.length; + for (e = 0; e < eLen; e++) { + error = errors.items[e]; + + mark(error.field, error.message); + } + } else { + for (key in errors) { + if (errors.hasOwnProperty(key)) { + value = errors[key]; + mark(key, value, errors); + } + } + } + return this; + }, + + + setValues: function(values) { + var me = this, + v, vLen, val, field; + + function setVal(fieldId, val) { + var field = me.findField(fieldId); + if (field) { + field.setValue(val); + if (me.trackResetOnLoad) { + field.resetOriginalValue(); + } + } + } + + if (Ext.isArray(values)) { + + vLen = values.length; + + for (v = 0; v < vLen; v++) { + val = values[v]; + + setVal(val.id, val.value); + } + } else { + + Ext.iterate(values, setVal); + } + return this; + }, + + + getValues: function(asString, dirtyOnly, includeEmptyText, useDataValues) { + var values = {}, + fields = this.getFields().items, + f, + fLen = fields.length, + isArray = Ext.isArray, + field, data, val, bucket, name; + + for (f = 0; f < fLen; f++) { + field = fields[f]; + + if (!dirtyOnly || field.isDirty()) { + data = field[useDataValues ? 'getModelData' : 'getSubmitData'](includeEmptyText); + + if (Ext.isObject(data)) { + for (name in data) { + if (data.hasOwnProperty(name)) { + val = data[name]; + + if (includeEmptyText && val === '') { + val = field.emptyText || ''; + } + + if (values.hasOwnProperty(name)) { + bucket = values[name]; + + if (!isArray(bucket)) { + bucket = values[name] = [bucket]; + } + + if (isArray(val)) { + values[name] = values[name] = bucket.concat(val); + } else { + bucket.push(val); + } + } else { + values[name] = val; + } + } + } + } + } + } + + if (asString) { + values = Ext.Object.toQueryString(values); + } + return values; + }, + + + getFieldValues: function(dirtyOnly) { + return this.getValues(false, dirtyOnly, false, true); + }, + + + clearInvalid: function() { + Ext.suspendLayouts(); + + var me = this, + fields = me.getFields().items, + f, + fLen = fields.length; + + for (f = 0; f < fLen; f++) { + fields[f].clearInvalid(); + } + + Ext.resumeLayouts(true); + return me; + }, + + + reset: function() { + Ext.suspendLayouts(); + + var me = this, + fields = me.getFields().items, + f, + fLen = fields.length; + + for (f = 0; f < fLen; f++) { + fields[f].reset(); + } + + Ext.resumeLayouts(true); + return me; + }, + + + applyToFields: function(obj) { + var fields = this.getFields().items, + f, + fLen = fields.length; + + for (f = 0; f < fLen; f++) { + Ext.apply(fields[f], obj); + } + + return this; + }, + + + applyIfToFields: function(obj) { + var fields = this.getFields().items, + f, + fLen = fields.length; + + for (f = 0; f < fLen; f++) { + Ext.applyIf(fields[f], obj); + } + + return this; + } +}); + + +Ext.define('Ext.form.Panel', { + extend:'Ext.panel.Panel', + mixins: { + fieldAncestor: 'Ext.form.FieldAncestor' + }, + alias: 'widget.form', + alternateClassName: ['Ext.FormPanel', 'Ext.form.FormPanel'], + requires: ['Ext.form.Basic', 'Ext.util.TaskRunner'], + + + + + + + layout: 'anchor', + + ariaRole: 'form', + + initComponent: function() { + var me = this; + + if (me.frame) { + me.border = false; + } + + me.initFieldAncestor(); + me.callParent(); + + me.relayEvents(me.form, [ + + 'beforeaction', + + 'actionfailed', + + 'actioncomplete', + + 'validitychange', + + 'dirtychange' + ]); + + + if (me.pollForChanges) { + me.startPolling(me.pollInterval || 500); + } + }, + + initItems: function() { + + var me = this; + + me.form = me.createForm(); + me.callParent(); + }, + + + afterFirstLayout: function() { + this.callParent(); + this.form.initialize(); + }, + + + createForm: function() { + return new Ext.form.Basic(this, Ext.applyIf({listeners: {}}, this.initialConfig)); + }, + + + getForm: function() { + return this.form; + }, + + + loadRecord: function(record) { + return this.getForm().loadRecord(record); + }, + + + getRecord: function() { + return this.getForm().getRecord(); + }, + + + getValues: function(asString, dirtyOnly, includeEmptyText, useDataValues) { + return this.getForm().getValues(asString, dirtyOnly, includeEmptyText, useDataValues); + }, + + beforeDestroy: function() { + this.stopPolling(); + this.form.destroy(); + this.callParent(); + }, + + + load: function(options) { + this.form.load(options); + }, + + + submit: function(options) { + this.form.submit(options); + }, + + + startPolling: function(interval) { + this.stopPolling(); + var task = new Ext.util.TaskRunner(interval); + task.start({ + interval: 0, + run: this.checkChange, + scope: this + }); + this.pollTask = task; + }, + + + stopPolling: function() { + var task = this.pollTask; + if (task) { + task.stopAll(); + delete this.pollTask; + } + }, + + + checkChange: function() { + var fields = this.form.getFields().items, + f, + fLen = fields.length, + field; + + for (f = 0; f < fLen; f++) { + fields[f].checkChange(); + } + } +}); + + + + + + + + + + +Ext.define('Ext.grid.RowEditor', { + extend: 'Ext.form.Panel', + requires: [ + 'Ext.tip.ToolTip', + 'Ext.util.HashMap', + 'Ext.util.KeyNav' + ], + + + saveBtnText : 'Update', + + + cancelBtnText: 'Cancel', + + + errorsText: 'Errors', + + + dirtyText: 'You need to commit or cancel your changes', + + + lastScrollLeft: 0, + lastScrollTop: 0, + + border: false, + + + + hideMode: 'offsets', + + initComponent: function() { + var me = this, + form; + + me.cls = Ext.baseCSSPrefix + 'grid-row-editor'; + + me.layout = { + type: 'hbox', + align: 'middle' + }; + + + + me.columns = new Ext.util.HashMap(); + me.columns.getKey = function(columnHeader) { + var f; + if (columnHeader.getEditor) { + f = columnHeader.getEditor(); + if (f) { + return f.id; + } + } + return columnHeader.id; + }; + me.mon(me.columns, { + add: me.onFieldAdd, + remove: me.onFieldRemove, + replace: me.onFieldReplace, + scope: me + }); + + me.callParent(arguments); + + if (me.fields) { + me.setField(me.fields); + delete me.fields; + } + + form = me.getForm(); + form.trackResetOnLoad = true; + }, + + onFieldChange: function() { + var me = this, + form = me.getForm(), + valid = form.isValid(); + if (me.errorSummary && me.isVisible()) { + me[valid ? 'hideToolTip' : 'showToolTip'](); + } + if (me.floatingButtons) { + me.floatingButtons.child('#update').setDisabled(!valid); + } + me.isValid = valid; + }, + + afterRender: function() { + var me = this, + plugin = me.editingPlugin; + + me.callParent(arguments); + me.mon(me.renderTo, 'scroll', me.onCtScroll, me, { buffer: 100 }); + + + me.mon(me.el, { + click: Ext.emptyFn, + stopPropagation: true + }); + + me.el.swallowEvent([ + 'keypress', + 'keydown' + ]); + + me.keyNav = new Ext.util.KeyNav(me.el, { + enter: plugin.completeEdit, + esc: plugin.onEscKey, + scope: plugin + }); + + me.mon(plugin.view, { + beforerefresh: me.onBeforeViewRefresh, + refresh: me.onViewRefresh, + scope: me + }); + }, + + onBeforeViewRefresh: function(view) { + var me = this, + viewDom = view.el.dom; + + if (me.el.dom.parentNode === viewDom) { + viewDom.removeChild(me.el.dom); + } + }, + + onViewRefresh: function(view) { + var me = this, + viewDom = view.el.dom, + context = me.context, + idx; + + viewDom.appendChild(me.el.dom); + + + if (context && (idx = context.store.indexOf(context.record)) >= 0) { + context.row = view.getNode(idx); + me.reposition(); + if (me.tooltip && me.tooltip.isVisible()) { + me.tooltip.setTarget(context.row); + } + } else { + me.editingPlugin.cancelEdit(); + } + }, + + onCtScroll: function(e, target) { + var me = this, + scrollTop = target.scrollTop, + scrollLeft = target.scrollLeft; + + if (scrollTop !== me.lastScrollTop) { + me.lastScrollTop = scrollTop; + if ((me.tooltip && me.tooltip.isVisible()) || me.hiddenTip) { + me.repositionTip(); + } + } + if (scrollLeft !== me.lastScrollLeft) { + me.lastScrollLeft = scrollLeft; + me.reposition(); + } + }, + + onColumnAdd: function(column) { + if (!column.isGroupHeader) { + this.setField(column); + } + }, + + onColumnRemove: function(column) { + this.columns.remove(column); + }, + + onColumnResize: function(column, width) { + if (!column.isGroupHeader) { + column.getEditor().setWidth(width - 2); + if (this.isVisible()) { + this.reposition(); + } + } + }, + + onColumnHide: function(column) { + if (!column.isGroupHeader) { + column.getEditor().hide(); + if (this.isVisible()) { + this.reposition(); + } + } + }, + + onColumnShow: function(column) { + var field = column.getEditor(); + field.setWidth(column.getWidth() - 2).show(); + if (this.isVisible()) { + this.reposition(); + } + }, + + onColumnMove: function(column, fromIdx, toIdx) { + if (!column.isGroupHeader) { + var field = column.getEditor(); + if (this.items.indexOf(field) != toIdx) { + this.move(fromIdx, toIdx); + } + } + }, + + onFieldAdd: function(map, fieldId, column) { + var me = this, + colIdx, + field; + + if (!column.isGroupHeader) { + colIdx = me.editingPlugin.grid.headerCt.getHeaderIndex(column); + field = column.getEditor({ xtype: 'displayfield' }); + me.insert(colIdx, field); + } + }, + + onFieldRemove: function(map, fieldId, column) { + var me = this, + field, + fieldEl; + + if (!column.isGroupHeader) { + field = column.getEditor(); + fieldEl = field.el; + me.remove(field, false); + if (fieldEl) { + fieldEl.remove(); + } + } + }, + + onFieldReplace: function(map, fieldId, column, oldColumn) { + this.onFieldRemove(map, fieldId, oldColumn); + }, + + clearFields: function() { + var map = this.columns, + key; + + for (key in map) { + if (map.hasOwnProperty(key)) { + map.removeAtKey(key); + } + } + }, + + getFloatingButtons: function() { + var me = this, + cssPrefix = Ext.baseCSSPrefix, + btnsCss = cssPrefix + 'grid-row-editor-buttons', + plugin = me.editingPlugin, + btns; + + if (!me.floatingButtons) { + btns = me.floatingButtons = new Ext.Container({ + renderTpl: [ + '
', + '
', + '
', + '
', + '
', + '{%this.renderContainer(out,values)%}' + ], + width: 200, + renderTo: me.el, + baseCls: btnsCss, + layout: { + type: 'hbox', + align: 'middle' + }, + defaults: { + flex: 1, + margins: '0 1 0 1' + }, + items: [{ + itemId: 'update', + xtype: 'button', + handler: plugin.completeEdit, + scope: plugin, + text: me.saveBtnText, + disabled: !me.isValid, + minWidth: Ext.panel.Panel.prototype.minButtonWidth + }, { + xtype: 'button', + handler: plugin.cancelEdit, + scope: plugin, + text: me.cancelBtnText, + minWidth: Ext.panel.Panel.prototype.minButtonWidth + }] + }); + + + me.mon(btns.el, { + + + mousedown: Ext.emptyFn, + click: Ext.emptyFn, + stopEvent: true + }); + } + return me.floatingButtons; + }, + + reposition: function(animateConfig) { + var me = this, + context = me.context, + row = context && Ext.get(context.row), + btns = me.getFloatingButtons(), + btnEl = btns.el, + grid = me.editingPlugin.grid, + viewEl = grid.view.el, + + + + mainBodyWidth = grid.headerCt.getFullWidth(), + scrollerWidth = grid.getWidth(), + + + + width = Math.min(mainBodyWidth, scrollerWidth), + scrollLeft = grid.view.el.dom.scrollLeft, + btnWidth = btns.getWidth(), + left = (width - btnWidth) / 2 + scrollLeft, + y, rowH, newHeight, + + invalidateScroller = function() { + btnEl.scrollIntoView(viewEl, false); + if (animateConfig && animateConfig.callback) { + animateConfig.callback.call(animateConfig.scope || me); + } + }, + + animObj; + + + if (row && Ext.isElement(row.dom)) { + + + row.scrollIntoView(viewEl, false); + + + + + y = row.getXY()[1] - 5; + rowH = row.getHeight(); + newHeight = rowH + (me.editingPlugin.grid.rowLines ? 9 : 10); + + + if (me.getHeight() != newHeight) { + me.setHeight(newHeight); + me.el.setLeft(0); + } + + if (animateConfig) { + animObj = { + to: { + y: y + }, + duration: animateConfig.duration || 125, + listeners: { + afteranimate: function() { + invalidateScroller(); + y = row.getXY()[1] - 5; + } + } + }; + me.el.animate(animObj); + } else { + me.el.setY(y); + invalidateScroller(); + } + } + if (me.getWidth() != mainBodyWidth) { + me.setWidth(mainBodyWidth); + } + btnEl.setLeft(left); + }, + + getEditor: function(fieldInfo) { + var me = this; + + if (Ext.isNumber(fieldInfo)) { + + + + return me.query('>[isFormField]')[fieldInfo]; + } else if (fieldInfo.isHeader && !fieldInfo.isGroupHeader) { + return fieldInfo.getEditor(); + } + }, + + removeField: function(field) { + var me = this; + + + field = me.getEditor(field); + me.mun(field, 'validitychange', me.onValidityChange, me); + + + + me.columns.removeAtKey(field.id); + Ext.destroy(field); + }, + + setField: function(column) { + var me = this, + i, + length, field; + + if (Ext.isArray(column)) { + length = column.length; + + for (i = 0; i < length; i++) { + me.setField(column[i]); + } + + return; + } + + + field = column.getEditor(null, { + xtype: 'displayfield', + + + getModelData: function() { + return null; + } + }); + field.margins = '0 0 0 2'; + me.mon(field, 'change', me.onFieldChange, me); + + if (me.isVisible() && me.context) { + if (field.is('displayfield')) { + me.renderColumnData(field, me.context.record, column); + } else { + field.suspendEvents(); + field.setValue(me.context.record.get(column.dataIndex)); + field.resumeEvents(); + } + } + + + + + me.columns.add(field.id, column); + if (column.hidden) { + me.onColumnHide(column); + } else if (column.rendered) { + + me.onColumnShow(column); + } + }, + + loadRecord: function(record) { + var me = this, + form = me.getForm(), + fields = form.getFields(), + items = fields.items, + length = items.length, + i, displayFields; + + + for (i = 0; i < length; i++) { + items[i].suspendEvents(); + } + + form.loadRecord(record); + + for (i = 0; i < length; i++) { + items[i].resumeEvents(); + } + + if (me.errorSummary) { + if (form.isValid()) { + me.hideToolTip(); + } else { + me.showToolTip(); + } + } + + + displayFields = me.query('>displayfield'); + length = displayFields.length; + + for (i = 0; i < length; i++) { + me.renderColumnData(displayFields[i], record); + } + }, + + renderColumnData: function(field, record, activeColumn) { + var me = this, + grid = me.editingPlugin.grid, + headerCt = grid.headerCt, + view = grid.view, + store = view.store, + column = activeColumn || me.columns.get(field.id), + value = record.get(column.dataIndex), + renderer = column.editRenderer || column.renderer, + metaData, + rowIdx, + colIdx; + + + if (renderer) { + metaData = { tdCls: '', style: '' }; + rowIdx = store.indexOf(record); + colIdx = headerCt.getHeaderIndex(column); + + value = renderer.call( + column.scope || headerCt.ownerCt, + value, + metaData, + record, + rowIdx, + colIdx, + store, + view + ); + } + + field.setRawValue(value); + field.resetOriginalValue(); + }, + + beforeEdit: function() { + var me = this; + + if (me.isVisible() && me.errorSummary && !me.autoCancel && me.isDirty()) { + me.showToolTip(); + return false; + } + }, + + + startEdit: function(record, columnHeader) { + var me = this, + grid = me.editingPlugin.grid, + store = grid.store, + context = me.context = Ext.apply(me.editingPlugin.context, { + view: grid.getView(), + store: store + }); + + + context.grid.getSelectionModel().select(record); + + + me.loadRecord(record); + + if (!me.isVisible()) { + me.show(); + me.focusContextCell(); + } else { + me.reposition({ + callback: this.focusContextCell + }); + } + }, + + + focusContextCell: function() { + var field = this.getEditor(this.context.colIdx); + if (field && field.focus) { + field.focus(); + } + }, + + cancelEdit: function() { + var me = this, + form = me.getForm(), + fields = form.getFields(), + items = fields.items, + length = items.length, + i; + + me.hide(); + form.clearInvalid(); + + + for (i = 0; i < length; i++) { + items[i].suspendEvents(); + } + + form.reset(); + + for (i = 0; i < length; i++) { + items[i].resumeEvents(); + } + }, + + completeEdit: function() { + var me = this, + form = me.getForm(); + + if (!form.isValid()) { + return; + } + + form.updateRecord(me.context.record); + me.hide(); + return true; + }, + + onShow: function() { + this.callParent(arguments); + this.reposition(); + }, + + onHide: function() { + var me = this; + me.callParent(arguments); + if (me.tooltip) { + me.hideToolTip(); + } + if (me.context) { + me.context.view.focus(); + me.context = null; + } + }, + + isDirty: function() { + var me = this, + form = me.getForm(); + return form.isDirty(); + }, + + getToolTip: function() { + return this.tooltip || (this.tooltip = new Ext.tip.ToolTip({ + cls: Ext.baseCSSPrefix + 'grid-row-editor-errors', + title: this.errorsText, + autoHide: false, + closable: true, + closeAction: 'disable', + anchor: 'left' + })); + }, + + hideToolTip: function() { + var me = this, + tip = me.getToolTip(); + if (tip.rendered) { + tip.disable(); + } + me.hiddenTip = false; + }, + + showToolTip: function() { + var me = this, + tip = me.getToolTip(), + context = me.context, + row = Ext.get(context.row), + viewEl = context.grid.view.el; + + tip.setTarget(row); + tip.showAt([-10000, -10000]); + tip.update(me.getErrors()); + tip.mouseOffset = [viewEl.getWidth() - row.getWidth() + me.lastScrollLeft + 15, 0]; + me.repositionTip(); + tip.doLayout(); + tip.enable(); + }, + + repositionTip: function() { + var me = this, + tip = me.getToolTip(), + context = me.context, + row = Ext.get(context.row), + viewEl = context.grid.view.el, + viewHeight = viewEl.getHeight(), + viewTop = me.lastScrollTop, + viewBottom = viewTop + viewHeight, + rowHeight = row.getHeight(), + rowTop = row.dom.offsetTop, + rowBottom = rowTop + rowHeight; + + if (rowBottom > viewTop && rowTop < viewBottom) { + tip.show(); + me.hiddenTip = false; + } else { + tip.hide(); + me.hiddenTip = true; + } + }, + + getErrors: function() { + var me = this, + dirtyText = !me.autoCancel && me.isDirty() ? me.dirtyText + '
' : '', + errors = [], + fields = me.query('>[isFormField]'), + length = fields.length, + i; + + function createListItem(e) { + return '
  • ' + e + '
  • '; + } + + for (i = 0; i < length; i++) { + errors = errors.concat( + Ext.Array.map(fields[i].getErrors(), createListItem) + ); + } + + return dirtyText + '
      ' + errors.join('') + '
    '; + }, + + beforeDestroy: function(){ + Ext.destroy(this.floatingButtons, this.tooltip); + this.callParent(); + } +}); + +Ext.define('Ext.grid.plugin.RowEditing', { + extend: 'Ext.grid.plugin.Editing', + alias: 'plugin.rowediting', + + requires: [ + 'Ext.grid.RowEditor' + ], + + editStyle: 'row', + + + autoCancel: true, + + + + + errorSummary: true, + + constructor: function() { + var me = this; + + me.callParent(arguments); + + if (!me.clicksToMoveEditor) { + me.clicksToMoveEditor = me.clicksToEdit; + } + + me.autoCancel = !!me.autoCancel; + }, + + init: function(grid) { + this.callParent([grid]); + }, + + + destroy: function() { + var me = this; + Ext.destroy(me.editor); + me.callParent(arguments); + }, + + + startEdit: function(record, columnHeader) { + var me = this, + editor = me.getEditor(); + + if ((me.callParent(arguments) !== false) && (editor.beforeEdit() !== false)) { + editor.startEdit(me.context.record, me.context.column); + return true; + } + return false; + }, + + + cancelEdit: function() { + var me = this; + + if (me.editing) { + me.getEditor().cancelEdit(); + me.callParent(arguments); + } + }, + + + completeEdit: function() { + var me = this; + + if (me.editing && me.validateEdit()) { + me.editing = false; + me.fireEvent('edit', me, me.context); + } + }, + + + validateEdit: function() { + var me = this, + editor = me.editor, + context = me.context, + record = context.record, + newValues = {}, + originalValues = {}, + editors = editor.items.items, + e, + eLen = editors.length, + name, item; + + for (e = 0; e < eLen; e++) { + item = editors[e]; + name = item.name; + + newValues[name] = item.getValue(); + originalValues[name] = record.get(name); + } + + Ext.apply(context, { + newValues : newValues, + originalValues : originalValues + }); + + return me.callParent(arguments) && me.getEditor().completeEdit(); + }, + + + getEditor: function() { + var me = this; + + if (!me.editor) { + me.editor = me.initEditor(); + } + return me.editor; + }, + + + initEditor: function() { + var me = this, + grid = me.grid, + view = me.view, + headerCt = grid.headerCt, + btns = ['saveBtnText', 'cancelBtnText', 'errorsText', 'dirtyText'], + b, + bLen = btns.length, + cfg = { + autoCancel: me.autoCancel, + errorSummary: me.errorSummary, + fields: headerCt.getGridColumns(), + hidden: true, + + + editingPlugin: me, + renderTo: view.el + }, + item; + + for (b = 0; b < bLen; b++) { + item = btns[b]; + + if (Ext.isDefined(me[item])) { + cfg[item] = me[item]; + } + } + + return Ext.create('Ext.grid.RowEditor', cfg); + }, + + + initEditTriggers: function() { + var me = this, + moveEditorEvent = me.clicksToMoveEditor === 1 ? 'click' : 'dblclick'; + + me.callParent(arguments); + + if (me.clicksToMoveEditor !== me.clicksToEdit) { + me.mon(me.view, 'cell' + moveEditorEvent, me.moveEditorByClick, me); + } + }, + + addHeaderEvents: function(){ + var me = this; + me.callParent(); + + me.mon(me.grid.headerCt, { + scope: me, + columnresize: me.onColumnResize, + columnhide: me.onColumnHide, + columnshow: me.onColumnShow, + columnmove: me.onColumnMove + }); + }, + + startEditByClick: function() { + var me = this; + if (!me.editing || me.clicksToMoveEditor === me.clicksToEdit) { + me.callParent(arguments); + } + }, + + moveEditorByClick: function() { + var me = this; + if (me.editing) { + me.superclass.onCellClick.apply(me, arguments); + } + }, + + + onColumnAdd: function(ct, column) { + if (column.isHeader) { + var me = this, + editor; + + me.initFieldAccessors(column); + + + + editor = me.editor; + if (editor && editor.onColumnAdd) { + editor.onColumnAdd(column); + } + } + }, + + + onColumnRemove: function(ct, column) { + if (column.isHeader) { + var me = this, + editor = me.getEditor(); + + if (editor && editor.onColumnRemove) { + editor.onColumnRemove(column); + } + me.removeFieldAccessors(column); + } + }, + + + onColumnResize: function(ct, column, width) { + if (column.isHeader) { + var me = this, + editor = me.getEditor(); + + if (editor && editor.onColumnResize) { + editor.onColumnResize(column, width); + } + } + }, + + + onColumnHide: function(ct, column) { + + var me = this, + editor = me.getEditor(); + + if (editor && editor.onColumnHide) { + editor.onColumnHide(column); + } + }, + + + onColumnShow: function(ct, column) { + + var me = this, + editor = me.getEditor(); + + if (editor && editor.onColumnShow) { + editor.onColumnShow(column); + } + }, + + + onColumnMove: function(ct, column, fromIdx, toIdx) { + + var me = this, + editor = me.getEditor(); + + if (editor && editor.onColumnMove) { + editor.onColumnMove(column, fromIdx, toIdx); + } + }, + + + setColumnField: function(column, field) { + var me = this, + editor = me.getEditor(); + + editor.removeField(column); + me.callParent(arguments); + me.getEditor().setField(column); + } +}); + + + + +Ext._endTime = new Date().getTime(); +if (Ext._beforereadyhandler){ + Ext._beforereadyhandler(); +} diff --git a/test/testcase/ext-all-dev.js b/test/testcase/ext-all-dev.js new file mode 100644 index 0000000..debb033 --- /dev/null +++ b/test/testcase/ext-all-dev.js @@ -0,0 +1,157403 @@ +/* +This file is part of Ext JS 4.1 + +Copyright (c) 2011-2012 Sencha Inc + +Contact: http://www.sencha.com/contact + +GNU General Public License Usage +This file may be used under the terms of the GNU General Public License version 3.0 as +published by the Free Software Foundation and appearing in the file LICENSE included in the +packaging of this file. + +Please review the following information to ensure the GNU General Public License version 3.0 +requirements will be met: http://www.gnu.org/copyleft/gpl.html. + +If you are unsure which license is appropriate for your use, please contact the sales department +at http://www.sencha.com/contact. + +Build date: 2012-04-20 14:10:47 (19f55ab932145a3443b228045fa80950dfeaf9cc) +*/ +/** + * @class Ext + * @singleton + */ +var Ext = Ext || {}; +Ext._startTime = new Date().getTime(); +(function() { + var global = this, + objectPrototype = Object.prototype, + toString = objectPrototype.toString, + enumerables = true, + enumerablesTest = { toString: 1 }, + emptyFn = function () {}, + // This is the "$previous" method of a hook function on an instance. When called, it + // calls through the class prototype by the name of the called method. + callOverrideParent = function () { + var method = callOverrideParent.caller.caller; // skip callParent (our caller) + return method.$owner.prototype[method.$name].apply(this, arguments); + }, + i; + + Ext.global = global; + + for (i in enumerablesTest) { + enumerables = null; + } + + if (enumerables) { + enumerables = ['hasOwnProperty', 'valueOf', 'isPrototypeOf', 'propertyIsEnumerable', + 'toLocaleString', 'toString', 'constructor']; + } + + /** + * An array containing extra enumerables for old browsers + * @property {String[]} + */ + Ext.enumerables = enumerables; + + /** + * Copies all the properties of config to the specified object. + * Note that if recursive merging and cloning without referencing the original objects / arrays is needed, use + * {@link Ext.Object#merge} instead. + * @param {Object} object The receiver of the properties + * @param {Object} config The source of the properties + * @param {Object} [defaults] A different object that will also be applied for default values + * @return {Object} returns obj + */ + Ext.apply = function(object, config, defaults) { + if (defaults) { + Ext.apply(object, defaults); + } + + if (object && config && typeof config === 'object') { + var i, j, k; + + for (i in config) { + object[i] = config[i]; + } + + if (enumerables) { + for (j = enumerables.length; j--;) { + k = enumerables[j]; + if (config.hasOwnProperty(k)) { + object[k] = config[k]; + } + } + } + } + + return object; + }; + + Ext.buildSettings = Ext.apply({ + baseCSSPrefix: 'x-', + scopeResetCSS: false + }, Ext.buildSettings || {}); + + Ext.apply(Ext, { + + /** + * @property {String} [name='Ext'] + *

    The name of the property in the global namespace (The window in browser environments) which refers to the current instance of Ext.

    + *

    This is usually "Ext", but if a sandboxed build of ExtJS is being used, this will be an alternative name.

    + *

    If code is being generated for use by eval or to create a new Function, and the global instance + * of Ext must be referenced, this is the name that should be built into the code.

    + */ + name: Ext.sandboxName || 'Ext', + + /** + * A reusable empty function + */ + emptyFn: emptyFn, + + /** + * A zero length string which will pass a truth test. Useful for passing to methods + * which use a truth test to reject falsy values where a string value must be cleared. + */ + emptyString: new String(), + + baseCSSPrefix: Ext.buildSettings.baseCSSPrefix, + + /** + * Copies all the properties of config to object if they don't already exist. + * @param {Object} object The receiver of the properties + * @param {Object} config The source of the properties + * @return {Object} returns obj + */ + applyIf: function(object, config) { + var property; + + if (object) { + for (property in config) { + if (object[property] === undefined) { + object[property] = config[property]; + } + } + } + + return object; + }, + + /** + * Iterates either an array or an object. This method delegates to + * {@link Ext.Array#each Ext.Array.each} if the given value is iterable, and {@link Ext.Object#each Ext.Object.each} otherwise. + * + * @param {Object/Array} object The object or array to be iterated. + * @param {Function} fn The function to be called for each iteration. See and {@link Ext.Array#each Ext.Array.each} and + * {@link Ext.Object#each Ext.Object.each} for detailed lists of arguments passed to this function depending on the given object + * type that is being iterated. + * @param {Object} scope (Optional) The scope (`this` reference) in which the specified function is executed. + * Defaults to the object being iterated itself. + * @markdown + */ + iterate: function(object, fn, scope) { + if (Ext.isEmpty(object)) { + return; + } + + if (scope === undefined) { + scope = object; + } + + if (Ext.isIterable(object)) { + Ext.Array.each.call(Ext.Array, object, fn, scope); + } + else { + Ext.Object.each.call(Ext.Object, object, fn, scope); + } + } + }); + + Ext.apply(Ext, { + + /** + * This method deprecated. Use {@link Ext#define Ext.define} instead. + * @method + * @param {Function} superclass + * @param {Object} overrides + * @return {Function} The subclass constructor from the overrides parameter, or a generated one if not provided. + * @deprecated 4.0.0 Use {@link Ext#define Ext.define} instead + */ + extend: (function() { + // inline overrides + var objectConstructor = objectPrototype.constructor, + inlineOverrides = function(o) { + for (var m in o) { + if (!o.hasOwnProperty(m)) { + continue; + } + this[m] = o[m]; + } + }; + + return function(subclass, superclass, overrides) { + // First we check if the user passed in just the superClass with overrides + if (Ext.isObject(superclass)) { + overrides = superclass; + superclass = subclass; + subclass = overrides.constructor !== objectConstructor ? overrides.constructor : function() { + superclass.apply(this, arguments); + }; + } + + if (!superclass) { + Ext.Error.raise({ + sourceClass: 'Ext', + sourceMethod: 'extend', + msg: 'Attempting to extend from a class which has not been loaded on the page.' + }); + } + + // We create a new temporary class + var F = function() {}, + subclassProto, superclassProto = superclass.prototype; + + F.prototype = superclassProto; + subclassProto = subclass.prototype = new F(); + subclassProto.constructor = subclass; + subclass.superclass = superclassProto; + + if (superclassProto.constructor === objectConstructor) { + superclassProto.constructor = superclass; + } + + subclass.override = function(overrides) { + Ext.override(subclass, overrides); + }; + + subclassProto.override = inlineOverrides; + subclassProto.proto = subclassProto; + + subclass.override(overrides); + subclass.extend = function(o) { + return Ext.extend(subclass, o); + }; + + return subclass; + }; + }()), + + /** + * Overrides members of the specified `target` with the given values. + * + * If the `target` is a class declared using {@link Ext#define Ext.define}, the + * `override` method of that class is called (see {@link Ext.Base#override}) given + * the `overrides`. + * + * If the `target` is a function, it is assumed to be a constructor and the contents + * of `overrides` are applied to its `prototype` using {@link Ext#apply Ext.apply}. + * + * If the `target` is an instance of a class declared using {@link Ext#define Ext.define}, + * the `overrides` are applied to only that instance. In this case, methods are + * specially processed to allow them to use {@link Ext.Base#callParent}. + * + * var panel = new Ext.Panel({ ... }); + * + * Ext.override(panel, { + * initComponent: function () { + * // extra processing... + * + * this.callParent(); + * } + * }); + * + * If the `target` is none of these, the `overrides` are applied to the `target` + * using {@link Ext#apply Ext.apply}. + * + * Please refer to {@link Ext#define Ext.define} and {@link Ext.Base#override} for + * further details. + * + * @param {Object} target The target to override. + * @param {Object} overrides The properties to add or replace on `target`. + * @method override + */ + override: function (target, overrides) { + if (target.$isClass) { + target.override(overrides); + } else if (typeof target == 'function') { + Ext.apply(target.prototype, overrides); + } else { + var owner = target.self, + name, value; + + if (owner && owner.$isClass) { // if (instance of Ext.define'd class) + for (name in overrides) { + if (overrides.hasOwnProperty(name)) { + value = overrides[name]; + + if (typeof value == 'function') { + if (owner.$className) { + value.displayName = owner.$className + '#' + name; + } + + value.$name = name; + value.$owner = owner; + value.$previous = target.hasOwnProperty(name) + ? target[name] // already hooked, so call previous hook + : callOverrideParent; // calls by name on prototype + } + + target[name] = value; + } + } + } else { + Ext.apply(target, overrides); + } + } + + return target; + } + }); + + // A full set of static methods to do type checking + Ext.apply(Ext, { + + /** + * Returns the given value itself if it's not empty, as described in {@link Ext#isEmpty}; returns the default + * value (second argument) otherwise. + * + * @param {Object} value The value to test + * @param {Object} defaultValue The value to return if the original value is empty + * @param {Boolean} allowBlank (optional) true to allow zero length strings to qualify as non-empty (defaults to false) + * @return {Object} value, if non-empty, else defaultValue + */ + valueFrom: function(value, defaultValue, allowBlank){ + return Ext.isEmpty(value, allowBlank) ? defaultValue : value; + }, + + /** + * Returns the type of the given variable in string format. List of possible values are: + * + * - `undefined`: If the given value is `undefined` + * - `null`: If the given value is `null` + * - `string`: If the given value is a string + * - `number`: If the given value is a number + * - `boolean`: If the given value is a boolean value + * - `date`: If the given value is a `Date` object + * - `function`: If the given value is a function reference + * - `object`: If the given value is an object + * - `array`: If the given value is an array + * - `regexp`: If the given value is a regular expression + * - `element`: If the given value is a DOM Element + * - `textnode`: If the given value is a DOM text node and contains something other than whitespace + * - `whitespace`: If the given value is a DOM text node and contains only whitespace + * + * @param {Object} value + * @return {String} + * @markdown + */ + typeOf: function(value) { + var type, + typeToString; + + if (value === null) { + return 'null'; + } + + type = typeof value; + + if (type === 'undefined' || type === 'string' || type === 'number' || type === 'boolean') { + return type; + } + + typeToString = toString.call(value); + + switch(typeToString) { + case '[object Array]': + return 'array'; + case '[object Date]': + return 'date'; + case '[object Boolean]': + return 'boolean'; + case '[object Number]': + return 'number'; + case '[object RegExp]': + return 'regexp'; + } + + if (type === 'function') { + return 'function'; + } + + if (type === 'object') { + if (value.nodeType !== undefined) { + if (value.nodeType === 3) { + return (/\S/).test(value.nodeValue) ? 'textnode' : 'whitespace'; + } + else { + return 'element'; + } + } + + return 'object'; + } + + Ext.Error.raise({ + sourceClass: 'Ext', + sourceMethod: 'typeOf', + msg: 'Failed to determine the type of the specified value "' + value + '". This is most likely a bug.' + }); + }, + + /** + * Returns true if the passed value is empty, false otherwise. The value is deemed to be empty if it is either: + * + * - `null` + * - `undefined` + * - a zero-length array + * - a zero-length string (Unless the `allowEmptyString` parameter is set to `true`) + * + * @param {Object} value The value to test + * @param {Boolean} allowEmptyString (optional) true to allow empty strings (defaults to false) + * @return {Boolean} + * @markdown + */ + isEmpty: function(value, allowEmptyString) { + return (value === null) || (value === undefined) || (!allowEmptyString ? value === '' : false) || (Ext.isArray(value) && value.length === 0); + }, + + /** + * Returns true if the passed value is a JavaScript Array, false otherwise. + * + * @param {Object} target The target to test + * @return {Boolean} + * @method + */ + isArray: ('isArray' in Array) ? Array.isArray : function(value) { + return toString.call(value) === '[object Array]'; + }, + + /** + * Returns true if the passed value is a JavaScript Date object, false otherwise. + * @param {Object} object The object to test + * @return {Boolean} + */ + isDate: function(value) { + return toString.call(value) === '[object Date]'; + }, + + /** + * Returns true if the passed value is a JavaScript Object, false otherwise. + * @param {Object} value The value to test + * @return {Boolean} + * @method + */ + isObject: (toString.call(null) === '[object Object]') ? + function(value) { + // check ownerDocument here as well to exclude DOM nodes + return value !== null && value !== undefined && toString.call(value) === '[object Object]' && value.ownerDocument === undefined; + } : + function(value) { + return toString.call(value) === '[object Object]'; + }, + + /** + * @private + */ + isSimpleObject: function(value) { + return value instanceof Object && value.constructor === Object; + }, + /** + * Returns true if the passed value is a JavaScript 'primitive', a string, number or boolean. + * @param {Object} value The value to test + * @return {Boolean} + */ + isPrimitive: function(value) { + var type = typeof value; + + return type === 'string' || type === 'number' || type === 'boolean'; + }, + + /** + * Returns true if the passed value is a JavaScript Function, false otherwise. + * @param {Object} value The value to test + * @return {Boolean} + * @method + */ + isFunction: + // Safari 3.x and 4.x returns 'function' for typeof , hence we need to fall back to using + // Object.prototype.toString (slower) + (typeof document !== 'undefined' && typeof document.getElementsByTagName('body') === 'function') ? function(value) { + return toString.call(value) === '[object Function]'; + } : function(value) { + return typeof value === 'function'; + }, + + /** + * Returns true if the passed value is a number. Returns false for non-finite numbers. + * @param {Object} value The value to test + * @return {Boolean} + */ + isNumber: function(value) { + return typeof value === 'number' && isFinite(value); + }, + + /** + * Validates that a value is numeric. + * @param {Object} value Examples: 1, '1', '2.34' + * @return {Boolean} True if numeric, false otherwise + */ + isNumeric: function(value) { + return !isNaN(parseFloat(value)) && isFinite(value); + }, + + /** + * Returns true if the passed value is a string. + * @param {Object} value The value to test + * @return {Boolean} + */ + isString: function(value) { + return typeof value === 'string'; + }, + + /** + * Returns true if the passed value is a boolean. + * + * @param {Object} value The value to test + * @return {Boolean} + */ + isBoolean: function(value) { + return typeof value === 'boolean'; + }, + + /** + * Returns true if the passed value is an HTMLElement + * @param {Object} value The value to test + * @return {Boolean} + */ + isElement: function(value) { + return value ? value.nodeType === 1 : false; + }, + + /** + * Returns true if the passed value is a TextNode + * @param {Object} value The value to test + * @return {Boolean} + */ + isTextNode: function(value) { + return value ? value.nodeName === "#text" : false; + }, + + /** + * Returns true if the passed value is defined. + * @param {Object} value The value to test + * @return {Boolean} + */ + isDefined: function(value) { + return typeof value !== 'undefined'; + }, + + /** + * Returns true if the passed value is iterable, false otherwise + * @param {Object} value The value to test + * @return {Boolean} + */ + isIterable: function(value) { + var type = typeof value, + checkLength = false; + if (value && type != 'string') { + // Functions have a length property, so we need to filter them out + if (type == 'function') { + // In Safari, NodeList/HTMLCollection both return "function" when using typeof, so we need + // to explicitly check them here. + if (Ext.isSafari) { + checkLength = value instanceof NodeList || value instanceof HTMLCollection; + } + } else { + checkLength = true; + } + } + return checkLength ? value.length !== undefined : false; + } + }); + + Ext.apply(Ext, { + + /** + * Clone simple variables including array, {}-like objects, DOM nodes and Date without keeping the old reference. + * A reference for the object itself is returned if it's not a direct decendant of Object. For model cloning, + * see {@link Model#copy Model.copy}. + * + * @param {Object} item The variable to clone + * @return {Object} clone + */ + clone: function(item) { + var type, + i, + j, + k, + clone, + key; + + if (item === null || item === undefined) { + return item; + } + + // DOM nodes + // TODO proxy this to Ext.Element.clone to handle automatic id attribute changing + // recursively + if (item.nodeType && item.cloneNode) { + return item.cloneNode(true); + } + + type = toString.call(item); + + // Date + if (type === '[object Date]') { + return new Date(item.getTime()); + } + + + // Array + if (type === '[object Array]') { + i = item.length; + + clone = []; + + while (i--) { + clone[i] = Ext.clone(item[i]); + } + } + // Object + else if (type === '[object Object]' && item.constructor === Object) { + clone = {}; + + for (key in item) { + clone[key] = Ext.clone(item[key]); + } + + if (enumerables) { + for (j = enumerables.length; j--;) { + k = enumerables[j]; + clone[k] = item[k]; + } + } + } + + return clone || item; + }, + + /** + * @private + * Generate a unique reference of Ext in the global scope, useful for sandboxing + */ + getUniqueGlobalNamespace: function() { + var uniqueGlobalNamespace = this.uniqueGlobalNamespace, + i; + + if (uniqueGlobalNamespace === undefined) { + i = 0; + + do { + uniqueGlobalNamespace = 'ExtBox' + (++i); + } while (Ext.global[uniqueGlobalNamespace] !== undefined); + + Ext.global[uniqueGlobalNamespace] = Ext; + this.uniqueGlobalNamespace = uniqueGlobalNamespace; + } + + return uniqueGlobalNamespace; + }, + + /** + * @private + */ + functionFactoryCache: {}, + + cacheableFunctionFactory: function() { + var me = this, + args = Array.prototype.slice.call(arguments), + cache = me.functionFactoryCache, + idx, fn, ln; + + if (Ext.isSandboxed) { + ln = args.length; + if (ln > 0) { + ln--; + args[ln] = 'var Ext=window.' + Ext.name + ';' + args[ln]; + } + } + idx = args.join(''); + fn = cache[idx]; + if (!fn) { + fn = Function.prototype.constructor.apply(Function.prototype, args); + + cache[idx] = fn; + } + return fn; + }, + + functionFactory: function() { + var me = this, + args = Array.prototype.slice.call(arguments), + ln; + + if (Ext.isSandboxed) { + ln = args.length; + if (ln > 0) { + ln--; + args[ln] = 'var Ext=window.' + Ext.name + ';' + args[ln]; + } + } + + return Function.prototype.constructor.apply(Function.prototype, args); + }, + + /** + * @private + * @property + */ + Logger: { + verbose: emptyFn, + log: emptyFn, + info: emptyFn, + warn: emptyFn, + error: function(message) { + throw new Error(message); + }, + deprecate: emptyFn + } + }); + + /** + * Old alias to {@link Ext#typeOf} + * @deprecated 4.0.0 Use {@link Ext#typeOf} instead + * @method + * @inheritdoc Ext#typeOf + */ + Ext.type = Ext.typeOf; + +}()); + +/* + * This method evaluates the given code free of any local variable. In some browsers this + * will be at global scope, in others it will be in a function. + * @parma {String} code The code to evaluate. + * @private + * @method + */ +Ext.globalEval = Ext.global.execScript + ? function(code) { + execScript(code); + } + : function($$code) { + // IMPORTANT: because we use eval we cannot place this in the above function or it + // will break the compressor's ability to rename local variables... + (function(){ + eval($$code); + }()); + }; + +/** + * @author Jacky Nguyen + * @docauthor Jacky Nguyen + * @class Ext.Version + * + * A utility class that wrap around a string version number and provide convenient + * method to perform comparison. See also: {@link Ext.Version#compare compare}. Example: + + var version = new Ext.Version('1.0.2beta'); + console.log("Version is " + version); // Version is 1.0.2beta + + console.log(version.getMajor()); // 1 + console.log(version.getMinor()); // 0 + console.log(version.getPatch()); // 2 + console.log(version.getBuild()); // 0 + console.log(version.getRelease()); // beta + + console.log(version.isGreaterThan('1.0.1')); // True + console.log(version.isGreaterThan('1.0.2alpha')); // True + console.log(version.isGreaterThan('1.0.2RC')); // False + console.log(version.isGreaterThan('1.0.2')); // False + console.log(version.isLessThan('1.0.2')); // True + + console.log(version.match(1.0)); // True + console.log(version.match('1.0.2')); // True + + * @markdown + */ +(function() { + +// Current core version +var version = '4.1.0', Version; + Ext.Version = Version = Ext.extend(Object, { + + /** + * @param {String/Number} version The version number in the follow standard format: major[.minor[.patch[.build[release]]]] + * Examples: 1.0 or 1.2.3beta or 1.2.3.4RC + * @return {Ext.Version} this + */ + constructor: function(version) { + var parts, releaseStartIndex; + + if (version instanceof Version) { + return version; + } + + this.version = this.shortVersion = String(version).toLowerCase().replace(/_/g, '.').replace(/[\-+]/g, ''); + + releaseStartIndex = this.version.search(/([^\d\.])/); + + if (releaseStartIndex !== -1) { + this.release = this.version.substr(releaseStartIndex, version.length); + this.shortVersion = this.version.substr(0, releaseStartIndex); + } + + this.shortVersion = this.shortVersion.replace(/[^\d]/g, ''); + + parts = this.version.split('.'); + + this.major = parseInt(parts.shift() || 0, 10); + this.minor = parseInt(parts.shift() || 0, 10); + this.patch = parseInt(parts.shift() || 0, 10); + this.build = parseInt(parts.shift() || 0, 10); + + return this; + }, + + /** + * Override the native toString method + * @private + * @return {String} version + */ + toString: function() { + return this.version; + }, + + /** + * Override the native valueOf method + * @private + * @return {String} version + */ + valueOf: function() { + return this.version; + }, + + /** + * Returns the major component value + * @return {Number} major + */ + getMajor: function() { + return this.major || 0; + }, + + /** + * Returns the minor component value + * @return {Number} minor + */ + getMinor: function() { + return this.minor || 0; + }, + + /** + * Returns the patch component value + * @return {Number} patch + */ + getPatch: function() { + return this.patch || 0; + }, + + /** + * Returns the build component value + * @return {Number} build + */ + getBuild: function() { + return this.build || 0; + }, + + /** + * Returns the release component value + * @return {Number} release + */ + getRelease: function() { + return this.release || ''; + }, + + /** + * Returns whether this version if greater than the supplied argument + * @param {String/Number} target The version to compare with + * @return {Boolean} True if this version if greater than the target, false otherwise + */ + isGreaterThan: function(target) { + return Version.compare(this.version, target) === 1; + }, + + /** + * Returns whether this version if greater than or equal to the supplied argument + * @param {String/Number} target The version to compare with + * @return {Boolean} True if this version if greater than or equal to the target, false otherwise + */ + isGreaterThanOrEqual: function(target) { + return Version.compare(this.version, target) >= 0; + }, + + /** + * Returns whether this version if smaller than the supplied argument + * @param {String/Number} target The version to compare with + * @return {Boolean} True if this version if smaller than the target, false otherwise + */ + isLessThan: function(target) { + return Version.compare(this.version, target) === -1; + }, + + /** + * Returns whether this version if less than or equal to the supplied argument + * @param {String/Number} target The version to compare with + * @return {Boolean} True if this version if less than or equal to the target, false otherwise + */ + isLessThanOrEqual: function(target) { + return Version.compare(this.version, target) <= 0; + }, + + /** + * Returns whether this version equals to the supplied argument + * @param {String/Number} target The version to compare with + * @return {Boolean} True if this version equals to the target, false otherwise + */ + equals: function(target) { + return Version.compare(this.version, target) === 0; + }, + + /** + * Returns whether this version matches the supplied argument. Example: + *
    
    +         * var version = new Ext.Version('1.0.2beta');
    +         * console.log(version.match(1)); // True
    +         * console.log(version.match(1.0)); // True
    +         * console.log(version.match('1.0.2')); // True
    +         * console.log(version.match('1.0.2RC')); // False
    +         * 
    + * @param {String/Number} target The version to compare with + * @return {Boolean} True if this version matches the target, false otherwise + */ + match: function(target) { + target = String(target); + return this.version.substr(0, target.length) === target; + }, + + /** + * Returns this format: [major, minor, patch, build, release]. Useful for comparison + * @return {Number[]} + */ + toArray: function() { + return [this.getMajor(), this.getMinor(), this.getPatch(), this.getBuild(), this.getRelease()]; + }, + + /** + * Returns shortVersion version without dots and release + * @return {String} + */ + getShortVersion: function() { + return this.shortVersion; + }, + + /** + * Convenient alias to {@link Ext.Version#isGreaterThan isGreaterThan} + * @param {String/Number} target + * @return {Boolean} + */ + gt: function() { + return this.isGreaterThan.apply(this, arguments); + }, + + /** + * Convenient alias to {@link Ext.Version#isLessThan isLessThan} + * @param {String/Number} target + * @return {Boolean} + */ + lt: function() { + return this.isLessThan.apply(this, arguments); + }, + + /** + * Convenient alias to {@link Ext.Version#isGreaterThanOrEqual isGreaterThanOrEqual} + * @param {String/Number} target + * @return {Boolean} + */ + gtEq: function() { + return this.isGreaterThanOrEqual.apply(this, arguments); + }, + + /** + * Convenient alias to {@link Ext.Version#isLessThanOrEqual isLessThanOrEqual} + * @param {String/Number} target + * @return {Boolean} + */ + ltEq: function() { + return this.isLessThanOrEqual.apply(this, arguments); + } + }); + + Ext.apply(Version, { + // @private + releaseValueMap: { + 'dev': -6, + 'alpha': -5, + 'a': -5, + 'beta': -4, + 'b': -4, + 'rc': -3, + '#': -2, + 'p': -1, + 'pl': -1 + }, + + /** + * Converts a version component to a comparable value + * + * @static + * @param {Object} value The value to convert + * @return {Object} + */ + getComponentValue: function(value) { + return !value ? 0 : (isNaN(value) ? this.releaseValueMap[value] || value : parseInt(value, 10)); + }, + + /** + * Compare 2 specified versions, starting from left to right. If a part contains special version strings, + * they are handled in the following order: + * 'dev' < 'alpha' = 'a' < 'beta' = 'b' < 'RC' = 'rc' < '#' < 'pl' = 'p' < 'anything else' + * + * @static + * @param {String} current The current version to compare to + * @param {String} target The target version to compare to + * @return {Number} Returns -1 if the current version is smaller than the target version, 1 if greater, and 0 if they're equivalent + */ + compare: function(current, target) { + var currentValue, targetValue, i; + + current = new Version(current).toArray(); + target = new Version(target).toArray(); + + for (i = 0; i < Math.max(current.length, target.length); i++) { + currentValue = this.getComponentValue(current[i]); + targetValue = this.getComponentValue(target[i]); + + if (currentValue < targetValue) { + return -1; + } else if (currentValue > targetValue) { + return 1; + } + } + + return 0; + } + }); + + Ext.apply(Ext, { + /** + * @private + */ + versions: {}, + + /** + * @private + */ + lastRegisteredVersion: null, + + /** + * Set version number for the given package name. + * + * @param {String} packageName The package name, for example: 'core', 'touch', 'extjs' + * @param {String/Ext.Version} version The version, for example: '1.2.3alpha', '2.4.0-dev' + * @return {Ext} + */ + setVersion: function(packageName, version) { + Ext.versions[packageName] = new Version(version); + Ext.lastRegisteredVersion = Ext.versions[packageName]; + + return this; + }, + + /** + * Get the version number of the supplied package name; will return the last registered version + * (last Ext.setVersion call) if there's no package name given. + * + * @param {String} packageName (Optional) The package name, for example: 'core', 'touch', 'extjs' + * @return {Ext.Version} The version + */ + getVersion: function(packageName) { + if (packageName === undefined) { + return Ext.lastRegisteredVersion; + } + + return Ext.versions[packageName]; + }, + + /** + * Create a closure for deprecated code. + * + // This means Ext.oldMethod is only supported in 4.0.0beta and older. + // If Ext.getVersion('extjs') returns a version that is later than '4.0.0beta', for example '4.0.0RC', + // the closure will not be invoked + Ext.deprecate('extjs', '4.0.0beta', function() { + Ext.oldMethod = Ext.newMethod; + + ... + }); + + * @param {String} packageName The package name + * @param {String} since The last version before it's deprecated + * @param {Function} closure The callback function to be executed with the specified version is less than the current version + * @param {Object} scope The execution scope (this) if the closure + * @markdown + */ + deprecate: function(packageName, since, closure, scope) { + if (Version.compare(Ext.getVersion(packageName), since) < 1) { + closure.call(scope); + } + } + }); // End Versioning + + Ext.setVersion('core', version); + +}()); + +/** + * @class Ext.String + * + * A collection of useful static methods to deal with strings + * @singleton + */ + +Ext.String = (function() { + var trimRegex = /^[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+|[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+$/g, + escapeRe = /('|\\)/g, + formatRe = /\{(\d+)\}/g, + escapeRegexRe = /([-.*+?\^${}()|\[\]\/\\])/g, + basicTrimRe = /^\s+|\s+$/g, + whitespaceRe = /\s+/, + varReplace = /(^[^a-z]*|[^\w])/gi, + charToEntity, + entityToChar, + charToEntityRegex, + entityToCharRegex, + htmlEncodeReplaceFn = function(match, capture) { + return charToEntity[capture]; + }, + htmlDecodeReplaceFn = function(match, capture) { + return (capture in entityToChar) ? entityToChar[capture] : String.fromCharCode(parseInt(capture.substr(2), 10)); + }; + + return { + + /** + * Converts a string of characters into a legal, parseable Javascript `var` name as long as the passed + * string contains at least one alphabetic character. Non alphanumeric characters, and *leading* non alphabetic + * characters will be removed. + * @param {String} s A string to be converted into a `var` name. + * @return {String} A legal Javascript `var` name. + */ + createVarName: function(s) { + return s.replace(varReplace, ''); + }, + + /** + * 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 + * @method + */ + htmlEncode: function(value) { + return (!value) ? value : String(value).replace(charToEntityRegex, htmlEncodeReplaceFn); + }, + + /** + * Convert certain characters (&, <, >, ', and ") from their HTML character equivalents. + * @param {String} value The string to decode + * @return {String} The decoded text + * @method + */ + htmlDecode: function(value) { + return (!value) ? value : String(value).replace(entityToCharRegex, htmlDecodeReplaceFn); + }, + + /** + * Adds a set of character entity definitions to the set used by + * {@link Ext.String#htmlEncode} and {@link Ext.String#htmlDecode}. + * + * This object should be keyed by the entity name sequence, + * with the value being the textual representation of the entity. + * + * Ext.String.addCharacterEntities({ + * '&Uuml;':'Ü', + * '&ccedil;':'ç', + * '&ntilde;':'ñ', + * '&egrave;':'è' + * }); + * var s = Ext.String.htmlEncode("A string with entities: èÜçñ"); + * + * Note: the values of the character entites defined on this object are expected + * to be single character values. As such, the actual values represented by the + * characters are sensitive to the character encoding of the javascript source + * file when defined in string literal form. Script tasgs referencing server + * resources with character entities must ensure that the 'charset' attribute + * of the script node is consistent with the actual character encoding of the + * server resource. + * + * The set of character entities may be reset back to the default state by using + * the {@link Ext.String#resetCharacterEntities} method + * + * @param {Object} entities The set of character entities to add to the current + * definitions. + */ + addCharacterEntities: function(newEntities) { + var charKeys = [], + entityKeys = [], + key, echar; + for (key in newEntities) { + echar = newEntities[key]; + entityToChar[key] = echar; + charToEntity[echar] = key; + charKeys.push(echar); + entityKeys.push(key); + } + charToEntityRegex = new RegExp('(' + charKeys.join('|') + ')', 'g'); + entityToCharRegex = new RegExp('(' + entityKeys.join('|') + '|&#[0-9]{1,5};' + ')', 'g'); + }, + + /** + * Resets the set of character entity definitions used by + * {@link Ext.String#htmlEncode} and {@link Ext.String#htmlDecode} back to the + * default state. + */ + resetCharacterEntities: function() { + charToEntity = {}; + entityToChar = {}; + // add the default set + this.addCharacterEntities({ + '&' : '&', + '>' : '>', + '<' : '<', + '"' : '"', + ''' : "'" + }); + }, + + /** + * Appends content to the query string of a URL, handling logic for whether to place + * a question mark or ampersand. + * @param {String} url The URL to append to. + * @param {String} string The content to append to the URL. + * @return {String} The resulting URL + */ + urlAppend : function(url, string) { + if (!Ext.isEmpty(string)) { + return url + (url.indexOf('?') === -1 ? '?' : '&') + string; + } + + return url; + }, + + /** + * Trims whitespace from either end of a string, leaving spaces within the string intact. Example: + * @example + var s = ' foo bar '; + alert('-' + s + '-'); //alerts "- foo bar -" + alert('-' + Ext.String.trim(s) + '-'); //alerts "-foo bar-" + + * @param {String} string The string to escape + * @return {String} The trimmed string + */ + trim: function(string) { + return string.replace(trimRegex, ""); + }, + + /** + * Capitalize the given string + * @param {String} string + * @return {String} + */ + capitalize: function(string) { + return string.charAt(0).toUpperCase() + string.substr(1); + }, + + /** + * Uncapitalize the given string + * @param {String} string + * @return {String} + */ + uncapitalize: function(string) { + return string.charAt(0).toLowerCase() + string.substr(1); + }, + + /** + * 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 word break + * @return {String} The converted text + */ + ellipsis: function(value, len, word) { + if (value && value.length > len) { + if (word) { + var vs = value.substr(0, len - 2), + index = Math.max(vs.lastIndexOf(' '), vs.lastIndexOf('.'), vs.lastIndexOf('!'), vs.lastIndexOf('?')); + if (index !== -1 && index >= (len - 15)) { + return vs.substr(0, index) + "..."; + } + } + return value.substr(0, len - 3) + "..."; + } + return value; + }, + + /** + * Escapes the passed string for use in a regular expression + * @param {String} string + * @return {String} + */ + escapeRegex: function(string) { + return string.replace(escapeRegexRe, "\\$1"); + }, + + /** + * Escapes the passed string for ' and \ + * @param {String} string The string to escape + * @return {String} The escaped string + */ + escape: function(string) { + return string.replace(escapeRe, "\\$1"); + }, + + /** + * Utility function that allows you to easily switch a string between two alternating values. The passed value + * is compared to the current string, and if they are equal, the other value that was passed in is returned. If + * they are already different, the first value passed in is returned. Note that this method returns the new value + * but does not change the current string. + *
    
    +        // alternate sort directions
    +        sort = Ext.String.toggle(sort, 'ASC', 'DESC');
    +
    +        // instead of conditional logic:
    +        sort = (sort == 'ASC' ? 'DESC' : 'ASC');
    +           
    + * @param {String} string The current string + * @param {String} value The value to compare to the current string + * @param {String} other The new value to use if the string already equals the first value passed in + * @return {String} The new value + */ + toggle: function(string, value, other) { + return string === value ? other : value; + }, + + /** + * Pads the left side of a string with a specified character. This is especially useful + * for normalizing number and date strings. Example usage: + * + *
    
    +    var s = Ext.String.leftPad('123', 5, '0');
    +    // s now contains the string: '00123'
    +           
    + * @param {String} string The original string + * @param {Number} size The total length of the output string + * @param {String} character (optional) The character with which to pad the original string (defaults to empty string " ") + * @return {String} The padded string + */ + leftPad: function(string, size, character) { + var result = String(string); + character = character || " "; + while (result.length < size) { + result = character + result; + } + return result; + }, + + /** + * Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens. Each + * token must be unique, and must increment in the format {0}, {1}, etc. Example usage: + *
    
    +    var cls = 'my-class', text = 'Some text';
    +    var s = Ext.String.format('<div class="{0}">{1}</div>', cls, text);
    +    // s now contains the string: '<div class="my-class">Some text</div>'
    +           
    + * @param {String} string The tokenized string to be formatted + * @param {String} value1 The value to replace token {0} + * @param {String} value2 Etc... + * @return {String} The formatted string + */ + format: function(format) { + var args = Ext.Array.toArray(arguments, 1); + return format.replace(formatRe, function(m, i) { + return args[i]; + }); + }, + + /** + * Returns a string with a specified number of repititions a given string pattern. + * The pattern be separated by a different string. + * + * var s = Ext.String.repeat('---', 4); // = '------------' + * var t = Ext.String.repeat('--', 3, '/'); // = '--/--/--' + * + * @param {String} pattern The pattern to repeat. + * @param {Number} count The number of times to repeat the pattern (may be 0). + * @param {String} sep An option string to separate each pattern. + */ + repeat: function(pattern, count, sep) { + for (var buf = [], i = count; i--; ) { + buf.push(pattern); + } + return buf.join(sep || ''); + }, + + /** + * Splits a string of space separated words into an array, trimming as needed. If the + * words are already an array, it is returned. + * + * @param {String/Array} words + */ + splitWords: function (words) { + if (words && typeof words == 'string') { + return words.replace(basicTrimRe, '').split(whitespaceRe); + } + return words || []; + } + }; +}()); + +// initialize the default encode / decode entities +Ext.String.resetCharacterEntities(); + +/** + * Old alias to {@link Ext.String#htmlEncode} + * @deprecated Use {@link Ext.String#htmlEncode} instead + * @method + * @member Ext + * @inheritdoc Ext.String#htmlEncode + */ +Ext.htmlEncode = Ext.String.htmlEncode; + + +/** + * Old alias to {@link Ext.String#htmlDecode} + * @deprecated Use {@link Ext.String#htmlDecode} instead + * @method + * @member Ext + * @inheritdoc Ext.String#htmlDecode + */ +Ext.htmlDecode = Ext.String.htmlDecode; + +/** + * Old alias to {@link Ext.String#urlAppend} + * @deprecated Use {@link Ext.String#urlAppend} instead + * @method + * @member Ext + * @inheritdoc Ext.String#urlAppend + */ +Ext.urlAppend = Ext.String.urlAppend; +/** + * @class Ext.Number + * + * A collection of useful static methods to deal with numbers + * @singleton + */ + +Ext.Number = new function() { + + var me = this, + isToFixedBroken = (0.9).toFixed() !== '1', + math = Math; + + Ext.apply(this, { + /** + * Checks whether or not the passed number is within a desired range. If the number is already within the + * range it is returned, otherwise the min or max value is returned depending on which side of the range is + * exceeded. Note that this method returns the constrained value but does not change the current number. + * @param {Number} number The number to check + * @param {Number} min The minimum number in the range + * @param {Number} max The maximum number in the range + * @return {Number} The constrained value if outside the range, otherwise the current value + */ + constrain: function(number, min, max) { + var x = parseFloat(number); + + // Watch out for NaN in Chrome 18 + // V8bug: http://code.google.com/p/v8/issues/detail?id=2056 + + // Operators are faster than Math.min/max. See http://jsperf.com/number-constrain + // ... and (x < Nan) || (x < undefined) == false + // ... same for (x > NaN) || (x > undefined) + // so if min or max are undefined or NaN, we never return them... sadly, this + // is not true of null (but even Math.max(-1,null)==0 and isNaN(null)==false) + return (x < min) ? min : ((x > max) ? max : x); + }, + + /** + * Snaps the passed number between stopping points based upon a passed increment value. + * + * The difference between this and {@link #snapInRange} is that {@link #snapInRange} uses the minValue + * when calculating snap points: + * + * r = Ext.Number.snap(56, 2, 55, 65); // Returns 56 - snap points are zero based + * + * r = Ext.Number.snapInRange(56, 2, 55, 65); // Returns 57 - snap points are based from minValue + * + * @param {Number} value The unsnapped value. + * @param {Number} increment The increment by which the value must move. + * @param {Number} minValue The minimum value to which the returned value must be constrained. Overrides the increment. + * @param {Number} maxValue The maximum value to which the returned value must be constrained. Overrides the increment. + * @return {Number} The value of the nearest snap target. + */ + snap : function(value, increment, minValue, maxValue) { + var m; + + // If no value passed, or minValue was passed and value is less than minValue (anything < undefined is false) + // Then use the minValue (or zero if the value was undefined) + if (value === undefined || value < minValue) { + return minValue || 0; + } + + if (increment) { + m = value % increment; + if (m !== 0) { + value -= m; + if (m * 2 >= increment) { + value += increment; + } else if (m * 2 < -increment) { + value -= increment; + } + } + } + return me.constrain(value, minValue, maxValue); + }, + + /** + * Snaps the passed number between stopping points based upon a passed increment value. + * + * The difference between this and {@link #snap} is that {@link #snap} does not use the minValue + * when calculating snap points: + * + * r = Ext.Number.snap(56, 2, 55, 65); // Returns 56 - snap points are zero based + * + * r = Ext.Number.snapInRange(56, 2, 55, 65); // Returns 57 - snap points are based from minValue + * + * @param {Number} value The unsnapped value. + * @param {Number} increment The increment by which the value must move. + * @param {Number} [minValue=0] The minimum value to which the returned value must be constrained. + * @param {Number} [maxValue=Infinity] The maximum value to which the returned value must be constrained. + * @return {Number} The value of the nearest snap target. + */ + snapInRange : function(value, increment, minValue, maxValue) { + var tween; + + // default minValue to zero + minValue = (minValue || 0); + + // If value is undefined, or less than minValue, use minValue + if (value === undefined || value < minValue) { + return minValue; + } + + // Calculate how many snap points from the minValue the passed value is. + if (increment && (tween = ((value - minValue) % increment))) { + value -= tween; + tween *= 2; + if (tween >= increment) { + value += increment; + } + } + + // If constraining within a maximum, ensure the maximum is on a snap point + if (maxValue !== undefined) { + if (value > (maxValue = me.snapInRange(maxValue, increment, minValue))) { + value = maxValue; + } + } + + return value; + }, + + /** + * Formats a number using fixed-point notation + * @param {Number} value The number to format + * @param {Number} precision The number of digits to show after the decimal point + */ + toFixed: isToFixedBroken ? function(value, precision) { + precision = precision || 0; + var pow = math.pow(10, precision); + return (math.round(value * pow) / pow).toFixed(precision); + } : function(value, precision) { + return value.toFixed(precision); + }, + + /** + * Validate that a value is numeric and convert it to a number if necessary. Returns the specified default value if + * it is not. + + Ext.Number.from('1.23', 1); // returns 1.23 + Ext.Number.from('abc', 1); // returns 1 + + * @param {Object} value + * @param {Number} defaultValue The value to return if the original value is non-numeric + * @return {Number} value, if numeric, defaultValue otherwise + */ + from: function(value, defaultValue) { + if (isFinite(value)) { + value = parseFloat(value); + } + + return !isNaN(value) ? value : defaultValue; + }, + + /** + * Returns a random integer between the specified range (inclusive) + * @param {Number} from Lowest value to return. + * @param {Number} to Highst value to return. + * @return {Number} A random integer within the specified range. + */ + randomInt: function (from, to) { + return math.floor(math.random() * (to - from + 1) + from); + } + }); + + /** + * @deprecated 4.0.0 Please use {@link Ext.Number#from} instead. + * @member Ext + * @method num + * @inheritdoc Ext.Number#from + */ + Ext.num = function() { + return me.from.apply(this, arguments); + }; +}; +/** + * @class Ext.Array + * @singleton + * @author Jacky Nguyen + * @docauthor Jacky Nguyen + * + * A set of useful static methods to deal with arrays; provide missing methods for older browsers. + */ +(function() { + + var arrayPrototype = Array.prototype, + slice = arrayPrototype.slice, + supportsSplice = (function () { + var array = [], + lengthBefore, + j = 20; + + if (!array.splice) { + return false; + } + + // This detects a bug in IE8 splice method: + // see http://social.msdn.microsoft.com/Forums/en-US/iewebdevelopment/thread/6e946d03-e09f-4b22-a4dd-cd5e276bf05a/ + + while (j--) { + array.push("A"); + } + + array.splice(15, 0, "F", "F", "F", "F", "F","F","F","F","F","F","F","F","F","F","F","F","F","F","F","F","F"); + + lengthBefore = array.length; //41 + array.splice(13, 0, "XXX"); // add one element + + if (lengthBefore+1 != array.length) { + return false; + } + // end IE8 bug + + return true; + }()), + supportsForEach = 'forEach' in arrayPrototype, + supportsMap = 'map' in arrayPrototype, + supportsIndexOf = 'indexOf' in arrayPrototype, + supportsEvery = 'every' in arrayPrototype, + supportsSome = 'some' in arrayPrototype, + supportsFilter = 'filter' in arrayPrototype, + supportsSort = (function() { + var a = [1,2,3,4,5].sort(function(){ return 0; }); + return a[0] === 1 && a[1] === 2 && a[2] === 3 && a[3] === 4 && a[4] === 5; + }()), + supportsSliceOnNodeList = true, + ExtArray, + erase, + replace, + splice; + + try { + // IE 6 - 8 will throw an error when using Array.prototype.slice on NodeList + if (typeof document !== 'undefined') { + slice.call(document.getElementsByTagName('body')); + } + } catch (e) { + supportsSliceOnNodeList = false; + } + + function fixArrayIndex (array, index) { + return (index < 0) ? Math.max(0, array.length + index) + : Math.min(array.length, index); + } + + /* + Does the same work as splice, but with a slightly more convenient signature. The splice + method has bugs in IE8, so this is the implementation we use on that platform. + + The rippling of items in the array can be tricky. Consider two use cases: + + index=2 + removeCount=2 + /=====\ + +---+---+---+---+---+---+---+---+ + | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | + +---+---+---+---+---+---+---+---+ + / \/ \/ \/ \ + / /\ /\ /\ \ + / / \/ \/ \ +--------------------------+ + / / /\ /\ +--------------------------+ \ + / / / \/ +--------------------------+ \ \ + / / / /+--------------------------+ \ \ \ + / / / / \ \ \ \ + v v v v v v v v + +---+---+---+---+---+---+ +---+---+---+---+---+---+---+---+---+ + | 0 | 1 | 4 | 5 | 6 | 7 | | 0 | 1 | a | b | c | 4 | 5 | 6 | 7 | + +---+---+---+---+---+---+ +---+---+---+---+---+---+---+---+---+ + A B \=========/ + insert=[a,b,c] + + In case A, it is obvious that copying of [4,5,6,7] must be left-to-right so + that we don't end up with [0,1,6,7,6,7]. In case B, we have the opposite; we + must go right-to-left or else we would end up with [0,1,a,b,c,4,4,4,4]. + */ + function replaceSim (array, index, removeCount, insert) { + var add = insert ? insert.length : 0, + length = array.length, + pos = fixArrayIndex(array, index), + remove, + tailOldPos, + tailNewPos, + tailCount, + lengthAfterRemove, + i; + + // we try to use Array.push when we can for efficiency... + if (pos === length) { + if (add) { + array.push.apply(array, insert); + } + } else { + remove = Math.min(removeCount, length - pos); + tailOldPos = pos + remove; + tailNewPos = tailOldPos + add - remove; + tailCount = length - tailOldPos; + lengthAfterRemove = length - remove; + + if (tailNewPos < tailOldPos) { // case A + for (i = 0; i < tailCount; ++i) { + array[tailNewPos+i] = array[tailOldPos+i]; + } + } else if (tailNewPos > tailOldPos) { // case B + for (i = tailCount; i--; ) { + array[tailNewPos+i] = array[tailOldPos+i]; + } + } // else, add == remove (nothing to do) + + if (add && pos === lengthAfterRemove) { + array.length = lengthAfterRemove; // truncate array + array.push.apply(array, insert); + } else { + array.length = lengthAfterRemove + add; // reserves space + for (i = 0; i < add; ++i) { + array[pos+i] = insert[i]; + } + } + } + + return array; + } + + function replaceNative (array, index, removeCount, insert) { + if (insert && insert.length) { + if (index < array.length) { + array.splice.apply(array, [index, removeCount].concat(insert)); + } else { + array.push.apply(array, insert); + } + } else { + array.splice(index, removeCount); + } + return array; + } + + function eraseSim (array, index, removeCount) { + return replaceSim(array, index, removeCount); + } + + function eraseNative (array, index, removeCount) { + array.splice(index, removeCount); + return array; + } + + function spliceSim (array, index, removeCount) { + var pos = fixArrayIndex(array, index), + removed = array.slice(index, fixArrayIndex(array, pos+removeCount)); + + if (arguments.length < 4) { + replaceSim(array, pos, removeCount); + } else { + replaceSim(array, pos, removeCount, slice.call(arguments, 3)); + } + + return removed; + } + + function spliceNative (array) { + return array.splice.apply(array, slice.call(arguments, 1)); + } + + erase = supportsSplice ? eraseNative : eraseSim; + replace = supportsSplice ? replaceNative : replaceSim; + splice = supportsSplice ? spliceNative : spliceSim; + + // NOTE: from here on, use erase, replace or splice (not native methods)... + + ExtArray = Ext.Array = { + /** + * Iterates an array or an iterable value and invoke the given callback function for each item. + * + * var countries = ['Vietnam', 'Singapore', 'United States', 'Russia']; + * + * Ext.Array.each(countries, function(name, index, countriesItSelf) { + * console.log(name); + * }); + * + * var sum = function() { + * var sum = 0; + * + * Ext.Array.each(arguments, function(value) { + * sum += value; + * }); + * + * return sum; + * }; + * + * sum(1, 2, 3); // returns 6 + * + * The iteration can be stopped by returning false in the function callback. + * + * Ext.Array.each(countries, function(name, index, countriesItSelf) { + * if (name === 'Singapore') { + * return false; // break here + * } + * }); + * + * {@link Ext#each Ext.each} is alias for {@link Ext.Array#each Ext.Array.each} + * + * @param {Array/NodeList/Object} iterable The value to be iterated. If this + * argument is not iterable, the callback function is called once. + * @param {Function} fn The callback function. If it returns false, the iteration stops and this method returns + * the current `index`. + * @param {Object} fn.item The item at the current `index` in the passed `array` + * @param {Number} fn.index The current `index` within the `array` + * @param {Array} fn.allItems The `array` itself which was passed as the first argument + * @param {Boolean} fn.return Return false to stop iteration. + * @param {Object} scope (Optional) The scope (`this` reference) in which the specified function is executed. + * @param {Boolean} reverse (Optional) Reverse the iteration order (loop from the end to the beginning) + * Defaults false + * @return {Boolean} See description for the `fn` parameter. + */ + each: function(array, fn, scope, reverse) { + array = ExtArray.from(array); + + var i, + ln = array.length; + + if (reverse !== true) { + for (i = 0; i < ln; i++) { + if (fn.call(scope || array[i], array[i], i, array) === false) { + return i; + } + } + } + else { + for (i = ln - 1; i > -1; i--) { + if (fn.call(scope || array[i], array[i], i, array) === false) { + return i; + } + } + } + + return true; + }, + + /** + * Iterates an array and invoke the given callback function for each item. Note that this will simply + * delegate to the native Array.prototype.forEach method if supported. It doesn't support stopping the + * iteration by returning false in the callback function like {@link Ext.Array#each}. However, performance + * could be much better in modern browsers comparing with {@link Ext.Array#each} + * + * @param {Array} array The array to iterate + * @param {Function} fn The callback function. + * @param {Object} fn.item The item at the current `index` in the passed `array` + * @param {Number} fn.index The current `index` within the `array` + * @param {Array} fn.allItems The `array` itself which was passed as the first argument + * @param {Object} scope (Optional) The execution scope (`this`) in which the specified function is executed. + */ + forEach: supportsForEach ? function(array, fn, scope) { + return array.forEach(fn, scope); + } : function(array, fn, scope) { + var i = 0, + ln = array.length; + + for (; i < ln; i++) { + fn.call(scope, array[i], i, array); + } + }, + + /** + * Get the index of the provided `item` in the given `array`, a supplement for the + * missing arrayPrototype.indexOf in Internet Explorer. + * + * @param {Array} array The array to check + * @param {Object} item The item to look for + * @param {Number} from (Optional) The index at which to begin the search + * @return {Number} The index of item in the array (or -1 if it is not found) + */ + indexOf: supportsIndexOf ? function(array, item, from) { + return array.indexOf(item, from); + } : function(array, item, from) { + var i, length = array.length; + + for (i = (from < 0) ? Math.max(0, length + from) : from || 0; i < length; i++) { + if (array[i] === item) { + return i; + } + } + + return -1; + }, + + /** + * Checks whether or not the given `array` contains the specified `item` + * + * @param {Array} array The array to check + * @param {Object} item The item to look for + * @return {Boolean} True if the array contains the item, false otherwise + */ + contains: supportsIndexOf ? function(array, item) { + return array.indexOf(item) !== -1; + } : function(array, item) { + var i, ln; + + for (i = 0, ln = array.length; i < ln; i++) { + if (array[i] === item) { + return true; + } + } + + return false; + }, + + /** + * Converts any iterable (numeric indices and a length property) into a true array. + * + * function test() { + * var args = Ext.Array.toArray(arguments), + * fromSecondToLastArgs = Ext.Array.toArray(arguments, 1); + * + * alert(args.join(' ')); + * alert(fromSecondToLastArgs.join(' ')); + * } + * + * test('just', 'testing', 'here'); // alerts 'just testing here'; + * // alerts 'testing here'; + * + * Ext.Array.toArray(document.getElementsByTagName('div')); // will convert the NodeList into an array + * Ext.Array.toArray('splitted'); // returns ['s', 'p', 'l', 'i', 't', 't', 'e', 'd'] + * Ext.Array.toArray('splitted', 0, 3); // returns ['s', 'p', 'l'] + * + * {@link Ext#toArray Ext.toArray} is alias for {@link Ext.Array#toArray Ext.Array.toArray} + * + * @param {Object} iterable the iterable object to be turned into a true Array. + * @param {Number} start (Optional) a zero-based index that specifies the start of extraction. Defaults to 0 + * @param {Number} end (Optional) a 1-based index that specifies the end of extraction. Defaults to the last + * index of the iterable value + * @return {Array} array + */ + toArray: function(iterable, start, end){ + if (!iterable || !iterable.length) { + return []; + } + + if (typeof iterable === 'string') { + iterable = iterable.split(''); + } + + if (supportsSliceOnNodeList) { + return slice.call(iterable, start || 0, end || iterable.length); + } + + var array = [], + i; + + start = start || 0; + end = end ? ((end < 0) ? iterable.length + end : end) : iterable.length; + + for (i = start; i < end; i++) { + array.push(iterable[i]); + } + + return array; + }, + + /** + * Plucks the value of a property from each item in the Array. Example: + * + * Ext.Array.pluck(Ext.query("p"), "className"); // [el1.className, el2.className, ..., elN.className] + * + * @param {Array/NodeList} array The Array of items to pluck the value from. + * @param {String} propertyName The property name to pluck from each element. + * @return {Array} The value from each item in the Array. + */ + pluck: function(array, propertyName) { + var ret = [], + i, ln, item; + + for (i = 0, ln = array.length; i < ln; i++) { + item = array[i]; + + ret.push(item[propertyName]); + } + + return ret; + }, + + /** + * Creates a new array with the results of calling a provided function on every element in this array. + * + * @param {Array} array + * @param {Function} fn Callback function for each item + * @param {Object} scope Callback function scope + * @return {Array} results + */ + map: supportsMap ? function(array, fn, scope) { + if (!fn) { + Ext.Error.raise('Ext.Array.map must have a callback function passed as second argument.'); + } + return array.map(fn, scope); + } : function(array, fn, scope) { + if (!fn) { + Ext.Error.raise('Ext.Array.map must have a callback function passed as second argument.'); + } + var results = [], + i = 0, + len = array.length; + + for (; i < len; i++) { + results[i] = fn.call(scope, array[i], i, array); + } + + return results; + }, + + /** + * Executes the specified function for each array element until the function returns a falsy value. + * If such an item is found, the function will return false immediately. + * Otherwise, it will return true. + * + * @param {Array} array + * @param {Function} fn Callback function for each item + * @param {Object} scope Callback function scope + * @return {Boolean} True if no false value is returned by the callback function. + */ + every: supportsEvery ? function(array, fn, scope) { + if (!fn) { + Ext.Error.raise('Ext.Array.every must have a callback function passed as second argument.'); + } + return array.every(fn, scope); + } : function(array, fn, scope) { + if (!fn) { + Ext.Error.raise('Ext.Array.every must have a callback function passed as second argument.'); + } + var i = 0, + ln = array.length; + + for (; i < ln; ++i) { + if (!fn.call(scope, array[i], i, array)) { + return false; + } + } + + return true; + }, + + /** + * Executes the specified function for each array element until the function returns a truthy value. + * If such an item is found, the function will return true immediately. Otherwise, it will return false. + * + * @param {Array} array + * @param {Function} fn Callback function for each item + * @param {Object} scope Callback function scope + * @return {Boolean} True if the callback function returns a truthy value. + */ + some: supportsSome ? function(array, fn, scope) { + if (!fn) { + Ext.Error.raise('Ext.Array.some must have a callback function passed as second argument.'); + } + return array.some(fn, scope); + } : function(array, fn, scope) { + if (!fn) { + Ext.Error.raise('Ext.Array.some must have a callback function passed as second argument.'); + } + var i = 0, + ln = array.length; + + for (; i < ln; ++i) { + if (fn.call(scope, array[i], i, array)) { + return true; + } + } + + return false; + }, + + /** + * Filter through an array and remove empty item as defined in {@link Ext#isEmpty Ext.isEmpty} + * + * See {@link Ext.Array#filter} + * + * @param {Array} array + * @return {Array} results + */ + clean: function(array) { + var results = [], + i = 0, + ln = array.length, + item; + + for (; i < ln; i++) { + item = array[i]; + + if (!Ext.isEmpty(item)) { + results.push(item); + } + } + + return results; + }, + + /** + * Returns a new array with unique items + * + * @param {Array} array + * @return {Array} results + */ + unique: function(array) { + var clone = [], + i = 0, + ln = array.length, + item; + + for (; i < ln; i++) { + item = array[i]; + + if (ExtArray.indexOf(clone, item) === -1) { + clone.push(item); + } + } + + return clone; + }, + + /** + * Creates a new array with all of the elements of this array for which + * the provided filtering function returns true. + * + * @param {Array} array + * @param {Function} fn Callback function for each item + * @param {Object} scope Callback function scope + * @return {Array} results + */ + filter: supportsFilter ? function(array, fn, scope) { + if (!fn) { + Ext.Error.raise('Ext.Array.filter must have a callback function passed as second argument.'); + } + return array.filter(fn, scope); + } : function(array, fn, scope) { + if (!fn) { + Ext.Error.raise('Ext.Array.filter must have a callback function passed as second argument.'); + } + var results = [], + i = 0, + ln = array.length; + + for (; i < ln; i++) { + if (fn.call(scope, array[i], i, array)) { + results.push(array[i]); + } + } + + return results; + }, + + /** + * Converts a value to an array if it's not already an array; returns: + * + * - An empty array if given value is `undefined` or `null` + * - Itself if given value is already an array + * - An array copy if given value is {@link Ext#isIterable iterable} (arguments, NodeList and alike) + * - An array with one item which is the given value, otherwise + * + * @param {Object} value The value to convert to an array if it's not already is an array + * @param {Boolean} newReference (Optional) True to clone the given array and return a new reference if necessary, + * defaults to false + * @return {Array} array + */ + from: function(value, newReference) { + if (value === undefined || value === null) { + return []; + } + + if (Ext.isArray(value)) { + return (newReference) ? slice.call(value) : value; + } + + var type = typeof value; + // Both strings and functions will have a length property. In phantomJS, NodeList + // instances report typeof=='function' but don't have an apply method... + if (value && value.length !== undefined && type !== 'string' && (type !== 'function' || !value.apply)) { + return ExtArray.toArray(value); + } + + return [value]; + }, + + /** + * Removes the specified item from the array if it exists + * + * @param {Array} array The array + * @param {Object} item The item to remove + * @return {Array} The passed array itself + */ + remove: function(array, item) { + var index = ExtArray.indexOf(array, item); + + if (index !== -1) { + erase(array, index, 1); + } + + return array; + }, + + /** + * Push an item into the array only if the array doesn't contain it yet + * + * @param {Array} array The array + * @param {Object} item The item to include + */ + include: function(array, item) { + if (!ExtArray.contains(array, item)) { + array.push(item); + } + }, + + /** + * Clone a flat array without referencing the previous one. Note that this is different + * from Ext.clone since it doesn't handle recursive cloning. It's simply a convenient, easy-to-remember method + * for Array.prototype.slice.call(array) + * + * @param {Array} array The array + * @return {Array} The clone array + */ + clone: function(array) { + return slice.call(array); + }, + + /** + * Merge multiple arrays into one with unique items. + * + * {@link Ext.Array#union} is alias for {@link Ext.Array#merge} + * + * @param {Array} array1 + * @param {Array} array2 + * @param {Array} etc + * @return {Array} merged + */ + merge: function() { + var args = slice.call(arguments), + array = [], + i, ln; + + for (i = 0, ln = args.length; i < ln; i++) { + array = array.concat(args[i]); + } + + return ExtArray.unique(array); + }, + + /** + * Merge multiple arrays into one with unique items that exist in all of the arrays. + * + * @param {Array} array1 + * @param {Array} array2 + * @param {Array} etc + * @return {Array} intersect + */ + intersect: function() { + var intersection = [], + arrays = slice.call(arguments), + arraysLength, + array, + arrayLength, + minArray, + minArrayIndex, + minArrayCandidate, + minArrayLength, + element, + elementCandidate, + elementCount, + i, j, k; + + if (!arrays.length) { + return intersection; + } + + // Find the smallest array + arraysLength = arrays.length; + for (i = minArrayIndex = 0; i < arraysLength; i++) { + minArrayCandidate = arrays[i]; + if (!minArray || minArrayCandidate.length < minArray.length) { + minArray = minArrayCandidate; + minArrayIndex = i; + } + } + + minArray = ExtArray.unique(minArray); + erase(arrays, minArrayIndex, 1); + + // Use the smallest unique'd array as the anchor loop. If the other array(s) do contain + // an item in the small array, we're likely to find it before reaching the end + // of the inner loop and can terminate the search early. + minArrayLength = minArray.length; + arraysLength = arrays.length; + for (i = 0; i < minArrayLength; i++) { + element = minArray[i]; + elementCount = 0; + + for (j = 0; j < arraysLength; j++) { + array = arrays[j]; + arrayLength = array.length; + for (k = 0; k < arrayLength; k++) { + elementCandidate = array[k]; + if (element === elementCandidate) { + elementCount++; + break; + } + } + } + + if (elementCount === arraysLength) { + intersection.push(element); + } + } + + return intersection; + }, + + /** + * Perform a set difference A-B by subtracting all items in array B from array A. + * + * @param {Array} arrayA + * @param {Array} arrayB + * @return {Array} difference + */ + difference: function(arrayA, arrayB) { + var clone = slice.call(arrayA), + ln = clone.length, + i, j, lnB; + + for (i = 0,lnB = arrayB.length; i < lnB; i++) { + for (j = 0; j < ln; j++) { + if (clone[j] === arrayB[i]) { + erase(clone, j, 1); + j--; + ln--; + } + } + } + + return clone; + }, + + /** + * Returns a shallow copy of a part of an array. This is equivalent to the native + * call "Array.prototype.slice.call(array, begin, end)". This is often used when "array" + * is "arguments" since the arguments object does not supply a slice method but can + * be the context object to Array.prototype.slice. + * + * @param {Array} array The array (or arguments object). + * @param {Number} begin The index at which to begin. Negative values are offsets from + * the end of the array. + * @param {Number} end The index at which to end. The copied items do not include + * end. Negative values are offsets from the end of the array. If end is omitted, + * all items up to the end of the array are copied. + * @return {Array} The copied piece of the array. + * @method slice + */ + // Note: IE6 will return [] on slice.call(x, undefined). + slice: ([1,2].slice(1, undefined).length ? + function (array, begin, end) { + return slice.call(array, begin, end); + } : + // at least IE6 uses arguments.length for variadic signature + function (array, begin, end) { + // After tested for IE 6, the one below is of the best performance + // see http://jsperf.com/slice-fix + if (typeof begin === 'undefined') { + return slice.call(array); + } + if (typeof end === 'undefined') { + return slice.call(array, begin); + } + return slice.call(array, begin, end); + } + ), + + /** + * Sorts the elements of an Array. + * By default, this method sorts the elements alphabetically and ascending. + * + * @param {Array} array The array to sort. + * @param {Function} sortFn (optional) The comparison function. + * @return {Array} The sorted array. + */ + sort: supportsSort ? function(array, sortFn) { + if (sortFn) { + return array.sort(sortFn); + } else { + return array.sort(); + } + } : function(array, sortFn) { + var length = array.length, + i = 0, + comparison, + j, min, tmp; + + for (; i < length; i++) { + min = i; + for (j = i + 1; j < length; j++) { + if (sortFn) { + comparison = sortFn(array[j], array[min]); + if (comparison < 0) { + min = j; + } + } else if (array[j] < array[min]) { + min = j; + } + } + if (min !== i) { + tmp = array[i]; + array[i] = array[min]; + array[min] = tmp; + } + } + + return array; + }, + + /** + * Recursively flattens into 1-d Array. Injects Arrays inline. + * + * @param {Array} array The array to flatten + * @return {Array} The 1-d array. + */ + flatten: function(array) { + var worker = []; + + function rFlatten(a) { + var i, ln, v; + + for (i = 0, ln = a.length; i < ln; i++) { + v = a[i]; + + if (Ext.isArray(v)) { + rFlatten(v); + } else { + worker.push(v); + } + } + + return worker; + } + + return rFlatten(array); + }, + + /** + * Returns the minimum value in the Array. + * + * @param {Array/NodeList} array The Array from which to select the minimum value. + * @param {Function} comparisonFn (optional) a function to perform the comparision which determines minimization. + * If omitted the "<" operator will be used. Note: gt = 1; eq = 0; lt = -1 + * @return {Object} minValue The minimum value + */ + min: function(array, comparisonFn) { + var min = array[0], + i, ln, item; + + for (i = 0, ln = array.length; i < ln; i++) { + item = array[i]; + + if (comparisonFn) { + if (comparisonFn(min, item) === 1) { + min = item; + } + } + else { + if (item < min) { + min = item; + } + } + } + + return min; + }, + + /** + * Returns the maximum value in the Array. + * + * @param {Array/NodeList} array The Array from which to select the maximum value. + * @param {Function} comparisonFn (optional) a function to perform the comparision which determines maximization. + * If omitted the ">" operator will be used. Note: gt = 1; eq = 0; lt = -1 + * @return {Object} maxValue The maximum value + */ + max: function(array, comparisonFn) { + var max = array[0], + i, ln, item; + + for (i = 0, ln = array.length; i < ln; i++) { + item = array[i]; + + if (comparisonFn) { + if (comparisonFn(max, item) === -1) { + max = item; + } + } + else { + if (item > max) { + max = item; + } + } + } + + return max; + }, + + /** + * Calculates the mean of all items in the array. + * + * @param {Array} array The Array to calculate the mean value of. + * @return {Number} The mean. + */ + mean: function(array) { + return array.length > 0 ? ExtArray.sum(array) / array.length : undefined; + }, + + /** + * Calculates the sum of all items in the given array. + * + * @param {Array} array The Array to calculate the sum value of. + * @return {Number} The sum. + */ + sum: function(array) { + var sum = 0, + i, ln, item; + + for (i = 0,ln = array.length; i < ln; i++) { + item = array[i]; + + sum += item; + } + + return sum; + }, + + /** + * Creates a map (object) keyed by the elements of the given array. The values in + * the map are the index+1 of the array element. For example: + * + * var map = Ext.Array.toMap(['a','b','c']); + * + * // map = { a: 1, b: 2, c: 3 }; + * + * Or a key property can be specified: + * + * var map = Ext.Array.toMap([ + * { name: 'a' }, + * { name: 'b' }, + * { name: 'c' } + * ], 'name'); + * + * // map = { a: 1, b: 2, c: 3 }; + * + * Lastly, a key extractor can be provided: + * + * var map = Ext.Array.toMap([ + * { name: 'a' }, + * { name: 'b' }, + * { name: 'c' } + * ], function (obj) { return obj.name.toUpperCase(); }); + * + * // map = { A: 1, B: 2, C: 3 }; + */ + toMap: function(array, getKey, scope) { + var map = {}, + i = array.length; + + if (!getKey) { + while (i--) { + map[array[i]] = i+1; + } + } else if (typeof getKey == 'string') { + while (i--) { + map[array[i][getKey]] = i+1; + } + } else { + while (i--) { + map[getKey.call(scope, array[i])] = i+1; + } + } + + return map; + }, + + _replaceSim: replaceSim, // for unit testing + _spliceSim: spliceSim, + + /** + * Removes items from an array. This is functionally equivalent to the splice method + * of Array, but works around bugs in IE8's splice method and does not copy the + * removed elements in order to return them (because very often they are ignored). + * + * @param {Array} array The Array on which to replace. + * @param {Number} index The index in the array at which to operate. + * @param {Number} removeCount The number of items to remove at index. + * @return {Array} The array passed. + * @method + */ + erase: erase, + + /** + * Inserts items in to an array. + * + * @param {Array} array The Array in which to insert. + * @param {Number} index The index in the array at which to operate. + * @param {Array} items The array of items to insert at index. + * @return {Array} The array passed. + */ + insert: function (array, index, items) { + return replace(array, index, 0, items); + }, + + /** + * Replaces items in an array. This is functionally equivalent to the splice method + * of Array, but works around bugs in IE8's splice method and is often more convenient + * to call because it accepts an array of items to insert rather than use a variadic + * argument list. + * + * @param {Array} array The Array on which to replace. + * @param {Number} index The index in the array at which to operate. + * @param {Number} removeCount The number of items to remove at index (can be 0). + * @param {Array} insert (optional) An array of items to insert at index. + * @return {Array} The array passed. + * @method + */ + replace: replace, + + /** + * Replaces items in an array. This is equivalent to the splice method of Array, but + * works around bugs in IE8's splice method. The signature is exactly the same as the + * splice method except that the array is the first argument. All arguments following + * removeCount are inserted in the array at index. + * + * @param {Array} array The Array on which to replace. + * @param {Number} index The index in the array at which to operate. + * @param {Number} removeCount The number of items to remove at index (can be 0). + * @param {Object...} elements The elements to add to the array. If you don't specify + * any elements, splice simply removes elements from the array. + * @return {Array} An array containing the removed items. + * @method + */ + splice: splice, + + /** + * Pushes new items onto the end of an Array. + * + * Passed parameters may be single items, or arrays of items. If an Array is found in the argument list, all its + * elements are pushed into the end of the target Array. + * + * @param {Array} target The Array onto which to push new items + * @param {Object...} elements The elements to add to the array. Each parameter may + * be an Array, in which case all the elements of that Array will be pushed into the end of the + * destination Array. + * @return {Array} An array containing all the new items push onto the end. + * + */ + push: function(array) { + var len = arguments.length, + i = 1, + newItem; + + if (array === undefined) { + array = []; + } else if (!Ext.isArray(array)) { + array = [array]; + } + for (; i < len; i++) { + newItem = arguments[i]; + Array.prototype.push[Ext.isArray(newItem) ? 'apply' : 'call'](array, newItem); + } + return array; + } + }; + + /** + * @method + * @member Ext + * @inheritdoc Ext.Array#each + */ + Ext.each = ExtArray.each; + + /** + * @method + * @member Ext.Array + * @inheritdoc Ext.Array#merge + */ + ExtArray.union = ExtArray.merge; + + /** + * Old alias to {@link Ext.Array#min} + * @deprecated 4.0.0 Use {@link Ext.Array#min} instead + * @method + * @member Ext + * @inheritdoc Ext.Array#min + */ + Ext.min = ExtArray.min; + + /** + * Old alias to {@link Ext.Array#max} + * @deprecated 4.0.0 Use {@link Ext.Array#max} instead + * @method + * @member Ext + * @inheritdoc Ext.Array#max + */ + Ext.max = ExtArray.max; + + /** + * Old alias to {@link Ext.Array#sum} + * @deprecated 4.0.0 Use {@link Ext.Array#sum} instead + * @method + * @member Ext + * @inheritdoc Ext.Array#sum + */ + Ext.sum = ExtArray.sum; + + /** + * Old alias to {@link Ext.Array#mean} + * @deprecated 4.0.0 Use {@link Ext.Array#mean} instead + * @method + * @member Ext + * @inheritdoc Ext.Array#mean + */ + Ext.mean = ExtArray.mean; + + /** + * Old alias to {@link Ext.Array#flatten} + * @deprecated 4.0.0 Use {@link Ext.Array#flatten} instead + * @method + * @member Ext + * @inheritdoc Ext.Array#flatten + */ + Ext.flatten = ExtArray.flatten; + + /** + * Old alias to {@link Ext.Array#clean} + * @deprecated 4.0.0 Use {@link Ext.Array#clean} instead + * @method + * @member Ext + * @inheritdoc Ext.Array#clean + */ + Ext.clean = ExtArray.clean; + + /** + * Old alias to {@link Ext.Array#unique} + * @deprecated 4.0.0 Use {@link Ext.Array#unique} instead + * @method + * @member Ext + * @inheritdoc Ext.Array#unique + */ + Ext.unique = ExtArray.unique; + + /** + * Old alias to {@link Ext.Array#pluck Ext.Array.pluck} + * @deprecated 4.0.0 Use {@link Ext.Array#pluck Ext.Array.pluck} instead + * @method + * @member Ext + * @inheritdoc Ext.Array#pluck + */ + Ext.pluck = ExtArray.pluck; + + /** + * @method + * @member Ext + * @inheritdoc Ext.Array#toArray + */ + Ext.toArray = function() { + return ExtArray.toArray.apply(ExtArray, arguments); + }; +}()); + +/** + * @class Ext.Function + * + * A collection of useful static methods to deal with function callbacks + * @singleton + * @alternateClassName Ext.util.Functions + */ +Ext.Function = { + + /** + * A very commonly used method throughout the framework. It acts as a wrapper around another method + * which originally accepts 2 arguments for `name` and `value`. + * The wrapped function then allows "flexible" value setting of either: + * + * - `name` and `value` as 2 arguments + * - one single object argument with multiple key - value pairs + * + * For example: + * + * var setValue = Ext.Function.flexSetter(function(name, value) { + * this[name] = value; + * }); + * + * // Afterwards + * // Setting a single name - value + * setValue('name1', 'value1'); + * + * // Settings multiple name - value pairs + * setValue({ + * name1: 'value1', + * name2: 'value2', + * name3: 'value3' + * }); + * + * @param {Function} setter + * @returns {Function} flexSetter + */ + flexSetter: function(fn) { + return function(a, b) { + var k, i; + + if (a === null) { + return this; + } + + if (typeof a !== 'string') { + for (k in a) { + if (a.hasOwnProperty(k)) { + fn.call(this, k, a[k]); + } + } + + if (Ext.enumerables) { + for (i = Ext.enumerables.length; i--;) { + k = Ext.enumerables[i]; + if (a.hasOwnProperty(k)) { + fn.call(this, k, a[k]); + } + } + } + } else { + fn.call(this, a, b); + } + + return this; + }; + }, + + /** + * Create a new function from the provided `fn`, change `this` to the provided scope, optionally + * overrides arguments for the call. (Defaults to the arguments passed by the caller) + * + * {@link Ext#bind Ext.bind} is alias for {@link Ext.Function#bind Ext.Function.bind} + * + * @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 default global environment object (usually 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 + */ + bind: function(fn, scope, args, appendArgs) { + if (arguments.length === 2) { + return function() { + return fn.apply(scope, arguments); + }; + } + + var method = fn, + slice = Array.prototype.slice; + + return function() { + var callArgs = args || arguments; + + if (appendArgs === true) { + callArgs = slice.call(arguments, 0); + callArgs = callArgs.concat(args); + } + else if (typeof appendArgs == 'number') { + callArgs = slice.call(arguments, 0); // copy arguments first + Ext.Array.insert(callArgs, appendArgs, args); + } + + return method.apply(scope || Ext.global, callArgs); + }; + }, + + /** + * Create a new function from the provided `fn`, the arguments of which are pre-set to `args`. + * New arguments passed to the newly created callback when it's invoked are appended after the pre-set ones. + * This is especially useful when creating callbacks. + * + * For example: + * + * var originalFunction = function(){ + * alert(Ext.Array.from(arguments).join(' ')); + * }; + * + * var callback = Ext.Function.pass(originalFunction, ['Hello', 'World']); + * + * callback(); // alerts 'Hello World' + * callback('by Me'); // alerts 'Hello World by Me' + * + * {@link Ext#pass Ext.pass} is alias for {@link Ext.Function#pass Ext.Function.pass} + * + * @param {Function} fn The original function + * @param {Array} args The arguments to pass to new callback + * @param {Object} scope (optional) The scope (`this` reference) in which the function is executed. + * @return {Function} The new callback function + */ + pass: function(fn, args, scope) { + if (!Ext.isArray(args)) { + if (Ext.isIterable(args)) { + args = Ext.Array.clone(args); + } else { + args = args !== undefined ? [args] : []; + } + } + + return function() { + var fnArgs = [].concat(args); + fnArgs.push.apply(fnArgs, arguments); + return fn.apply(scope || this, fnArgs); + }; + }, + + /** + * Create an alias to the provided method property with name `methodName` of `object`. + * Note that the execution scope will still be bound to the provided `object` itself. + * + * @param {Object/Function} object + * @param {String} methodName + * @return {Function} aliasFn + */ + alias: function(object, methodName) { + return function() { + return object[methodName].apply(object, arguments); + }; + }, + + /** + * Create a "clone" of the provided method. The returned method will call the given + * method passing along all arguments and the "this" pointer and return its result. + * + * @param {Function} method + * @return {Function} cloneFn + */ + clone: function(method) { + return function() { + return method.apply(this, arguments); + }; + }, + + /** + * 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); + * } + * + * sayHi('Fred'); // alerts "Hi, Fred" + * + * // create a new function that validates input without + * // directly modifying the original function: + * var sayHiToFriend = Ext.Function.createInterceptor(sayHi, function(name){ + * return name == 'Brian'; + * }); + * + * 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.** + * @param {Object} returnValue (optional) The value to return if the passed function return false (defaults to null). + * @return {Function} The new function + */ + createInterceptor: function(origFn, newFn, scope, returnValue) { + 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 || Ext.global, args) !== false) ? origFn.apply(me || Ext.global, args) : returnValue || null; + }; + } + }, + + /** + * Creates a delegate (callback) which, when called, executes after a specific delay. + * + * @param {Function} fn The function which will be called on a delay when the returned function is called. + * Optionally, a replacement (or additional) argument list may be specified. + * @param {Number} delay The number of milliseconds to defer execution by whenever called. + * @param {Object} scope (optional) The scope (`this` reference) used by the function at execution time. + * @param {Array} args (optional) Override 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} A function which, when called, executes the original function after the specified delay. + */ + createDelayed: function(fn, delay, scope, args, appendArgs) { + if (scope || args) { + fn = Ext.Function.bind(fn, scope, args, appendArgs); + } + + return function() { + var me = this, + args = Array.prototype.slice.call(arguments); + + setTimeout(function() { + fn.apply(me, args); + }, delay); + }; + }, + + /** + * Calls this function after the number of millseconds specified, optionally in a specific scope. Example usage: + * + * var sayHi = function(name){ + * alert('Hi, ' + name); + * } + * + * // executes immediately: + * sayHi('Fred'); + * + * // executes after 2 seconds: + * Ext.Function.defer(sayHi, 2000, this, ['Fred']); + * + * // this syntax is sometimes useful for deferring + * // execution of an anonymous function: + * Ext.Function.defer(function(){ + * alert('Anonymous'); + * }, 100); + * + * {@link Ext#defer Ext.defer} is alias for {@link Ext.Function#defer Ext.Function.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 + */ + defer: function(fn, millis, scope, args, appendArgs) { + fn = Ext.Function.bind(fn, scope, args, appendArgs); + if (millis > 0) { + return setTimeout(Ext.supports.TimeoutActualLateness ? function () { + fn(); + } : fn, millis); + } + fn(); + return 0; + }, + + /** + * 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 function is called with the parameters of the original function. Example usage: + * + * var sayHi = function(name){ + * alert('Hi, ' + name); + * } + * + * sayHi('Fred'); // alerts "Hi, Fred" + * + * var sayGoodbye = Ext.Function.createSequence(sayHi, function(name){ + * alert('Bye, ' + name); + * }); + * + * sayGoodbye('Fred'); // both alerts show + * + * @param {Function} originalFn 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 default global environment object (usually the browser window). + * @return {Function} The new function + */ + createSequence: function(originalFn, newFn, scope) { + if (!newFn) { + return originalFn; + } + else { + return function() { + var result = originalFn.apply(this, arguments); + newFn.apply(scope || this, arguments); + return result; + }; + } + }, + + /** + * Creates a delegate function, optionally with a bound scope which, when called, buffers + * the execution of the passed function for the configured number of milliseconds. + * If called again within that period, the impending invocation will be canceled, and the + * timeout period will begin again. + * + * @param {Function} fn The function to invoke on a buffered timer. + * @param {Number} buffer The number of milliseconds by which to buffer the invocation of the + * function. + * @param {Object} scope (optional) The scope (`this` reference) in which + * the passed function is executed. If omitted, defaults to the scope specified by the caller. + * @param {Array} args (optional) Override arguments for the call. Defaults to the arguments + * passed by the caller. + * @return {Function} A function which invokes the passed function after buffering for the specified time. + */ + createBuffered: function(fn, buffer, scope, args) { + var timerId; + + return function() { + var callArgs = args || Array.prototype.slice.call(arguments, 0), + me = scope || this; + + if (timerId) { + clearTimeout(timerId); + } + + timerId = setTimeout(function(){ + fn.apply(me, callArgs); + }, buffer); + }; + }, + + /** + * Creates a throttled version of the passed function which, when called repeatedly and + * rapidly, invokes the passed function only after a certain interval has elapsed since the + * previous invocation. + * + * This is useful for wrapping functions which may be called repeatedly, such as + * a handler of a mouse move event when the processing is expensive. + * + * @param {Function} fn The function to execute at a regular time interval. + * @param {Number} interval The interval **in milliseconds** on which the passed function is executed. + * @param {Object} scope (optional) The scope (`this` reference) in which + * the passed function is executed. If omitted, defaults to the scope specified by the caller. + * @returns {Function} A function which invokes the passed function at the specified interval. + */ + createThrottled: function(fn, interval, scope) { + var lastCallTime, elapsed, lastArgs, timer, execute = function() { + fn.apply(scope || this, lastArgs); + lastCallTime = new Date().getTime(); + }; + + return function() { + elapsed = new Date().getTime() - lastCallTime; + lastArgs = arguments; + + clearTimeout(timer); + if (!lastCallTime || (elapsed >= interval)) { + execute(); + } else { + timer = setTimeout(execute, interval - elapsed); + } + }; + }, + + + /** + * Adds behavior to an existing method that is executed before the + * original behavior of the function. For example: + * + * var soup = { + * contents: [], + * add: function(ingredient) { + * this.contents.push(ingredient); + * } + * }; + * Ext.Function.interceptBefore(soup, "add", function(ingredient){ + * if (!this.contents.length && ingredient !== "water") { + * // Always add water to start with + * this.contents.push("water"); + * } + * }); + * soup.add("onions"); + * soup.add("salt"); + * soup.contents; // will contain: water, onions, salt + * + * @param {Object} object The target object + * @param {String} methodName Name of the method to override + * @param {Function} fn Function with the new behavior. It will + * be called with the same arguments as the original method. The + * return value of this function will be the return value of the + * new method. + * @param {Object} [scope] The scope to execute the interceptor function. Defaults to the object. + * @return {Function} The new function just created. + */ + interceptBefore: function(object, methodName, fn, scope) { + var method = object[methodName] || Ext.emptyFn; + + return (object[methodName] = function() { + var ret = fn.apply(scope || this, arguments); + method.apply(this, arguments); + + return ret; + }); + }, + + /** + * Adds behavior to an existing method that is executed after the + * original behavior of the function. For example: + * + * var soup = { + * contents: [], + * add: function(ingredient) { + * this.contents.push(ingredient); + * } + * }; + * Ext.Function.interceptAfter(soup, "add", function(ingredient){ + * // Always add a bit of extra salt + * this.contents.push("salt"); + * }); + * soup.add("water"); + * soup.add("onions"); + * soup.contents; // will contain: water, salt, onions, salt + * + * @param {Object} object The target object + * @param {String} methodName Name of the method to override + * @param {Function} fn Function with the new behavior. It will + * be called with the same arguments as the original method. The + * return value of this function will be the return value of the + * new method. + * @param {Object} [scope] The scope to execute the interceptor function. Defaults to the object. + * @return {Function} The new function just created. + */ + interceptAfter: function(object, methodName, fn, scope) { + var method = object[methodName] || Ext.emptyFn; + + return (object[methodName] = function() { + method.apply(this, arguments); + return fn.apply(scope || this, arguments); + }); + } +}; + +/** + * @method + * @member Ext + * @inheritdoc Ext.Function#defer + */ +Ext.defer = Ext.Function.alias(Ext.Function, 'defer'); + +/** + * @method + * @member Ext + * @inheritdoc Ext.Function#pass + */ +Ext.pass = Ext.Function.alias(Ext.Function, 'pass'); + +/** + * @method + * @member Ext + * @inheritdoc Ext.Function#bind + */ +Ext.bind = Ext.Function.alias(Ext.Function, 'bind'); + +/** + * @author Jacky Nguyen + * @docauthor Jacky Nguyen + * @class Ext.Object + * + * A collection of useful static methods to deal with objects. + * + * @singleton + */ + +(function() { + +// The "constructor" for chain: +var TemplateClass = function(){}, + ExtObject = Ext.Object = { + + /** + * Returns a new object with the given object as the prototype chain. + * @param {Object} object The prototype chain for the new object. + */ + chain: function (object) { + TemplateClass.prototype = object; + var result = new TemplateClass(); + TemplateClass.prototype = null; + return result; + }, + + /** + * Converts a `name` - `value` pair to an array of objects with support for nested structures. Useful to construct + * query strings. For example: + * + * var objects = Ext.Object.toQueryObjects('hobbies', ['reading', 'cooking', 'swimming']); + * + * // objects then equals: + * [ + * { name: 'hobbies', value: 'reading' }, + * { name: 'hobbies', value: 'cooking' }, + * { name: 'hobbies', value: 'swimming' }, + * ]; + * + * var objects = Ext.Object.toQueryObjects('dateOfBirth', { + * day: 3, + * month: 8, + * year: 1987, + * extra: { + * hour: 4 + * minute: 30 + * } + * }, true); // Recursive + * + * // objects then equals: + * [ + * { name: 'dateOfBirth[day]', value: 3 }, + * { name: 'dateOfBirth[month]', value: 8 }, + * { name: 'dateOfBirth[year]', value: 1987 }, + * { name: 'dateOfBirth[extra][hour]', value: 4 }, + * { name: 'dateOfBirth[extra][minute]', value: 30 }, + * ]; + * + * @param {String} name + * @param {Object/Array} value + * @param {Boolean} [recursive=false] True to traverse object recursively + * @return {Array} + */ + toQueryObjects: function(name, value, recursive) { + var self = ExtObject.toQueryObjects, + objects = [], + i, ln; + + if (Ext.isArray(value)) { + for (i = 0, ln = value.length; i < ln; i++) { + if (recursive) { + objects = objects.concat(self(name + '[' + i + ']', value[i], true)); + } + else { + objects.push({ + name: name, + value: value[i] + }); + } + } + } + else if (Ext.isObject(value)) { + for (i in value) { + if (value.hasOwnProperty(i)) { + if (recursive) { + objects = objects.concat(self(name + '[' + i + ']', value[i], true)); + } + else { + objects.push({ + name: name, + value: value[i] + }); + } + } + } + } + else { + objects.push({ + name: name, + value: value + }); + } + + return objects; + }, + + /** + * Takes an object and converts it to an encoded query string. + * + * Non-recursive: + * + * Ext.Object.toQueryString({foo: 1, bar: 2}); // returns "foo=1&bar=2" + * Ext.Object.toQueryString({foo: null, bar: 2}); // returns "foo=&bar=2" + * Ext.Object.toQueryString({'some price': '$300'}); // returns "some%20price=%24300" + * Ext.Object.toQueryString({date: new Date(2011, 0, 1)}); // returns "date=%222011-01-01T00%3A00%3A00%22" + * Ext.Object.toQueryString({colors: ['red', 'green', 'blue']}); // returns "colors=red&colors=green&colors=blue" + * + * Recursive: + * + * Ext.Object.toQueryString({ + * username: 'Jacky', + * dateOfBirth: { + * day: 1, + * month: 2, + * year: 1911 + * }, + * hobbies: ['coding', 'eating', 'sleeping', ['nested', 'stuff']] + * }, true); // returns the following string (broken down and url-decoded for ease of reading purpose): + * // username=Jacky + * // &dateOfBirth[day]=1&dateOfBirth[month]=2&dateOfBirth[year]=1911 + * // &hobbies[0]=coding&hobbies[1]=eating&hobbies[2]=sleeping&hobbies[3][0]=nested&hobbies[3][1]=stuff + * + * @param {Object} object The object to encode + * @param {Boolean} [recursive=false] Whether or not to interpret the object in recursive format. + * (PHP / Ruby on Rails servers and similar). + * @return {String} queryString + */ + toQueryString: function(object, recursive) { + var paramObjects = [], + params = [], + i, j, ln, paramObject, value; + + for (i in object) { + if (object.hasOwnProperty(i)) { + paramObjects = paramObjects.concat(ExtObject.toQueryObjects(i, object[i], recursive)); + } + } + + for (j = 0, ln = paramObjects.length; j < ln; j++) { + paramObject = paramObjects[j]; + value = paramObject.value; + + if (Ext.isEmpty(value)) { + value = ''; + } + else if (Ext.isDate(value)) { + value = Ext.Date.toString(value); + } + + params.push(encodeURIComponent(paramObject.name) + '=' + encodeURIComponent(String(value))); + } + + return params.join('&'); + }, + + /** + * Converts a query string back into an object. + * + * Non-recursive: + * + * Ext.Object.fromQueryString("foo=1&bar=2"); // returns {foo: 1, bar: 2} + * Ext.Object.fromQueryString("foo=&bar=2"); // returns {foo: null, bar: 2} + * Ext.Object.fromQueryString("some%20price=%24300"); // returns {'some price': '$300'} + * Ext.Object.fromQueryString("colors=red&colors=green&colors=blue"); // returns {colors: ['red', 'green', 'blue']} + * + * Recursive: + * + * Ext.Object.fromQueryString( + * "username=Jacky&"+ + * "dateOfBirth[day]=1&dateOfBirth[month]=2&dateOfBirth[year]=1911&"+ + * "hobbies[0]=coding&hobbies[1]=eating&hobbies[2]=sleeping&"+ + * "hobbies[3][0]=nested&hobbies[3][1]=stuff", true); + * + * // returns + * { + * username: 'Jacky', + * dateOfBirth: { + * day: '1', + * month: '2', + * year: '1911' + * }, + * hobbies: ['coding', 'eating', 'sleeping', ['nested', 'stuff']] + * } + * + * @param {String} queryString The query string to decode + * @param {Boolean} [recursive=false] Whether or not to recursively decode the string. This format is supported by + * PHP / Ruby on Rails servers and similar. + * @return {Object} + */ + fromQueryString: function(queryString, recursive) { + var parts = queryString.replace(/^\?/, '').split('&'), + object = {}, + temp, components, name, value, i, ln, + part, j, subLn, matchedKeys, matchedName, + keys, key, nextKey; + + for (i = 0, ln = parts.length; i < ln; i++) { + part = parts[i]; + + if (part.length > 0) { + components = part.split('='); + name = decodeURIComponent(components[0]); + value = (components[1] !== undefined) ? decodeURIComponent(components[1]) : ''; + + if (!recursive) { + if (object.hasOwnProperty(name)) { + if (!Ext.isArray(object[name])) { + object[name] = [object[name]]; + } + + object[name].push(value); + } + else { + object[name] = value; + } + } + else { + matchedKeys = name.match(/(\[):?([^\]]*)\]/g); + matchedName = name.match(/^([^\[]+)/); + + if (!matchedName) { + throw new Error('[Ext.Object.fromQueryString] Malformed query string given, failed parsing name from "' + part + '"'); + } + + name = matchedName[0]; + keys = []; + + if (matchedKeys === null) { + object[name] = value; + continue; + } + + for (j = 0, subLn = matchedKeys.length; j < subLn; j++) { + key = matchedKeys[j]; + key = (key.length === 2) ? '' : key.substring(1, key.length - 1); + keys.push(key); + } + + keys.unshift(name); + + temp = object; + + for (j = 0, subLn = keys.length; j < subLn; j++) { + key = keys[j]; + + if (j === subLn - 1) { + if (Ext.isArray(temp) && key === '') { + temp.push(value); + } + else { + temp[key] = value; + } + } + else { + if (temp[key] === undefined || typeof temp[key] === 'string') { + nextKey = keys[j+1]; + + temp[key] = (Ext.isNumeric(nextKey) || nextKey === '') ? [] : {}; + } + + temp = temp[key]; + } + } + } + } + } + + return object; + }, + + /** + * Iterates through an object and invokes the given callback function for each iteration. + * The iteration can be stopped by returning `false` in the callback function. For example: + * + * var person = { + * name: 'Jacky' + * hairColor: 'black' + * loves: ['food', 'sleeping', 'wife'] + * }; + * + * Ext.Object.each(person, function(key, value, myself) { + * console.log(key + ":" + value); + * + * if (key === 'hairColor') { + * return false; // stop the iteration + * } + * }); + * + * @param {Object} object The object to iterate + * @param {Function} fn The callback function. + * @param {String} fn.key + * @param {Object} fn.value + * @param {Object} fn.object The object itself + * @param {Object} [scope] The execution scope (`this`) of the callback function + */ + each: function(object, fn, scope) { + for (var property in object) { + if (object.hasOwnProperty(property)) { + if (fn.call(scope || object, property, object[property], object) === false) { + return; + } + } + } + }, + + /** + * Merges any number of objects recursively without referencing them or their children. + * + * var extjs = { + * companyName: 'Ext JS', + * products: ['Ext JS', 'Ext GWT', 'Ext Designer'], + * isSuperCool: true, + * office: { + * size: 2000, + * location: 'Palo Alto', + * isFun: true + * } + * }; + * + * var newStuff = { + * companyName: 'Sencha Inc.', + * products: ['Ext JS', 'Ext GWT', 'Ext Designer', 'Sencha Touch', 'Sencha Animator'], + * office: { + * size: 40000, + * location: 'Redwood City' + * } + * }; + * + * var sencha = Ext.Object.merge(extjs, newStuff); + * + * // extjs and sencha then equals to + * { + * companyName: 'Sencha Inc.', + * products: ['Ext JS', 'Ext GWT', 'Ext Designer', 'Sencha Touch', 'Sencha Animator'], + * isSuperCool: true, + * office: { + * size: 40000, + * location: 'Redwood City', + * isFun: true + * } + * } + * + * @param {Object} destination The object into which all subsequent objects are merged. + * @param {Object...} object Any number of objects to merge into the destination. + * @return {Object} merged The destination object with all passed objects merged in. + */ + merge: function(destination) { + var i = 1, + ln = arguments.length, + mergeFn = ExtObject.merge, + cloneFn = Ext.clone, + object, key, value, sourceKey; + + for (; i < ln; i++) { + object = arguments[i]; + + for (key in object) { + value = object[key]; + if (value && value.constructor === Object) { + sourceKey = destination[key]; + if (sourceKey && sourceKey.constructor === Object) { + mergeFn(sourceKey, value); + } + else { + destination[key] = cloneFn(value); + } + } + else { + destination[key] = value; + } + } + } + + return destination; + }, + + /** + * @private + * @param destination + */ + mergeIf: function(destination) { + var i = 1, + ln = arguments.length, + cloneFn = Ext.clone, + object, key, value; + + for (; i < ln; i++) { + object = arguments[i]; + + for (key in object) { + if (!(key in destination)) { + value = object[key]; + + if (value && value.constructor === Object) { + destination[key] = cloneFn(value); + } + else { + destination[key] = value; + } + } + } + } + + return destination; + }, + + /** + * Returns the first matching key corresponding to the given value. + * If no matching value is found, null is returned. + * + * var person = { + * name: 'Jacky', + * loves: 'food' + * }; + * + * alert(Ext.Object.getKey(person, 'food')); // alerts 'loves' + * + * @param {Object} object + * @param {Object} value The value to find + */ + getKey: function(object, value) { + for (var property in object) { + if (object.hasOwnProperty(property) && object[property] === value) { + return property; + } + } + + return null; + }, + + /** + * Gets all values of the given object as an array. + * + * var values = Ext.Object.getValues({ + * name: 'Jacky', + * loves: 'food' + * }); // ['Jacky', 'food'] + * + * @param {Object} object + * @return {Array} An array of values from the object + */ + getValues: function(object) { + var values = [], + property; + + for (property in object) { + if (object.hasOwnProperty(property)) { + values.push(object[property]); + } + } + + return values; + }, + + /** + * Gets all keys of the given object as an array. + * + * var values = Ext.Object.getKeys({ + * name: 'Jacky', + * loves: 'food' + * }); // ['name', 'loves'] + * + * @param {Object} object + * @return {String[]} An array of keys from the object + * @method + */ + getKeys: (typeof Object.keys == 'function') + ? function(object){ + if (!object) { + return []; + } + return Object.keys(object); + } + : function(object) { + var keys = [], + property; + + for (property in object) { + if (object.hasOwnProperty(property)) { + keys.push(property); + } + } + + return keys; + }, + + /** + * Gets the total number of this object's own properties + * + * var size = Ext.Object.getSize({ + * name: 'Jacky', + * loves: 'food' + * }); // size equals 2 + * + * @param {Object} object + * @return {Number} size + */ + getSize: function(object) { + var size = 0, + property; + + for (property in object) { + if (object.hasOwnProperty(property)) { + size++; + } + } + + return size; + }, + + /** + * @private + */ + classify: function(object) { + var prototype = object, + objectProperties = [], + propertyClassesMap = {}, + objectClass = function() { + var i = 0, + ln = objectProperties.length, + property; + + for (; i < ln; i++) { + property = objectProperties[i]; + this[property] = new propertyClassesMap[property](); + } + }, + key, value; + + for (key in object) { + if (object.hasOwnProperty(key)) { + value = object[key]; + + if (value && value.constructor === Object) { + objectProperties.push(key); + propertyClassesMap[key] = ExtObject.classify(value); + } + } + } + + objectClass.prototype = prototype; + + return objectClass; + } +}; + +/** + * A convenient alias method for {@link Ext.Object#merge}. + * + * @member Ext + * @method merge + * @inheritdoc Ext.Object#merge + */ +Ext.merge = Ext.Object.merge; + +/** + * @private + */ +Ext.mergeIf = Ext.Object.mergeIf; + +/** + * + * @member Ext + * @method urlEncode + * @inheritdoc Ext.Object#toQueryString + * @deprecated 4.0.0 Use {@link Ext.Object#toQueryString} instead + */ +Ext.urlEncode = function() { + var args = Ext.Array.from(arguments), + prefix = ''; + + // Support for the old `pre` argument + if ((typeof args[1] === 'string')) { + prefix = args[1] + '&'; + args[1] = false; + } + + return prefix + ExtObject.toQueryString.apply(ExtObject, args); +}; + +/** + * Alias for {@link Ext.Object#fromQueryString}. + * + * @member Ext + * @method urlDecode + * @inheritdoc Ext.Object#fromQueryString + * @deprecated 4.0.0 Use {@link Ext.Object#fromQueryString} instead + */ +Ext.urlDecode = function() { + return ExtObject.fromQueryString.apply(ExtObject, arguments); +}; + +}()); + +/** + * @class Ext.Date + * A set of useful static methods to deal with date + * Note that if Ext.Date is required and loaded, it will copy all methods / properties to + * this object for convenience + * + * 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
    +  MS    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');
    +console.log(Ext.Date.format(dt, 'Y-m-d'));                          // 2007-01-10
    +console.log(Ext.Date.format(dt, 'F j, Y, g:i a'));                  // January 10, 2007, 3:05 pm
    +console.log(Ext.Date.format(dt, 'l, \\t\\he jS \\of F Y h:i:s A')); // Wednesday, the 10th of January 2007 03:05:01 PM
    +
    + * + * Here are some standard date/time patterns that you might find helpful. They + * are not part of the source of Ext.Date, but to use them you can simply copy this + * block of code into any script that is included after Ext.Date and they will also become + * globally available on the Date object. Feel free to add or remove patterns as needed in your code. + *
    
    +Ext.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();
    +console.log(Ext.Date.format(dt, Ext.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}.

    + * @singleton + */ + +/* + * 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() { + +// create private copy of Ext's Ext.util.Format.format() method +// - to remove unnecessary dependency +// - to resolve namespace conflict with MS-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]; + }); +} + +Ext.Date = { + /** + * Returns the current timestamp + * @return {Number} The current timestamp + * @method + */ + now: Date.now || function() { + return +new Date(); + }, + + /** + * @private + * Private for now + */ + toString: function(date) { + var pad = Ext.String.leftPad; + + return date.getFullYear() + "-" + + pad(date.getMonth() + 1, 2, '0') + "-" + + pad(date.getDate(), 2, '0') + "T" + + pad(date.getHours(), 2, '0') + ":" + + pad(date.getMinutes(), 2, '0') + ":" + + pad(date.getSeconds(), 2, '0'); + }, + + /** + * Returns the number of milliseconds between two dates + * @param {Date} dateA The first date + * @param {Date} dateB (optional) The second date, defaults to now + * @return {Number} The difference in milliseconds + */ + getElapsed: function(dateA, dateB) { + return Math.abs(dateA - (dateB || new Date())); + }, + + /** + * 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 #parse} for more information) + * Defaults to false. + * @type Boolean + */ + useStrict: false, + + // private + formatCodeToRegex: function(character, currentGroup) { + // Note: currentGroup - position in regex result array (see notes for Ext.Date.parseCodes below) + var p = utilDate.parseCodes[character]; + + if (p) { + p = typeof p == 'function'? p() : p; + utilDate.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.String.escapeRegex(character) // treat unrecognised characters as literals + }; + }, + + /** + *

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

    + *

    Example:

    
    +Ext.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 + * @type Object + */ + parseFunctions: { + "MS": function(input, strict) { + // note: the timezone offset is ignored since the MS Ajax server sends + // a UTC milliseconds-since-Unix-epoch value (negative values are allowed) + var re = new RegExp('\\/Date\\(([-+])?(\\d+)(?:[+-]\\d{4})?\\)\\/'), + r = (input || '').match(re); + return r? new Date(((r[1] || '') + r[2]) * 1) : 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:

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

    A formatting function should return a string representation of the passed Date object, and is passed the following parameters:

      + *
    • 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 + * @type Object + */ + formatFunctions: { + "MS": function() { + // UTC milliseconds since Unix epoch (MS-AJAX serialized date format (MRSF)) + return '\\/Date(' + this.getTime() + ')\\/'; + } + }, + + y2kYear : 50, + + /** + * Date interval constant + * @type String + */ + MILLI : "ms", + + /** + * Date interval constant + * @type String + */ + SECOND : "s", + + /** + * Date interval constant + * @type String + */ + MINUTE : "mi", + + /** Date interval constant + * @type String + */ + HOUR : "h", + + /** + * Date interval constant + * @type String + */ + DAY : "d", + + /** + * Date interval constant + * @type String + */ + MONTH : "mo", + + /** + * Date interval constant + * @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 #parse} 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
    +Ext.Date.defaults.d = 1;
    +
    +// parse a February date string containing only year and month values.
    +// setting the default day value to 1 prevents weird date rollover issues
    +// when attempting to parse the following date string on, for example, March 31st 2009.
    +Ext.Date.parse('2009-02', 'Y-m'); // returns a Date object representing February 1st 2009
    +
    + * @property defaults + * @type Object + */ + defaults: {}, + + // + /** + * @property {String[]} dayNames + * An array of textual day names. + * Override these values for international dates. + * Example: + *
    
    +Ext.Date.dayNames = [
    +    'SundayInYourLang',
    +    'MondayInYourLang',
    +    ...
    +];
    +
    + */ + dayNames : [ + "Sunday", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday" + ], + //
    + + // + /** + * @property {String[]} monthNames + * An array of textual month names. + * Override these values for international dates. + * Example: + *
    
    +Ext.Date.monthNames = [
    +    'JanInYourLang',
    +    'FebInYourLang',
    +    ...
    +];
    +
    + */ + monthNames : [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December" + ], + //
    + + // + /** + * @property {Object} monthNumbers + * 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: + *
    
    +Ext.Date.monthNumbers = {
    +    'LongJanNameInYourLang': 0,
    +    'ShortJanNameInYourLang':0,
    +    'LongFebNameInYourLang':1,
    +    'ShortFebNameInYourLang':1,
    +    ...
    +};
    +
    + */ + monthNumbers : { + January: 0, + Jan: 0, + February: 1, + Feb: 1, + March: 2, + Mar: 2, + April: 3, + Apr: 3, + May: 4, + June: 5, + Jun: 5, + July: 6, + Jul: 6, + August: 7, + Aug: 7, + September: 8, + Sep: 8, + October: 9, + Oct: 9, + November: 10, + Nov: 10, + December: 11, + Dec: 11 + }, + //
    + + // + /** + * @property {String} defaultFormat + *

    The date format string that the {@link Ext.util.Format#dateRenderer} + * and {@link Ext.util.Format#date} functions use. See {@link Ext.Date} for details.

    + *

    This may be overridden in a locale file.

    + */ + defaultFormat : "m/d/Y", + //
    + // + /** + * 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. + */ + getShortMonthName : function(month) { + return Ext.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. + */ + getShortDayName : function(day) { + return Ext.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. + */ + getMonthNumber : function(name) { + // handle camel casing for english month names (since the keys for the Ext.Date.monthNumbers hash are case sensitive) + return Ext.Date.monthNumbers[name.substring(0, 1).toUpperCase() + name.substring(1, 3).toLowerCase()]; + }, + // + + /** + * Checks if the specified format contains hour information + * @param {String} format The format to check + * @return {Boolean} True if the format contains hour information + * @method + */ + formatContainsHourInfo : (function(){ + var stripEscapeRe = /(\\.)/g, + hourInfoRe = /([gGhHisucUOPZ]|MS)/; + return function(format){ + return hourInfoRe.test(format.replace(stripEscapeRe, '')); + }; + }()), + + /** + * Checks if the specified format contains information about + * anything other than the time. + * @param {String} format The format to check + * @return {Boolean} True if the format contains information about + * date/day information. + * @method + */ + formatContainsDateInfo : (function(){ + var stripEscapeRe = /(\\.)/g, + dateInfoRe = /([djzmnYycU]|MS)/; + + return function(format){ + return dateInfoRe.test(format.replace(stripEscapeRe, '')); + }; + }()), + + /** + * Removes all escaping for a date format string. In date formats, + * using a '\' can be used to escape special characters. + * @param {String} format The format to unescape + * @return {String} The unescaped format + * @method + */ + unescapeFormat: (function() { + var slashRe = /\\/gi; + return function(format) { + // Escape the format, since \ can be used to escape special + // characters in a date format. For example, in a spanish + // locale the format may be: 'd \\de F \\de Y' + return format.replace(slashRe, ''); + } + }()), + + /** + * 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: Ext.Date.format() treats characters as literals if an appropriate mapping cannot be found. + * Example: + *
    
    +Ext.Date.formatCodes.x = "Ext.util.Format.leftPad(this.getDate(), 2, '0')";
    +console.log(Ext.Date.format(new Date(), 'X'); // returns the current day of the month
    +
    + * @type Object + */ + formatCodes : { + d: "Ext.String.leftPad(this.getDate(), 2, '0')", + D: "Ext.Date.getShortDayName(this.getDay())", // get localised short day name + j: "this.getDate()", + l: "Ext.Date.dayNames[this.getDay()]", + N: "(this.getDay() ? this.getDay() : 7)", + S: "Ext.Date.getSuffix(this)", + w: "this.getDay()", + z: "Ext.Date.getDayOfYear(this)", + W: "Ext.String.leftPad(Ext.Date.getWeekOfYear(this), 2, '0')", + F: "Ext.Date.monthNames[this.getMonth()]", + m: "Ext.String.leftPad(this.getMonth() + 1, 2, '0')", + M: "Ext.Date.getShortMonthName(this.getMonth())", // get localised short month name + n: "(this.getMonth() + 1)", + t: "Ext.Date.getDaysInMonth(this)", + L: "(Ext.Date.isLeapYear(this) ? 1 : 0)", + o: "(this.getFullYear() + (Ext.Date.getWeekOfYear(this) == 1 && this.getMonth() > 0 ? +1 : (Ext.Date.getWeekOfYear(this) >= 52 && this.getMonth() < 11 ? -1 : 0)))", + Y: "Ext.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: "Ext.String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0')", + H: "Ext.String.leftPad(this.getHours(), 2, '0')", + i: "Ext.String.leftPad(this.getMinutes(), 2, '0')", + s: "Ext.String.leftPad(this.getSeconds(), 2, '0')", + u: "Ext.String.leftPad(this.getMilliseconds(), 3, '0')", + O: "Ext.Date.getGMTOffset(this)", + P: "Ext.Date.getGMTOffset(this, true)", + T: "Ext.Date.getTimezone(this)", + Z: "(this.getTimezoneOffset() * -60)", + + c: function() { // ISO-8601 -- GMT format + var c, code, i, l, e; + for (c = "Y-m-dTH:i:sP", code = [], i = 0, l = c.length; i < l; ++i) { + e = c.charAt(i); + code.push(e == "T" ? "'T'" : utilDate.getFormatCode(e)); // treat T as a character literal + } + return code.join(" + "); + }, + /* + c: function() { // ISO-8601 -- UTC format + return [ + "this.getUTCFullYear()", "'-'", + "Ext.util.Format.leftPad(this.getUTCMonth() + 1, 2, '0')", "'-'", + "Ext.util.Format.leftPad(this.getUTCDate(), 2, '0')", + "'T'", + "Ext.util.Format.leftPad(this.getUTCHours(), 2, '0')", "':'", + "Ext.util.Format.leftPad(this.getUTCMinutes(), 2, '0')", "':'", + "Ext.util.Format.leftPad(this.getUTCSeconds(), 2, '0')", + "'Z'" + ].join(" + "); + }, + */ + + U: "Math.round(this.getTime() / 1000)" + }, + + /** + * Checks if the passed Date parameters will cause a javascript Date "rollover". + * @param {Number} year 4-digit year + * @param {Number} month 1-based month-of-year + * @param {Number} day Day of month + * @param {Number} hour (optional) Hour + * @param {Number} minute (optional) Minute + * @param {Number} second (optional) Second + * @param {Number} millisecond (optional) Millisecond + * @return {Boolean} true if the passed parameters do not cause a Date "rollover", false otherwise. + */ + isValid : function(y, m, d, h, i, s, ms) { + // setup defaults + h = h || 0; + i = i || 0; + s = s || 0; + ms = ms || 0; + + // Special handling for year < 100 + var dt = utilDate.add(new Date(y < 100 ? 100 : y, m - 1, d, h, i, s, ms), utilDate.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(); + }, + + /** + * 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 = Ext.Date.parse("2006", "Y");
    +
    +//dt = Sun Jan 15 2006 (all date parts specified)
    +dt = Ext.Date.parse("2006-01-15", "Y-m-d");
    +
    +//dt = Sun Jan 15 2006 15:20:01
    +dt = Ext.Date.parse("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 = Ext.Date.parse("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. + */ + parse : function(input, format, strict) { + var p = utilDate.parseFunctions; + if (p[format] == null) { + utilDate.createParser(format); + } + return p[format](input, Ext.isDefined(strict) ? strict : utilDate.useStrict); + }, + + // Backwards compat + parseDate: function(input, format, strict){ + return utilDate.parse(input, format, strict); + }, + + + // private + getFormatCode : function(character) { + var f = utilDate.formatCodes[character]; + + if (f) { + f = typeof f == 'function'? f() : f; + utilDate.formatCodes[character] = f; // reassign function result to prevent repeated execution + } + + // note: unknown characters are treated as literals + return f || ("'" + Ext.String.escape(character) + "'"); + }, + + // private + createFormat : function(format) { + var code = [], + special = false, + ch = '', + i; + + for (i = 0; i < format.length; ++i) { + ch = format.charAt(i); + if (!special && ch == "\\") { + special = true; + } else if (special) { + special = false; + code.push("'" + Ext.String.escape(ch) + "'"); + } else { + code.push(utilDate.getFormatCode(ch)); + } + } + utilDate.formatFunctions[format] = Ext.functionFactory("return " + code.join('+')); + }, + + // private + createParser : (function() { + var code = [ + "var dt, y, m, d, h, i, s, ms, o, z, zz, u, v,", + "def = Ext.Date.defaults,", + "results = String(input).match(Ext.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 = Ext.Date.clearTime(new Date);", + + // date calculations (note: these calculations create a dependency on Ext.Number.from()) + "y = Ext.Number.from(y, Ext.Number.from(def.y, dt.getFullYear()));", + "m = Ext.Number.from(m, Ext.Number.from(def.m - 1, dt.getMonth()));", + "d = Ext.Number.from(d, Ext.Number.from(def.d, dt.getDate()));", + + // time calculations (note: these calculations create a dependency on Ext.Number.from()) + "h = Ext.Number.from(h, Ext.Number.from(def.h, dt.getHours()));", + "i = Ext.Number.from(i, Ext.Number.from(def.i, dt.getMinutes()));", + "s = Ext.Number.from(s, Ext.Number.from(def.s, dt.getSeconds()));", + "ms = Ext.Number.from(ms, Ext.Number.from(def.ms, dt.getMilliseconds()));", + + "if(z >= 0 && y >= 0){", + // both the year and zero-based day of year are defined and >= 0. + // these 2 values alone provide sufficient info to create a full date object + + // create Date object representing January 1st for the given year + // handle years < 100 appropriately + "v = Ext.Date.add(new Date(y < 100 ? 100 : y, 0, 1, h, i, s, ms), Ext.Date.YEAR, y < 100 ? y - 100 : 0);", + + // then add day of year, checking for Date "rollover" if necessary + "v = !strict? v : (strict === true && (z <= 364 || (Ext.Date.isLeapYear(v) && z <= 365))? Ext.Date.add(v, Ext.Date.DAY, z) : null);", + "}else if(strict === true && !Ext.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 + // handle years < 100 properly + "v = Ext.Date.add(new Date(y < 100 ? 100 : y, m, d, h, i, s, ms), Ext.Date.YEAR, y < 100 ? y - 100 : 0);", + "}", + "}", + "}", + + "if(v){", + // favour UTC offset over GMT offset + "if(zz != null){", + // reset to UTC, then add offset + "v = Ext.Date.add(v, Ext.Date.SECOND, -v.getTimezoneOffset() * 60 - zz);", + "}else if(o){", + // reset to GMT, then add offset + "v = Ext.Date.add(v, Ext.Date.MINUTE, -v.getTimezoneOffset() + (sn == '+'? -1 : 1) * (hr * 60 + mn));", + "}", + "}", + + "return v;" + ].join('\n'); + + return function(format) { + var regexNum = utilDate.parseRegexes.length, + currentGroup = 1, + calc = [], + regex = [], + special = false, + ch = "", + i = 0, + len = format.length, + atEnd = [], + obj; + + for (; i < len; ++i) { + ch = format.charAt(i); + if (!special && ch == "\\") { + special = true; + } else if (special) { + special = false; + regex.push(Ext.String.escape(ch)); + } else { + obj = utilDate.formatCodeToRegex(ch, currentGroup); + currentGroup += obj.g; + regex.push(obj.s); + if (obj.g && obj.c) { + if (obj.calcAtEnd) { + atEnd.push(obj.c); + } else { + calc.push(obj.c); + } + } + } + } + + calc = calc.concat(atEnd); + + utilDate.parseRegexes[regexNum] = new RegExp("^" + regex.join('') + "$", 'i'); + utilDate.parseFunctions[format] = Ext.functionFactory("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:"(3[0-1]|[1-2][0-9]|0[1-9])" // day of month with leading zeroes (01 - 31) + }, + j: { + g:1, + c:"d = parseInt(results[{0}], 10);\n", + s:"(3[0-1]|[1-2][0-9]|[1-9])" // day of month without leading zeroes (1 - 31) + }, + D: function() { + for (var a = [], i = 0; i < 7; a.push(utilDate.getShortDayName(i)), ++i); // get localised short day names + return { + g:0, + c:null, + s:"(?:" + a.join("|") +")" + }; + }, + l: function() { + return { + g:0, + c:null, + s:"(?:" + utilDate.dayNames.join("|") + ")" + }; + }, + N: { + g:0, + c:null, + s:"[1-7]" // ISO-8601 day number (1 (monday) - 7 (sunday)) + }, + // + S: { + g:0, + c:null, + s:"(?:st|nd|rd|th)" + }, + // + w: { + g:0, + c:null, + s:"[0-6]" // javascript day number (0 (sunday) - 6 (saturday)) + }, + z: { + g:1, + c:"z = parseInt(results[{0}], 10);\n", + s:"(\\d{1,3})" // day of the year (0 - 364 (365 in leap years)) + }, + W: { + g:0, + c:null, + s:"(?:\\d{2})" // ISO-8601 week number (with leading zero) + }, + F: function() { + return { + g:1, + c:"m = parseInt(Ext.Date.getMonthNumber(results[{0}]), 10);\n", // get localised month number + s:"(" + utilDate.monthNames.join("|") + ")" + }; + }, + M: function() { + for (var a = [], i = 0; i < 12; a.push(utilDate.getShortMonthName(i)), ++i); // get localised short month names + return Ext.applyIf({ + s:"(" + a.join("|") + ")" + }, utilDate.formatCodeToRegex("F")); + }, + m: { + g:1, + c:"m = parseInt(results[{0}], 10) - 1;\n", + s:"(1[0-2]|0[1-9])" // month number with leading zeros (01 - 12) + }, + n: { + g:1, + c:"m = parseInt(results[{0}], 10) - 1;\n", + s:"(1[0-2]|[1-9])" // 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 utilDate.formatCodeToRegex("Y"); + }, + Y: { + g:1, + c:"y = parseInt(results[{0}], 10);\n", + s:"(\\d{4})" // 4-digit year + }, + y: { + g:1, + c:"var ty = parseInt(results[{0}], 10);\n" + + "y = ty > Ext.Date.y2kYear ? 1900 + ty : 2000 + ty;\n", // 2-digit year + s:"(\\d{1,2})" + }, + /* + * In the am/pm parsing routines, we allow both upper and lower case + * even though it doesn't exactly match the spec. It gives much more flexibility + * in being able to specify case insensitive regexes. + */ + // + a: { + 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)", + calcAtEnd: true + }, + // + // + A: { + 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)", + calcAtEnd: true + }, + // + g: { + g:1, + c:"h = parseInt(results[{0}], 10);\n", + s:"(1[0-2]|[0-9])" // 12-hr format of an hour without leading zeroes (1 - 12) + }, + G: { + g:1, + c:"h = parseInt(results[{0}], 10);\n", + s:"(2[0-3]|1[0-9]|[0-9])" // 24-hr format of an hour without leading zeroes (0 - 23) + }, + h: { + g:1, + c:"h = parseInt(results[{0}], 10);\n", + s:"(1[0-2]|0[1-9])" // 12-hr format of an hour with leading zeroes (01 - 12) + }, + H: { + g:1, + c:"h = parseInt(results[{0}], 10);\n", + s:"(2[0-3]|[0-1][0-9])" // 24-hr format of an hour with leading zeroes (00 - 23) + }, + i: { + g:1, + c:"i = parseInt(results[{0}], 10);\n", + s:"([0-5][0-9])" // minutes with leading zeros (00 - 59) + }, + s: { + g:1, + c:"s = parseInt(results[{0}], 10);\n", + s:"([0-5][0-9])" // seconds with leading zeros (00 - 59) + }, + u: { + g:1, + c:"ms = results[{0}]; ms = parseInt(ms, 10)/Math.pow(10, ms.length - 3);\n", + s:"(\\d+)" // decimal fraction of a second (minimum = 1 digit, maximum = unlimited) + }, + O: { + g:1, + c:[ + "o = results[{0}];", + "var sn = o.substring(0,1),", // get + / - sign + "hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60),", // get hours (performs minutes-to-hour conversion also, just in case) + "mn = o.substring(3,5) % 60;", // get minutes + "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))? (sn + Ext.String.leftPad(hr, 2, '0') + Ext.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 + Ext.String.leftPad(hr, 2, '0') + Ext.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 = [ + utilDate.formatCodeToRegex("Y", 1), // year + utilDate.formatCodeToRegex("m", 2), // month + utilDate.formatCodeToRegex("d", 3), // day + utilDate.formatCodeToRegex("H", 4), // hour + utilDate.formatCodeToRegex("i", 5), // minute + utilDate.formatCodeToRegex("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){", + utilDate.formatCodeToRegex("P", 8).c, // timezone offset with colon separator + "}else{", + utilDate.formatCodeToRegex("O", 8).c, // timezone offset without colon separator + "}", + "}" + ].join('\n')} + ], + i, + l; + + for (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 + } + }, + + //Old Ext.Date prototype methods. + // private + dateFormat: function(date, format) { + return utilDate.format(date, format); + }, + + /** + * Compares if two dates are equal by comparing their values. + * @param {Date} date1 + * @param {Date} date2 + * @return {Boolean} True if the date values are equal + */ + isEqual: function(date1, date2) { + // check we have 2 date objects + if (date1 && date2) { + return (date1.getTime() === date2.getTime()); + } + // one or both isn't a date, only equal if both are falsey + return !(date1 || date2); + }, + + /** + * Formats a date given the supplied format string. + * @param {Date} date The date to format + * @param {String} format The format string + * @return {String} The formatted date or an empty string if date parameter is not a JavaScript Date object + */ + format: function(date, format) { + var formatFunctions = utilDate.formatFunctions; + + if (!Ext.isDate(date)) { + return ''; + } + + if (formatFunctions[format] == null) { + utilDate.createFormat(format); + } + + return formatFunctions[format].call(date) + ''; + }, + + /** + * 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. + * @param {Date} date The date + * @return {String} The abbreviated timezone name (e.g. 'CST', 'PDT', 'EDT', 'MPST' ...). + */ + getTimezone : function(date) { + // 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 date.toString().replace(/^.* (?:\((.*)\)|([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?)$/, "$1$2").replace(/[^A-Z]/g, ""); + }, + + /** + * Get the offset from GMT of the current date (equivalent to the format specifier 'O'). + * @param {Date} date The date + * @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(date, colon) { + var offset = date.getTimezoneOffset(); + return (offset > 0 ? "-" : "+") + + Ext.String.leftPad(Math.floor(Math.abs(offset) / 60), 2, "0") + + (colon ? ":" : "") + + Ext.String.leftPad(Math.abs(offset % 60), 2, "0"); + }, + + /** + * Get the numeric day number of the year, adjusted for leap year. + * @param {Date} date The date + * @return {Number} 0 to 364 (365 in leap years). + */ + getDayOfYear: function(date) { + var num = 0, + d = Ext.Date.clone(date), + m = date.getMonth(), + i; + + for (i = 0, d.setDate(1), d.setMonth(0); i < m; d.setMonth(++i)) { + num += utilDate.getDaysInMonth(d); + } + return num + date.getDate() - 1; + }, + + /** + * Get the numeric ISO-8601 week number of the year. + * (equivalent to the format specifier 'W', but without a leading zero). + * @param {Date} date The date + * @return {Number} 1 to 53 + * @method + */ + getWeekOfYear : (function() { + // adapted from http://www.merlyn.demon.co.uk/weekcalc.htm + var ms1d = 864e5, // milliseconds in a day + ms7d = 7 * ms1d; // milliseconds in a week + + return function(date) { // return a closure so constants get calculated only once + var DC3 = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate() + 3) / ms1d, // an Absolute Day Number + AWN = Math.floor(DC3 / 7), // an Absolute Week Number + Wyr = new Date(AWN * ms7d).getUTCFullYear(); + + return AWN - Math.floor(Date.UTC(Wyr, 0, 7) / ms7d) + 1; + }; + }()), + + /** + * Checks if the current date falls within a leap year. + * @param {Date} date The date + * @return {Boolean} True if the current date falls within a leap year, false otherwise. + */ + isLeapYear : function(date) { + var year = date.getFullYear(); + return !!((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year))); + }, + + /** + * Get the first day of the current month, adjusted for leap year. The returned value + * is the numeric day index within the week (0-6) which can be used in conjunction with + * the {@link #monthNames} array to retrieve the textual day name. + * Example: + *
    
    +var dt = new Date('1/10/2007'),
    +    firstDay = Ext.Date.getFirstDayOfMonth(dt);
    +console.log(Ext.Date.dayNames[firstDay]); //output: 'Monday'
    +     * 
    + * @param {Date} date The date + * @return {Number} The day number (0-6). + */ + getFirstDayOfMonth : function(date) { + var day = (date.getDay() - (date.getDate() - 1)) % 7; + return (day < 0) ? (day + 7) : day; + }, + + /** + * Get the last day of the current month, adjusted for leap year. The returned value + * is the numeric day index within the week (0-6) which can be used in conjunction with + * the {@link #monthNames} array to retrieve the textual day name. + * Example: + *
    
    +var dt = new Date('1/10/2007'),
    +    lastDay = Ext.Date.getLastDayOfMonth(dt);
    +console.log(Ext.Date.dayNames[lastDay]); //output: 'Wednesday'
    +     * 
    + * @param {Date} date The date + * @return {Number} The day number (0-6). + */ + getLastDayOfMonth : function(date) { + return utilDate.getLastDateOfMonth(date).getDay(); + }, + + + /** + * Get the date of the first day of the month in which this date resides. + * @param {Date} date The date + * @return {Date} + */ + getFirstDateOfMonth : function(date) { + return new Date(date.getFullYear(), date.getMonth(), 1); + }, + + /** + * Get the date of the last day of the month in which this date resides. + * @param {Date} date The date + * @return {Date} + */ + getLastDateOfMonth : function(date) { + return new Date(date.getFullYear(), date.getMonth(), utilDate.getDaysInMonth(date)); + }, + + /** + * Get the number of days in the current month, adjusted for leap year. + * @param {Date} date The date + * @return {Number} The number of days in the month. + * @method + */ + getDaysInMonth: (function() { + var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + + return function(date) { // return a closure for efficiency + var m = date.getMonth(); + + return m == 1 && utilDate.isLeapYear(date) ? 29 : daysInMonth[m]; + }; + }()), + + // + /** + * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S'). + * @param {Date} date The date + * @return {String} 'st, 'nd', 'rd' or 'th'. + */ + getSuffix : function(date) { + switch (date.getDate()) { + case 1: + case 21: + case 31: + return "st"; + case 2: + case 22: + return "nd"; + case 3: + case 23: + return "rd"; + default: + return "th"; + } + }, + // + + /** + * Creates and returns a new Date instance with the exact same date value as the called instance. + * Dates are copied and passed by reference, so if a copied date variable is modified later, the original + * variable will also be changed. When the intention is to create a new variable that will not + * modify the original instance, you should create a clone. + * + * Example of correctly cloning a date: + *
    
    +//wrong way:
    +var orig = new Date('10/1/2006');
    +var copy = orig;
    +copy.setDate(5);
    +console.log(orig);  //returns 'Thu Oct 05 2006'!
    +
    +//correct way:
    +var orig = new Date('10/1/2006'),
    +    copy = Ext.Date.clone(orig);
    +copy.setDate(5);
    +console.log(orig);  //returns 'Thu Oct 01 2006'
    +     * 
    + * @param {Date} date The date + * @return {Date} The new Date instance. + */ + clone : function(date) { + return new Date(date.getTime()); + }, + + /** + * Checks if the current date is affected by Daylight Saving Time (DST). + * @param {Date} date The date + * @return {Boolean} True if the current date is affected by DST. + */ + isDST : function(date) { + // adapted from http://sencha.com/forum/showthread.php?p=247172#post247172 + // courtesy of @geoffrey.mcgill + return new Date(date.getFullYear(), 0, 1).getTimezoneOffset() != date.getTimezoneOffset(); + }, + + /** + * Attempts to clear all time information from this Date by setting the time to midnight of the same day, + * automatically adjusting for Daylight Saving Time (DST) where applicable. + * (note: DST timezone information for the browser's host operating system is assumed to be up-to-date) + * @param {Date} date The 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(date, clone) { + if (clone) { + return Ext.Date.clearTime(Ext.Date.clone(date)); + } + + // get current date before clearing time + var d = date.getDate(), + hr, + c; + + // clear time + date.setHours(0); + date.setMinutes(0); + date.setSeconds(0); + date.setMilliseconds(0); + + if (date.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 (hr = 1, c = utilDate.add(date, Ext.Date.HOUR, hr); c.getDate() != d; hr++, c = utilDate.add(date, Ext.Date.HOUR, hr)); + + date.setDate(d); + date.setHours(c.getHours()); + } + + return date; + }, + + /** + * 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 = Ext.Date.add(new Date('10/29/2006'), Ext.Date.DAY, 5);
    +console.log(dt); //returns 'Fri Nov 03 2006 00:00:00'
    +
    +// Negative values will be subtracted:
    +var dt2 = Ext.Date.add(new Date('10/1/2006'), Ext.Date.DAY, -5);
    +console.log(dt2); //returns 'Tue Sep 26 2006 00:00:00'
    +
    +     * 
    + * + * @param {Date} date The date to modify + * @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(date, interval, value) { + var d = Ext.Date.clone(date), + Date = Ext.Date, + day; + if (!interval || value === 0) { + return d; + } + + switch(interval.toLowerCase()) { + case Ext.Date.MILLI: + d.setMilliseconds(d.getMilliseconds() + value); + break; + case Ext.Date.SECOND: + d.setSeconds(d.getSeconds() + value); + break; + case Ext.Date.MINUTE: + d.setMinutes(d.getMinutes() + value); + break; + case Ext.Date.HOUR: + d.setHours(d.getHours() + value); + break; + case Ext.Date.DAY: + d.setDate(d.getDate() + value); + break; + case Ext.Date.MONTH: + day = date.getDate(); + if (day > 28) { + day = Math.min(day, Ext.Date.getLastDateOfMonth(Ext.Date.add(Ext.Date.getFirstDateOfMonth(date), Ext.Date.MONTH, value)).getDate()); + } + d.setDate(day); + d.setMonth(date.getMonth() + value); + break; + case Ext.Date.YEAR: + day = date.getDate(); + if (day > 28) { + day = Math.min(day, Ext.Date.getLastDateOfMonth(Ext.Date.add(Ext.Date.getFirstDateOfMonth(date), Ext.Date.YEAR, value)).getDate()); + } + d.setDate(day); + d.setFullYear(date.getFullYear() + value); + break; + } + return d; + }, + + /** + * Checks if a date falls on or between the given start and end dates. + * @param {Date} date The date to check + * @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(date, start, end) { + var t = date.getTime(); + return start.getTime() <= t && t <= end.getTime(); + }, + + //Maintains compatibility with old static and prototype window.Date methods. + compat: function() { + var nativeDate = window.Date, + p, u, + statics = ['useStrict', 'formatCodeToRegex', 'parseFunctions', 'parseRegexes', 'formatFunctions', 'y2kYear', 'MILLI', 'SECOND', 'MINUTE', 'HOUR', 'DAY', 'MONTH', 'YEAR', 'defaults', 'dayNames', 'monthNames', 'monthNumbers', 'getShortMonthName', 'getShortDayName', 'getMonthNumber', 'formatCodes', 'isValid', 'parseDate', 'getFormatCode', 'createFormat', 'createParser', 'parseCodes'], + proto = ['dateFormat', 'format', 'getTimezone', 'getGMTOffset', 'getDayOfYear', 'getWeekOfYear', 'isLeapYear', 'getFirstDayOfMonth', 'getLastDayOfMonth', 'getDaysInMonth', 'getSuffix', 'clone', 'isDST', 'clearTime', 'add', 'between'], + sLen = statics.length, + pLen = proto.length, + stat, prot, s; + + //Append statics + for (s = 0; s < sLen; s++) { + stat = statics[s]; + nativeDate[stat] = utilDate[stat]; + } + + //Append to prototype + for (p = 0; p < pLen; p++) { + prot = proto[p]; + nativeDate.prototype[prot] = function() { + var args = Array.prototype.slice.call(arguments); + args.unshift(this); + return utilDate[prot].apply(utilDate, args); + }; + } + } +}; + +var utilDate = Ext.Date; + +}()); + +/** + * @author Jacky Nguyen + * @docauthor Jacky Nguyen + * @class Ext.Base + * + * The root of all classes created with {@link Ext#define}. + * + * Ext.Base is the building block of all Ext classes. All classes in Ext inherit from Ext.Base. + * All prototype and static members of this class are inherited by all other classes. + */ +(function(flexSetter) { + +var noArgs = [], + Base = function(){}; + + // These static properties will be copied to every newly created class with {@link Ext#define} + Ext.apply(Base, { + $className: 'Ext.Base', + + $isClass: true, + + /** + * Create a new instance of this Class. + * + * Ext.define('My.cool.Class', { + * ... + * }); + * + * My.cool.Class.create({ + * someConfig: true + * }); + * + * All parameters are passed to the constructor of the class. + * + * @return {Object} the created instance. + * @static + * @inheritable + */ + create: function() { + return Ext.create.apply(Ext, [this].concat(Array.prototype.slice.call(arguments, 0))); + }, + + /** + * @private + * @param config + */ + extend: function(parent) { + var parentPrototype = parent.prototype, + basePrototype, prototype, i, ln, name, statics; + + prototype = this.prototype = Ext.Object.chain(parentPrototype); + prototype.self = this; + + this.superclass = prototype.superclass = parentPrototype; + + if (!parent.$isClass) { + basePrototype = Ext.Base.prototype; + + for (i in basePrototype) { + if (i in prototype) { + prototype[i] = basePrototype[i]; + } + } + } + + // Statics inheritance + statics = parentPrototype.$inheritableStatics; + + if (statics) { + for (i = 0,ln = statics.length; i < ln; i++) { + name = statics[i]; + + if (!this.hasOwnProperty(name)) { + this[name] = parent[name]; + } + } + } + + if (parent.$onExtended) { + this.$onExtended = parent.$onExtended.slice(); + } + + prototype.config = new prototype.configClass(); + prototype.initConfigList = prototype.initConfigList.slice(); + prototype.initConfigMap = Ext.clone(prototype.initConfigMap); + prototype.configMap = Ext.Object.chain(prototype.configMap); + }, + + /** + * @private + */ + $onExtended: [], + + /** + * @private + */ + triggerExtended: function() { + var callbacks = this.$onExtended, + ln = callbacks.length, + i, callback; + + if (ln > 0) { + for (i = 0; i < ln; i++) { + callback = callbacks[i]; + callback.fn.apply(callback.scope || this, arguments); + } + } + }, + + /** + * @private + */ + onExtended: function(fn, scope) { + this.$onExtended.push({ + fn: fn, + scope: scope + }); + + return this; + }, + + /** + * @private + * @param config + */ + addConfig: function(config, fullMerge) { + var prototype = this.prototype, + configNameCache = Ext.Class.configNameCache, + hasConfig = prototype.configMap, + initConfigList = prototype.initConfigList, + initConfigMap = prototype.initConfigMap, + defaultConfig = prototype.config, + initializedName, name, value; + + for (name in config) { + if (config.hasOwnProperty(name)) { + if (!hasConfig[name]) { + hasConfig[name] = true; + } + + value = config[name]; + + initializedName = configNameCache[name].initialized; + + if (!initConfigMap[name] && value !== null && !prototype[initializedName]) { + initConfigMap[name] = true; + initConfigList.push(name); + } + } + } + + if (fullMerge) { + Ext.merge(defaultConfig, config); + } + else { + Ext.mergeIf(defaultConfig, config); + } + + prototype.configClass = Ext.Object.classify(defaultConfig); + }, + + /** + * Add / override static properties of this class. + * + * Ext.define('My.cool.Class', { + * ... + * }); + * + * My.cool.Class.addStatics({ + * someProperty: 'someValue', // My.cool.Class.someProperty = 'someValue' + * method1: function() { ... }, // My.cool.Class.method1 = function() { ... }; + * method2: function() { ... } // My.cool.Class.method2 = function() { ... }; + * }); + * + * @param {Object} members + * @return {Ext.Base} this + * @static + * @inheritable + */ + addStatics: function(members) { + var member, name; + + for (name in members) { + if (members.hasOwnProperty(name)) { + member = members[name]; + if (typeof member == 'function') { + member.displayName = Ext.getClassName(this) + '.' + name; + } + this[name] = member; + } + } + + return this; + }, + + /** + * @private + * @param {Object} members + */ + addInheritableStatics: function(members) { + var inheritableStatics, + hasInheritableStatics, + prototype = this.prototype, + name, member; + + inheritableStatics = prototype.$inheritableStatics; + hasInheritableStatics = prototype.$hasInheritableStatics; + + if (!inheritableStatics) { + inheritableStatics = prototype.$inheritableStatics = []; + hasInheritableStatics = prototype.$hasInheritableStatics = {}; + } + + for (name in members) { + if (members.hasOwnProperty(name)) { + member = members[name]; + if (typeof member == 'function') { + member.displayName = Ext.getClassName(this) + '.' + name; + } + this[name] = member; + + if (!hasInheritableStatics[name]) { + hasInheritableStatics[name] = true; + inheritableStatics.push(name); + } + } + } + + return this; + }, + + /** + * Add methods / properties to the prototype of this class. + * + * Ext.define('My.awesome.Cat', { + * constructor: function() { + * ... + * } + * }); + * + * My.awesome.Cat.implement({ + * meow: function() { + * alert('Meowww...'); + * } + * }); + * + * var kitty = new My.awesome.Cat; + * kitty.meow(); + * + * @param {Object} members + * @static + * @inheritable + */ + addMembers: function(members) { + var prototype = this.prototype, + enumerables = Ext.enumerables, + names = [], + i, ln, name, member; + + for (name in members) { + names.push(name); + } + + if (enumerables) { + names.push.apply(names, enumerables); + } + + for (i = 0,ln = names.length; i < ln; i++) { + name = names[i]; + + if (members.hasOwnProperty(name)) { + member = members[name]; + + if (typeof member == 'function' && !member.$isClass && member !== Ext.emptyFn) { + member.$owner = this; + member.$name = name; + member.displayName = (this.$className || '') + '#' + name; + } + + prototype[name] = member; + } + } + + return this; + }, + + /** + * @private + * @param name + * @param member + */ + addMember: function(name, member) { + if (typeof member == 'function' && !member.$isClass && member !== Ext.emptyFn) { + member.$owner = this; + member.$name = name; + member.displayName = (this.$className || '') + '#' + name; + } + + this.prototype[name] = member; + + return this; + }, + + /** + * @private + */ + implement: function() { + this.addMembers.apply(this, arguments); + }, + + /** + * Borrow another class' members to the prototype of this class. + * + * Ext.define('Bank', { + * money: '$$$', + * printMoney: function() { + * alert('$$$$$$$'); + * } + * }); + * + * Ext.define('Thief', { + * ... + * }); + * + * Thief.borrow(Bank, ['money', 'printMoney']); + * + * var steve = new Thief(); + * + * alert(steve.money); // alerts '$$$' + * steve.printMoney(); // alerts '$$$$$$$' + * + * @param {Ext.Base} fromClass The class to borrow members from + * @param {Array/String} members The names of the members to borrow + * @return {Ext.Base} this + * @static + * @inheritable + * @private + */ + borrow: function(fromClass, members) { + var prototype = this.prototype, + fromPrototype = fromClass.prototype, + className = Ext.getClassName(this), + i, ln, name, fn, toBorrow; + + members = Ext.Array.from(members); + + for (i = 0,ln = members.length; i < ln; i++) { + name = members[i]; + + toBorrow = fromPrototype[name]; + + if (typeof toBorrow == 'function') { + fn = Ext.Function.clone(toBorrow); + + if (className) { + fn.displayName = className + '#' + name; + } + + fn.$owner = this; + fn.$name = name; + + prototype[name] = fn; + } + else { + prototype[name] = toBorrow; + } + } + + return this; + }, + + /** + * Override members of this class. Overridden methods can be invoked via + * {@link Ext.Base#callParent}. + * + * Ext.define('My.Cat', { + * constructor: function() { + * alert("I'm a cat!"); + * } + * }); + * + * My.Cat.override({ + * constructor: function() { + * alert("I'm going to be a cat!"); + * + * this.callParent(arguments); + * + * alert("Meeeeoooowwww"); + * } + * }); + * + * var kitty = new My.Cat(); // alerts "I'm going to be a cat!" + * // alerts "I'm a cat!" + * // alerts "Meeeeoooowwww" + * + * As of 4.1, direct use of this method is deprecated. Use {@link Ext#define Ext.define} + * instead: + * + * Ext.define('My.CatOverride', { + * override: 'My.Cat', + * constructor: function() { + * alert("I'm going to be a cat!"); + * + * this.callParent(arguments); + * + * alert("Meeeeoooowwww"); + * } + * }); + * + * The above accomplishes the same result but can be managed by the {@link Ext.Loader} + * which can properly order the override and its target class and the build process + * can determine whether the override is needed based on the required state of the + * target class (My.Cat). + * + * @param {Object} members The properties to add to this class. This should be + * specified as an object literal containing one or more properties. + * @return {Ext.Base} this class + * @static + * @inheritable + * @markdown + * @deprecated 4.1.0 Use {@link Ext#define Ext.define} instead + */ + override: function(members) { + var me = this, + enumerables = Ext.enumerables, + target = me.prototype, + cloneFunction = Ext.Function.clone, + name, index, member, statics, names, previous; + + if (arguments.length === 2) { + name = members; + members = {}; + members[name] = arguments[1]; + enumerables = null; + } + + do { + names = []; // clean slate for prototype (1st pass) and static (2nd pass) + statics = null; // not needed 1st pass, but needs to be cleared for 2nd pass + + for (name in members) { // hasOwnProperty is checked in the next loop... + if (name == 'statics') { + statics = members[name]; + } else if (name == 'config') { + me.addConfig(members[name], true); + } else { + names.push(name); + } + } + + if (enumerables) { + names.push.apply(names, enumerables); + } + + for (index = names.length; index--; ) { + name = names[index]; + + if (members.hasOwnProperty(name)) { + member = members[name]; + + if (typeof member == 'function' && !member.$className && member !== Ext.emptyFn) { + if (typeof member.$owner != 'undefined') { + member = cloneFunction(member); + } + + if (me.$className) { + member.displayName = me.$className + '#' + name; + } + + member.$owner = me; + member.$name = name; + + previous = target[name]; + if (previous) { + member.$previous = previous; + } + } + + target[name] = member; + } + } + + target = me; // 2nd pass is for statics + members = statics; // statics will be null on 2nd pass + } while (members); + + return this; + }, + + // Documented downwards + callParent: function(args) { + var method; + + // This code is intentionally inlined for the least number of debugger stepping + return (method = this.callParent.caller) && (method.$previous || + ((method = method.$owner ? method : method.caller) && + method.$owner.superclass.$class[method.$name])).apply(this, args || noArgs); + }, + + /** + * Used internally by the mixins pre-processor + * @private + * @inheritable + */ + mixin: function(name, mixinClass) { + var mixin = mixinClass.prototype, + prototype = this.prototype, + key; + + if (typeof mixin.onClassMixedIn != 'undefined') { + mixin.onClassMixedIn.call(mixinClass, this); + } + + if (!prototype.hasOwnProperty('mixins')) { + if ('mixins' in prototype) { + prototype.mixins = Ext.Object.chain(prototype.mixins); + } + else { + prototype.mixins = {}; + } + } + + for (key in mixin) { + if (key === 'mixins') { + Ext.merge(prototype.mixins, mixin[key]); + } + else if (typeof prototype[key] == 'undefined' && key != 'mixinId' && key != 'config') { + prototype[key] = mixin[key]; + } + } + + if ('config' in mixin) { + this.addConfig(mixin.config, false); + } + + prototype.mixins[name] = mixin; + }, + + /** + * Get the current class' name in string format. + * + * Ext.define('My.cool.Class', { + * constructor: function() { + * alert(this.self.getName()); // alerts 'My.cool.Class' + * } + * }); + * + * My.cool.Class.getName(); // 'My.cool.Class' + * + * @return {String} className + * @static + * @inheritable + */ + getName: function() { + return Ext.getClassName(this); + }, + + /** + * Create aliases for existing prototype methods. Example: + * + * Ext.define('My.cool.Class', { + * method1: function() { ... }, + * method2: function() { ... } + * }); + * + * var test = new My.cool.Class(); + * + * My.cool.Class.createAlias({ + * method3: 'method1', + * method4: 'method2' + * }); + * + * test.method3(); // test.method1() + * + * My.cool.Class.createAlias('method5', 'method3'); + * + * test.method5(); // test.method3() -> test.method1() + * + * @param {String/Object} alias The new method name, or an object to set multiple aliases. See + * {@link Ext.Function#flexSetter flexSetter} + * @param {String/Object} origin The original method name + * @static + * @inheritable + * @method + */ + createAlias: flexSetter(function(alias, origin) { + this.override(alias, function() { + return this[origin].apply(this, arguments); + }); + }), + + /** + * @private + */ + addXtype: function(xtype) { + var prototype = this.prototype, + xtypesMap = prototype.xtypesMap, + xtypes = prototype.xtypes, + xtypesChain = prototype.xtypesChain; + + if (!prototype.hasOwnProperty('xtypesMap')) { + xtypesMap = prototype.xtypesMap = Ext.merge({}, prototype.xtypesMap || {}); + xtypes = prototype.xtypes = prototype.xtypes ? [].concat(prototype.xtypes) : []; + xtypesChain = prototype.xtypesChain = prototype.xtypesChain ? [].concat(prototype.xtypesChain) : []; + prototype.xtype = xtype; + } + + if (!xtypesMap[xtype]) { + xtypesMap[xtype] = true; + xtypes.push(xtype); + xtypesChain.push(xtype); + Ext.ClassManager.setAlias(this, 'widget.' + xtype); + } + + return this; + } + }); + + Base.implement({ + isInstance: true, + + $className: 'Ext.Base', + + configClass: Ext.emptyFn, + + initConfigList: [], + + configMap: {}, + + initConfigMap: {}, + + /** + * Get the reference to the class from which this object was instantiated. Note that unlike {@link Ext.Base#self}, + * `this.statics()` is scope-independent and it always returns the class from which it was called, regardless of what + * `this` points to during run-time + * + * Ext.define('My.Cat', { + * statics: { + * totalCreated: 0, + * speciesName: 'Cat' // My.Cat.speciesName = 'Cat' + * }, + * + * constructor: function() { + * var statics = this.statics(); + * + * alert(statics.speciesName); // always equals to 'Cat' no matter what 'this' refers to + * // equivalent to: My.Cat.speciesName + * + * alert(this.self.speciesName); // dependent on 'this' + * + * statics.totalCreated++; + * }, + * + * clone: function() { + * var cloned = new this.self; // dependent on 'this' + * + * cloned.groupName = this.statics().speciesName; // equivalent to: My.Cat.speciesName + * + * return cloned; + * } + * }); + * + * + * Ext.define('My.SnowLeopard', { + * extend: 'My.Cat', + * + * statics: { + * speciesName: 'Snow Leopard' // My.SnowLeopard.speciesName = 'Snow Leopard' + * }, + * + * constructor: function() { + * this.callParent(); + * } + * }); + * + * var cat = new My.Cat(); // alerts 'Cat', then alerts 'Cat' + * + * var snowLeopard = new My.SnowLeopard(); // alerts 'Cat', then alerts 'Snow Leopard' + * + * var clone = snowLeopard.clone(); + * alert(Ext.getClassName(clone)); // alerts 'My.SnowLeopard' + * alert(clone.groupName); // alerts 'Cat' + * + * alert(My.Cat.totalCreated); // alerts 3 + * + * @protected + * @return {Ext.Class} + */ + statics: function() { + var method = this.statics.caller, + self = this.self; + + if (!method) { + return self; + } + + return method.$owner; + }, + + /** + * Call the "parent" method of the current method. That is the method previously + * overridden by derivation or by an override (see {@link Ext#define}). + * + * Ext.define('My.Base', { + * constructor: function (x) { + * this.x = x; + * }, + * + * statics: { + * method: function (x) { + * return x; + * } + * } + * }); + * + * Ext.define('My.Derived', { + * extend: 'My.Base', + * + * constructor: function () { + * this.callParent([21]); + * } + * }); + * + * var obj = new My.Derived(); + * + * alert(obj.x); // alerts 21 + * + * This can be used with an override as follows: + * + * Ext.define('My.DerivedOverride', { + * override: 'My.Derived', + * + * constructor: function (x) { + * this.callParent([x*2]); // calls original My.Derived constructor + * } + * }); + * + * var obj = new My.Derived(); + * + * alert(obj.x); // now alerts 42 + * + * This also works with static methods. + * + * Ext.define('My.Derived2', { + * extend: 'My.Base', + * + * statics: { + * method: function (x) { + * return this.callParent([x*2]); // calls My.Base.method + * } + * } + * }); + * + * alert(My.Base.method(10); // alerts 10 + * alert(My.Derived2.method(10); // alerts 20 + * + * Lastly, it also works with overridden static methods. + * + * Ext.define('My.Derived2Override', { + * override: 'My.Derived2', + * + * statics: { + * method: function (x) { + * return this.callParent([x*2]); // calls My.Derived2.method + * } + * } + * }); + * + * alert(My.Derived2.method(10); // now alerts 40 + * + * @protected + * @param {Array/Arguments} args The arguments, either an array or the `arguments` object + * from the current method, for example: `this.callParent(arguments)` + * @return {Object} Returns the result of calling the parent method + */ + callParent: function(args) { + // NOTE: this code is deliberately as few expressions (and no function calls) + // as possible so that a debugger can skip over this noise with the minimum number + // of steps. Basically, just hit Step Into until you are where you really wanted + // to be. + var method, + superMethod = (method = this.callParent.caller) && (method.$previous || + ((method = method.$owner ? method : method.caller) && + method.$owner.superclass[method.$name])); + + if (!superMethod) { + method = this.callParent.caller; + var parentClass, methodName; + + if (!method.$owner) { + if (!method.caller) { + throw new Error("Attempting to call a protected method from the public scope, which is not allowed"); + } + + method = method.caller; + } + + parentClass = method.$owner.superclass; + methodName = method.$name; + + if (!(methodName in parentClass)) { + throw new Error("this.callParent() was called but there's no such method (" + methodName + + ") found in the parent class (" + (Ext.getClassName(parentClass) || 'Object') + ")"); + } + } + + return superMethod.apply(this, args || noArgs); + }, + + /** + * @property {Ext.Class} self + * + * Get the reference to the current class from which this object was instantiated. Unlike {@link Ext.Base#statics}, + * `this.self` is scope-dependent and it's meant to be used for dynamic inheritance. See {@link Ext.Base#statics} + * for a detailed comparison + * + * Ext.define('My.Cat', { + * statics: { + * speciesName: 'Cat' // My.Cat.speciesName = 'Cat' + * }, + * + * constructor: function() { + * alert(this.self.speciesName); // dependent on 'this' + * }, + * + * clone: function() { + * return new this.self(); + * } + * }); + * + * + * Ext.define('My.SnowLeopard', { + * extend: 'My.Cat', + * statics: { + * speciesName: 'Snow Leopard' // My.SnowLeopard.speciesName = 'Snow Leopard' + * } + * }); + * + * var cat = new My.Cat(); // alerts 'Cat' + * var snowLeopard = new My.SnowLeopard(); // alerts 'Snow Leopard' + * + * var clone = snowLeopard.clone(); + * alert(Ext.getClassName(clone)); // alerts 'My.SnowLeopard' + * + * @protected + */ + self: Base, + + // Default constructor, simply returns `this` + constructor: function() { + return this; + }, + + /** + * Initialize configuration for this class. a typical example: + * + * Ext.define('My.awesome.Class', { + * // The default config + * config: { + * name: 'Awesome', + * isAwesome: true + * }, + * + * constructor: function(config) { + * this.initConfig(config); + * } + * }); + * + * var awesome = new My.awesome.Class({ + * name: 'Super Awesome' + * }); + * + * alert(awesome.getName()); // 'Super Awesome' + * + * @protected + * @param {Object} config + * @return {Object} mixins The mixin prototypes as key - value pairs + */ + initConfig: function(config) { + var instanceConfig = config, + configNameCache = Ext.Class.configNameCache, + defaultConfig = new this.configClass(), + defaultConfigList = this.initConfigList, + hasConfig = this.configMap, + nameMap, i, ln, name, initializedName; + + this.initConfig = Ext.emptyFn; + + this.initialConfig = instanceConfig || {}; + + this.config = config = (instanceConfig) ? Ext.merge(defaultConfig, config) : defaultConfig; + + if (instanceConfig) { + defaultConfigList = defaultConfigList.slice(); + + for (name in instanceConfig) { + if (hasConfig[name]) { + if (instanceConfig[name] !== null) { + defaultConfigList.push(name); + this[configNameCache[name].initialized] = false; + } + } + } + } + + for (i = 0,ln = defaultConfigList.length; i < ln; i++) { + name = defaultConfigList[i]; + nameMap = configNameCache[name]; + initializedName = nameMap.initialized; + + if (!this[initializedName]) { + this[initializedName] = true; + this[nameMap.set].call(this, config[name]); + } + } + + return this; + }, + + /** + * @private + * @param config + */ + hasConfig: function(name) { + return Boolean(this.configMap[name]); + }, + + /** + * @private + */ + setConfig: function(config, applyIfNotSet) { + if (!config) { + return this; + } + + var configNameCache = Ext.Class.configNameCache, + currentConfig = this.config, + hasConfig = this.configMap, + initialConfig = this.initialConfig, + name, value; + + applyIfNotSet = Boolean(applyIfNotSet); + + for (name in config) { + if (applyIfNotSet && initialConfig.hasOwnProperty(name)) { + continue; + } + + value = config[name]; + currentConfig[name] = value; + + if (hasConfig[name]) { + this[configNameCache[name].set](value); + } + } + + return this; + }, + + /** + * @private + * @param name + */ + getConfig: function(name) { + var configNameCache = Ext.Class.configNameCache; + + return this[configNameCache[name].get](); + }, + + /** + * + * @param name + */ + getInitialConfig: function(name) { + var config = this.config; + + if (!name) { + return config; + } + else { + return config[name]; + } + }, + + /** + * @private + * @param names + * @param callback + * @param scope + */ + onConfigUpdate: function(names, callback, scope) { + var self = this.self, + className = self.$className, + i, ln, name, + updaterName, updater, newUpdater; + + names = Ext.Array.from(names); + + scope = scope || this; + + for (i = 0,ln = names.length; i < ln; i++) { + name = names[i]; + updaterName = 'update' + Ext.String.capitalize(name); + updater = this[updaterName] || Ext.emptyFn; + newUpdater = function() { + updater.apply(this, arguments); + scope[callback].apply(scope, arguments); + }; + newUpdater.$name = updaterName; + newUpdater.$owner = self; + newUpdater.displayName = className + '#' + updaterName; + + this[updaterName] = newUpdater; + } + }, + + destroy: function() { + this.destroy = Ext.emptyFn; + } + }); + + /** + * Call the original method that was previously overridden with {@link Ext.Base#override} + * + * Ext.define('My.Cat', { + * constructor: function() { + * alert("I'm a cat!"); + * } + * }); + * + * My.Cat.override({ + * constructor: function() { + * alert("I'm going to be a cat!"); + * + * this.callOverridden(); + * + * alert("Meeeeoooowwww"); + * } + * }); + * + * var kitty = new My.Cat(); // alerts "I'm going to be a cat!" + * // alerts "I'm a cat!" + * // alerts "Meeeeoooowwww" + * + * @param {Array/Arguments} args The arguments, either an array or the `arguments` object + * from the current method, for example: `this.callOverridden(arguments)` + * @return {Object} Returns the result of calling the overridden method + * @protected + * @deprecated as of 4.1. Use {@link #callParent} instead. + */ + Base.prototype.callOverridden = Base.prototype.callParent; + + Ext.Base = Base; + +}(Ext.Function.flexSetter)); + +/** + * @author Jacky Nguyen + * @docauthor Jacky Nguyen + * @class Ext.Class + * + * Handles class creation throughout the framework. This is a low level factory that is used by Ext.ClassManager and generally + * should not be used directly. If you choose to use Ext.Class you will lose out on the namespace, aliasing and depency loading + * features made available by Ext.ClassManager. The only time you would use Ext.Class directly is to create an anonymous class. + * + * If you wish to create a class you should use {@link Ext#define Ext.define} which aliases + * {@link Ext.ClassManager#create Ext.ClassManager.create} to enable namespacing and dynamic dependency resolution. + * + * Ext.Class is the factory and **not** the superclass of everything. For the base class that **all** Ext classes inherit + * from, see {@link Ext.Base}. + */ +(function() { + var ExtClass, + Base = Ext.Base, + baseStaticMembers = [], + baseStaticMember, baseStaticMemberLength; + + for (baseStaticMember in Base) { + if (Base.hasOwnProperty(baseStaticMember)) { + baseStaticMembers.push(baseStaticMember); + } + } + + baseStaticMemberLength = baseStaticMembers.length; + + // Creates a constructor that has nothing extra in its scope chain. + function makeCtor (className) { + function constructor () { + // Opera has some problems returning from a constructor when Dragonfly isn't running. The || null seems to + // be sufficient to stop it misbehaving. Known to be required against 10.53, 11.51 and 11.61. + return this.constructor.apply(this, arguments) || null; + } + if (className) { + constructor.displayName = className; + } + return constructor; + } + + /** + * @method constructor + * Create a new anonymous class. + * + * @param {Object} data An object represent the properties of this class + * @param {Function} onCreated Optional, the callback function to be executed when this class is fully created. + * Note that the creation process can be asynchronous depending on the pre-processors used. + * + * @return {Ext.Base} The newly created class + */ + Ext.Class = ExtClass = function(Class, data, onCreated) { + if (typeof Class != 'function') { + onCreated = data; + data = Class; + Class = null; + } + + if (!data) { + data = {}; + } + + Class = ExtClass.create(Class, data); + + ExtClass.process(Class, data, onCreated); + + return Class; + }; + + Ext.apply(ExtClass, { + /** + * @private + * @param Class + * @param data + * @param hooks + */ + onBeforeCreated: function(Class, data, hooks) { + Class.addMembers(data); + + hooks.onCreated.call(Class, Class); + }, + + /** + * @private + * @param Class + * @param classData + * @param onClassCreated + */ + create: function(Class, data) { + var name, i; + + if (!Class) { + // This "helped" a bit in IE8 when we create 450k instances (3400ms->2700ms), + // but removes some flexibility as a result because overrides cannot override + // the constructor method... kept in case we want to reconsider because it is + // more involved than just use the pass 'constructor' + // + //if (data.hasOwnProperty('constructor')) { + // Class = data.constructor; + // delete data.constructor; + // Class.$owner = Class; + // Class.$name = 'constructor'; + //} else { + Class = makeCtor( + data.$className + ); + //} + } + + for (i = 0; i < baseStaticMemberLength; i++) { + name = baseStaticMembers[i]; + Class[name] = Base[name]; + } + + return Class; + }, + + /** + * @private + * @param Class + * @param data + * @param onCreated + */ + process: function(Class, data, onCreated) { + var preprocessorStack = data.preprocessors || ExtClass.defaultPreprocessors, + registeredPreprocessors = this.preprocessors, + hooks = { + onBeforeCreated: this.onBeforeCreated + }, + preprocessors = [], + preprocessor, preprocessorsProperties, + i, ln, j, subLn, preprocessorProperty, process; + + delete data.preprocessors; + + for (i = 0,ln = preprocessorStack.length; i < ln; i++) { + preprocessor = preprocessorStack[i]; + + if (typeof preprocessor == 'string') { + preprocessor = registeredPreprocessors[preprocessor]; + preprocessorsProperties = preprocessor.properties; + + if (preprocessorsProperties === true) { + preprocessors.push(preprocessor.fn); + } + else if (preprocessorsProperties) { + for (j = 0,subLn = preprocessorsProperties.length; j < subLn; j++) { + preprocessorProperty = preprocessorsProperties[j]; + + if (data.hasOwnProperty(preprocessorProperty)) { + preprocessors.push(preprocessor.fn); + break; + } + } + } + } + else { + preprocessors.push(preprocessor); + } + } + + hooks.onCreated = onCreated ? onCreated : Ext.emptyFn; + hooks.preprocessors = preprocessors; + + this.doProcess(Class, data, hooks); + }, + + doProcess: function(Class, data, hooks){ + var me = this, + preprocessor = hooks.preprocessors.shift(); + + if (!preprocessor) { + hooks.onBeforeCreated.apply(me, arguments); + return; + } + + if (preprocessor.call(me, Class, data, hooks, me.doProcess) !== false) { + me.doProcess(Class, data, hooks); + } + }, + + /** @private */ + preprocessors: {}, + + /** + * Register a new pre-processor to be used during the class creation process + * + * @param {String} name The pre-processor's name + * @param {Function} fn The callback function to be executed. Typical format: + * + * function(cls, data, fn) { + * // Your code here + * + * // Execute this when the processing is finished. + * // Asynchronous processing is perfectly ok + * if (fn) { + * fn.call(this, cls, data); + * } + * }); + * + * @param {Function} fn.cls The created class + * @param {Object} fn.data The set of properties passed in {@link Ext.Class} constructor + * @param {Function} fn.fn The callback function that **must** to be executed when this + * pre-processor finishes, regardless of whether the processing is synchronous or aynchronous. + * @return {Ext.Class} this + * @private + * @static + */ + registerPreprocessor: function(name, fn, properties, position, relativeTo) { + if (!position) { + position = 'last'; + } + + if (!properties) { + properties = [name]; + } + + this.preprocessors[name] = { + name: name, + properties: properties || false, + fn: fn + }; + + this.setDefaultPreprocessorPosition(name, position, relativeTo); + + return this; + }, + + /** + * Retrieve a pre-processor callback function by its name, which has been registered before + * + * @param {String} name + * @return {Function} preprocessor + * @private + * @static + */ + getPreprocessor: function(name) { + return this.preprocessors[name]; + }, + + /** + * @private + */ + getPreprocessors: function() { + return this.preprocessors; + }, + + /** + * @private + */ + defaultPreprocessors: [], + + /** + * Retrieve the array stack of default pre-processors + * @return {Function[]} defaultPreprocessors + * @private + * @static + */ + getDefaultPreprocessors: function() { + return this.defaultPreprocessors; + }, + + /** + * Set the default array stack of default pre-processors + * + * @private + * @param {Array} preprocessors + * @return {Ext.Class} this + * @static + */ + setDefaultPreprocessors: function(preprocessors) { + this.defaultPreprocessors = Ext.Array.from(preprocessors); + + return this; + }, + + /** + * Insert this pre-processor at a specific position in the stack, optionally relative to + * any existing pre-processor. For example: + * + * Ext.Class.registerPreprocessor('debug', function(cls, data, fn) { + * // Your code here + * + * if (fn) { + * fn.call(this, cls, data); + * } + * }).setDefaultPreprocessorPosition('debug', 'last'); + * + * @private + * @param {String} name The pre-processor name. Note that it needs to be registered with + * {@link Ext#registerPreprocessor registerPreprocessor} before this + * @param {String} offset The insertion position. Four possible values are: + * 'first', 'last', or: 'before', 'after' (relative to the name provided in the third argument) + * @param {String} relativeName + * @return {Ext.Class} this + * @static + */ + setDefaultPreprocessorPosition: function(name, offset, relativeName) { + var defaultPreprocessors = this.defaultPreprocessors, + index; + + if (typeof offset == 'string') { + if (offset === 'first') { + defaultPreprocessors.unshift(name); + + return this; + } + else if (offset === 'last') { + defaultPreprocessors.push(name); + + return this; + } + + offset = (offset === 'after') ? 1 : -1; + } + + index = Ext.Array.indexOf(defaultPreprocessors, relativeName); + + if (index !== -1) { + Ext.Array.splice(defaultPreprocessors, Math.max(0, index + offset), 0, name); + } + + return this; + }, + + configNameCache: {}, + + getConfigNameMap: function(name) { + var cache = this.configNameCache, + map = cache[name], + capitalizedName; + + if (!map) { + capitalizedName = name.charAt(0).toUpperCase() + name.substr(1); + + map = cache[name] = { + internal: name, + initialized: '_is' + capitalizedName + 'Initialized', + apply: 'apply' + capitalizedName, + update: 'update' + capitalizedName, + 'set': 'set' + capitalizedName, + 'get': 'get' + capitalizedName, + doSet : 'doSet' + capitalizedName, + changeEvent: name.toLowerCase() + 'change' + }; + } + + return map; + } + }); + + /** + * @cfg {String} extend + * The parent class that this class extends. For example: + * + * Ext.define('Person', { + * say: function(text) { alert(text); } + * }); + * + * Ext.define('Developer', { + * extend: 'Person', + * say: function(text) { this.callParent(["print "+text]); } + * }); + */ + ExtClass.registerPreprocessor('extend', function(Class, data) { + var Base = Ext.Base, + basePrototype = Base.prototype, + extend = data.extend, + Parent, parentPrototype, i; + + delete data.extend; + + if (extend && extend !== Object) { + Parent = extend; + } + else { + Parent = Base; + } + + parentPrototype = Parent.prototype; + + if (!Parent.$isClass) { + for (i in basePrototype) { + if (!parentPrototype[i]) { + parentPrototype[i] = basePrototype[i]; + } + } + } + + Class.extend(Parent); + + Class.triggerExtended.apply(Class, arguments); + + if (data.onClassExtended) { + Class.onExtended(data.onClassExtended, Class); + delete data.onClassExtended; + } + + }, true); + + /** + * @cfg {Object} statics + * List of static methods for this class. For example: + * + * Ext.define('Computer', { + * statics: { + * factory: function(brand) { + * // 'this' in static methods refer to the class itself + * return new this(brand); + * } + * }, + * + * constructor: function() { ... } + * }); + * + * var dellComputer = Computer.factory('Dell'); + */ + ExtClass.registerPreprocessor('statics', function(Class, data) { + Class.addStatics(data.statics); + + delete data.statics; + }); + + /** + * @cfg {Object} inheritableStatics + * List of inheritable static methods for this class. + * Otherwise just like {@link #statics} but subclasses inherit these methods. + */ + ExtClass.registerPreprocessor('inheritableStatics', function(Class, data) { + Class.addInheritableStatics(data.inheritableStatics); + + delete data.inheritableStatics; + }); + + /** + * @cfg {Object} config + * List of configuration options with their default values, for which automatically + * accessor methods are generated. For example: + * + * Ext.define('SmartPhone', { + * config: { + * hasTouchScreen: false, + * operatingSystem: 'Other', + * price: 500 + * }, + * constructor: function(cfg) { + * this.initConfig(cfg); + * } + * }); + * + * var iPhone = new SmartPhone({ + * hasTouchScreen: true, + * operatingSystem: 'iOS' + * }); + * + * iPhone.getPrice(); // 500; + * iPhone.getOperatingSystem(); // 'iOS' + * iPhone.getHasTouchScreen(); // true; + */ + ExtClass.registerPreprocessor('config', function(Class, data) { + var config = data.config, + prototype = Class.prototype; + + delete data.config; + + Ext.Object.each(config, function(name, value) { + var nameMap = ExtClass.getConfigNameMap(name), + internalName = nameMap.internal, + initializedName = nameMap.initialized, + applyName = nameMap.apply, + updateName = nameMap.update, + setName = nameMap.set, + getName = nameMap.get, + hasOwnSetter = (setName in prototype) || data.hasOwnProperty(setName), + hasOwnApplier = (applyName in prototype) || data.hasOwnProperty(applyName), + hasOwnUpdater = (updateName in prototype) || data.hasOwnProperty(updateName), + optimizedGetter, customGetter; + + if (value === null || (!hasOwnSetter && !hasOwnApplier && !hasOwnUpdater)) { + prototype[internalName] = value; + prototype[initializedName] = true; + } + else { + prototype[initializedName] = false; + } + + if (!hasOwnSetter) { + data[setName] = function(value) { + var oldValue = this[internalName], + applier = this[applyName], + updater = this[updateName]; + + if (!this[initializedName]) { + this[initializedName] = true; + } + + if (applier) { + value = applier.call(this, value, oldValue); + } + + if (typeof value != 'undefined') { + this[internalName] = value; + + if (updater && value !== oldValue) { + updater.call(this, value, oldValue); + } + } + + return this; + }; + } + + if (!(getName in prototype) || data.hasOwnProperty(getName)) { + customGetter = data[getName] || false; + + if (customGetter) { + optimizedGetter = function() { + return customGetter.apply(this, arguments); + }; + } + else { + optimizedGetter = function() { + return this[internalName]; + }; + } + + data[getName] = function() { + var currentGetter; + + if (!this[initializedName]) { + this[initializedName] = true; + this[setName](this.config[name]); + } + + currentGetter = this[getName]; + + if ('$previous' in currentGetter) { + currentGetter.$previous = optimizedGetter; + } + else { + this[getName] = optimizedGetter; + } + + return optimizedGetter.apply(this, arguments); + }; + } + }); + + Class.addConfig(config, true); + }); + + /** + * @cfg {String[]/Object} mixins + * List of classes to mix into this class. For example: + * + * Ext.define('CanSing', { + * sing: function() { + * alert("I'm on the highway to hell...") + * } + * }); + * + * Ext.define('Musician', { + * mixins: ['CanSing'] + * }) + * + * In this case the Musician class will get a `sing` method from CanSing mixin. + * + * But what if the Musician already has a `sing` method? Or you want to mix + * in two classes, both of which define `sing`? In such a cases it's good + * to define mixins as an object, where you assign a name to each mixin: + * + * Ext.define('Musician', { + * mixins: { + * canSing: 'CanSing' + * }, + * + * sing: function() { + * // delegate singing operation to mixin + * this.mixins.canSing.sing.call(this); + * } + * }) + * + * In this case the `sing` method of Musician will overwrite the + * mixed in `sing` method. But you can access the original mixed in method + * through special `mixins` property. + */ + ExtClass.registerPreprocessor('mixins', function(Class, data, hooks) { + var mixins = data.mixins, + name, mixin, i, ln; + + delete data.mixins; + + Ext.Function.interceptBefore(hooks, 'onCreated', function() { + if (mixins instanceof Array) { + for (i = 0,ln = mixins.length; i < ln; i++) { + mixin = mixins[i]; + name = mixin.prototype.mixinId || mixin.$className; + + Class.mixin(name, mixin); + } + } + else { + for (var mixinName in mixins) { + if (mixins.hasOwnProperty(mixinName)) { + Class.mixin(mixinName, mixins[mixinName]); + } + } + } + }); + }); + + // Backwards compatible + Ext.extend = function(Class, Parent, members) { + if (arguments.length === 2 && Ext.isObject(Parent)) { + members = Parent; + Parent = Class; + Class = null; + } + + var cls; + + if (!Parent) { + throw new Error("[Ext.extend] Attempting to extend from a class which has not been loaded on the page."); + } + + members.extend = Parent; + members.preprocessors = [ + 'extend' + ,'statics' + ,'inheritableStatics' + ,'mixins' + ,'config' + ]; + + if (Class) { + cls = new ExtClass(Class, members); + } + else { + cls = new ExtClass(members); + } + + cls.prototype.override = function(o) { + for (var m in o) { + if (o.hasOwnProperty(m)) { + this[m] = o[m]; + } + } + }; + + return cls; + }; + +}()); + +/** + * @author Jacky Nguyen + * @docauthor Jacky Nguyen + * @class Ext.ClassManager + * + * Ext.ClassManager manages all classes and handles mapping from string class name to + * actual class objects throughout the whole framework. It is not generally accessed directly, rather through + * these convenient shorthands: + * + * - {@link Ext#define Ext.define} + * - {@link Ext#create Ext.create} + * - {@link Ext#widget Ext.widget} + * - {@link Ext#getClass Ext.getClass} + * - {@link Ext#getClassName Ext.getClassName} + * + * # Basic syntax: + * + * Ext.define(className, properties); + * + * in which `properties` is an object represent a collection of properties that apply to the class. See + * {@link Ext.ClassManager#create} for more detailed instructions. + * + * Ext.define('Person', { + * name: 'Unknown', + * + * constructor: function(name) { + * if (name) { + * this.name = name; + * } + * }, + * + * eat: function(foodType) { + * alert("I'm eating: " + foodType); + * + * return this; + * } + * }); + * + * var aaron = new Person("Aaron"); + * aaron.eat("Sandwich"); // alert("I'm eating: Sandwich"); + * + * Ext.Class has a powerful set of extensible {@link Ext.Class#registerPreprocessor pre-processors} which takes care of + * everything related to class creation, including but not limited to inheritance, mixins, configuration, statics, etc. + * + * # Inheritance: + * + * Ext.define('Developer', { + * extend: 'Person', + * + * constructor: function(name, isGeek) { + * this.isGeek = isGeek; + * + * // Apply a method from the parent class' prototype + * this.callParent([name]); + * }, + * + * code: function(language) { + * alert("I'm coding in: " + language); + * + * this.eat("Bugs"); + * + * return this; + * } + * }); + * + * var jacky = new Developer("Jacky", true); + * jacky.code("JavaScript"); // alert("I'm coding in: JavaScript"); + * // alert("I'm eating: Bugs"); + * + * See {@link Ext.Base#callParent} for more details on calling superclass' methods + * + * # Mixins: + * + * Ext.define('CanPlayGuitar', { + * playGuitar: function() { + * alert("F#...G...D...A"); + * } + * }); + * + * Ext.define('CanComposeSongs', { + * composeSongs: function() { ... } + * }); + * + * Ext.define('CanSing', { + * sing: function() { + * alert("I'm on the highway to hell...") + * } + * }); + * + * Ext.define('Musician', { + * extend: 'Person', + * + * mixins: { + * canPlayGuitar: 'CanPlayGuitar', + * canComposeSongs: 'CanComposeSongs', + * canSing: 'CanSing' + * } + * }) + * + * Ext.define('CoolPerson', { + * extend: 'Person', + * + * mixins: { + * canPlayGuitar: 'CanPlayGuitar', + * canSing: 'CanSing' + * }, + * + * sing: function() { + * alert("Ahem...."); + * + * this.mixins.canSing.sing.call(this); + * + * alert("[Playing guitar at the same time...]"); + * + * this.playGuitar(); + * } + * }); + * + * var me = new CoolPerson("Jacky"); + * + * me.sing(); // alert("Ahem..."); + * // alert("I'm on the highway to hell..."); + * // alert("[Playing guitar at the same time...]"); + * // alert("F#...G...D...A"); + * + * # Config: + * + * Ext.define('SmartPhone', { + * config: { + * hasTouchScreen: false, + * operatingSystem: 'Other', + * price: 500 + * }, + * + * isExpensive: false, + * + * constructor: function(config) { + * this.initConfig(config); + * }, + * + * applyPrice: function(price) { + * this.isExpensive = (price > 500); + * + * return price; + * }, + * + * applyOperatingSystem: function(operatingSystem) { + * if (!(/^(iOS|Android|BlackBerry)$/i).test(operatingSystem)) { + * return 'Other'; + * } + * + * return operatingSystem; + * } + * }); + * + * var iPhone = new SmartPhone({ + * hasTouchScreen: true, + * operatingSystem: 'iOS' + * }); + * + * iPhone.getPrice(); // 500; + * iPhone.getOperatingSystem(); // 'iOS' + * iPhone.getHasTouchScreen(); // true; + * iPhone.hasTouchScreen(); // true + * + * iPhone.isExpensive; // false; + * iPhone.setPrice(600); + * iPhone.getPrice(); // 600 + * iPhone.isExpensive; // true; + * + * iPhone.setOperatingSystem('AlienOS'); + * iPhone.getOperatingSystem(); // 'Other' + * + * # Statics: + * + * Ext.define('Computer', { + * statics: { + * factory: function(brand) { + * // 'this' in static methods refer to the class itself + * return new this(brand); + * } + * }, + * + * constructor: function() { ... } + * }); + * + * var dellComputer = Computer.factory('Dell'); + * + * Also see {@link Ext.Base#statics} and {@link Ext.Base#self} for more details on accessing + * static properties within class methods + * + * @singleton + */ +(function(Class, alias, arraySlice, arrayFrom, global) { + + var Manager = Ext.ClassManager = { + + /** + * @property {Object} classes + * All classes which were defined through the ClassManager. Keys are the + * name of the classes and the values are references to the classes. + * @private + */ + classes: {}, + + /** + * @private + */ + existCache: {}, + + /** + * @private + */ + namespaceRewrites: [{ + from: 'Ext.', + to: Ext + }], + + /** + * @private + */ + maps: { + alternateToName: {}, + aliasToName: {}, + nameToAliases: {}, + nameToAlternates: {} + }, + + /** @private */ + enableNamespaceParseCache: true, + + /** @private */ + namespaceParseCache: {}, + + /** @private */ + instantiators: [], + + /** + * Checks if a class has already been created. + * + * @param {String} className + * @return {Boolean} exist + */ + isCreated: function(className) { + var existCache = this.existCache, + i, ln, part, root, parts; + + if (typeof className != 'string' || className.length < 1) { + throw new Error("[Ext.ClassManager] Invalid classname, must be a string and must not be empty"); + } + + if (this.classes[className] || existCache[className]) { + return true; + } + + root = global; + parts = this.parseNamespace(className); + + for (i = 0, ln = parts.length; i < ln; i++) { + part = parts[i]; + + if (typeof part != 'string') { + root = part; + } else { + if (!root || !root[part]) { + return false; + } + + root = root[part]; + } + } + + existCache[className] = true; + + this.triggerCreated(className); + + return true; + }, + + /** + * @private + */ + createdListeners: [], + + /** + * @private + */ + nameCreatedListeners: {}, + + /** + * @private + */ + triggerCreated: function(className) { + var listeners = this.createdListeners, + nameListeners = this.nameCreatedListeners, + alternateNames = this.maps.nameToAlternates[className], + names = [className], + i, ln, j, subLn, listener, name; + + for (i = 0,ln = listeners.length; i < ln; i++) { + listener = listeners[i]; + listener.fn.call(listener.scope, className); + } + + if (alternateNames) { + names.push.apply(names, alternateNames); + } + + for (i = 0,ln = names.length; i < ln; i++) { + name = names[i]; + listeners = nameListeners[name]; + + if (listeners) { + for (j = 0,subLn = listeners.length; j < subLn; j++) { + listener = listeners[j]; + listener.fn.call(listener.scope, name); + } + delete nameListeners[name]; + } + } + }, + + /** + * @private + */ + onCreated: function(fn, scope, className) { + var listeners = this.createdListeners, + nameListeners = this.nameCreatedListeners, + listener = { + fn: fn, + scope: scope + }; + + if (className) { + if (this.isCreated(className)) { + fn.call(scope, className); + return; + } + + if (!nameListeners[className]) { + nameListeners[className] = []; + } + + nameListeners[className].push(listener); + } + else { + listeners.push(listener); + } + }, + + /** + * Supports namespace rewriting + * @private + */ + parseNamespace: function(namespace) { + if (typeof namespace != 'string') { + throw new Error("[Ext.ClassManager] Invalid namespace, must be a string"); + } + + var cache = this.namespaceParseCache, + parts, + rewrites, + root, + name, + rewrite, from, to, i, ln; + + if (this.enableNamespaceParseCache) { + if (cache.hasOwnProperty(namespace)) { + return cache[namespace]; + } + } + + parts = []; + rewrites = this.namespaceRewrites; + root = global; + name = namespace; + + for (i = 0, ln = rewrites.length; i < ln; i++) { + rewrite = rewrites[i]; + from = rewrite.from; + to = rewrite.to; + + if (name === from || name.substring(0, from.length) === from) { + name = name.substring(from.length); + + if (typeof to != 'string') { + root = to; + } else { + parts = parts.concat(to.split('.')); + } + + break; + } + } + + parts.push(root); + + parts = parts.concat(name.split('.')); + + if (this.enableNamespaceParseCache) { + cache[namespace] = parts; + } + + return parts; + }, + + /** + * Creates a namespace and assign the `value` to the created object + * + * Ext.ClassManager.setNamespace('MyCompany.pkg.Example', someObject); + * + * alert(MyCompany.pkg.Example === someObject); // alerts true + * + * @param {String} name + * @param {Object} value + */ + setNamespace: function(name, value) { + var root = global, + parts = this.parseNamespace(name), + ln = parts.length - 1, + leaf = parts[ln], + i, part; + + for (i = 0; i < ln; i++) { + part = parts[i]; + + if (typeof part != 'string') { + root = part; + } else { + if (!root[part]) { + root[part] = {}; + } + + root = root[part]; + } + } + + root[leaf] = value; + + return root[leaf]; + }, + + /** + * The new Ext.ns, supports namespace rewriting + * @private + */ + createNamespaces: function() { + var root = global, + parts, part, i, j, ln, subLn; + + for (i = 0, ln = arguments.length; i < ln; i++) { + parts = this.parseNamespace(arguments[i]); + + for (j = 0, subLn = parts.length; j < subLn; j++) { + part = parts[j]; + + if (typeof part != 'string') { + root = part; + } else { + if (!root[part]) { + root[part] = {}; + } + + root = root[part]; + } + } + } + + return root; + }, + + /** + * Sets a name reference to a class. + * + * @param {String} name + * @param {Object} value + * @return {Ext.ClassManager} this + */ + set: function(name, value) { + var me = this, + maps = me.maps, + nameToAlternates = maps.nameToAlternates, + targetName = me.getName(value), + alternates; + + me.classes[name] = me.setNamespace(name, value); + + if (targetName && targetName !== name) { + maps.alternateToName[name] = targetName; + alternates = nameToAlternates[targetName] || (nameToAlternates[targetName] = []); + alternates.push(name); + } + + return this; + }, + + /** + * Retrieve a class by its name. + * + * @param {String} name + * @return {Ext.Class} class + */ + get: function(name) { + var classes = this.classes, + root, + parts, + part, i, ln; + + if (classes[name]) { + return classes[name]; + } + + root = global; + parts = this.parseNamespace(name); + + for (i = 0, ln = parts.length; i < ln; i++) { + part = parts[i]; + + if (typeof part != 'string') { + root = part; + } else { + if (!root || !root[part]) { + return null; + } + + root = root[part]; + } + } + + return root; + }, + + /** + * Register the alias for a class. + * + * @param {Ext.Class/String} cls a reference to a class or a className + * @param {String} alias Alias to use when referring to this class + */ + setAlias: function(cls, alias) { + var aliasToNameMap = this.maps.aliasToName, + nameToAliasesMap = this.maps.nameToAliases, + className; + + if (typeof cls == 'string') { + className = cls; + } else { + className = this.getName(cls); + } + + if (alias && aliasToNameMap[alias] !== className) { + if (aliasToNameMap[alias] && Ext.isDefined(global.console)) { + global.console.log("[Ext.ClassManager] Overriding existing alias: '" + alias + "' " + + "of: '" + aliasToNameMap[alias] + "' with: '" + className + "'. Be sure it's intentional."); + } + + aliasToNameMap[alias] = className; + } + + if (!nameToAliasesMap[className]) { + nameToAliasesMap[className] = []; + } + + if (alias) { + Ext.Array.include(nameToAliasesMap[className], alias); + } + + return this; + }, + + /** + * Get a reference to the class by its alias. + * + * @param {String} alias + * @return {Ext.Class} class + */ + getByAlias: function(alias) { + return this.get(this.getNameByAlias(alias)); + }, + + /** + * Get the name of a class by its alias. + * + * @param {String} alias + * @return {String} className + */ + getNameByAlias: function(alias) { + return this.maps.aliasToName[alias] || ''; + }, + + /** + * Get the name of a class by its alternate name. + * + * @param {String} alternate + * @return {String} className + */ + getNameByAlternate: function(alternate) { + return this.maps.alternateToName[alternate] || ''; + }, + + /** + * Get the aliases of a class by the class name + * + * @param {String} name + * @return {Array} aliases + */ + getAliasesByName: function(name) { + return this.maps.nameToAliases[name] || []; + }, + + /** + * Get the name of the class by its reference or its instance; + * usually invoked by the shorthand {@link Ext#getClassName Ext.getClassName} + * + * Ext.ClassManager.getName(Ext.Action); // returns "Ext.Action" + * + * @param {Ext.Class/Object} object + * @return {String} className + */ + getName: function(object) { + return object && object.$className || ''; + }, + + /** + * Get the class of the provided object; returns null if it's not an instance + * of any class created with Ext.define. This is usually invoked by the shorthand {@link Ext#getClass Ext.getClass} + * + * var component = new Ext.Component(); + * + * Ext.ClassManager.getClass(component); // returns Ext.Component + * + * @param {Object} object + * @return {Ext.Class} class + */ + getClass: function(object) { + return object && object.self || null; + }, + + /** + * Defines a class. + * @deprecated 4.1.0 Use {@link Ext#define} instead, as that also supports creating overrides. + */ + create: function(className, data, createdFn) { + if (typeof className != 'string') { + throw new Error("[Ext.define] Invalid class name '" + className + "' specified, must be a non-empty string"); + } + + data.$className = className; + + return new Class(data, function() { + var postprocessorStack = data.postprocessors || Manager.defaultPostprocessors, + registeredPostprocessors = Manager.postprocessors, + postprocessors = [], + postprocessor, i, ln, j, subLn, postprocessorProperties, postprocessorProperty; + + delete data.postprocessors; + + for (i = 0,ln = postprocessorStack.length; i < ln; i++) { + postprocessor = postprocessorStack[i]; + + if (typeof postprocessor == 'string') { + postprocessor = registeredPostprocessors[postprocessor]; + postprocessorProperties = postprocessor.properties; + + if (postprocessorProperties === true) { + postprocessors.push(postprocessor.fn); + } + else if (postprocessorProperties) { + for (j = 0,subLn = postprocessorProperties.length; j < subLn; j++) { + postprocessorProperty = postprocessorProperties[j]; + + if (data.hasOwnProperty(postprocessorProperty)) { + postprocessors.push(postprocessor.fn); + break; + } + } + } + } + else { + postprocessors.push(postprocessor); + } + } + + data.postprocessors = postprocessors; + data.createdFn = createdFn; + Manager.processCreate(className, this, data); + }); + }, + + processCreate: function(className, cls, clsData){ + var me = this, + postprocessor = clsData.postprocessors.shift(), + createdFn = clsData.createdFn; + + if (!postprocessor) { + me.set(className, cls); + + if (createdFn) { + createdFn.call(cls, cls); + } + + me.triggerCreated(className); + return; + } + + if (postprocessor.call(me, className, cls, clsData, me.processCreate) !== false) { + me.processCreate(className, cls, clsData); + } + }, + + createOverride: function (className, data, createdFn) { + var me = this, + overriddenClassName = data.override, + requires = data.requires, + uses = data.uses, + classReady = function () { + var cls, temp; + + if (requires) { + temp = requires; + requires = null; // do the real thing next time (which may be now) + + // Since the override is going to be used (its target class is now + // created), we need to fetch the required classes for the override + // and call us back once they are loaded: + Ext.Loader.require(temp, classReady); + } else { + // The target class and the required classes for this override are + // ready, so we can apply the override now: + cls = me.get(overriddenClassName); + + // We don't want to apply these: + delete data.override; + delete data.requires; + delete data.uses; + + Ext.override(cls, data); + + // This pushes the overridding file itself into Ext.Loader.history + // Hence if the target class never exists, the overriding file will + // never be included in the build. + me.triggerCreated(className); + + if (uses) { + Ext.Loader.addUsedClasses(uses); // get these classes too! + } + + if (createdFn) { + createdFn.call(cls); // last but not least! + } + } + }; + + me.existCache[className] = true; + + // Override the target class right after it's created + me.onCreated(classReady, me, overriddenClassName); + + return me; + }, + + /** + * Instantiate a class by its alias; usually invoked by the convenient shorthand {@link Ext#createByAlias Ext.createByAlias} + * If {@link Ext.Loader} is {@link Ext.Loader#setConfig enabled} and the class has not been defined yet, it will + * attempt to load the class via synchronous loading. + * + * var window = Ext.ClassManager.instantiateByAlias('widget.window', { width: 600, height: 800, ... }); + * + * @param {String} alias + * @param {Object...} args Additional arguments after the alias will be passed to the + * class constructor. + * @return {Object} instance + */ + instantiateByAlias: function() { + var alias = arguments[0], + args = arraySlice.call(arguments), + className = this.getNameByAlias(alias); + + if (!className) { + className = this.maps.aliasToName[alias]; + + if (!className) { + throw new Error("[Ext.createByAlias] Cannot create an instance of unrecognized alias: " + alias); + } + + if (global.console) { + global.console.warn("[Ext.Loader] Synchronously loading '" + className + "'; consider adding " + + "Ext.require('" + alias + "') above Ext.onReady"); + } + + Ext.syncRequire(className); + } + + args[0] = className; + + return this.instantiate.apply(this, args); + }, + + /** + * @private + */ + instantiate: function() { + var name = arguments[0], + nameType = typeof name, + args = arraySlice.call(arguments, 1), + alias = name, + possibleName, cls; + + if (nameType != 'function') { + if (nameType != 'string' && args.length === 0) { + args = [name]; + name = name.xclass; + } + + if (typeof name != 'string' || name.length < 1) { + throw new Error("[Ext.create] Invalid class name or alias '" + name + "' specified, must be a non-empty string"); + } + + cls = this.get(name); + } + else { + cls = name; + } + + // No record of this class name, it's possibly an alias, so look it up + if (!cls) { + possibleName = this.getNameByAlias(name); + + if (possibleName) { + name = possibleName; + + cls = this.get(name); + } + } + + // Still no record of this class name, it's possibly an alternate name, so look it up + if (!cls) { + possibleName = this.getNameByAlternate(name); + + if (possibleName) { + name = possibleName; + + cls = this.get(name); + } + } + + // Still not existing at this point, try to load it via synchronous mode as the last resort + if (!cls) { + if (global.console) { + global.console.warn("[Ext.Loader] Synchronously loading '" + name + "'; consider adding " + + "Ext.require('" + ((possibleName) ? alias : name) + "') above Ext.onReady"); + } + + Ext.syncRequire(name); + + cls = this.get(name); + } + + if (!cls) { + throw new Error("[Ext.create] Cannot create an instance of unrecognized class name / alias: " + alias); + } + + if (typeof cls != 'function') { + throw new Error("[Ext.create] '" + name + "' is a singleton and cannot be instantiated"); + } + + return this.getInstantiator(args.length)(cls, args); + }, + + /** + * @private + * @param name + * @param args + */ + dynInstantiate: function(name, args) { + args = arrayFrom(args, true); + args.unshift(name); + + return this.instantiate.apply(this, args); + }, + + /** + * @private + * @param length + */ + getInstantiator: function(length) { + var instantiators = this.instantiators, + instantiator, + i, + args; + + instantiator = instantiators[length]; + + if (!instantiator) { + i = length; + args = []; + + for (i = 0; i < length; i++) { + args.push('a[' + i + ']'); + } + + instantiator = instantiators[length] = new Function('c', 'a', 'return new c(' + args.join(',') + ')'); + instantiator.displayName = "Ext.ClassManager.instantiate" + length; + } + + return instantiator; + }, + + /** + * @private + */ + postprocessors: {}, + + /** + * @private + */ + defaultPostprocessors: [], + + /** + * Register a post-processor function. + * + * @private + * @param {String} name + * @param {Function} postprocessor + */ + registerPostprocessor: function(name, fn, properties, position, relativeTo) { + if (!position) { + position = 'last'; + } + + if (!properties) { + properties = [name]; + } + + this.postprocessors[name] = { + name: name, + properties: properties || false, + fn: fn + }; + + this.setDefaultPostprocessorPosition(name, position, relativeTo); + + return this; + }, + + /** + * Set the default post processors array stack which are applied to every class. + * + * @private + * @param {String/Array} The name of a registered post processor or an array of registered names. + * @return {Ext.ClassManager} this + */ + setDefaultPostprocessors: function(postprocessors) { + this.defaultPostprocessors = arrayFrom(postprocessors); + + return this; + }, + + /** + * Insert this post-processor at a specific position in the stack, optionally relative to + * any existing post-processor + * + * @private + * @param {String} name The post-processor name. Note that it needs to be registered with + * {@link Ext.ClassManager#registerPostprocessor} before this + * @param {String} offset The insertion position. Four possible values are: + * 'first', 'last', or: 'before', 'after' (relative to the name provided in the third argument) + * @param {String} relativeName + * @return {Ext.ClassManager} this + */ + setDefaultPostprocessorPosition: function(name, offset, relativeName) { + var defaultPostprocessors = this.defaultPostprocessors, + index; + + if (typeof offset == 'string') { + if (offset === 'first') { + defaultPostprocessors.unshift(name); + + return this; + } + else if (offset === 'last') { + defaultPostprocessors.push(name); + + return this; + } + + offset = (offset === 'after') ? 1 : -1; + } + + index = Ext.Array.indexOf(defaultPostprocessors, relativeName); + + if (index !== -1) { + Ext.Array.splice(defaultPostprocessors, Math.max(0, index + offset), 0, name); + } + + return this; + }, + + /** + * Converts a string expression to an array of matching class names. An expression can either refers to class aliases + * or class names. Expressions support wildcards: + * + * // returns ['Ext.window.Window'] + * var window = Ext.ClassManager.getNamesByExpression('widget.window'); + * + * // returns ['widget.panel', 'widget.window', ...] + * var allWidgets = Ext.ClassManager.getNamesByExpression('widget.*'); + * + * // returns ['Ext.data.Store', 'Ext.data.ArrayProxy', ...] + * var allData = Ext.ClassManager.getNamesByExpression('Ext.data.*'); + * + * @param {String} expression + * @return {String[]} classNames + */ + getNamesByExpression: function(expression) { + var nameToAliasesMap = this.maps.nameToAliases, + names = [], + name, alias, aliases, possibleName, regex, i, ln; + + if (typeof expression != 'string' || expression.length < 1) { + throw new Error("[Ext.ClassManager.getNamesByExpression] Expression " + expression + " is invalid, must be a non-empty string"); + } + + if (expression.indexOf('*') !== -1) { + expression = expression.replace(/\*/g, '(.*?)'); + regex = new RegExp('^' + expression + '$'); + + for (name in nameToAliasesMap) { + if (nameToAliasesMap.hasOwnProperty(name)) { + aliases = nameToAliasesMap[name]; + + if (name.search(regex) !== -1) { + names.push(name); + } + else { + for (i = 0, ln = aliases.length; i < ln; i++) { + alias = aliases[i]; + + if (alias.search(regex) !== -1) { + names.push(name); + break; + } + } + } + } + } + + } else { + possibleName = this.getNameByAlias(expression); + + if (possibleName) { + names.push(possibleName); + } else { + possibleName = this.getNameByAlternate(expression); + + if (possibleName) { + names.push(possibleName); + } else { + names.push(expression); + } + } + } + + return names; + } + }; + + /** + * @cfg {String[]} alias + * @member Ext.Class + * List of short aliases for class names. Most useful for defining xtypes for widgets: + * + * Ext.define('MyApp.CoolPanel', { + * extend: 'Ext.panel.Panel', + * alias: ['widget.coolpanel'], + * title: 'Yeah!' + * }); + * + * // Using Ext.create + * Ext.create('widget.coolpanel'); + * + * // Using the shorthand for defining widgets by xtype + * Ext.widget('panel', { + * items: [ + * {xtype: 'coolpanel', html: 'Foo'}, + * {xtype: 'coolpanel', html: 'Bar'} + * ] + * }); + * + * Besides "widget" for xtype there are alias namespaces like "feature" for ftype and "plugin" for ptype. + */ + Manager.registerPostprocessor('alias', function(name, cls, data) { + var aliases = data.alias, + i, ln; + + for (i = 0,ln = aliases.length; i < ln; i++) { + alias = aliases[i]; + + this.setAlias(cls, alias); + } + + }, ['xtype', 'alias']); + + /** + * @cfg {Boolean} singleton + * @member Ext.Class + * When set to true, the class will be instantiated as singleton. For example: + * + * Ext.define('Logger', { + * singleton: true, + * log: function(msg) { + * console.log(msg); + * } + * }); + * + * Logger.log('Hello'); + */ + Manager.registerPostprocessor('singleton', function(name, cls, data, fn) { + fn.call(this, name, new cls(), data); + return false; + }); + + /** + * @cfg {String/String[]} alternateClassName + * @member Ext.Class + * Defines alternate names for this class. For example: + * + * Ext.define('Developer', { + * alternateClassName: ['Coder', 'Hacker'], + * code: function(msg) { + * alert('Typing... ' + msg); + * } + * }); + * + * var joe = Ext.create('Developer'); + * joe.code('stackoverflow'); + * + * var rms = Ext.create('Hacker'); + * rms.code('hack hack'); + */ + Manager.registerPostprocessor('alternateClassName', function(name, cls, data) { + var alternates = data.alternateClassName, + i, ln, alternate; + + if (!(alternates instanceof Array)) { + alternates = [alternates]; + } + + for (i = 0, ln = alternates.length; i < ln; i++) { + alternate = alternates[i]; + + if (typeof alternate != 'string') { + throw new Error("[Ext.define] Invalid alternate of: '" + alternate + "' for class: '" + name + "'; must be a valid string"); + } + + this.set(alternate, cls); + } + }); + + Ext.apply(Ext, { + /** + * Instantiate a class by either full name, alias or alternate name. + * + * If {@link Ext.Loader} is {@link Ext.Loader#setConfig enabled} and the class has + * not been defined yet, it will attempt to load the class via synchronous loading. + * + * For example, all these three lines return the same result: + * + * // alias + * var window = Ext.create('widget.window', { + * width: 600, + * height: 800, + * ... + * }); + * + * // alternate name + * var window = Ext.create('Ext.Window', { + * width: 600, + * height: 800, + * ... + * }); + * + * // full class name + * var window = Ext.create('Ext.window.Window', { + * width: 600, + * height: 800, + * ... + * }); + * + * // single object with xclass property: + * var window = Ext.create({ + * xclass: 'Ext.window.Window', // any valid value for 'name' (above) + * width: 600, + * height: 800, + * ... + * }); + * + * @param {String} [name] The class name or alias. Can be specified as `xclass` + * property if only one object parameter is specified. + * @param {Object...} [args] Additional arguments after the name will be passed to + * the class' constructor. + * @return {Object} instance + * @member Ext + * @method create + */ + create: alias(Manager, 'instantiate'), + + /** + * Convenient shorthand to create a widget by its xtype or a config object. + * See also {@link Ext.ClassManager#instantiateByAlias}. + * + * var button = Ext.widget('button'); // Equivalent to Ext.create('widget.button'); + * + * var panel = Ext.widget('panel', { // Equivalent to Ext.create('widget.panel') + * title: 'Panel' + * }); + * + * var grid = Ext.widget({ + * xtype: 'grid', + * ... + * }); + * + * If a {@link Ext.Component component} instance is passed, it is simply returned. + * + * @member Ext + * @param {String} [name] The xtype of the widget to create. + * @param {Object} [config] The configuration object for the widget constructor. + * @return {Object} The widget instance + */ + widget: function(name, config) { + // forms: + // 1: (xtype) + // 2: (xtype, config) + // 3: (config) + // 4: (xtype, component) + // 5: (component) + // + var xtype = name, + alias, className, T, load; + + if (typeof xtype != 'string') { // if (form 3 or 5) + // first arg is config or component + config = name; // arguments[0] + xtype = config.xtype; + } else { + config = config || {}; + } + + if (config.isComponent) { + return config; + } + + alias = 'widget.' + xtype; + className = Manager.getNameByAlias(alias); + + // this is needed to support demand loading of the class + if (!className) { + load = true; + } + + T = Manager.get(className); + if (load || !T) { + return Manager.instantiateByAlias(alias, config); + } + return new T(config); + }, + + /** + * Convenient shorthand, see {@link Ext.ClassManager#instantiateByAlias} + * @member Ext + * @method createByAlias + */ + createByAlias: alias(Manager, 'instantiateByAlias'), + + /** + * @method + * Defines a class or override. A basic class is defined like this: + * + * Ext.define('My.awesome.Class', { + * someProperty: 'something', + * + * someMethod: function() { + * alert(s + this.someProperty); + * } + * + * ... + * }); + * + * var obj = new My.awesome.Class(); + * + * obj.someMethod('Say '); // alerts 'Say something' + * + * To defines an override, include the `override` property. The content of an + * override is aggregated with the specified class in order to extend or modify + * that class. This can be as simple as setting default property values or it can + * extend and/or replace methods. This can also extend the statics of the class. + * + * One use for an override is to break a large class into manageable pieces. + * + * // File: /src/app/Panel.js + * + * Ext.define('My.app.Panel', { + * extend: 'Ext.panel.Panel', + * requires: [ + * 'My.app.PanelPart2', + * 'My.app.PanelPart3' + * ] + * + * constructor: function (config) { + * this.callParent(arguments); // calls Ext.panel.Panel's constructor + * //... + * }, + * + * statics: { + * method: function () { + * return 'abc'; + * } + * } + * }); + * + * // File: /src/app/PanelPart2.js + * Ext.define('My.app.PanelPart2', { + * override: 'My.app.Panel', + * + * constructor: function (config) { + * this.callParent(arguments); // calls My.app.Panel's constructor + * //... + * } + * }); + * + * Another use of overrides is to provide optional parts of classes that can be + * independently required. In this case, the class may even be unaware of the + * override altogether. + * + * Ext.define('My.ux.CoolTip', { + * override: 'Ext.tip.ToolTip', + * + * constructor: function (config) { + * this.callParent(arguments); // calls Ext.tip.ToolTip's constructor + * //... + * } + * }); + * + * The above override can now be required as normal. + * + * Ext.define('My.app.App', { + * requires: [ + * 'My.ux.CoolTip' + * ] + * }); + * + * Overrides can also contain statics: + * + * Ext.define('My.app.BarMod', { + * override: 'Ext.foo.Bar', + * + * statics: { + * method: function (x) { + * return this.callParent([x * 2]); // call Ext.foo.Bar.method + * } + * } + * }); + * + * IMPORTANT: An override is only included in a build if the class it overrides is + * required. Otherwise, the override, like the target class, is not included. + * + * @param {String} className The class name to create in string dot-namespaced format, for example: + * 'My.very.awesome.Class', 'FeedViewer.plugin.CoolPager' + * It is highly recommended to follow this simple convention: + * - The root and the class name are 'CamelCased' + * - Everything else is lower-cased + * @param {Object} data The key - value pairs of properties to apply to this class. Property names can be of any valid + * strings, except those in the reserved listed below: + * - `mixins` + * - `statics` + * - `config` + * - `alias` + * - `self` + * - `singleton` + * - `alternateClassName` + * - `override` + * + * @param {Function} createdFn Optional callback to execute after the class is created, the execution scope of which + * (`this`) will be the newly created class itself. + * @return {Ext.Base} + * @markdown + * @member Ext + * @method define + */ + define: function (className, data, createdFn) { + if (data.override) { + return Manager.createOverride.apply(Manager, arguments); + } + + return Manager.create.apply(Manager, arguments); + }, + + /** + * Convenient shorthand, see {@link Ext.ClassManager#getName} + * @member Ext + * @method getClassName + */ + getClassName: alias(Manager, 'getName'), + + /** + * Returns the displayName property or className or object. When all else fails, returns "Anonymous". + * @param {Object} object + * @return {String} + */ + getDisplayName: function(object) { + if (object) { + if (object.displayName) { + return object.displayName; + } + + if (object.$name && object.$class) { + return Ext.getClassName(object.$class) + '#' + object.$name; + } + + if (object.$className) { + return object.$className; + } + } + + return 'Anonymous'; + }, + + /** + * Convenient shorthand, see {@link Ext.ClassManager#getClass} + * @member Ext + * @method getClass + */ + getClass: alias(Manager, 'getClass'), + + /** + * Creates namespaces to be used for scoping variables and classes so that they are not global. + * Specifying the last node of a namespace implicitly creates all other nodes. Usage: + * + * Ext.namespace('Company', 'Company.data'); + * + * // equivalent and preferable to the above syntax + * Ext.ns('Company.data'); + * + * Company.Widget = function() { ... }; + * + * Company.data.CustomStore = function(config) { ... }; + * + * @param {String...} namespaces + * @return {Object} The namespace object. + * (If multiple arguments are passed, this will be the last namespace created) + * @member Ext + * @method namespace + */ + namespace: alias(Manager, 'createNamespaces') + }); + + /** + * Old name for {@link Ext#widget}. + * @deprecated 4.0.0 Use {@link Ext#widget} instead. + * @method createWidget + * @member Ext + */ + Ext.createWidget = Ext.widget; + + /** + * Convenient alias for {@link Ext#namespace Ext.namespace}. + * @inheritdoc Ext#namespace + * @member Ext + * @method ns + */ + Ext.ns = Ext.namespace; + + Class.registerPreprocessor('className', function(cls, data) { + if (data.$className) { + cls.$className = data.$className; + cls.displayName = cls.$className; + } + }, true, 'first'); + + Class.registerPreprocessor('alias', function(cls, data) { + var prototype = cls.prototype, + xtypes = arrayFrom(data.xtype), + aliases = arrayFrom(data.alias), + widgetPrefix = 'widget.', + widgetPrefixLength = widgetPrefix.length, + xtypesChain = Array.prototype.slice.call(prototype.xtypesChain || []), + xtypesMap = Ext.merge({}, prototype.xtypesMap || {}), + i, ln, alias, xtype; + + for (i = 0,ln = aliases.length; i < ln; i++) { + alias = aliases[i]; + + if (typeof alias != 'string' || alias.length < 1) { + throw new Error("[Ext.define] Invalid alias of: '" + alias + "' for class: '" + name + "'; must be a valid string"); + } + + if (alias.substring(0, widgetPrefixLength) === widgetPrefix) { + xtype = alias.substring(widgetPrefixLength); + Ext.Array.include(xtypes, xtype); + } + } + + cls.xtype = data.xtype = xtypes[0]; + data.xtypes = xtypes; + + for (i = 0,ln = xtypes.length; i < ln; i++) { + xtype = xtypes[i]; + + if (!xtypesMap[xtype]) { + xtypesMap[xtype] = true; + xtypesChain.push(xtype); + } + } + + data.xtypesChain = xtypesChain; + data.xtypesMap = xtypesMap; + + Ext.Function.interceptAfter(data, 'onClassCreated', function() { + var mixins = prototype.mixins, + key, mixin; + + for (key in mixins) { + if (mixins.hasOwnProperty(key)) { + mixin = mixins[key]; + + xtypes = mixin.xtypes; + + if (xtypes) { + for (i = 0,ln = xtypes.length; i < ln; i++) { + xtype = xtypes[i]; + + if (!xtypesMap[xtype]) { + xtypesMap[xtype] = true; + xtypesChain.push(xtype); + } + } + } + } + } + }); + + for (i = 0,ln = xtypes.length; i < ln; i++) { + xtype = xtypes[i]; + + if (typeof xtype != 'string' || xtype.length < 1) { + throw new Error("[Ext.define] Invalid xtype of: '" + xtype + "' for class: '" + name + "'; must be a valid non-empty string"); + } + + Ext.Array.include(aliases, widgetPrefix + xtype); + } + + data.alias = aliases; + + }, ['xtype', 'alias']); + +}(Ext.Class, Ext.Function.alias, Array.prototype.slice, Ext.Array.from, Ext.global)); + +/** + * @author Jacky Nguyen + * @docauthor Jacky Nguyen + * @class Ext.Loader + * + * Ext.Loader is the heart of the new dynamic dependency loading capability in Ext JS 4+. It is most commonly used + * via the {@link Ext#require} shorthand. Ext.Loader supports both asynchronous and synchronous loading + * approaches, and leverage their advantages for the best development flow. We'll discuss about the pros and cons of each approach: + * + * # Asynchronous Loading # + * + * - Advantages: + * + Cross-domain + * + No web server needed: you can run the application via the file system protocol (i.e: `file://path/to/your/index + * .html`) + * + Best possible debugging experience: error messages come with the exact file name and line number + * + * - Disadvantages: + * + Dependencies need to be specified before-hand + * + * ### Method 1: Explicitly include what you need: ### + * + * // Syntax + * Ext.require({String/Array} expressions); + * + * // Example: Single alias + * Ext.require('widget.window'); + * + * // Example: Single class name + * Ext.require('Ext.window.Window'); + * + * // Example: Multiple aliases / class names mix + * Ext.require(['widget.window', 'layout.border', 'Ext.data.Connection']); + * + * // Wildcards + * Ext.require(['widget.*', 'layout.*', 'Ext.data.*']); + * + * ### Method 2: Explicitly exclude what you don't need: ### + * + * // Syntax: Note that it must be in this chaining format. + * Ext.exclude({String/Array} expressions) + * .require({String/Array} expressions); + * + * // Include everything except Ext.data.* + * Ext.exclude('Ext.data.*').require('*'); + * + * // Include all widgets except widget.checkbox*, + * // which will match widget.checkbox, widget.checkboxfield, widget.checkboxgroup, etc. + * Ext.exclude('widget.checkbox*').require('widget.*'); + * + * # Synchronous Loading on Demand # + * + * - Advantages: + * + There's no need to specify dependencies before-hand, which is always the convenience of including ext-all.js + * before + * + * - Disadvantages: + * + Not as good debugging experience since file name won't be shown (except in Firebug at the moment) + * + Must be from the same domain due to XHR restriction + * + Need a web server, same reason as above + * + * There's one simple rule to follow: Instantiate everything with Ext.create instead of the `new` keyword + * + * Ext.create('widget.window', { ... }); // Instead of new Ext.window.Window({...}); + * + * Ext.create('Ext.window.Window', {}); // Same as above, using full class name instead of alias + * + * Ext.widget('window', {}); // Same as above, all you need is the traditional `xtype` + * + * Behind the scene, {@link Ext.ClassManager} will automatically check whether the given class name / alias has already + * existed on the page. If it's not, Ext.Loader will immediately switch itself to synchronous mode and automatic load the given + * class and all its dependencies. + * + * # Hybrid Loading - The Best of Both Worlds # + * + * It has all the advantages combined from asynchronous and synchronous loading. The development flow is simple: + * + * ### Step 1: Start writing your application using synchronous approach. + * + * Ext.Loader will automatically fetch all dependencies on demand as they're needed during run-time. For example: + * + * Ext.onReady(function(){ + * var window = Ext.createWidget('window', { + * width: 500, + * height: 300, + * layout: { + * type: 'border', + * padding: 5 + * }, + * title: 'Hello Dialog', + * items: [{ + * title: 'Navigation', + * collapsible: true, + * region: 'west', + * width: 200, + * html: 'Hello', + * split: true + * }, { + * title: 'TabPanel', + * region: 'center' + * }] + * }); + * + * window.show(); + * }) + * + * ### Step 2: Along the way, when you need better debugging ability, watch the console for warnings like these: ### + * + * [Ext.Loader] Synchronously loading 'Ext.window.Window'; consider adding Ext.require('Ext.window.Window') before your application's code + * ClassManager.js:432 + * [Ext.Loader] Synchronously loading 'Ext.layout.container.Border'; consider adding Ext.require('Ext.layout.container.Border') before your application's code + * + * Simply copy and paste the suggested code above `Ext.onReady`, i.e: + * + * Ext.require('Ext.window.Window'); + * Ext.require('Ext.layout.container.Border'); + * + * Ext.onReady(...); + * + * Everything should now load via asynchronous mode. + * + * # Deployment # + * + * It's important to note that dynamic loading should only be used during development on your local machines. + * During production, all dependencies should be combined into one single JavaScript file. Ext.Loader makes + * the whole process of transitioning from / to between development / maintenance and production as easy as + * possible. Internally {@link Ext.Loader#history Ext.Loader.history} maintains the list of all dependencies your application + * needs in the exact loading sequence. It's as simple as concatenating all files in this array into one, + * then include it on top of your application. + * + * This process will be automated with Sencha Command, to be released and documented towards Ext JS 4 Final. + * + * @singleton + */ + +Ext.Loader = new function() { + var Loader = this, + Manager = Ext.ClassManager, + Class = Ext.Class, + flexSetter = Ext.Function.flexSetter, + alias = Ext.Function.alias, + pass = Ext.Function.pass, + defer = Ext.Function.defer, + arrayErase = Ext.Array.erase, + dependencyProperties = ['extend', 'mixins', 'requires'], + isInHistory = {}, + history = [], + slashDotSlashRe = /\/\.\//g, + dotRe = /\./g; + + Ext.apply(Loader, { + + /** + * @private + */ + isInHistory: isInHistory, + + /** + * An array of class names to keep track of the dependency loading order. + * This is not guaranteed to be the same everytime due to the asynchronous + * nature of the Loader. + * + * @property {Array} history + */ + history: history, + + /** + * Configuration + * @private + */ + config: { + /** + * @cfg {Boolean} enabled + * Whether or not to enable the dynamic dependency loading feature. + */ + enabled: false, + + /** + * @cfg {Boolean} scriptChainDelay + * millisecond delay between asynchronous script injection (prevents stack overflow on some user agents) + * 'false' disables delay but potentially increases stack load. + */ + scriptChainDelay : false, + + /** + * @cfg {Boolean} disableCaching + * Appends current timestamp to script files to prevent caching. + */ + disableCaching: true, + + /** + * @cfg {String} disableCachingParam + * The get parameter name for the cache buster's timestamp. + */ + disableCachingParam: '_dc', + + /** + * @cfg {Boolean} garbageCollect + * True to prepare an asynchronous script tag for garbage collection (effective only + * if {@link #preserveScripts preserveScripts} is false) + */ + garbageCollect : false, + + /** + * @cfg {Object} paths + * The mapping from namespaces to file paths + * + * { + * 'Ext': '.', // This is set by default, Ext.layout.container.Container will be + * // loaded from ./layout/Container.js + * + * 'My': './src/my_own_folder' // My.layout.Container will be loaded from + * // ./src/my_own_folder/layout/Container.js + * } + * + * Note that all relative paths are relative to the current HTML document. + * If not being specified, for example, Other.awesome.Class + * will simply be loaded from ./Other/awesome/Class.js + */ + paths: { + 'Ext': '.' + }, + + /** + * @cfg {Boolean} preserveScripts + * False to remove and optionally {@link #garbageCollect garbage-collect} asynchronously loaded scripts, + * True to retain script element for browser debugger compatibility and improved load performance. + */ + preserveScripts : true, + + /** + * @cfg {String} scriptCharset + * Optional charset to specify encoding of dynamic script content. + */ + scriptCharset : undefined + }, + + /** + * Set the configuration for the loader. This should be called right after ext-(debug).js + * is included in the page, and before Ext.onReady. i.e: + * + * + * + * + * + * Refer to config options of {@link Ext.Loader} for the list of possible properties + * + * @param {Object} config The config object to override the default values + * @return {Ext.Loader} this + */ + setConfig: function(name, value) { + if (Ext.isObject(name) && arguments.length === 1) { + Ext.merge(Loader.config, name); + } + else { + Loader.config[name] = (Ext.isObject(value)) ? Ext.merge(Loader.config[name], value) : value; + } + + return Loader; + }, + + /** + * Get the config value corresponding to the specified name. If no name is given, will return the config object + * @param {String} name The config property name + * @return {Object} + */ + getConfig: function(name) { + if (name) { + return Loader.config[name]; + } + + return Loader.config; + }, + + /** + * Sets the path of a namespace. + * For Example: + * + * Ext.Loader.setPath('Ext', '.'); + * + * @param {String/Object} name See {@link Ext.Function#flexSetter flexSetter} + * @param {String} path See {@link Ext.Function#flexSetter flexSetter} + * @return {Ext.Loader} this + * @method + */ + setPath: flexSetter(function(name, path) { + Loader.config.paths[name] = path; + + return Loader; + }), + + /** + * Translates a className to a file path by adding the + * the proper prefix and converting the .'s to /'s. For example: + * + * Ext.Loader.setPath('My', '/path/to/My'); + * + * alert(Ext.Loader.getPath('My.awesome.Class')); // alerts '/path/to/My/awesome/Class.js' + * + * Note that the deeper namespace levels, if explicitly set, are always resolved first. For example: + * + * Ext.Loader.setPath({ + * 'My': '/path/to/lib', + * 'My.awesome': '/other/path/for/awesome/stuff', + * 'My.awesome.more': '/more/awesome/path' + * }); + * + * alert(Ext.Loader.getPath('My.awesome.Class')); // alerts '/other/path/for/awesome/stuff/Class.js' + * + * alert(Ext.Loader.getPath('My.awesome.more.Class')); // alerts '/more/awesome/path/Class.js' + * + * alert(Ext.Loader.getPath('My.cool.Class')); // alerts '/path/to/lib/cool/Class.js' + * + * alert(Ext.Loader.getPath('Unknown.strange.Stuff')); // alerts 'Unknown/strange/Stuff.js' + * + * @param {String} className + * @return {String} path + */ + getPath: function(className) { + var path = '', + paths = Loader.config.paths, + prefix = Loader.getPrefix(className); + + if (prefix.length > 0) { + if (prefix === className) { + return paths[prefix]; + } + + path = paths[prefix]; + className = className.substring(prefix.length + 1); + } + + if (path.length > 0) { + path += '/'; + } + + return path.replace(slashDotSlashRe, '/') + className.replace(dotRe, "/") + '.js'; + }, + + /** + * @private + * @param {String} className + */ + getPrefix: function(className) { + var paths = Loader.config.paths, + prefix, deepestPrefix = ''; + + if (paths.hasOwnProperty(className)) { + return className; + } + + for (prefix in paths) { + if (paths.hasOwnProperty(prefix) && prefix + '.' === className.substring(0, prefix.length + 1)) { + if (prefix.length > deepestPrefix.length) { + deepestPrefix = prefix; + } + } + } + + return deepestPrefix; + }, + + /** + * @private + * @param {String} className + */ + isAClassNameWithAKnownPrefix: function(className) { + var prefix = Loader.getPrefix(className); + + // we can only say it's really a class if className is not equal to any known namespace + return prefix !== '' && prefix !== className; + }, + + /** + * Loads all classes by the given names and all their direct dependencies; optionally executes the given callback function when + * finishes, within the optional scope. This method is aliased by {@link Ext#require Ext.require} for convenience + * @param {String/Array} expressions Can either be a string or an array of string + * @param {Function} fn (Optional) The callback function + * @param {Object} scope (Optional) The execution scope (`this`) of the callback function + * @param {String/Array} excludes (Optional) Classes to be excluded, useful when being used with expressions + */ + require: function(expressions, fn, scope, excludes) { + if (fn) { + fn.call(scope); + } + }, + + /** + * Synchronously loads all classes by the given names and all their direct dependencies; optionally executes the given callback function when finishes, within the optional scope. This method is aliased by {@link Ext#syncRequire} for convenience + * @param {String/Array} expressions Can either be a string or an array of string + * @param {Function} fn (Optional) The callback function + * @param {Object} scope (Optional) The execution scope (`this`) of the callback function + * @param {String/Array} excludes (Optional) Classes to be excluded, useful when being used with expressions + */ + syncRequire: function() {}, + + /** + * Explicitly exclude files from being loaded. Useful when used in conjunction with a broad include expression. + * Can be chained with more `require` and `exclude` methods, eg: + * + * Ext.exclude('Ext.data.*').require('*'); + * + * Ext.exclude('widget.button*').require('widget.*'); + * + * @param {Array} excludes + * @return {Object} object contains `require` method for chaining + */ + exclude: function(excludes) { + return { + require: function(expressions, fn, scope) { + return Loader.require(expressions, fn, scope, excludes); + }, + + syncRequire: function(expressions, fn, scope) { + return Loader.syncRequire(expressions, fn, scope, excludes); + } + }; + }, + + /** + * Add a new listener to be executed when all required scripts are fully loaded + * + * @param {Function} fn The function callback to be executed + * @param {Object} scope The execution scope (this) of the callback function + * @param {Boolean} withDomReady Whether or not to wait for document dom ready as well + */ + onReady: function(fn, scope, withDomReady, options) { + var oldFn; + + if (withDomReady !== false && Ext.onDocumentReady) { + oldFn = fn; + + fn = function() { + Ext.onDocumentReady(oldFn, scope, options); + }; + } + + fn.call(scope); + } + }); + + var queue = [], + isClassFileLoaded = {}, + isFileLoaded = {}, + classNameToFilePathMap = {}, + scriptElements = {}, + readyListeners = [], + usedClasses = [], + requiresMap = {}; + + Ext.apply(Loader, { + /** + * @private + */ + documentHead: typeof document != 'undefined' && (document.head || document.getElementsByTagName('head')[0]), + + /** + * Flag indicating whether there are still files being loaded + * @private + */ + isLoading: false, + + /** + * Maintain the queue for all dependencies. Each item in the array is an object of the format: + * + * { + * requires: [...], // The required classes for this queue item + * callback: function() { ... } // The function to execute when all classes specified in requires exist + * } + * + * @private + */ + queue: queue, + + /** + * Maintain the list of files that have already been handled so that they never get double-loaded + * @private + */ + isClassFileLoaded: isClassFileLoaded, + + /** + * @private + */ + isFileLoaded: isFileLoaded, + + /** + * Maintain the list of listeners to execute when all required scripts are fully loaded + * @private + */ + readyListeners: readyListeners, + + /** + * Contains classes referenced in `uses` properties. + * @private + */ + optionalRequires: usedClasses, + + /** + * Map of fully qualified class names to an array of dependent classes. + * @private + */ + requiresMap: requiresMap, + + /** + * @private + */ + numPendingFiles: 0, + + /** + * @private + */ + numLoadedFiles: 0, + + /** @private */ + hasFileLoadError: false, + + /** + * @private + */ + classNameToFilePathMap: classNameToFilePathMap, + + /** + * The number of scripts loading via loadScript. + * @private + */ + scriptsLoading: 0, + + /** + * @private + */ + syncModeEnabled: false, + + scriptElements: scriptElements, + + /** + * Refresh all items in the queue. If all dependencies for an item exist during looping, + * it will execute the callback and call refreshQueue again. Triggers onReady when the queue is + * empty + * @private + */ + refreshQueue: function() { + var ln = queue.length, + i, item, j, requires; + + // When the queue of loading classes reaches zero, trigger readiness + + if (!ln && !Loader.scriptsLoading) { + return Loader.triggerReady(); + } + + for (i = 0; i < ln; i++) { + item = queue[i]; + + if (item) { + requires = item.requires; + + // Don't bother checking when the number of files loaded + // is still less than the array length + if (requires.length > Loader.numLoadedFiles) { + continue; + } + + // Remove any required classes that are loaded + for (j = 0; j < requires.length; ) { + if (Manager.isCreated(requires[j])) { + // Take out from the queue + arrayErase(requires, j, 1); + } + else { + j++; + } + } + + // If we've ended up with no required classes, call the callback + if (item.requires.length === 0) { + arrayErase(queue, i, 1); + item.callback.call(item.scope); + Loader.refreshQueue(); + break; + } + } + } + + return Loader; + }, + + /** + * Inject a script element to document's head, call onLoad and onError accordingly + * @private + */ + injectScriptElement: function(url, onLoad, onError, scope, charset) { + var script = document.createElement('script'), + dispatched = false, + config = Loader.config, + onLoadFn = function() { + + if(!dispatched) { + dispatched = true; + script.onload = script.onreadystatechange = script.onerror = null; + if (typeof config.scriptChainDelay == 'number') { + //free the stack (and defer the next script) + defer(onLoad, config.scriptChainDelay, scope); + } else { + onLoad.call(scope); + } + Loader.cleanupScriptElement(script, config.preserveScripts === false, config.garbageCollect); + } + + }, + onErrorFn = function(arg) { + defer(onError, 1, scope); //free the stack + Loader.cleanupScriptElement(script, config.preserveScripts === false, config.garbageCollect); + }; + + script.type = 'text/javascript'; + script.onerror = onErrorFn; + charset = charset || config.scriptCharset; + if (charset) { + script.charset = charset; + } + + /* + * IE9 Standards mode (and others) SHOULD follow the load event only + * (Note: IE9 supports both onload AND readystatechange events) + */ + if ('addEventListener' in script ) { + script.onload = onLoadFn; + } else if ('readyState' in script) { // for = 200 && status < 300) || (status === 304) + ) { + // Debugger friendly, file names are still shown even though they're eval'ed code + // Breakpoints work on both Firebug and Chrome's Web Inspector + Ext.globalEval(xhr.responseText + "\n//@ sourceURL=" + url); + + onLoad.call(scope); + } + else { + onError.call(Loader, "Failed loading synchronously via XHR: '" + url + "'; please " + + "verify that the file exists. " + + "XHR status code: " + status, synchronous); + } + + // Prevent potential IE memory leak + xhr = null; + } + }, + + // documented above + syncRequire: function() { + var syncModeEnabled = Loader.syncModeEnabled; + + if (!syncModeEnabled) { + Loader.syncModeEnabled = true; + } + + Loader.require.apply(Loader, arguments); + + if (!syncModeEnabled) { + Loader.syncModeEnabled = false; + } + + Loader.refreshQueue(); + }, + + // documented above + require: function(expressions, fn, scope, excludes) { + var excluded = {}, + included = {}, + excludedClassNames = [], + possibleClassNames = [], + classNames = [], + references = [], + callback, + syncModeEnabled, + filePath, expression, exclude, className, + possibleClassName, i, j, ln, subLn; + + if (excludes) { + // Convert possible single string to an array. + excludes = (typeof excludes === 'string') ? [ excludes ] : excludes; + + for (i = 0,ln = excludes.length; i < ln; i++) { + exclude = excludes[i]; + + if (typeof exclude == 'string' && exclude.length > 0) { + excludedClassNames = Manager.getNamesByExpression(exclude); + + for (j = 0,subLn = excludedClassNames.length; j < subLn; j++) { + excluded[excludedClassNames[j]] = true; + } + } + } + } + + // Convert possible single string to an array. + expressions = (typeof expressions === 'string') ? [ expressions ] : (expressions ? expressions : []); + + if (fn) { + if (fn.length > 0) { + callback = function() { + var classes = [], + i, ln; + + for (i = 0,ln = references.length; i < ln; i++) { + classes.push(Manager.get(references[i])); + } + + return fn.apply(this, classes); + }; + } + else { + callback = fn; + } + } + else { + callback = Ext.emptyFn; + } + + scope = scope || Ext.global; + + for (i = 0,ln = expressions.length; i < ln; i++) { + expression = expressions[i]; + + if (typeof expression == 'string' && expression.length > 0) { + possibleClassNames = Manager.getNamesByExpression(expression); + subLn = possibleClassNames.length; + + for (j = 0; j < subLn; j++) { + possibleClassName = possibleClassNames[j]; + + if (excluded[possibleClassName] !== true) { + references.push(possibleClassName); + + if (!Manager.isCreated(possibleClassName) && !included[possibleClassName]) { + included[possibleClassName] = true; + classNames.push(possibleClassName); + } + } + } + } + } + + // If the dynamic dependency feature is not being used, throw an error + // if the dependencies are not defined + if (classNames.length > 0) { + if (!Loader.config.enabled) { + throw new Error("Ext.Loader is not enabled, so dependencies cannot be resolved dynamically. " + + "Missing required class" + ((classNames.length > 1) ? "es" : "") + ": " + classNames.join(', ')); + } + } + else { + callback.call(scope); + return Loader; + } + + syncModeEnabled = Loader.syncModeEnabled; + + if (!syncModeEnabled) { + queue.push({ + requires: classNames.slice(), // this array will be modified as the queue is processed, + // so we need a copy of it + callback: callback, + scope: scope + }); + } + + ln = classNames.length; + + for (i = 0; i < ln; i++) { + className = classNames[i]; + + filePath = Loader.getPath(className); + + // If we are synchronously loading a file that has already been asychronously loaded before + // we need to destroy the script tag and revert the count + // This file will then be forced loaded in synchronous + if (syncModeEnabled && isClassFileLoaded.hasOwnProperty(className)) { + Loader.numPendingFiles--; + Loader.removeScriptElement(filePath); + delete isClassFileLoaded[className]; + } + + if (!isClassFileLoaded.hasOwnProperty(className)) { + isClassFileLoaded[className] = false; + + classNameToFilePathMap[className] = filePath; + + Loader.numPendingFiles++; + Loader.loadScriptFile( + filePath, + pass(Loader.onFileLoaded, [className, filePath], Loader), + pass(Loader.onFileLoadError, [className, filePath], Loader), + Loader, + syncModeEnabled + ); + } + } + + if (syncModeEnabled) { + callback.call(scope); + + if (ln === 1) { + return Manager.get(className); + } + } + + return Loader; + }, + + /** + * @private + * @param {String} className + * @param {String} filePath + */ + onFileLoaded: function(className, filePath) { + Loader.numLoadedFiles++; + + isClassFileLoaded[className] = true; + isFileLoaded[filePath] = true; + + Loader.numPendingFiles--; + + if (Loader.numPendingFiles === 0) { + Loader.refreshQueue(); + } + + if (!Loader.syncModeEnabled && Loader.numPendingFiles === 0 && Loader.isLoading && !Loader.hasFileLoadError) { + var missingClasses = [], + missingPaths = [], + requires, + i, ln, j, subLn; + + for (i = 0,ln = queue.length; i < ln; i++) { + requires = queue[i].requires; + + for (j = 0,subLn = requires.length; j < subLn; j++) { + if (isClassFileLoaded[requires[j]]) { + missingClasses.push(requires[j]); + } + } + } + + if (missingClasses.length < 1) { + return; + } + + missingClasses = Ext.Array.filter(Ext.Array.unique(missingClasses), function(item) { + return !requiresMap.hasOwnProperty(item); + }, Loader); + + for (i = 0,ln = missingClasses.length; i < ln; i++) { + missingPaths.push(classNameToFilePathMap[missingClasses[i]]); + } + + throw new Error("The following classes are not declared even if their files have been " + + "loaded: '" + missingClasses.join("', '") + "'. Please check the source code of their " + + "corresponding files for possible typos: '" + missingPaths.join("', '")); + } + }, + + /** + * @private + */ + onFileLoadError: function(className, filePath, errorMessage, isSynchronous) { + Loader.numPendingFiles--; + Loader.hasFileLoadError = true; + + throw new Error("[Ext.Loader] " + errorMessage); + }, + + /** + * @private + * Ensure that any classes referenced in the `uses` property are loaded. + */ + addUsedClasses: function (classes) { + var cls, i, ln; + + if (classes) { + classes = (typeof classes == 'string') ? [classes] : classes; + for (i = 0, ln = classes.length; i < ln; i++) { + cls = classes[i]; + if (typeof cls == 'string' && !Ext.Array.contains(usedClasses, cls)) { + usedClasses.push(cls); + } + } + } + + return Loader; + }, + + /** + * @private + */ + triggerReady: function() { + var listener, + i, refClasses = usedClasses; + + if (Loader.isLoading) { + Loader.isLoading = false; + + if (refClasses.length !== 0) { + // Clone then empty the array to eliminate potential recursive loop issue + refClasses = refClasses.slice(); + usedClasses.length = 0; + // this may immediately call us back if all 'uses' classes + // have been loaded + Loader.require(refClasses, Loader.triggerReady, Loader); + return Loader; + } + } + + // this method can be called with Loader.isLoading either true or false + // (can be called with false when all 'uses' classes are already loaded) + // this may bypass the above if condition + while (readyListeners.length && !Loader.isLoading) { + // calls to refreshQueue may re-enter triggerReady + // so we cannot necessarily iterate the readyListeners array + listener = readyListeners.shift(); + listener.fn.call(listener.scope); + } + + return Loader; + }, + + // Documented above already + onReady: function(fn, scope, withDomReady, options) { + var oldFn; + + if (withDomReady !== false && Ext.onDocumentReady) { + oldFn = fn; + + fn = function() { + Ext.onDocumentReady(oldFn, scope, options); + }; + } + + if (!Loader.isLoading) { + fn.call(scope); + } + else { + readyListeners.push({ + fn: fn, + scope: scope + }); + } + }, + + /** + * @private + * @param {String} className + */ + historyPush: function(className) { + if (className && isClassFileLoaded.hasOwnProperty(className) && !isInHistory[className]) { + isInHistory[className] = true; + history.push(className); + } + return Loader; + } + }); + + /** + * Turns on or off the "cache buster" applied to dynamically loaded scripts. Normally + * dynamically loaded scripts have an extra query parameter appended to avoid stale + * cached scripts. This method can be used to disable this mechanism, and is primarily + * useful for testing. This is done using a cookie. + * @param {Boolean} disable True to disable the cache buster. + * @param {String} [path="/"] An optional path to scope the cookie. + * @private + */ + Ext.disableCacheBuster = function (disable, path) { + var date = new Date(); + date.setTime(date.getTime() + (disable ? 10*365 : -1) * 24*60*60*1000); + date = date.toGMTString(); + document.cookie = 'ext-cache=1; expires=' + date + '; path='+(path || '/'); + }; + + + /** + * Convenient alias of {@link Ext.Loader#require}. Please see the introduction documentation of + * {@link Ext.Loader} for examples. + * @member Ext + * @method require + */ + Ext.require = alias(Loader, 'require'); + + /** + * Synchronous version of {@link Ext#require}, convenient alias of {@link Ext.Loader#syncRequire}. + * + * @member Ext + * @method syncRequire + */ + Ext.syncRequire = alias(Loader, 'syncRequire'); + + /** + * Convenient shortcut to {@link Ext.Loader#exclude} + * @member Ext + * @method exclude + */ + Ext.exclude = alias(Loader, 'exclude'); + + /** + * @member Ext + * @method onReady + */ + Ext.onReady = function(fn, scope, options) { + Loader.onReady(fn, scope, true, options); + }; + + /** + * @cfg {String[]} requires + * @member Ext.Class + * List of classes that have to be loaded before instantiating this class. + * For example: + * + * Ext.define('Mother', { + * requires: ['Child'], + * giveBirth: function() { + * // we can be sure that child class is available. + * return new Child(); + * } + * }); + */ + Class.registerPreprocessor('loader', function(cls, data, hooks, continueFn) { + var me = this, + dependencies = [], + dependency, + className = Manager.getName(cls), + i, j, ln, subLn, value, propertyName, propertyValue, + requiredMap, requiredDep; + + /* + Loop through the dependencyProperties, look for string class names and push + them into a stack, regardless of whether the property's value is a string, array or object. For example: + { + extend: 'Ext.MyClass', + requires: ['Ext.some.OtherClass'], + mixins: { + observable: 'Ext.util.Observable'; + } + } + which will later be transformed into: + { + extend: Ext.MyClass, + requires: [Ext.some.OtherClass], + mixins: { + observable: Ext.util.Observable; + } + } + */ + + for (i = 0,ln = dependencyProperties.length; i < ln; i++) { + propertyName = dependencyProperties[i]; + + if (data.hasOwnProperty(propertyName)) { + propertyValue = data[propertyName]; + + if (typeof propertyValue == 'string') { + dependencies.push(propertyValue); + } + else if (propertyValue instanceof Array) { + for (j = 0, subLn = propertyValue.length; j < subLn; j++) { + value = propertyValue[j]; + + if (typeof value == 'string') { + dependencies.push(value); + } + } + } + else if (typeof propertyValue != 'function') { + for (j in propertyValue) { + if (propertyValue.hasOwnProperty(j)) { + value = propertyValue[j]; + + if (typeof value == 'string') { + dependencies.push(value); + } + } + } + } + } + } + + if (dependencies.length === 0) { + return; + } + + var deadlockPath = [], + detectDeadlock; + + /* + Automatically detect deadlocks before-hand, + will throw an error with detailed path for ease of debugging. Examples of deadlock cases: + + - A extends B, then B extends A + - A requires B, B requires C, then C requires A + + The detectDeadlock function will recursively transverse till the leaf, hence it can detect deadlocks + no matter how deep the path is. + */ + + if (className) { + requiresMap[className] = dependencies; + requiredMap = Loader.requiredByMap || (Loader.requiredByMap = {}); + + for (i = 0,ln = dependencies.length; i < ln; i++) { + dependency = dependencies[i]; + (requiredMap[dependency] || (requiredMap[dependency] = [])).push(className); + } + detectDeadlock = function(cls) { + deadlockPath.push(cls); + + if (requiresMap[cls]) { + if (Ext.Array.contains(requiresMap[cls], className)) { + throw new Error("Deadlock detected while loading dependencies! '" + className + "' and '" + + deadlockPath[1] + "' " + "mutually require each other. Path: " + + deadlockPath.join(' -> ') + " -> " + deadlockPath[0]); + } + + for (i = 0,ln = requiresMap[cls].length; i < ln; i++) { + detectDeadlock(requiresMap[cls][i]); + } + } + }; + + detectDeadlock(className); + } + + + Loader.require(dependencies, function() { + for (i = 0,ln = dependencyProperties.length; i < ln; i++) { + propertyName = dependencyProperties[i]; + + if (data.hasOwnProperty(propertyName)) { + propertyValue = data[propertyName]; + + if (typeof propertyValue == 'string') { + data[propertyName] = Manager.get(propertyValue); + } + else if (propertyValue instanceof Array) { + for (j = 0, subLn = propertyValue.length; j < subLn; j++) { + value = propertyValue[j]; + + if (typeof value == 'string') { + data[propertyName][j] = Manager.get(value); + } + } + } + else if (typeof propertyValue != 'function') { + for (var k in propertyValue) { + if (propertyValue.hasOwnProperty(k)) { + value = propertyValue[k]; + + if (typeof value == 'string') { + data[propertyName][k] = Manager.get(value); + } + } + } + } + } + } + + continueFn.call(me, cls, data, hooks); + }); + + return false; + }, true, 'after', 'className'); + + /** + * @cfg {String[]} uses + * @member Ext.Class + * List of optional classes to load together with this class. These aren't neccessarily loaded before + * this class is created, but are guaranteed to be available before Ext.onReady listeners are + * invoked. For example: + * + * Ext.define('Mother', { + * uses: ['Child'], + * giveBirth: function() { + * // This code might, or might not work: + * // return new Child(); + * + * // Instead use Ext.create() to load the class at the spot if not loaded already: + * return Ext.create('Child'); + * } + * }); + */ + Manager.registerPostprocessor('uses', function(name, cls, data) { + var uses = data.uses; + if (uses) { + Loader.addUsedClasses(uses); + } + }); + + Manager.onCreated(Loader.historyPush); +}; + +/** + * @author Brian Moeskau + * @docauthor Brian Moeskau + * + * A wrapper class for the native JavaScript Error object that adds a few useful capabilities for handling + * errors in an Ext application. When you use Ext.Error to {@link #raise} an error from within any class that + * uses the Ext 4 class system, the Error class can automatically add the source class and method from which + * the error was raised. It also includes logic to automatically log the eroor to the console, if available, + * with additional metadata about the error. In all cases, the error will always be thrown at the end so that + * execution will halt. + * + * Ext.Error also offers a global error {@link #handle handling} method that can be overridden in order to + * handle application-wide errors in a single spot. You can optionally {@link #ignore} errors altogether, + * although in a real application it's usually a better idea to override the handling function and perform + * logging or some other method of reporting the errors in a way that is meaningful to the application. + * + * At its simplest you can simply raise an error as a simple string from within any code: + * + * Example usage: + * + * Ext.Error.raise('Something bad happened!'); + * + * If raised from plain JavaScript code, the error will be logged to the console (if available) and the message + * displayed. In most cases however you'll be raising errors from within a class, and it may often be useful to add + * additional metadata about the error being raised. The {@link #raise} method can also take a config object. + * In this form the `msg` attribute becomes the error description, and any other data added to the config gets + * added to the error object and, if the console is available, logged to the console for inspection. + * + * Example usage: + * + * Ext.define('Ext.Foo', { + * doSomething: function(option){ + * if (someCondition === false) { + * Ext.Error.raise({ + * msg: 'You cannot do that!', + * option: option, // whatever was passed into the method + * 'error code': 100 // other arbitrary info + * }); + * } + * } + * }); + * + * If a console is available (that supports the `console.dir` function) you'll see console output like: + * + * An error was raised with the following data: + * option: Object { foo: "bar"} + * foo: "bar" + * error code: 100 + * msg: "You cannot do that!" + * sourceClass: "Ext.Foo" + * sourceMethod: "doSomething" + * + * uncaught exception: You cannot do that! + * + * As you can see, the error will report exactly where it was raised and will include as much information as the + * raising code can usefully provide. + * + * If you want to handle all application errors globally you can simply override the static {@link #handle} method + * and provide whatever handling logic you need. If the method returns true then the error is considered handled + * and will not be thrown to the browser. If anything but true is returned then the error will be thrown normally. + * + * Example usage: + * + * Ext.Error.handle = function(err) { + * if (err.someProperty == 'NotReallyAnError') { + * // maybe log something to the application here if applicable + * return true; + * } + * // any non-true return value (including none) will cause the error to be thrown + * } + * + */ +Ext.Error = Ext.extend(Error, { + statics: { + /** + * @property {Boolean} ignore + * Static flag that can be used to globally disable error reporting to the browser if set to true + * (defaults to false). Note that if you ignore Ext errors it's likely that some other code may fail + * and throw a native JavaScript error thereafter, so use with caution. In most cases it will probably + * be preferable to supply a custom error {@link #handle handling} function instead. + * + * Example usage: + * + * Ext.Error.ignore = true; + * + * @static + */ + ignore: false, + + /** + * @property {Boolean} notify + * Static flag that can be used to globally control error notification to the user. Unlike + * Ex.Error.ignore, this does not effect exceptions. They are still thrown. This value can be + * set to false to disable the alert notification (default is true for IE6 and IE7). + * + * Only the first error will generate an alert. Internally this flag is set to false when the + * first error occurs prior to displaying the alert. + * + * This flag is not used in a release build. + * + * Example usage: + * + * Ext.Error.notify = false; + * + * @static + */ + //notify: Ext.isIE6 || Ext.isIE7, + + /** + * Raise an error that can include additional data and supports automatic console logging if available. + * You can pass a string error message or an object with the `msg` attribute which will be used as the + * error message. The object can contain any other name-value attributes (or objects) to be logged + * along with the error. + * + * Note that after displaying the error message a JavaScript error will ultimately be thrown so that + * execution will halt. + * + * Example usage: + * + * Ext.Error.raise('A simple string error message'); + * + * // or... + * + * Ext.define('Ext.Foo', { + * doSomething: function(option){ + * if (someCondition === false) { + * Ext.Error.raise({ + * msg: 'You cannot do that!', + * option: option, // whatever was passed into the method + * 'error code': 100 // other arbitrary info + * }); + * } + * } + * }); + * + * @param {String/Object} err The error message string, or an object containing the attribute "msg" that will be + * used as the error message. Any other data included in the object will also be logged to the browser console, + * if available. + * @static + */ + raise: function(err){ + err = err || {}; + if (Ext.isString(err)) { + err = { msg: err }; + } + + var method = this.raise.caller, + msg; + + if (method) { + if (method.$name) { + err.sourceMethod = method.$name; + } + if (method.$owner) { + err.sourceClass = method.$owner.$className; + } + } + + if (Ext.Error.handle(err) !== true) { + msg = Ext.Error.prototype.toString.call(err); + + Ext.log({ + msg: msg, + level: 'error', + dump: err, + stack: true + }); + + throw new Ext.Error(err); + } + }, + + /** + * Globally handle any Ext errors that may be raised, optionally providing custom logic to + * handle different errors individually. Return true from the function to bypass throwing the + * error to the browser, otherwise the error will be thrown and execution will halt. + * + * Example usage: + * + * Ext.Error.handle = function(err) { + * if (err.someProperty == 'NotReallyAnError') { + * // maybe log something to the application here if applicable + * return true; + * } + * // any non-true return value (including none) will cause the error to be thrown + * } + * + * @param {Ext.Error} err The Ext.Error object being raised. It will contain any attributes that were originally + * raised with it, plus properties about the method and class from which the error originated (if raised from a + * class that uses the Ext 4 class system). + * @static + */ + handle: function(){ + return Ext.Error.ignore; + } + }, + + // This is the standard property that is the name of the constructor. + name: 'Ext.Error', + + /** + * Creates new Error object. + * @param {String/Object} config The error message string, or an object containing the + * attribute "msg" that will be used as the error message. Any other data included in + * the object will be applied to the error instance and logged to the browser console, if available. + */ + constructor: function(config){ + if (Ext.isString(config)) { + config = { msg: config }; + } + + var me = this; + + Ext.apply(me, config); + + me.message = me.message || me.msg; // 'message' is standard ('msg' is non-standard) + // note: the above does not work in old WebKit (me.message is readonly) (Safari 4) + }, + + /** + * Provides a custom string representation of the error object. This is an override of the base JavaScript + * `Object.toString` method, which is useful so that when logged to the browser console, an error object will + * be displayed with a useful message instead of `[object Object]`, the default `toString` result. + * + * The default implementation will include the error message along with the raising class and method, if available, + * but this can be overridden with a custom implementation either at the prototype level (for all errors) or on + * a particular error instance, if you want to provide a custom description that will show up in the console. + * @return {String} The error message. If raised from within the Ext 4 class system, the error message will also + * include the raising class and method names, if available. + */ + toString: function(){ + var me = this, + className = me.sourceClass ? me.sourceClass : '', + methodName = me.sourceMethod ? '.' + me.sourceMethod + '(): ' : '', + msg = me.msg || '(No description provided)'; + + return className + methodName + msg; + } +}); + +/* + * Create a function that will throw an error if called (in debug mode) with a message that + * indicates the method has been removed. + * @param {String} suggestion Optional text to include in the message (a workaround perhaps). + * @return {Function} The generated function. + * @private + */ +Ext.deprecated = function (suggestion) { + if (!suggestion) { + suggestion = ''; + } + + function fail () { + Ext.Error.raise('The method "' + fail.$owner.$className + '.' + fail.$name + + '" has been removed. ' + suggestion); + } + + return fail; + return Ext.emptyFn; +}; + +/* + * This mechanism is used to notify the user of the first error encountered on the page. This + * was previously internal to Ext.Error.raise and is a desirable feature since errors often + * slip silently under the radar. It cannot live in Ext.Error.raise since there are times + * where exceptions are handled in a try/catch. + */ +(function () { + var timer, errors = 0, + win = Ext.global, + msg; + + if (typeof window === 'undefined') { + return; // build system or some such environment... + } + + // This method is called to notify the user of the current error status. + function notify () { + var counters = Ext.log.counters, + supports = Ext.supports, + hasOnError = supports && supports.WindowOnError; // TODO - timing + + // Put log counters to the status bar (for most browsers): + if (counters && (counters.error + counters.warn + counters.info + counters.log)) { + msg = [ 'Logged Errors:',counters.error, 'Warnings:',counters.warn, + 'Info:',counters.info, 'Log:',counters.log].join(' '); + if (errors) { + msg = '*** Errors: ' + errors + ' - ' + msg; + } else if (counters.error) { + msg = '*** ' + msg; + } + win.status = msg; + } + + // Display an alert on the first error: + if (!Ext.isDefined(Ext.Error.notify)) { + Ext.Error.notify = Ext.isIE6 || Ext.isIE7; // TODO - timing + } + if (Ext.Error.notify && (hasOnError ? errors : (counters && counters.error))) { + Ext.Error.notify = false; + + if (timer) { + win.clearInterval(timer); // ticks can queue up so stop... + timer = null; + } + + alert('Unhandled error on page: See console or log'); + poll(); + } + } + + // Sets up polling loop. This is the only way to know about errors in some browsers + // (Opera/Safari) and is the only way to update the status bar for warnings and other + // non-errors. + function poll () { + timer = win.setInterval(notify, 1000); + } + + // window.onerror sounds ideal but it prevents the built-in error dialog from doing + // its (better) thing. + poll(); +}()); + + +/** + * @class Ext.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.JSON = (new(function() { + var me = this, + encodingFunction, + decodingFunction, + useNative = null, + useHasOwn = !! {}.hasOwnProperty, + isNative = function() { + if (useNative === null) { + useNative = Ext.USE_NATIVE_JSON && window.JSON && JSON.toString() == '[object JSON]'; + } + return useNative; + }, + pad = function(n) { + return n < 10 ? "0" + n : n; + }, + doDecode = function(json) { + return eval("(" + json + ')'); + }, + doEncode = function(o, newline) { + // http://jsperf.com/is-undefined + if (o === null || o === undefined) { + return "null"; + } else if (Ext.isDate(o)) { + return Ext.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); + } + // Allow custom zerialization by adding a toJSON method to any object type. + // Date/String have a toJSON in some environments, so check these first. + else if (o.toJSON) { + return o.toJSON(); + } else if (Ext.isArray(o)) { + return encodeArray(o, newline); + } else if (Ext.isObject(o)) { + return encodeObject(o, newline); + } else if (typeof o === "function") { + return "null"; + } + return 'undefined'; + }, + m = { + "\b": '\\b', + "\t": '\\t', + "\n": '\\n', + "\f": '\\f', + "\r": '\\r', + '"': '\\"', + "\\": '\\\\', + '\x0b': '\\u000b' //ie doesn't handle \v + }, + charToReplace = /[\\\"\x00-\x1f\x7f-\uffff]/g, + encodeString = function(s) { + return '"' + s.replace(charToReplace, function(a) { + var c = m[a]; + return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); + }) + '"'; + }, + + encodeArrayPretty = function(o, newline) { + var len = o.length, + cnewline = newline + ' ', + sep = ',' + cnewline, + a = ["[", cnewline], // Note newline in case there are no members + i; + + for (i = 0; i < len; i += 1) { + a.push(doEncode(o[i], cnewline), sep); + } + + // Overwrite trailing comma (or empty string) + a[a.length - 1] = newline + ']'; + + return a.join(''); + }, + + encodeObjectPretty = function(o, newline) { + var cnewline = newline + ' ', + sep = ',' + cnewline, + a = ["{", cnewline], // Note newline in case there are no members + i; + + for (i in o) { + if (!useHasOwn || o.hasOwnProperty(i)) { + a.push(doEncode(i) + ': ' + doEncode(o[i], cnewline), sep); + } + } + + // Overwrite trailing comma (or empty string) + a[a.length - 1] = newline + '}'; + + return a.join(''); + }, + + encodeArray = function(o, newline) { + if (newline) { + return encodeArrayPretty(o, newline); + } + + var a = ["[", ""], // Note empty string in case there are no serializable members. + len = o.length, + i; + for (i = 0; i < len; i += 1) { + a.push(doEncode(o[i]), ','); + } + // Overwrite trailing comma (or empty string) + a[a.length - 1] = ']'; + return a.join(""); + }, + + encodeObject = function(o, newline) { + if (newline) { + return encodeObjectPretty(o, newline); + } + + var a = ["{", ""], // Note empty string in case there are no serializable members. + i; + for (i in o) { + if (!useHasOwn || o.hasOwnProperty(i)) { + a.push(doEncode(i), ":", doEncode(o[i]), ','); + } + } + // Overwrite trailing comma (or empty string) + a[a.length - 1] = '}'; + return a.join(""); + }; + + /** + * The function which {@link #encode} uses to encode all javascript values to their JSON representations + * when {@link Ext#USE_NATIVE_JSON} is `false`. + * + * This is made public so that it can be replaced with a custom implementation. + * + * @param {Object} o Any javascript value to be converted to its JSON representation + * @return {String} The JSON representation of the passed value. + * @method + */ + me.encodeValue = doEncode; + + /** + * Encodes a Date. This returns the actual string which is inserted into the JSON string as the literal expression. + * **The returned value includes enclosing double quotation marks.** + * + * The default return format is "yyyy-mm-ddThh:mm:ss". + * + * To override this: + * Ext.JSON.encodeDate = function(d) { + * return Ext.Date.format(d, '"Y-m-d"'); + * }; + * + * @param {Date} d The Date to encode + * @return {String} The string literal to use in a JSON string. + */ + me.encodeDate = function(o) { + return '"' + o.getFullYear() + "-" + + pad(o.getMonth() + 1) + "-" + + pad(o.getDate()) + "T" + + pad(o.getHours()) + ":" + + pad(o.getMinutes()) + ":" + + pad(o.getSeconds()) + '"'; + }; + + /** + * Encodes an Object, Array or other value. + * + * If the environment's native JSON encoding is not being used ({@link Ext#USE_NATIVE_JSON} is not set, or the environment does not support it), then + * ExtJS's encoding will be used. This allows the developer to add a `toJSON` method to their classes which need serializing to return a valid + * JSON representation of the object. + * + * @param {Object} o The variable to encode + * @return {String} The JSON string + */ + me.encode = function(o) { + if (!encodingFunction) { + // setup encoding function on first access + encodingFunction = isNative() ? JSON.stringify : me.encodeValue; + } + return encodingFunction(o); + }; + + /** + * Decodes (parses) a JSON string to an object. If the JSON is invalid, this function throws a SyntaxError unless the safe option is set. + * @param {String} json The JSON string + * @param {Boolean} safe (optional) Whether to return null or throw an exception if the JSON is invalid. + * @return {Object} The resulting object + */ + me.decode = function(json, safe) { + if (!decodingFunction) { + // setup decoding function on first access + decodingFunction = isNative() ? JSON.parse : doDecode; + } + try { + return decodingFunction(json); + } catch (e) { + if (safe === true) { + return null; + } + Ext.Error.raise({ + sourceClass: "Ext.JSON", + sourceMethod: "decode", + msg: "You're trying to decode an invalid JSON String: " + json + }); + } + }; +})()); +/** + * Shorthand for {@link Ext.JSON#encode} + * @member Ext + * @method encode + * @inheritdoc Ext.JSON#encode + */ +Ext.encode = Ext.JSON.encode; +/** + * Shorthand for {@link Ext.JSON#decode} + * @member Ext + * @method decode + * @inheritdoc Ext.JSON#decode + */ +Ext.decode = Ext.JSON.decode; +/** + * @class Ext + * + * The Ext namespace (global object) encapsulates all classes, singletons, and + * utility methods provided by Sencha's libraries. + * + * Most user interface Components are at a lower level of nesting in the namespace, + * but many common utility functions are provided as direct properties of the Ext namespace. + * + * Also many frequently used methods from other classes are provided as shortcuts + * within the Ext namespace. For example {@link Ext#getCmp Ext.getCmp} aliases + * {@link Ext.ComponentManager#get Ext.ComponentManager.get}. + * + * Many applications are initiated with {@link Ext#onReady Ext.onReady} which is + * called once the DOM is ready. This ensures all scripts have been loaded, + * preventing dependency issues. For example: + * + * Ext.onReady(function(){ + * new Ext.Component({ + * renderTo: document.body, + * html: 'DOM ready!' + * }); + * }); + * + * For more information about how to use the Ext classes, see: + * + * - The Learning Center + * - The FAQ + * - The forums + * + * @singleton + */ +Ext.apply(Ext, { + userAgent: navigator.userAgent.toLowerCase(), + cache: {}, + idSeed: 1000, + windowId: 'ext-window', + documentId: 'ext-document', + + /** + * True when the document is fully initialized and ready for action + */ + isReady: false, + + /** + * True to automatically uncache orphaned Ext.Elements periodically + */ + enableGarbageCollector: true, + + /** + * True to automatically purge event listeners during garbageCollection. + */ + enableListenerCollection: true, + + addCacheEntry: function(id, el, dom) { + dom = dom || el.dom; + + if (!dom) { + // Without the DOM node we can't GC the entry + Ext.Error.raise('Cannot add an entry to the element cache without the DOM node'); + } + + var key = id || (el && el.id) || dom.id, + entry = Ext.cache[key] || (Ext.cache[key] = { + data: {}, + events: {}, + + dom: dom, + + // Skip garbage collection for special elements (window, document, iframes) + skipGarbageCollection: !!(dom.getElementById || dom.navigator) + }); + + if (el) { + el.$cache = entry; + // Inject the back link from the cache in case the cache entry + // had already been created by Ext.fly. Ext.fly creates a cache entry with no el link. + entry.el = el; + } + + return entry; + }, + + /** + * Generates unique ids. If the element already has an id, it is unchanged + * @param {HTMLElement/Ext.Element} [el] The element to generate an id for + * @param {String} prefix (optional) Id prefix (defaults "ext-gen") + * @return {String} The generated Id. + */ + id: function(el, prefix) { + var me = this, + sandboxPrefix = ''; + el = Ext.getDom(el, true) || {}; + if (el === document) { + el.id = me.documentId; + } + else if (el === window) { + el.id = me.windowId; + } + if (!el.id) { + if (me.isSandboxed) { + sandboxPrefix = Ext.sandboxName.toLowerCase() + '-'; + } + el.id = sandboxPrefix + (prefix || "ext-gen") + (++Ext.idSeed); + } + return el.id; + }, + + escapeId: (function(){ + var validIdRe = /^[a-zA-Z_][a-zA-Z0-9_\-]*$/i, + escapeRx = /([\W]{1})/g, + leadingNumRx = /^(\d)/g, + escapeFn = function(match, capture){ + return "\\" + capture; + }, + numEscapeFn = function(match, capture){ + return '\\00' + capture.charCodeAt(0).toString(16) + ' '; + }; + + return function(id) { + return validIdRe.test(id) + ? id + // replace the number portion last to keep the trailing ' ' + // from being escaped + : id.replace(escapeRx, escapeFn) + .replace(leadingNumRx, numEscapeFn); + }; + }()), + + /** + * Returns the current document body as an {@link Ext.Element}. + * @return Ext.Element The document body + */ + getBody: (function() { + var body; + return function() { + return body || (body = Ext.get(document.body)); + }; + }()), + + /** + * Returns the current document head as an {@link Ext.Element}. + * @return Ext.Element The document head + * @method + */ + getHead: (function() { + var head; + return function() { + return head || (head = Ext.get(document.getElementsByTagName("head")[0])); + }; + }()), + + /** + * Returns the current HTML document object as an {@link Ext.Element}. + * @return Ext.Element The document + */ + getDoc: (function() { + var doc; + return function() { + return doc || (doc = Ext.get(document)); + }; + }()), + + /** + * This is shorthand reference to {@link Ext.ComponentManager#get}. + * Looks up an existing {@link Ext.Component Component} by {@link Ext.Component#id id} + * + * @param {String} id The component {@link Ext.Component#id id} + * @return Ext.Component The Component, `undefined` if not found, or `null` if a + * Class was found. + */ + getCmp: function(id) { + return Ext.ComponentManager.get(id); + }, + + /** + * Returns the current orientation of the mobile device + * @return {String} Either 'portrait' or 'landscape' + */ + getOrientation: function() { + return window.innerHeight > window.innerWidth ? 'portrait' : 'landscape'; + }, + + /** + * Attempts to destroy any objects passed to it by removing all event listeners, removing them from the + * DOM (if applicable) and calling their destroy functions (if available). This method is primarily + * intended for arguments of type {@link Ext.Element} and {@link Ext.Component}, but any subclass of + * {@link Ext.util.Observable} can be passed in. Any number of elements and/or components can be + * passed into this function in a single call as separate arguments. + * + * @param {Ext.Element/Ext.Component/Ext.Element[]/Ext.Component[]...} args + * An {@link Ext.Element}, {@link Ext.Component}, or an Array of either of these to destroy + */ + destroy: function() { + var ln = arguments.length, + i, arg; + + for (i = 0; i < ln; i++) { + arg = arguments[i]; + if (arg) { + if (Ext.isArray(arg)) { + this.destroy.apply(this, arg); + } + else if (Ext.isFunction(arg.destroy)) { + arg.destroy(); + } + else if (arg.dom) { + arg.remove(); + } + } + } + }, + + /** + * Execute a callback function in a particular scope. If no function is passed the call is ignored. + * + * For example, these lines are equivalent: + * + * Ext.callback(myFunc, this, [arg1, arg2]); + * Ext.isFunction(myFunc) && myFunc.apply(this, [arg1, arg2]); + * + * @param {Function} callback The callback to execute + * @param {Object} [scope] The scope to execute in + * @param {Array} [args] The arguments to pass to the function + * @param {Number} [delay] Pass a number to delay the call by a number of milliseconds. + */ + callback: function(callback, scope, args, delay){ + if(Ext.isFunction(callback)){ + args = args || []; + scope = scope || window; + if (delay) { + Ext.defer(callback, delay, scope, args); + } else { + callback.apply(scope, args); + } + } + }, + + /** + * Alias for {@link Ext.String#htmlEncode}. + * @inheritdoc Ext.String#htmlEncode + */ + htmlEncode : function(value) { + return Ext.String.htmlEncode(value); + }, + + /** + * Alias for {@link Ext.String#htmlDecode}. + * @inheritdoc Ext.String#htmlDecode + */ + htmlDecode : function(value) { + return Ext.String.htmlDecode(value); + }, + + /** + * Alias for {@link Ext.String#urlAppend}. + * @inheritdoc Ext.String#urlAppend + */ + urlAppend : function(url, s) { + return Ext.String.urlAppend(url, s); + } +}); + + +Ext.ns = Ext.namespace; + +// for old browsers +window.undefined = window.undefined; + +/** + * @class Ext + */ +(function(){ +/* +FF 3.6 - Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.17) Gecko/20110420 Firefox/3.6.17 +FF 4.0.1 - Mozilla/5.0 (Windows NT 5.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1 +FF 5.0 - Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0 + +IE6 - Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1;) +IE7 - Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1;) +IE8 - Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0) +IE9 - Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E) + +Chrome 11 - Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.60 Safari/534.24 + +Safari 5 - Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1 + +Opera 11.11 - Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11 +*/ + var check = function(regex){ + return regex.test(Ext.userAgent); + }, + isStrict = document.compatMode == "CSS1Compat", + version = function (is, regex) { + var m; + return (is && (m = regex.exec(Ext.userAgent))) ? parseFloat(m[1]) : 0; + }, + docMode = document.documentMode, + isOpera = check(/opera/), + isOpera10_5 = isOpera && check(/version\/10\.5/), + isChrome = check(/\bchrome\b/), + isWebKit = check(/webkit/), + isSafari = !isChrome && check(/safari/), + isSafari2 = isSafari && check(/applewebkit\/4/), // unique to Safari 2 + isSafari3 = isSafari && check(/version\/3/), + isSafari4 = isSafari && check(/version\/4/), + isSafari5_0 = isSafari && check(/version\/5\.0/), + isSafari5 = isSafari && check(/version\/5/), + isIE = !isOpera && check(/msie/), + isIE7 = isIE && ((check(/msie 7/) && docMode != 8 && docMode != 9) || docMode == 7), + isIE8 = isIE && ((check(/msie 8/) && docMode != 7 && docMode != 9) || docMode == 8), + isIE9 = isIE && ((check(/msie 9/) && docMode != 7 && docMode != 8) || docMode == 9), + isIE6 = isIE && check(/msie 6/), + isGecko = !isWebKit && check(/gecko/), + isGecko3 = isGecko && check(/rv:1\.9/), + isGecko4 = isGecko && check(/rv:2\.0/), + isGecko5 = isGecko && check(/rv:5\./), + isGecko10 = isGecko && check(/rv:10\./), + isFF3_0 = isGecko3 && check(/rv:1\.9\.0/), + isFF3_5 = isGecko3 && check(/rv:1\.9\.1/), + isFF3_6 = isGecko3 && check(/rv:1\.9\.2/), + isWindows = check(/windows|win32/), + isMac = check(/macintosh|mac os x/), + isLinux = check(/linux/), + scrollbarSize = null, + chromeVersion = version(true, /\bchrome\/(\d+\.\d+)/), + firefoxVersion = version(true, /\bfirefox\/(\d+\.\d+)/), + ieVersion = version(isIE, /msie (\d+\.\d+)/), + operaVersion = version(isOpera, /version\/(\d+\.\d+)/), + safariVersion = version(isSafari, /version\/(\d+\.\d+)/), + webKitVersion = version(isWebKit, /webkit\/(\d+\.\d+)/), + isSecure = /^https/i.test(window.location.protocol), + nullLog; + + // remove css image flicker + try { + document.execCommand("BackgroundImageCache", false, true); + } catch(e) {} + + + var primitiveRe = /string|number|boolean/; + function dumpObject (object) { + var member, type, value, name, + members = []; + + // Cannot use Ext.encode since it can recurse endlessly (if we're lucky) + // ...and the data could be prettier! + for (name in object) { + if (object.hasOwnProperty(name)) { + value = object[name]; + + type = typeof value; + if (type == "function") { + continue; + } + + if (type == 'undefined') { + member = type; + } else if (value === null || primitiveRe.test(type) || Ext.isDate(value)) { + member = Ext.encode(value); + } else if (Ext.isArray(value)) { + member = '[ ]'; + } else if (Ext.isObject(value)) { + member = '{ }'; + } else { + member = type; + } + members.push(Ext.encode(name) + ': ' + member); + } + } + + if (members.length) { + return ' \nData: {\n ' + members.join(',\n ') + '\n}'; + } + return ''; + } + + function log (message) { + var options, dump, + con = Ext.global.console, + level = 'log', + indent = log.indent || 0, + stack, + out, + max; + + log.indent = indent; + + if (typeof message != 'string') { + options = message; + message = options.msg || ''; + level = options.level || level; + dump = options.dump; + stack = options.stack; + + if (options.indent) { + ++log.indent; + } else if (options.outdent) { + log.indent = indent = Math.max(indent - 1, 0); + } + + if (dump && !(con && con.dir)) { + message += dumpObject(dump); + dump = null; + } + } + + if (arguments.length > 1) { + message += Array.prototype.slice.call(arguments, 1).join(''); + } + + message = indent ? Ext.String.repeat(' ', log.indentSize * indent) + message : message; + // w/o console, all messages are equal, so munge the level into the message: + if (level != 'log') { + message = '[' + level.charAt(0).toUpperCase() + '] ' + message; + } + + // Not obvious, but 'console' comes and goes when Firebug is turned on/off, so + // an early test may fail either direction if Firebug is toggled. + // + if (con) { // if (Firebug-like console) + if (con[level]) { + con[level](message); + } else { + con.log(message); + } + + if (dump) { + con.dir(dump); + } + + if (stack && con.trace) { + // Firebug's console.error() includes a trace already... + if (!con.firebug || level != 'error') { + con.trace(); + } + } + } else { + if (Ext.isOpera) { + opera.postError(message); + } else { + out = log.out; + max = log.max; + + if (out.length >= max) { + // this formula allows out.max to change (via debugger), where the + // more obvious "max/4" would not quite be the same + Ext.Array.erase(out, 0, out.length - 3 * Math.floor(max / 4)); // keep newest 75% + } + + out.push(message); + } + } + + // Mostly informational, but the Ext.Error notifier uses them: + ++log.count; + ++log.counters[level]; + } + + function logx (level, args) { + if (typeof args[0] == 'string') { + args.unshift({}); + } + args[0].level = level; + log.apply(this, args); + } + + log.error = function () { + logx('error', Array.prototype.slice.call(arguments)); + }; + log.info = function () { + logx('info', Array.prototype.slice.call(arguments)); + }; + log.warn = function () { + logx('warn', Array.prototype.slice.call(arguments)); + }; + + log.count = 0; + log.counters = { error: 0, warn: 0, info: 0, log: 0 }; + log.indentSize = 2; + log.out = []; + log.max = 750; + log.show = function () { + window.open('','extlog').document.write([ + ''].join('')); + }; + + nullLog = function () {}; + nullLog.info = nullLog.warn = nullLog.error = Ext.emptyFn; + + Ext.setVersion('extjs', '4.1.0'); + Ext.apply(Ext, { + /** + * @property {String} SSL_SECURE_URL + * URL to a blank file used by Ext when in secure mode for iframe src and onReady src + * to prevent the IE insecure content warning (`'about:blank'`, except for IE + * in secure mode, which is `'javascript:""'`). + */ + SSL_SECURE_URL : isSecure && isIE ? 'javascript:\'\'' : 'about:blank', + + /** + * @property {Boolean} enableFx + * True if the {@link Ext.fx.Anim} Class is available. + */ + + /** + * @property {Boolean} scopeResetCSS + * True to scope the reset CSS to be just applied to Ext components. Note that this + * wraps root containers with an additional element. Also remember that when you turn + * on this option, you have to use ext-all-scoped (unless you use the bootstrap.js to + * load your javascript, in which case it will be handled for you). + */ + scopeResetCSS : Ext.buildSettings.scopeResetCSS, + + /** + * @property {String} resetCls + * The css class used to wrap Ext components when the {@link #scopeResetCSS} option + * is used. + */ + resetCls: Ext.buildSettings.baseCSSPrefix + 'reset', + + /** + * @property {Boolean} enableNestedListenerRemoval + * **Experimental.** True to cascade listener removal to child elements when an element + * is removed. Currently not optimized for performance. + */ + enableNestedListenerRemoval : false, + + /** + * @property {Boolean} USE_NATIVE_JSON + * Indicates whether to use native browser parsing for JSON methods. + * This option is ignored if the browser does not support native JSON methods. + * + * **Note:** Native JSON methods will not work with objects that have functions. + * Also, property names must be quoted, otherwise the data will not parse. + */ + USE_NATIVE_JSON : false, + + /** + * Returns the dom node for the passed String (id), dom node, or Ext.Element. + * Optional 'strict' flag is needed for IE since it can return 'name' and + * 'id' elements by using getElementById. + * + * Here are some examples: + * + * // gets dom node based on id + * var elDom = Ext.getDom('elId'); + * // gets dom node based on the dom node + * var elDom1 = Ext.getDom(elDom); + * + * // If we don't know if we are working with an + * // Ext.Element or a dom node use Ext.getDom + * function(el){ + * var dom = Ext.getDom(el); + * // do something with the dom node + * } + * + * **Note:** the dom node to be found actually needs to exist (be rendered, etc) + * when this method is called to be successful. + * + * @param {String/HTMLElement/Ext.Element} el + * @return HTMLElement + */ + getDom : function(el, strict) { + if (!el || !document) { + return null; + } + if (el.dom) { + return el.dom; + } else { + if (typeof el == 'string') { + var e = Ext.getElementById(el); + // IE returns elements with the 'name' and 'id' attribute. + // we do a strict check to return the element with only the id attribute + if (e && isIE && strict) { + if (el == e.getAttribute('id')) { + return e; + } else { + return null; + } + } + return e; + } else { + return el; + } + } + }, + + /** + * Removes a DOM node from the document. + * + * Removes this element from the document, removes all DOM event listeners, and + * deletes the cache reference. All DOM event listeners are removed from this element. + * If {@link Ext#enableNestedListenerRemoval Ext.enableNestedListenerRemoval} is + * `true`, then DOM event listeners are also removed from all child nodes. + * The body node will be ignored if passed in. + * + * @param {HTMLElement} node The node to remove + * @method + */ + removeNode : isIE6 || isIE7 || isIE8 + ? (function() { + var d; + return function(n){ + if(n && n.tagName.toUpperCase() != 'BODY'){ + (Ext.enableNestedListenerRemoval) ? Ext.EventManager.purgeElement(n) : Ext.EventManager.removeAll(n); + + var cache = Ext.cache, + id = n.id; + + if (cache[id]) { + delete cache[id].dom; + delete cache[id]; + } + + // removing an iframe this way can cause severe leaks + // fixes leak issue with htmleditor in themes example + if (n.tagName.toUpperCase() != 'IFRAME') { + if (isIE8 && n.parentNode) { + n.parentNode.removeChild(n); + } + d = d || document.createElement('div'); + d.appendChild(n); + d.innerHTML = ''; + } + } + }; + }()) + : function(n) { + if (n && n.parentNode && n.tagName.toUpperCase() != 'BODY') { + (Ext.enableNestedListenerRemoval) ? Ext.EventManager.purgeElement(n) : Ext.EventManager.removeAll(n); + + var cache = Ext.cache, + id = n.id; + + if (cache[id]) { + delete cache[id].dom; + delete cache[id]; + } + + n.parentNode.removeChild(n); + } + }, + + isStrict: isStrict, + + isIEQuirks: isIE && !isStrict, + + /** + * True if the detected browser is Opera. + * @type Boolean + */ + isOpera : isOpera, + + /** + * True if the detected browser is Opera 10.5x. + * @type Boolean + */ + isOpera10_5 : isOpera10_5, + + /** + * True if the detected browser uses WebKit. + * @type Boolean + */ + isWebKit : isWebKit, + + /** + * True if the detected browser is Chrome. + * @type Boolean + */ + isChrome : isChrome, + + /** + * True if the detected browser is Safari. + * @type Boolean + */ + isSafari : isSafari, + + /** + * True if the detected browser is Safari 3.x. + * @type Boolean + */ + isSafari3 : isSafari3, + + /** + * True if the detected browser is Safari 4.x. + * @type Boolean + */ + isSafari4 : isSafari4, + + /** + * True if the detected browser is Safari 5.x. + * @type Boolean + */ + isSafari5 : isSafari5, + + /** + * True if the detected browser is Safari 5.0.x. + * @type Boolean + */ + isSafari5_0 : isSafari5_0, + + + /** + * True if the detected browser is Safari 2.x. + * @type Boolean + */ + isSafari2 : isSafari2, + + /** + * True if the detected browser is Internet Explorer. + * @type Boolean + */ + isIE : isIE, + + /** + * True if the detected browser is Internet Explorer 6.x. + * @type Boolean + */ + isIE6 : isIE6, + + /** + * True if the detected browser is Internet Explorer 7.x. + * @type Boolean + */ + isIE7 : isIE7, + + /** + * True if the detected browser is Internet Explorer 8.x. + * @type Boolean + */ + isIE8 : isIE8, + + /** + * True if the detected browser is Internet Explorer 9.x. + * @type Boolean + */ + isIE9 : isIE9, + + /** + * True if the detected browser uses the Gecko layout engine (e.g. Mozilla, Firefox). + * @type Boolean + */ + isGecko : isGecko, + + /** + * True if the detected browser uses a Gecko 1.9+ layout engine (e.g. Firefox 3.x). + * @type Boolean + */ + isGecko3 : isGecko3, + + /** + * True if the detected browser uses a Gecko 2.0+ layout engine (e.g. Firefox 4.x). + * @type Boolean + */ + isGecko4 : isGecko4, + + /** + * True if the detected browser uses a Gecko 5.0+ layout engine (e.g. Firefox 5.x). + * @type Boolean + */ + isGecko5 : isGecko5, + + /** + * True if the detected browser uses a Gecko 5.0+ layout engine (e.g. Firefox 5.x). + * @type Boolean + */ + isGecko10 : isGecko10, + + /** + * True if the detected browser uses FireFox 3.0 + * @type Boolean + */ + isFF3_0 : isFF3_0, + + /** + * True if the detected browser uses FireFox 3.5 + * @type Boolean + */ + isFF3_5 : isFF3_5, + + /** + * True if the detected browser uses FireFox 3.6 + * @type Boolean + */ + isFF3_6 : isFF3_6, + + /** + * True if the detected browser uses FireFox 4 + * @type Boolean + */ + isFF4 : 4 <= firefoxVersion && firefoxVersion < 5, + + /** + * True if the detected browser uses FireFox 5 + * @type Boolean + */ + isFF5 : 5 <= firefoxVersion && firefoxVersion < 6, + + /** + * True if the detected browser uses FireFox 10 + * @type Boolean + */ + isFF10 : 10 <= firefoxVersion && firefoxVersion < 11, + + /** + * True if the detected platform is Linux. + * @type Boolean + */ + isLinux : isLinux, + + /** + * True if the detected platform is Windows. + * @type Boolean + */ + isWindows : isWindows, + + /** + * True if the detected platform is Mac OS. + * @type Boolean + */ + isMac : isMac, + + /** + * The current version of Chrome (0 if the browser is not Chrome). + * @type Number + */ + chromeVersion: chromeVersion, + + /** + * The current version of Firefox (0 if the browser is not Firefox). + * @type Number + */ + firefoxVersion: firefoxVersion, + + /** + * The current version of IE (0 if the browser is not IE). This does not account + * for the documentMode of the current page, which is factored into {@link #isIE7}, + * {@link #isIE8} and {@link #isIE9}. Thus this is not always true: + * + * Ext.isIE8 == (Ext.ieVersion == 8) + * + * @type Number + */ + ieVersion: ieVersion, + + /** + * The current version of Opera (0 if the browser is not Opera). + * @type Number + */ + operaVersion: operaVersion, + + /** + * The current version of Safari (0 if the browser is not Safari). + * @type Number + */ + safariVersion: safariVersion, + + /** + * The current version of WebKit (0 if the browser does not use WebKit). + * @type Number + */ + webKitVersion: webKitVersion, + + /** + * True if the page is running over SSL + * @type Boolean + */ + isSecure: isSecure, + + /** + * URL to a 1x1 transparent gif image used by Ext to create inline icons with + * CSS background images. In older versions of IE, this defaults to + * "http://sencha.com/s.gif" and you should change this to a URL on your server. + * For other browsers it uses an inline data URL. + * @type String + */ + BLANK_IMAGE_URL : (isIE6 || isIE7) ? '/' + '/www.sencha.com/s.gif' : 'data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==', + + /** + * Utility method for returning a default value if the passed value is empty. + * + * The value is deemed to be empty if it is: + * + * - null + * - undefined + * - an empty array + * - a zero length string (Unless the `allowBlank` parameter is `true`) + * + * @param {Object} value The value to test + * @param {Object} defaultValue The value to return if the original value is empty + * @param {Boolean} [allowBlank=false] true to allow zero length strings to qualify as non-empty. + * @return {Object} value, if non-empty, else defaultValue + * @deprecated 4.0.0 Use {@link Ext#valueFrom} instead + */ + value : function(v, defaultValue, allowBlank){ + return Ext.isEmpty(v, allowBlank) ? defaultValue : v; + }, + + /** + * Escapes the passed string for use in a regular expression. + * @param {String} str + * @return {String} + * @deprecated 4.0.0 Use {@link Ext.String#escapeRegex} instead + */ + escapeRe : function(s) { + return s.replace(/([-.*+?\^${}()|\[\]\/\\])/g, "\\$1"); + }, + + /** + * Applies event listeners to elements by selectors when the document is ready. + * The event name is specified with an `@` suffix. + * + * Ext.addBehaviors({ + * // add a listener for click on all anchors in element with id foo + * '#foo a@click' : function(e, t){ + * // do something + * }, + * + * // add the same listener to multiple selectors (separated by comma BEFORE the @) + * '#foo a, #bar span.some-class@mouseover' : function(){ + * // do something + * } + * }); + * + * @param {Object} obj The list of behaviors to apply + */ + addBehaviors : function(o){ + if(!Ext.isReady){ + Ext.onReady(function(){ + Ext.addBehaviors(o); + }); + } else { + var cache = {}, // simple cache for applying multiple behaviors to same selector does query multiple times + parts, + b, + s; + for (b in o) { + if ((parts = b.split('@'))[1]) { // for Object prototype breakers + s = parts[0]; + if(!cache[s]){ + cache[s] = Ext.select(s); + } + cache[s].on(parts[1], o[b]); + } + } + cache = null; + } + }, + + /** + * Returns the size of the browser scrollbars. This can differ depending on + * operating system settings, such as the theme or font size. + * @param {Boolean} [force] true to force a recalculation of the value. + * @return {Object} An object containing scrollbar sizes. + * @return.width {Number} The width of the vertical scrollbar. + * @return.height {Number} The height of the horizontal scrollbar. + */ + getScrollbarSize: function (force) { + if (!Ext.isReady) { + return {}; + } + + if (force || !scrollbarSize) { + var db = document.body, + div = document.createElement('div'); + + div.style.width = div.style.height = '100px'; + div.style.overflow = 'scroll'; + div.style.position = 'absolute'; + + db.appendChild(div); // now we can measure the div... + + // at least in iE9 the div is not 100px - the scrollbar size is removed! + scrollbarSize = { + width: div.offsetWidth - div.clientWidth, + height: div.offsetHeight - div.clientHeight + }; + + db.removeChild(div); + } + + return scrollbarSize; + }, + + /** + * Utility method for getting the width of the browser's vertical scrollbar. This + * can differ depending on operating system settings, such as the theme or font size. + * + * This method is deprected in favor of {@link #getScrollbarSize}. + * + * @param {Boolean} [force] true to force a recalculation of the value. + * @return {Number} The width of a vertical scrollbar. + * @deprecated + */ + getScrollBarWidth: function(force){ + var size = Ext.getScrollbarSize(force); + return size.width + 2; // legacy fudge factor + }, + + /** + * Copies a set of named properties fom the source object to the destination object. + * + * Example: + * + * ImageComponent = Ext.extend(Ext.Component, { + * initComponent: function() { + * this.autoEl = { tag: 'img' }; + * MyComponent.superclass.initComponent.apply(this, arguments); + * this.initialBox = Ext.copyTo({}, this.initialConfig, 'x,y,width,height'); + * } + * }); + * + * Important note: To borrow class prototype methods, use {@link Ext.Base#borrow} instead. + * + * @param {Object} dest The destination object. + * @param {Object} source The source object. + * @param {String/String[]} names Either an Array of property names, or a comma-delimited list + * of property names to copy. + * @param {Boolean} [usePrototypeKeys] Defaults to false. Pass true to copy keys off of the + * prototype as well as the instance. + * @return {Object} The modified object. + */ + copyTo : function(dest, source, names, usePrototypeKeys){ + if(typeof names == 'string'){ + names = names.split(/[,;\s]/); + } + + var n, + nLen = names.length, + name; + + for(n = 0; n < nLen; n++) { + name = names[n]; + + if(usePrototypeKeys || source.hasOwnProperty(name)){ + dest[name] = source[name]; + } + } + + return dest; + }, + + /** + * Attempts to destroy and then remove a set of named properties of the passed object. + * @param {Object} o The object (most likely a Component) who's properties you wish to destroy. + * @param {String...} args One or more names of the properties to destroy and remove from the object. + */ + destroyMembers : function(o){ + for (var i = 1, a = arguments, len = a.length; i < len; i++) { + Ext.destroy(o[a[i]]); + delete o[a[i]]; + } + }, + + /** + * Logs a message. If a console is present it will be used. On Opera, the method + * "opera.postError" is called. In other cases, the message is logged to an array + * "Ext.log.out". An attached debugger can watch this array and view the log. The + * log buffer is limited to a maximum of "Ext.log.max" entries (defaults to 250). + * The `Ext.log.out` array can also be written to a popup window by entering the + * following in the URL bar (a "bookmarklet"): + * + * javascript:void(Ext.log.show()); + * + * If additional parameters are passed, they are joined and appended to the message. + * A technique for tracing entry and exit of a function is this: + * + * function foo () { + * Ext.log({ indent: 1 }, '>> foo'); + * + * // log statements in here or methods called from here will be indented + * // by one step + * + * Ext.log({ outdent: 1 }, '<< foo'); + * } + * + * This method does nothing in a release build. + * + * @param {String/Object} message The message to log or an options object with any + * of the following properties: + * + * - `msg`: The message to log (required). + * - `level`: One of: "error", "warn", "info" or "log" (the default is "log"). + * - `dump`: An object to dump to the log as part of the message. + * - `stack`: True to include a stack trace in the log. + * - `indent`: Cause subsequent log statements to be indented one step. + * - `outdent`: Cause this and following statements to be one step less indented. + * + * @method + */ + log : + log || + nullLog, + + /** + * Partitions the set into two sets: a true set and a false set. + * + * Example 1: + * + * Ext.partition([true, false, true, true, false]); + * // returns [[true, true, true], [false, false]] + * + * Example 2: + * + * Ext.partition( + * Ext.query("p"), + * function(val){ + * return val.className == "class1" + * } + * ); + * // true are those paragraph elements with a className of "class1", + * // false set are those that do not have that className. + * + * @param {Array/NodeList} arr The array to partition + * @param {Function} truth (optional) a function to determine truth. + * If this is omitted the element itself must be able to be evaluated for its truthfulness. + * @return {Array} [array of truish values, array of falsy values] + * @deprecated 4.0.0 Will be removed in the next major version + */ + partition : function(arr, truth){ + var ret = [[],[]], + a, v, + aLen = arr.length; + + for (a = 0; a < aLen; a++) { + v = arr[a]; + ret[ (truth && truth(v, a, arr)) || (!truth && v) ? 0 : 1].push(v); + } + + return ret; + }, + + /** + * Invokes a method on each item in an Array. + * + * Example: + * + * Ext.invoke(Ext.query("p"), "getAttribute", "id"); + * // [el1.getAttribute("id"), el2.getAttribute("id"), ..., elN.getAttribute("id")] + * + * @param {Array/NodeList} arr The Array of items to invoke the method on. + * @param {String} methodName The method name to invoke. + * @param {Object...} args Arguments to send into the method invocation. + * @return {Array} The results of invoking the method on each item in the array. + * @deprecated 4.0.0 Will be removed in the next major version + */ + invoke : function(arr, methodName){ + var ret = [], + args = Array.prototype.slice.call(arguments, 2), + a, v, + aLen = arr.length; + + for (a = 0; a < aLen; a++) { + v = arr[a]; + + if (v && typeof v[methodName] == 'function') { + ret.push(v[methodName].apply(v, args)); + } else { + ret.push(undefined); + } + } + + return ret; + }, + + /** + * Zips N sets together. + * + * Example 1: + * + * Ext.zip([1,2,3],[4,5,6]); // [[1,4],[2,5],[3,6]] + * + * Example 2: + * + * Ext.zip( + * [ "+", "-", "+"], + * [ 12, 10, 22], + * [ 43, 15, 96], + * function(a, b, c){ + * return "$" + a + "" + b + "." + c + * } + * ); // ["$+12.43", "$-10.15", "$+22.96"] + * + * @param {Array/NodeList...} arr This argument may be repeated. Array(s) + * to contribute values. + * @param {Function} zipper (optional) The last item in the argument list. + * This will drive how the items are zipped together. + * @return {Array} The zipped set. + * @deprecated 4.0.0 Will be removed in the next major version + */ + 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 = [], + i, + j, + aLen; + + for (i = 0; i < len; i++) { + ret[i] = []; + if(fn){ + ret[i] = fn.apply(fn, Ext.pluck(arrs, i)); + }else{ + for (j = 0, aLen = arrs.length; j < aLen; j++){ + ret[i].push( arrs[j][i] ); + } + } + } + return ret; + }, + + /** + * Turns an array into a sentence, joined by a specified connector - e.g.: + * + * Ext.toSentence(['Adama', 'Tigh', 'Roslin']); //'Adama, Tigh and Roslin' + * Ext.toSentence(['Adama', 'Tigh', 'Roslin'], 'or'); //'Adama, Tigh or Roslin' + * + * @param {String[]} items The array to create a sentence from + * @param {String} connector The string to use to connect the last two words. + * Usually 'and' or 'or' - defaults to 'and'. + * @return {String} The sentence string + * @deprecated 4.0.0 Will be removed in the next major version + */ + toSentence: function(items, connector) { + var length = items.length, + head, + tail; + + if (length <= 1) { + return items[0]; + } else { + head = items.slice(0, length - 1); + tail = items[length - 1]; + + return Ext.util.Format.format("{0} {1} {2}", head.join(", "), connector || 'and', tail); + } + }, + + /** + * @property {Boolean} useShims + * By default, Ext intelligently decides whether floating elements should be shimmed. + * If you are using flash, you may want to set this to true. + */ + useShims: isIE6 + }); +}()); + +/** + * Loads Ext.app.Application class and starts it up with given configuration after the page is ready. + * + * See Ext.app.Application for details. + * + * @param {Object} config + */ +Ext.application = function(config) { + Ext.require('Ext.app.Application'); + + Ext.onReady(function() { + new Ext.app.Application(config); + }); +}; + +/** + * @class Ext.util.Format + +This class is a centralized place for formatting functions. It includes +functions to format various different types of data, such as text, dates and numeric values. + +__Localization__ +This class contains several options for localization. These can be set once the library has loaded, +all calls to the functions from that point will use the locale settings that were specified. +Options include: +- thousandSeparator +- decimalSeparator +- currenyPrecision +- currencySign +- currencyAtEnd +This class also uses the default date format defined here: {@link Ext.Date#defaultFormat}. + +__Using with renderers__ +There are two helper functions that return a new function that can be used in conjunction with +grid renderers: + + columns: [{ + dataIndex: 'date', + renderer: Ext.util.Format.dateRenderer('Y-m-d') + }, { + dataIndex: 'time', + renderer: Ext.util.Format.numberRenderer('0.000') + }] + +Functions that only take a single argument can also be passed directly: + columns: [{ + dataIndex: 'cost', + renderer: Ext.util.Format.usMoney + }, { + dataIndex: 'productCode', + renderer: Ext.util.Format.uppercase + }] + +__Using with XTemplates__ +XTemplates can also directly use Ext.util.Format functions: + + new Ext.XTemplate([ + 'Date: {startDate:date("Y-m-d")}', + 'Cost: {cost:usMoney}' + ]); + + * @markdown + * @singleton + */ +(function() { + Ext.ns('Ext.util'); + + Ext.util.Format = {}; + var UtilFormat = Ext.util.Format, + stripTagsRE = /<\/?[^>]+>/gi, + stripScriptsRe = /(?:)((\n|\r|.)*?)(?:<\/script>)/ig, + nl2brRe = /\r?\n/g, + + // A RegExp to remove from a number format string, all characters except digits and '.' + formatCleanRe = /[^\d\.]/g, + + // A RegExp to remove from a number format string, all characters except digits and the local decimal separator. + // Created on first use. The local decimal separator character must be initialized for this to be created. + I18NFormatCleanRe; + + Ext.apply(UtilFormat, { + /** + * @property {String} thousandSeparator + *

    The character that the {@link #number} function uses as a thousand separator.

    + *

    This may be overridden in a locale file.

    + */ + // + thousandSeparator: ',', + // + + /** + * @property {String} decimalSeparator + *

    The character that the {@link #number} function uses as a decimal point.

    + *

    This may be overridden in a locale file.

    + */ + // + decimalSeparator: '.', + // + + /** + * @property {Number} currencyPrecision + *

    The number of decimal places that the {@link #currency} function displays.

    + *

    This may be overridden in a locale file.

    + */ + // + currencyPrecision: 2, + // + + /** + * @property {String} currencySign + *

    The currency sign that the {@link #currency} function displays.

    + *

    This may be overridden in a locale file.

    + */ + // + currencySign: '$', + // + + /** + * @property {Boolean} currencyAtEnd + *

    This may be set to true to make the {@link #currency} function + * append the currency sign to the formatted value.

    + *

    This may be overridden in a locale file.

    + */ + // + currencyAtEnd: false, + // + + /** + * Checks a reference and converts it to empty string if it is undefined + * @param {Object} value Reference to check + * @return {Object} 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 {Object} 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; + }, + + /** + * 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 : 'ab'.substr(-1) != 'b' + ? function (value, start, length) { + var str = String(value); + return (start < 0) + ? str.substr(Math.max(str.length + start, 0), length) + : str.substr(start, length); + } + : 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(); + }, + + /** + * Format a number as US currency + * @param {Number/String} value The numeric value to format + * @return {String} The formatted currency string + */ + usMoney : function(v) { + return UtilFormat.currency(v, '$', 2); + }, + + /** + * Format a number as a currency + * @param {Number/String} value The numeric value to format + * @param {String} sign The currency sign to use (defaults to {@link #currencySign}) + * @param {Number} decimals The number of decimals to use for the currency (defaults to {@link #currencyPrecision}) + * @param {Boolean} end True if the currency sign should be at the end of the string (defaults to {@link #currencyAtEnd}) + * @return {String} The formatted currency string + */ + currency: function(v, currencySign, decimals, end) { + var negativeSign = '', + format = ",0", + i = 0; + v = v - 0; + if (v < 0) { + v = -v; + negativeSign = '-'; + } + decimals = Ext.isDefined(decimals) ? decimals : UtilFormat.currencyPrecision; + format += format + (decimals > 0 ? '.' : ''); + for (; i < decimals; i++) { + format += '0'; + } + v = UtilFormat.number(v, format); + if ((end || UtilFormat.currencyAtEnd) === true) { + return Ext.String.format("{0}{1}{2}", negativeSign, v, currencySign || UtilFormat.currencySign); + } else { + return Ext.String.format("{0}{1}{2}", negativeSign, currencySign || UtilFormat.currencySign, v); + } + }, + + /** + * Formats the passed date using the specified format pattern. + * @param {String/Date} value The value to format. If a string is passed, it is converted to a Date by the Javascript + * Date object's parse() method. + * @param {String} format (Optional) Any valid date format string. Defaults to {@link Ext.Date#defaultFormat}. + * @return {String} The formatted date string. + */ + date: function(v, format) { + if (!v) { + return ""; + } + if (!Ext.isDate(v)) { + v = new Date(Date.parse(v)); + } + return Ext.Date.dateFormat(v, format || Ext.Date.defaultFormat); + }, + + /** + * 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. Defaults to {@link Ext.Date#defaultFormat}. + * @return {Function} The date formatting function + */ + dateRenderer : function(format) { + return function(v) { + return UtilFormat.date(v, format); + }; + }, + + /** + * Strips all HTML tags + * @param {Object} value The text from which to strip tags + * @return {String} The stripped text + */ + stripTags : function(v) { + return !v ? v : String(v).replace(stripTagsRE, ""); + }, + + /** + * Strips all script tags + * @param {Object} value The text from which to strip script tags + * @return {String} The stripped text + */ + stripScripts : function(v) { + return !v ? v : String(v).replace(stripScriptsRe, ""); + }, + + /** + * Simple format for a file size (xxx bytes, xxx KB, xxx MB) + * @param {Number/String} size The numeric value to format + * @return {String} The formatted file size + */ + fileSize : function(size) { + if (size < 1024) { + return size + " bytes"; + } else if (size < 1048576) { + return (Math.round(((size*10) / 1024))/10) + " KB"; + } else { + return (Math.round(((size*10) / 1048576))/10) + " MB"; + } + }, + + /** + * It does simple math for use in a template, for example:
    
    +         * var tpl = new Ext.Template('{value} * 10 = {value:math("* 10")}');
    +         * 
    + * @return {Function} A function that operates on the passed value. + * @method + */ + math : (function(){ + var fns = {}; + + return function(v, a){ + if (!fns[a]) { + fns[a] = Ext.functionFactory('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 passed number according to the passed format string.

    + *

    The number of digits after the decimal separator character specifies the number of + * decimal places in the resulting string. The local-specific decimal character is used in the result.

    + *

    The presence of a thousand separator character in the format string specifies that + * the locale-specific thousand separator (if any) is inserted separating thousand groups.

    + *

    By default, "," is expected as the thousand separator, and "." is expected as the decimal separator.

    + *

    New to Ext JS 4

    + *

    Locale-specific characters are always used in the formatted output when inserting + * thousand and decimal separators.

    + *

    The format string must specify separator characters according to US/UK conventions ("," as the + * thousand separator, and "." as the decimal separator)

    + *

    To allow specification of format strings according to local conventions for separator characters, add + * the string /i to the end of 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 allow specification of the formatting string using UK/US grouping characters (,) 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, formatString) { + if (!formatString) { + return v; + } + v = Ext.Number.from(v, NaN); + if (isNaN(v)) { + return ''; + } + var comma = UtilFormat.thousandSeparator, + dec = UtilFormat.decimalSeparator, + i18n = false, + neg = v < 0, + hasComma, + psplit, + fnum, + cnum, + parr, + j, + m, + n, + i; + + v = Math.abs(v); + + // The "/i" suffix allows caller to use a locale-specific formatting string. + // Clean the format string by removing all but numerals and the decimal separator. + // Then split the format string into pre and post decimal segments according to *what* the + // decimal separator is. If they are specifying "/i", they are using the local convention in the format string. + if (formatString.substr(formatString.length - 2) == '/i') { + if (!I18NFormatCleanRe) { + I18NFormatCleanRe = new RegExp('[^\\d\\' + UtilFormat.decimalSeparator + ']','g'); + } + formatString = formatString.substr(0, formatString.length - 2); + i18n = true; + hasComma = formatString.indexOf(comma) != -1; + psplit = formatString.replace(I18NFormatCleanRe, '').split(dec); + } else { + hasComma = formatString.indexOf(',') != -1; + psplit = formatString.replace(formatCleanRe, '').split('.'); + } + + if (psplit.length > 2) { + Ext.Error.raise({ + sourceClass: "Ext.util.Format", + sourceMethod: "number", + value: v, + formatString: formatString, + msg: "Invalid number format, should have no more than 1 decimal" + }); + } else if (psplit.length > 1) { + v = Ext.Number.toFixed(v, psplit[1].length); + } else { + v = Ext.Number.toFixed(v, 0); + } + + fnum = v.toString(); + + psplit = fnum.split('.'); + + if (hasComma) { + cnum = psplit[0]; + parr = []; + j = cnum.length; + m = Math.floor(j / 3); + n = cnum.length % 3 || 3; + + 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]; + } + } + + if (neg) { + /* + * Edge case. If we have a very small negative number it will get rounded to 0, + * however the initial check at the top will still report as negative. Replace + * everything but 1-9 and check if the string is empty to determine a 0 value. + */ + neg = fnum.replace(/[^1-9]/g, '') !== ''; + } + + return (neg ? '-' : '') + formatString.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 UtilFormat.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 Ext.isEmpty(v) ? '' : v.replace(nl2brRe, '
    '); + }, + + /** + * Alias for {@link Ext.String#capitalize}. + * @method + * @inheritdoc Ext.String#capitalize + */ + capitalize: Ext.String.capitalize, + + /** + * Alias for {@link Ext.String#ellipsis}. + * @method + * @inheritdoc Ext.String#ellipsis + */ + ellipsis: Ext.String.ellipsis, + + /** + * Alias for {@link Ext.String#format}. + * @method + * @inheritdoc Ext.String#format + */ + format: Ext.String.format, + + /** + * Alias for {@link Ext.String#htmlDecode}. + * @method + * @inheritdoc Ext.String#htmlDecode + */ + htmlDecode: Ext.String.htmlDecode, + + /** + * Alias for {@link Ext.String#htmlEncode}. + * @method + * @inheritdoc Ext.String#htmlEncode + */ + htmlEncode: Ext.String.htmlEncode, + + /** + * Alias for {@link Ext.String#leftPad}. + * @method + * @inheritdoc Ext.String#leftPad + */ + leftPad: Ext.String.leftPad, + + /** + * Alias for {@link Ext.String#trim}. + * @method + * @inheritdoc Ext.String#trim + */ + trim : Ext.String.trim, + + /** + * Parses a number or string representing margin sizes into an object. Supports CSS-style margin declarations + * (e.g. 10, "10", "10 10", "10 10 10" and "10 10 10 10" are all valid options and would return the same result) + * @param {Number/String} v The encoded margins + * @return {Object} An object with margin sizes for top, right, bottom and left + */ + parseBox : function(box) { + box = Ext.isEmpty(box) ? '' : box; + if (Ext.isNumber(box)) { + box = box.toString(); + } + var parts = box.split(' '), + ln = parts.length; + + if (ln == 1) { + parts[1] = parts[2] = parts[3] = parts[0]; + } + else if (ln == 2) { + parts[2] = parts[0]; + parts[3] = parts[1]; + } + else if (ln == 3) { + parts[3] = parts[1]; + } + + return { + top :parseInt(parts[0], 10) || 0, + right :parseInt(parts[1], 10) || 0, + bottom:parseInt(parts[2], 10) || 0, + left :parseInt(parts[3], 10) || 0 + }; + }, + + /** + * Escapes the passed string for use in a regular expression + * @param {String} str + * @return {String} + */ + escapeRegex : function(s) { + return s.replace(/([\-.*+?\^${}()|\[\]\/\\])/g, "\\$1"); + } + }); +}()); + +/** + * Provides the ability to execute one or more arbitrary tasks in a asynchronous manner. + * Generally, you can use the singleton {@link Ext.TaskManager} instead, but if needed, + * you can create separate instances of TaskRunner. Any number of separate tasks can be + * started at any time and will run independently of each other. + * + * Example usage: + * + * // Start a simple clock task that updates a div once per second + * var updateClock = function () { + * Ext.fly('clock').update(new Date().format('g:i:s A')); + * } + * + * var runner = new Ext.util.TaskRunner(); + * var task = runner.start({ + * run: updateClock, + * interval: 1000 + * } + * + * The equivalent using TaskManager: + * + * var task = Ext.TaskManager.start({ + * run: updateClock, + * interval: 1000 + * }); + * + * To end a running task: + * + * task.destroy(); + * + * If a task needs to be started and stopped repeated over time, you can create a + * {@link Ext.util.TaskRunner.Task Task} instance. + * + * var task = runner.newTask({ + * run: function () { + * // useful code + * }, + * interval: 1000 + * }); + * + * task.start(); + * + * // ... + * + * task.stop(); + * + * // ... + * + * task.start(); + * + * A re-usable, one-shot task can be managed similar to the above: + * + * var task = runner.newTask({ + * run: function () { + * // useful code to run once + * }, + * repeat: 1 + * }); + * + * task.start(); + * + * // ... + * + * task.start(); + * + * See the {@link #start} method for details about how to configure a task object. + * + * Also see {@link Ext.util.DelayedTask}. + * + * @constructor + * @param {Number/Object} [interval=10] The minimum precision in milliseconds supported by this + * TaskRunner instance. Alternatively, a config object to apply to the new instance. + */ +Ext.define('Ext.util.TaskRunner', { + /** + * @cfg interval + * The timer resolution. + */ + interval: 10, + + /** + * @property timerId + * The id of the current timer. + * @private + */ + timerId: null, + + constructor: function (interval) { + var me = this; + + if (typeof interval == 'number') { + me.interval = interval; + } else if (interval) { + Ext.apply(me, interval); + } + + me.tasks = []; + me.timerFn = Ext.Function.bind(me.onTick, me); + }, + + /** + * Creates a new {@link Ext.util.TaskRunner.Task Task} instance. These instances can + * be easily started and stopped. + * @param {Object} config The config object. For details on the supported properties, + * see {@link #start}. + */ + newTask: function (config) { + var task = new Ext.util.TaskRunner.Task(config); + task.manager = this; + return task; + }, + + /** + * Starts a new task. + * + * Before each invocation, Ext injects the property `taskRunCount` into the task object + * so that calculations based on the repeat count can be performed. + * + * The returned task will contain a `destroy` method that can be used to destroy the + * task and cancel further calls. This is equivalent to the {@link #stop} method. + * + * @param {Object} task A config object that supports the following properties: + * @param {Function} task.run The function to execute each time the task is invoked. The + * function will be called at each interval and passed the `args` argument if specified, + * and the current invocation count if not. + * + * If a particular scope (`this` reference) is required, be sure to specify it using + * the `scope` argument. + * + * @param {Function} task.onError The function to execute in case of unhandled + * error on task.run. + * + * @param {Boolean} task.run.return `false` from this function to terminate the task. + * + * @param {Number} task.interval The frequency in milliseconds with which the task + * should be invoked. + * + * @param {Object[]} task.args An array of arguments to be passed to the function + * specified by `run`. If not specified, the current invocation count is passed. + * + * @param {Object} task.scope The scope (`this` reference) in which to execute the + * `run` function. Defaults to the task config object. + * + * @param {Number} task.duration The length of time in milliseconds to invoke the task + * before stopping automatically (defaults to indefinite). + * + * @param {Number} task.repeat The number of times to invoke the task before stopping + * automatically (defaults to indefinite). + * @return {Object} The task + */ + start: function(task) { + var me = this, + now = new Date().getTime(); + + if (!task.pending) { + me.tasks.push(task); + task.pending = true; // don't allow the task to be added to me.tasks again + } + + task.stopped = false; // might have been previously stopped... + task.taskStartTime = now; + task.taskRunTime = task.fireOnStart !== false ? 0 : task.taskStartTime; + task.taskRunCount = 0; + + if (!me.firing) { + if (task.fireOnStart !== false) { + me.startTimer(0, now); + } else { + me.startTimer(task.interval, now); + } + } + + return task; + }, + + /** + * Stops an existing running task. + * @param {Object} task The task to stop + * @return {Object} The task + */ + stop: function(task) { + // NOTE: we don't attempt to remove the task from me.tasks at this point because + // this could be called from inside a task which would then corrupt the state of + // the loop in onTick + if (!task.stopped) { + task.stopped = true; + + if (task.onStop) { + task.onStop.call(task.scope || task, task); + } + } + + return task; + }, + + /** + * Stops all tasks that are currently running. + */ + stopAll: function() { + // onTick will take care of cleaning up the mess after this point... + Ext.each(this.tasks, this.stop, this); + }, + + //------------------------------------------------------------------------- + + firing: false, + + nextExpires: 1e99, + + // private + onTick: function () { + var me = this, + tasks = me.tasks, + now = new Date().getTime(), + nextExpires = 1e99, + len = tasks.length, + expires, newTasks, i, task, rt, remove; + + me.timerId = null; + me.firing = true; // ensure we don't startTimer during this loop... + + // tasks.length can be > len if start is called during a task.run call... so we + // first check len to avoid tasks.length reference but eventually we need to also + // check tasks.length. we avoid repeating use of tasks.length by setting len at + // that time (to help the next loop) + for (i = 0; i < len || i < (len = tasks.length); ++i) { + task = tasks[i]; + + if (!(remove = task.stopped)) { + expires = task.taskRunTime + task.interval; + + if (expires <= now) { + rt = 1; // otherwise we have a stale "rt" + try { + rt = task.run.apply(task.scope || task, task.args || [++task.taskRunCount]); + } catch (taskError) { + try { + if (task.onError) { + rt = task.onError.call(task.scope || task, task, taskError); + } + } catch (ignore) { } + } + task.taskRunTime = now; + if (rt === false || task.taskRunCount === task.repeat) { + me.stop(task); + remove = true; + } else { + remove = task.stopped; // in case stop was called by run + expires = now + task.interval; + } + } + + if (!remove && task.duration && task.duration <= (now - task.taskStartTime)) { + me.stop(task); + remove = true; + } + } + + if (remove) { + task.pending = false; // allow the task to be added to me.tasks again + + // once we detect that a task needs to be removed, we copy the tasks that + // will carry forward into newTasks... this way we avoid O(N*N) to remove + // each task from the tasks array (and ripple the array down) and also the + // potentially wasted effort of making a new tasks[] even if all tasks are + // going into the next wave. + if (!newTasks) { + newTasks = tasks.slice(0, i); + // we don't set me.tasks here because callbacks can also start tasks, + // which get added to me.tasks... so we will visit them in this loop + // and account for their expirations in nextExpires... + } + } else { + if (newTasks) { + newTasks.push(task); // we've cloned the tasks[], so keep this one... + } + + if (nextExpires > expires) { + nextExpires = expires; // track the nearest expiration time + } + } + } + + if (newTasks) { + // only now can we copy the newTasks to me.tasks since no user callbacks can + // take place + me.tasks = newTasks; + } + + me.firing = false; // we're done, so allow startTimer afterwards + + if (me.tasks.length) { + // we create a new Date here because all the callbacks could have taken a long + // time... we want to base the next timeout on the current time (after the + // callback storm): + me.startTimer(nextExpires - now, new Date().getTime()); + } + }, + + // private + startTimer: function (timeout, now) { + var me = this, + expires = now + timeout, + timerId = me.timerId; + + // Check to see if this request is enough in advance of the current timer. If so, + // we reschedule the timer based on this new expiration. + if (timerId && me.nextExpires - expires > me.interval) { + clearTimeout(timerId); + timerId = null; + } + + if (!timerId) { + if (timeout < me.interval) { + timeout = me.interval; + } + + me.timerId = setTimeout(me.timerFn, timeout); + me.nextExpires = expires; + } + } +}, +function () { + var me = this, + proto = me.prototype; + + /** + * Destroys this instance, stopping all tasks that are currently running. + * @method destroy + */ + proto.destroy = proto.stopAll; + + /** + * @class Ext.TaskManager + * @extends Ext.util.TaskRunner + * @singleton + * + * A static {@link Ext.util.TaskRunner} instance that can be used to start and stop + * arbitrary tasks. See {@link Ext.util.TaskRunner} for supported methods and task + * config properties. + * + * // Start a simple clock task that updates a div once per second + * var task = { + * run: function(){ + * Ext.fly('clock').update(new Date().format('g:i:s A')); + * }, + * interval: 1000 //1 second + * } + * + * Ext.TaskManager.start(task); + * + * See the {@link #start} method for details about how to configure a task object. + */ + Ext.util.TaskManager = Ext.TaskManager = new me(); + + /** + * Instances of this class are created by {@link Ext.util.TaskRunner#newTask} method. + * + * For details on config properties, see {@link Ext.util.TaskRunner#start}. + * @class Ext.util.TaskRunner.Task + */ + me.Task = new Ext.Class({ + isTask: true, + + /** + * This flag is set to `true` by {@link #stop}. + * @private + */ + stopped: true, // this avoids the odd combination of !stopped && !pending + + /** + * Override default behavior + */ + fireOnStart: false, + + constructor: function (config) { + Ext.apply(this, config); + }, + + /** + * Restarts this task, clearing it duration, expiration and run count. + * @param {Number} [interval] Optionally reset this task's interval. + */ + restart: function (interval) { + if (interval !== undefined) { + this.interval = interval; + } + + this.manager.start(this); + }, + + /** + * Starts this task if it is not already started. + * @param {Number} [interval] Optionally reset this task's interval. + */ + start: function (interval) { + if (this.stopped) { + this.restart(interval); + } + }, + + /** + * Stops this task. + */ + stop: function () { + this.manager.stop(this); + } + }); + + proto = me.Task.prototype; + + /** + * Destroys this instance, stopping this task's execution. + * @method destroy + */ + proto.destroy = proto.stop; +}); + +/** + * @class Ext.perf.Accumulator + * @private + */ +Ext.define('Ext.perf.Accumulator', (function () { + var currentFrame = null, + khrome = Ext.global['chrome'], + formatTpl, + // lazy init on first request for timestamp (avoids infobar in IE until needed) + // Also avoids kicking off Chrome's microsecond timer until first needed + getTimestamp = function () { + + getTimestamp = function () { + return new Date().getTime(); + }; + + var interval, toolbox; + + // If Chrome is started with the --enable-benchmarking switch + if (Ext.isChrome && khrome && khrome.Interval) { + interval = new khrome.Interval(); + interval.start(); + getTimestamp = function () { + return interval.microseconds() / 1000; + }; + } else if (window.ActiveXObject) { + try { + // the above technique is not very accurate for small intervals... + toolbox = new ActiveXObject('SenchaToolbox.Toolbox'); + Ext.senchaToolbox = toolbox; // export for other uses + getTimestamp = function () { + return toolbox.milliseconds; + }; + } catch (e) { + // ignore + } + } else if (Date.now) { + getTimestamp = Date.now; + } + + Ext.perf.getTimestamp = Ext.perf.Accumulator.getTimestamp = getTimestamp; + return getTimestamp(); + }; + + function adjustSet (set, time) { + set.sum += time; + set.min = Math.min(set.min, time); + set.max = Math.max(set.max, time); + } + + function leaveFrame (time) { + var totalTime = time ? time : (getTimestamp() - this.time), // do this first + me = this, // me = frame + accum = me.accum; + + ++accum.count; + if (! --accum.depth) { + adjustSet(accum.total, totalTime); + } + adjustSet(accum.pure, totalTime - me.childTime); + + currentFrame = me.parent; + if (currentFrame) { + ++currentFrame.accum.childCount; + currentFrame.childTime += totalTime; + } + } + + function makeSet () { + return { + min: Number.MAX_VALUE, + max: 0, + sum: 0 + }; + } + + function makeTap (me, fn) { + return function () { + var frame = me.enter(), + ret = fn.apply(this, arguments); + + frame.leave(); + return ret; + }; + } + + function round (x) { + return Math.round(x * 100) / 100; + } + + function setToJSON (count, childCount, calibration, set) { + var data = { + avg: 0, + min: set.min, + max: set.max, + sum: 0 + }; + + if (count) { + calibration = calibration || 0; + data.sum = set.sum - childCount * calibration; + data.avg = data.sum / count; + // min and max cannot be easily corrected since we don't know the number of + // child calls for them. + } + + return data; + } + + return { + constructor: function (name) { + var me = this; + + me.count = me.childCount = me.depth = me.maxDepth = 0; + me.pure = makeSet(); + me.total = makeSet(); + me.name = name; + }, + + statics: { + getTimestamp: getTimestamp + }, + + format: function (calibration) { + if (!formatTpl) { + formatTpl = new Ext.XTemplate([ + '{name} - {count} call(s)', + '', + '', + ' ({childCount} children)', + '', + '', + ' ({depth} deep)', + '', + '', + ', {type}: {[this.time(values.sum)]} msec (', + //'min={[this.time(values.min)]}, ', + 'avg={[this.time(values.sum / parent.count)]}', + //', max={[this.time(values.max)]}', + ')', + '', + '' + ].join(''), { + time: function (t) { + return Math.round(t * 100) / 100; + } + }); + } + + var data = this.getData(calibration); + data.name = this.name; + data.pure.type = 'Pure'; + data.total.type = 'Total'; + data.times = [data.pure, data.total]; + return formatTpl.apply(data); + }, + + getData: function (calibration) { + var me = this; + + return { + count: me.count, + childCount: me.childCount, + depth: me.maxDepth, + pure: setToJSON(me.count, me.childCount, calibration, me.pure), + total: setToJSON(me.count, me.childCount, calibration, me.total) + }; + }, + + enter: function () { + var me = this, + frame = { + accum: me, + leave: leaveFrame, + childTime: 0, + parent: currentFrame + }; + + ++me.depth; + if (me.maxDepth < me.depth) { + me.maxDepth = me.depth; + } + + currentFrame = frame; + frame.time = getTimestamp(); // do this last + return frame; + }, + + monitor: function (fn, scope, args) { + var frame = this.enter(); + if (args) { + fn.apply(scope, args); + } else { + fn.call(scope); + } + frame.leave(); + }, + + report: function () { + Ext.log(this.format()); + }, + + tap: function (className, methodName) { + var me = this, + methods = typeof methodName == 'string' ? [methodName] : methodName, + klass, statik, i, parts, length, name, src, + tapFunc; + + tapFunc = function(){ + if (typeof className == 'string') { + klass = Ext.global; + parts = className.split('.'); + for (i = 0, length = parts.length; i < length; ++i) { + klass = klass[parts[i]]; + } + } else { + klass = className; + } + + for (i = 0, length = methods.length; i < length; ++i) { + name = methods[i]; + statik = name.charAt(0) == '!'; + + if (statik) { + name = name.substring(1); + } else { + statik = !(name in klass.prototype); + } + + src = statik ? klass : klass.prototype; + src[name] = makeTap(me, src[name]); + } + }; + + Ext.ClassManager.onCreated(tapFunc, me, className); + + return me; + } + }; +}()), + +function () { + Ext.perf.getTimestamp = this.getTimestamp; +}); + +/** + * @class Ext.perf.Monitor + * @singleton + * @private + */ +Ext.define('Ext.perf.Monitor', { + singleton: true, + alternateClassName: 'Ext.Perf', + + requires: [ + 'Ext.perf.Accumulator' + ], + + constructor: function () { + this.accumulators = []; + this.accumulatorsByName = {}; + }, + + calibrate: function () { + var accum = new Ext.perf.Accumulator('$'), + total = accum.total, + getTimestamp = Ext.perf.Accumulator.getTimestamp, + count = 0, + frame, + endTime, + startTime; + + startTime = getTimestamp(); + + do { + frame = accum.enter(); + frame.leave(); + ++count; + } while (total.sum < 100); + + endTime = getTimestamp(); + + return (endTime - startTime) / count; + }, + + get: function (name) { + var me = this, + accum = me.accumulatorsByName[name]; + + if (!accum) { + me.accumulatorsByName[name] = accum = new Ext.perf.Accumulator(name); + me.accumulators.push(accum); + } + + return accum; + }, + + enter: function (name) { + return this.get(name).enter(); + }, + + monitor: function (name, fn, scope) { + this.get(name).monitor(fn, scope); + }, + + report: function () { + var me = this, + accumulators = me.accumulators, + calibration = me.calibrate(); + + accumulators.sort(function (a, b) { + return (a.name < b.name) ? -1 : ((b.name < a.name) ? 1 : 0); + }); + + me.updateGC(); + + Ext.log('Calibration: ' + Math.round(calibration * 100) / 100 + ' msec/sample'); + Ext.each(accumulators, function (accum) { + Ext.log(accum.format(calibration)); + }); + }, + + getData: function (all) { + var ret = {}, + accumulators = this.accumulators; + + Ext.each(accumulators, function (accum) { + if (all || accum.count) { + ret[accum.name] = accum.getData(); + } + }); + + return ret; + }, + + updateGC: function () { + var accumGC = this.accumulatorsByName.GC, + toolbox = Ext.senchaToolbox, + bucket; + + if (accumGC) { + accumGC.count = toolbox.garbageCollectionCounter || 0; + + if (accumGC.count) { + bucket = accumGC.pure; + accumGC.total.sum = bucket.sum = toolbox.garbageCollectionMilliseconds; + bucket.min = bucket.max = bucket.sum / accumGC.count; + bucket = accumGC.total; + bucket.min = bucket.max = bucket.sum / accumGC.count; + } + } + }, + + watchGC: function () { + Ext.perf.getTimestamp(); // initializes SenchaToolbox (if available) + + var toolbox = Ext.senchaToolbox; + + if (toolbox) { + this.get("GC"); + toolbox.watchGarbageCollector(false); // no logging, just totals + } + }, + + setup: function (config) { + if (!config) { + config = { + /*insertHtml: { + 'Ext.dom.Helper': 'insertHtml' + },*/ + /*xtplCompile: { + 'Ext.XTemplateCompiler': 'compile' + },*/ +// doInsert: { +// 'Ext.Template': 'doInsert' +// }, +// applyOut: { +// 'Ext.XTemplate': 'applyOut' +// }, + render: { + 'Ext.AbstractComponent': 'render' + }, +// fnishRender: { +// 'Ext.AbstractComponent': 'finishRender' +// }, +// renderSelectors: { +// 'Ext.AbstractComponent': 'applyRenderSelectors' +// }, +// compAddCls: { +// 'Ext.AbstractComponent': 'addCls' +// }, +// compRemoveCls: { +// 'Ext.AbstractComponent': 'removeCls' +// }, +// getStyle: { +// 'Ext.core.Element': 'getStyle' +// }, +// setStyle: { +// 'Ext.core.Element': 'setStyle' +// }, +// addCls: { +// 'Ext.core.Element': 'addCls' +// }, +// removeCls: { +// 'Ext.core.Element': 'removeCls' +// }, +// measure: { +// 'Ext.layout.component.Component': 'measureAutoDimensions' +// }, +// moveItem: { +// 'Ext.layout.Layout': 'moveItem' +// }, +// layoutFlush: { +// 'Ext.layout.Context': 'flush' +// }, + layout: { + 'Ext.layout.Context': 'run' + } + }; + } + + this.currentConfig = config; + + var key, prop, + accum, className, methods; + for (key in config) { + if (config.hasOwnProperty(key)) { + prop = config[key]; + accum = Ext.Perf.get(key); + + for (className in prop) { + if (prop.hasOwnProperty(className)) { + methods = prop[className]; + accum.tap(className, methods); + } + } + } + } + + this.watchGC(); + } +}); + +/** + * @class Ext.is + * + * Determines information about the current platform the application is running on. + * + * @singleton + */ +Ext.is = { + init : function(navigator) { + var platforms = this.platforms, + ln = platforms.length, + i, platform; + + navigator = navigator || window.navigator; + + for (i = 0; i < ln; i++) { + platform = platforms[i]; + this[platform.identity] = platform.regex.test(navigator[platform.property]); + } + + /** + * @property Desktop True if the browser is running on a desktop machine + * @type {Boolean} + */ + this.Desktop = this.Mac || this.Windows || (this.Linux && !this.Android); + /** + * @property Tablet True if the browser is running on a tablet (iPad) + */ + this.Tablet = this.iPad; + /** + * @property Phone True if the browser is running on a phone. + * @type {Boolean} + */ + this.Phone = !this.Desktop && !this.Tablet; + /** + * @property iOS True if the browser is running on iOS + * @type {Boolean} + */ + this.iOS = this.iPhone || this.iPad || this.iPod; + + /** + * @property Standalone Detects when application has been saved to homescreen. + * @type {Boolean} + */ + this.Standalone = !!window.navigator.standalone; + }, + + /** + * @property iPhone True when the browser is running on a iPhone + * @type {Boolean} + */ + platforms: [{ + property: 'platform', + regex: /iPhone/i, + identity: 'iPhone' + }, + + /** + * @property iPod True when the browser is running on a iPod + * @type {Boolean} + */ + { + property: 'platform', + regex: /iPod/i, + identity: 'iPod' + }, + + /** + * @property iPad True when the browser is running on a iPad + * @type {Boolean} + */ + { + property: 'userAgent', + regex: /iPad/i, + identity: 'iPad' + }, + + /** + * @property Blackberry True when the browser is running on a Blackberry + * @type {Boolean} + */ + { + property: 'userAgent', + regex: /Blackberry/i, + identity: 'Blackberry' + }, + + /** + * @property Android True when the browser is running on an Android device + * @type {Boolean} + */ + { + property: 'userAgent', + regex: /Android/i, + identity: 'Android' + }, + + /** + * @property Mac True when the browser is running on a Mac + * @type {Boolean} + */ + { + property: 'platform', + regex: /Mac/i, + identity: 'Mac' + }, + + /** + * @property Windows True when the browser is running on Windows + * @type {Boolean} + */ + { + property: 'platform', + regex: /Win/i, + identity: 'Windows' + }, + + /** + * @property Linux True when the browser is running on Linux + * @type {Boolean} + */ + { + property: 'platform', + regex: /Linux/i, + identity: 'Linux' + }] +}; + +Ext.is.init(); + +/** + * @class Ext.supports + * + * Determines information about features are supported in the current environment + * + * @singleton + */ +(function(){ + + // this is a local copy of certain logic from (Abstract)Element.getStyle + // to break a dependancy between the supports mechanism and Element + // use this instead of element references to check for styling info + var getStyle = function(element, styleName){ + var view = element.ownerDocument.defaultView, + style = (view ? view.getComputedStyle(element, null) : element.currentStyle) || element.style; + return style[styleName]; + }; + +Ext.supports = { + /** + * Runs feature detection routines and sets the various flags. This is called when + * the scripts loads (very early) and again at {@link Ext#onReady}. Some detections + * are flagged as `early` and run immediately. Others that require the document body + * will not run until ready. + * + * Each test is run only once, so calling this method from an onReady function is safe + * and ensures that all flags have been set. + * @markdown + * @private + */ + init : function() { + var me = this, + doc = document, + tests = me.tests, + n = tests.length, + div = n && Ext.isReady && doc.createElement('div'), + test, notRun = []; + + if (div) { + div.innerHTML = [ + '
    ', + '
    ', + '
    ', + '
    ', + '
    ', + '
    ', + '
    ', + '
    ' + ].join(''); + + doc.body.appendChild(div); + } + + while (n--) { + test = tests[n]; + if (div || test.early) { + me[test.identity] = test.fn.call(me, doc, div); + } else { + notRun.push(test); + } + } + + if (div) { + doc.body.removeChild(div); + } + + me.tests = notRun; + }, + + /** + * @property PointerEvents True if document environment supports the CSS3 pointer-events style. + * @type {Boolean} + */ + PointerEvents: 'pointerEvents' in document.documentElement.style, + + /** + * @property CSS3BoxShadow True if document environment supports the CSS3 box-shadow style. + * @type {Boolean} + */ + CSS3BoxShadow: 'boxShadow' in document.documentElement.style || 'WebkitBoxShadow' in document.documentElement.style || 'MozBoxShadow' in document.documentElement.style, + + /** + * @property ClassList True if document environment supports the HTML5 classList API. + * @type {Boolean} + */ + ClassList: !!document.documentElement.classList, + + /** + * @property OrientationChange True if the device supports orientation change + * @type {Boolean} + */ + OrientationChange: ((typeof window.orientation != 'undefined') && ('onorientationchange' in window)), + + /** + * @property DeviceMotion True if the device supports device motion (acceleration and rotation rate) + * @type {Boolean} + */ + DeviceMotion: ('ondevicemotion' in window), + + /** + * @property Touch True if the device supports touch + * @type {Boolean} + */ + // is.Desktop is needed due to the bug in Chrome 5.0.375, Safari 3.1.2 + // and Safari 4.0 (they all have 'ontouchstart' in the window object). + Touch: ('ontouchstart' in window) && (!Ext.is.Desktop), + + /** + * @property TimeoutActualLateness True if the browser passes the "actualLateness" parameter to + * setTimeout. See: https://developer.mozilla.org/en/DOM/window.setTimeout + * @type {Boolean} + */ + TimeoutActualLateness: (function(){ + setTimeout(function(){ + Ext.supports.TimeoutActualLateness = arguments.length !== 0; + }, 0); + }()), + + tests: [ + /** + * @property Transitions True if the device supports CSS3 Transitions + * @type {Boolean} + */ + { + identity: 'Transitions', + fn: function(doc, div) { + var prefix = [ + 'webkit', + 'Moz', + 'o', + 'ms', + 'khtml' + ], + TE = 'TransitionEnd', + transitionEndName = [ + prefix[0] + TE, + 'transitionend', //Moz bucks the prefixing convention + prefix[2] + TE, + prefix[3] + TE, + prefix[4] + TE + ], + ln = prefix.length, + i = 0, + out = false; + + for (; i < ln; i++) { + if (getStyle(div, prefix[i] + "TransitionProperty")) { + Ext.supports.CSS3Prefix = prefix[i]; + Ext.supports.CSS3TransitionEnd = transitionEndName[i]; + out = true; + break; + } + } + return out; + } + }, + + /** + * @property RightMargin True if the device supports right margin. + * See https://bugs.webkit.org/show_bug.cgi?id=13343 for why this is needed. + * @type {Boolean} + */ + { + identity: 'RightMargin', + fn: function(doc, div) { + var view = doc.defaultView; + return !(view && view.getComputedStyle(div.firstChild.firstChild, null).marginRight != '0px'); + } + }, + + /** + * @property DisplayChangeInputSelectionBug True if INPUT elements lose their + * selection when their display style is changed. Essentially, if a text input + * has focus and its display style is changed, the I-beam disappears. + * + * This bug is encountered due to the work around in place for the {@link #RightMargin} + * bug. This has been observed in Safari 4.0.4 and older, and appears to be fixed + * in Safari 5. It's not clear if Safari 4.1 has the bug, but it has the same WebKit + * version number as Safari 5 (according to http://unixpapa.com/js/gecko.html). + */ + { + identity: 'DisplayChangeInputSelectionBug', + early: true, + fn: function() { + var webKitVersion = Ext.webKitVersion; + // WebKit but older than Safari 5 or Chrome 6: + return 0 < webKitVersion && webKitVersion < 533; + } + }, + + /** + * @property DisplayChangeTextAreaSelectionBug True if TEXTAREA elements lose their + * selection when their display style is changed. Essentially, if a text area has + * focus and its display style is changed, the I-beam disappears. + * + * This bug is encountered due to the work around in place for the {@link #RightMargin} + * bug. This has been observed in Chrome 10 and Safari 5 and older, and appears to + * be fixed in Chrome 11. + */ + { + identity: 'DisplayChangeTextAreaSelectionBug', + early: true, + fn: function() { + var webKitVersion = Ext.webKitVersion; + + /* + Has bug w/textarea: + + (Chrome) Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7; en-US) + AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.127 + Safari/534.16 + (Safari) Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7; en-us) + AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 + Safari/533.21.1 + + No bug: + + (Chrome) Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_7) + AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.57 + Safari/534.24 + */ + return 0 < webKitVersion && webKitVersion < 534.24; + } + }, + + /** + * @property TransparentColor True if the device supports transparent color + * @type {Boolean} + */ + { + identity: 'TransparentColor', + fn: function(doc, div, view) { + view = doc.defaultView; + return !(view && view.getComputedStyle(div.lastChild, null).backgroundColor != 'transparent'); + } + }, + + /** + * @property ComputedStyle True if the browser supports document.defaultView.getComputedStyle() + * @type {Boolean} + */ + { + identity: 'ComputedStyle', + fn: function(doc, div, view) { + view = doc.defaultView; + return view && view.getComputedStyle; + } + }, + + /** + * @property SVG True if the device supports SVG + * @type {Boolean} + */ + { + identity: 'Svg', + fn: function(doc) { + return !!doc.createElementNS && !!doc.createElementNS( "http:/" + "/www.w3.org/2000/svg", "svg").createSVGRect; + } + }, + + /** + * @property Canvas True if the device supports Canvas + * @type {Boolean} + */ + { + identity: 'Canvas', + fn: function(doc) { + return !!doc.createElement('canvas').getContext; + } + }, + + /** + * @property VML True if the device supports VML + * @type {Boolean} + */ + { + identity: 'Vml', + fn: function(doc) { + var d = doc.createElement("div"); + d.innerHTML = ""; + return (d.childNodes.length == 2); + } + }, + + /** + * @property Float True if the device supports CSS float + * @type {Boolean} + */ + { + identity: 'Float', + fn: function(doc, div) { + return !!div.lastChild.style.cssFloat; + } + }, + + /** + * @property AudioTag True if the device supports the HTML5 audio tag + * @type {Boolean} + */ + { + identity: 'AudioTag', + fn: function(doc) { + return !!doc.createElement('audio').canPlayType; + } + }, + + /** + * @property History True if the device supports HTML5 history + * @type {Boolean} + */ + { + identity: 'History', + fn: function() { + var history = window.history; + return !!(history && history.pushState); + } + }, + + /** + * @property CSS3DTransform True if the device supports CSS3DTransform + * @type {Boolean} + */ + { + identity: 'CSS3DTransform', + fn: function() { + return (typeof WebKitCSSMatrix != 'undefined' && new WebKitCSSMatrix().hasOwnProperty('m41')); + } + }, + + /** + * @property CSS3LinearGradient True if the device supports CSS3 linear gradients + * @type {Boolean} + */ + { + identity: 'CSS3LinearGradient', + fn: function(doc, div) { + var property = 'background-image:', + webkit = '-webkit-gradient(linear, left top, right bottom, from(black), to(white))', + w3c = 'linear-gradient(left top, black, white)', + moz = '-moz-' + w3c, + opera = '-o-' + w3c, + options = [property + webkit, property + w3c, property + moz, property + opera]; + + div.style.cssText = options.join(';'); + + return ("" + div.style.backgroundImage).indexOf('gradient') !== -1; + } + }, + + /** + * @property CSS3BorderRadius True if the device supports CSS3 border radius + * @type {Boolean} + */ + { + identity: 'CSS3BorderRadius', + fn: function(doc, div) { + var domPrefixes = ['borderRadius', 'BorderRadius', 'MozBorderRadius', 'WebkitBorderRadius', 'OBorderRadius', 'KhtmlBorderRadius'], + pass = false, + i; + for (i = 0; i < domPrefixes.length; i++) { + if (document.body.style[domPrefixes[i]] !== undefined) { + return true; + } + } + return pass; + } + }, + + /** + * @property GeoLocation True if the device supports GeoLocation + * @type {Boolean} + */ + { + identity: 'GeoLocation', + fn: function() { + return (typeof navigator != 'undefined' && typeof navigator.geolocation != 'undefined') || (typeof google != 'undefined' && typeof google.gears != 'undefined'); + } + }, + /** + * @property MouseEnterLeave True if the browser supports mouseenter and mouseleave events + * @type {Boolean} + */ + { + identity: 'MouseEnterLeave', + fn: function(doc, div){ + return ('onmouseenter' in div && 'onmouseleave' in div); + } + }, + /** + * @property MouseWheel True if the browser supports the mousewheel event + * @type {Boolean} + */ + { + identity: 'MouseWheel', + fn: function(doc, div) { + return ('onmousewheel' in div); + } + }, + /** + * @property Opacity True if the browser supports normal css opacity + * @type {Boolean} + */ + { + identity: 'Opacity', + fn: function(doc, div){ + // Not a strict equal comparison in case opacity can be converted to a number. + if (Ext.isIE6 || Ext.isIE7 || Ext.isIE8) { + return false; + } + div.firstChild.style.cssText = 'opacity:0.73'; + return div.firstChild.style.opacity == '0.73'; + } + }, + /** + * @property Placeholder True if the browser supports the HTML5 placeholder attribute on inputs + * @type {Boolean} + */ + { + identity: 'Placeholder', + fn: function(doc) { + return 'placeholder' in doc.createElement('input'); + } + }, + + /** + * @property Direct2DBug True if when asking for an element's dimension via offsetWidth or offsetHeight, + * getBoundingClientRect, etc. the browser returns the subpixel width rounded to the nearest pixel. + * @type {Boolean} + */ + { + identity: 'Direct2DBug', + fn: function() { + return Ext.isString(document.body.style.msTransformOrigin); + } + }, + /** + * @property BoundingClientRect True if the browser supports the getBoundingClientRect method on elements + * @type {Boolean} + */ + { + identity: 'BoundingClientRect', + fn: function(doc, div) { + return Ext.isFunction(div.getBoundingClientRect); + } + }, + { + identity: 'IncludePaddingInWidthCalculation', + fn: function(doc, div){ + return div.childNodes[1].firstChild.offsetWidth == 210; + } + }, + { + identity: 'IncludePaddingInHeightCalculation', + fn: function(doc, div){ + return div.childNodes[1].firstChild.offsetHeight == 210; + } + }, + + /** + * @property ArraySort True if the Array sort native method isn't bugged. + * @type {Boolean} + */ + { + identity: 'ArraySort', + fn: function() { + var a = [1,2,3,4,5].sort(function(){ return 0; }); + return a[0] === 1 && a[1] === 2 && a[2] === 3 && a[3] === 4 && a[4] === 5; + } + }, + /** + * @property Range True if browser support document.createRange native method. + * @type {Boolean} + */ + { + identity: 'Range', + fn: function() { + return !!document.createRange; + } + }, + /** + * @property CreateContextualFragment True if browser support CreateContextualFragment range native methods. + * @type {Boolean} + */ + { + identity: 'CreateContextualFragment', + fn: function() { + var range = Ext.supports.Range ? document.createRange() : false; + + return range && !!range.createContextualFragment; + } + }, + + /** + * @property WindowOnError True if browser supports window.onerror. + * @type {Boolean} + */ + { + identity: 'WindowOnError', + fn: function () { + // sadly, we cannot feature detect this... + return Ext.isIE || Ext.isGecko || Ext.webKitVersion >= 534.16; // Chrome 10+ + } + }, + + /** + * @property TextAreaMaxLength True if the browser supports maxlength on textareas. + * @type {Boolean} + */ + { + identity: 'TextAreaMaxLength', + fn: function(){ + var el = document.createElement('textarea'); + return ('maxlength' in el); + } + }, + /** + * @property GetPositionPercentage True if the browser will return the left/top/right/bottom + * position as a percentage when explicitly set as a percentage value. + * @type {Boolean} + */ + // Related bug: https://bugzilla.mozilla.org/show_bug.cgi?id=707691#c7 + { + identity: 'GetPositionPercentage', + fn: function(doc, div){ + return getStyle(div.childNodes[2], 'left') == '10%'; + } + } + ] +}; +}()); + +Ext.supports.init(); // run the "early" detections now + + +/** + * @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. If not specified here, it must be specified during the {@link #delay} call. + * @param {Object} scope (optional) 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 + */ + this.delay = function(delay, newFn, newScope, newArgs) { + me.cancel(); + fn = newFn || fn; + scope = newScope || scope; + args = newArgs || args; + id = setInterval(call, delay); + }; + + /** + * Cancel the last queued timeout + */ + this.cancel = function(){ + if (id) { + clearInterval(id); + id = null; + } + }; +}; +Ext.require('Ext.util.DelayedTask', function() { + + /** + * Represents single event type that an Observable object listens to. + * All actual listeners are tracked inside here. When the event fires, + * it calls all the registered listener functions. + * + * @private + */ + Ext.util.Event = Ext.extend(Object, (function() { + function createTargeted(handler, listener, o, scope){ + return function(){ + if (o.target === arguments[0]){ + handler.apply(scope, arguments); + } + }; + } + + function createBuffered(handler, listener, o, scope) { + listener.task = new Ext.util.DelayedTask(); + return function() { + listener.task.delay(o.buffer, handler, scope, Ext.Array.toArray(arguments)); + }; + } + + function createDelayed(handler, listener, o, scope) { + return function() { + var task = new Ext.util.DelayedTask(); + if (!listener.tasks) { + listener.tasks = []; + } + listener.tasks.push(task); + task.delay(o.delay || 10, handler, scope, Ext.Array.toArray(arguments)); + }; + } + + function createSingle(handler, listener, o, scope) { + return function() { + var event = listener.ev; + + if (event.removeListener(listener.fn, scope) && event.observable) { + // Removing from a regular Observable-owned, named event (not an anonymous + // event such as Ext's readyEvent): Decrement the listeners count + event.observable.hasListeners[event.name]--; + } + + return handler.apply(scope, arguments); + }; + } + + return { + /** + * @property {Boolean} isEvent + * `true` in this class to identify an object as an instantiated Event, or subclass thereof. + */ + isEvent: true, + + constructor: function(observable, name) { + this.name = name; + this.observable = observable; + this.listeners = []; + }, + + addListener: function(fn, scope, options) { + var me = this, + listener; + scope = scope || me.observable; + + if (!fn) { + Ext.Error.raise({ + sourceClass: Ext.getClassName(this.observable), + sourceMethod: "addListener", + msg: "The specified callback function is undefined" + }); + } + + if (!me.isListening(fn, scope)) { + listener = me.createListener(fn, scope, options); + if (me.firing) { + // if we are currently firing this event, don't disturb the listener loop + me.listeners = me.listeners.slice(0); + } + me.listeners.push(listener); + } + }, + + createListener: function(fn, scope, o) { + o = o || {}; + scope = scope || this.observable; + + var listener = { + fn: fn, + scope: scope, + o: o, + ev: this + }, + handler = fn; + + // The order is important. The 'single' wrapper must be wrapped by the 'buffer' and 'delayed' wrapper + // because the event removal that the single listener does destroys the listener's DelayedTask(s) + if (o.single) { + handler = createSingle(handler, listener, o, scope); + } + if (o.target) { + handler = createTargeted(handler, listener, o, scope); + } + if (o.delay) { + handler = createDelayed(handler, listener, o, scope); + } + if (o.buffer) { + handler = createBuffered(handler, listener, o, scope); + } + + listener.fireFn = handler; + return listener; + }, + + findListener: function(fn, scope) { + var listeners = this.listeners, + i = listeners.length, + listener, + s; + + while (i--) { + listener = listeners[i]; + if (listener) { + s = listener.scope; + if (listener.fn == fn && (s == scope || s == this.observable)) { + return i; + } + } + } + + return - 1; + }, + + isListening: function(fn, scope) { + return this.findListener(fn, scope) !== -1; + }, + + removeListener: function(fn, scope) { + var me = this, + index, + listener, + k; + index = me.findListener(fn, scope); + if (index != -1) { + listener = me.listeners[index]; + + if (me.firing) { + me.listeners = me.listeners.slice(0); + } + + // cancel and remove a buffered handler that hasn't fired yet + if (listener.task) { + listener.task.cancel(); + delete listener.task; + } + + // cancel and remove all delayed handlers that haven't fired yet + k = listener.tasks && listener.tasks.length; + if (k) { + while (k--) { + listener.tasks[k].cancel(); + } + delete listener.tasks; + } + + // remove this listener from the listeners array + Ext.Array.erase(me.listeners, index, 1); + return true; + } + + return false; + }, + + // Iterate to stop any buffered/delayed events + clearListeners: function() { + var listeners = this.listeners, + i = listeners.length; + + while (i--) { + this.removeListener(listeners[i].fn, listeners[i].scope); + } + }, + + fire: function() { + var me = this, + listeners = me.listeners, + count = listeners.length, + i, + args, + listener; + + if (count > 0) { + me.firing = true; + for (i = 0; i < count; i++) { + listener = listeners[i]; + args = arguments.length ? Array.prototype.slice.call(arguments, 0) : []; + if (listener.o) { + args.push(listener.o); + } + if (listener && listener.fireFn.apply(listener.scope || me.observable, args) === false) { + return (me.firing = false); + } + } + } + me.firing = false; + return true; + } + }; + }())); +}); + +/** + * @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 = new function() { + var EventManager = this, + doc = document, + win = window, + initExtCss = function() { + // find the body element + var bd = doc.body || doc.getElementsByTagName('body')[0], + baseCSSPrefix = Ext.baseCSSPrefix, + cls = [baseCSSPrefix + 'body'], + htmlCls = [], + html; + + if (!bd) { + return false; + } + + html = bd.parentNode; + + function add (c) { + cls.push(baseCSSPrefix + c); + } + + //Let's keep this human readable! + if (Ext.isIE) { + add('ie'); + + // very often CSS needs to do checks like "IE7+" or "IE6 or 7". To help + // reduce the clutter (since CSS/SCSS cannot do these tests), we add some + // additional classes: + // + // x-ie7p : IE7+ : 7 <= ieVer + // x-ie7m : IE7- : ieVer <= 7 + // x-ie8p : IE8+ : 8 <= ieVer + // x-ie8m : IE8- : ieVer <= 8 + // x-ie9p : IE9+ : 9 <= ieVer + // x-ie78 : IE7 or 8 : 7 <= ieVer <= 8 + // + if (Ext.isIE6) { + add('ie6'); + } else { // ignore pre-IE6 :) + add('ie7p'); + + if (Ext.isIE7) { + add('ie7'); + } else { + add('ie8p'); + + if (Ext.isIE8) { + add('ie8'); + } else { + add('ie9p'); + + if (Ext.isIE9) { + add('ie9'); + } + } + } + } + + if (Ext.isIE6 || Ext.isIE7) { + add('ie7m'); + } + if (Ext.isIE6 || Ext.isIE7 || Ext.isIE8) { + add('ie8m'); + } + if (Ext.isIE7 || Ext.isIE8) { + add('ie78'); + } + } + if (Ext.isGecko) { + add('gecko'); + if (Ext.isGecko3) { + add('gecko3'); + } + if (Ext.isGecko4) { + add('gecko4'); + } + if (Ext.isGecko5) { + add('gecko5'); + } + } + if (Ext.isOpera) { + add('opera'); + } + if (Ext.isWebKit) { + add('webkit'); + } + if (Ext.isSafari) { + add('safari'); + if (Ext.isSafari2) { + add('safari2'); + } + if (Ext.isSafari3) { + add('safari3'); + } + if (Ext.isSafari4) { + add('safari4'); + } + if (Ext.isSafari5) { + add('safari5'); + } + if (Ext.isSafari5_0) { + add('safari5_0') + } + } + if (Ext.isChrome) { + add('chrome'); + } + if (Ext.isMac) { + add('mac'); + } + if (Ext.isLinux) { + add('linux'); + } + if (!Ext.supports.CSS3BorderRadius) { + add('nbr'); + } + if (!Ext.supports.CSS3LinearGradient) { + add('nlg'); + } + if (!Ext.scopeResetCSS) { + add('reset'); + } + + // add to the parent to allow for selectors x-strict x-border-box, also set the isBorderBox property correctly + if (html) { + if (Ext.isStrict && (Ext.isIE6 || Ext.isIE7)) { + Ext.isBorderBox = false; + } + else { + Ext.isBorderBox = true; + } + + if(Ext.isBorderBox) { + htmlCls.push(baseCSSPrefix + 'border-box'); + } + if (Ext.isStrict) { + htmlCls.push(baseCSSPrefix + 'strict'); + } else { + htmlCls.push(baseCSSPrefix + 'quirks'); + } + Ext.fly(html, '_internal').addCls(htmlCls); + } + + Ext.fly(bd, '_internal').addCls(cls); + return true; + }; + + Ext.apply(EventManager, { + /** + * Check if we have bound our global onReady listener + * @private + */ + hasBoundOnReady: false, + + /** + * Check if fireDocReady has been called + * @private + */ + hasFiredReady: false, + + /** + * Additionally, allow the 'DOM' listener thread to complete (usually desirable with mobWebkit, Gecko) + * before firing the entire onReady chain (high stack load on Loader) by specifying a delay value + * @default 1ms + * @private + */ + deferReadyEvent : 1, + + /* + * diags: a list of event names passed to onReadyEvent (in chron order) + * @private + */ + onReadyChain : [], + + /** + * Holds references to any onReady functions + * @private + */ + readyEvent: + (function () { + var event = new Ext.util.Event(); + event.fire = function () { + Ext._beforeReadyTime = Ext._beforeReadyTime || new Date().getTime(); + event.self.prototype.fire.apply(event, arguments); + Ext._afterReadytime = new Date().getTime(); + }; + return event; + }()), + + /** + * Fires when a DOM event handler finishes its run, just before returning to browser control. + * This can be useful for performing cleanup, or upfdate tasks which need to happen only + * after all code in an event handler has been run, but which should not be executed in a timer + * due to the intervening browser reflow/repaint which would take place. + * + */ + idleEvent: new Ext.util.Event(), + + /** + * detects whether the EventManager has been placed in a paused state for synchronization + * with external debugging / perf tools (PageAnalyzer) + * @private + */ + isReadyPaused: function(){ + return (/[?&]ext-pauseReadyFire\b/i.test(location.search) && !Ext._continueFireReady); + }, + + /** + * Binds the appropriate browser event for checking if the DOM has loaded. + * @private + */ + bindReadyEvent: function() { + if (EventManager.hasBoundOnReady) { + return; + } + + // Test scenario where Core is dynamically loaded AFTER window.load + if ( doc.readyState == 'complete' ) { // Firefox4+ got support for this state, others already do. + EventManager.onReadyEvent({ + type: doc.readyState || 'body' + }); + } else { + document.addEventListener('DOMContentLoaded', EventManager.onReadyEvent, false); + window.addEventListener('load', EventManager.onReadyEvent, false); + EventManager.hasBoundOnReady = true; + } + }, + + onReadyEvent : function(e) { + if (e && e.type) { + EventManager.onReadyChain.push(e.type); + } + + if (EventManager.hasBoundOnReady) { + document.removeEventListener('DOMContentLoaded', EventManager.onReadyEvent, false); + window.removeEventListener('load', EventManager.onReadyEvent, false); + } + + if (!Ext.isReady) { + EventManager.fireDocReady(); + } + }, + + /** + * We know the document is loaded, so trigger any onReady events. + * @private + */ + fireDocReady: function() { + if (!Ext.isReady) { + Ext._readyTime = new Date().getTime(); + Ext.isReady = true; + + Ext.supports.init(); + EventManager.onWindowUnload(); + EventManager.readyEvent.onReadyChain = EventManager.onReadyChain; //diags report + + if (Ext.isNumber(EventManager.deferReadyEvent)) { + Ext.Function.defer(EventManager.fireReadyEvent, EventManager.deferReadyEvent); + EventManager.hasDocReadyTimer = true; + } else { + EventManager.fireReadyEvent(); + } + } + }, + + /** + * Fires the ready event + * @private + */ + fireReadyEvent: function(){ + var readyEvent = EventManager.readyEvent; + + // Unset the timer flag here since other onReady events may be + // added during the fire() call and we don't want to block them + EventManager.hasDocReadyTimer = false; + EventManager.isFiring = true; + + // Ready events are all single: true, if we get to the end + // & there are more listeners, it means they were added + // inside some other ready event + while (readyEvent.listeners.length && !EventManager.isReadyPaused()) { + readyEvent.fire(); + } + EventManager.isFiring = false; + EventManager.hasFiredReady = true; + }, + + /** + * 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}. + */ + onDocumentReady: function(fn, scope, options) { + options = options || {}; + // force single, only ever fire it once + options.single = true; + EventManager.readyEvent.addListener(fn, scope, options); + + // If we're in the middle of firing, or we have a deferred timer + // pending, drop out since the event will be fired later + if (!(EventManager.isFiring || EventManager.hasDocReadyTimer)) { + if (Ext.isReady) { + EventManager.fireReadyEvent(); + } else { + EventManager.bindReadyEvent(); + } + } + }, + + // --------------------- event binding --------------------- + + /** + * Contains a list of all document mouse downs, so we can ensure they fire even when stopEvent is called. + * @private + */ + stoppedMouseDownEvent: new Ext.util.Event(), + + /** + * Options to parse for the 4th argument to addListener. + * @private + */ + propRe: /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate|freezeEvent)$/, + + /** + * Get the id of the element. If one has not been assigned, automatically assign it. + * @param {HTMLElement/Ext.Element} element The element to get the id for. + * @return {String} id + */ + getId : function(element) { + var id; + + element = Ext.getDom(element); + + if (element === doc || element === win) { + id = element === doc ? Ext.documentId : Ext.windowId; + } + else { + id = Ext.id(element); + } + + if (!Ext.cache[id]) { + Ext.addCacheEntry(id, null, element); + } + + return id; + }, + + /** + * Convert a "config style" listener into a set of flat arguments so they can be passed to addListener + * @private + * @param {Object} element The element the event is for + * @param {Object} event The event configuration + * @param {Object} isRemove True if a removal should be performed, otherwise an add will be done. + */ + prepareListenerConfig: function(element, config, isRemove) { + var propRe = EventManager.propRe, + key, value, args; + + // loop over all the keys in the object + for (key in config) { + if (config.hasOwnProperty(key)) { + // if the key is something else then an event option + if (!propRe.test(key)) { + value = config[key]; + // if the value is a function it must be something like click: function() {}, scope: this + // which means that there might be multiple event listeners with shared options + if (typeof value == 'function') { + // shared options + args = [element, key, value, config.scope, config]; + } else { + // if its not a function, it must be an object like click: {fn: function() {}, scope: this} + args = [element, key, value.fn, value.scope, value]; + } + + if (isRemove) { + EventManager.removeListener.apply(EventManager, args); + } else { + EventManager.addListener.apply(EventManager, args); + } + } + } + } + }, + + mouseEnterLeaveRe: /mouseenter|mouseleave/, + + /** + * Normalize cross browser event differences + * @private + * @param {Object} eventName The event name + * @param {Object} fn The function to execute + * @return {Object} The new event name/function + */ + normalizeEvent: function(eventName, fn) { + if (EventManager.mouseEnterLeaveRe.test(eventName) && !Ext.supports.MouseEnterLeave) { + if (fn) { + fn = Ext.Function.createInterceptor(fn, EventManager.contains); + } + eventName = eventName == 'mouseenter' ? 'mouseover' : 'mouseout'; + } else if (eventName == 'mousewheel' && !Ext.supports.MouseWheel && !Ext.isOpera) { + eventName = 'DOMMouseScroll'; + } + return { + eventName: eventName, + fn: fn + }; + }, + + /** + * Checks whether the event's relatedTarget is contained inside (or is) the element. + * @private + * @param {Object} event + */ + contains: function(event) { + var parent = event.browserEvent.currentTarget, + child = EventManager.getRelatedTarget(event); + + if (parent && parent.firstChild) { + while (child) { + if (child === parent) { + return false; + } + child = child.parentNode; + if (child && (child.nodeType != 1)) { + child = null; + } + } + } + return true; + }, + + /** + * 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:
      + *
    • evt : EventObject
      The {@link Ext.EventObject EventObject} describing the event.
    • + *
    • t : Element
      The {@link Ext.Element Element} which was the target of the event. + * Note that this may be filtered by using the delegate option.
    • + *
    • o : Object
      The options object from the addListener call.
    • + *
    + * @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:
      + *
    • scope : Object
      The scope (this reference) in which the handler function is executed. Defaults to the Element.
    • + *
    • delegate : String
      A simple selector to filter the target or look for a descendant of the target
    • + *
    • stopEvent : Boolean
      True to stop the event. That is stop propagation, and prevent the default action.
    • + *
    • preventDefault : Boolean
      True to prevent the default action
    • + *
    • stopPropagation : Boolean
      True to prevent event propagation
    • + *
    • normalized : Boolean
      False to pass a browser event to the handler function instead of an Ext.EventObject
    • + *
    • delay : Number
      The number of milliseconds to delay the invocation of the handler after te event fires.
    • + *
    • single : Boolean
      True to add a handler to handle just the next firing of the event, and then remove itself.
    • + *
    • buffer : Number
      Causes the handler to be scheduled to run in an {@link Ext.util.DelayedTask} delayed + * by the specified number of milliseconds. If the event fires again within that time, the original + * handler is not invoked, but the new handler is scheduled in its place.
    • + *
    • target : Element
      Only call the handler if the event was fired on the target Element, not if the event was bubbled up from a child node.
    • + *

    + *

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

    + */ + addListener: function(element, eventName, fn, scope, options) { + // Check if we've been passed a "config style" event. + if (typeof eventName !== 'string') { + EventManager.prepareListenerConfig(element, eventName); + return; + } + + var dom = element.dom || Ext.getDom(element), + bind, wrap; + + if (!fn) { + Ext.Error.raise({ + sourceClass: 'Ext.EventManager', + sourceMethod: 'addListener', + targetElement: element, + eventName: eventName, + msg: 'Error adding "' + eventName + '\" listener. The handler function is undefined.' + }); + } + + // create the wrapper function + options = options || {}; + + bind = EventManager.normalizeEvent(eventName, fn); + wrap = EventManager.createListenerWrap(dom, eventName, bind.fn, scope, options); + + if (dom.attachEvent) { + dom.attachEvent('on' + bind.eventName, wrap); + } else { + dom.addEventListener(bind.eventName, wrap, options.capture || false); + } + + if (dom == doc && eventName == 'mousedown') { + EventManager.stoppedMouseDownEvent.addListener(wrap); + } + + // add all required data into the event cache + EventManager.getEventListenerCache(element.dom ? element : dom, eventName).push({ + fn: fn, + wrap: wrap, + scope: scope + }); + }, + + /** + * Removes an event handler from an element. The shorthand version {@link #un} is equivalent. Typically + * you will use {@link Ext.Element#removeListener} directly on an Element in favor of calling this version. + * @param {String/HTMLElement} el The id or html element from which to remove the listener. + * @param {String} eventName The name of the event. + * @param {Function} fn The handler function to remove. 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) { + // handle our listener config object syntax + if (typeof eventName !== 'string') { + EventManager.prepareListenerConfig(element, eventName, true); + return; + } + + var dom = Ext.getDom(element), + el = element.dom ? element : Ext.get(dom), + cache = EventManager.getEventListenerCache(el, eventName), + bindName = EventManager.normalizeEvent(eventName).eventName, + i = cache.length, j, + listener, wrap, tasks; + + + while (i--) { + listener = cache[i]; + + if (listener && (!fn || listener.fn == fn) && (!scope || listener.scope === scope)) { + wrap = listener.wrap; + + // clear buffered calls + if (wrap.task) { + clearTimeout(wrap.task); + delete wrap.task; + } + + // clear delayed calls + j = wrap.tasks && wrap.tasks.length; + if (j) { + while (j--) { + clearTimeout(wrap.tasks[j]); + } + delete wrap.tasks; + } + + if (dom.detachEvent) { + dom.detachEvent('on' + bindName, wrap); + } else { + dom.removeEventListener(bindName, wrap, false); + } + + if (wrap && dom == doc && eventName == 'mousedown') { + EventManager.stoppedMouseDownEvent.removeListener(wrap); + } + + // remove listener from cache + Ext.Array.erase(cache, i, 1); + } + } + }, + + /** + * 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(element) { + var el = element.dom ? element : Ext.get(element), + cache, events, eventName; + + if (!el) { + return; + } + cache = (el.$cache || el.getCache()); + events = cache.events; + + for (eventName in events) { + if (events.hasOwnProperty(eventName)) { + EventManager.removeListener(el, eventName); + } + } + cache.events = {}; + }, + + /** + * Recursively removes all previous added listeners from an element and its children. Typically you will use {@link Ext.Element#purgeAllListeners} + * 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. + * @param {String} eventName (optional) The name of the event. + */ + purgeElement : function(element, eventName) { + var dom = Ext.getDom(element), + i = 0, len; + + if (eventName) { + EventManager.removeListener(element, eventName); + } + else { + EventManager.removeAll(element); + } + + if (dom && dom.childNodes) { + for (len = element.childNodes.length; i < len; i++) { + EventManager.purgeElement(element.childNodes[i], eventName); + } + } + }, + + /** + * Create the wrapper function for the event + * @private + * @param {HTMLElement} dom The dom element + * @param {String} ename The event name + * @param {Function} fn The function to execute + * @param {Object} scope The scope to execute callback in + * @param {Object} options The options + * @return {Function} the wrapper function + */ + createListenerWrap : function(dom, ename, fn, scope, options) { + options = options || {}; + + var f, gen, escapeRx = /\\/g, wrap = function(e, args) { + // Compile the implementation upon first firing + if (!gen) { + f = ['if(!' + Ext.name + ') {return;}']; + + if(options.buffer || options.delay || options.freezeEvent) { + f.push('e = new X.EventObjectImpl(e, ' + (options.freezeEvent ? 'true' : 'false' ) + ');'); + } else { + f.push('e = X.EventObject.setEvent(e);'); + } + + if (options.delegate) { + // double up '\' characters so escape sequences survive the + // string-literal translation + f.push('var t = e.getTarget("' + (options.delegate + '').replace(escapeRx, '\\\\') + '", this);'); + f.push('if(!t) {return;}'); + } else { + f.push('var t = e.target;'); + } + + if (options.target) { + f.push('if(e.target !== options.target) {return;}'); + } + + if(options.stopEvent) { + f.push('e.stopEvent();'); + } else { + if(options.preventDefault) { + f.push('e.preventDefault();'); + } + if(options.stopPropagation) { + f.push('e.stopPropagation();'); + } + } + + if(options.normalized === false) { + f.push('e = e.browserEvent;'); + } + + if(options.buffer) { + f.push('(wrap.task && clearTimeout(wrap.task));'); + f.push('wrap.task = setTimeout(function() {'); + } + + if(options.delay) { + f.push('wrap.tasks = wrap.tasks || [];'); + f.push('wrap.tasks.push(setTimeout(function() {'); + } + + // finally call the actual handler fn + f.push('fn.call(scope || dom, e, t, options);'); + + if(options.single) { + f.push('evtMgr.removeListener(dom, ename, fn, scope);'); + } + + // Fire the global idle event for all events except mousemove which is too common, and + // fires too frequently and fast to be use in tiggering onIdle processing. + if (ename !== 'mousemove') { + f.push('if (evtMgr.idleEvent.listeners.length) {'); + f.push('evtMgr.idleEvent.fire();'); + f.push('}'); + } + + if(options.delay) { + f.push('}, ' + options.delay + '));'); + } + + if(options.buffer) { + f.push('}, ' + options.buffer + ');'); + } + + gen = Ext.cacheableFunctionFactory('e', 'options', 'fn', 'scope', 'ename', 'dom', 'wrap', 'args', 'X', 'evtMgr', f.join('\n')); + } + + gen.call(dom, e, options, fn, scope, ename, dom, wrap, args, Ext, EventManager); + }; + return wrap; + }, + + /** + * Get the event cache for a particular element for a particular event + * @private + * @param {HTMLElement} element The element + * @param {Object} eventName The event name + * @return {Array} The events for the element + */ + getEventListenerCache : function(element, eventName) { + var elementCache, eventCache; + if (!element) { + return []; + } + + if (element.$cache) { + elementCache = element.$cache; + } else { + // getId will populate the cache for this element if it isn't already present + elementCache = Ext.cache[EventManager.getId(element)]; + } + eventCache = elementCache.events || (elementCache.events = {}); + + return eventCache[eventName] || (eventCache[eventName] = []); + }, + + // --------------------- utility methods --------------------- + mouseLeaveRe: /(mouseout|mouseleave)/, + mouseEnterRe: /(mouseover|mouseenter)/, + + /** + * Stop the event (preventDefault and stopPropagation) + * @param {Event} The event to stop + */ + stopEvent: function(event) { + EventManager.stopPropagation(event); + EventManager.preventDefault(event); + }, + + /** + * Cancels bubbling of the event. + * @param {Event} The event to stop bubbling. + */ + stopPropagation: function(event) { + event = event.browserEvent || event; + if (event.stopPropagation) { + event.stopPropagation(); + } else { + event.cancelBubble = true; + } + }, + + /** + * Prevents the browsers default handling of the event. + * @param {Event} The event to prevent the default + */ + preventDefault: function(event) { + event = event.browserEvent || event; + if (event.preventDefault) { + event.preventDefault(); + } else { + event.returnValue = false; + // Some keys events require setting the keyCode to -1 to be prevented + try { + // all ctrl + X and F1 -> F12 + if (event.ctrlKey || event.keyCode > 111 && event.keyCode < 124) { + event.keyCode = -1; + } + } catch (e) { + // see this outdated document http://support.microsoft.com/kb/934364/en-us for more info + } + } + }, + + /** + * Gets the related target from the event. + * @param {Object} event The event + * @return {HTMLElement} The related target. + */ + getRelatedTarget: function(event) { + event = event.browserEvent || event; + var target = event.relatedTarget; + if (!target) { + if (EventManager.mouseLeaveRe.test(event.type)) { + target = event.toElement; + } else if (EventManager.mouseEnterRe.test(event.type)) { + target = event.fromElement; + } + } + return EventManager.resolveTextNode(target); + }, + + /** + * Gets the x coordinate from the event + * @param {Object} event The event + * @return {Number} The x coordinate + */ + getPageX: function(event) { + return EventManager.getPageXY(event)[0]; + }, + + /** + * Gets the y coordinate from the event + * @param {Object} event The event + * @return {Number} The y coordinate + */ + getPageY: function(event) { + return EventManager.getPageXY(event)[1]; + }, + + /** + * Gets the x & y coordinate from the event + * @param {Object} event The event + * @return {Number[]} The x/y coordinate + */ + getPageXY: function(event) { + event = event.browserEvent || event; + var x = event.pageX, + y = event.pageY, + docEl = doc.documentElement, + body = doc.body; + + // pageX/pageY not available (undefined, not null), use clientX/clientY instead + if (!x && x !== 0) { + x = event.clientX + (docEl && docEl.scrollLeft || body && body.scrollLeft || 0) - (docEl && docEl.clientLeft || body && body.clientLeft || 0); + y = event.clientY + (docEl && docEl.scrollTop || body && body.scrollTop || 0) - (docEl && docEl.clientTop || body && body.clientTop || 0); + } + return [x, y]; + }, + + /** + * Gets the target of the event. + * @param {Object} event The event + * @return {HTMLElement} target + */ + getTarget: function(event) { + event = event.browserEvent || event; + return EventManager.resolveTextNode(event.target || event.srcElement); + }, + + // technically no need to browser sniff this, however it makes + // no sense to check this every time, for every event, whether + // the string is equal. + /** + * Resolve any text nodes accounting for browser differences. + * @private + * @param {HTMLElement} node The node + * @return {HTMLElement} The resolved node + */ + resolveTextNode: Ext.isGecko ? + function(node) { + if (!node) { + return; + } + // work around firefox bug, https://bugzilla.mozilla.org/show_bug.cgi?id=101197 + var s = HTMLElement.prototype.toString.call(node); + if (s == '[xpconnect wrapped native prototype]' || s == '[object XULElement]') { + return; + } + return node.nodeType == 3 ? node.parentNode: node; + }: function(node) { + return node && node.nodeType == 3 ? node.parentNode: node; + }, + + // --------------------- custom event binding --------------------- + + // Keep track of the current width/height + curWidth: 0, + curHeight: 0, + + /** + * Adds a listener to be notified when the browser window is resized and provides resize event buffering (100 milliseconds), + * passes new viewport width and height to handlers. + * @param {Function} fn The handler function the window resize event invokes. + * @param {Object} scope The scope (this reference) in which the handler function executes. Defaults to the browser window. + * @param {Boolean} options Options object as passed to {@link Ext.Element#addListener} + */ + onWindowResize: function(fn, scope, options) { + var resize = EventManager.resizeEvent; + + if (!resize) { + EventManager.resizeEvent = resize = new Ext.util.Event(); + EventManager.on(win, 'resize', EventManager.fireResize, null, {buffer: 100}); + } + resize.addListener(fn, scope, options); + }, + + /** + * Fire the resize event. + * @private + */ + fireResize: function() { + var w = Ext.Element.getViewWidth(), + h = Ext.Element.getViewHeight(); + + //whacky problem in IE where the resize event will sometimes fire even though the w/h are the same. + if (EventManager.curHeight != h || EventManager.curWidth != w) { + EventManager.curHeight = h; + EventManager.curWidth = w; + EventManager.resizeEvent.fire(w, h); + } + }, + + /** + * 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) { + var resize = EventManager.resizeEvent; + if (resize) { + resize.removeListener(fn, scope); + } + }, + + /** + * Adds a listener to be notified when the browser window is unloaded. + * @param {Function} fn The handler function the window unload event invokes. + * @param {Object} scope The scope (this reference) in which the handler function executes. Defaults to the browser window. + * @param {Boolean} options Options object as passed to {@link Ext.Element#addListener} + */ + onWindowUnload: function(fn, scope, options) { + var unload = EventManager.unloadEvent; + + if (!unload) { + EventManager.unloadEvent = unload = new Ext.util.Event(); + EventManager.addListener(win, 'unload', EventManager.fireUnload); + } + if (fn) { + unload.addListener(fn, scope, options); + } + }, + + /** + * Fires the unload event for items bound with onWindowUnload + * @private + */ + fireUnload: function() { + // wrap in a try catch, could have some problems during unload + try { + // relinquish references. + doc = win = undefined; + + var gridviews, i, ln, + el, cache; + + EventManager.unloadEvent.fire(); + // Work around FF3 remembering the last scroll position when refreshing the grid and then losing grid view + if (Ext.isGecko3) { + gridviews = Ext.ComponentQuery.query('gridview'); + i = 0; + ln = gridviews.length; + for (; i < ln; i++) { + gridviews[i].scrollToTop(); + } + } + // Purge all elements in the cache + cache = Ext.cache; + + for (el in cache) { + if (cache.hasOwnProperty(el)) { + EventManager.removeAll(el); + } + } + } catch(e) { + } + }, + + /** + * Removes the passed window unload listener. + * @param {Function} fn The method the event invokes + * @param {Object} scope The scope of handler + */ + removeUnloadListener: function(fn, scope) { + var unload = EventManager.unloadEvent; + if (unload) { + unload.removeListener(fn, scope); + } + }, + + /** + * 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) + * @private + */ + useKeyDown: Ext.isWebKit ? + parseInt(navigator.userAgent.match(/AppleWebKit\/(\d+)/)[1], 10) >= 525 : + !((Ext.isGecko && !Ext.isWindows) || Ext.isOpera), + + /** + * Indicates which event to use for getting key presses. + * @return {String} The appropriate event name. + */ + getKeyEvent: function() { + return EventManager.useKeyDown ? 'keydown' : 'keypress'; + } + }); + + // route "< ie9-Standards" to a legacy IE onReady implementation + if(!('addEventListener' in document) && document.attachEvent) { + Ext.apply( EventManager, { + /* Customized implementation for Legacy IE. The default implementation is configured for use + * with all other 'standards compliant' agents. + * References: http://javascript.nwbox.com/IEContentLoaded/ + * licensed courtesy of http://developer.yahoo.com/yui/license.html + */ + + /** + * This strategy has minimal benefits for Sencha solutions that build themselves (ie. minimal initial page markup). + * However, progressively-enhanced pages (with image content and/or embedded frames) will benefit the most from it. + * Browser timer resolution is too poor to ensure a doScroll check more than once on a page loaded with minimal + * assets (the readystatechange event 'complete' usually beats the doScroll timer on a 'lightly-loaded' initial document). + */ + pollScroll : function() { + var scrollable = true; + + try { + document.documentElement.doScroll('left'); + } catch(e) { + scrollable = false; + } + + if (scrollable) { + EventManager.onReadyEvent({ + type:'doScroll' + }); + } else { + /* + * minimize thrashing -- + * adjusted for setTimeout's close-to-minimums (not too low), + * as this method SHOULD always be called once initially + */ + EventManager.scrollTimeout = setTimeout(EventManager.pollScroll, 20); + } + + return scrollable; + }, + + /** + * Timer for doScroll polling + * @private + */ + scrollTimeout: null, + + /* @private + */ + readyStatesRe : /complete/i, + + /* @private + */ + checkReadyState: function() { + var state = document.readyState; + + if (EventManager.readyStatesRe.test(state)) { + EventManager.onReadyEvent({ + type: state + }); + } + }, + + bindReadyEvent: function() { + var topContext = true; + + if (EventManager.hasBoundOnReady) { + return; + } + + //are we in an IFRAME? (doScroll ineffective here) + try { + topContext = !window.frameElement; + } catch(e) { + } + + if (!topContext || !doc.documentElement.doScroll) { + EventManager.pollScroll = Ext.emptyFn; //then noop this test altogether + } + + // starts doScroll polling if necessary + if (EventManager.pollScroll() === true) { + return; + } + + // Core is loaded AFTER initial document write/load ? + if (doc.readyState == 'complete' ) { + EventManager.onReadyEvent({type: 'already ' + (doc.readyState || 'body') }); + } else { + doc.attachEvent('onreadystatechange', EventManager.checkReadyState); + window.attachEvent('onload', EventManager.onReadyEvent); + EventManager.hasBoundOnReady = true; + } + }, + + onReadyEvent : function(e) { + if (e && e.type) { + EventManager.onReadyChain.push(e.type); + } + + if (EventManager.hasBoundOnReady) { + document.detachEvent('onreadystatechange', EventManager.checkReadyState); + window.detachEvent('onload', EventManager.onReadyEvent); + } + + if (Ext.isNumber(EventManager.scrollTimeout)) { + clearTimeout(EventManager.scrollTimeout); + delete EventManager.scrollTimeout; + } + + if (!Ext.isReady) { + EventManager.fireDocReady(); + } + }, + + //diags: a list of event types passed to onReadyEvent (in chron order) + onReadyChain : [] + }); + } + + + /** + * Alias for {@link Ext.Loader#onReady Ext.Loader.onReady} with withDomReady set to true + * @member Ext + * @method onReady + */ + Ext.onReady = function(fn, scope, options) { + Ext.Loader.onReady(fn, scope, true, options); + }; + + /** + * Alias for {@link Ext.EventManager#onDocumentReady Ext.EventManager.onDocumentReady} + * @member Ext + * @method onDocumentReady + */ + Ext.onDocumentReady = EventManager.onDocumentReady; + + /** + * Alias for {@link Ext.EventManager#addListener Ext.EventManager.addListener} + * @member Ext.EventManager + * @method on + */ + EventManager.on = EventManager.addListener; + + /** + * Alias for {@link Ext.EventManager#removeListener Ext.EventManager.removeListener} + * @member Ext.EventManager + * @method un + */ + EventManager.un = EventManager.removeListener; + + Ext.onReady(initExtCss); +}; + +/** + * @class Ext.EventObject + +Just as {@link Ext.Element} wraps around a native DOM node, Ext.EventObject +wraps the browser's native event-object normalizing cross-browser differences, +such as which mouse button is clicked, keys pressed, mechanisms to stop +event-propagation along with a method to prevent default actions from taking place. + +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 + * @markdown + */ +Ext.define('Ext.EventObjectImpl', { + uses: ['Ext.util.Point'], + + /** 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, + /** 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, + /** Key constant @type Number */ + PAGE_DOWN: 34, + /** 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, + /** + * The mouse wheel delta scaling factor. This value depends on browser version and OS and + * attempts to produce a similar scrolling experience across all platforms and browsers. + * + * To change this value: + * + * Ext.EventObjectImpl.prototype.WHEEL_SCALE = 72; + * + * @type Number + * @markdown + */ + WHEEL_SCALE: (function () { + var scale; + + if (Ext.isGecko) { + // Firefox uses 3 on all platforms + scale = 3; + } else if (Ext.isMac) { + // Continuous scrolling devices have momentum and produce much more scroll than + // discrete devices on the same OS and browser. To make things exciting, Safari + // (and not Chrome) changed from small values to 120 (like IE). + + if (Ext.isSafari && Ext.webKitVersion >= 532.0) { + // Safari changed the scrolling factor to match IE (for details see + // https://bugs.webkit.org/show_bug.cgi?id=24368). The WebKit version where this + // change was introduced was 532.0 + // Detailed discussion: + // https://bugs.webkit.org/show_bug.cgi?id=29601 + // http://trac.webkit.org/browser/trunk/WebKit/chromium/src/mac/WebInputEventFactory.mm#L1063 + scale = 120; + } else { + // MS optical wheel mouse produces multiples of 12 which is close enough + // to help tame the speed of the continuous mice... + scale = 12; + } + + // Momentum scrolling produces very fast scrolling, so increase the scale factor + // to help produce similar results cross platform. This could be even larger and + // it would help those mice, but other mice would become almost unusable as a + // result (since we cannot tell which device type is in use). + scale *= 3; + } else { + // IE, Opera and other Windows browsers use 120. + scale = 120; + } + + return scale; + }()), + + /** + * Simple click regex + * @private + */ + clickRe: /(dbl)?click/, + // 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, don't see any way to feature detect this. + btnMap: Ext.isIE ? { + 1: 0, + 4: 1, + 2: 2 + } : { + 0: 0, + 1: 1, + 2: 2 + }, + + /** + * @property {Boolean} ctrlKey + * True if the control key was down during the event. + * In Mac this will also be true when meta key was down. + */ + /** + * @property {Boolean} altKey + * True if the alt key was down during the event. + */ + /** + * @property {Boolean} shiftKey + * True if the shift key was down during the event. + */ + + constructor: function(event, freezeEvent){ + if (event) { + this.setEvent(event.browserEvent || event, freezeEvent); + } + }, + + setEvent: function(event, freezeEvent){ + var me = this, button, options; + + if (event == me || (event && event.browserEvent)) { // already wrapped + return event; + } + me.browserEvent = event; + if (event) { + // normalize buttons + button = event.button ? me.btnMap[event.button] : (event.which ? event.which - 1 : -1); + if (me.clickRe.test(event.type) && button == -1) { + button = 0; + } + options = { + type: event.type, + button: button, + shiftKey: event.shiftKey, + // mac metaKey behaves like ctrlKey + ctrlKey: event.ctrlKey || event.metaKey || false, + altKey: event.altKey, + // in getKey these will be normalized for the mac + keyCode: event.keyCode, + charCode: event.charCode, + // cache the targets for the delayed and or buffered events + target: Ext.EventManager.getTarget(event), + relatedTarget: Ext.EventManager.getRelatedTarget(event), + currentTarget: event.currentTarget, + xy: (freezeEvent ? me.getXY() : null) + }; + } else { + options = { + button: -1, + shiftKey: false, + ctrlKey: false, + altKey: false, + keyCode: 0, + charCode: 0, + target: null, + xy: [0, 0] + }; + } + Ext.apply(me, options); + return me; + }, + + /** + * Stop the event (preventDefault and stopPropagation) + */ + stopEvent: function(){ + this.stopPropagation(); + this.preventDefault(); + }, + + /** + * Prevents the browsers default handling of the event. + */ + preventDefault: function(){ + if (this.browserEvent) { + Ext.EventManager.preventDefault(this.browserEvent); + } + }, + + /** + * Cancels bubbling of the event. + */ + stopPropagation: function(){ + var browserEvent = this.browserEvent; + + if (browserEvent) { + if (browserEvent.type == 'mousedown') { + Ext.EventManager.stoppedMouseDownEvent.fire(this); + } + Ext.EventManager.stopPropagation(browserEvent); + } + }, + + /** + * Gets the character code for the event. + * @return {Number} + */ + getCharCode: function(){ + return this.charCode || this.keyCode; + }, + + /** + * Returns a normalized keyCode for the event. + * @return {Number} The key code + */ + getKey: function(){ + return this.normalizeKey(this.keyCode || this.charCode); + }, + + /** + * Normalize key codes across browsers + * @private + * @param {Number} key The key code + * @return {Number} The normalized code + */ + normalizeKey: function(key){ + // can't feature detect this + return Ext.isWebKit ? (this.safariKeys[key] || key) : key; + }, + + /** + * Gets the x coordinate of the event. + * @return {Number} + * @deprecated 4.0 Replaced by {@link #getX} + */ + getPageX: function(){ + return this.getX(); + }, + + /** + * Gets the y coordinate of the event. + * @return {Number} + * @deprecated 4.0 Replaced by {@link #getY} + */ + getPageY: function(){ + return this.getY(); + }, + + /** + * Gets the x coordinate of the event. + * @return {Number} + */ + getX: function() { + return this.getXY()[0]; + }, + + /** + * Gets the y coordinate of the event. + * @return {Number} + */ + getY: function() { + return this.getXY()[1]; + }, + + /** + * Gets the page coordinates of the event. + * @return {Number[]} The xy values like [x, y] + */ + getXY: function() { + if (!this.xy) { + // same for XY + this.xy = Ext.EventManager.getPageXY(this.browserEvent); + } + return this.xy; + }, + + /** + * Gets the target for the event. + * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target + * @param {Number/HTMLElement} 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){ + if (selector) { + return Ext.fly(this.target).findParent(selector, maxDepth, returnEl); + } + return returnEl ? Ext.get(this.target) : this.target; + }, + + /** + * Gets the related target. + * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target + * @param {Number/HTMLElement} 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} + */ + getRelatedTarget : function(selector, maxDepth, returnEl){ + if (selector) { + return Ext.fly(this.relatedTarget).findParent(selector, maxDepth, returnEl); + } + return returnEl ? Ext.get(this.relatedTarget) : this.relatedTarget; + }, + + /** + * Correctly scales a given wheel delta. + * @param {Number} delta The delta value. + */ + correctWheelDelta : function (delta) { + var scale = this.WHEEL_SCALE, + ret = Math.round(delta / scale); + + if (!ret && delta) { + ret = (delta < 0) ? -1 : 1; // don't allow non-zero deltas to go to zero! + } + + return ret; + }, + + /** + * Returns the mouse wheel deltas for this event. + * @return {Object} An object with "x" and "y" properties holding the mouse wheel deltas. + */ + getWheelDeltas : function () { + var me = this, + event = me.browserEvent, + dx = 0, dy = 0; // the deltas + + if (Ext.isDefined(event.wheelDeltaX)) { // WebKit has both dimensions + dx = event.wheelDeltaX; + dy = event.wheelDeltaY; + } else if (event.wheelDelta) { // old WebKit and IE + dy = event.wheelDelta; + } else if (event.detail) { // Gecko + dy = -event.detail; // gecko is backwards + + // Gecko sometimes returns really big values if the user changes settings to + // scroll a whole page per scroll + if (dy > 100) { + dy = 3; + } else if (dy < -100) { + dy = -3; + } + + // Firefox 3.1 adds an axis field to the event to indicate direction of + // scroll. See https://developer.mozilla.org/en/Gecko-Specific_DOM_Events + if (Ext.isDefined(event.axis) && event.axis === event.HORIZONTAL_AXIS) { + dx = dy; + dy = 0; + } + } + + return { + x: me.correctWheelDelta(dx), + y: me.correctWheelDelta(dy) + }; + }, + + /** + * Normalizes mouse wheel y-delta across browsers. To get x-delta information, use + * {@link #getWheelDeltas} instead. + * @return {Number} The mouse wheel y-delta + */ + getWheelDelta : function(){ + var deltas = this.getWheelDeltas(); + + return deltas.y; + }, + + /** + * 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!');
    +    }
    +});
    +
    +// 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!');
    +    }
    +});
    +
    + * @param {String/HTMLElement/Ext.Element} 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 = related ? this.getRelatedTarget() : this.getTarget(), + result; + + if (t) { + result = Ext.fly(el).contains(t); + if (!result && allowEl) { + result = t == Ext.getDom(el); + } + return result; + } + } + return false; + }, + + /** + * Checks if the key pressed was a "navigation" key + * @return {Boolean} True if the press is a navigation keypress + */ + 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; + }, + + /** + * Checks if the key pressed was a "special" key + * @return {Boolean} True if the press is a special keypress + */ + isSpecialKey : function(){ + var k = this.normalizeKey(this.keyCode); + return (this.type == 'keypress' && this.ctrlKey) || + this.isNavKeyPress() || + (k == this.BACKSPACE) || // Backspace + (k >= 16 && k <= 20) || // Shift, Ctrl, Alt, Pause, Caps Lock + (k >= 44 && k <= 46); // Print Screen, Insert, Delete + }, + + /** + * Returns a point object that consists of the object coordinates. + * @return {Ext.util.Point} point + */ + getPoint : function(){ + var xy = this.getXY(); + return new Ext.util.Point(xy[0], 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 || this.metaKey; + }, + + /** + * Injects a DOM event using the data in this object and (optionally) a new target. + * This is a low-level technique and not likely to be used by application code. The + * currently supported event types are: + *

    HTMLEvents

    + *
      + *
    • load
    • + *
    • unload
    • + *
    • select
    • + *
    • change
    • + *
    • submit
    • + *
    • reset
    • + *
    • resize
    • + *
    • scroll
    • + *
    + *

    MouseEvents

    + *
      + *
    • click
    • + *
    • dblclick
    • + *
    • mousedown
    • + *
    • mouseup
    • + *
    • mouseover
    • + *
    • mousemove
    • + *
    • mouseout
    • + *
    + *

    UIEvents

    + *
      + *
    • focusin
    • + *
    • focusout
    • + *
    • activate
    • + *
    • focus
    • + *
    • blur
    • + *
    + * @param {Ext.Element/HTMLElement} target (optional) If specified, the target for the event. This + * is likely to be used when relaying a DOM event. If not specified, {@link #getTarget} + * is used to determine the target. + */ + injectEvent: (function () { + var API, + dispatchers = {}, // keyed by event type (e.g., 'mousedown') + crazyIEButtons; + + // Good reference: http://developer.yahoo.com/yui/docs/UserAction.js.html + + // IE9 has createEvent, but this code causes major problems with htmleditor (it + // blocks all mouse events and maybe more). TODO + + if (!Ext.isIE && document.createEvent) { // if (DOM compliant) + API = { + createHtmlEvent: function (doc, type, bubbles, cancelable) { + var event = doc.createEvent('HTMLEvents'); + + event.initEvent(type, bubbles, cancelable); + return event; + }, + + createMouseEvent: function (doc, type, bubbles, cancelable, detail, + clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, + button, relatedTarget) { + var event = doc.createEvent('MouseEvents'), + view = doc.defaultView || window; + + if (event.initMouseEvent) { + event.initMouseEvent(type, bubbles, cancelable, view, detail, + clientX, clientY, clientX, clientY, ctrlKey, altKey, + shiftKey, metaKey, button, relatedTarget); + } else { // old Safari + event = doc.createEvent('UIEvents'); + event.initEvent(type, bubbles, cancelable); + event.view = view; + event.detail = detail; + event.screenX = clientX; + event.screenY = clientY; + event.clientX = clientX; + event.clientY = clientY; + event.ctrlKey = ctrlKey; + event.altKey = altKey; + event.metaKey = metaKey; + event.shiftKey = shiftKey; + event.button = button; + event.relatedTarget = relatedTarget; + } + + return event; + }, + + createUIEvent: function (doc, type, bubbles, cancelable, detail) { + var event = doc.createEvent('UIEvents'), + view = doc.defaultView || window; + + event.initUIEvent(type, bubbles, cancelable, view, detail); + return event; + }, + + fireEvent: function (target, type, event) { + target.dispatchEvent(event); + }, + + fixTarget: function (target) { + // Safari3 doesn't have window.dispatchEvent() + if (target == window && !target.dispatchEvent) { + return document; + } + + return target; + } + }; + } else if (document.createEventObject) { // else if (IE) + crazyIEButtons = { 0: 1, 1: 4, 2: 2 }; + + API = { + createHtmlEvent: function (doc, type, bubbles, cancelable) { + var event = doc.createEventObject(); + event.bubbles = bubbles; + event.cancelable = cancelable; + return event; + }, + + createMouseEvent: function (doc, type, bubbles, cancelable, detail, + clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, + button, relatedTarget) { + var event = doc.createEventObject(); + event.bubbles = bubbles; + event.cancelable = cancelable; + event.detail = detail; + event.screenX = clientX; + event.screenY = clientY; + event.clientX = clientX; + event.clientY = clientY; + event.ctrlKey = ctrlKey; + event.altKey = altKey; + event.shiftKey = shiftKey; + event.metaKey = metaKey; + event.button = crazyIEButtons[button] || button; + event.relatedTarget = relatedTarget; // cannot assign to/fromElement + return event; + }, + + createUIEvent: function (doc, type, bubbles, cancelable, detail) { + var event = doc.createEventObject(); + event.bubbles = bubbles; + event.cancelable = cancelable; + return event; + }, + + fireEvent: function (target, type, event) { + target.fireEvent('on' + type, event); + }, + + fixTarget: function (target) { + if (target == document) { + // IE6,IE7 thinks window==document and doesn't have window.fireEvent() + // IE6,IE7 cannot properly call document.fireEvent() + return document.documentElement; + } + + return target; + } + }; + } + + //---------------- + // HTMLEvents + + Ext.Object.each({ + load: [false, false], + unload: [false, false], + select: [true, false], + change: [true, false], + submit: [true, true], + reset: [true, false], + resize: [true, false], + scroll: [true, false] + }, + function (name, value) { + var bubbles = value[0], cancelable = value[1]; + dispatchers[name] = function (targetEl, srcEvent) { + var e = API.createHtmlEvent(name, bubbles, cancelable); + API.fireEvent(targetEl, name, e); + }; + }); + + //---------------- + // MouseEvents + + function createMouseEventDispatcher (type, detail) { + var cancelable = (type != 'mousemove'); + return function (targetEl, srcEvent) { + var xy = srcEvent.getXY(), + e = API.createMouseEvent(targetEl.ownerDocument, type, true, cancelable, + detail, xy[0], xy[1], srcEvent.ctrlKey, srcEvent.altKey, + srcEvent.shiftKey, srcEvent.metaKey, srcEvent.button, + srcEvent.relatedTarget); + API.fireEvent(targetEl, type, e); + }; + } + + Ext.each(['click', 'dblclick', 'mousedown', 'mouseup', 'mouseover', 'mousemove', 'mouseout'], + function (eventName) { + dispatchers[eventName] = createMouseEventDispatcher(eventName, 1); + }); + + //---------------- + // UIEvents + + Ext.Object.each({ + focusin: [true, false], + focusout: [true, false], + activate: [true, true], + focus: [false, false], + blur: [false, false] + }, + function (name, value) { + var bubbles = value[0], cancelable = value[1]; + dispatchers[name] = function (targetEl, srcEvent) { + var e = API.createUIEvent(targetEl.ownerDocument, name, bubbles, cancelable, 1); + API.fireEvent(targetEl, name, e); + }; + }); + + //--------- + if (!API) { + // not even sure what ancient browsers fall into this category... + + dispatchers = {}; // never mind all those we just built :P + + API = { + fixTarget: function (t) { + return t; + } + }; + } + + function cannotInject (target, srcEvent) { + // TODO log something + } + + return function (target) { + var me = this, + dispatcher = dispatchers[me.type] || cannotInject, + t = target ? (target.dom || target) : me.getTarget(); + + t = API.fixTarget(t); + dispatcher(t, me); + }; + }()) // call to produce method + +}, function() { + +Ext.EventObject = new Ext.EventObjectImpl(); + +}); + + +/** + * @class Ext.dom.AbstractQuery + * @private + */ +Ext.define('Ext.dom.AbstractQuery', { + /** + * Selects a group of elements. + * @param {String} selector The selector/xpath query (can be a comma separated list of selectors) + * @param {HTMLElement/String} [root] The start of the query (defaults to document). + * @return {HTMLElement[]} An Array of DOM elements which match the selector. If there are + * no matches, and empty Array is returned. + */ + select: function(q, root) { + var results = [], + nodes, + i, + j, + qlen, + nlen; + + root = root || document; + + if (typeof root == 'string') { + root = document.getElementById(root); + } + + q = q.split(","); + + for (i = 0,qlen = q.length; i < qlen; i++) { + if (typeof q[i] == 'string') { + + //support for node attribute selection + if (typeof q[i][0] == '@') { + nodes = root.getAttributeNode(q[i].substring(1)); + results.push(nodes); + } else { + nodes = root.querySelectorAll(q[i]); + + for (j = 0,nlen = nodes.length; j < nlen; j++) { + results.push(nodes[j]); + } + } + } + } + + return results; + }, + + /** + * Selects a single element. + * @param {String} selector The selector/xpath query + * @param {HTMLElement/String} [root] The start of the query (defaults to document). + * @return {HTMLElement} The DOM element which matched the selector. + */ + selectNode: function(q, root) { + return this.select(q, root)[0]; + }, + + /** + * 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, q) { + if (typeof el == "string") { + el = document.getElementById(el); + } + return this.select(q).indexOf(el) !== -1; + } + +}); + +/** + * @class Ext.dom.AbstractHelper + * @private + * Abstract base class for {@link Ext.dom.Helper}. + * @private + */ +Ext.define('Ext.dom.AbstractHelper', { + emptyTags : /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i, + confRe : /tag|children|cn|html|tpl|tplData$/i, + endRe : /end/i, + + attribXlat: { cls : 'class', htmlFor : 'for' }, + + closeTags: {}, + + decamelizeName : (function () { + var camelCaseRe = /([a-z])([A-Z])/g, + cache = {}; + + function decamel (match, p1, p2) { + return p1 + '-' + p2.toLowerCase(); + } + + return function (s) { + return cache[s] || (cache[s] = s.replace(camelCaseRe, decamel)); + }; + }()), + + generateMarkup: function(spec, buffer) { + var me = this, + attr, val, tag, i, closeTags; + + if (typeof spec == "string") { + buffer.push(spec); + } else if (Ext.isArray(spec)) { + for (i = 0; i < spec.length; i++) { + if (spec[i]) { + me.generateMarkup(spec[i], buffer); + } + } + } else { + tag = spec.tag || 'div'; + buffer.push('<', tag); + + for (attr in spec) { + if (spec.hasOwnProperty(attr)) { + val = spec[attr]; + if (!me.confRe.test(attr)) { + if (typeof val == "object") { + buffer.push(' ', attr, '="'); + me.generateStyles(val, buffer).push('"'); + } else { + buffer.push(' ', me.attribXlat[attr] || attr, '="', val, '"'); + } + } + } + } + + // Now either just close the tag or try to add children and close the tag. + if (me.emptyTags.test(tag)) { + buffer.push('/>'); + } else { + buffer.push('>'); + + // Apply the tpl html, and cn specifications + if ((val = spec.tpl)) { + val.applyOut(spec.tplData, buffer); + } + if ((val = spec.html)) { + buffer.push(val); + } + if ((val = spec.cn || spec.children)) { + me.generateMarkup(val, buffer); + } + + // we generate a lot of close tags, so cache them rather than push 3 parts + closeTags = me.closeTags; + buffer.push(closeTags[tag] || (closeTags[tag] = '')); + } + } + + return buffer; + }, + + /** + * Converts the styles from the given object to text. The styles are CSS style names + * with their associated value. + * + * The basic form of this method returns a string: + * + * var s = Ext.DomHelper.generateStyles({ + * backgroundColor: 'red' + * }); + * + * // s = 'background-color:red;' + * + * Alternatively, this method can append to an output array. + * + * var buf = []; + * + * ... + * + * Ext.DomHelper.generateStyles({ + * backgroundColor: 'red' + * }, buf); + * + * In this case, the style text is pushed on to the array and the array is returned. + * + * @param {Object} styles The object describing the styles. + * @param {String[]} [buffer] The output buffer. + * @return {String/String[]} If buffer is passed, it is returned. Otherwise the style + * string is returned. + */ + generateStyles: function (styles, buffer) { + var a = buffer || [], + name; + + for (name in styles) { + if (styles.hasOwnProperty(name)) { + a.push(this.decamelizeName(name), ':', styles[name], ';'); + } + } + + return buffer || a.join(''); + }, + + /** + * Returns the markup for the passed Element(s) config. + * @param {Object} spec The DOM object spec (and children) + * @return {String} + */ + markup: function(spec) { + if (typeof spec == "string") { + return spec; + } + + var buf = this.generateMarkup(spec, []); + return buf.join(''); + }, + + /** + * 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 (typeof styles == 'function') { + styles = styles.call(); + } + if (typeof styles == 'string'){ + styles = Ext.util.Format.trim(styles).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. + * + * For example take the following HTML: `
    Contents
    ` + * + * Using different `where` values inserts element to the following places: + * + * - beforeBegin: `
    Contents
    ` + * - afterBegin: `
    Contents
    ` + * - beforeEnd: `
    Contents
    ` + * - afterEnd: `
    Contents
    ` + * + * @param {HTMLElement/TextNode} 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']; + + range = el.ownerDocument.createRange(); + setStart = 'setStart' + (this.endRe.test(where) ? 'After' : 'Before'); + if (hash[where]) { + range[setStart](el); + frag = range.createContextualFragment(html); + el.parentNode.insertBefore(frag, where == 'beforebegin' ? el : el.nextSibling); + return el[(where == 'beforebegin' ? 'previous' : 'next') + 'Sibling']; + } + else { + rangeEl = (where == 'afterbegin' ? 'first' : 'last') + 'Child'; + if (el.firstChild) { + range[setStart](el[rangeEl]); + frag = range.createContextualFragment(html); + if (where == 'afterbegin') { + el.insertBefore(frag, el.firstChild); + } + else { + el.appendChild(frag); + } + } + else { + el.innerHTML = html; + } + return el[rangeEl]; + } + + throw 'Illegal insertion point -> "' + where + '"'; + }, + + /** + * Creates new DOM element(s) and inserts them before el. + * @param {String/HTMLElement/Ext.Element} el The context element + * @param {Object/String} o The DOM object spec (and children) or raw HTML blob + * @param {Boolean} [returnElement] true to return a Ext.Element + * @return {HTMLElement/Ext.Element} The new node + */ + insertBefore: function(el, o, returnElement) { + return this.doInsert(el, o, returnElement, 'beforebegin'); + }, + + /** + * Creates new DOM element(s) and inserts them after el. + * @param {String/HTMLElement/Ext.Element} el The context element + * @param {Object} o The DOM object spec (and children) + * @param {Boolean} [returnElement] true to return a Ext.Element + * @return {HTMLElement/Ext.Element} The new node + */ + insertAfter: function(el, o, returnElement) { + return this.doInsert(el, o, returnElement, 'afterend', 'nextSibling'); + }, + + /** + * Creates new DOM element(s) and inserts them as the first child of el. + * @param {String/HTMLElement/Ext.Element} el The context element + * @param {Object/String} o The DOM object spec (and children) or raw HTML blob + * @param {Boolean} [returnElement] true to return a Ext.Element + * @return {HTMLElement/Ext.Element} The new node + */ + insertFirst: function(el, o, returnElement) { + return this.doInsert(el, o, returnElement, 'afterbegin', 'firstChild'); + }, + + /** + * Creates new DOM element(s) and appends them to el. + * @param {String/HTMLElement/Ext.Element} el The context element + * @param {Object/String} o The DOM object spec (and children) or raw HTML blob + * @param {Boolean} [returnElement] true to return a Ext.Element + * @return {HTMLElement/Ext.Element} The new node + */ + append: function(el, o, returnElement) { + return this.doInsert(el, o, returnElement, 'beforeend', '', true); + }, + + /** + * Creates new DOM element(s) and overwrites the contents of el with them. + * @param {String/HTMLElement/Ext.Element} el The context element + * @param {Object/String} o The DOM object spec (and children) or raw HTML blob + * @param {Boolean} [returnElement] true to return a Ext.Element + * @return {HTMLElement/Ext.Element} The new node + */ + overwrite: function(el, o, returnElement) { + el = Ext.getDom(el); + el.innerHTML = this.markup(o); + return returnElement ? Ext.get(el.firstChild) : el.firstChild; + }, + + doInsert: function(el, o, returnElement, pos, sibling, append) { + var newNode = this.insertHtml(pos, Ext.getDom(el), this.markup(o)); + return returnElement ? Ext.get(newNode, true) : newNode; + } + +}); + +/** + * @class Ext.dom.AbstractElement + * @extend Ext.Base + * @private + */ +(function() { + +var document = window.document, + trimRe = /^\s+|\s+$/g, + whitespaceRe = /\s/; + +if (!Ext.cache){ + Ext.cache = {}; +} + +Ext.define('Ext.dom.AbstractElement', { + + inheritableStatics: { + + /** + * Retrieves Ext.dom.Element objects. {@link Ext#get} is alias for {@link Ext.dom.Element#get}. + * + * **This method does not retrieve {@link Ext.Component Component}s.** This method retrieves Ext.dom.Element + * objects which encapsulate DOM elements. To retrieve a Component by its ID, use {@link Ext.ComponentManager#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 {String/HTMLElement/Ext.Element} el The id of the node, a DOM Node or an existing Element. + * @return {Ext.dom.Element} The Element object (or null if no matching element was found) + * @static + * @inheritable + */ + get: function(el) { + var me = this, + El = Ext.dom.Element, + cache, + extEl, + dom, + id; + + if (!el) { + return null; + } + + if (typeof el == "string") { // element id + if (el == Ext.windowId) { + return El.get(window); + } else if (el == Ext.documentId) { + return El.get(document); + } + + cache = Ext.cache[el]; + // This code is here to catch the case where we've got a reference to a document of an iframe + // It getElementById will fail because it's not part of the document, so if we're skipping + // GC it means it's a window/document object that isn't the default window/document, which we have + // already handled above + if (cache && cache.skipGarbageCollection) { + extEl = cache.el; + return extEl; + } + + if (!(dom = document.getElementById(el))) { + return null; + } + + if (cache && cache.el) { + extEl = cache.el; + extEl.dom = dom; + } else { + // Force new element if there's a cache but no el attached + extEl = new El(dom, !!cache); + } + return extEl; + } else if (el.tagName) { // dom element + if (!(id = el.id)) { + id = Ext.id(el); + } + cache = Ext.cache[id]; + if (cache && cache.el) { + extEl = Ext.cache[id].el; + extEl.dom = el; + } else { + // Force new element if there's a cache but no el attached + extEl = new El(el, !!cache); + } + return extEl; + } else if (el instanceof me) { + if (el != me.docEl && el != me.winEl) { + // refresh dom element in case no longer valid, + // catch case where it hasn't been appended + el.dom = document.getElementById(el.id) || el.dom; + } + return el; + } else if (el.isComposite) { + return el; + } else if (Ext.isArray(el)) { + return me.select(el); + } else if (el === document) { + // create a bogus element object representing the document object + if (!me.docEl) { + me.docEl = Ext.Object.chain(El.prototype); + me.docEl.dom = document; + me.docEl.id = Ext.id(document); + me.addToCache(me.docEl); + } + return me.docEl; + } else if (el === window) { + if (!me.winEl) { + me.winEl = Ext.Object.chain(El.prototype); + me.winEl.dom = window; + me.winEl.id = Ext.id(window); + me.addToCache(me.winEl); + } + return me.winEl; + } + return null; + }, + + addToCache: function(el, id) { + if (el) { + Ext.addCacheEntry(id, el); + } + return el; + }, + + addMethods: function() { + this.override.apply(this, arguments); + }, + + /** + *

    Returns an array of unique class names based upon the input strings, or string arrays.

    + *

    The number of parameters is unlimited.

    + *

    Example

    +// Add x-invalid and x-mandatory classes, do not duplicate
    +myElement.dom.className = Ext.core.Element.mergeClsList(this.initialClasses, 'x-invalid x-mandatory');
    +
    + * @param {Mixed} clsList1 A string of class names, or an array of class names. + * @param {Mixed} clsList2 A string of class names, or an array of class names. + * @return {Array} An array of strings representing remaining unique, merged class names. If class names were added to the first list, the changed property will be true. + * @static + * @inheritable + */ + mergeClsList: function() { + var clsList, clsHash = {}, + i, length, j, listLength, clsName, result = [], + changed = false; + + for (i = 0, length = arguments.length; i < length; i++) { + clsList = arguments[i]; + if (Ext.isString(clsList)) { + clsList = clsList.replace(trimRe, '').split(whitespaceRe); + } + if (clsList) { + for (j = 0, listLength = clsList.length; j < listLength; j++) { + clsName = clsList[j]; + if (!clsHash[clsName]) { + if (i) { + changed = true; + } + clsHash[clsName] = true; + } + } + } + } + + for (clsName in clsHash) { + result.push(clsName); + } + result.changed = changed; + return result; + }, + + /** + *

    Returns an array of unique class names deom the first parameter with all class names + * from the second parameter removed.

    + *

    Example

    +// Remove x-invalid and x-mandatory classes if present.
    +myElement.dom.className = Ext.core.Element.removeCls(this.initialClasses, 'x-invalid x-mandatory');
    +
    + * @param {Mixed} existingClsList A string of class names, or an array of class names. + * @param {Mixed} removeClsList A string of class names, or an array of class names to remove from existingClsList. + * @return {Array} An array of strings representing remaining class names. If class names were removed, the changed property will be true. + * @static + * @inheritable + */ + removeCls: function(existingClsList, removeClsList) { + var clsHash = {}, + i, length, clsName, result = [], + changed = false; + + if (existingClsList) { + if (Ext.isString(existingClsList)) { + existingClsList = existingClsList.replace(trimRe, '').split(whitespaceRe); + } + for (i = 0, length = existingClsList.length; i < length; i++) { + clsHash[existingClsList[i]] = true; + } + } + if (removeClsList) { + if (Ext.isString(removeClsList)) { + removeClsList = removeClsList.split(whitespaceRe); + } + for (i = 0, length = removeClsList.length; i < length; i++) { + clsName = removeClsList[i]; + if (clsHash[clsName]) { + changed = true; + delete clsHash[clsName]; + } + } + } + for (clsName in clsHash) { + result.push(clsName); + } + result.changed = changed; + return result; + }, + + /** + * @property + * Visibility mode constant for use with {@link Ext.dom.Element#setVisibilityMode}. + * Use the CSS 'visibility' property to hide the element. + * + * Note that in this mode, {@link #isVisible} may return true for an element even though + * it actually has a parent element that is hidden. For this reason, and in most cases, + * using the {@link #OFFSETS} mode is a better choice. + * @static + * @inheritable + */ + VISIBILITY: 1, + + /** + * @property + * Visibility mode constant for use with {@link Ext.dom.Element#setVisibilityMode}. + * Use the CSS 'display' property to hide the element. + * @static + * @inheritable + */ + DISPLAY: 2, + + /** + * @property + * Visibility mode constant for use with {@link Ext.dom.Element#setVisibilityMode}. + * Use CSS absolute positioning and top/left offsets to hide the element. + * @static + * @inheritable + */ + OFFSETS: 3, + + /** + * @property + * Visibility mode constant for use with {@link Ext.dom.Element#setVisibilityMode}. + * Add or remove the {@link Ext.Layer#visibilityCls} class to hide the element. + * @static + * @inheritable + */ + ASCLASS: 4 + }, + + constructor: function(element, forceNew) { + var me = this, + dom = typeof element == 'string' + ? document.getElementById(element) + : element, + id; + + if (!dom) { + return null; + } + + id = dom.id; + if (!forceNew && id && Ext.cache[id]) { + // element object already exists + return Ext.cache[id].el; + } + + /** + * @property {HTMLElement} dom + * The DOM element + */ + me.dom = dom; + + /** + * @property {String} id + * The DOM element ID + */ + me.id = id || Ext.id(dom); + + me.self.addToCache(me); + }, + + /** + * 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=true] false to override the default setAttribute to use expandos. + * @return {Ext.dom.Element} this + */ + set: function(o, useSet) { + var el = this.dom, + attr, + value; + + for (attr in o) { + if (o.hasOwnProperty(attr)) { + value = o[attr]; + if (attr == 'style') { + this.applyStyles(value); + } + else if (attr == 'cls') { + el.className = value; + } + else if (useSet !== false) { + if (value === undefined) { + el.removeAttribute(attr); + } else { + el.setAttribute(attr, value); + } + } + else { + el[attr] = value; + } + } + } + return this; + }, + + /** + * @property {String} defaultUnit + * The default unit to append to CSS values where a unit isn't provided. + */ + 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); + }, + + /** + * 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; + }, + + /** + * Removes this element's dom reference. Note that event and cache removal is handled at {@link Ext#removeNode + * Ext.removeNode} + */ + remove: function() { + var me = this, + dom = me.dom; + + if (dom) { + Ext.removeNode(dom); + delete me.dom; + } + }, + + /** + * 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) { + if (!el) { + return false; + } + + var me = this, + dom = el.dom || el; + + // we need el-contains-itself logic here because isAncestor does not do that: + return (dom === me.dom) || Ext.dom.AbstractElement.isAncestor(me.dom, dom); + }, + + /** + * Returns the value of an attribute from the element's underlying DOM node. + * @param {String} name The attribute name + * @param {String} [namespace] The namespace in which to look for the attribute + * @return {String} The attribute value + */ + getAttribute: function(name, ns) { + var dom = this.dom; + return dom.getAttributeNS(ns, name) || dom.getAttribute(ns + ":" + name) || dom.getAttribute(name) || dom[name]; + }, + + /** + * Update the innerHTML of this element + * @param {String} html The new HTML + * @return {Ext.dom.Element} this + */ + update: function(html) { + if (this.dom) { + this.dom.innerHTML = html; + } + return this; + }, + + + /** + * Set the innerHTML of this element + * @param {String} html The new HTML + * @return {Ext.Element} this + */ + setHTML: function(html) { + if(this.dom) { + this.dom.innerHTML = html; + } + return this; + }, + + /** + * Returns the innerHTML of an Element or an empty string if the element's + * dom no longer exists. + */ + getHTML: function() { + return this.dom ? this.dom.innerHTML : ''; + }, + + /** + * 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() { + this.setVisible(false); + 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() { + this.setVisible(true); + return this; + }, + + /** + * 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, + statics = me.self, + mode = me.getVisibilityMode(), + prefix = Ext.baseCSSPrefix; + + switch (mode) { + case statics.VISIBILITY: + me.removeCls([prefix + 'hidden-display', prefix + 'hidden-offsets']); + me[visible ? 'removeCls' : 'addCls'](prefix + 'hidden-visibility'); + break; + + case statics.DISPLAY: + me.removeCls([prefix + 'hidden-visibility', prefix + 'hidden-offsets']); + me[visible ? 'removeCls' : 'addCls'](prefix + 'hidden-display'); + break; + + case statics.OFFSETS: + me.removeCls([prefix + 'hidden-visibility', prefix + 'hidden-display']); + me[visible ? 'removeCls' : 'addCls'](prefix + 'hidden-offsets'); + break; + } + + return me; + }, + + getVisibilityMode: function() { + // Only flyweights won't have a $cache object, by calling getCache the cache + // will be created for future accesses. As such, we're eliminating the method + // call since it's mostly redundant + var data = (this.$cache || this.getCache()).data, + visMode = data.visibilityMode; + + if (visMode === undefined) { + data.visibilityMode = visMode = this.self.DISPLAY; + } + + return visMode; + }, + + /** + * Use this to change the visibility mode between {@link #VISIBILITY}, {@link #DISPLAY}, {@link #OFFSETS} or {@link #ASCLASS}. + */ + setVisibilityMode: function(mode) { + (this.$cache || this.getCache()).data.visibilityMode = mode; + return this; + }, + + getCache: function() { + var me = this, + id = me.dom.id || Ext.id(me.dom); + + // Note that we do not assign an ID to the calling object here. + // An Ext.dom.Element will have one assigned at construction, and an Ext.dom.AbstractElement.Fly must not have one. + // We assign an ID to the DOM element if it does not have one. + me.$cache = Ext.cache[id] || Ext.addCacheEntry(id, null, me.dom); + + return me.$cache; + } + +}, function() { + var AbstractElement = this; + + Ext.getDetachedBody = function () { + var detachedEl = AbstractElement.detachedBodyEl; + + if (!detachedEl) { + detachedEl = document.createElement('div'); + AbstractElement.detachedBodyEl = detachedEl = new AbstractElement.Fly(detachedEl); + detachedEl.isDetachedBody = true; + } + + return detachedEl; + }; + + Ext.getElementById = function (id) { + var el = document.getElementById(id), + detachedBodyEl; + + if (!el && (detachedBodyEl = AbstractElement.detachedBodyEl)) { + el = detachedBodyEl.dom.querySelector('#' + Ext.escapeId(id)); + } + + return el; + }; + + /** + * @member Ext + * @method get + * @inheritdoc Ext.dom.Element#get + */ + Ext.get = function(el) { + return Ext.dom.Element.get(el); + }; + + this.addStatics({ + /** + * @class Ext.dom.AbstractElement.Fly + * @extends Ext.dom.AbstractElement + * + * A non-persistent wrapper for a DOM element which may be used to execute methods of {@link Ext.dom.Element} + * upon a DOM element without creating an instance of {@link Ext.dom.Element}. + * + * A **singleton** instance of this class is returned when you use {@link Ext#fly} + * + * Because it is a singleton, this Flyweight does not have an ID, and must be used and discarded in a single line. + * You should not keep and use the reference to this singleton over multiple lines because methods that you call + * may themselves make use of {@link Ext#fly} and may change the DOM element to which the instance refers. + */ + Fly: new Ext.Class({ + extend: AbstractElement, + + /** + * @property {Boolean} isFly + * This is `true` to identify Element flyweights + */ + isFly: true, + + constructor: function(dom) { + this.dom = dom; + }, + + /** + * @private + * Attach this fliyweight instance to the passed DOM element. + * + * Note that a flightweight does **not** have an ID, and does not acquire the ID of the DOM element. + */ + attach: function (dom) { + + // Attach to the passed DOM element. The same code as in Ext.Fly + this.dom = dom; + // Use cached data if there is existing cached data for the referenced DOM element, + // otherwise it will be created when needed by getCache. + this.$cache = dom.id ? Ext.cache[dom.id] : null; + return this; + } + }), + + _flyweights: {}, + + /** + * Gets the singleton {@link Ext.dom.AbstractElement.Fly flyweight} element, with the passed node as the active element. + * + * Because it is a singleton, this Flyweight does not have an ID, and must be used and discarded in a single line. + * You may not keep and use the reference to this singleton over multiple lines because methods that you call + * may themselves make use of {@link Ext#fly} and may change the DOM element to which the instance refers. + * + * {@link Ext#fly} is alias for {@link Ext.dom.AbstractElement#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 Ext.get} will be more appropriate to take advantage of the caching provided by the Ext.dom.Element + * class. + * + * @param {String/HTMLElement} dom The dom node or id + * @param {String} [named] Allows for creation of named reusable flyweights to prevent conflicts (e.g. + * internally Ext uses "_global") + * @return {Ext.dom.AbstractElement.Fly} The singleton flyweight object (or null if no matching element was found) + * @static + * @member Ext.dom.AbstractElement + */ + fly: function(dom, named) { + var fly = null, + _flyweights = AbstractElement._flyweights; + + named = named || '_global'; + + dom = Ext.getDom(dom); + + if (dom) { + fly = _flyweights[named] || (_flyweights[named] = new AbstractElement.Fly()); + + // Attach to the passed DOM element. + // This code performs the same function as Fly.attach, but inline it for efficiency + fly.dom = dom; + // Use cached data if there is existing cached data for the referenced DOM element, + // otherwise it will be created when needed by getCache. + fly.$cache = dom.id ? Ext.cache[dom.id] : null; + } + return fly; + } + }); + + /** + * @member Ext + * @method fly + * @inheritdoc Ext.dom.AbstractElement#fly + */ + Ext.fly = function() { + return AbstractElement.fly.apply(AbstractElement, arguments); + }; + + (function (proto) { + /** + * @method destroy + * @member Ext.dom.AbstractElement + * @inheritdoc Ext.dom.AbstractElement#remove + * Alias to {@link #remove}. + */ + proto.destroy = proto.remove; + + /** + * Returns a child element of this element given its `id`. + * @method getById + * @member Ext.dom.AbstractElement + * @param {String} id The id of the desired child element. + * @param {Boolean} [asDom=false] True to return the DOM element, false to return a + * wrapped Element object. + */ + if (document.querySelector) { + proto.getById = function (id, asDom) { + // for normal elements getElementById is the best solution, but if the el is + // not part of the document.body, we have to resort to querySelector + var dom = document.getElementById(id) || + this.dom.querySelector('#'+Ext.escapeId(id)); + return asDom ? dom : (dom ? Ext.get(dom) : null); + }; + } else { + proto.getById = function (id, asDom) { + var dom = document.getElementById(id); + return asDom ? dom : (dom ? Ext.get(dom) : null); + }; + } + }(this.prototype)); +}); + +}()); + +/** + * @class Ext.dom.AbstractElement + */ +Ext.dom.AbstractElement.addInheritableStatics({ + unitRe: /\d+(px|em|%|en|ex|pt|in|cm|mm|pc)$/i, + camelRe: /(-[a-z])/gi, + cssRe: /([a-z0-9\-]+)\s*:\s*([^;\s]+(?:\s*[^;\s]+)*);?/gi, + opacityRe: /alpha\(opacity=(.*)\)/i, + propertyCache: {}, + defaultUnit : "px", + 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'}, + /** + * Test if size has a unit, otherwise appends the passed unit string, or the default for this Element. + * @param size {Object} The size to set + * @param units {String} The units to append to a numeric size value + * @private + * @static + */ + addUnits: function(size, units) { + // Most common case first: Size is set to a number + if (typeof size == 'number') { + return size + (units || this.defaultUnit || 'px'); + } + + // Size set to a value which means "auto" + if (size === "" || size == "auto" || size === undefined || size === null) { + return size || ''; + } + + // Otherwise, warn if it's not a valid CSS measurement + if (!this.unitRe.test(size)) { + if (Ext.isDefined(Ext.global.console)) { + Ext.global.console.warn("Warning, size detected as NaN on Element.addUnits."); + } + return size || ''; + } + + return size; + }, + + /** + * @static + * @private + */ + isAncestor: function(p, c) { + var ret = false; + + p = Ext.getDom(p); + c = Ext.getDom(c); + if (p && c) { + if (p.contains) { + return p.contains(c); + } else if (p.compareDocumentPosition) { + return !!(p.compareDocumentPosition(c) & 16); + } else { + while ((c = c.parentNode)) { + ret = c == p || ret; + } + } + } + return ret; + }, + + /** + * Parses a number or string representing margin sizes into an object. Supports CSS-style margin declarations + * (e.g. 10, "10", "10 10", "10 10 10" and "10 10 10 10" are all valid options and would return the same result) + * @static + * @param {Number/String} box The encoded margins + * @return {Object} An object with margin sizes for top, right, bottom and left + */ + parseBox: function(box) { + if (typeof box != 'string') { + box = box.toString(); + } + var parts = box.split(' '), + ln = parts.length; + + if (ln == 1) { + parts[1] = parts[2] = parts[3] = parts[0]; + } + else if (ln == 2) { + parts[2] = parts[0]; + parts[3] = parts[1]; + } + else if (ln == 3) { + parts[3] = parts[1]; + } + + return { + top :parseFloat(parts[0]) || 0, + right :parseFloat(parts[1]) || 0, + bottom:parseFloat(parts[2]) || 0, + left :parseFloat(parts[3]) || 0 + }; + }, + + /** + * Parses a number or string representing margin sizes into an object. Supports CSS-style margin declarations + * (e.g. 10, "10", "10 10", "10 10 10" and "10 10 10 10" are all valid options and would return the same result) + * @static + * @param {Number/String} box The encoded margins + * @param {String} units The type of units to add + * @return {String} An string with unitized (px if units is not specified) metrics for top, right, bottom and left + */ + unitizeBox: function(box, units) { + var a = this.addUnits, + b = this.parseBox(box); + + return a(b.top, units) + ' ' + + a(b.right, units) + ' ' + + a(b.bottom, units) + ' ' + + a(b.left, units); + + }, + + // private + camelReplaceFn: function(m, a) { + return a.charAt(1).toUpperCase(); + }, + + /** + * Normalizes CSS property keys from dash delimited to camel case JavaScript Syntax. + * For example: + * + * - border-width -> borderWidth + * - padding-top -> paddingTop + * + * @static + * @param {String} prop The property to normalize + * @return {String} The normalized string + */ + normalize: function(prop) { + // TODO: Mobile optimization? + if (prop == 'float') { + prop = Ext.supports.Float ? 'cssFloat' : 'styleFloat'; + } + return this.propertyCache[prop] || (this.propertyCache[prop] = prop.replace(this.camelRe, this.camelReplaceFn)); + }, + + /** + * Retrieves the document height + * @static + * @return {Number} documentHeight + */ + getDocumentHeight: function() { + return Math.max(!Ext.isStrict ? document.body.scrollHeight : document.documentElement.scrollHeight, this.getViewportHeight()); + }, + + /** + * Retrieves the document width + * @static + * @return {Number} documentWidth + */ + getDocumentWidth: function() { + return Math.max(!Ext.isStrict ? document.body.scrollWidth : document.documentElement.scrollWidth, this.getViewportWidth()); + }, + + /** + * Retrieves the viewport height of the window. + * @static + * @return {Number} viewportHeight + */ + getViewportHeight: function(){ + return window.innerHeight; + }, + + /** + * Retrieves the viewport width of the window. + * @static + * @return {Number} viewportWidth + */ + getViewportWidth: function() { + return window.innerWidth; + }, + + /** + * Retrieves the viewport size of the window. + * @static + * @return {Object} object containing width and height properties + */ + getViewSize: function() { + return { + width: window.innerWidth, + height: window.innerHeight + }; + }, + + /** + * Retrieves the current orientation of the window. This is calculated by + * determing if the height is greater than the width. + * @static + * @return {String} Orientation of window: 'portrait' or 'landscape' + */ + getOrientation: function() { + if (Ext.supports.OrientationChange) { + return (window.orientation == 0) ? 'portrait' : 'landscape'; + } + + return (window.innerHeight > window.innerWidth) ? 'portrait' : 'landscape'; + }, + + /** + * Returns the top Element that is located at the passed coordinates + * @static + * @param {Number} x The x coordinate + * @param {Number} y The y coordinate + * @return {String} The found Element + */ + fromPoint: function(x, y) { + return Ext.get(document.elementFromPoint(x, y)); + }, + + /** + * Converts a CSS string into an object with a property for each style. + * + * The sample code below would return an object with 2 properties, one + * for background-color and one for color. + * + * var css = 'background-color: red;color: blue; '; + * console.log(Ext.dom.Element.parseStyles(css)); + * + * @static + * @param {String} styles A CSS string + * @return {Object} styles + */ + parseStyles: function(styles){ + var out = {}, + cssRe = this.cssRe, + matches; + + if (styles) { + // Since we're using the g flag on the regex, we need to set the lastIndex. + // This automatically happens on some implementations, but not others, see: + // http://stackoverflow.com/questions/2645273/javascript-regular-expression-literal-persists-between-function-calls + // http://blog.stevenlevithan.com/archives/fixing-javascript-regexp + cssRe.lastIndex = 0; + while ((matches = cssRe.exec(styles))) { + out[matches[1]] = matches[2]; + } + } + return out; + } +}); + +//TODO Need serious cleanups +(function(){ + var doc = document, + AbstractElement = Ext.dom.AbstractElement, + activeElement = null, + isCSS1 = doc.compatMode == "CSS1Compat", + flyInstance, + fly = function (el) { + if (!flyInstance) { + flyInstance = new AbstractElement.Fly(); + } + flyInstance.attach(el); + return flyInstance; + }; + + // If the browser does not support document.activeElement we need some assistance. + // This covers old Safari 3.2 (4.0 added activeElement along with just about all + // other browsers). We need this support to handle issues with old Safari. + if (!('activeElement' in doc) && doc.addEventListener) { + doc.addEventListener('focus', + function (ev) { + if (ev && ev.target) { + activeElement = (ev.target == doc) ? null : ev.target; + } + }, true); + } + + /* + * Helper function to create the function that will restore the selection. + */ + function makeSelectionRestoreFn (activeEl, start, end) { + return function () { + activeEl.selectionStart = start; + activeEl.selectionEnd = end; + }; + } + + AbstractElement.addInheritableStatics({ + /** + * Returns the active element in the DOM. If the browser supports activeElement + * on the document, this is returned. If not, the focus is tracked and the active + * element is maintained internally. + * @return {HTMLElement} The active (focused) element in the document. + */ + getActiveElement: function () { + return doc.activeElement || activeElement; + }, + + /** + * Creates a function to call to clean up problems with the work-around for the + * WebKit RightMargin bug. The work-around is to add "display: 'inline-block'" to + * the element before calling getComputedStyle and then to restore its original + * display value. The problem with this is that it corrupts the selection of an + * INPUT or TEXTAREA element (as in the "I-beam" goes away but ths focus remains). + * To cleanup after this, we need to capture the selection of any such element and + * then restore it after we have restored the display style. + * + * @param {Ext.dom.Element} target The top-most element being adjusted. + * @private + */ + getRightMarginFixCleaner: function (target) { + var supports = Ext.supports, + hasInputBug = supports.DisplayChangeInputSelectionBug, + hasTextAreaBug = supports.DisplayChangeTextAreaSelectionBug, + activeEl, + tag, + start, + end; + + if (hasInputBug || hasTextAreaBug) { + activeEl = doc.activeElement || activeElement; // save a call + tag = activeEl && activeEl.tagName; + + if ((hasTextAreaBug && tag == 'TEXTAREA') || + (hasInputBug && tag == 'INPUT' && activeEl.type == 'text')) { + if (Ext.dom.Element.isAncestor(target, activeEl)) { + start = activeEl.selectionStart; + end = activeEl.selectionEnd; + + if (Ext.isNumber(start) && Ext.isNumber(end)) { // to be safe... + // We don't create the raw closure here inline because that + // will be costly even if we don't want to return it (nested + // function decls and exprs are often instantiated on entry + // regardless of whether execution ever reaches them): + return makeSelectionRestoreFn(activeEl, start, end); + } + } + } + } + + return Ext.emptyFn; // avoid special cases, just return a nop + }, + + getViewWidth: function(full) { + return full ? Ext.dom.Element.getDocumentWidth() : Ext.dom.Element.getViewportWidth(); + }, + + getViewHeight: function(full) { + return full ? Ext.dom.Element.getDocumentHeight() : Ext.dom.Element.getViewportHeight(); + }, + + getDocumentHeight: function() { + return Math.max(!isCSS1 ? doc.body.scrollHeight : doc.documentElement.scrollHeight, Ext.dom.Element.getViewportHeight()); + }, + + getDocumentWidth: function() { + return Math.max(!isCSS1 ? doc.body.scrollWidth : doc.documentElement.scrollWidth, Ext.dom.Element.getViewportWidth()); + }, + + getViewportHeight: function(){ + return Ext.isIE ? + (Ext.isStrict ? doc.documentElement.clientHeight : doc.body.clientHeight) : + self.innerHeight; + }, + + getViewportWidth: function() { + return (!Ext.isStrict && !Ext.isOpera) ? doc.body.clientWidth : + Ext.isIE ? doc.documentElement.clientWidth : self.innerWidth; + }, + + getY: function(el) { + return Ext.dom.Element.getXY(el)[1]; + }, + + getX: function(el) { + return Ext.dom.Element.getXY(el)[0]; + }, + + getXY: function(el) { + var bd = doc.body, + docEl = doc.documentElement, + leftBorder = 0, + topBorder = 0, + ret = [0,0], + round = Math.round, + box, + scroll; + + el = Ext.getDom(el); + + if(el != doc && el != bd){ + // IE has the potential to throw when getBoundingClientRect called + // on element not attached to dom + if (Ext.isIE) { + try { + box = el.getBoundingClientRect(); + // In some versions of IE, the documentElement (HTML element) will have a 2px border that gets included, so subtract it off + topBorder = docEl.clientTop || bd.clientTop; + leftBorder = docEl.clientLeft || bd.clientLeft; + } catch (ex) { + box = { left: 0, top: 0 }; + } + } else { + box = el.getBoundingClientRect(); + } + + scroll = fly(document).getScroll(); + ret = [round(box.left + scroll.left - leftBorder), round(box.top + scroll.top - topBorder)]; + } + return ret; + }, + + setXY: function(el, xy) { + (el = Ext.fly(el, '_setXY')).position(); + + var pts = el.translatePoints(xy), + style = el.dom.style, + pos; + + for (pos in pts) { + if (!isNaN(pts[pos])) { + style[pos] = pts[pos] + "px"; + } + } + }, + + setX: function(el, x) { + Ext.dom.Element.setXY(el, [x, false]); + }, + + setY: function(el, y) { + Ext.dom.Element.setXY(el, [false, y]); + }, + + /** + * Serializes a DOM form into a url encoded string + * @param {Object} form The form + * @return {String} The url encoded form + */ + serializeForm: function(form) { + var fElements = form.elements || (document.forms[form] || Ext.getDom(form)).elements, + hasSubmit = false, + encoder = encodeURIComponent, + data = '', + eLen = fElements.length, + element, name, type, options, hasValue, e, + o, oLen, opt; + + for (e = 0; e < eLen; e++) { + element = fElements[e]; + name = element.name; + type = element.type; + options = element.options; + + if (!element.disabled && name) { + if (/select-(one|multiple)/i.test(type)) { + oLen = options.length; + for (o = 0; o < oLen; o++) { + opt = options[o]; + if (opt.selected) { + hasValue = opt.hasAttribute ? opt.hasAttribute('value') : opt.getAttributeNode('value').specified; + data += Ext.String.format("{0}={1}&", encoder(name), encoder(hasValue ? opt.value : opt.text)); + } + } + } else if (!(/file|undefined|reset|button/i.test(type))) { + if (!(/radio|checkbox/i.test(type) && !element.checked) && !(type == 'submit' && hasSubmit)) { + data += encoder(name) + '=' + encoder(element.value) + '&'; + hasSubmit = /submit/i.test(type); + } + } + } + } + return data.substr(0, data.length - 1); + } + }); +}()); + +/** + * @class Ext.dom.AbstractElement + */ +Ext.dom.AbstractElement.override({ + + /** + * Gets the x,y coordinates specified by the anchor position on the element. + * @param {String} [anchor] The specified anchor position (defaults to "c"). See {@link Ext.dom.Element#alignTo} + * for details on supported anchor positions. + * @param {Boolean} [local] True to get the local (element top/left-relative) anchor position instead + * of page coordinates + * @param {Object} [size] 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, size) { + //Passing a different size is useful for pre-calculating anchors, + //especially for anchored animations that change the el size. + anchor = (anchor || "tl").toLowerCase(); + size = size || {}; + + var me = this, + vp = me.dom == document.body || me.dom == document, + width = size.width || vp ? window.innerWidth: me.getWidth(), + height = size.height || vp ? window.innerHeight: me.getHeight(), + xy, + rnd = Math.round, + myXY = me.getXY(), + extraX = vp ? 0: !local ? myXY[0] : 0, + extraY = vp ? 0: !local ? myXY[1] : 0, + hash = { + c: [rnd(width * 0.5), rnd(height * 0.5)], + t: [rnd(width * 0.5), 0], + l: [0, rnd(height * 0.5)], + r: [width, rnd(height * 0.5)], + b: [rnd(width * 0.5), height], + tl: [0, 0], + bl: [0, height], + br: [width, height], + tr: [width, 0] + }; + + xy = hash[anchor]; + return [xy[0] + extraX, xy[1] + extraY]; + }, + + alignToRe: /^([a-z]+)-([a-z]+)(\?)?$/, + + /** + * Gets the x,y coordinates to align this element with another element. See {@link Ext.dom.Element#alignTo} for more info on the + * supported position values. + * @param {Ext.Element/HTMLElement/String} element The element to align to. + * @param {String} [position="tl-bl?"] The position to align to. + * @param {Array} [offsets=[0,0]] Offset the positioning by [x, y] + * @return {Array} [x, y] + */ + getAlignToXY: function(el, position, offsets, local) { + local = !!local; + el = Ext.get(el); + + if (!el || !el.dom) { + throw new Error("Element.alignToXY with an element that doesn't exist"); + } + offsets = offsets || [0, 0]; + + if (!position || position == '?') { + position = 'tl-bl?'; + } + else if (! (/-/).test(position) && position !== "") { + position = 'tl-' + position; + } + position = position.toLowerCase(); + + var me = this, + matches = position.match(this.alignToRe), + dw = window.innerWidth, + dh = window.innerHeight, + p1 = "", + p2 = "", + a1, + a2, + x, + y, + swapX, + swapY, + p1x, + p1y, + p2x, + p2y, + width, + height, + region, + constrain; + + if (!matches) { + throw "Element.alignTo with an invalid alignment " + position; + } + + p1 = matches[1]; + p2 = matches[2]; + constrain = !!matches[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, local); + + x = a2[0] - a1[0] + offsets[0]; + y = a2[1] - a1[1] + offsets[1]; + + if (constrain) { + width = me.getWidth(); + height = me.getHeight(); + + region = el.getPageBox(); + + //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 + width > dw) { + x = swapX ? region.left - width: dw - width; + } + if (x < 0) { + x = swapX ? region.right: 0; + } + if (y + height > dh) { + y = swapY ? region.top - height: dh - height; + } + if (y < 0) { + y = swapY ? region.bottom: 0; + } + } + + return [x, y]; + }, + + // private + getAnchor: function(){ + var data = (this.$cache || this.getCache()).data, + anchor; + + if (!this.dom) { + return; + } + anchor = data._anchor; + + if(!anchor){ + anchor = data._anchor = {}; + } + return anchor; + }, + + // private ==> used outside of core + adjustForConstraints: function(xy, parent) { + var vector = this.getConstrainVector(parent, xy); + if (vector) { + xy[0] += vector[0]; + xy[1] += vector[1]; + } + return xy; + } + +}); + +/** + * @class Ext.dom.AbstractElement + */ +Ext.dom.AbstractElement.addMethods({ + /** + * Appends the passed element(s) to this element + * @param {String/HTMLElement/Ext.dom.AbstractElement} el + * The id of the node, a DOM Node or an existing Element. + * @return {Ext.dom.AbstractElement} This element + */ + appendChild: function(el) { + return Ext.get(el).appendTo(this); + }, + + /** + * Appends this element to the passed element + * @param {String/HTMLElement/Ext.dom.AbstractElement} el The new parent element. + * The id of the node, a DOM Node or an existing Element. + * @return {Ext.dom.AbstractElement} This element + */ + appendTo: function(el) { + Ext.getDom(el).appendChild(this.dom); + return this; + }, + + /** + * Inserts this element before the passed element in the DOM + * @param {String/HTMLElement/Ext.dom.AbstractElement} el The element before which this element will be inserted. + * The id of the node, a DOM Node or an existing Element. + * @return {Ext.dom.AbstractElement} This element + */ + insertBefore: function(el) { + el = Ext.getDom(el); + el.parentNode.insertBefore(this.dom, el); + return this; + }, + + /** + * Inserts this element after the passed element in the DOM + * @param {String/HTMLElement/Ext.dom.AbstractElement} el The element to insert after. + * The id of the node, a DOM Node or an existing Element. + * @return {Ext.dom.AbstractElement} This element + */ + insertAfter: function(el) { + el = Ext.getDom(el); + 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 {String/HTMLElement/Ext.dom.AbstractElement/Object} el The id or element to insert or a DomHelper config + * to create and insert + * @return {Ext.dom.AbstractElement} The new child + */ + insertFirst: function(el, returnDom) { + el = el || {}; + if (el.nodeType || el.dom || typeof el == 'string') { // element + el = Ext.getDom(el); + this.dom.insertBefore(el, this.dom.firstChild); + return !returnDom ? Ext.get(el) : el; + } + else { // dh config + return this.createChild(el, this.dom.firstChild, returnDom); + } + }, + + /** + * Inserts (or creates) the passed element (or DomHelper config) as a sibling of this element + * @param {String/HTMLElement/Ext.dom.AbstractElement/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='before'] 'before' or 'after' + * @param {Boolean} [returnDom=false] True to return the .;ll;l,raw DOM element instead of Ext.dom.AbstractElement + * @return {Ext.dom.AbstractElement} The inserted Element. If an array is passed, the last inserted element is returned. + */ + insertSibling: function(el, where, returnDom){ + var me = this, + isAfter = (where || 'before').toLowerCase() == 'after', + rt, insertEl, eLen, e; + + if (Ext.isArray(el)) { + insertEl = me; + eLen = el.length; + + for (e = 0; e < eLen; e++) { + rt = Ext.fly(insertEl, '_internal').insertSibling(el[e], where, returnDom); + + if (isAfter) { + insertEl = rt; + } + } + + return rt; + } + + el = el || {}; + + if(el.nodeType || el.dom){ + rt = me.dom.parentNode.insertBefore(Ext.getDom(el), isAfter ? me.dom.nextSibling : me.dom); + if (!returnDom) { + rt = Ext.get(rt); + } + }else{ + if (isAfter && !me.dom.nextSibling) { + rt = Ext.core.DomHelper.append(me.dom.parentNode, el, !returnDom); + } else { + rt = Ext.core.DomHelper[isAfter ? 'insertAfter' : 'insertBefore'](me.dom, el, !returnDom); + } + } + return rt; + }, + + /** + * Replaces the passed element with this element + * @param {String/HTMLElement/Ext.dom.AbstractElement} el The element to replace. + * The id of the node, a DOM Node or an existing Element. + * @return {Ext.dom.AbstractElement} This element + */ + replace: function(el) { + el = Ext.get(el); + this.insertBefore(el); + el.remove(); + return this; + }, + + /** + * Replaces this element with the passed element + * @param {String/HTMLElement/Ext.dom.AbstractElement/Object} el The new element (id of the node, a DOM Node + * or an existing Element) or a DomHelper config of an element to create + * @return {Ext.dom.AbstractElement} This element + */ + replaceWith: function(el){ + var me = this; + + if(el.nodeType || el.dom || typeof el == 'string'){ + el = Ext.get(el); + me.dom.parentNode.insertBefore(el, me.dom); + }else{ + el = Ext.core.DomHelper.insertBefore(me.dom, el); + } + + delete Ext.cache[me.id]; + Ext.removeNode(me.dom); + me.id = Ext.id(me.dom = el); + Ext.dom.AbstractElement.addToCache(me.isFlyweight ? new Ext.dom.AbstractElement(me.dom) : me); + return me; + }, + + /** + * Creates the passed DomHelper config and appends it to this element or optionally inserts it before the passed child element. + * @param {Object} config DomHelper element config object. If no tag is specified (e.g., {tag:'input'}) then a div will be + * automatically generated with the specified attributes. + * @param {HTMLElement} [insertBefore] a child element of this element + * @param {Boolean} [returnDom=false] true to return the dom node instead of creating an Element + * @return {Ext.dom.AbstractElement} The new child element + */ + createChild: function(config, insertBefore, returnDom) { + config = config || {tag:'div'}; + if (insertBefore) { + return Ext.core.DomHelper.insertBefore(insertBefore, config, returnDom !== true); + } + else { + return Ext.core.DomHelper[!this.dom.firstChild ? 'insertFirst' : 'append'](this.dom, config, returnDom !== true); + } + }, + + /** + * Creates and wraps this element with another element + * @param {Object} [config] DomHelper element config object for the wrapper element or null for an empty div + * @param {Boolean} [returnDom=false] True to return the raw DOM element instead of Ext.dom.AbstractElement + * @return {HTMLElement/Ext.dom.AbstractElement} The newly created wrapper element + */ + wrap: function(config, returnDom) { + var newEl = Ext.core.DomHelper.insertBefore(this.dom, config || {tag: "div"}, !returnDom), + d = newEl.dom || newEl; + + d.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. + * See {@link Ext.dom.Helper#insertHtml} for details. + * @param {String} html The HTML fragment + * @param {Boolean} [returnEl=false] True to return an Ext.dom.AbstractElement + * @return {HTMLElement/Ext.dom.AbstractElement} The inserted node (or nearest related if more than 1 inserted) + */ + insertHtml: function(where, html, returnEl) { + var el = Ext.core.DomHelper.insertHtml(where, this.dom, html); + return returnEl ? Ext.get(el) : el; + } +}); + +/** + * @class Ext.dom.AbstractElement + */ +(function(){ + +var Element = Ext.dom.AbstractElement; + +Element.override({ + + /** + * 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(el) { + return this.getXY(el)[0]; + }, + + /** + * 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(el) { + return this.getXY(el)[1]; + }, + + /** + * 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() { + // @FEATUREDETECT + var point = window.webkitConvertPointFromNodeToPage(this.dom, new WebKitPoint(0, 0)); + return [point.x, point.y]; + }, + + /** + * 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 {Ext.Element/HTMLElement/String} 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] True for the default animation, or a standard Element + * animation config object + * @return {Ext.dom.AbstractElement} this + */ + setX: function(x){ + return this.setXY([x, this.getY()]); + }, + + /** + * 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] True for the default animation, or a standard Element + * animation config object + * @return {Ext.dom.AbstractElement} this + */ + setY: function(y) { + return this.setXY([this.getX(), y]); + }, + + /** + * Sets the element's left position directly using CSS style (instead of {@link #setX}). + * @param {String} left The left CSS property value + * @return {Ext.dom.AbstractElement} this + */ + setLeft: function(left) { + this.setStyle('left', Element.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.dom.AbstractElement} this + */ + setTop: function(top) { + this.setStyle('top', Element.addUnits(top)); + return this; + }, + + /** + * Sets the element's CSS right style. + * @param {String} right The right CSS property value + * @return {Ext.dom.AbstractElement} this + */ + setRight: function(right) { + this.setStyle('right', Element.addUnits(right)); + return this; + }, + + /** + * Sets the element's CSS bottom style. + * @param {String} bottom The bottom CSS property value + * @return {Ext.dom.AbstractElement} this + */ + setBottom: function(bottom) { + this.setStyle('bottom', Element.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] True for the default animation, or a standard Element animation config object + * @return {Ext.dom.AbstractElement} this + */ + setXY: function(pos) { + var me = this, + pts, + style, + pt; + + if (arguments.length > 1) { + pos = [pos, arguments[1]]; + } + + // me.position(); + pts = me.translatePoints(pos); + style = me.dom.style; + + for (pt in pts) { + if (!pts.hasOwnProperty(pt)) { + continue; + } + if (!isNaN(pts[pt])) { + style[pt] = pts[pt] + "px"; + } + } + return me; + }, + + /** + * 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 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) { + return parseInt(this.getStyle('right'), 10) || 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 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) { + return parseInt(this.getStyle('bottom'), 10) || 0; + }, + + /** + * 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] 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)}; + }, + + /** + * 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] Whether to adjust for box-model issues automatically + * @param {Boolean/Object} [animate] true for the default animation or a standard + * Element animation config object + * @return {Ext.dom.AbstractElement} this + */ + setBox: function(box) { + var me = this, + width = box.width, + height = box.height, + top = box.top, + left = box.left; + + if (left !== undefined) { + me.setLeft(left); + } + if (top !== undefined) { + me.setTop(top); + } + if (width !== undefined) { + me.setWidth(width); + } + if (height !== undefined) { + me.setHeight(height); + } + + return this; + }, + + /** + * Return an object defining the area of this Element which can be passed to {@link #setBox} to + * set another Element's size/location to match this element. + * + * @param {Boolean} [contentBox] If true a box for the content of the element is returned. + * @param {Boolean} [local] 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: , + * bottom: , + * right: + * } + * + * The returned object may also be addressed as an Array where index 0 contains the X position + * and index 1 contains the Y position. So the result may also be used for {@link #setXY} + */ + getBox: function(contentBox, local) { + var me = this, + dom = me.dom, + width = dom.offsetWidth, + height = dom.offsetHeight, + xy, box, l, r, t, b; + + if (!local) { + xy = me.getXY(); + } + else if (contentBox) { + xy = [0,0]; + } + else { + xy = [parseInt(me.getStyle("left"), 10) || 0, parseInt(me.getStyle("top"), 10) || 0]; + } + + if (!contentBox) { + box = { + x: xy[0], + y: xy[1], + 0: xy[0], + 1: xy[1], + width: width, + height: height + }; + } + else { + l = me.getBorderWidth.call(me, "l") + me.getPadding.call(me, "l"); + r = me.getBorderWidth.call(me, "r") + me.getPadding.call(me, "r"); + t = me.getBorderWidth.call(me, "t") + me.getPadding.call(me, "t"); + b = me.getBorderWidth.call(me, "b") + me.getPadding.call(me, "b"); + box = { + x: xy[0] + l, + y: xy[1] + t, + 0: xy[0] + l, + 1: xy[1] + t, + width: width - (l + r), + height: height - (t + b) + }; + } + + box.left = box.x; + box.top = box.y; + box.right = box.x + box.width; + box.bottom = box.y + box.height; + + return box; + }, + + /** + * Return an object defining the area of this Element which can be passed to {@link #setBox} to + * set another Element's size/location to match this element. + * + * @param {Boolean} [asRegion] If true an Ext.util.Region will be returned + * @return {Object} box An object in the format + * + * { + * x: , + * y: , + * width: , + * height: , + * bottom: , + * right: + * } + * + * The returned object may also be addressed as an Array where index 0 contains the X position + * and index 1 contains the Y position. So the result may also be used for {@link #setXY} + */ + getPageBox: function(getRegion) { + var me = this, + el = me.dom, + w = el.offsetWidth, + h = el.offsetHeight, + xy = me.getXY(), + t = xy[1], + r = xy[0] + w, + b = xy[1] + h, + l = xy[0]; + + if (!el) { + return new Ext.util.Region(); + } + + if (getRegion) { + return new Ext.util.Region(t, r, b, l); + } + else { + return { + left: l, + top: t, + width: w, + height: h, + right: r, + bottom: b + }; + } + } +}); + +}()); + +/** + * @class Ext.dom.AbstractElement + */ +(function(){ + // local style camelizing for speed + var Element = Ext.dom.AbstractElement, + view = document.defaultView, + array = Ext.Array, + trimRe = /^\s+|\s+$/g, + wordsRe = /\w/g, + spacesRe = /\s+/, + transparentRe = /^(?:transparent|(?:rgba[(](?:\s*\d+\s*[,]){3}\s*0\s*[)]))$/i, + hasClassList = Ext.supports.ClassList, + PADDING = 'padding', + MARGIN = 'margin', + BORDER = 'border', + LEFT_SUFFIX = '-left', + RIGHT_SUFFIX = '-right', + TOP_SUFFIX = '-top', + BOTTOM_SUFFIX = '-bottom', + WIDTH = '-width', + // special markup used throughout Ext when box wrapping elements + borders = {l: BORDER + LEFT_SUFFIX + WIDTH, r: BORDER + RIGHT_SUFFIX + WIDTH, t: BORDER + TOP_SUFFIX + WIDTH, b: BORDER + BOTTOM_SUFFIX + WIDTH}, + paddings = {l: PADDING + LEFT_SUFFIX, r: PADDING + RIGHT_SUFFIX, t: PADDING + TOP_SUFFIX, b: PADDING + BOTTOM_SUFFIX}, + margins = {l: MARGIN + LEFT_SUFFIX, r: MARGIN + RIGHT_SUFFIX, t: MARGIN + TOP_SUFFIX, b: MARGIN + BOTTOM_SUFFIX}; + + + Element.override({ + + /** + * This shared object is keyed by style name (e.g., 'margin-left' or 'marginLeft'). The + * values are objects with the following properties: + * + * * `name` (String) : The actual name to be presented to the DOM. This is typically the value + * returned by {@link #normalize}. + * * `get` (Function) : A hook function that will perform the get on this style. These + * functions receive "(dom, el)" arguments. The `dom` parameter is the DOM Element + * from which to get ths tyle. The `el` argument (may be null) is the Ext.Element. + * * `set` (Function) : A hook function that will perform the set on this style. These + * functions receive "(dom, value, el)" arguments. The `dom` parameter is the DOM Element + * from which to get ths tyle. The `value` parameter is the new value for the style. The + * `el` argument (may be null) is the Ext.Element. + * + * The `this` pointer is the object that contains `get` or `set`, which means that + * `this.name` can be accessed if needed. The hook functions are both optional. + * @private + */ + styleHooks: {}, + + // private + addStyles : function(sides, styles){ + var totalSize = 0, + sidesArr = (sides || '').match(wordsRe), + i, + len = sidesArr.length, + side, + styleSides = []; + + if (len == 1) { + totalSize = Math.abs(parseFloat(this.getStyle(styles[sidesArr[0]])) || 0); + } else if (len) { + for (i = 0; i < len; i++) { + side = sidesArr[i]; + styleSides.push(styles[side]); + } + //Gather all at once, returning a hash + styleSides = this.getStyle(styleSides); + + for (i=0; i < len; i++) { + side = sidesArr[i]; + totalSize += Math.abs(parseFloat(styleSides[styles[side]]) || 0); + } + } + + return totalSize; + }, + + /** + * Adds one or more CSS classes to the element. Duplicate classes are automatically filtered out. + * @param {String/String[]} className The CSS classes to add separated by space, or an array of classes + * @return {Ext.dom.Element} this + * @method + */ + addCls: hasClassList ? + function (className) { + if (String(className).indexOf('undefined') > -1) { + Ext.Logger.warn("called with an undefined className: " + className); + } + var me = this, + dom = me.dom, + classList, + newCls, + i, + len, + cls; + + if (typeof(className) == 'string') { + // split string on spaces to make an array of className + className = className.replace(trimRe, '').split(spacesRe); + } + + // the gain we have here is that we can skip parsing className and use the + // classList.contains method, so now O(M) not O(M+N) + if (dom && className && !!(len = className.length)) { + if (!dom.className) { + dom.className = className.join(' '); + } else { + classList = dom.classList; + for (i = 0; i < len; ++i) { + cls = className[i]; + if (cls) { + if (!classList.contains(cls)) { + if (newCls) { + newCls.push(cls); + } else { + newCls = dom.className.replace(trimRe, ''); + newCls = newCls ? [newCls, cls] : [cls]; + } + } + } + } + + if (newCls) { + dom.className = newCls.join(' '); // write to DOM once + } + } + } + return me; + } : + function(className) { + if (String(className).indexOf('undefined') > -1) { + Ext.Logger.warn("called with an undefined className: '" + className + "'"); + } + var me = this, + dom = me.dom, + changed, + elClasses; + + if (dom && className && className.length) { + elClasses = Ext.Element.mergeClsList(dom.className, className); + if (elClasses.changed) { + dom.className = elClasses.join(' '); // write to DOM once + } + } + return me; + }, + + + /** + * Removes one or more CSS classes from the element. + * @param {String/String[]} className The CSS classes to remove separated by space, or an array of classes + * @return {Ext.dom.Element} this + */ + removeCls: function(className) { + var me = this, + dom = me.dom, + len, + elClasses; + + if (typeof(className) == 'string') { + // split string on spaces to make an array of className + className = className.replace(trimRe, '').split(spacesRe); + } + + if (dom && dom.className && className && !!(len = className.length)) { + if (len == 1 && hasClassList) { + if (className[0]) { + dom.classList.remove(className[0]); // one DOM write + } + } else { + elClasses = Ext.Element.removeCls(dom.className, className); + if (elClasses.changed) { + dom.className = elClasses.join(' '); + } + } + } + return me; + }, + + /** + * Adds one or more CSS classes to this element and removes the same class(es) from all siblings. + * @param {String/String[]} className The CSS class to add, or an array of classes + * @return {Ext.dom.Element} this + */ + radioCls: 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').removeCls(className); + } + } + return this.addCls(className); + }, + + /** + * Toggles the specified CSS class on this element (removes it if it already exists, otherwise adds it). + * @param {String} className The CSS class to toggle + * @return {Ext.dom.Element} this + * @method + */ + toggleCls: hasClassList ? + function (className) { + var me = this, + dom = me.dom; + + if (dom) { + className = className.replace(trimRe, ''); + if (className) { + dom.classList.toggle(className); + } + } + + return me; + } : + function(className) { + var me = this; + return me.hasCls(className) ? me.removeCls(className) : me.addCls(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 + * @method + */ + hasCls: hasClassList ? + function (className) { + var dom = this.dom; + return (dom && className) ? dom.classList.contains(className) : false; + } : + function(className) { + var dom = this.dom; + return dom ? className && (' '+dom.className+' ').indexOf(' '+className+' ') != -1 : false; + }, + + /** + * 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.dom.Element} this + */ + replaceCls: function(oldClassName, newClassName){ + return this.removeCls(oldClassName).addCls(newClassName); + }, + + /** + * Checks if the current value of a style is equal to a given value. + * @param {String} style property whose value is returned. + * @param {String} value to check against. + * @return {Boolean} true for when the current value equals the given value. + */ + isStyle: function(style, val) { + return this.getStyle(style) == val; + }, + + /** + * Returns a named style property based on computed/currentStyle (primary) and + * inline-style if primary is not available. + * + * @param {String/String[]} property The style property (or multiple property names + * in an array) whose value is returned. + * @param {Boolean} [inline=false] if `true` only inline styles will be returned. + * @return {String/Object} The current value of the style property for this element + * (or a hash of named style values if multiple property arguments are requested). + * @method + */ + getStyle: function (property, inline) { + var me = this, + dom = me.dom, + multiple = typeof property != 'string', + hooks = me.styleHooks, + prop = property, + props = prop, + len = 1, + domStyle, camel, values, hook, out, style, i; + + if (multiple) { + values = {}; + prop = props[0]; + i = 0; + if (!(len = props.length)) { + return values; + } + } + + if (!dom || dom.documentElement) { + return values || ''; + } + + domStyle = dom.style; + + if (inline) { + style = domStyle; + } else { + // Caution: Firefox will not render "presentation" (ie. computed styles) in + // iframes that are display:none or those inheriting display:none. Similar + // issues with legacy Safari. + // + style = dom.ownerDocument.defaultView.getComputedStyle(dom, null); + + // fallback to inline style if rendering context not available + if (!style) { + inline = true; + style = domStyle; + } + } + + do { + hook = hooks[prop]; + + if (!hook) { + hooks[prop] = hook = { name: Element.normalize(prop) }; + } + + if (hook.get) { + out = hook.get(dom, me, inline, style); + } else { + camel = hook.name; + out = style[camel]; + } + + if (!multiple) { + return out; + } + + values[prop] = out; + prop = props[++i]; + } while (i < len); + + return values; + }, + + getStyles: function () { + var props = Ext.Array.slice(arguments), + len = props.length, + inline; + + if (len && typeof props[len-1] == 'boolean') { + inline = props.pop(); + } + + return this.getStyle(props, inline); + }, + + /** + * Returns true if the value of the given property is visually transparent. This + * may be due to a 'transparent' style value or an rgba value with 0 in the alpha + * component. + * @param {String} prop The style property whose value is to be tested. + * @return {Boolean} True if the style property is visually transparent. + */ + isTransparent: function (prop) { + var value = this.getStyle(prop); + return value ? transparentRe.test(value) : false; + }, + + /** + * 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] The value to apply to the given property, or null if an object was passed. + * @return {Ext.dom.Element} this + */ + setStyle: function(prop, value) { + var me = this, + dom = me.dom, + hooks = me.styleHooks, + style = dom.style, + name = prop, + hook; + + // we don't promote the 2-arg form to object-form to avoid the overhead... + if (typeof name == 'string') { + hook = hooks[name]; + if (!hook) { + hooks[name] = hook = { name: Element.normalize(name) }; + } + value = (value == null) ? '' : value; + if (hook.set) { + hook.set(dom, value, me); + } else { + style[hook.name] = value; + } + if (hook.afterSet) { + hook.afterSet(dom, value, me); + } + } else { + for (name in prop) { + if (prop.hasOwnProperty(name)) { + hook = hooks[name]; + if (!hook) { + hooks[name] = hook = { name: Element.normalize(name) }; + } + value = prop[name]; + value = (value == null) ? '' : value; + if (hook.set) { + hook.set(dom, value, me); + } else { + style[hook.name] = value; + } + if (hook.afterSet) { + hook.afterSet(dom, value, me); + } + } + } + } + + return me; + }, + + /** + * Returns the offset height of the element + * @param {Boolean} [contentHeight] true to get the height minus borders and padding + * @return {Number} The element's height + */ + getHeight: function(contentHeight) { + var dom = this.dom, + height = contentHeight ? (dom.clientHeight - this.getPadding("tb")) : dom.offsetHeight; + return height > 0 ? height: 0; + }, + + /** + * Returns the offset width of the element + * @param {Boolean} [contentWidth] true to get the width minus borders and padding + * @return {Number} The element's width + */ + getWidth: function(contentWidth) { + var dom = this.dom, + width = contentWidth ? (dom.clientWidth - this.getPadding("lr")) : dom.offsetWidth; + return width > 0 ? width: 0; + }, + + /** + * Set the width of this Element. + * @param {Number/String} 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] true for the default animation or a standard Element animation config object + * @return {Ext.dom.Element} this + */ + setWidth: function(width) { + var me = this; + me.dom.style.width = Element.addUnits(width); + return me; + }, + + /** + * 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 {Number/String} 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] true for the default animation or a standard Element animation config object + * @return {Ext.dom.Element} this + */ + setHeight: function(height) { + var me = this; + me.dom.style.height = Element.addUnits(height); + 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 **l**eft width + the border **r**ight width. + * @return {Number} The width of the sides passed added together + */ + getBorderWidth: function(side){ + return this.addStyles(side, borders); + }, + + /** + * Gets the width of the padding(s) for the specified side(s) + * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example, + * passing `'lr'` would get the padding **l**eft + the padding **r**ight. + * @return {Number} The padding of the sides passed added together + */ + getPadding: function(side){ + return this.addStyles(side, paddings); + }, + + margins : margins, + + /** + * 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.dom.Element} this + */ + applyStyles: function(styles) { + if (styles) { + var i, + len, + dom = this.dom; + + if (typeof styles == 'function') { + styles = styles.call(); + } + if (typeof styles == 'string') { + styles = Ext.util.Format.trim(styles).split(/\s*(?::|;)\s*/); + for (i = 0, len = styles.length; i < len;) { + dom.style[Element.normalize(styles[i++])] = styles[i++]; + } + } + else if (typeof styles == 'object') { + this.setStyle(styles); + } + } + }, + + /** + * Set the size of this Element. If animation is true, both width and height will be animated concurrently. + * @param {Number/String} 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 {Number/String} 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] true for the default animation or a standard Element animation config object + * @return {Ext.dom.Element} this + */ + setSize: function(width, height) { + var me = this, + style = me.dom.style; + + if (Ext.isObject(width)) { + // in case of object from getSize() + height = width.height; + width = width.width; + } + + style.width = Element.addUnits(width); + style.height = Element.addUnits(height); + return me; + }, + + /** + * Returns the dimensions of the element available to lay content out in. + * + * If the element (or any ancestor element) has CSS style `display: none`, the dimensions will be zero. + * + * Example: + * + * 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. + * + * getViewSize utilizes clientHeight/clientWidth which excludes sizing of scrollbars. + * To obtain the size including scrollbars, use getStyleSize + * + * Sizing of the document body is handled at the adapter level which handles special cases for IE and strict modes, etc. + * + * @return {Object} Object describing width and height. + * @return {Number} return.width + * @return {Number} return.height + */ + getViewSize: function() { + var doc = document, + dom = this.dom; + + if (dom == doc || dom == doc.body) { + return { + width: Element.getViewportWidth(), + height: Element.getViewportHeight() + }; + } + else { + return { + width: dom.clientWidth, + height: dom.clientHeight + }; + } + }, + + /** + * Returns the size of the element. + * @param {Boolean} [contentSize] true to get the width/size minus borders and padding + * @return {Object} An object containing the element's size: + * @return {Number} return.width + * @return {Number} return.height + */ + getSize: function(contentSize) { + var dom = this.dom; + return { + width: Math.max(0, contentSize ? (dom.clientWidth - this.getPadding("lr")) : dom.offsetWidth), + height: Math.max(0, contentSize ? (dom.clientHeight - this.getPadding("tb")) : dom.offsetHeight) + }; + }, + + /** + * Forces the browser to repaint this element + * @return {Ext.dom.Element} this + */ + repaint: function(){ + var dom = this.dom; + this.addCls(Ext.baseCSSPrefix + 'repaint'); + setTimeout(function(){ + Ext.fly(dom).removeCls(Ext.baseCSSPrefix + 'repaint'); + }, 1); + return this; + }, + + /** + * 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] Any combination of l, r, t, b to get the sum of those sides + * @return {Object/Number} + */ + getMargin: function(side){ + var me = this, + hash = {t:"top", l:"left", r:"right", b: "bottom"}, + key, + o, + margins; + + if (!side) { + margins = []; + for (key in me.margins) { + if(me.margins.hasOwnProperty(key)) { + margins.push(me.margins[key]); + } + } + o = me.getStyle(margins); + if(o && typeof o == 'object') { + //now mixin nomalized values (from hash table) + for (key in me.margins) { + if(me.margins.hasOwnProperty(key)) { + o[hash[key]] = parseFloat(o[me.margins[key]]) || 0; + } + } + } + + return o; + } else { + return me.addStyles.call(me, side, me.margins); + } + }, + + /** + * 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] A message to display in the mask + * @param {String} [msgCls] A css class to apply to the msg element + */ + mask: function(msg, msgCls, transparent) { + var me = this, + dom = me.dom, + data = (me.$cache || me.getCache()).data, + el = data.mask, + mask, + size, + cls = '', + prefix = Ext.baseCSSPrefix; + + me.addCls(prefix + 'masked'); + if (me.getStyle("position") == "static") { + me.addCls(prefix + 'masked-relative'); + } + if (el) { + el.remove(); + } + if (msgCls && typeof msgCls == 'string' ) { + cls = ' ' + msgCls; + } + else { + cls = ' ' + prefix + 'mask-gray'; + } + + mask = me.createChild({ + cls: prefix + 'mask' + ((transparent !== false) ? '' : (' ' + prefix + 'mask-gray')), + html: msg ? ('
    ' + msg + '
    ') : '' + }); + + size = me.getSize(); + + data.mask = mask; + + if (dom === document.body) { + size.height = window.innerHeight; + if (me.orientationHandler) { + Ext.EventManager.unOrientationChange(me.orientationHandler, me); + } + + me.orientationHandler = function() { + size = me.getSize(); + size.height = window.innerHeight; + mask.setSize(size); + }; + + Ext.EventManager.onOrientationChange(me.orientationHandler, me); + } + mask.setSize(size); + if (Ext.is.iPad) { + Ext.repaint(); + } + }, + + /** + * Removes a previously applied mask. + */ + unmask: function() { + var me = this, + data = (me.$cache || me.getCache()).data, + mask = data.mask, + prefix = Ext.baseCSSPrefix; + + if (mask) { + mask.remove(); + delete data.mask; + } + me.removeCls([prefix + 'masked', prefix + 'masked-relative']); + + if (me.dom === document.body) { + Ext.EventManager.unOrientationChange(me.orientationHandler, me); + delete me.orientationHandler; + } + } + }); + + /** + * Creates mappings for 'margin-before' to 'marginLeft' (etc.) given the output + * map and an ordering pair (e.g., ['left', 'right']). The ordering pair is in + * before/after order. + */ + Element.populateStyleMap = function (map, order) { + var baseStyles = ['margin-', 'padding-', 'border-width-'], + beforeAfter = ['before', 'after'], + index, style, name, i; + + for (index = baseStyles.length; index--; ) { + for (i = 2; i--; ) { + style = baseStyles[index] + beforeAfter[i]; // margin-before + // ex: maps margin-before and marginBefore to marginLeft + map[Element.normalize(style)] = map[style] = { + name: Element.normalize(baseStyles[index] + order[i]) + }; + } + } + }; + + Ext.onReady(function () { + var supports = Ext.supports, + styleHooks, + colorStyles, i, name, camel; + + function fixTransparent (dom, el, inline, style) { + var value = style[this.name] || ''; + return transparentRe.test(value) ? 'transparent' : value; + } + + function fixRightMargin (dom, el, inline, style) { + var result = style.marginRight, + domStyle, display; + + // Ignore cases when the margin is correctly reported as 0, the bug only shows + // numbers larger. + if (result != '0px') { + domStyle = dom.style; + display = domStyle.display; + domStyle.display = 'inline-block'; + result = (inline ? style : dom.ownerDocument.defaultView.getComputedStyle(dom, null)).marginRight; + domStyle.display = display; + } + + return result; + } + + function fixRightMarginAndInputFocus (dom, el, inline, style) { + var result = style.marginRight, + domStyle, cleaner, display; + + if (result != '0px') { + domStyle = dom.style; + cleaner = Element.getRightMarginFixCleaner(dom); + display = domStyle.display; + domStyle.display = 'inline-block'; + result = (inline ? style : dom.ownerDocument.defaultView.getComputedStyle(dom, '')).marginRight; + domStyle.display = display; + cleaner(); + } + + return result; + } + + styleHooks = Element.prototype.styleHooks; + + // Populate the LTR flavors of margin-before et.al. (see Ext.rtl.AbstractElement): + Element.populateStyleMap(styleHooks, ['left', 'right']); + + // Ext.supports needs to be initialized (we run very early in the onready sequence), + // but it is OK to call Ext.supports.init() more times than necessary... + if (supports.init) { + supports.init(); + } + + // Fix bug caused by this: https://bugs.webkit.org/show_bug.cgi?id=13343 + if (!supports.RightMargin) { + styleHooks.marginRight = styleHooks['margin-right'] = { + name: 'marginRight', + // TODO - Touch should use conditional compilation here or ensure that the + // underlying Ext.supports flags are set correctly... + get: (supports.DisplayChangeInputSelectionBug || supports.DisplayChangeTextAreaSelectionBug) ? + fixRightMarginAndInputFocus : fixRightMargin + }; + } + + if (!supports.TransparentColor) { + colorStyles = ['background-color', 'border-color', 'color', 'outline-color']; + for (i = colorStyles.length; i--; ) { + name = colorStyles[i]; + camel = Element.normalize(name); + + styleHooks[name] = styleHooks[camel] = { + name: camel, + get: fixTransparent + }; + } + } + }); +}()); + +/** + * @class Ext.dom.AbstractElement + */ +Ext.dom.AbstractElement.override({ + /** + * 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/String/HTMLElement/Ext.Element} [limit] + * The max depth to search as a number or an element which causes the upward traversal to stop + * and is not considered for inclusion as the result. (defaults to 50 || document.documentElement) + * @param {Boolean} [returnEl=false] 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, limit, returnEl) { + var target = this.dom, + topmost = document.documentElement, + depth = 0, + stopEl; + + limit = limit || 50; + if (isNaN(limit)) { + stopEl = Ext.getDom(limit); + limit = Number.MAX_VALUE; + } + while (target && target.nodeType == 1 && depth < limit && target != topmost && target != stopEl) { + if (Ext.DomQuery.is(target, simpleSelector)) { + return returnEl ? Ext.get(target) : target; + } + depth++; + target = target.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/String/HTMLElement/Ext.Element} [limit] + * The max depth to search as a number or an element which causes the upward traversal to stop + * and is not considered for inclusion as the result. (defaults to 50 || document.documentElement) + * @param {Boolean} [returnEl=false] 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, limit, returnEl) { + var p = Ext.fly(this.dom.parentNode, '_internal'); + return p ? p.findParent(simpleSelector, limit, 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.dom.Element. + * @param {String} selector The simple selector to test + * @param {Number/String/HTMLElement/Ext.Element} [limit] + * The max depth to search as a number or an element which causes the upward traversal to stop + * and is not considered for inclusion as the result. (defaults to 50 || document.documentElement) + * @return {Ext.Element} The matching DOM node (or null if no match was found) + */ + up: function(simpleSelector, limit) { + return this.findParentNode(simpleSelector, limit, true); + }, + + /** + * Creates a {@link Ext.CompositeElement} for child nodes based on the passed CSS selector (the selector should not contain an id). + * @param {String} selector The CSS selector + * @return {Ext.CompositeElement} The composite element + */ + select: function(selector, composite) { + return Ext.dom.Element.select(selector, this.dom, composite); + }, + + /** + * Selects child nodes based on the passed CSS selector (the selector should not contain an id). + * @param {String} selector The CSS selector + * @return {HTMLElement[]} An array of the matched nodes + */ + query: function(selector) { + return Ext.DomQuery.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=false] True to return the DOM node instead of Ext.dom.Element + * @return {HTMLElement/Ext.dom.Element} The child Ext.dom.Element (or DOM node if returnDom = true) + */ + down: function(selector, returnDom) { + var n = Ext.DomQuery.selectNode(selector, this.dom); + return returnDom ? n : Ext.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=false] True to return the DOM node instead of Ext.dom.Element. + * @return {HTMLElement/Ext.dom.Element} The child Ext.dom.Element (or DOM node if returnDom = true) + */ + child: function(selector, returnDom) { + var node, + me = this, + id; + + // Pull the ID from the DOM (Ext.id also ensures that there *is* an ID). + // If this object is a Flyweight, it will not have an ID + id = Ext.id(me.dom); + // Escape . or : + id = id.replace(/[\.:]/g, "\\$0"); + node = Ext.DomQuery.selectNode('#' + id + " > " + selector, me.dom); + return returnDom ? node : Ext.get(node); + }, + + /** + * Gets the parent node for this element, optionally chaining up trying to match a selector + * @param {String} [selector] Find a parent node that matches the passed simple selector + * @param {Boolean} [returnDom=false] True to return a raw dom node instead of an Ext.dom.Element + * @return {Ext.dom.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] Find the next sibling that matches the passed simple selector + * @param {Boolean} [returnDom=false] True to return a raw dom node instead of an Ext.dom.Element + * @return {Ext.dom.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] Find the previous sibling that matches the passed simple selector + * @param {Boolean} [returnDom=false] True to return a raw dom node instead of an Ext.dom.Element + * @return {Ext.dom.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] Find the next sibling that matches the passed simple selector + * @param {Boolean} [returnDom=false] True to return a raw dom node instead of an Ext.dom.Element + * @return {Ext.dom.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] Find the previous sibling that matches the passed simple selector + * @param {Boolean} [returnDom=false] True to return a raw dom node instead of an Ext.dom.Element + * @return {Ext.dom.Element/HTMLElement} The last child or null + */ + last: function(selector, returnDom) { + return this.matchNode('previousSibling', 'lastChild', selector, returnDom); + }, + + matchNode: function(dir, start, selector, returnDom) { + if (!this.dom) { + return null; + } + + var n = this.dom[start]; + while (n) { + if (n.nodeType == 1 && (!selector || Ext.DomQuery.is(n, selector))) { + return !returnDom ? Ext.get(n) : n; + } + n = n[dir]; + } + return null; + }, + + isAncestor: function(element) { + return this.self.isAncestor.call(this.self, this.dom, element); + } +}); + +/** + * @class Ext.dom.Helper + * @extends Ext.dom.AbstractHelper + * @alternateClassName Ext.DomHelper + * @alternateClassName Ext.core.DomHelper + * @singleton + * + * 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: + * + * - **tag** - The tag name of the element. + * - **children** or **cn** - An array of the same kind of element definition objects to be created and appended. + * These can be nested as deep as you want. + * - **cls** - The class attribute of the element. This will end up being either the "class" attribute on a HTML + * fragment or className for a DOM node, depending on whether DomHelper is using fragments or DOM. + * - **html** - The innerHTML for the element. + * + * **NOTE:** For other arbitrary attributes, the value will currently **not** be automatically HTML-escaped prior to + * building the element's HTML string. This means that if your attribute value contains special characters that would + * not normally be allowed in a double-quoted attribute value, you **must** manually HTML-encode it beforehand (see + * {@link Ext.String#htmlEncode}) or risk malformed HTML being created. This behavior may change in a future release. + * + * # Insertion methods + * + * Commonly used insertion methods: + * + * - **{@link #append}** + * - **{@link #insertBefore}** + * - **{@link #insertAfter}** + * - **{@link #overwrite}** + * - **{@link #createTemplate}** + * - **{@link #insertHtml}** + * + * # 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.edspencer.net/', "Ed'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.edspencer.net/', + * text: "Ed'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 + * + */ +(function() { + +// kill repeat to save bytes +var afterbegin = 'afterbegin', + afterend = 'afterend', + beforebegin = 'beforebegin', + beforeend = 'beforeend', + ts = '', + te = '
    ', + tbs = ts+'', + tbe = ''+te, + trs = tbs + '', + tre = ''+tbe, + detachedDiv = document.createElement('div'), + bbValues = ['BeforeBegin', 'previousSibling'], + aeValues = ['AfterEnd', 'nextSibling'], + bb_ae_PositionHash = { + beforebegin: bbValues, + afterend: aeValues + }, + fullPositionHash = { + beforebegin: bbValues, + afterend: aeValues, + afterbegin: ['AfterBegin', 'firstChild'], + beforeend: ['BeforeEnd', 'lastChild'] + }; + +Ext.define('Ext.dom.Helper', { + extend: 'Ext.dom.AbstractHelper', + + tableRe: /^table|tbody|tr|td$/i, + + tableElRe: /td|tr|tbody/i, + + /** + * @property {Boolean} useDom + * True to force the use of DOM instead of html fragments. + */ + useDom : false, + + /** + * 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: function(o, parentNode){ + var el, + doc = document, + useSet, + attr, + val, + cn, + i, l; + + if (Ext.isArray(o)) { // Allow Arrays of siblings to be inserted + el = doc.createDocumentFragment(); // in one shot using a DocumentFragment + for (i = 0, l = o.length; i < l; i++) { + this.createDom(o[i], el); + } + } else if (typeof o == 'string') { // Allow a string as a child spec. + el = doc.createTextNode(o); + } else { + el = doc.createElement(o.tag || 'div'); + useSet = !!el.setAttribute; // In IE some elements don't have setAttribute + for (attr in o) { + if (!this.confRe.test(attr)) { + val = o[attr]; + if (attr == 'cls') { + el.className = val; + } else { + if (useSet) { + el.setAttribute(attr, val); + } else { + el[attr] = val; + } + } + } + } + Ext.DomHelper.applyStyles(el, o.style); + + if ((cn = o.children || o.cn)) { + this.createDom(cn, el); + } else if (o.html) { + el.innerHTML = o.html; + } + } + if (parentNode) { + parentNode.appendChild(el); + } + return el; + }, + + ieTable: function(depth, openingTags, htmlContent, closingTags){ + detachedDiv.innerHTML = [openingTags, htmlContent, closingTags].join(''); + + var i = -1, + el = detachedDiv, + ns; + + while (++i < depth) { + el = el.firstChild; + } + // If the result is multiple siblings, then encapsulate them into one fragment. + ns = el.nextSibling; + + if (ns) { + el = document.createDocumentFragment(); + while (ns) { + el.appendChild(ns); + ns = ns.nextSibling; + } + } + return el; + }, + + /** + * @private + * Nasty code for IE's broken table implementation + */ + insertIntoTable: function(tag, where, destinationEl, html) { + var node, + before, + bb = where == beforebegin, + ab = where == afterbegin, + be = where == beforeend, + ae = where == afterend; + + if (tag == 'td' && (ab || be) || !this.tableElRe.test(tag) && (bb || ae)) { + return null; + } + before = bb ? destinationEl : + ae ? destinationEl.nextSibling : + ab ? destinationEl.firstChild : null; + + if (bb || ae) { + destinationEl = destinationEl.parentNode; + } + + if (tag == 'td' || (tag == 'tr' && (be || ab))) { + node = this.ieTable(4, trs, html, tre); + } else if ((tag == 'tbody' && (be || ab)) || + (tag == 'tr' && (bb || ae))) { + node = this.ieTable(3, tbs, html, tbe); + } else { + node = this.ieTable(2, ts, html, te); + } + destinationEl.insertBefore(node, before); + return node; + }, + + /** + * @private + * Fix for IE9 createContextualFragment missing method + */ + createContextualFragment: function(html) { + var fragment = document.createDocumentFragment(), + length, childNodes; + + detachedDiv.innerHTML = html; + childNodes = detachedDiv.childNodes; + length = childNodes.length; + + // Move nodes into fragment, don't clone: http://jsperf.com/create-fragment + while (length--) { + fragment.appendChild(childNodes[0]); + } + return fragment; + }, + + applyStyles: function(el, styles) { + if (styles) { + el = Ext.fly(el); + if (typeof styles == "function") { + styles = styles.call(); + } + if (typeof styles == "string") { + styles = Ext.dom.Element.parseStyles(styles); + } + if (typeof styles == "object") { + el.setStyle(styles); + } + } + }, + + /** + * Alias for {@link #markup}. + * @inheritdoc Ext.dom.AbstractHelper#markup + */ + createHtml: function(spec) { + return this.markup(spec); + }, + + doInsert: function(el, o, returnElement, pos, sibling, append) { + + el = el.dom || Ext.getDom(el); + + var newNode; + + if (this.useDom) { + newNode = this.createDom(o, null); + + if (append) { + el.appendChild(newNode); + } + else { + (sibling == 'firstChild' ? el : el.parentNode).insertBefore(newNode, el[sibling] || el); + } + + } else { + newNode = this.insertHtml(pos, el, this.markup(o)); + } + return returnElement ? Ext.get(newNode, true) : newNode; + }, + + /** + * Creates new DOM element(s) and overwrites the contents of el with them. + * @param {String/HTMLElement/Ext.Element} el The context element + * @param {Object/String} o The DOM object spec (and children) or raw HTML blob + * @param {Boolean} [returnElement] true to return an Ext.Element + * @return {HTMLElement/Ext.Element} The new node + */ + overwrite: function(el, html, returnElement) { + var newNode; + + el = Ext.getDom(el); + html = this.markup(html); + + // IE Inserting HTML into a table/tbody/tr requires extra processing: http://www.ericvasilik.com/2006/07/code-karma.html + if (Ext.isIE && this.tableRe.test(el.tagName)) { + // Clearing table elements requires removal of all elements. + while (el.firstChild) { + el.removeChild(el.firstChild); + } + if (html) { + newNode = this.insertHtml('afterbegin', el, html); + return returnElement ? Ext.get(newNode) : newNode; + } + return null; + } + el.innerHTML = html; + return returnElement ? Ext.get(el.firstChild) : el.firstChild; + }, + + insertHtml: function(where, el, html) { + var hashVal, + range, + rangeEl, + setStart, + frag; + + where = where.toLowerCase(); + + // Has fast HTML insertion into existing DOM: http://www.w3.org/TR/html5/apis-in-html-documents.html#insertadjacenthtml + if (el.insertAdjacentHTML) { + + // IE's incomplete table implementation: http://www.ericvasilik.com/2006/07/code-karma.html + if (Ext.isIE && this.tableRe.test(el.tagName) && (frag = this.insertIntoTable(el.tagName.toLowerCase(), where, el, html))) { + return frag; + } + + if ((hashVal = fullPositionHash[where])) { + el.insertAdjacentHTML(hashVal[0], html); + return el[hashVal[1]]; + } + // if (not IE and context element is an HTMLElement) or TextNode + } else { + // we cannot insert anything inside a textnode so... + if (el.nodeType === 3) { + where = where === 'afterbegin' ? 'beforebegin' : where; + where = where === 'beforeend' ? 'afterend' : where; + } + range = Ext.supports.CreateContextualFragment ? el.ownerDocument.createRange() : undefined; + setStart = 'setStart' + (this.endRe.test(where) ? 'After' : 'Before'); + if (bb_ae_PositionHash[where]) { + if (range) { + range[setStart](el); + frag = range.createContextualFragment(html); + } else { + frag = this.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) { + if (range) { + range[setStart](el[rangeEl]); + frag = range.createContextualFragment(html); + } else { + frag = this.createContextualFragment(html); + } + + if (where == afterbegin) { + el.insertBefore(frag, el.firstChild); + } else { + el.appendChild(frag); + } + } else { + el.innerHTML = html; + } + return el[rangeEl]; + } + } + Ext.Error.raise({ + sourceClass: 'Ext.DomHelper', + sourceMethod: 'insertHtml', + htmlToInsert: html, + targetElement: el, + msg: 'Illegal insertion point reached: "' + where + '"' + }); + }, + + /** + * 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 = this.markup(o); + return new Ext.Template(html); + } + +}, function() { + Ext.ns('Ext.core'); + Ext.DomHelper = Ext.core.DomHelper = new this; +}); + + +}()); + +/* + * This is code is also distributed under MIT license for use + * with jQuery and prototype JavaScript libraries. + */ +/** + * @class Ext.dom.Query + * @alternateClassName Ext.DomQuery + * @alternateClassName Ext.core.DomQuery + * @singleton + * + * 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][1], 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: + * + * - **`*`** any element + * - **`E`** an element with the tag E + * - **`E F`** All descendent elements of E that have the tag F + * - **`E > F`** or **E/F** all direct children elements of E that have the tag F + * - **`E + F`** all elements with the tag F that are immediately preceded by an element with the tag E + * - **`E ~ F`** all elements with the tag F that are preceded by a sibling element with the tag E + * + * ## Attribute Selectors: + * + * The use of `@` and quotes are optional. For example, `div[@foo='bar']` is also a valid attribute selector. + * + * - **`E[foo]`** has an attribute "foo" + * - **`E[foo=bar]`** has an attribute "foo" that equals "bar" + * - **`E[foo^=bar]`** has an attribute "foo" that starts with "bar" + * - **`E[foo$=bar]`** has an attribute "foo" that ends with "bar" + * - **`E[foo*=bar]`** has an attribute "foo" that contains the substring "bar" + * - **`E[foo%=2]`** has an attribute "foo" that is evenly divisible by 2 + * - **`E[foo!=bar]`** attribute "foo" does not equal "bar" + * + * ## Pseudo Classes: + * + * - **`E:first-child`** E is the first child of its parent + * - **`E:last-child`** E is the last child of its parent + * - **`E:nth-child(_n_)`** E is the _n_th child of its parent (1 based as per the spec) + * - **`E:nth-child(odd)`** E is an odd child of its parent + * - **`E:nth-child(even)`** E is an even child of its parent + * - **`E:only-child`** E is the only child of its parent + * - **`E:checked`** E is an element that is has a checked attribute that is true (e.g. a radio or checkbox) + * - **`E:first`** the first E in the resultset + * - **`E:last`** the last E in the resultset + * - **`E:nth(_n_)`** the _n_th E in the resultset (1 based) + * - **`E:odd`** shortcut for :nth-child(odd) + * - **`E:even`** shortcut for :nth-child(even) + * - **`E:contains(foo)`** E's innerHTML contains the substring "foo" + * - **`E:nodeValue(foo)`** E contains a textNode with a nodeValue that equals "foo" + * - **`E:not(S)`** an E element that does not match simple selector S + * - **`E:has(S)`** an E element that has a descendent that matches simple selector S + * - **`E:next(S)`** an E element whose next sibling matches simple selector S + * - **`E:prev(S)`** an E element whose previous sibling matches simple selector S + * - **`E:any(S1|S2|S2)`** an E element which matches any of the simple selectors S1, S2 or S3 + * + * ## CSS Value Selectors: + * + * - **`E{display=none}`** css value "display" that equals "none" + * - **`E{display^=none}`** css value "display" that starts with "none" + * - **`E{display$=none}`** css value "display" that ends with "none" + * - **`E{display*=none}`** css value "display" that contains the substring "none" + * - **`E{display%=2}`** css value "display" that is evenly divisible by 2 + * - **`E{display!=none}`** css value "display" that does not equal "none" + * + * [1]: http://www.w3.org/TR/2005/WD-css3-selectors-20051215/#selectors + */ +Ext.ns('Ext.core'); + +Ext.dom.Query = Ext.core.DomQuery = 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/, + startIdRe = /^\s*\#/, + // This is for IE MSXML which does not support expandos. + // IE runs the same speed using setAttribute, however FF slows way down + // and Safari completely fails so they need to continue to use expandos. + isIE = window.ActiveXObject ? true : false, + key = 30803, + longHex = /\\([0-9a-fA-F]{6})/g, + shortHex = /\\([0-9a-fA-F]{1,6})\s{0,1}/g, + nonHex = /\\([^0-9a-fA-F]{1})/g, + escapes = /\\/g, + num, hasEscapes, + + // replaces a long hex regex match group with the appropriate ascii value + // $args indicate regex match pos + longHexToChar = function($0, $1) { + return String.fromCharCode(parseInt($1, 16)); + }, + + // converts a shortHex regex match to the long form + shortToLongHex = function($0, $1) { + while ($1.length < 6) { + $1 = '0' + $1; + } + return '\\' + $1; + }, + + // converts a single char escape to long escape form + charToLongHex = function($0, $1) { + num = $1.charCodeAt(0).toString(16); + if (num.length === 1) { + num = '0' + num; + } + return '\\0000' + num; + }, + + // Un-escapes an input selector string. Assumes all escape sequences have been + // normalized to the css '\\0000##' 6-hex-digit style escape sequence : + // will not handle any other escape formats + unescapeCssSelector = function (selector) { + return (hasEscapes) + ? selector.replace(longHex, longHexToChar) + : selector; + }; + + // this eval is stop the compressor from + // renaming the variable to something shorter + eval("var batch = 30803;"); + + // Retrieve the child node from a particular + // parent at the specified index. + function child(parent, index){ + var i = 0, + n = parent.firstChild; + while(n){ + if(n.nodeType == 1){ + if(++i == index){ + return n; + } + } + n = n.nextSibling; + } + return null; + } + + // retrieve the next element node + function next(n){ + while((n = n.nextSibling) && n.nodeType != 1); + return n; + } + + // retrieve the previous element node + function prev(n){ + while((n = n.previousSibling) && n.nodeType != 1); + return n; + } + + // Mark each child node with a nodeIndex skipping and + // removing empty text nodes. + function children(parent){ + var n = parent.firstChild, + nodeIndex = -1, + nextNode; + while(n){ + nextNode = n.nextSibling; + // clean worthless empty nodes. + if(n.nodeType == 3 && !nonSpace.test(n.nodeValue)){ + parent.removeChild(n); + }else{ + // add an expando nodeIndex + n.nodeIndex = ++nodeIndex; + } + n = nextNode; + } + return this; + } + + // nodeSet - array of nodes + // cls - CSS Class + function byClassName(nodeSet, cls){ + cls = unescapeCssSelector(cls); + if(!cls){ + return nodeSet; + } + var result = [], ri = -1, + i, ci; + for(i = 0, ci; ci = nodeSet[i]; i++){ + if((' '+ci.className+' ').indexOf(cls) != -1){ + result[++ri] = ci; + } + } + return result; + } + + function attrValue(n, attr){ + // if its an array, use the first node. + if(!n.tagName && typeof n.length != "undefined"){ + n = n[0]; + } + if(!n){ + return null; + } + + if(attr == "for"){ + return n.htmlFor; + } + if(attr == "class" || attr == "className"){ + return n.className; + } + return n.getAttribute(attr) || n[attr]; + + } + + + // ns - nodes + // mode - false, /, >, +, ~ + // tagName - defaults to "*" + function getNodes(ns, mode, tagName){ + var result = [], ri = -1, cs, + i, ni, j, ci, cn, utag, n, cj; + if(!ns){ + return result; + } + tagName = tagName || "*"; + // convert to array + if(typeof ns.getElementsByTagName != "undefined"){ + ns = [ns]; + } + + // no mode specified, grab all elements by tagName + // at any depth + if(!mode){ + for(i = 0, ni; ni = ns[i]; i++){ + cs = ni.getElementsByTagName(tagName); + for(j = 0, ci; ci = cs[j]; j++){ + result[++ri] = ci; + } + } + // Direct Child mode (/ or >) + // E > F or E/F all direct children elements of E that have the tag + } else if(mode == "/" || mode == ">"){ + utag = tagName.toUpperCase(); + for(i = 0, ni, cn; ni = ns[i]; i++){ + cn = ni.childNodes; + for(j = 0, cj; cj = cn[j]; j++){ + if(cj.nodeName == utag || cj.nodeName == tagName || tagName == '*'){ + result[++ri] = cj; + } + } + } + // Immediately Preceding mode (+) + // E + F all elements with the tag F that are immediately preceded by an element with the tag E + }else if(mode == "+"){ + utag = tagName.toUpperCase(); + for(i = 0, n; n = ns[i]; i++){ + while((n = n.nextSibling) && n.nodeType != 1); + if(n && (n.nodeName == utag || n.nodeName == tagName || tagName == '*')){ + result[++ri] = n; + } + } + // Sibling mode (~) + // E ~ F all elements with the tag F that are preceded by a sibling element with the tag E + }else if(mode == "~"){ + utag = tagName.toUpperCase(); + for(i = 0, n; n = ns[i]; i++){ + while((n = n.nextSibling)){ + if (n.nodeName == utag || n.nodeName == tagName || tagName == '*'){ + result[++ri] = n; + } + } + } + } + return result; + } + + function concat(a, b){ + if(b.slice){ + return a.concat(b); + } + for(var i = 0, l = b.length; i < l; i++){ + a[a.length] = b[i]; + } + return a; + } + + function byTag(cs, tagName){ + if(cs.tagName || cs == document){ + cs = [cs]; + } + if(!tagName){ + return cs; + } + var result = [], ri = -1, + i, ci; + tagName = tagName.toLowerCase(); + for(i = 0, ci; ci = cs[i]; i++){ + if(ci.nodeType == 1 && ci.tagName.toLowerCase() == tagName){ + result[++ri] = ci; + } + } + return result; + } + + function byId(cs, id){ + id = unescapeCssSelector(id); + if(cs.tagName || cs == document){ + cs = [cs]; + } + if(!id){ + return cs; + } + var result = [], ri = -1, + i, ci; + for(i = 0, ci; ci = cs[i]; i++){ + if(ci && ci.id == id){ + result[++ri] = ci; + return result; + } + } + return result; + } + + // operators are =, !=, ^=, $=, *=, %=, |= and ~= + // custom can be "{" + function byAttribute(cs, attr, value, op, custom){ + var result = [], + ri = -1, + useGetStyle = custom == "{", + fn = Ext.DomQuery.operators[op], + a, + xml, + hasXml, + i, ci; + + value = unescapeCssSelector(value); + + for(i = 0, ci; ci = cs[i]; i++){ + // skip non-element nodes. + if(ci.nodeType != 1){ + continue; + } + // only need to do this for the first node + if(!hasXml){ + xml = Ext.DomQuery.isXml(ci); + hasXml = true; + } + + // we only need to change the property names if we're dealing with html nodes, not XML + 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"){ + // getAttribute href bug + // http://www.glennjones.net/Post/809/getAttributehrefbug.htm + a = ci.getAttribute("href", 2); + } else{ + a = ci.getAttribute(attr); + } + }else{ + a = ci.getAttribute(attr); + } + if((fn && fn(a, value)) || (!fn && a)){ + result[++ri] = ci; + } + } + return result; + } + + function byPseudo(cs, name, value){ + value = unescapeCssSelector(value); + return Ext.DomQuery.pseudos[name](cs, value); + } + + function nodupIEXml(cs){ + var d = ++key, + r, + i, len, c; + cs[0].setAttribute("_nodup", d); + r = [cs[0]]; + for(i = 1, len = cs.length; i < len; i++){ + c = cs[i]; + if(!c.getAttribute("_nodup") != d){ + c.setAttribute("_nodup", d); + r[r.length] = c; + } + } + for(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, d, j; + if(!len || typeof cs.nodeType != "undefined" || len == 1){ + return cs; + } + if(isIE && typeof cs[0].selectSingleNode != "undefined"){ + return nodupIEXml(cs); + } + d = ++key; + cs[0]._nodup = d; + for(i = 1; c = cs[i]; i++){ + if(c._nodup != d){ + c._nodup = d; + }else{ + r = []; + for(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 = [], + i, len; + for(i = 0, len = c1.length; i < len; i++){ + c1[i].setAttribute("_qdiff", d); + } + for(i = 0, len = c2.length; i < len; i++){ + if(c2[i].getAttribute("_qdiff") != d){ + r[r.length] = c2[i]; + } + } + for(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 = [], + i, len; + if(!len1){ + return c2; + } + if(isIE && typeof c1[0].selectSingleNode != "undefined"){ + return quickDiffIEXml(c1, c2); + } + for(i = 0; i < len1; i++){ + c1[i]._qdiff = d; + } + for(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){ + id = unescapeCssSelector(id); + var d = root.ownerDocument || root; + return d.getElementById(id); + } + ns = getNodes(ns, mode, "*"); + return byId(ns, id); + } + + return { + getStyle : function(el, name){ + return Ext.fly(el).getStyle(name); + }, + /** + * Compiles a selector/xpath query into a reusable function. The returned function + * takes one parameter "root" (optional), which is the context node from where the query should start. + * @param {String} selector The selector/xpath query + * @param {String} [type="select"] Either "select" or "simple" for a simple selector match + * @return {Function} + */ + compile : function(path, type){ + type = type || "select"; + + // setup fn preamble + var fn = ["var f = function(root){\n var mode; ++batch; var n = root || document;\n"], + mode, + lastPath, + matchers = Ext.DomQuery.matchers, + matchersLn = matchers.length, + modeMatch, + // accept leading mode switch + lmode = path.match(modeRe), + tokenMatch, matched, j, t, m; + + hasEscapes = (path.indexOf('\\') > -1); + if (hasEscapes) { + path = path + .replace(shortHex, shortToLongHex) + .replace(nonHex, charToLongHex) + .replace(escapes, '\\\\'); // double the '\' for js compilation + } + + if(lmode && lmode[1]){ + fn[fn.length] = 'mode="'+lmode[1].replace(trimRe, "")+'";'; + path = path.replace(lmode[1], ""); + } + + // strip leading slashes + while(path.substr(0, 1)=="/"){ + path = path.substr(1); + } + + while(path && lastPath != path){ + lastPath = path; + tokenMatch = path.match(tagTokenRe); + if(type == "select"){ + if(tokenMatch){ + // ID Selector + if(tokenMatch[1] == "#"){ + fn[fn.length] = 'n = quickId(n, mode, root, "'+tokenMatch[2]+'");'; + }else{ + fn[fn.length] = 'n = getNodes(n, mode, "'+tokenMatch[2]+'");'; + } + path = path.replace(tokenMatch[0], ""); + }else if(path.substr(0, 1) != '@'){ + fn[fn.length] = 'n = getNodes(n, mode, "*");'; + } + // type of "simple" + }else{ + if(tokenMatch){ + if(tokenMatch[1] == "#"){ + fn[fn.length] = 'n = byId(n, "'+tokenMatch[2]+'");'; + }else{ + fn[fn.length] = 'n = byTag(n, "'+tokenMatch[2]+'");'; + } + path = path.replace(tokenMatch[0], ""); + } + } + while(!(modeMatch = path.match(modeRe))){ + matched = false; + for(j = 0; j < matchersLn; j++){ + t = matchers[j]; + m = path.match(t.re); + if(m){ + fn[fn.length] = t.select.replace(tplRe, function(x, i){ + return m[i]; + }); + path = path.replace(m[0], ""); + matched = true; + break; + } + } + // prevent infinite loop on bad selector + if(!matched){ + Ext.Error.raise({ + sourceClass: 'Ext.DomQuery', + sourceMethod: 'compile', + msg: 'Error parsing selector. Parsing failed at "' + path + '"' + }); + } + } + if(modeMatch[1]){ + fn[fn.length] = 'mode="'+modeMatch[1].replace(trimRe, "")+'";'; + path = path.replace(modeMatch[1], ""); + } + } + // close fn out + fn[fn.length] = "return nodup(n);\n}"; + + // eval fn and return it + eval(fn.join("")); + return f; + }, + + /** + * Selects an array of DOM nodes using JavaScript-only implementation. + * + * Use {@link #select} to take advantage of browsers built-in support for CSS selectors. + * @param {String} selector The selector/xpath query (can be a comma separated list of selectors) + * @param {HTMLElement/String} [root=document] The start of the query. + * @return {HTMLElement[]} An Array of DOM elements which match the selector. If there are + * no matches, and empty Array is returned. + */ + jsSelect: function(path, root, type){ + // set root to doc if not specified. + root = root || document; + + if(typeof root == "string"){ + root = document.getElementById(root); + } + var paths = path.split(","), + results = [], + i, len, subPath, result; + + // loop over each selector + for(i = 0, len = paths.length; i < len; i++){ + subPath = paths[i].replace(trimRe, ""); + // compile and place in cache + if(!cache[subPath]){ + cache[subPath] = Ext.DomQuery.compile(subPath, type); + if(!cache[subPath]){ + Ext.Error.raise({ + sourceClass: 'Ext.DomQuery', + sourceMethod: 'jsSelect', + msg: subPath + ' is not a valid selector' + }); + } + } + result = cache[subPath](root); + if(result && result != document){ + results = results.concat(result); + } + } + + // if there were multiple selectors, make sure dups + // are eliminated + if(paths.length > 1){ + return nodup(results); + } + return results; + }, + + isXml: function(el) { + var docEl = (el ? el.ownerDocument || el : 0).documentElement; + return docEl ? docEl.nodeName !== "HTML" : false; + }, + + /** + * Selects an array of DOM nodes by CSS/XPath selector. + * + * Uses [document.querySelectorAll][0] if browser supports that, otherwise falls back to + * {@link Ext.dom.Query#jsSelect} to do the work. + * + * Aliased as {@link Ext#query}. + * + * [0]: https://developer.mozilla.org/en/DOM/document.querySelectorAll + * + * @param {String} path The selector/xpath query + * @param {HTMLElement} [root=document] The start of the query. + * @return {HTMLElement[]} An array of DOM elements (not a NodeList as returned by `querySelectorAll`). + * @param {String} [type="select"] Either "select" or "simple" for a simple selector match (only valid when + * used when the call is deferred to the jsSelect method) + * @method + */ + select : document.querySelectorAll ? function(path, root, type) { + root = root || document; + if (!Ext.DomQuery.isXml(root)) { + try { + /* + * This checking here is to "fix" the behaviour of querySelectorAll + * for non root document queries. The way qsa works is intentional, + * however it's definitely not the expected way it should work. + * When descendant selectors are used, only the lowest selector must be inside the root! + * More info: http://ejohn.org/blog/thoughts-on-queryselectorall/ + * So we create a descendant selector by prepending the root's ID, and query the parent node. + * UNLESS the root has no parent in which qsa will work perfectly. + * + * We only modify the path for single selectors (ie, no multiples), + * without a full parser it makes it difficult to do this correctly. + */ + if (root.parentNode && (root.nodeType !== 9) && path.indexOf(',') === -1 && !startIdRe.test(path)) { + path = '#' + Ext.escapeId(Ext.id(root)) + ' ' + path; + root = root.parentNode; + } + return Ext.Array.toArray(root.querySelectorAll(path)); + } + catch (e) { + } + } + return Ext.DomQuery.jsSelect.call(this, path, root, type); + } : function(path, root, type) { + return Ext.DomQuery.jsSelect.call(this, path, root, type); + }, + + /** + * Selects a single element. + * @param {String} selector The selector/xpath query + * @param {HTMLElement} [root=document] The start of the query. + * @return {HTMLElement} 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 {HTMLElement} [root=document] The start of the query. + * @param {String} [defaultValue] When specified, this is return as empty value. + * @return {String} + */ + selectValue : function(path, root, defaultValue){ + path = path.replace(trimRe, ""); + if(!valueCache[path]){ + valueCache[path] = Ext.DomQuery.compile(path, "select"); + } + var n = valueCache[path](root), v; + n = n[0] ? n[0] : n; + + // overcome a limitation of maximum textnode size + // Rumored to potentially crash IE6 but has not been confirmed. + // http://reference.sitepoint.com/javascript/Node/normalize + // https://developer.mozilla.org/En/DOM/Node.normalize + if (typeof n.normalize == 'function') { + n.normalize(); + } + + v = (n && n.firstChild ? n.firstChild.nodeValue : null); + return ((v === null||v === undefined||v==='') ? defaultValue : v); + }, + + /** + * Selects the value of a node, parsing integers and floats. + * Returns the defaultValue, or 0 if none is specified. + * @param {String} selector The selector/xpath query + * @param {HTMLElement} [root=document] The start of the query. + * @param {Number} [defaultValue] When specified, this is return as empty value. + * @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/HTMLElement[]} 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 {HTMLElement[]} 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 {HTMLElement[]} An Array of DOM elements which match the selector. If there are no matches, and empty + * Array is returned. + */ + filter : function(els, ss, nonMatches){ + ss = ss.replace(trimRe, ""); + if(!simpleCache[ss]){ + simpleCache[ss] = Ext.DomQuery.compile(ss, "simple"); + } + var result = simpleCache[ss](els); + return nonMatches ? quickDiff(result, els) : result; + }, + + /** + * Collection of matching regular expressions and code snippets. + * Each capture group within `()` will be replace the `{}` in the select + * statement as specified by their index. + */ + matchers : [{ + re: /^\.([\w\-\\]+)/, + select: 'n = byClassName(n, " {1} ");' + }, { + re: /^\:([\w\-]+)(?:\(((?:[^\s>\/]*|.*?))\))?/, + select: 'n = byPseudo(n, "{1}", "{2}");' + },{ + re: /^(?:([\[\{])(?:@)?([\w\-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]\}])/, + select: 'n = byAttribute(n, "{2}", "{4}", "{3}", "{1}");' + }, { + re: /^#([\w\-\\]+)/, + select: 'n = byId(n, "{1}");' + },{ + re: /^@([\w\-]+)/, + select: 'return {firstChild:{nodeValue:attrValue(n, "{1}")}};' + } + ], + + /** + * Collection of operator comparison functions. + * The default operators are `=`, `!=`, `^=`, `$=`, `*=`, `%=`, `|=` and `~=`. + * New operators can be added as long as the match the format *c*`=` where *c* + * is any character other than space, `>`, or `<`. + */ + 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: + * + * - **c** : Array + * An Array of DOM elements to filter. + * + * - **v** : String + * The argument (if any) supplied in the selector. + * + * 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, + i, ci; + for(i = 0; (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, + i, ci; + for(i = 0; (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, + i, n, j, cn, pn; + for(i = 0; n = c[i]; i++){ + pn = n.parentNode; + if (batch != pn._batch) { + j = 0; + for(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, + i, ci; + for(i = 0; ci = c[i]; i++){ + if(!prev(ci) && !next(ci)){ + r[++ri] = ci; + } + } + return r; + }, + + "empty" : function(c){ + var r = [], ri = -1, + i, ci, cns, j, cn, empty; + for(i = 0, ci; ci = c[i]; i++){ + cns = ci.childNodes; + j = 0; + 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, + i, ci; + for(i = 0; ci = c[i]; i++){ + if((ci.textContent||ci.innerText||ci.text||'').indexOf(v) != -1){ + r[++ri] = ci; + } + } + return r; + }, + + "nodeValue" : function(c, v){ + var r = [], ri = -1, + i, ci; + for(i = 0; ci = c[i]; i++){ + if(ci.firstChild && ci.firstChild.nodeValue == v){ + r[++ri] = ci; + } + } + return r; + }, + + "checked" : function(c){ + var r = [], ri = -1, + i, ci; + for(i = 0; 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, + i, ci, j; + for(i = 0; ci = c[i]; i++){ + for(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, + i, ci; + for(i = 0; 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, + i, ci, n; + for(i = 0; ci = c[i]; i++){ + 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, + i, ci, n; + for(i = 0; ci = c[i]; i++){ + n = prev(ci); + if(n && is(n, ss)){ + r[++ri] = ci; + } + } + return r; + } + } + }; +}()); + +/** + * Shorthand of {@link Ext.dom.Query#select} + * @member Ext + * @method query + * @inheritdoc Ext.dom.Query#select + */ +Ext.query = Ext.DomQuery.select; + + +/** + * @class Ext.dom.Element + * @alternateClassName Ext.Element + * @alternateClassName Ext.core.Element + * @extend Ext.dom.AbstractElement + * + * 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.Anim} 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. Some older browsers + * may not support the full range of events. Which events are supported is beyond the control of Ext JS. + * + * 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.Anim} animation options specific to Fx effects. The supported Element animation configuration options + * are: + * + * Option Default Description + * --------- -------- --------------------------------------------- + * {@link Ext.fx.Anim#duration duration} .35 The duration of the animation in seconds + * {@link Ext.fx.Anim#easing easing} easeOut The easing method + * {@link Ext.fx.Anim#callback callback} none A function to execute when the anim completes + * {@link Ext.fx.Anim#scope scope} this The scope (this) of the callback function + * + * Usage: + * + * // Element animation options object + * var opt = { + * {@link Ext.fx.Anim#duration duration}: 1, + * {@link Ext.fx.Anim#easing easing}: 'elasticIn', + * {@link Ext.fx.Anim#callback callback}: this.foo, + * {@link Ext.fx.Anim#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(); + * } + * + * # Composite (Collections of) Elements + * + * For working with collections of Elements, see {@link Ext.CompositeElement} + * + * @constructor + * Creates new Element directly. + * @param {String/HTMLElement} element + * @param {Boolean} [forceNew] 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). + * @return {Object} + */ +(function() { + +var HIDDEN = 'hidden', + DOC = document, + VISIBILITY = "visibility", + DISPLAY = "display", + NONE = "none", + XMASKED = Ext.baseCSSPrefix + "masked", + XMASKEDRELATIVE = Ext.baseCSSPrefix + "masked-relative", + EXTELMASKMSG = Ext.baseCSSPrefix + "mask-msg", + bodyRe = /^body/i, + visFly, + + // speedy lookup for elements never to box adjust + noBoxAdjust = Ext.isStrict ? { + select: 1 + }: { + input: 1, + select: 1, + textarea: 1 + }, + + // Pseudo for use by cacheScrollValues + isScrolled = function(c) { + var r = [], ri = -1, + i, ci; + for (i = 0; ci = c[i]; i++) { + if (ci.scrollTop > 0 || ci.scrollLeft > 0) { + r[++ri] = ci; + } + } + return r; + }, + + Element = Ext.define('Ext.dom.Element', { + + extend: 'Ext.dom.AbstractElement', + + alternateClassName: ['Ext.Element', 'Ext.core.Element'], + + addUnits: function() { + return this.self.addUnits.apply(this.self, arguments); + }, + + /** + * Tries to focus the element. Any exceptions are caught and ignored. + * @param {Number} [defer] Milliseconds to defer the focus + * @return {Ext.dom.Element} this + */ + focus: function(defer, /* private */ dom) { + var me = this, + scrollTop, + body; + + dom = dom || me.dom; + body = (dom.ownerDocument || DOC).body || DOC.body; + try { + if (Number(defer)) { + Ext.defer(me.focus, defer, me, [null, dom]); + } else { + // Focusing a large element, the browser attempts to scroll as much of it into view + // as possible. We need to override this behaviour. + if (dom.offsetHeight > Element.getViewHeight()) { + scrollTop = body.scrollTop; + } + dom.focus(); + if (scrollTop !== undefined) { + body.scrollTop = scrollTop; + } + } + } catch(e) { + } + return me; + }, + + /** + * Tries to blur the element. Any exceptions are caught and ignored. + * @return {Ext.dom.Element} this + */ + blur: function() { + try { + this.dom.blur(); + } catch(e) { + } + return this; + }, + + /** + * Tests various css rules/browsers to determine if this element uses a border box + * @return {Boolean} + */ + isBorderBox: function() { + var box = Ext.isBorderBox; + if (box) { + box = !((this.dom.tagName || "").toLowerCase() in noBoxAdjust); + } + return box; + }, + + /** + * 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] The scope (`this` reference) in which the functions are executed. Defaults + * to the Element's DOM element. + * @param {Object} [options] Options for the listener. See {@link Ext.util.Observable#addListener the + * options parameter}. + * @return {Ext.dom.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 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 + */ + getAttributeNS: function(ns, name) { + return this.getAttribute(name, ns); + }, + + getAttribute: (Ext.isIE && !(Ext.isIE9 && DOC.documentMode === 9)) ? + function(name, ns) { + var d = this.dom, + type; + if (ns) { + type = typeof d[ns + ":" + name]; + if (type != 'undefined' && type != 'unknown') { + return d[ns + ":" + name] || null; + } + return null; + } + if (name === "for") { + name = "htmlFor"; + } + return d[name] || null; + } : function(name, ns) { + var d = this.dom; + if (ns) { + return d.getAttributeNS(ns, name) || d.getAttribute(ns + ":" + name); + } + return d.getAttribute(name) || d[name] || null; + }, + + /** + * When an element is moved around in the DOM, or is hidden using `display:none`, it loses layout, and therefore + * all scroll positions of all descendant elements are lost. + * + * This function caches them, and returns a function, which when run will restore the cached positions. + * In the following example, the Panel is moved from one Container to another which will cause it to lose all scroll positions: + * + * var restoreScroll = myPanel.el.cacheScrollValues(); + * myOtherContainer.add(myPanel); + * restoreScroll(); + * + * @return {Function} A function which will restore all descentant elements of this Element to their scroll + * positions recorded when this function was executed. Be aware that the returned function is a closure which has + * captured the scope of `cacheScrollValues`, so take care to derefence it as soon as not needed - if is it is a `var` + * it will drop out of scope, and the reference will be freed. + */ + cacheScrollValues: function() { + var me = this, + scrolledDescendants, + el, i, + scrollValues = [], + result = function() { + for (i = 0; i < scrolledDescendants.length; i++) { + el = scrolledDescendants[i]; + el.scrollLeft = scrollValues[i][0]; + el.scrollTop = scrollValues[i][1]; + } + }; + + if (!Ext.DomQuery.pseudos.isScrolled) { + Ext.DomQuery.pseudos.isScrolled = isScrolled; + } + scrolledDescendants = me.query(':isScrolled'); + for (i = 0; i < scrolledDescendants.length; i++) { + el = scrolledDescendants[i]; + scrollValues[i] = [el.scrollLeft, el.scrollTop]; + } + return result; + }, + + /** + * @property {Boolean} autoBoxAdjust + * True to automatically adjust width and height settings for box-model issues. + */ + autoBoxAdjust: true, + + /** + * Checks whether the element is currently visible using both visibility and display properties. + * @param {Boolean} [deep=false] True to walk the dom and see if parent elements are hidden. + * If false, the function only checks the visibility of the element itself and it may return + * `true` even though a parent is not visible. + * @return {Boolean} `true` if the element is currently visible, else `false` + */ + isVisible : function(deep) { + var me = this, + dom = me.dom, + stopNode = dom.ownerDocument.documentElement; + + if (!visFly) { + visFly = new Element.Fly(); + } + + while (dom !== stopNode) { + // We're invisible if we hit a nonexistent parentNode or a document + // fragment or computed style visibility:hidden or display:none + if (!dom || dom.nodeType === 11 || (visFly.attach(dom)).isStyle(VISIBILITY, HIDDEN) || visFly.isStyle(DISPLAY, NONE)) { + return false; + } + // Quit now unless we are being asked to check parent nodes. + if (!deep) { + break; + } + dom = dom.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] What to set display to when visible + * @return {Ext.dom.Element} this + */ + enableDisplayMode : function(display) { + var me = this; + + me.setVisibilityMode(Element.DISPLAY); + + if (!Ext.isEmpty(display)) { + (me.$cache || me.getCache()).data.originalDisplay = display; + } + + return me; + }, + + /** + * 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] A message to display in the mask + * @param {String} [msgCls] A css class to apply to the msg element + * @return {Ext.dom.Element} The mask element + */ + mask : function(msg, msgCls /* private - passed by AbstractComponent.mask to avoid the need to interrogate the DOM to get the height*/, elHeight) { + var me = this, + dom = me.dom, + setExpression = dom.style.setExpression, + data = (me.$cache || me.getCache()).data, + maskEl = data.maskEl, + maskMsg = data.maskMsg; + + if (!(bodyRe.test(dom.tagName) && me.getStyle('position') == 'static')) { + me.addCls(XMASKEDRELATIVE); + } + + // We always needs to recreate the mask since the DOM element may have been re-created + if (maskEl) { + maskEl.remove(); + } + + if (maskMsg) { + maskMsg.remove(); + } + + Ext.DomHelper.append(dom, [{ + cls : Ext.baseCSSPrefix + "mask" + }, { + cls : msgCls ? EXTELMASKMSG + " " + msgCls : EXTELMASKMSG, + cn : { + tag: 'div', + html: msg || '' + } + }]); + + maskMsg = Ext.get(dom.lastChild); + maskEl = Ext.get(maskMsg.dom.previousSibling); + data.maskMsg = maskMsg; + data.maskEl = maskEl; + + me.addCls(XMASKED); + maskEl.setDisplayed(true); + + if (typeof msg == 'string') { + maskMsg.setDisplayed(true); + maskMsg.center(me); + } else { + maskMsg.setDisplayed(false); + } + // NOTE: CSS expressions are resource intensive and to be used only as a last resort + // These expressions are removed as soon as they are no longer necessary - in the unmask method. + // In normal use cases an element will be masked for a limited period of time. + // Fix for https://sencha.jira.com/browse/EXTJSIV-19. + // IE6 strict mode and IE6-9 quirks mode takes off left+right padding when calculating width! + if (!Ext.supports.IncludePaddingInWidthCalculation && setExpression) { + maskEl.dom.style.setExpression('width', 'this.parentNode.clientWidth + "px"'); + } + + // Some versions and modes of IE subtract top+bottom padding when calculating height. + // Different versions from those which make the same error for width! + if (!Ext.supports.IncludePaddingInHeightCalculation && setExpression) { + maskEl.dom.style.setExpression('height', 'this.parentNode.' + (dom == DOC.body ? 'scrollHeight' : 'offsetHeight') + ' + "px"'); + } + // ie will not expand full height automatically + else if (Ext.isIE && !(Ext.isIE7 && Ext.isStrict) && me.getStyle('height') == 'auto') { + maskEl.setSize(undefined, elHeight || me.getHeight()); + } + return maskEl; + }, + + /** + * Hides a previously applied mask. + */ + unmask : function() { + var me = this, + data = (me.$cache || me.getCache()).data, + maskEl = data.maskEl, + maskMsg = data.maskMsg, + style; + + if (maskEl) { + style = maskEl.dom.style; + // Remove resource-intensive CSS expressions as soon as they are not required. + if (style.clearExpression) { + style.clearExpression('width'); + style.clearExpression('height'); + } + + if (maskEl) { + maskEl.remove(); + delete data.maskEl; + } + + if (maskMsg) { + maskMsg.remove(); + delete data.maskMsg; + } + + me.removeCls([XMASKED, XMASKEDRELATIVE]); + } + }, + + /** + * Returns true if this element is masked. Also re-centers any displayed message within the mask. + * @return {Boolean} + */ + isMasked : function() { + var me = this, + data = (me.$cache || me.getCache()).data, + maskEl = data.maskEl, + maskMsg = data.maskMsg, + hasMask = false; + + if (maskEl && maskEl.isVisible()) { + if (maskMsg) { + maskMsg.center(me); + } + hasMask = true; + } + return hasMask; + }, + + /** + * Creates an iframe shim for this element to keep selects and other windowed objects from + * showing through. + * @return {Ext.dom.Element} The new shim element + */ + createShim : function() { + var el = DOC.createElement('iframe'), + shim; + + el.frameBorder = '0'; + el.className = Ext.baseCSSPrefix + 'shim'; + el.src = Ext.SSL_SECURE_URL; + shim = Ext.get(this.dom.parentNode.insertBefore(el, this.dom)); + shim.autoBoxAdjust = false; + return shim; + }, + + /** + * Convenience method for constructing a KeyMap + * @param {String/Number/Number[]/Object} 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: + * @param {Number/Array} key.key + * @param {Boolean} key.shift + * @param {Boolean} key.ctrl + * @param {Boolean} key.alt + * @param {Function} fn The function to call + * @param {Object} [scope] The scope (`this` reference) in which the specified function is executed. Defaults to this Element. + * @return {Ext.util.KeyMap} The KeyMap created + */ + addKeyListener : function(key, fn, scope){ + var config; + if(typeof key != 'object' || Ext.isArray(key)){ + config = { + target: this, + key: key, + fn: fn, + scope: scope + }; + }else{ + config = { + target: this, + key : key.key, + shift : key.shift, + ctrl : key.ctrl, + alt : key.alt, + fn: fn, + scope: scope + }; + } + return new Ext.util.KeyMap(config); + }, + + /** + * Creates a KeyMap for this element + * @param {Object} config The KeyMap config. See {@link Ext.util.KeyMap} for more details + * @return {Ext.util.KeyMap} The KeyMap created + */ + addKeyMap : function(config) { + return new Ext.util.KeyMap(Ext.apply({ + target: this + }, config)); + }, + + // 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. + */ + /** + * @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. + */ + /** + * @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. + */ + /** + * @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. + */ + /** + * @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. + */ + /** + * @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. + */ + /** + * @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. + */ + /** + * @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. + */ + /** + * @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. + */ + /** + * @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. + */ + + // 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. + */ + /** + * @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. + */ + /** + * @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. + */ + + // 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. + */ + /** + * @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. + */ + /** + * @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. + */ + /** + * @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. + */ + /** + * @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. + */ + /** + * @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. + */ + + // 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. + */ + /** + * @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. + */ + /** + * @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. + */ + /** + * @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. + */ + /** + * @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. + */ + /** + * @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. + */ + + // 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. + */ + /** + * @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. + */ + /** + * @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. + */ + + // 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. + */ + /** + * @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. + */ + /** + * @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. + */ + /** + * @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. + */ + /** + * @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. + */ + /** + * @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. + */ + /** + * @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. + */ + + /** + * Appends an event handler to this element. + * + * @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: + * + * - **evt** : EventObject + * + * The {@link Ext.EventObject EventObject} describing the event. + * + * - **el** : HtmlElement + * + * The DOM element which was the target of the event. Note that this may be filtered by using the delegate option. + * + * - **o** : Object + * + * The options object from the call that setup the listener. + * + * @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: + * + * - **scope** Object : + * + * The scope (**this** reference) in which the handler function is executed. **If omitted, defaults to this + * Element.** + * + * - **delegate** String: + * + * A simple selector to filter the target or look for a descendant of the target. See below for additional details. + * + * - **stopEvent** Boolean: + * + * True to stop the event. That is stop propagation, and prevent the default action. + * + * - **preventDefault** Boolean: + * + * True to prevent the default action + * + * - **stopPropagation** Boolean: + * + * True to prevent event propagation + * + * - **normalized** Boolean: + * + * False to pass a browser event to the handler function instead of an Ext.EventObject + * + * - **target** Ext.dom.Element: + * + * Only call the handler if the event was fired on the target Element, _not_ if the event was bubbled up from a + * child node. + * + * - **delay** Number: + * + * The number of milliseconds to delay the invocation of the handler after the event fires. + * + * - **single** Boolean: + * + * True to add a handler to handle just the next firing of the event, and then remove itself. + * + * - **buffer** Number: + * + * Causes the handler to be scheduled to run in an {@link Ext.util.DelayedTask} delayed by the specified number of + * milliseconds. If the event fires again within that time, the original handler is _not_ invoked, but the new + * handler is scheduled in its place. + * + * **Combining Options** + * + * 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: + *
    + *

    paragraph one

    + *

    paragraph two

    + *

    paragraph three

    + *
    + * + * // 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.dom.Element} this + */ + on: function(eventName, fn, scope, options) { + Ext.EventManager.on(this, eventName, fn, scope || this, options); + return this; + }, + + /** + * Removes an event handler from this element. + * + * **Note**: if a *scope* was explicitly specified when {@link #on adding} the listener, + * the same scope must be specified here. + * + * Example: + * + * el.un('click', this.handlerFn); + * // or + * el.removeListener('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 #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. + * @return {Ext.dom.Element} this + */ + un: function(eventName, fn, scope) { + Ext.EventManager.un(this, eventName, fn, scope || this); + return this; + }, + + /** + * Removes all previous added listeners from this element + * @return {Ext.dom.Element} this + */ + removeAllListeners: function() { + Ext.EventManager.removeAll(this); + return this; + }, + + /** + * Recursively removes all previous added listeners from this element and its children + * @return {Ext.dom.Element} this + */ + purgeAllListeners: function() { + Ext.EventManager.purgeElement(this); + return this; + } + +}, function() { + + var EC = Ext.cache, + El = this, + AbstractElement = Ext.dom.AbstractElement, + focusRe = /a|button|embed|iframe|img|input|object|select|textarea/i, + nonSpaceRe = /\S/, + scriptTagRe = /(?:]*)?>)((\n|\r|.)*?)(?:<\/script>)/ig, + replaceScriptTagRe = /(?:)((\n|\r|.)*?)(?:<\/script>)/ig, + srcRe = /\ssrc=([\'\"])(.*?)\1/i, + typeRe = /\stype=([\'\"])(.*?)\1/i, + useDocForId = !(Ext.isIE6 || Ext.isIE7 || Ext.isIE8); + + El.boxMarkup = '
    '; + // + + // private + // Garbage collection - uncache elements/purge listeners on orphaned elements + // so we don't hold a reference and cause the browser to retain them + function garbageCollect() { + if (!Ext.enableGarbageCollector) { + clearInterval(El.collectorThreadId); + } else { + var eid, + d, + o, + t; + + for (eid in EC) { + if (!EC.hasOwnProperty(eid)) { + continue; + } + + o = EC[eid]; + + // Skip document and window elements + if (o.skipGarbageCollection) { + continue; + } + + d = o.dom; + + // Should always have a DOM node + if (!d) { + Ext.Error.raise('Missing DOM node in element garbage collection: ' + eid); + } + + // Check that document and window elements haven't got through + if (d && (d.getElementById || d.navigator)) { + Ext.Error.raise('Unexpected document or window element in element garbage collection'); + } + + // ------------------------------------------------------- + // Determining what is 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.parentNode || (!d.offsetParent && !Ext.getElementById(eid))) { + if (d && Ext.enableListenerCollection) { + Ext.EventManager.removeAll(d); + } + delete EC[eid]; + } + } + // Cleanup IE Object leaks + if (Ext.isIE) { + t = {}; + for (eid in EC) { + if (!EC.hasOwnProperty(eid)) { + continue; + } + t[eid] = EC[eid]; + } + EC = Ext.cache = t; + } + } + } + + El.collectorThreadId = setInterval(garbageCollect, 30000); + + //Stuff from Element-more.js + El.addMethods({ + + /** + * Monitors this Element for the mouse leaving. Calls the function after the specified delay only if + * the mouse was not moved back into the Element within the delay. If the mouse *was* moved + * back in, the function is not called. + * @param {Number} delay The delay **in milliseconds** to wait for possible mouse re-entry before calling the handler function. + * @param {Function} handler The function to call if the mouse remains outside of this Element for the specified time. + * @param {Object} [scope] The scope (`this` reference) in which the handler function executes. Defaults to this Element. + * @return {Object} The listeners object which was added to this element so that monitoring can be stopped. Example usage: + * + * // Hide the menu if the mouse moves out for 250ms or more + * this.mouseLeaveMonitor = this.menuEl.monitorMouseLeave(250, this.hideMenu, this); + * + * ... + * // Remove mouseleave monitor on menu destroy + * this.menuEl.un(this.mouseLeaveMonitor); + * + */ + monitorMouseLeave: function(delay, handler, scope) { + var me = this, + timer, + listeners = { + mouseleave: function(e) { + timer = setTimeout(Ext.Function.bind(handler, scope||me, [e]), delay); + }, + mouseenter: function() { + clearTimeout(timer); + }, + freezeEvent: true + }; + + me.on(listeners); + return listeners; + }, + + /** + * Stops the specified event(s) from bubbling and optionally prevents the default action + * @param {String/String[]} eventName an event / array of events to stop from bubbling + * @param {Boolean} [preventDefault] true to prevent the default action too + * @return {Ext.dom.Element} this + */ + swallowEvent : function(eventName, preventDefault) { + var me = this, + e, eLen; + function fn(e) { + e.stopPropagation(); + if (preventDefault) { + e.preventDefault(); + } + } + + if (Ext.isArray(eventName)) { + eLen = eventName.length; + + for (e = 0; e < eLen; e++) { + me.on(eventName[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} observable 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 Empty, or whitespace filled text nodes. Combines adjacent text nodes. + * @param {Boolean} [forceReclean=false] 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, + data = (me.$cache || me.getCache()).data, + n = dom.firstChild, + ni = -1, + nx; + + if (data.isCleaned && forceReclean !== true) { + return me; + } + + while (n) { + nx = n.nextSibling; + if (n.nodeType == 3) { + // Remove empty/whitespace text nodes + if (!(nonSpaceRe.test(n.nodeValue))) { + dom.removeChild(n); + // Combine adjacent text nodes + } else if (nx && nx.nodeType == 3) { + n.appendData(Ext.String.trim(nx.data)); + dom.removeChild(nx); + nx = n.nextSibling; + n.nodeIndex = ++ni; + } + } else { + // Recursively clean + Ext.fly(n).clean(); + n.nodeIndex = ++ni; + } + n = nx; + } + + data.isCleaned = true; + return me; + }, + + /** + * Direct access to the Ext.ElementLoader {@link Ext.ElementLoader#method-load} method. The method takes the same object + * parameter as {@link Ext.ElementLoader#method-load} + * @return {Ext.dom.Element} this + */ + load : function(options) { + this.getLoader().load(options); + return this; + }, + + /** + * Gets this element's {@link Ext.ElementLoader ElementLoader} + * @return {Ext.ElementLoader} The loader + */ + getLoader : function() { + var me = this, + data = (me.$cache || me.getCache()).data, + loader = data.loader; + + if (!loader) { + data.loader = loader = new Ext.ElementLoader({ + target: me + }); + } + return loader; + }, + + /** + * Updates the innerHTML of this element, optionally searching for and processing scripts. + * @param {String} html The new HTML + * @param {Boolean} [loadScripts] True to look for and process scripts (defaults to false) + * @param {Function} [callback] For async script loading you can be notified when the update completes + * @return {Ext.dom.Element} this + */ + update : function(html, loadScripts, callback) { + var me = this, + id, + dom, + interval; + + if (!me.dom) { + return me; + } + html = html || ''; + dom = me.dom; + + if (loadScripts !== true) { + dom.innerHTML = html; + Ext.callback(callback, me); + return me; + } + + id = Ext.id(); + html += ''; + + interval = setInterval(function() { + var hd, + match, + attrs, + srcMatch, + typeMatch, + el, + s; + if (!(el = DOC.getElementById(id))) { + return false; + } + clearInterval(interval); + Ext.removeNode(el); + hd = Ext.getHead().dom; + + while ((match = scriptTagRe.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.callback(callback, me); + }, 20); + dom.innerHTML = html.replace(replaceScriptTagRe, ''); + return me; + }, + + // inherit docs, overridden so we can add removeAnchor + removeAllListeners : function() { + this.removeAnchor(); + Ext.EventManager.removeAll(this.dom); + return this; + }, + + /** + * Creates a proxy element of this element + * @param {String/Object} config The class name of the proxy element or a DomHelper config object + * @param {String/HTMLElement} [renderTo] The element or element id to render the proxy to. Defaults to: document.body. + * @param {Boolean} [matchBox=false] True to align and size the proxy to this element now. + * @return {Ext.dom.Element} The new proxy element + */ + createProxy : function(config, renderTo, matchBox) { + config = (typeof config == 'object') ? config : {tag : "div", cls: config}; + + var me = this, + proxy = renderTo ? Ext.DomHelper.append(renderTo, config, true) : + Ext.DomHelper.insertBefore(me.dom, config, true); + + proxy.setVisibilityMode(Element.DISPLAY); + proxy.hide(); + if (matchBox && me.setBox && me.getBox) { // check to make sure Element.position.js is loaded + proxy.setBox(me.getBox()); + } + return proxy; + }, + + /** + * Gets the parent node of the current element taking into account Ext.scopeResetCSS + * @protected + * @return {HTMLElement} The parent element + */ + getScopeParent: function() { + var parent = this.dom.parentNode; + return Ext.scopeResetCSS ? parent.parentNode : parent; + }, + + /** + * Returns true if this element needs an explicit tabIndex to make it focusable. Input fields, text areas, buttons + * anchors elements **with an href** etc do not need a tabIndex, but structural elements do. + */ + needsTabIndex: function() { + if (this.dom) { + if ((this.dom.nodeName === 'a') && (!this.dom.href)) { + return true; + } + return !focusRe.test(this.dom.nodeName); + } + }, + + /** + * Checks whether this element can be focused. + * @return {Boolean} True if the element is focusable + */ + focusable: function () { + var dom = this.dom, + nodeName = dom.nodeName, + canFocus = false; + + if (!dom.disabled) { + if (focusRe.test(nodeName)) { + if ((nodeName !== 'a') || dom.href) { + canFocus = true; + } + } else { + canFocus = !isNaN(dom.tabIndex); + } + } + return canFocus && this.isVisible(true); + } + }); + + if (Ext.isIE) { + El.prototype.getById = function (id, asDom) { + var dom = this.dom, + cached, el, ret; + + if (dom) { + // for normal elements getElementById is the best solution, but if the el is + // not part of the document.body, we need to use all[] + el = (useDocForId && DOC.getElementById(id)) || dom.all[id]; + if (el) { + if (asDom) { + ret = el; + } else { + // calling El.get here is a real hit (2x slower) because it has to + // redetermine that we are giving it a dom el. + cached = EC[id]; + if (cached && cached.el) { + ret = cached.el; + ret.dom = el; + } else { + ret = new Element(el); + } + } + return ret; + } + } + + return asDom ? Ext.getDom(id) : El.get(id); + }; + } + + El.createAlias({ + /** + * @method + * @inheritdoc Ext.dom.Element#on + * Shorthand for {@link #on}. + */ + addListener: 'on', + /** + * @method + * @inheritdoc Ext.dom.Element#un + * Shorthand for {@link #un}. + */ + removeListener: 'un', + /** + * @method + * @inheritdoc Ext.dom.Element#removeAllListeners + * Alias for {@link #removeAllListeners}. + */ + clearListeners: 'removeAllListeners' + }); + + El.Fly = AbstractElement.Fly = new Ext.Class({ + extend: El, + + constructor: function(dom) { + this.dom = dom; + }, + + attach: AbstractElement.Fly.prototype.attach + }); + + if (Ext.isIE) { + Ext.getElementById = function (id) { + var el = DOC.getElementById(id), + detachedBodyEl; + + if (!el && (detachedBodyEl = AbstractElement.detachedBodyEl)) { + el = detachedBodyEl.dom.all[id]; + } + + return el; + }; + } else if (!DOC.querySelector) { + Ext.getDetachedBody = Ext.getBody; + + Ext.getElementById = function (id) { + return DOC.getElementById(id); + }; + } +}); + +}()); + +/** + * @class Ext.dom.Element + */ +Ext.dom.Element.override((function() { + + var doc = document, + win = window, + alignRe = /^([a-z]+)-([a-z]+)(\?)?$/, + round = Math.round; + + return { + + /** + * Gets the x,y coordinates specified by the anchor position on the element. + * @param {String} [anchor='c'] The specified anchor position. See {@link #alignTo} + * for details on supported anchor positions. + * @param {Boolean} [local] True to get the local (element top/left-relative) anchor position instead + * of page coordinates + * @param {Object} [size] 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 {Number[]} [x, y] An array containing the element's x and y coordinates + */ + getAnchorXY: function(anchor, local, mySize) { + //Passing a different size is useful for pre-calculating anchors, + //especially for anchored animations that change the el size. + anchor = (anchor || "tl").toLowerCase(); + mySize = mySize || {}; + + var me = this, + isViewport = me.dom == doc.body || me.dom == doc, + myWidth = mySize.width || isViewport ? Ext.dom.Element.getViewWidth() : me.getWidth(), + myHeight = mySize.height || isViewport ? Ext.dom.Element.getViewHeight() : me.getHeight(), + xy, + myPos = me.getXY(), + scroll = me.getScroll(), + extraX = isViewport ? scroll.left : !local ? myPos[0] : 0, + extraY = isViewport ? scroll.top : !local ? myPos[1] : 0; + + // Calculate anchor position. + // Test most common cases for picker alignment first. + switch (anchor) { + case 'tl' : xy = [ 0, 0]; + break; + case 'bl' : xy = [ 0, myHeight]; + break; + case 'tr' : xy = [ myWidth, 0]; + break; + case 'c' : xy = [ round(myWidth * 0.5), round(myHeight * 0.5)]; + break; + case 't' : xy = [ round(myWidth * 0.5), 0]; + break; + case 'l' : xy = [ 0, round(myHeight * 0.5)]; + break; + case 'r' : xy = [ myWidth, round(myHeight * 0.5)]; + break; + case 'b' : xy = [ round(myWidth * 0.5), myHeight]; + break; + case 'br' : xy = [ myWidth, myHeight]; + } + return [xy[0] + extraX, xy[1] + extraY]; + }, + + /** + * Gets the x,y coordinates to align this element with another element. See {@link #alignTo} for more info on the + * supported position values. + * @param {String/HTMLElement/Ext.Element} element The element to align to. + * @param {String} [position="tl-bl?"] The position to align to (defaults to ) + * @param {Number[]} [offsets] Offset the positioning by [x, y] + * @return {Number[]} [x, y] + */ + getAlignToXY : function(alignToEl, posSpec, offset) { + alignToEl = Ext.get(alignToEl); + + if (!alignToEl || !alignToEl.dom) { + Ext.Error.raise({ + sourceClass: 'Ext.dom.Element', + sourceMethod: 'getAlignToXY', + msg: 'Attempted to align an element that doesn\'t exist' + }); + } + + offset = offset || [0,0]; + posSpec = (!posSpec || posSpec == "?" ? "tl-bl?" : (!(/-/).test(posSpec) && posSpec !== "" ? "tl-" + posSpec : posSpec || "tl-bl")).toLowerCase(); + + var me = this, + myPosition, + alignToElPosition, + x, + y, + myWidth, + myHeight, + alignToElRegion, + viewportWidth = Ext.dom.Element.getViewWidth() - 10, // 10px of margin for ie + viewportHeight = Ext.dom.Element.getViewHeight() - 10, // 10px of margin for ie + p1y, + p1x, + p2y, + p2x, + swapY, + swapX, + docElement = doc.documentElement, + docBody = doc.body, + scrollX = (docElement.scrollLeft || docBody.scrollLeft || 0),// + 5, WHY was 5 ever added? + scrollY = (docElement.scrollTop || docBody.scrollTop || 0),// + 5, It means align will fail if the alignTo el was at less than 5,5 + constrain, //constrain to viewport + align1, + align2, + alignMatch = posSpec.match(alignRe); + + if (!alignMatch) { + Ext.Error.raise({ + sourceClass: 'Ext.dom.Element', + sourceMethod: 'getAlignToXY', + el: alignToEl, + position: posSpec, + offset: offset, + msg: 'Attemmpted to align an element with an invalid position: "' + posSpec + '"' + }); + } + + align1 = alignMatch[1]; + align2 = alignMatch[2]; + constrain = !!alignMatch[3]; + + //Subtract the aligned el's internal xy from the target's offset xy + //plus custom offset to get this Element's new offset xy + myPosition = me.getAnchorXY(align1, true); + alignToElPosition = alignToEl.getAnchorXY(align2, false); + + x = alignToElPosition[0] - myPosition[0] + offset[0]; + y = alignToElPosition[1] - myPosition[1] + offset[1]; + + // If position spec ended with a "?", then constrain to viewport is necessary + if (constrain) { + myWidth = me.getWidth(); + myHeight = me.getHeight(); + alignToElRegion = alignToEl.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 = align1.charAt(0); + p1x = align1.charAt(align1.length - 1); + p2y = align2.charAt(0); + p2x = align2.charAt(align2.length - 1); + swapY = ((p1y == "t" && p2y == "b") || (p1y == "b" && p2y == "t")); + swapX = ((p1x == "r" && p2x == "l") || (p1x == "l" && p2x == "r")); + + if (x + myWidth > viewportWidth + scrollX) { + x = swapX ? alignToElRegion.left - myWidth : viewportWidth + scrollX - myWidth; + } + if (x < scrollX) { + x = swapX ? alignToElRegion.right : scrollX; + } + if (y + myHeight > viewportHeight + scrollY) { + y = swapY ? alignToElRegion.top - myHeight : viewportHeight + scrollY - myHeight; + } + if (y < scrollY) { + y = swapY ? alignToElRegion.bottom : scrollY; + } + } + return [x,y]; + }, + + + /** + * Anchors an element to another element and realigns it when the window is resized. + * @param {String/HTMLElement/Ext.Element} element The element to align to. + * @param {String} position The position to align to. + * @param {Number[]} [offsets] Offset the positioning by [x, y] + * @param {Boolean/Object} [animate] True for the default animation or a standard Element animation config object + * @param {Boolean/Number} [monitorScroll] True to monitor body scroll and reposition. If this parameter + * is a number, it is used as the buffer delay (defaults to 50ms). + * @param {Function} [callback] The function to call after the animation finishes + * @return {Ext.Element} this + */ + anchorTo : function(el, alignment, offsets, animate, monitorScroll, callback) { + var me = this, + dom = me.dom, + scroll = !Ext.isEmpty(monitorScroll), + action = function() { + Ext.fly(dom).alignTo(el, alignment, offsets, animate); + Ext.callback(callback, Ext.fly(dom)); + }, + anchor = this.getAnchor(); + + // previous listener anchor, remove it + this.removeAnchor(); + Ext.apply(anchor, { + fn: action, + scroll: scroll + }); + + Ext.EventManager.onWindowResize(action, null); + + if (scroll) { + Ext.EventManager.on(win, 'scroll', action, null, + {buffer: !isNaN(monitorScroll) ? monitorScroll : 50}); + } + action.call(me); // align immediately + return me; + }, + + /** + * Remove any anchor to this element. See {@link #anchorTo}. + * @return {Ext.dom.Element} this + */ + removeAnchor : function() { + var me = this, + anchor = this.getAnchor(); + + if (anchor && anchor.fn) { + Ext.EventManager.removeResizeListener(anchor.fn); + if (anchor.scroll) { + Ext.EventManager.un(win, 'scroll', anchor.fn); + } + delete anchor.fn; + } + return me; + }, + + getAlignVector: function(el, spec, offset) { + var me = this, + myPos = me.getXY(), + alignedPos = me.getAlignToXY(el, spec, offset); + + el = Ext.get(el); + if (!el || !el.dom) { + Ext.Error.raise({ + sourceClass: 'Ext.dom.Element', + sourceMethod: 'getAlignVector', + msg: 'Attempted to align an element that doesn\'t exist' + }); + } + + alignedPos[0] -= myPos[0]; + alignedPos[1] -= myPos[1]; + return alignedPos; + }, + + /** + * 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 {String/HTMLElement/Ext.Element} element The element to align to. + * @param {String} [position="tl-bl?"] The position to align to + * @param {Number[]} [offsets] Offset the positioning by [x, y] + * @param {Boolean/Object} [animate] 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.anim && !!animate ? me.anim(animate) : false); + }, + + /** + * Returns the `[X, Y]` vector by which this element must be translated to make a best attempt + * to constrain within the passed constraint. Returns `false` is this element does not need to be moved. + * + * Priority is given to constraining the top and left within the constraint. + * + * The constraint may either be an existing element into which this element is to be constrained, or + * an {@link Ext.util.Region Region} into which this element is to be constrained. + * + * @param {Ext.Element/Ext.util.Region} constrainTo The Element or Region into which this element is to be constrained. + * @param {Number[]} proposedPosition A proposed `[X, Y]` position to test for validity and to produce a vector for instead + * of using this Element's current position; + * @returns {Number[]/Boolean} **If** this element *needs* to be translated, an `[X, Y]` + * vector by which this element must be translated. Otherwise, `false`. + */ + getConstrainVector: function(constrainTo, proposedPosition) { + if (!(constrainTo instanceof Ext.util.Region)) { + constrainTo = Ext.get(constrainTo).getViewRegion(); + } + var thisRegion = this.getRegion(), + vector = [0, 0], + shadowSize = this.shadow && this.shadow.offset, + overflowed = false; + + // Shift this region to occupy the proposed position + if (proposedPosition) { + thisRegion.translateBy(proposedPosition[0] - thisRegion.x, proposedPosition[1] - thisRegion.y); + } + + // Reduce the constrain region to allow for shadow + // TODO: Rewrite the Shadow class. When that's done, get the extra for each side from the Shadow. + if (shadowSize) { + constrainTo.adjust(0, -shadowSize, -shadowSize, shadowSize); + } + + // Constrain the X coordinate by however much this Element overflows + if (thisRegion.right > constrainTo.right) { + overflowed = true; + vector[0] = (constrainTo.right - thisRegion.right); // overflowed the right + } + if (thisRegion.left + vector[0] < constrainTo.left) { + overflowed = true; + vector[0] = (constrainTo.left - thisRegion.left); // overflowed the left + } + + // Constrain the Y coordinate by however much this Element overflows + if (thisRegion.bottom > constrainTo.bottom) { + overflowed = true; + vector[1] = (constrainTo.bottom - thisRegion.bottom); // overflowed the bottom + } + if (thisRegion.top + vector[1] < constrainTo.top) { + overflowed = true; + vector[1] = (constrainTo.top - thisRegion.top); // overflowed the top + } + return overflowed ? vector : false; + }, + + /** + * Calculates the x, y to center this element on the screen + * @return {Number[]} The x, y values [x, y] + */ + getCenterXY : function(){ + return this.getAlignToXY(doc, 'c-c'); + }, + + /** + * Centers the Element in either the viewport, or another Element. + * @param {String/HTMLElement/Ext.Element} [centerIn] The element in which to center the element. + */ + center : function(centerIn){ + return this.alignTo(centerIn || doc, 'c-c'); + } + }; +}())); +/** + * @class Ext.dom.Element + */ +/* ================================ + * A Note About Wrapped Animations + * ================================ + * A few of the effects below implement two different animations per effect, one wrapping + * animation that performs the visual effect and a "no-op" animation on this Element where + * no attributes of the element itself actually change. The purpose for this is that the + * wrapper is required for the effect to work and so it does the actual animation work, but + * we always animate `this` so that the element's events and callbacks work as expected to + * the callers of this API. + * + * Because of this, we always want each wrap animation to complete first (we don't want to + * cut off the visual effect early). To ensure that, we arbitrarily increase the duration of + * the element's no-op animation, also ensuring that it has a decent minimum value -- on slow + * systems, too-low durations can cause race conditions between the wrap animation and the + * element animation being removed out of order. Note that in each wrap's `afteranimate` + * callback it will explicitly terminate the element animation as soon as the wrap is complete, + * so there's no real danger in making the duration too long. + * + * This applies to all effects that get wrapped, including slideIn, slideOut, switchOff and frame. + */ + +Ext.dom.Element.override({ + // @private override base Ext.util.Animate mixin for animate for backwards compatibility + animate: function(config) { + var me = this, + listeners, + anim, + animId = me.dom.id || Ext.id(me.dom); + + if (!Ext.fx.Manager.hasFxBlock(animId)) { + // Bit of gymnastics here to ensure our internal listeners get bound first + if (config.listeners) { + listeners = config.listeners; + delete config.listeners; + } + if (config.internalListeners) { + config.listeners = config.internalListeners; + delete config.internalListeners; + } + anim = new Ext.fx.Anim(me.anim(config)); + if (listeners) { + anim.on(listeners); + } + Ext.fx.Manager.queueFx(anim); + } + return me; + }, + + // @private override base Ext.util.Animate mixin for animate for backwards compatibility + anim: function(config) { + if (!Ext.isObject(config)) { + return (config) ? {} : false; + } + + var me = this, + duration = config.duration || Ext.fx.Anim.prototype.duration, + easing = config.easing || 'ease', + animConfig; + + if (config.stopAnimation) { + me.stopAnimation(); + } + + Ext.applyIf(config, Ext.fx.Manager.getFxDefaults(me.id)); + + // Clear any 'paused' defaults. + Ext.fx.Manager.setFxDefaults(me.id, { + delay: 0 + }); + + animConfig = { + // Pass the DOM reference. That's tested first so will be converted to an Ext.fx.Target fastest. + target: me.dom, + remove: config.remove, + alternate: config.alternate || false, + duration: duration, + easing: easing, + callback: config.callback, + listeners: config.listeners, + iterations: config.iterations || 1, + scope: config.scope, + block: config.block, + concurrent: config.concurrent, + delay: config.delay || 0, + paused: true, + keyframes: config.keyframes, + from: config.from || {}, + to: Ext.apply({}, config) + }; + Ext.apply(animConfig.to, config.to); + + // Anim API properties - backward compat + delete animConfig.to.to; + delete animConfig.to.from; + delete animConfig.to.remove; + delete animConfig.to.alternate; + delete animConfig.to.keyframes; + delete animConfig.to.iterations; + delete animConfig.to.listeners; + delete animConfig.to.target; + delete animConfig.to.paused; + delete animConfig.to.callback; + delete animConfig.to.scope; + delete animConfig.to.duration; + delete animConfig.to.easing; + delete animConfig.to.concurrent; + delete animConfig.to.block; + delete animConfig.to.stopAnimation; + delete animConfig.to.delay; + return animConfig; + }, + + /** + * 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: 2000 }); + * + * // common config options shown with default values + * el.slideIn('t', { + * easing: 'easeOut', + * duration: 500 + * }); + * + * @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 + * @param {Boolean} options.preserveScroll Set to true if preservation of any descendant elements' + * `scrollTop` values is required. By default the DOM wrapping operation performed by `slideIn` and + * `slideOut` causes the browser to lose all scroll positions. + * @return {Ext.dom.Element} The Element + */ + slideIn: function(anchor, obj, slideOut) { + var me = this, + elStyle = me.dom.style, + beforeAnim, + wrapAnim, + restoreScroll, + wrapDomParentNode; + + anchor = anchor || "t"; + obj = obj || {}; + + beforeAnim = function() { + var animScope = this, + listeners = obj.listeners, + box, originalStyles, anim, wrap; + + if (!slideOut) { + me.fixDisplay(); + } + + box = me.getBox(); + if ((anchor == 't' || anchor == 'b') && box.height === 0) { + box.height = me.dom.scrollHeight; + } + else if ((anchor == 'l' || anchor == 'r') && box.width === 0) { + box.width = me.dom.scrollWidth; + } + + originalStyles = me.getStyles('width', 'height', 'left', 'right', 'top', 'bottom', 'position', 'z-index', true); + me.setSize(box.width, box.height); + + // Cache all descendants' scrollTop & scrollLeft values if configured to preserve scroll. + if (obj.preserveScroll) { + restoreScroll = me.cacheScrollValues(); + } + + wrap = me.wrap({ + id: Ext.id() + '-anim-wrap-for-' + me.id, + style: { + visibility: slideOut ? 'visible' : 'hidden' + } + }); + wrapDomParentNode = wrap.dom.parentNode; + wrap.setPositioning(me.getPositioning()); + if (wrap.isStyle('position', 'static')) { + wrap.position('relative'); + } + me.clearPositioning('auto'); + wrap.clip(); + + // The wrap will have reset all descendant scrollTops. Restore them if we cached them. + if (restoreScroll) { + restoreScroll(); + } + + // This element is temporarily positioned absolute within its wrapper. + // Restore to its default, CSS-inherited visibility setting. + // We cannot explicitly poke visibility:visible into its style because that overrides the visibility of the wrap. + me.setStyle({ + visibility: '', + position: 'absolute' + }); + if (slideOut) { + wrap.setSize(box.width, box.height); + } + + switch (anchor) { + case 't': + anim = { + from: { + width: box.width + 'px', + height: '0px' + }, + to: { + width: box.width + 'px', + height: box.height + 'px' + } + }; + elStyle.bottom = '0px'; + break; + case 'l': + anim = { + from: { + width: '0px', + height: box.height + 'px' + }, + to: { + width: box.width + 'px', + height: box.height + 'px' + } + }; + elStyle.right = '0px'; + break; + case 'r': + anim = { + from: { + x: box.x + box.width, + width: '0px', + height: box.height + 'px' + }, + to: { + x: box.x, + width: box.width + 'px', + height: box.height + 'px' + } + }; + break; + case 'b': + anim = { + from: { + y: box.y + box.height, + width: box.width + 'px', + height: '0px' + }, + to: { + y: box.y, + width: box.width + 'px', + height: box.height + 'px' + } + }; + break; + case 'tl': + anim = { + from: { + x: box.x, + y: box.y, + width: '0px', + height: '0px' + }, + to: { + width: box.width + 'px', + height: box.height + 'px' + } + }; + elStyle.bottom = '0px'; + elStyle.right = '0px'; + break; + case 'bl': + anim = { + from: { + x: box.x + box.width, + width: '0px', + height: '0px' + }, + to: { + x: box.x, + width: box.width + 'px', + height: box.height + 'px' + } + }; + elStyle.right = '0px'; + break; + case 'br': + anim = { + from: { + x: box.x + box.width, + y: box.y + box.height, + width: '0px', + height: '0px' + }, + to: { + x: box.x, + y: box.y, + width: box.width + 'px', + height: box.height + 'px' + } + }; + break; + case 'tr': + anim = { + from: { + y: box.y + box.height, + width: '0px', + height: '0px' + }, + to: { + y: box.y, + width: box.width + 'px', + height: box.height + 'px' + } + }; + elStyle.bottom = '0px'; + break; + } + + wrap.show(); + wrapAnim = Ext.apply({}, obj); + delete wrapAnim.listeners; + wrapAnim = new Ext.fx.Anim(Ext.applyIf(wrapAnim, { + target: wrap, + duration: 500, + easing: 'ease-out', + from: slideOut ? anim.to : anim.from, + to: slideOut ? anim.from : anim.to + })); + + // In the absence of a callback, this listener MUST be added first + wrapAnim.on('afteranimate', function() { + me.setStyle(originalStyles); + if (slideOut) { + if (obj.useDisplay) { + me.setDisplayed(false); + } else { + me.hide(); + } + } + if (wrap.dom) { + if (wrap.dom.parentNode) { + wrap.dom.parentNode.insertBefore(me.dom, wrap.dom); + } else { + wrapDomParentNode.appendChild(me.dom); + } + wrap.remove(); + } + // The unwrap will have reset all descendant scrollTops. Restore them if we cached them. + if (restoreScroll) { + restoreScroll(); + } + // kill the no-op element animation created below + animScope.end(); + }); + // Add configured listeners after + if (listeners) { + wrapAnim.on(listeners); + } + }; + + me.animate({ + // See "A Note About Wrapped Animations" at the top of this class: + duration: obj.duration ? Math.max(obj.duration, 500) * 2 : 1000, + listeners: { + beforeanimate: beforeAnim // kick off the wrap animation + } + }); + 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: 2000 }); + * + * // common config options shown with default values + * el.slideOut('t', { + * easing: 'easeOut', + * duration: 500, + * 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.dom.Element} The Element + */ + slideOut: function(anchor, o) { + return this.slideIn(anchor, o, true); + }, + + /** + * 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. Usage: + * + * // default + * el.puff(); + * + * // common config options shown with default values + * el.puff({ + * easing: 'easeOut', + * duration: 500, + * useDisplay: false + * }); + * + * @param {Object} options (optional) Object literal with any of the Fx config options + * @return {Ext.dom.Element} The Element + */ + puff: function(obj) { + var me = this, + beforeAnim, + box = me.getBox(), + originalStyles = me.getStyles('width', 'height', 'left', 'right', 'top', 'bottom', 'position', 'z-index', 'font-size', 'opacity', true); + + obj = Ext.applyIf(obj || {}, { + easing: 'ease-out', + duration: 500, + useDisplay: false + }); + + beforeAnim = function() { + me.clearOpacity(); + me.show(); + this.to = { + width: box.width * 2, + height: box.height * 2, + x: box.x - (box.width / 2), + y: box.y - (box.height /2), + opacity: 0, + fontSize: '200%' + }; + this.on('afteranimate',function() { + if (me.dom) { + if (obj.useDisplay) { + me.setDisplayed(false); + } else { + me.hide(); + } + me.setStyle(originalStyles); + obj.callback.call(obj.scope); + } + }); + }; + + me.animate({ + duration: obj.duration, + easing: obj.easing, + listeners: { + beforeanimate: { + fn: beforeAnim + } + } + }); + 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.dom.Element} The Element + */ + switchOff: function(obj) { + var me = this, + beforeAnim; + + obj = Ext.applyIf(obj || {}, { + easing: 'ease-in', + duration: 500, + remove: false, + useDisplay: false + }); + + beforeAnim = function() { + var animScope = this, + size = me.getSize(), + xy = me.getXY(), + keyframe, position; + me.clearOpacity(); + me.clip(); + position = me.getPositioning(); + + keyframe = new Ext.fx.Animator({ + target: me, + duration: obj.duration, + easing: obj.easing, + keyframes: { + 33: { + opacity: 0.3 + }, + 66: { + height: 1, + y: xy[1] + size.height / 2 + }, + 100: { + width: 1, + x: xy[0] + size.width / 2 + } + } + }); + keyframe.on('afteranimate', function() { + if (obj.useDisplay) { + me.setDisplayed(false); + } else { + me.hide(); + } + me.clearOpacity(); + me.setPositioning(position); + me.setSize(size); + // kill the no-op element animation created below + animScope.end(); + }); + }; + + me.animate({ + // See "A Note About Wrapped Animations" at the top of this class: + duration: (Math.max(obj.duration, 500) * 2), + listeners: { + beforeanimate: { + fn: beforeAnim + } + } + }); + 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.dom.Element} The Element + */ + frame : function(color, count, obj){ + var me = this, + beforeAnim; + + color = color || '#C3DAF9'; + count = count || 1; + obj = obj || {}; + + beforeAnim = function() { + me.show(); + var animScope = this, + box = me.getBox(), + proxy = Ext.getBody().createChild({ + id: me.id + '-anim-proxy', + style: { + position : 'absolute', + 'pointer-events': 'none', + 'z-index': 35000, + border : '0px solid ' + color + } + }), + proxyAnim; + proxyAnim = new Ext.fx.Anim({ + target: proxy, + duration: obj.duration || 1000, + iterations: count, + from: { + top: box.y, + left: box.x, + borderWidth: 0, + opacity: 1, + height: box.height, + width: box.width + }, + to: { + top: box.y - 20, + left: box.x - 20, + borderWidth: 10, + opacity: 0, + height: box.height + 40, + width: box.width + 40 + } + }); + proxyAnim.on('afteranimate', function() { + proxy.remove(); + // kill the no-op element animation created below + animScope.end(); + }); + }; + + me.animate({ + // See "A Note About Wrapped Animations" at the top of this class: + duration: (Math.max(obj.duration, 500) * 2) || 2000, + listeners: { + beforeanimate: { + fn: beforeAnim + } + } + }); + return me; + }, + + /** + * 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: 2000 }); + * + * // common config options shown with default values + * el.ghost('b', { + * easing: 'easeOut', + * duration: 500 + * }); + * + * @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.dom.Element} The Element + */ + ghost: function(anchor, obj) { + var me = this, + beforeAnim; + + anchor = anchor || "b"; + beforeAnim = function() { + var width = me.getWidth(), + height = me.getHeight(), + xy = me.getXY(), + position = me.getPositioning(), + to = { + opacity: 0 + }; + switch (anchor) { + case 't': + to.y = xy[1] - height; + break; + case 'l': + to.x = xy[0] - width; + break; + case 'r': + to.x = xy[0] + width; + break; + case 'b': + to.y = xy[1] + height; + break; + case 'tl': + to.x = xy[0] - width; + to.y = xy[1] - height; + break; + case 'bl': + to.x = xy[0] - width; + to.y = xy[1] + height; + break; + case 'br': + to.x = xy[0] + width; + to.y = xy[1] + height; + break; + case 'tr': + to.x = xy[0] + width; + to.y = xy[1] - height; + break; + } + this.to = to; + this.on('afteranimate', function () { + if (me.dom) { + me.hide(); + me.clearOpacity(); + me.setPositioning(position); + } + }); + }; + + me.animate(Ext.applyIf(obj || {}, { + duration: 500, + easing: 'ease-out', + listeners: { + beforeanimate: { + fn: beforeAnim + } + } + })); + 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: 2000 }); + * + * // common config options shown with default values + * el.highlight("ffff9c", { + * attr: "backgroundColor", //can be any valid CSS property (attribute) that supports a color value + * endColor: (current color) or "ffffff", + * easing: 'easeIn', + * duration: 1000 + * }); + * + * @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.dom.Element} The Element + */ + highlight: function(color, o) { + var me = this, + dom = me.dom, + from = {}, + restore, to, attr, lns, event, fn; + + o = o || {}; + lns = o.listeners || {}; + attr = o.attr || 'backgroundColor'; + from[attr] = color || 'ffff9c'; + + if (!o.to) { + to = {}; + to[attr] = o.endColor || me.getColor(attr, 'ffffff', ''); + } + else { + to = o.to; + } + + // Don't apply directly on lns, since we reference it in our own callbacks below + o.listeners = Ext.apply(Ext.apply({}, lns), { + beforeanimate: function() { + restore = dom.style[attr]; + me.clearOpacity(); + me.show(); + + event = lns.beforeanimate; + if (event) { + fn = event.fn || event; + return fn.apply(event.scope || lns.scope || window, arguments); + } + }, + afteranimate: function() { + if (dom) { + dom.style[attr] = restore; + } + + event = lns.afteranimate; + if (event) { + fn = event.fn || event; + fn.apply(event.scope || lns.scope || window, arguments); + } + } + }); + + me.animate(Ext.apply({}, o, { + duration: 1000, + easing: 'ease-in', + from: from, + to: to + })); + return me; + }, + + /** + * @deprecated 4.0 + * 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(ms) { + var me = this; + Ext.fx.Manager.setFxDefaults(me.id, { + delay: ms + }); + return me; + }, + + /** + * Fade an element in (from transparent to opaque). The ending opacity can be specified using the `opacity` + * 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({ opacity: .75, duration: 2000}); + * + * // common config options shown with default values + * el.fadeIn({ + * opacity: 1, //can be any value between 0 and 1 (e.g. .5) + * easing: 'easeOut', + * duration: 500 + * }); + * + * @param {Object} options (optional) Object literal with any of the Fx config options + * @return {Ext.Element} The Element + */ + fadeIn: function(o) { + var me = this; + me.animate(Ext.apply({}, o, { + opacity: 1, + internalListeners: { + beforeanimate: function(anim){ + // restore any visibility/display that may have + // been applied by a fadeout animation + if (me.isStyle('display', 'none')) { + me.setDisplayed(''); + } else { + me.show(); + } + } + } + })); + return this; + }, + + /** + * Fade an element out (from opaque to transparent). The ending opacity can be specified using the `opacity` + * config option. Note that IE may require `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({ opacity: .25, duration: 2000}); + * + * // common config options shown with default values + * el.fadeOut({ + * opacity: 0, //can be any value between 0 and 1 (e.g. .5) + * easing: 'easeOut', + * duration: 500, + * 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) { + var me = this; + o = Ext.apply({ + opacity: 0, + internalListeners: { + afteranimate: function(anim){ + var dom = me.dom; + if (dom && anim.to.opacity === 0) { + if (o.useDisplay) { + me.setDisplayed(false); + } else { + me.hide(); + } + } + } + } + }, o); + me.animate(o); + return me; + }, + + /** + * @deprecated 4.0 + * 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.animate(Ext.apply({}, o, { + width: w, + height: h + })); + return this; + }, + + /** + * @deprecated 4.0 + * 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(config) { + this.animate(config); + return this; + } +}); + +/** + * @class Ext.dom.Element + */ +Ext.dom.Element.override({ + /** + * Initializes a {@link Ext.dd.DD} drag drop object for this element. + * @param {String} group The group the DD object is member of + * @param {Object} config The DD config object + * @param {Object} overrides An object containing methods to override/implement on the DD object + * @return {Ext.dd.DD} The DD object + */ + initDD : function(group, config, overrides){ + var dd = new Ext.dd.DD(Ext.id(this.dom), group, config); + return Ext.apply(dd, overrides); + }, + + /** + * Initializes a {@link Ext.dd.DDProxy} object for this element. + * @param {String} group The group the DDProxy object is member of + * @param {Object} config The DDProxy config object + * @param {Object} overrides An object containing methods to override/implement on the DDProxy object + * @return {Ext.dd.DDProxy} The DDProxy object + */ + initDDProxy : function(group, config, overrides){ + var dd = new Ext.dd.DDProxy(Ext.id(this.dom), group, config); + return Ext.apply(dd, overrides); + }, + + /** + * Initializes a {@link Ext.dd.DDTarget} object for this element. + * @param {String} group The group the DDTarget object is member of + * @param {Object} config The DDTarget config object + * @param {Object} overrides An object containing methods to override/implement on the DDTarget object + * @return {Ext.dd.DDTarget} The DDTarget object + */ + initDDTarget : function(group, config, overrides){ + var dd = new Ext.dd.DDTarget(Ext.id(this.dom), group, config); + return Ext.apply(dd, overrides); + } +}); + +/** + * @class Ext.dom.Element + */ +(function() { + +var Element = Ext.dom.Element, + VISIBILITY = "visibility", + DISPLAY = "display", + NONE = "none", + HIDDEN = 'hidden', + VISIBLE = 'visible', + OFFSETS = "offsets", + ASCLASS = "asclass", + NOSIZE = 'nosize', + ORIGINALDISPLAY = 'originalDisplay', + VISMODE = 'visibilityMode', + ISVISIBLE = 'isVisible', + OFFSETCLASS = Ext.baseCSSPrefix + 'hide-offsets', + getDisplay = function(el) { + var data = (el.$cache || el.getCache()).data, + display = data[ORIGINALDISPLAY]; + + if (display === undefined) { + data[ORIGINALDISPLAY] = display = ''; + } + return display; + }, + getVisMode = function(el){ + var data = (el.$cache || el.getCache()).data, + visMode = data[VISMODE]; + + if (visMode === undefined) { + data[VISMODE] = visMode = Element.VISIBILITY; + } + return visMode; + }; + +Element.override({ + /** + * The element's default display mode. + */ + originalDisplay : "", + visibilityMode : 1, + + /** + * 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] True for the default animation, or a standard Element animation config object + * @return {Ext.dom.Element} this + */ + setVisible : function(visible, animate) { + var me = this, + dom = me.dom, + visMode = getVisMode(me); + + // hideMode string override + if (typeof animate == 'string') { + switch (animate) { + case DISPLAY: + visMode = Element.DISPLAY; + break; + case VISIBILITY: + visMode = Element.VISIBILITY; + break; + case OFFSETS: + visMode = Element.OFFSETS; + break; + case NOSIZE: + case ASCLASS: + visMode = Element.ASCLASS; + break; + } + me.setVisibilityMode(visMode); + animate = false; + } + + if (!animate || !me.anim) { + if (visMode == Element.DISPLAY) { + return me.setDisplayed(visible); + } else if (visMode == Element.OFFSETS) { + me[visible?'removeCls':'addCls'](OFFSETCLASS); + } else if (visMode == Element.VISIBILITY) { + me.fixDisplay(); + // Show by clearing visibility style. Explicitly setting to "visible" overrides parent visibility setting + dom.style.visibility = visible ? '' : HIDDEN; + } else if (visMode == Element.ASCLASS) { + me[visible?'removeCls':'addCls'](me.visibilityCls || Element.visibilityCls); + } + } else { + // closure for composites + if (visible) { + me.setOpacity(0.01); + me.setVisible(true); + } + if (!Ext.isObject(animate)) { + animate = { + duration: 350, + easing: 'ease-in' + }; + } + me.animate(Ext.applyIf({ + callback: function() { + if (!visible) { + me.setVisible(false).setOpacity(1); + } + }, + to: { + opacity: (visible) ? 1 : 0 + } + }, animate)); + } + (me.$cache || me.getCache()).data[ISVISIBLE] = visible; + return me; + }, + + /** + * @private + * Determine if the Element has a relevant height and width available based + * upon current logical visibility state + */ + hasMetrics : function(){ + var visMode = getVisMode(this); + return this.isVisible() || (visMode == Element.OFFSETS) || (visMode == Element.VISIBILITY); + }, + + /** + * Toggles the element's visibility or display, depending on visibility mode. + * @param {Boolean/Object} [animate] True for the default animation, or a standard Element animation config object + * @return {Ext.dom.Element} this + */ + toggle : function(animate){ + var me = this; + me.setVisible(!me.isVisible(), me.anim(animate)); + return me; + }, + + /** + * Sets the CSS display property. Uses originalDisplay if the specified value is a boolean true. + * @param {Boolean/String} value Boolean value to display the element using its default display, or a string to set the display directly. + * @return {Ext.dom.Element} this + */ + setDisplayed : function(value) { + if(typeof value == "boolean"){ + value = value ? getDisplay(this) : 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(me)); // 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] true for the default animation or a standard Element animation config object + * @return {Ext.dom.Element} this + */ + hide : function(animate){ + // hideMode override + if (typeof animate == 'string'){ + this.setVisible(false, animate); + return this; + } + this.setVisible(false, this.anim(animate)); + return this; + }, + + /** + * Show this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}. + * @param {Boolean/Object} [animate] true for the default animation or a standard Element animation config object + * @return {Ext.dom.Element} this + */ + show : function(animate){ + // hideMode override + if (typeof animate == 'string'){ + this.setVisible(true, animate); + return this; + } + this.setVisible(true, this.anim(animate)); + return this; + } +}); + +}()); + +/** + * @class Ext.dom.Element + */ +(function() { + +var Element = Ext.dom.Element, + LEFT = "left", + RIGHT = "right", + TOP = "top", + BOTTOM = "bottom", + POSITION = "position", + STATIC = "static", + RELATIVE = "relative", + AUTO = "auto", + ZINDEX = "z-index", + BODY = 'BODY', + + PADDING = 'padding', + BORDER = 'border', + SLEFT = '-left', + SRIGHT = '-right', + STOP = '-top', + SBOTTOM = '-bottom', + SWIDTH = '-width', + // special markup used throughout Ext when box wrapping elements + borders = {l: BORDER + SLEFT + SWIDTH, r: BORDER + SRIGHT + SWIDTH, t: BORDER + STOP + SWIDTH, b: BORDER + SBOTTOM + SWIDTH}, + paddings = {l: PADDING + SLEFT, r: PADDING + SRIGHT, t: PADDING + STOP, b: PADDING + SBOTTOM}, + paddingsTLRB = [paddings.l, paddings.r, paddings.t, paddings.b], + bordersTLRB = [borders.l, borders.r, borders.t, borders.b], + positionTopLeft = ['position', 'top', 'left']; + +Element.override({ + + getX: function() { + return Element.getX(this.dom); + }, + + getY: function() { + return Element.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 {Number[]} The XY position of the element + */ + getXY: function() { + return Element.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 {String/HTMLElement/Ext.Element} element The element to get the offsets from. + * @return {Number[]} 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]]; + }, + + setX: function(x, animate) { + return this.setXY([x, this.getY()], animate); + }, + + setY: function(y, animate) { + return this.setXY([this.getX(), y], animate); + }, + + setLeft: function(left) { + this.setStyle(LEFT, this.addUnits(left)); + return this; + }, + + setTop: function(top) { + this.setStyle(TOP, this.addUnits(top)); + return this; + }, + + setRight: function(right) { + this.setStyle(RIGHT, this.addUnits(right)); + return 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 {Number[]} pos Contains X & Y [x, y] values for new position (coordinates are page-based) + * @param {Boolean/Object} [animate] 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) { + Element.setXY(me.dom, pos); + } + else { + if (!Ext.isObject(animate)) { + animate = {}; + } + me.animate(Ext.applyIf({ to: { x: pos[0], y: pos[1] } }, animate)); + } + return me; + }, + + getLeft: function(local) { + return !local ? this.getX() : parseFloat(this.getStyle(LEFT)) || 0; + }, + + getRight: function(local) { + var me = this; + return !local ? me.getX() + me.getWidth() : (me.getLeft(true) + me.getWidth()) || 0; + }, + + getTop: function(local) { + return !local ? this.getY() : parseFloat(this.getStyle(TOP)) || 0; + }, + + getBottom: function(local) { + var me = this; + return !local ? me.getY() + me.getHeight() : (me.getTop(true) + me.getHeight()) || 0; + }, + + translatePoints: function(x, y) { + var me = this, + styles = me.getStyle(positionTopLeft), + relative = styles.position == 'relative', + left = parseFloat(styles.left), + top = parseFloat(styles.top), + xy = me.getXY(); + + if (Ext.isArray(x)) { + y = x[1]; + x = x[0]; + } + if (isNaN(left)) { + left = relative ? 0 : me.dom.offsetLeft; + } + if (isNaN(top)) { + top = relative ? 0 : me.dom.offsetTop; + } + left = (typeof x == 'number') ? x - xy[0] + left : undefined; + top = (typeof y == 'number') ? y - xy[1] + top : undefined; + return { + left: left, + top: top + }; + + }, + + 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, animate); + return me; + }, + + getBox: function(contentBox, local) { + var me = this, + xy, + left, + top, + paddingWidth, + bordersWidth, + l, r, t, b, w, h, bx; + + if (!local) { + xy = me.getXY(); + } else { + xy = me.getStyle([LEFT, TOP]); + xy = [ parseFloat(xy.left) || 0, parseFloat(xy.top) || 0]; + } + w = me.getWidth(); + h = me.getHeight(); + if (!contentBox) { + bx = { + x: xy[0], + y: xy[1], + 0: xy[0], + 1: xy[1], + width: w, + height: h + }; + } else { + paddingWidth = me.getStyle(paddingsTLRB); + bordersWidth = me.getStyle(bordersTLRB); + + l = (parseFloat(bordersWidth[borders.l]) || 0) + (parseFloat(paddingWidth[paddings.l]) || 0); + r = (parseFloat(bordersWidth[borders.r]) || 0) + (parseFloat(paddingWidth[paddings.r]) || 0); + t = (parseFloat(bordersWidth[borders.t]) || 0) + (parseFloat(paddingWidth[paddings.t]) || 0); + b = (parseFloat(bordersWidth[borders.b]) || 0) + (parseFloat(paddingWidth[paddings.b]) || 0); + + 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; + }, + + getPageBox: function(getRegion) { + var me = this, + el = me.dom, + isDoc = el.nodeName == BODY, + w = isDoc ? Ext.dom.AbstractElement.getViewWidth() : el.offsetWidth, + h = isDoc ? Ext.dom.AbstractElement.getViewHeight() : el.offsetHeight, + xy = me.getXY(), + t = xy[1], + r = xy[0] + w, + b = xy[1] + h, + l = xy[0]; + + if (getRegion) { + return new Ext.util.Region(t, r, b, l); + } + else { + return { + left: l, + top: t, + width: w, + height: h, + right: r, + bottom: b + }; + } + }, + + /** + * 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] True for the default animation, or a standard Element + * animation config object + * @return {Ext.dom.AbstractElement} this + */ + setLocation : function(x, y, animate) { + return this.setXY([x, y], animate); + }, + + /** + * 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] True for the default animation, or a standard Element + * animation config object + * @return {Ext.dom.AbstractElement} this + */ + moveTo : function(x, y, animate) { + return this.setXY([x, y], animate); + }, + + /** + * 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] Positioning to use "relative", "absolute" or "fixed" + * @param {Number} [zIndex] The zIndex to apply + * @param {Number} [x] Set the page X position + * @param {Number} [y] 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]); + } + }, + + /** + * Clears positioning back to the default when the document was loaded. + * @param {String} [value=''] The value to use for the left, right, top, bottom. You could use 'auto'. + * @return {Ext.dom.AbstractElement} 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 styles = this.getStyle([LEFT, TOP, POSITION, RIGHT, BOTTOM, ZINDEX]); + styles[RIGHT] = styles[LEFT] ? '' : styles[RIGHT]; + styles[BOTTOM] = styles[TOP] ? '' : styles[BOTTOM]; + return styles; + }, + + /** + * Set positioning with an object returned by #getPositioning. + * @param {Object} posCfg + * @return {Ext.dom.AbstractElement} 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; + }, + + /** + * 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] true for the default animation or a standard Element + * animation config object + */ + 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], animate); + }, + + /** + * Conveniently sets left and top adding default units. + * @param {String} left The left CSS property value + * @param {String} top The top CSS property value + * @return {Ext.dom.Element} this + */ + setLeftTop: function(left, top) { + var style = this.dom.style; + + style.left = Element.addUnits(left); + style.top = Element.addUnits(top); + + return this; + }, + + /** + * Returns the region of this element. + * The element must be part of the DOM tree to have a region + * (display:none or elements not appended return false). + * @return {Ext.util.Region} A Region containing "top, left, bottom, right" member data. + */ + getRegion: function() { + return this.getPageBox(true); + }, + + /** + * Returns the **content** region of this element. That is the region within the borders and padding. + * @return {Ext.util.Region} A Region containing "top, left, bottom, right" member data. + */ + getViewRegion: function() { + var me = this, + isBody = me.dom.nodeName == BODY, + scroll, pos, top, left, width, height; + + // For the body we want to do some special logic + if (isBody) { + scroll = me.getScroll(); + left = scroll.left; + top = scroll.top; + width = Ext.dom.AbstractElement.getViewportWidth(); + height = Ext.dom.AbstractElement.getViewportHeight(); + } + else { + pos = me.getXY(); + left = pos[0] + me.getBorderWidth('l') + me.getPadding('l'); + top = pos[1] + me.getBorderWidth('t') + me.getPadding('t'); + width = me.getWidth(true); + height = me.getHeight(true); + } + + return new Ext.util.Region(top, left + width, top + height, left); + }, + + /** + * 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 {Number/String} 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 {Number/String} 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] true for the default animation or a standard Element + * animation config object + * + * @return {Ext.dom.AbstractElement} this + */ + setBounds: function(x, y, width, height, animate) { + var me = this; + if (!animate || !me.anim) { + me.setSize(width, height); + me.setLocation(x, y); + } else { + if (!Ext.isObject(animate)) { + animate = {}; + } + me.animate(Ext.applyIf({ + to: { + x: x, + y: y, + width: me.adjustWidth(width), + height: me.adjustHeight(height) + } + }, animate)); + } + 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.util.Region} region The region to fill + * @param {Boolean/Object} [animate] true for the default animation or a standard Element + * animation config object + * @return {Ext.dom.AbstractElement} this + */ + setRegion: function(region, animate) { + return this.setBounds(region.left, region.top, region.right - region.left, region.bottom - region.top, animate); + } +}); + +}()); + + +/** + * @class Ext.dom.Element + */ +Ext.dom.Element.override({ + /** + * Returns true if this element is scrollable. + * @return {Boolean} + */ + isScrollable: function() { + var dom = this.dom; + return dom.scrollHeight > dom.clientHeight || dom.scrollWidth > dom.clientWidth; + }, + + /** + * 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; + }, + + /** + * Scrolls this element by the passed delta values, optionally animating. + * + * All of the following are equivalent: + * + * el.scrollBy(10, 10, true); + * el.scrollBy([10, 10], true); + * el.scrollBy({ x: 10, y: 10 }, true); + * + * @param {Number/Number[]/Object} deltaX Either the x delta, an Array specifying x and y deltas or + * an object with "x" and "y" properties. + * @param {Number/Boolean/Object} deltaY Either the y delta, or an animate flag or config object. + * @param {Boolean/Object} animate Animate flag/config object if the delta values were passed separately. + * @return {Ext.Element} this + */ + scrollBy: function(deltaX, deltaY, animate) { + var me = this, + dom = me.dom; + + // Extract args if deltas were passed as an Array. + if (deltaX.length) { + animate = deltaY; + deltaY = deltaX[1]; + deltaX = deltaX[0]; + } else if (typeof deltaX != 'number') { // or an object + animate = deltaY; + deltaY = deltaX.y; + deltaX = deltaX.x; + } + + if (deltaX) { + me.scrollTo('left', Math.max(Math.min(dom.scrollLeft + deltaX, dom.scrollWidth - dom.clientWidth), 0), animate); + } + if (deltaY) { + me.scrollTo('top', Math.max(Math.min(dom.scrollTop + deltaY, dom.scrollHeight - dom.clientHeight), 0), animate); + } + + return me; + }, + + /** + * 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] true for the default animation or a standard Element + * animation config object + * @return {Ext.Element} this + */ + scrollTo: function(side, value, animate) { + //check if we're scrolling top or left + var top = /top/i.test(side), + me = this, + dom = me.dom, + obj = {}, + prop; + + if (!animate || !me.anim) { + // just setting the value, so grab the direction + prop = 'scroll' + (top ? 'Top' : 'Left'); + dom[prop] = value; + } + else { + if (!Ext.isObject(animate)) { + animate = {}; + } + obj['scroll' + (top ? 'Top' : 'Left')] = value; + me.animate(Ext.applyIf({ + to: obj + }, animate)); + } + return me; + }, + + /** + * Scrolls this element into view within the passed container. + * @param {String/HTMLElement/Ext.Element} [container=document.body] The container element + * to scroll. Should be a string (id), dom node, or Ext.Element. + * @param {Boolean} [hscroll=true] False to disable horizontal scroll. + * @return {Ext.dom.Element} this + */ + scrollIntoView: function(container, hscroll) { + container = Ext.getDom(container) || Ext.getBody().dom; + var el = this.dom, + offsets = this.getOffsetsTo(container), + // el's box + left = offsets[0] + container.scrollLeft, + top = offsets[1] + container.scrollTop, + bottom = top + el.offsetHeight, + right = left + el.offsetWidth, + // ct's box + ctClientHeight = container.clientHeight, + ctScrollTop = parseInt(container.scrollTop, 10), + ctScrollLeft = parseInt(container.scrollLeft, 10), + ctBottom = ctScrollTop + ctClientHeight, + ctRight = ctScrollLeft + container.clientWidth; + + if (el.offsetHeight > ctClientHeight || top < ctScrollTop) { + container.scrollTop = top; + } else if (bottom > ctBottom) { + container.scrollTop = bottom - ctClientHeight; + } + // corrects IE, other browsers will ignore + container.scrollTop = container.scrollTop; + + if (hscroll !== false) { + if (el.offsetWidth > container.clientWidth || left < ctScrollLeft) { + container.scrollLeft = left; + } + else if (right > ctRight) { + container.scrollLeft = right - container.clientWidth; + } + container.scrollLeft = container.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] 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 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.anim(animate)); + } + return scrolled; + } +}); + +/** + * @class Ext.dom.Element + */ +(function() { + +var Element = Ext.dom.Element, + view = document.defaultView, + adjustDirect2DTableRe = /table-row|table-.*-group/, + INTERNAL = '_internal', + HIDDEN = 'hidden', + HEIGHT = 'height', + WIDTH = 'width', + ISCLIPPED = 'isClipped', + OVERFLOW = 'overflow', + OVERFLOWX = 'overflow-x', + OVERFLOWY = 'overflow-y', + ORIGINALCLIP = 'originalClip', + DOCORBODYRE = /#document|body/i, + // This reduces the lookup of 'me.styleHooks' by one hop in the prototype chain. It is + // the same object. + styleHooks, + edges, k, edge, borderWidth; + +if (!view || !view.getComputedStyle) { + Element.prototype.getStyle = function (property, inline) { + var me = this, + dom = me.dom, + multiple = typeof property != 'string', + hooks = me.styleHooks, + prop = property, + props = prop, + len = 1, + isInline = inline, + camel, domStyle, values, hook, out, style, i; + + if (multiple) { + values = {}; + prop = props[0]; + i = 0; + if (!(len = props.length)) { + return values; + } + } + + if (!dom || dom.documentElement) { + return values || ''; + } + + domStyle = dom.style; + + if (inline) { + style = domStyle; + } else { + style = dom.currentStyle; + + // fallback to inline style if rendering context not available + if (!style) { + isInline = true; + style = domStyle; + } + } + + do { + hook = hooks[prop]; + + if (!hook) { + hooks[prop] = hook = { name: Element.normalize(prop) }; + } + + if (hook.get) { + out = hook.get(dom, me, isInline, style); + } else { + camel = hook.name; + + // In some cases, IE6 will throw Invalid Argument exceptions for properties + // like fontSize (/examples/tabs/tabs.html in 4.0 used to exhibit this but + // no longer does due to font style changes). There is a real cost to a try + // block, so we avoid it where possible... + if (hook.canThrow) { + try { + out = style[camel]; + } catch (e) { + out = ''; + } + } else { + // EXTJSIV-5657 - In IE9 quirks mode there is a chance that VML root element + // has neither `currentStyle` nor `style`. Return '' this case. + out = style ? style[camel] : ''; + } + } + + if (!multiple) { + return out; + } + + values[prop] = out; + prop = props[++i]; + } while (i < len); + + return values; + }; +} + +Element.override({ + getHeight: function(contentHeight, preciseHeight) { + var me = this, + dom = me.dom, + hidden = me.isStyle('display', 'none'), + height, + floating; + + if (hidden) { + return 0; + } + + height = Math.max(dom.offsetHeight, dom.clientHeight) || 0; + + // IE9 Direct2D dimension rounding bug + if (Ext.supports.Direct2DBug) { + floating = me.adjustDirect2DDimension(HEIGHT); + if (preciseHeight) { + height += floating; + } + else if (floating > 0 && floating < 0.5) { + height++; + } + } + + if (contentHeight) { + height -= me.getBorderWidth("tb") + me.getPadding("tb"); + } + + return (height < 0) ? 0 : height; + }, + + getWidth: function(contentWidth, preciseWidth) { + var me = this, + dom = me.dom, + hidden = me.isStyle('display', 'none'), + rect, width, floating; + + if (hidden) { + return 0; + } + + // Gecko will in some cases report an offsetWidth that is actually less than the width of the + // text contents, because it measures fonts with sub-pixel precision but rounds the calculated + // value down. Using getBoundingClientRect instead of offsetWidth allows us to get the precise + // subpixel measurements so we can force them to always be rounded up. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=458617 + // Rounding up ensures that the width includes the full width of the text contents. + if (Ext.supports.BoundingClientRect) { + rect = dom.getBoundingClientRect(); + width = rect.right - rect.left; + width = preciseWidth ? width : Math.ceil(width); + } else { + width = dom.offsetWidth; + } + + width = Math.max(width, dom.clientWidth) || 0; + + // IE9 Direct2D dimension rounding bug + if (Ext.supports.Direct2DBug) { + // get the fractional portion of the sub-pixel precision width of the element's text contents + floating = me.adjustDirect2DDimension(WIDTH); + if (preciseWidth) { + width += floating; + } + // IE9 also measures fonts with sub-pixel precision, but unlike Gecko, instead of rounding the offsetWidth down, + // it rounds to the nearest integer. This means that in order to ensure that the width includes the full + // width of the text contents we need to increment the width by 1 only if the fractional portion is less than 0.5 + else if (floating > 0 && floating < 0.5) { + width++; + } + } + + if (contentWidth) { + width -= me.getBorderWidth("lr") + me.getPadding("lr"); + } + + return (width < 0) ? 0 : width; + }, + + setWidth: function(width, animate) { + var me = this; + width = me.adjustWidth(width); + if (!animate || !me.anim) { + me.dom.style.width = me.addUnits(width); + } + else { + if (!Ext.isObject(animate)) { + animate = {}; + } + me.animate(Ext.applyIf({ + to: { + width: width + } + }, animate)); + } + return me; + }, + + setHeight : function(height, animate) { + var me = this; + + height = me.adjustHeight(height); + if (!animate || !me.anim) { + me.dom.style.height = me.addUnits(height); + } + else { + if (!Ext.isObject(animate)) { + animate = {}; + } + me.animate(Ext.applyIf({ + to: { + height: height + } + }, animate)); + } + + return me; + }, + + applyStyles: function(style) { + Ext.DomHelper.applyStyles(this.dom, style); + return this; + }, + + setSize: function(width, height, animate) { + var me = this; + + if (Ext.isObject(width)) { // in case of object from getSize() + animate = height; + 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 { + if (animate === true) { + animate = {}; + } + me.animate(Ext.applyIf({ + to: { + width: width, + height: height + } + }, animate)); + } + + return me; + }, + + getViewSize : function() { + var me = this, + dom = me.dom, + isDoc = DOCORBODYRE.test(dom.nodeName), + ret; + + // If the body, use static methods + if (isDoc) { + ret = { + width : Element.getViewWidth(), + height : Element.getViewHeight() + }; + } else { + ret = { + width : dom.clientWidth, + height : dom.clientHeight + }; + } + + return ret; + }, + + getSize: function(contentSize) { + return {width: this.getWidth(contentSize), height: this.getHeight(contentSize)}; + }, + + // TODO: Look at this + + // private ==> used by Fx + adjustWidth : function(width) { + var me = this, + isNum = (typeof width == 'number'); + + if (isNum && me.autoBoxAdjust && !me.isBorderBox()) { + width -= (me.getBorderWidth("lr") + me.getPadding("lr")); + } + return (isNum && width < 0) ? 0 : width; + }, + + // private ==> used by Fx + adjustHeight : function(height) { + var me = this, + isNum = (typeof height == "number"); + + if (isNum && me.autoBoxAdjust && !me.isBorderBox()) { + height -= (me.getBorderWidth("tb") + me.getPadding("tb")); + } + return (isNum && height < 0) ? 0 : height; + }, + + /** + * 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] defaults to #. Use an empty string when working with + * color anims. + */ + getColor : function(attr, defaultValue, prefix) { + var v = this.getStyle(attr), + color = prefix || prefix === '' ? prefix : '#', + h, len, i=0; + + if (!v || (/transparent|inherit/.test(v))) { + return defaultValue; + } + if (/^r/.test(v)) { + v = v.slice(4, v.length - 1).split(','); + len = v.length; + for (; i 5 ? color.toLowerCase() : defaultValue); + }, + + /** + * Set the opacity of the element + * @param {Number} opacity The new opacity. 0 = transparent, .5 = 50% visibile, 1 = fully visible, etc + * @param {Boolean/Object} [animate] a standard Element animation config object or `true` for + * the default animation (`{duration: .35, easing: 'easeIn'}`) + * @return {Ext.dom.Element} this + */ + setOpacity: function(opacity, animate) { + var me = this; + + if (!me.dom) { + return me; + } + + if (!animate || !me.anim) { + me.setStyle('opacity', opacity); + } + else { + if (typeof animate != 'object') { + animate = { + duration: 350, + easing: 'ease-in' + }; + } + + me.animate(Ext.applyIf({ + to: { + opacity: opacity + } + }, animate)); + } + return me; + }, + + /** + * Clears any opacity settings from this element. Required in some cases for IE. + * @return {Ext.dom.Element} this + */ + clearOpacity : function() { + return this.setOpacity(''); + }, + + /** + * @private + * Returns 1 if the browser returns the subpixel dimension rounded to the lowest pixel. + * @return {Number} 0 or 1 + */ + adjustDirect2DDimension: function(dimension) { + var me = this, + dom = me.dom, + display = me.getStyle('display'), + inlineDisplay = dom.style.display, + inlinePosition = dom.style.position, + originIndex = dimension === WIDTH ? 0 : 1, + currentStyle = dom.currentStyle, + floating; + + if (display === 'inline') { + dom.style.display = 'inline-block'; + } + + dom.style.position = display.match(adjustDirect2DTableRe) ? 'absolute' : 'static'; + + // floating will contain digits that appears after the decimal point + // if height or width are set to auto we fallback to msTransformOrigin calculation + + // Use currentStyle here instead of getStyle. In some difficult to reproduce + // instances it resets the scrollWidth of the element + floating = (parseFloat(currentStyle[dimension]) || parseFloat(currentStyle.msTransformOrigin.split(' ')[originIndex]) * 2) % 1; + + dom.style.position = inlinePosition; + + if (display === 'inline') { + dom.style.display = inlineDisplay; + } + + return floating; + }, + + /** + * Store the current overflow setting and clip overflow on the element - use {@link #unclip} to remove + * @return {Ext.dom.Element} this + */ + clip : function() { + var me = this, + data = (me.$cache || me.getCache()).data, + style; + + if (!data[ISCLIPPED]) { + data[ISCLIPPED] = true; + style = me.getStyle([OVERFLOW, OVERFLOWX, OVERFLOWY]); + data[ORIGINALCLIP] = { + o: style[OVERFLOW], + x: style[OVERFLOWX], + y: style[OVERFLOWY] + }; + me.setStyle(OVERFLOW, HIDDEN); + me.setStyle(OVERFLOWX, HIDDEN); + me.setStyle(OVERFLOWY, HIDDEN); + } + return me; + }, + + /** + * Return clipping (overflow) to original clipping before {@link #clip} was called + * @return {Ext.dom.Element} this + */ + unclip : function() { + var me = this, + data = (me.$cache || me.getCache()).data, + clip; + + if (data[ISCLIPPED]) { + data[ISCLIPPED] = false; + clip = data[ORIGINALCLIP]; + if (clip.o) { + me.setStyle(OVERFLOW, clip.o); + } + if (clip.x) { + me.setStyle(OVERFLOWX, clip.x); + } + if (clip.y) { + me.setStyle(OVERFLOWY, clip.y); + } + } + return me; + }, + + /** + * 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.Button}, + * {@link Ext.panel.Panel} when {@link Ext.panel.Panel#frame frame=true}, {@link Ext.window.Window}). + * The markup is of this form: + * + * Ext.dom.Element.boxMarkup = + * '
    + *
    + *
    '; + * + * 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().addCls("x-box-blue"); + * + * @param {String} [class='x-box'] A base CSS class to apply to the containing wrapper element. + * 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.dom.Element} The outermost wrapping element of the created box structure. + */ + boxWrap : function(cls) { + cls = cls || Ext.baseCSSPrefix + 'box'; + var el = Ext.get(this.insertHtml("beforeBegin", "
    " + Ext.String.format(Element.boxMarkup, cls) + "
    ")); + Ext.DomQuery.selectNode('.' + cls + '-mc', el.dom).appendChild(this.dom); + return el; + }, + + /** + * Returns either the offsetHeight or the height of this element based on CSS height adjusted by padding or borders + * when needed to simulate offsetHeight when offsets aren't available. This may not work on display:none elements + * if a height has not been set using CSS. + * @return {Number} + */ + getComputedHeight : function() { + var me = this, + h = Math.max(me.dom.offsetHeight, me.dom.clientHeight); + if (!h) { + h = parseFloat(me.getStyle(HEIGHT)) || 0; + if (!me.isBorderBox()) { + h += me.getFrameWidth('tb'); + } + } + return h; + }, + + /** + * Returns either the offsetWidth or the width of this element based on CSS width adjusted by padding or borders + * when needed to simulate offsetWidth when offsets aren't available. This may not work on display:none elements + * if a width has not been set using CSS. + * @return {Number} + */ + getComputedWidth : function() { + var me = this, + w = Math.max(me.dom.offsetWidth, me.dom.clientWidth); + + if (!w) { + w = parseFloat(me.getStyle(WIDTH)) || 0; + if (!me.isBorderBox()) { + w += me.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 The class to add + * @param {Function} [testFn] A test function to execute before adding the class. The passed parameter + * will be the Element instance. If this functions returns false, the class will not be added. + * @param {Object} [scope] The scope to execute the testFn in. + * @return {Ext.dom.Element} this + */ + addClsOnOver : function(className, testFn, scope) { + var me = this, + dom = me.dom, + hasTest = Ext.isFunction(testFn); + + me.hover( + function() { + if (hasTest && testFn.call(scope || me, me) === false) { + return; + } + Ext.fly(dom, INTERNAL).addCls(className); + }, + function() { + Ext.fly(dom, INTERNAL).removeCls(className); + } + ); + return me; + }, + + /** + * Sets up event handlers to add and remove a css class when this element has the focus + * @param {String} className The class to add + * @param {Function} [testFn] A test function to execute before adding the class. The passed parameter + * will be the Element instance. If this functions returns false, the class will not be added. + * @param {Object} [scope] The scope to execute the testFn in. + * @return {Ext.dom.Element} this + */ + addClsOnFocus : function(className, testFn, scope) { + var me = this, + dom = me.dom, + hasTest = Ext.isFunction(testFn); + + me.on("focus", function() { + if (hasTest && testFn.call(scope || me, me) === false) { + return false; + } + Ext.fly(dom, INTERNAL).addCls(className); + }); + me.on("blur", function() { + Ext.fly(dom, INTERNAL).removeCls(className); + }); + return me; + }, + + /** + * 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 The class to add + * @param {Function} [testFn] A test function to execute before adding the class. The passed parameter + * will be the Element instance. If this functions returns false, the class will not be added. + * @param {Object} [scope] The scope to execute the testFn in. + * @return {Ext.dom.Element} this + */ + addClsOnClick : function(className, testFn, scope) { + var me = this, + dom = me.dom, + hasTest = Ext.isFunction(testFn); + + me.on("mousedown", function() { + if (hasTest && testFn.call(scope || me, me) === false) { + return false; + } + Ext.fly(dom, INTERNAL).addCls(className); + var d = Ext.getDoc(), + fn = function() { + Ext.fly(dom, INTERNAL).removeCls(className); + d.removeListener("mouseup", fn); + }; + d.on("mouseup", fn); + }); + return me; + }, + + /** + * Returns the dimensions of the element available to lay content out in. + * + * getStyleSize utilizes prefers style sizing if present, otherwise it chooses the larger of offsetHeight/clientHeight and + * offsetWidth/clientWidth. To obtain the size excluding scrollbars, use getViewSize. + * + * Sizing of the document body is handled at the adapter level which handles special cases for IE and strict modes, etc. + * + * @return {Object} Object describing width and height. + * @return {Number} return.width + * @return {Number} return.height + */ + getStyleSize : function() { + var me = this, + d = this.dom, + isDoc = DOCORBODYRE.test(d.nodeName), + s , + w, h; + + // If the body, use static methods + if (isDoc) { + return { + width : Element.getViewWidth(), + height : Element.getViewHeight() + }; + } + + s = me.getStyle([HEIGHT, WIDTH], true); //seek inline + // Use Styles if they are set + if (s.width && s.width != 'auto') { + w = parseFloat(s.width); + if (me.isBorderBox()) { + w -= me.getFrameWidth('lr'); + } + } + // Use Styles if they are set + if (s.height && s.height != 'auto') { + h = parseFloat(s.height); + if (me.isBorderBox()) { + h -= me.getFrameWidth('tb'); + } + } + // Use getWidth/getHeight if style not set. + return {width: w || me.getWidth(true), height: h || me.getHeight(true)}; + }, + + /** + * Enable text selection for this element (normalized across browsers) + * @return {Ext.Element} this + */ + selectable : function() { + var me = this; + me.dom.unselectable = "off"; + // Prevent it from bubles up and enables it to be selectable + me.on('selectstart', function (e) { + e.stopPropagation(); + return true; + }); + me.applyStyles("-moz-user-select: text; -khtml-user-select: text;"); + me.removeCls(Ext.baseCSSPrefix + 'unselectable'); + return me; + }, + + /** + * Disables text selection for this element (normalized across browsers) + * @return {Ext.dom.Element} this + */ + unselectable : function() { + var me = this; + me.dom.unselectable = "on"; + + me.swallowEvent("selectstart", true); + me.applyStyles("-moz-user-select:-moz-none;-khtml-user-select:none;"); + me.addCls(Ext.baseCSSPrefix + 'unselectable'); + + return me; + } +}); + +Element.prototype.styleHooks = styleHooks = Ext.dom.AbstractElement.prototype.styleHooks; + +if (Ext.isIE6) { + styleHooks.fontSize = styleHooks['font-size'] = { + name: 'fontSize', + canThrow: true + }; +} + +// override getStyle for border-*-width +if (Ext.isIEQuirks || Ext.isIE && Ext.ieVersion <= 8) { + function getBorderWidth (dom, el, inline, style) { + if (style[this.styleName] == 'none') { + return '0px'; + } + return style[this.name]; + } + + edges = ['Top','Right','Bottom','Left']; + k = edges.length; + + while (k--) { + edge = edges[k]; + borderWidth = 'border' + edge + 'Width'; + + styleHooks['border-'+edge.toLowerCase()+'-width'] = styleHooks[borderWidth] = { + name: borderWidth, + styleName: 'border' + edge + 'Style', + get: getBorderWidth + }; + } +} + +}()); + +Ext.onReady(function () { + var opacityRe = /alpha\(opacity=(.*)\)/i, + trimRe = /^\s+|\s+$/g, + hooks = Ext.dom.Element.prototype.styleHooks; + + // Ext.supports flags are not populated until onReady... + hooks.opacity = { + name: 'opacity', + afterSet: function(dom, value, el) { + if (el.isLayer) { + el.onOpacitySet(value); + } + } + }; + if (!Ext.supports.Opacity && Ext.isIE) { + Ext.apply(hooks.opacity, { + get: function (dom) { + var filter = dom.style.filter, + match, opacity; + if (filter.match) { + match = filter.match(opacityRe); + if (match) { + opacity = parseFloat(match[1]); + if (!isNaN(opacity)) { + return opacity ? opacity / 100 : 0; + } + } + } + return 1; + }, + set: function (dom, value) { + var style = dom.style, + val = style.filter.replace(opacityRe, '').replace(trimRe, ''); + + style.zoom = 1; // ensure dom.hasLayout + + // value can be a number or '' or null... so treat falsey as no opacity + if (typeof(value) == 'number' && value >= 0 && value < 1) { + value *= 100; + style.filter = val + (val.length ? ' ' : '') + 'alpha(opacity='+value+')'; + } else { + style.filter = val; + } + } + }); + } + // else there is no work around for the lack of opacity support. Should not be a + // problem given that this has been supported for a long time now... +}); + +/** + * @class Ext.dom.Element + */ +Ext.dom.Element.override({ + select: function(selector) { + return Ext.dom.Element.select(selector, false, this.dom); + } +}); + +/** + * 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.dom.Element} and + * {@link Ext.fx.Anim}. 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.define('Ext.dom.CompositeElementLite', { + alternateClassName: 'Ext.CompositeElementLite', + + requires: ['Ext.dom.Element'], + + statics: { + /** + * @private + * Copies all of the functions from Ext.dom.Element's prototype onto CompositeElementLite's prototype. + * This is called twice - once immediately below, and once again after additional Ext.dom.Element + * are added in Ext JS + */ + importElementMethods: function() { + var name, + elementPrototype = Ext.dom.Element.prototype, + prototype = this.prototype; + + for (name in elementPrototype) { + if (typeof elementPrototype[name] == 'function'){ + (function(key) { + prototype[key] = prototype[key] || function() { + return this.invoke(key, arguments); + }; + }).call(prototype, name); + + } + } + } + }, + + constructor: function(elements, root) { + /** + * @property {HTMLElement[]} elements + * The Array of DOM elements which this CompositeElement encapsulates. + * + * 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.dom.CompositeElementLite, { + * nextAll: function() { + * var elements = this.elements, i, l = elements.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 = elements[i].nextSibling; n; n = n.nextSibling) { + * r[++ri] = n; + * } + * } + * + * // Add all found siblings to this Composite + * return this.add(r); + * } + * }); + * + * @readonly + */ + this.elements = []; + this.add(elements, root); + this.el = new Ext.dom.AbstractElement.Fly(); + }, + + /** + * @property {Boolean} isComposite + * `true` in this class to identify an object as an instantiated CompositeElement, or subclass thereof. + */ + isComposite: true, + + // private + getElement: function(el) { + // Set the shared flyweight dom property to the current element + return this.el.attach(el); + }, + + // private + transformElement: function(el) { + return Ext.getDom(el); + }, + + /** + * Returns the number of elements in this Composite. + * @return {Number} + */ + getCount: function() { + return this.elements.length; + }, + + /** + * Adds elements to this Composite object. + * @param {HTMLElement[]/Ext.dom.CompositeElement} els Either an Array of DOM elements to add, or another Composite + * object who's elements should be added. + * @return {Ext.dom.CompositeElement} This Composite object. + */ + add: function(els, root) { + var elements = this.elements, + i, ln; + + if (!els) { + return this; + } + + if (typeof els == "string") { + els = Ext.dom.Element.selectorFunction(els, root); + } + else if (els.isComposite) { + els = els.elements; + } + else if (!Ext.isIterable(els)) { + els = [els]; + } + + for (i = 0, ln = els.length; i < ln; ++i) { + elements.push(this.transformElement(els[i])); + } + + return this; + }, + + invoke: function(fn, args) { + var elements = this.elements, + ln = elements.length, + element, + i; + + fn = Ext.dom.Element.prototype[fn]; + for (i = 0; i < ln; i++) { + element = elements[i]; + + if (element) { + fn.apply(this.getElement(element), args); + } + } + return this; + }, + + /** + * Returns a flyweight Element of the dom element object at the specified index + * @param {Number} index + * @return {Ext.dom.Element} + */ + item: function(index) { + var el = this.elements[index], + out = null; + + if (el) { + out = this.getElement(el); + } + + return out; + }, + + // fixes scope with flyweight + addListener: function(eventName, handler, scope, opt) { + var els = this.elements, + len = els.length, + i, e; + + for (i = 0; i < len; i++) { + e = els[i]; + if (e) { + Ext.EventManager.on(e, eventName, handler, scope || e, opt); + } + } + return this; + }, + /** + * Calls the passed function for each element in this composite. + * @param {Function} fn The function to call. + * @param {Ext.dom.Element} fn.el The current Element in the iteration. **This is the flyweight + * (shared) Ext.dom.Element instance, so if you require a a reference to the dom node, use el.dom.** + * @param {Ext.dom.CompositeElement} fn.c This Composite object. + * @param {Number} fn.index The zero-based index in the iteration. + * @param {Object} [scope] The scope (this reference) in which the function is executed. + * Defaults to the Element. + * @return {Ext.dom.CompositeElement} this + */ + each: function(fn, scope) { + var me = this, + els = me.elements, + len = els.length, + i, e; + + for (i = 0; i < len; i++) { + e = els[i]; + if (e) { + e = this.getElement(e); + if (fn.call(scope || e, e, me, i) === false) { + break; + } + } + } + return me; + }, + + /** + * Clears this Composite and adds the elements passed. + * @param {HTMLElement[]/Ext.dom.CompositeElement} els Either an array of DOM elements, or another Composite from which + * to fill this Composite. + * @return {Ext.dom.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: + * @param {Ext.dom.Element} selector.el The current DOM element. + * @param {Number} selector.index The current index within the collection. + * @return {Ext.dom.CompositeElement} this + */ + filter: function(selector) { + var me = this, + els = me.elements, + len = els.length, + out = [], + i = 0, + isFunc = typeof selector == 'function', + add, + el; + + for (; i < len; i++) { + el = els[i]; + add = false; + if (el) { + el = me.getElement(el); + + if (isFunc) { + add = selector.call(el, el, me, i) !== false; + } else { + add = el.is(selector); + } + + if (add) { + out.push(me.transformElement(el)); + } + } + } + + me.elements = out; + return me; + }, + + /** + * Find the index of the passed element within the composite collection. + * @param {String/HTMLElement/Ext.Element/Number} el The id of an element, or an Ext.dom.Element, or an HtmlElement + * to find within the composite collection. + * @return {Number} The index of the passed Ext.dom.Element in the composite collection, or -1 if not found. + */ + indexOf: function(el) { + return Ext.Array.indexOf(this.elements, this.transformElement(el)); + }, + + /** + * Replaces the specified element with the passed element. + * @param {String/HTMLElement/Ext.Element/Number} el The id of an element, the Element itself, the index of the + * element in this composite to replace. + * @param {String/Ext.Element} replacement The id of an element or the Element itself. + * @param {Boolean} [domReplace] True to remove and replace the element in the document too. + * @return {Ext.dom.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); + } + Ext.Array.splice(this.elements, index, 1, replacement); + } + return this; + }, + + /** + * Removes all elements. + */ + clear: function() { + this.elements = []; + }, + + addElements: function(els, root) { + if (!els) { + return this; + } + + if (typeof els == "string") { + els = Ext.dom.Element.selectorFunction(els, root); + } + + var yels = this.elements, + eLen = els.length, + e; + + for (e = 0; e < eLen; e++) { + yels.push(Ext.get(els[e])); + } + + return this; + }, + + /** + * Returns the first Element + * @return {Ext.dom.Element} + */ + first: function() { + return this.item(0); + }, + + /** + * Returns the last Element + * @return {Ext.dom.Element} + */ + last: function() { + return this.item(this.getCount() - 1); + }, + + /** + * Returns true if this composite contains the passed element + * @param {String/HTMLElement/Ext.Element/Number} el 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 {String/HTMLElement/Ext.Element/Number} 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] True to also remove the element from the document + * @return {Ext.dom.CompositeElement} this + */ + removeElement: function(keys, removeDom) { + keys = [].concat(keys); + + var me = this, + elements = me.elements, + kLen = keys.length, + val, el, k; + + for (k = 0; k < kLen; k++) { + val = keys[k]; + + if ((el = (elements[val] || elements[val = me.indexOf(val)]))) { + if (removeDom) { + if (el.dom) { + el.remove(); + } else { + Ext.removeNode(el); + } + } + Ext.Array.erase(elements, val, 1); + } + } + + return me; + } + +}, function() { + this.importElementMethods(); + + this.prototype.on = this.prototype.addListener; + + if (Ext.DomQuery){ + Ext.dom.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.dom.CompositeElement CompositeElement} or + * {@link Ext.dom.CompositeElementLite CompositeElementLite} object. + * @param {String/HTMLElement[]} selector The CSS selector or an array of elements + * @param {HTMLElement/String} [root] The root element of the query or id of the root + * @return {Ext.dom.CompositeElementLite/Ext.dom.CompositeElement} + * @member Ext.dom.Element + * @method select + * @static + */ + Ext.dom.Element.select = function(selector, root) { + var elements; + + if (typeof selector == "string") { + elements = Ext.dom.Element.selectorFunction(selector, root); + } + else if (selector.length !== undefined) { + elements = selector; + } + else { + throw new Error("[Ext.select] Invalid selector specified: " + selector); + } + + return new Ext.CompositeElementLite(elements); + }; + + /** + * @member Ext + * @method select + * @inheritdoc Ext.dom.Element#select + */ + Ext.select = function() { + return Ext.dom.Element.select.apply(Ext.dom.Element, arguments); + }; +}); + +/** + * @class Ext.dom.CompositeElement + *

    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.dom.Element} and + * {@link Ext.fx.Anim}. The methods from these classes will be performed on all the elements in this collection.

    + *

    All methods return this and can be chained.

    + * Usage: +
    
    + 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.define('Ext.dom.CompositeElement', { + alternateClassName: 'Ext.CompositeElement', + + extend: 'Ext.dom.CompositeElementLite', + + // private + getElement: function(el) { + // In this case just return it, since we already have a reference to it + return el; + }, + + // private + transformElement: function(el) { + return Ext.get(el); + } + +}, function() { + /** + * 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/HTMLElement[]} selector The CSS selector or an array of elements + * @param {Boolean} [unique] true to create a unique Ext.Element for each element (defaults to a shared flyweight object) + * @param {HTMLElement/String} [root] The root element of the query or id of the root + * @return {Ext.CompositeElementLite/Ext.CompositeElement} + * @member Ext.dom.Element + * @method select + * @static + */ + + Ext.dom.Element.select = function(selector, unique, root) { + var elements; + + if (typeof selector == "string") { + elements = Ext.dom.Element.selectorFunction(selector, root); + } + else if (selector.length !== undefined) { + elements = selector; + } + else { + throw new Error("[Ext.select] Invalid selector specified: " + selector); + } + return (unique === true) ? new Ext.CompositeElement(elements) : new Ext.CompositeElementLite(elements); + }; +}); + +/** + * Shorthand of {@link Ext.Element#method-select}. + * @member Ext + * @method select + * @inheritdoc Ext.Element#select + */ +Ext.select = Ext.Element.select; + + +/** + * The AbstractPlugin class is the base class from which user-implemented plugins should inherit. + * + * This class defines the essential API of plugins as used by Components by defining the following methods: + * + * - `init` : The plugin initialization method which the owning Component calls at Component initialization time. + * + * The Component passes itself as the sole parameter. + * + * Subclasses should set up bidirectional links between the plugin and its client Component here. + * + * - `destroy` : The plugin cleanup method which the owning Component calls at Component destruction time. + * + * Use this method to break links between the plugin and the Component and to free any allocated resources. + * + * - `enable` : The base implementation just sets the plugin's `disabled` flag to `false` + * + * - `disable` : The base implementation just sets the plugin's `disabled` flag to `true` + */ +Ext.define('Ext.AbstractPlugin', { + disabled: false, + + constructor: function(config) { + if (!config.cmp && Ext.global.console) { + Ext.global.console.warn("Attempted to attach a plugin "); + } + Ext.apply(this, config); + }, + + getCmp: function() { + return this.cmp; + }, + + /** + * @method + * The init method is invoked after initComponent method has been run for the client Component. + * + * The supplied implementation is empty. Subclasses should perform plugin initialization, and set up bidirectional + * links between the plugin and its client Component in their own implementation of this method. + * @param {Ext.Component} client The client Component which owns this plugin. + */ + init: Ext.emptyFn, + + /** + * @method + * The destroy method is invoked by the owning Component at the time the Component is being destroyed. + * + * The supplied implementation is empty. Subclasses should perform plugin cleanup in their own implementation of + * this method. + */ + destroy: Ext.emptyFn, + + /** + * The base implementation just sets the plugin's `disabled` flag to `false` + * + * Plugin subclasses which need more complex processing may implement an overriding implementation. + */ + enable: function() { + this.disabled = false; + }, + + /** + * The base implementation just sets the plugin's `disabled` flag to `true` + * + * Plugin subclasses which need more complex processing may implement an overriding implementation. + */ + disable: function() { + this.disabled = true; + } +}); +/** + * Provides searching of Components within Ext.ComponentManager (globally) or a specific + * Ext.container.Container on the document with a similar syntax to a CSS selector. + * + * Components can be retrieved by using their {@link Ext.Component xtype} with an optional . prefix + * + * - `component` or `.component` + * - `gridpanel` or `.gridpanel` + * + * An itemId or id must be prefixed with a # + * + * - `#myContainer` + * + * Attributes must be wrapped in brackets + * + * - `component[autoScroll]` + * - `panel[title="Test"]` + * + * Member expressions from candidate Components may be tested. If the expression returns a *truthy* value, + * the candidate Component will be included in the query: + * + * var disabledFields = myFormPanel.query("{isDisabled()}"); + * + * Pseudo classes may be used to filter results in the same way as in {@link Ext.DomQuery DomQuery}: + * + * // Function receives array and returns a filtered array. + * Ext.ComponentQuery.pseudos.invalid = function(items) { + * var i = 0, l = items.length, c, result = []; + * for (; i < l; i++) { + * if (!(c = items[i]).isValid()) { + * result.push(c); + * } + * } + * return result; + * }; + * + * var invalidFields = myFormPanel.query('field:invalid'); + * if (invalidFields.length) { + * invalidFields[0].getEl().scrollIntoView(myFormPanel.body); + * for (var i = 0, l = invalidFields.length; i < l; i++) { + * invalidFields[i].getEl().frame("red"); + * } + * } + * + * Default pseudos include: + * + * - not + * - last + * + * Queries return an array of components. + * Here are some example queries. + * + * // retrieve all Ext.Panels in the document by xtype + * var panelsArray = Ext.ComponentQuery.query('panel'); + * + * // retrieve all Ext.Panels within the container with an id myCt + * var panelsWithinmyCt = Ext.ComponentQuery.query('#myCt panel'); + * + * // retrieve all direct children which are Ext.Panels within myCt + * var directChildPanel = Ext.ComponentQuery.query('#myCt > panel'); + * + * // retrieve all grids and trees + * var gridsAndTrees = Ext.ComponentQuery.query('gridpanel, treepanel'); + * + * For easy access to queries based from a particular Container see the {@link Ext.container.Container#query}, + * {@link Ext.container.Container#down} and {@link Ext.container.Container#child} methods. Also see + * {@link Ext.Component#up}. + */ +Ext.define('Ext.ComponentQuery', { + singleton: true, + uses: ['Ext.ComponentManager'] +}, function() { + + var cq = this, + + // A function source code pattern with a placeholder which accepts an expression which yields a truth value when applied + // as a member on each item in the passed array. + filterFnPattern = [ + 'var r = [],', + 'i = 0,', + 'it = items,', + 'l = it.length,', + 'c;', + 'for (; i < l; i++) {', + 'c = it[i];', + 'if (c.{0}) {', + 'r.push(c);', + '}', + '}', + 'return r;' + ].join(''), + + filterItems = function(items, operation) { + // Argument list for the operation is [ itemsArray, operationArg1, operationArg2...] + // The operation's method loops over each item in the candidate array and + // returns an array of items which match its criteria + return operation.method.apply(this, [ items ].concat(operation.args)); + }, + + getItems = function(items, mode) { + var result = [], + i = 0, + length = items.length, + candidate, + deep = mode !== '>'; + + for (; i < length; i++) { + candidate = items[i]; + if (candidate.getRefItems) { + result = result.concat(candidate.getRefItems(deep)); + } + } + return result; + }, + + getAncestors = function(items) { + var result = [], + i = 0, + length = items.length, + candidate; + for (; i < length; i++) { + candidate = items[i]; + while (!!(candidate = (candidate.ownerCt || candidate.floatParent))) { + result.push(candidate); + } + } + return result; + }, + + // Filters the passed candidate array and returns only items which match the passed xtype + filterByXType = function(items, xtype, shallow) { + if (xtype === '*') { + return items.slice(); + } + else { + var result = [], + i = 0, + length = items.length, + candidate; + for (; i < length; i++) { + candidate = items[i]; + if (candidate.isXType(xtype, shallow)) { + result.push(candidate); + } + } + return result; + } + }, + + // Filters the passed candidate array and returns only items which have the passed className + filterByClassName = function(items, className) { + var EA = Ext.Array, + result = [], + i = 0, + length = items.length, + candidate; + for (; i < length; i++) { + candidate = items[i]; + if (candidate.hasCls(className)) { + result.push(candidate); + } + } + return result; + }, + + // Filters the passed candidate array and returns only items which have the specified property match + filterByAttribute = function(items, property, operator, value) { + var result = [], + i = 0, + length = items.length, + candidate; + for (; i < length; i++) { + candidate = items[i]; + if (!value ? !!candidate[property] : (String(candidate[property]) === value)) { + result.push(candidate); + } + } + return result; + }, + + // Filters the passed candidate array and returns only items which have the specified itemId or id + filterById = function(items, id) { + var result = [], + i = 0, + length = items.length, + candidate; + for (; i < length; i++) { + candidate = items[i]; + if (candidate.getItemId() === id) { + result.push(candidate); + } + } + return result; + }, + + // Filters the passed candidate array and returns only items which the named pseudo class matcher filters in + filterByPseudo = function(items, name, value) { + return cq.pseudos[name](items, value); + }, + + // Determines leading mode + // > for direct child, and ^ to switch to ownerCt axis + modeRe = /^(\s?([>\^])\s?|\s|$)/, + + // Matches a token with possibly (true|false) appended for the "shallow" parameter + tokenRe = /^(#)?([\w\-]+|\*)(?:\((true|false)\))?/, + + matchers = [{ + // Checks for .xtype with possibly (true|false) appended for the "shallow" parameter + re: /^\.([\w\-]+)(?:\((true|false)\))?/, + method: filterByXType + },{ + // checks for [attribute=value] + re: /^(?:[\[](?:@)?([\w\-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]])/, + method: filterByAttribute + }, { + // checks for #cmpItemId + re: /^#([\w\-]+)/, + method: filterById + }, { + // checks for :() + re: /^\:([\w\-]+)(?:\(((?:\{[^\}]+\})|(?:(?!\{)[^\s>\/]*?(?!\})))\))?/, + method: filterByPseudo + }, { + // checks for {} + re: /^(?:\{([^\}]+)\})/, + method: filterFnPattern + }]; + + // Internal class Ext.ComponentQuery.Query + cq.Query = Ext.extend(Object, { + constructor: function(cfg) { + cfg = cfg || {}; + Ext.apply(this, cfg); + }, + + // Executes this Query upon the selected root. + // The root provides the initial source of candidate Component matches which are progressively + // filtered by iterating through this Query's operations cache. + // If no root is provided, all registered Components are searched via the ComponentManager. + // root may be a Container who's descendant Components are filtered + // root may be a Component with an implementation of getRefItems which provides some nested Components such as the + // docked items within a Panel. + // root may be an array of candidate Components to filter using this Query. + execute : function(root) { + var operations = this.operations, + i = 0, + length = operations.length, + operation, + workingItems; + + // no root, use all Components in the document + if (!root) { + workingItems = Ext.ComponentManager.all.getArray(); + } + // Root is a candidate Array + else if (Ext.isArray(root)) { + workingItems = root; + } + // Root is a MixedCollection + else if (root.isMixedCollection) { + workingItems = root.items; + } + + // We are going to loop over our operations and take care of them + // one by one. + for (; i < length; i++) { + operation = operations[i]; + + // The mode operation requires some custom handling. + // All other operations essentially filter down our current + // working items, while mode replaces our current working + // items by getting children from each one of our current + // working items. The type of mode determines the type of + // children we get. (e.g. > only gets direct children) + if (operation.mode === '^') { + workingItems = getAncestors(workingItems || [root]); + } + else if (operation.mode) { + workingItems = getItems(workingItems || [root], operation.mode); + } + else { + workingItems = filterItems(workingItems || getItems([root]), operation); + } + + // If this is the last operation, it means our current working + // items are the final matched items. Thus return them! + if (i === length -1) { + return workingItems; + } + } + return []; + }, + + is: function(component) { + var operations = this.operations, + components = Ext.isArray(component) ? component : [component], + originalLength = components.length, + lastOperation = operations[operations.length-1], + ln, i; + + components = filterItems(components, lastOperation); + if (components.length === originalLength) { + if (operations.length > 1) { + for (i = 0, ln = components.length; i < ln; i++) { + if (Ext.Array.indexOf(this.execute(), components[i]) === -1) { + return false; + } + } + } + return true; + } + return false; + } + }); + + Ext.apply(this, { + + // private cache of selectors and matching ComponentQuery.Query objects + cache: {}, + + // private cache of pseudo class filter functions + pseudos: { + not: function(components, selector){ + var CQ = Ext.ComponentQuery, + i = 0, + length = components.length, + results = [], + index = -1, + component; + + for(; i < length; ++i) { + component = components[i]; + if (!CQ.is(component, selector)) { + results[++index] = component; + } + } + return results; + }, + last: function(components) { + return components[components.length - 1]; + } + }, + + /** + * Returns an array of matched Components from within the passed root object. + * + * This method filters returned Components in a similar way to how CSS selector based DOM + * queries work using a textual selector string. + * + * See class summary for details. + * + * @param {String} selector The selector string to filter returned Components + * @param {Ext.container.Container} root The Container within which to perform the query. + * If omitted, all Components within the document are included in the search. + * + * This parameter may also be an array of Components to filter according to the selector.

    + * @returns {Ext.Component[]} The matched Components. + * + * @member Ext.ComponentQuery + */ + query: function(selector, root) { + var selectors = selector.split(','), + length = selectors.length, + i = 0, + results = [], + noDupResults = [], + dupMatcher = {}, + query, resultsLn, cmp; + + for (; i < length; i++) { + selector = Ext.String.trim(selectors[i]); + query = this.cache[selector] || (this.cache[selector] = this.parse(selector)); + results = results.concat(query.execute(root)); + } + + // multiple selectors, potential to find duplicates + // lets filter them out. + if (length > 1) { + resultsLn = results.length; + for (i = 0; i < resultsLn; i++) { + cmp = results[i]; + if (!dupMatcher[cmp.id]) { + noDupResults.push(cmp); + dupMatcher[cmp.id] = true; + } + } + results = noDupResults; + } + return results; + }, + + /** + * Tests whether the passed Component matches the selector string. + * @param {Ext.Component} component The Component to test + * @param {String} selector The selector string to test against. + * @return {Boolean} True if the Component matches the selector. + * @member Ext.ComponentQuery + */ + is: function(component, selector) { + if (!selector) { + return true; + } + var selectors = selector.split(','), + length = selectors.length, + i = 0, + query; + + for (; i < length; i++) { + selector = Ext.String.trim(selectors[i]); + query = this.cache[selector] || (this.cache[selector] = this.parse(selector)); + if (query.is(component)) { + return true; + } + } + }, + + parse: function(selector) { + var operations = [], + length = matchers.length, + lastSelector, + tokenMatch, + matchedChar, + modeMatch, + selectorMatch, + i, matcher, method; + + // We are going to parse the beginning of the selector over and + // over again, slicing off the selector any portions we converted into an + // operation, until it is an empty string. + while (selector && lastSelector !== selector) { + lastSelector = selector; + + // First we check if we are dealing with a token like #, * or an xtype + tokenMatch = selector.match(tokenRe); + + if (tokenMatch) { + matchedChar = tokenMatch[1]; + + // If the token is prefixed with a # we push a filterById operation to our stack + if (matchedChar === '#') { + operations.push({ + method: filterById, + args: [Ext.String.trim(tokenMatch[2])] + }); + } + // If the token is prefixed with a . we push a filterByClassName operation to our stack + // FIXME: Not enabled yet. just needs \. adding to the tokenRe prefix + else if (matchedChar === '.') { + operations.push({ + method: filterByClassName, + args: [Ext.String.trim(tokenMatch[2])] + }); + } + // If the token is a * or an xtype string, we push a filterByXType + // operation to the stack. + else { + operations.push({ + method: filterByXType, + args: [Ext.String.trim(tokenMatch[2]), Boolean(tokenMatch[3])] + }); + } + + // Now we slice of the part we just converted into an operation + selector = selector.replace(tokenMatch[0], ''); + } + + // If the next part of the query is not a space or > or ^, it means we + // are going to check for more things that our current selection + // has to comply to. + while (!(modeMatch = selector.match(modeRe))) { + // Lets loop over each type of matcher and execute it + // on our current selector. + for (i = 0; selector && i < length; i++) { + matcher = matchers[i]; + selectorMatch = selector.match(matcher.re); + method = matcher.method; + + // If we have a match, add an operation with the method + // associated with this matcher, and pass the regular + // expression matches are arguments to the operation. + if (selectorMatch) { + operations.push({ + method: Ext.isString(matcher.method) + // Turn a string method into a function by formatting the string with our selector matche expression + // A new method is created for different match expressions, eg {id=='textfield-1024'} + // Every expression may be different in different selectors. + ? Ext.functionFactory('items', Ext.String.format.apply(Ext.String, [method].concat(selectorMatch.slice(1)))) + : matcher.method, + args: selectorMatch.slice(1) + }); + selector = selector.replace(selectorMatch[0], ''); + break; // Break on match + } + // Exhausted all matches: It's an error + if (i === (length - 1)) { + Ext.Error.raise('Invalid ComponentQuery selector: "' + arguments[0] + '"'); + } + } + } + + // Now we are going to check for a mode change. This means a space + // or a > to determine if we are going to select all the children + // of the currently matched items, or a ^ if we are going to use the + // ownerCt axis as the candidate source. + if (modeMatch[1]) { // Assignment, and test for truthiness! + operations.push({ + mode: modeMatch[2]||modeMatch[1] + }); + selector = selector.replace(modeMatch[0], ''); + } + } + + // Now that we have all our operations in an array, we are going + // to create a new Query using these operations. + return new cq.Query({ + operations: operations + }); + } + }); +}); +/** + * Represents an HTML fragment template. Templates may be {@link #compile precompiled} for greater performance. + * + * An instance of this class may be created by passing to the constructor either a single argument, or multiple + * arguments: + * + * # Single argument: String/Array + * + * The single argument may be either a String or an Array: + * + * - String: + * + * var t = new Ext.Template("
    Hello {0}.
    "); + * t.{@link #append}('some-element', ['foo']); + * + * - Array: + * + * An Array will be combined with `join('')`. + * + * var t = new Ext.Template([ + * '
    ', + * '{name:trim} {value:ellipsis(10)}', + * '
    ', + * ]); + * t.{@link #compile}(); + * t.{@link #append}('some-element', {id: 'myid', cls: 'myclass', name: 'foo', value: 'bar'}); + * + * # Multiple arguments: String, Object, Array, ... + * + * Multiple arguments will be combined with `join('')`. + * + * var t = new Ext.Template( + * '
    ', + * '{name} {value}', + * '
    ', + * // a configuration object: + * { + * compiled: true, // {@link #compile} immediately + * } + * ); + * + * # Notes + * + * - For a list of available format functions, see {@link Ext.util.Format}. + * - `disableFormats` reduces `{@link #apply}` time when no formatting is required. + */ +Ext.define('Ext.Template', { + + /* Begin Definitions */ + + requires: ['Ext.dom.Helper', 'Ext.util.Format'], + + inheritableStatics: { + /** + * 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 (optional) Config object + * @return {Ext.Template} The created template + * @static + * @inheritable + */ + from: function(el, config) { + el = Ext.getDom(el); + return new this(el.value || el.innerHTML, config || ''); + } + }, + + /* End Definitions */ + + /** + * Creates new template. + * + * @param {String...} html List of strings to be concatenated into template. + * Alternatively an array of strings can be given, but then no config object may be passed. + * @param {Object} config (optional) Config object + */ + constructor: function(html) { + var me = this, + args = arguments, + buffer = [], + i = 0, + length = args.length, + value; + + me.initialConfig = {}; + + // Allow an array to be passed here so we can + // pass an array of strings and an object + // at the end + if (length === 1 && Ext.isArray(html)) { + args = html; + length = args.length; + } + + if (length > 1) { + for (; i < length; i++) { + value = args[i]; + if (typeof value == 'object') { + Ext.apply(me.initialConfig, value); + Ext.apply(me, value); + } else { + buffer.push(value); + } + } + } else { + buffer.push(html); + } + + // @private + me.html = buffer.join(''); + + if (me.compiled) { + me.compile(); + } + }, + + /** + * @property {Boolean} isTemplate + * `true` in this class to identify an object as an instantiated Template, or subclass thereof. + */ + isTemplate: true, + + /** + * @cfg {Boolean} compiled + * True to immediately compile the template. Defaults to false. + */ + + /** + * @cfg {Boolean} disableFormats + * True to disable format functions in the template. If the template doesn't contain + * format functions, setting disableFormats to true will reduce apply time. Defaults to false. + */ + disableFormats: false, + + 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: + * + * var tpl = new Ext.Template('Name: {0}, Age: {1}'); + * tpl.apply(['John', 25]); + * + * or an object: + * + * var tpl = new Ext.Template('Name: {name}, Age: {age}'); + * tpl.apply({name: 'John', age: 25}); + * + * @return {String} The HTML fragment + */ + apply: function(values) { + var me = this, + useFormat = me.disableFormats !== true, + fm = Ext.util.Format, + tpl = me, + ret; + + if (me.compiled) { + return me.compiled(values).join(''); + } + + function fn(m, name, format, args) { + if (format && useFormat) { + if (args) { + args = [values[name]].concat(Ext.functionFactory('return ['+ args +'];')()); + } else { + args = [values[name]]; + } + if (format.substr(0, 5) == "this.") { + return tpl[format.substr(5)].apply(tpl, args); + } + else { + return fm[format].apply(fm, args); + } + } + else { + return values[name] !== undefined ? values[name] : ""; + } + } + + ret = me.html.replace(me.re, fn); + return ret; + }, + + /** + * Appends the result of this template to the provided output array. + * @param {Object/Array} values The template values. See {@link #apply}. + * @param {Array} out The array to which output is pushed. + * @return {Array} The given out array. + */ + applyOut: function(values, out) { + var me = this; + + if (me.compiled) { + out.push.apply(out, me.compiled(values)); + } else { + out.push(me.apply(values)); + } + + return out; + }, + + /** + * @method applyTemplate + * @member Ext.Template + * Alias for {@link #apply}. + * @inheritdoc Ext.Template#apply + */ + applyTemplate: function () { + return this.apply.apply(this, arguments); + }, + + /** + * Sets the HTML used as the template and optionally compiles it. + * @param {String} html + * @param {Boolean} compile (optional) True to compile the template. + * @return {Ext.Template} this + */ + set: function(html, compile) { + var me = this; + me.html = html; + me.compiled = null; + return compile ? me.compile() : me; + }, + + compileARe: /\\/g, + compileBRe: /(\r\n|\n)/g, + compileCRe: /'/g, + + /** + * Compiles the template into an internal function, eliminating the RegEx overhead. + * @return {Ext.Template} this + */ + compile: function() { + var me = this, + fm = Ext.util.Format, + useFormat = me.disableFormats !== true, + body, bodyReturn; + + function fn(m, name, format, args) { + if (format && useFormat) { + args = args ? ',' + args: ""; + if (format.substr(0, 5) != "this.") { + format = "fm." + format + '('; + } + else { + format = 'this.' + format.substr(5) + '('; + } + } + else { + args = ''; + format = "(values['" + name + "'] == undefined ? '' : "; + } + return "'," + format + "values['" + name + "']" + args + ") ,'"; + } + + bodyReturn = me.html.replace(me.compileARe, '\\\\').replace(me.compileBRe, '\\n').replace(me.compileCRe, "\\'").replace(me.re, fn); + body = "this.compiled = function(values){ return ['" + bodyReturn + "'];};"; + eval(body); + return me; + }, + + /** + * Applies the supplied values to the template and inserts the new node(s) as the first child of el. + * + * @param {String/HTMLElement/Ext.Element} el The context element + * @param {Object/Array} values The template values. See {@link #applyTemplate} for details. + * @param {Boolean} returnElement (optional) true to return a Ext.Element. + * @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 {String/HTMLElement/Ext.Element} el The context element + * @param {Object/Array} values The template values. See {@link #applyTemplate} for details. + * @param {Boolean} returnElement (optional) true to return a Ext.Element. + * @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 {String/HTMLElement/Ext.Element} el The context element + * @param {Object/Array} values The template values. See {@link #applyTemplate} for details. + * @param {Boolean} returnElement (optional) true to return a Ext.Element. + * @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 see {@link Ext.Template Ext.Template class docs}. + * + * @param {String/HTMLElement/Ext.Element} el The context element + * @param {Object/Array} values The template values. See {@link #applyTemplate} for details. + * @param {Boolean} returnElement (optional) true to return an Ext.Element. + * @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, returnElement) { + var newNode = Ext.DomHelper.insertHtml(where, Ext.getDom(el), this.apply(values)); + return returnElement ? Ext.get(newNode) : newNode; + }, + + /** + * Applies the supplied values to the template and overwrites the content of el with the new node(s). + * + * @param {String/HTMLElement/Ext.Element} el The context element + * @param {Object/Array} values The template values. See {@link #applyTemplate} for details. + * @param {Boolean} returnElement (optional) true to return a Ext.Element. + * @return {HTMLElement/Ext.Element} The new node or Element + */ + overwrite: function(el, values, returnElement) { + var newNode = Ext.DomHelper.overwrite(Ext.getDom(el), this.apply(values)); + return returnElement ? Ext.get(newNode) : newNode; + } +}); + +/** + * This class parses the XTemplate syntax and calls abstract methods to process the parts. + * @private + */ +Ext.define('Ext.XTemplateParser', { + constructor: function (config) { + Ext.apply(this, config); + }, + + /** + * @property {Number} level The 'for' loop context level. This is adjusted up by one + * prior to calling {@link #doFor} and down by one after calling the corresponding + * {@link #doEnd} that closes the loop. This will be 1 on the first {@link #doFor} + * call. + */ + + /** + * This method is called to process a piece of raw text from the tpl. + * @param {String} text + * @method doText + */ + // doText: function (text) + + /** + * This method is called to process expressions (like `{[expr]}`). + * @param {String} expr The body of the expression (inside "{[" and "]}"). + * @method doExpr + */ + // doExpr: function (expr) + + /** + * This method is called to process simple tags (like `{tag}`). + * @method doTag + */ + // doTag: function (tag) + + /** + * This method is called to process ``. + * @method doElse + */ + // doElse: function () + + /** + * This method is called to process `{% text %}`. + * @param {String} text + * @method doEval + */ + // doEval: function (text) + + /** + * This method is called to process ``. If there are other attributes, + * these are passed in the actions object. + * @param {String} action + * @param {Object} actions Other actions keyed by the attribute name (such as 'exec'). + * @method doIf + */ + // doIf: function (action, actions) + + /** + * This method is called to process ``. If there are other attributes, + * these are passed in the actions object. + * @param {String} action + * @param {Object} actions Other actions keyed by the attribute name (such as 'exec'). + * @method doElseIf + */ + // doElseIf: function (action, actions) + + /** + * This method is called to process ``. If there are other attributes, + * these are passed in the actions object. + * @param {String} action + * @param {Object} actions Other actions keyed by the attribute name (such as 'exec'). + * @method doSwitch + */ + // doSwitch: function (action, actions) + + /** + * This method is called to process ``. If there are other attributes, + * these are passed in the actions object. + * @param {String} action + * @param {Object} actions Other actions keyed by the attribute name (such as 'exec'). + * @method doCase + */ + // doCase: function (action, actions) + + /** + * This method is called to process ``. + * @method doDefault + */ + // doDefault: function () + + /** + * This method is called to process ``. It is given the action type that started + * the tpl and the set of additional actions. + * @param {String} type The type of action that is being ended. + * @param {Object} actions The other actions keyed by the attribute name (such as 'exec'). + * @method doEnd + */ + // doEnd: function (type, actions) + + /** + * This method is called to process ``. If there are other attributes, + * these are passed in the actions object. + * @param {String} action + * @param {Object} actions Other actions keyed by the attribute name (such as 'exec'). + * @method doFor + */ + // doFor: function (action, actions) + + /** + * This method is called to process ``. If there are other attributes, + * these are passed in the actions object. + * @param {String} action + * @param {Object} actions Other actions keyed by the attribute name. + * @method doExec + */ + // doExec: function (action, actions) + + /** + * This method is called to process an empty ``. This is unlikely to need to be + * implemented, so a default (do nothing) version is provided. + * @method + */ + doTpl: Ext.emptyFn, + + parse: function (str) { + var me = this, + len = str.length, + aliases = { elseif: 'elif' }, + topRe = me.topRe, + actionsRe = me.actionsRe, + index, stack, s, m, t, prev, frame, subMatch, begin, end, actions, + prop; + + me.level = 0; + me.stack = stack = []; + + for (index = 0; index < len; index = end) { + topRe.lastIndex = index; + m = topRe.exec(str); + + if (!m) { + me.doText(str.substring(index, len)); + break; + } + + begin = m.index; + end = topRe.lastIndex; + + if (index < begin) { + me.doText(str.substring(index, begin)); + } + + if (m[1]) { + end = str.indexOf('%}', begin+2); + me.doEval(str.substring(begin+2, end)); + end += 2; + } else if (m[2]) { + end = str.indexOf(']}', begin+2); + me.doExpr(str.substring(begin+2, end)); + end += 2; + } else if (m[3]) { // if ('{' token) + me.doTag(m[3]); + } else if (m[4]) { // content of a tag + actions = null; + while ((subMatch = actionsRe.exec(m[4])) !== null) { + s = subMatch[2] || subMatch[3]; + if (s) { + s = Ext.String.htmlDecode(s); // decode attr value + t = subMatch[1]; + t = aliases[t] || t; + actions = actions || {}; + prev = actions[t]; + + if (typeof prev == 'string') { + actions[t] = [prev, s]; + } else if (prev) { + actions[t].push(s); + } else { + actions[t] = s; + } + } + } + + if (!actions) { + if (me.elseRe.test(m[4])) { + me.doElse(); + } else if (me.defaultRe.test(m[4])) { + me.doDefault(); + } else { + me.doTpl(); + stack.push({ type: 'tpl' }); + } + } + else if (actions['if']) { + me.doIf(actions['if'], actions); + stack.push({ type: 'if' }); + } + else if (actions['switch']) { + me.doSwitch(actions['switch'], actions); + stack.push({ type: 'switch' }); + } + else if (actions['case']) { + me.doCase(actions['case'], actions); + } + else if (actions['elif']) { + me.doElseIf(actions['elif'], actions); + } + else if (actions['for']) { + ++me.level; + + // Extract property name to use from indexed item + if (prop = me.propRe.exec(m[4])) { + actions.propName = prop[1] || prop[2]; + } + me.doFor(actions['for'], actions); + stack.push({ type: 'for', actions: actions }); + } + else if (actions.exec) { + me.doExec(actions.exec, actions); + stack.push({ type: 'exec', actions: actions }); + } + /* + else { + // todo - error + } + */ + } else if (m[0].length === 5) { + // if the length of m[0] is 5, assume that we're dealing with an opening tpl tag with no attributes (e.g. ...) + // in this case no action is needed other than pushing it on to the stack + stack.push({ type: 'tpl' }); + } else { + frame = stack.pop(); + me.doEnd(frame.type, frame.actions); + if (frame.type == 'for') { + --me.level; + } + } + } + }, + + // Internal regexes + + topRe: /(?:(\{\%)|(\{\[)|\{([^{}]*)\})|(?:]*)\>)|(?:<\/tpl>)/g, + actionsRe: /\s*(elif|elseif|if|for|exec|switch|case|eval)\s*\=\s*(?:(?:"([^"]*)")|(?:'([^']*)'))\s*/g, + propRe: /prop=(?:(?:"([^"]*)")|(?:'([^']*)'))/, + defaultRe: /^\s*default\s*$/, + elseRe: /^\s*else\s*$/ +}); + +/** + * @class Ext.chart.Callout + * A mixin providing callout functionality for Ext.chart.series.Series. + */ +Ext.define('Ext.chart.Callout', { + + /* Begin Definitions */ + + /* End Definitions */ + + constructor: function(config) { + if (config.callouts) { + config.callouts.styles = Ext.applyIf(config.callouts.styles || {}, { + color: "#000", + font: "11px Helvetica, sans-serif" + }); + this.callouts = Ext.apply(this.callouts || {}, config.callouts); + this.calloutsArray = []; + } + }, + + renderCallouts: function() { + if (!this.callouts) { + return; + } + + var me = this, + items = me.items, + animate = me.chart.animate, + config = me.callouts, + styles = config.styles, + group = me.calloutsArray, + store = me.chart.store, + len = store.getCount(), + ratio = items.length / len, + previouslyPlacedCallouts = [], + i, + count, + j, + p, + item, + label, + storeItem, + display; + + for (i = 0, count = 0; i < len; i++) { + for (j = 0; j < ratio; j++) { + item = items[count]; + label = group[count]; + storeItem = store.getAt(i); + + display = config.filter(storeItem); + + if (!display && !label) { + count++; + continue; + } + + if (!label) { + group[count] = label = me.onCreateCallout(storeItem, item, i, display, j, count); + } + for (p in label) { + if (label[p] && label[p].setAttributes) { + label[p].setAttributes(styles, true); + } + } + if (!display) { + for (p in label) { + if (label[p]) { + if (label[p].setAttributes) { + label[p].setAttributes({ + hidden: true + }, true); + } else if(label[p].setVisible) { + label[p].setVisible(false); + } + } + } + } + config.renderer(label, storeItem); + me.onPlaceCallout(label, storeItem, item, i, display, animate, + j, count, previouslyPlacedCallouts); + previouslyPlacedCallouts.push(label); + count++; + } + } + this.hideCallouts(count); + }, + + onCreateCallout: function(storeItem, item, i, display) { + var me = this, + group = me.calloutsGroup, + config = me.callouts, + styles = config.styles, + width = styles.width, + height = styles.height, + chart = me.chart, + surface = chart.surface, + calloutObj = { + //label: false, + //box: false, + lines: false + }; + + calloutObj.lines = surface.add(Ext.apply({}, + { + type: 'path', + path: 'M0,0', + stroke: me.getLegendColor() || '#555' + }, + styles)); + + if (config.items) { + calloutObj.panel = new Ext.Panel({ + style: "position: absolute;", + width: width, + height: height, + items: config.items, + renderTo: chart.el + }); + } + + return calloutObj; + }, + + hideCallouts: function(index) { + var calloutsArray = this.calloutsArray, + len = calloutsArray.length, + co, + p; + while (len-->index) { + co = calloutsArray[len]; + for (p in co) { + if (co[p]) { + co[p].hide(true); + } + } + } + } +}); + +/** + * @class Ext.chart.Navigation + * + * Handles panning and zooming capabilities. + * + * Used as mixin by Ext.chart.Chart. + */ +Ext.define('Ext.chart.Navigation', { + + constructor: function() { + this.originalStore = this.store; + }, + + /** + * Zooms the chart to the specified selection range. + * Can be used with a selection mask. For example: + * + * items: { + * xtype: 'chart', + * animate: true, + * store: store1, + * mask: 'horizontal', + * listeners: { + * select: { + * fn: function(me, selection) { + * me.setZoom(selection); + * me.mask.hide(); + * } + * } + * } + * } + */ + setZoom: function(zoomConfig) { + var me = this, + axes = me.axes, + axesItems = axes.items, + i, ln, axis, + bbox = me.chartBBox, + xScale = 1 / bbox.width, + yScale = 1 / bbox.height, + zoomer = { + x : zoomConfig.x * xScale, + y : zoomConfig.y * yScale, + width : zoomConfig.width * xScale, + height : zoomConfig.height * yScale + }, + ends, from, to; + for (i = 0, ln = axesItems.length; i < ln; i++) { + axis = axesItems[i]; + ends = axis.calcEnds(); + if (axis.position == 'bottom' || axis.position == 'top') { + from = (ends.to - ends.from) * zoomer.x + ends.from; + to = (ends.to - ends.from) * zoomer.width + from; + axis.minimum = from; + axis.maximum = to; + } else { + to = (ends.to - ends.from) * (1 - zoomer.y) + ends.from; + from = to - (ends.to - ends.from) * zoomer.height; + axis.minimum = from; + axis.maximum = to; + } + } + me.redraw(false); + }, + + /** + * Restores the zoom to the original value. This can be used to reset + * the previous zoom state set by `setZoom`. For example: + * + * myChart.restoreZoom(); + */ + restoreZoom: function() { + if (this.originalStore) { + this.store = this.substore = this.originalStore; + this.redraw(true); + } + } + +}); + +/** + * @private + */ +Ext.define('Ext.chart.Shape', { + + /* Begin Definitions */ + + singleton: true, + + /* End Definitions */ + + circle: function (surface, opts) { + return surface.add(Ext.apply({ + type: 'circle', + x: opts.x, + y: opts.y, + stroke: null, + radius: opts.radius + }, opts)); + }, + line: function (surface, opts) { + return surface.add(Ext.apply({ + type: 'rect', + x: opts.x - opts.radius, + y: opts.y - opts.radius, + height: 2 * opts.radius, + width: 2 * opts.radius / 5 + }, opts)); + }, + square: function (surface, opts) { + return surface.add(Ext.applyIf({ + type: 'rect', + x: opts.x - opts.radius, + y: opts.y - opts.radius, + height: 2 * opts.radius, + width: 2 * opts.radius, + radius: null + }, opts)); + }, + triangle: function (surface, opts) { + opts.radius *= 1.75; + return surface.add(Ext.apply({ + type: 'path', + stroke: null, + path: "M".concat(opts.x, ",", opts.y, "m0-", opts.radius * 0.58, "l", opts.radius * 0.5, ",", opts.radius * 0.87, "-", opts.radius, ",0z") + }, opts)); + }, + diamond: function (surface, opts) { + var r = opts.radius; + r *= 1.5; + return surface.add(Ext.apply({ + type: 'path', + stroke: null, + path: ["M", opts.x, opts.y - r, "l", r, r, -r, r, -r, -r, r, -r, "z"] + }, opts)); + }, + cross: function (surface, opts) { + var r = opts.radius; + r = r / 1.7; + return surface.add(Ext.apply({ + type: 'path', + stroke: null, + path: "M".concat(opts.x - r, ",", opts.y, "l", [-r, -r, r, -r, r, r, r, -r, r, r, -r, r, r, r, -r, r, -r, -r, -r, r, -r, -r, "z"]) + }, opts)); + }, + plus: function (surface, opts) { + var r = opts.radius / 1.3; + return surface.add(Ext.apply({ + type: 'path', + stroke: null, + path: "M".concat(opts.x - r / 2, ",", opts.y - r / 2, "l", [0, -r, r, 0, 0, r, r, 0, 0, r, -r, 0, 0, r, -r, 0, 0, -r, -r, 0, 0, -r, "z"]) + }, opts)); + }, + arrow: function (surface, opts) { + var r = opts.radius; + return surface.add(Ext.apply({ + type: 'path', + path: "M".concat(opts.x - r * 0.7, ",", opts.y - r * 0.4, "l", [r * 0.6, 0, 0, -r * 0.4, r, r * 0.8, -r, r * 0.8, 0, -r * 0.4, -r * 0.6, 0], "z") + }, opts)); + }, + drop: function (surface, x, y, text, size, angle) { + size = size || 30; + angle = angle || 0; + surface.add({ + type: 'path', + path: ['M', x, y, 'l', size, 0, 'A', size * 0.4, size * 0.4, 0, 1, 0, x + size * 0.7, y - size * 0.7, 'z'], + fill: '#000', + stroke: 'none', + rotate: { + degrees: 22.5 - angle, + x: x, + y: y + } + }); + angle = (angle + 90) * Math.PI / 180; + surface.add({ + type: 'text', + x: x + size * Math.sin(angle) - 10, // Shift here, Not sure why. + y: y + size * Math.cos(angle) + 5, + text: text, + 'font-size': size * 12 / 40, + stroke: 'none', + fill: '#fff' + }); + } +}); +/** + * @author Don Griffin + * + * This class is a base for all id generators. It also provides lookup of id generators by + * their id. + * + * Generally, id generators are used to generate a primary key for new model instances. There + * are different approaches to solving this problem, so this mechanism has both simple use + * cases and is open to custom implementations. A {@link Ext.data.Model} requests id generation + * using the {@link Ext.data.Model#idgen} property. + * + * # Identity, Type and Shared IdGenerators + * + * It is often desirable to share IdGenerators to ensure uniqueness or common configuration. + * This is done by giving IdGenerator instances an id property by which they can be looked + * up using the {@link #get} method. To configure two {@link Ext.data.Model Model} classes + * to share one {@link Ext.data.SequentialIdGenerator sequential} id generator, you simply + * assign them the same id: + * + * Ext.define('MyApp.data.MyModelA', { + * extend: 'Ext.data.Model', + * idgen: { + * type: 'sequential', + * id: 'foo' + * } + * }); + * + * Ext.define('MyApp.data.MyModelB', { + * extend: 'Ext.data.Model', + * idgen: { + * type: 'sequential', + * id: 'foo' + * } + * }); + * + * To make this as simple as possible for generator types that are shared by many (or all) + * Models, the IdGenerator types (such as 'sequential' or 'uuid') are also reserved as + * generator id's. This is used by the {@link Ext.data.UuidGenerator} which has an id equal + * to its type ('uuid'). In other words, the following Models share the same generator: + * + * Ext.define('MyApp.data.MyModelX', { + * extend: 'Ext.data.Model', + * idgen: 'uuid' + * }); + * + * Ext.define('MyApp.data.MyModelY', { + * extend: 'Ext.data.Model', + * idgen: 'uuid' + * }); + * + * This can be overridden (by specifying the id explicitly), but there is no particularly + * good reason to do so for this generator type. + * + * # Creating Custom Generators + * + * An id generator should derive from this class and implement the {@link #generate} method. + * The constructor will apply config properties on new instances, so a constructor is often + * not necessary. + * + * To register an id generator type, a derived class should provide an `alias` like so: + * + * Ext.define('MyApp.data.CustomIdGenerator', { + * extend: 'Ext.data.IdGenerator', + * alias: 'idgen.custom', + * + * configProp: 42, // some config property w/default value + * + * generate: function () { + * return ... // a new id + * } + * }); + * + * Using the custom id generator is then straightforward: + * + * Ext.define('MyApp.data.MyModel', { + * extend: 'Ext.data.Model', + * idgen: 'custom' + * }); + * // or... + * + * Ext.define('MyApp.data.MyModel', { + * extend: 'Ext.data.Model', + * idgen: { + * type: 'custom', + * configProp: value + * } + * }); + * + * It is not recommended to mix shared generators with generator configuration. This leads + * to unpredictable results unless all configurations match (which is also redundant). In + * such cases, a custom generator with a default id is the best approach. + * + * Ext.define('MyApp.data.CustomIdGenerator', { + * extend: 'Ext.data.SequentialIdGenerator', + * alias: 'idgen.custom', + * + * id: 'custom', // shared by default + * + * prefix: 'ID_', + * seed: 1000 + * }); + * + * Ext.define('MyApp.data.MyModelX', { + * extend: 'Ext.data.Model', + * idgen: 'custom' + * }); + * + * Ext.define('MyApp.data.MyModelY', { + * extend: 'Ext.data.Model', + * idgen: 'custom' + * }); + * + * // the above models share a generator that produces ID_1000, ID_1001, etc.. + * + */ +Ext.define('Ext.data.IdGenerator', { + + /** + * @property {Boolean} isGenerator + * `true` in this class to identify an object as an instantiated IdGenerator, or subclass thereof. + */ + isGenerator: true, + + /** + * Initializes a new instance. + * @param {Object} config (optional) Configuration object to be applied to the new instance. + */ + constructor: function(config) { + var me = this; + + Ext.apply(me, config); + + if (me.id) { + Ext.data.IdGenerator.all[me.id] = me; + } + }, + + /** + * @cfg {String} id + * The id by which to register a new instance. This instance can be found using the + * {@link Ext.data.IdGenerator#get} static method. + */ + + getRecId: function (rec) { + return rec.modelName + '-' + rec.internalId; + }, + + /** + * Generates and returns the next id. This method must be implemented by the derived + * class. + * + * @return {String} The next id. + * @method generate + * @abstract + */ + + statics: { + /** + * @property {Object} all + * This object is keyed by id to lookup instances. + * @private + * @static + */ + all: {}, + + /** + * Returns the IdGenerator given its config description. + * @param {String/Object} config If this parameter is an IdGenerator instance, it is + * simply returned. If this is a string, it is first used as an id for lookup and + * then, if there is no match, as a type to create a new instance. This parameter + * can also be a config object that contains a `type` property (among others) that + * are used to create and configure the instance. + * @static + */ + get: function (config) { + var generator, + id, + type; + + if (typeof config == 'string') { + id = type = config; + config = null; + } else if (config.isGenerator) { + return config; + } else { + id = config.id || config.type; + type = config.type; + } + + generator = this.all[id]; + if (!generator) { + generator = Ext.create('idgen.' + type, config); + } + + return generator; + } + } +}); + +/** + * @class Ext.data.JsonP + * @singleton + * This class is used to create JSONP requests. JSONP is a mechanism that allows for making + * requests for data cross domain. More information is available here. + */ +Ext.define('Ext.data.JsonP', { + + /* Begin Definitions */ + + singleton: true, + + statics: { + requestCount: 0, + requests: {} + }, + + /* End Definitions */ + + /** + * @property timeout + * @type Number + * A default timeout for any JsonP requests. If the request has not completed in this time the + * failure callback will be fired. The timeout is in ms. Defaults to 30000. + */ + timeout: 30000, + + /** + * @property disableCaching + * @type Boolean + * True to add a unique cache-buster param to requests. Defaults to true. + */ + disableCaching: true, + + /** + * @property disableCachingParam + * @type String + * Change the parameter which is sent went disabling caching through a cache buster. Defaults to '_dc'. + */ + disableCachingParam: '_dc', + + /** + * @property callbackKey + * @type String + * Specifies the GET parameter that will be sent to the server containing the function name to be executed when + * the request completes. Defaults to callback. Thus, a common request will be in the form of + * url?callback=Ext.data.JsonP.callback1 + */ + callbackKey: 'callback', + + /** + * Makes a JSONP request. + * @param {Object} options An object which may contain the following properties. Note that options will + * take priority over any defaults that are specified in the class. + *
      + *
    • url : String
      The URL to request.
    • + *
    • params : Object (Optional)
      An object containing a series of + * key value pairs that will be sent along with the request.
    • + *
    • timeout : Number (Optional)
      See {@link #timeout}
    • + *
    • callbackKey : String (Optional)
      See {@link #callbackKey}
    • + *
    • callbackName : String (Optional)
      The function name to use for this request. + * By default this name will be auto-generated: Ext.data.JsonP.callback1, Ext.data.JsonP.callback2, etc. + * Setting this option to "my_name" will force the function name to be Ext.data.JsonP.my_name. + * Use this if you want deterministic behavior, but be careful - the callbackName should be different + * in each JsonP request that you make.
    • + *
    • disableCaching : Boolean (Optional)
      See {@link #disableCaching}
    • + *
    • disableCachingParam : String (Optional)
      See {@link #disableCachingParam}
    • + *
    • success : Function (Optional)
      A function to execute if the request succeeds.
    • + *
    • failure : Function (Optional)
      A function to execute if the request fails.
    • + *
    • callback : Function (Optional)
      A function to execute when the request + * completes, whether it is a success or failure.
    • + *
    • scope : Object (Optional)
      The scope in + * which to execute the callbacks: The "this" object for the callback function. Defaults to the browser window.
    • + *
    + * @return {Object} request An object containing the request details. + */ + request: function(options){ + options = Ext.apply({}, options); + + if (!options.url) { + Ext.Error.raise('A url must be specified for a JSONP request.'); + } + + var me = this, + disableCaching = Ext.isDefined(options.disableCaching) ? options.disableCaching : me.disableCaching, + cacheParam = options.disableCachingParam || me.disableCachingParam, + id = ++me.statics().requestCount, + callbackName = options.callbackName || 'callback' + id, + callbackKey = options.callbackKey || me.callbackKey, + timeout = Ext.isDefined(options.timeout) ? options.timeout : me.timeout, + params = Ext.apply({}, options.params), + url = options.url, + name = Ext.name, + request, + script; + + params[callbackKey] = name + '.data.JsonP.' + callbackName; + if (disableCaching) { + params[cacheParam] = new Date().getTime(); + } + + script = me.createScript(url, params, options); + + me.statics().requests[id] = request = { + url: url, + params: params, + script: script, + id: id, + scope: options.scope, + success: options.success, + failure: options.failure, + callback: options.callback, + callbackKey: callbackKey, + callbackName: callbackName + }; + + if (timeout > 0) { + request.timeout = setTimeout(Ext.bind(me.handleTimeout, me, [request]), timeout); + } + + me.setupErrorHandling(request); + me[callbackName] = Ext.bind(me.handleResponse, me, [request], true); + me.loadScript(request); + return request; + }, + + /** + * Abort a request. If the request parameter is not specified all open requests will + * be aborted. + * @param {Object/String} request (Optional) The request to abort + */ + abort: function(request){ + var me = this, + requests = me.statics().requests, + key; + + if (request) { + if (!request.id) { + request = requests[request]; + } + me.handleAbort(request); + } else { + for (key in requests) { + if (requests.hasOwnProperty(key)) { + me.abort(requests[key]); + } + } + } + }, + + /** + * Sets up error handling for the script + * @private + * @param {Object} request The request + */ + setupErrorHandling: function(request){ + request.script.onerror = Ext.bind(this.handleError, this, [request]); + }, + + /** + * Handles any aborts when loading the script + * @private + * @param {Object} request The request + */ + handleAbort: function(request){ + request.errorType = 'abort'; + this.handleResponse(null, request); + }, + + /** + * Handles any script errors when loading the script + * @private + * @param {Object} request The request + */ + handleError: function(request){ + request.errorType = 'error'; + this.handleResponse(null, request); + }, + + /** + * Cleans up anu script handling errors + * @private + * @param {Object} request The request + */ + cleanupErrorHandling: function(request){ + request.script.onerror = null; + }, + + /** + * Handle any script timeouts + * @private + * @param {Object} request The request + */ + handleTimeout: function(request){ + request.errorType = 'timeout'; + this.handleResponse(null, request); + }, + + /** + * Handle a successful response + * @private + * @param {Object} result The result from the request + * @param {Object} request The request + */ + handleResponse: function(result, request){ + + var success = true; + + if (request.timeout) { + clearTimeout(request.timeout); + } + delete this[request.callbackName]; + delete this.statics().requests[request.id]; + this.cleanupErrorHandling(request); + Ext.fly(request.script).remove(); + + if (request.errorType) { + success = false; + Ext.callback(request.failure, request.scope, [request.errorType]); + } else { + Ext.callback(request.success, request.scope, [result]); + } + Ext.callback(request.callback, request.scope, [success, result, request.errorType]); + }, + + /** + * Create the script tag given the specified url, params and options. The options + * parameter is passed to allow an override to access it. + * @private + * @param {String} url The url of the request + * @param {Object} params Any extra params to be sent + * @param {Object} options The object passed to {@link #request}. + */ + createScript: function(url, params, options) { + var script = document.createElement('script'); + script.setAttribute("src", Ext.urlAppend(url, Ext.Object.toQueryString(params))); + script.setAttribute("async", true); + script.setAttribute("type", "text/javascript"); + return script; + }, + + /** + * Loads the script for the given request by appending it to the HEAD element. This is + * its own method so that users can override it (as well as {@link #createScript}). + * @private + * @param request The request object. + */ + loadScript: function (request) { + Ext.getHead().appendChild(request.script); + } +}); + +/** + * @author Ed Spencer + * + * Represents a single read or write operation performed by a {@link Ext.data.proxy.Proxy Proxy}. Operation objects are + * used to enable communication between Stores and Proxies. Application developers should rarely need to interact with + * Operation objects directly. + * + * Several Operations can be batched together in a {@link Ext.data.Batch batch}. + */ +Ext.define('Ext.data.Operation', { + /** + * @cfg {Boolean} synchronous + * True if this Operation is to be executed synchronously. This property is inspected by a + * {@link Ext.data.Batch Batch} to see if a series of Operations can be executed in parallel or not. + */ + synchronous: true, + + /** + * @cfg {String} action + * The action being performed by this Operation. Should be one of 'create', 'read', 'update' or 'destroy'. + */ + action: undefined, + + /** + * @cfg {Ext.util.Filter[]} filters + * Optional array of filter objects. Only applies to 'read' actions. + */ + filters: undefined, + + /** + * @cfg {Ext.util.Sorter[]} sorters + * Optional array of sorter objects. Only applies to 'read' actions. + */ + sorters: undefined, + + /** + * @cfg {Ext.util.Grouper[]} groupers + * Optional grouping configuration. Only applies to 'read' actions where grouping is desired. + */ + groupers: undefined, + + /** + * @cfg {Number} start + * The start index (offset), used in paging when running a 'read' action. + */ + start: undefined, + + /** + * @cfg {Number} limit + * The number of records to load. Used on 'read' actions when paging is being used. + */ + limit: undefined, + + /** + * @cfg {Ext.data.Batch} batch + * The batch that this Operation is a part of. + */ + batch: undefined, + + /** + * @cfg {Function} callback + * Function to execute when operation completed. + * @cfg {Ext.data.Model[]} callback.records Array of records. + * @cfg {Ext.data.Operation} callback.operation The Operation itself. + * @cfg {Boolean} callback.success True when operation completed successfully. + */ + callback: undefined, + + /** + * @cfg {Object} scope + * Scope for the {@link #callback} function. + */ + scope: undefined, + + /** + * @property {Boolean} started + * The start status of this Operation. Use {@link #isStarted}. + * @readonly + * @private + */ + started: false, + + /** + * @property {Boolean} running + * The run status of this Operation. Use {@link #isRunning}. + * @readonly + * @private + */ + running: false, + + /** + * @property {Boolean} complete + * The completion status of this Operation. Use {@link #isComplete}. + * @readonly + * @private + */ + complete: false, + + /** + * @property {Boolean} success + * Whether the Operation was successful or not. This starts as undefined and is set to true + * or false by the Proxy that is executing the Operation. It is also set to false by {@link #setException}. Use + * {@link #wasSuccessful} to query success status. + * @readonly + * @private + */ + success: undefined, + + /** + * @property {Boolean} exception + * The exception status of this Operation. Use {@link #hasException} and see {@link #getError}. + * @readonly + * @private + */ + exception: false, + + /** + * @property {String/Object} error + * The error object passed when {@link #setException} was called. This could be any object or primitive. + * @private + */ + error: undefined, + + /** + * @property {RegExp} actionCommitRecordsRe + * The RegExp used to categorize actions that require record commits. + */ + actionCommitRecordsRe: /^(?:create|update)$/i, + + /** + * @property {RegExp} actionSkipSyncRe + * The RegExp used to categorize actions that skip local record synchronization. This defaults + * to match 'destroy'. + */ + actionSkipSyncRe: /^destroy$/i, + + /** + * Creates new Operation object. + * @param {Object} config (optional) Config object. + */ + constructor: function(config) { + Ext.apply(this, config || {}); + }, + + /** + * This method is called to commit data to this instance's records given the records in + * the server response. This is followed by calling {@link Ext.data.Model#commit} on all + * those records (for 'create' and 'update' actions). + * + * If this {@link #action} is 'destroy', any server records are ignored and the + * {@link Ext.data.Model#commit} method is not called. + * + * @param {Ext.data.Model[]} serverRecords An array of {@link Ext.data.Model} objects returned by + * the server. + * @markdown + */ + commitRecords: function (serverRecords) { + var me = this, + mc, index, clientRecords, serverRec, clientRec; + + if (!me.actionSkipSyncRe.test(me.action)) { + clientRecords = me.records; + + if (clientRecords && clientRecords.length) { + if (clientRecords.length > 1) { + // if this operation has multiple records, client records need to be matched up with server records + // so that any data returned from the server can be updated in the client records. + mc = new Ext.util.MixedCollection(); + mc.addAll(serverRecords); + + for (index = clientRecords.length; index--; ) { + clientRec = clientRecords[index]; + serverRec = mc.findBy(me.matchClientRec, clientRec); + + // Replace client record data with server record data + clientRec.copyFrom(serverRec); + } + } else { + // operation only has one record, so just match the first client record up with the first server record + clientRec = clientRecords[0]; + serverRec = serverRecords[0]; + // if the client record is not a phantom, make sure the ids match before replacing the client data with server data. + if(serverRec && (clientRec.phantom || clientRec.getId() === serverRec.getId())) { + clientRec.copyFrom(serverRec); + } + } + + if (me.actionCommitRecordsRe.test(me.action)) { + for (index = clientRecords.length; index--; ) { + clientRecords[index].commit(); + } + } + } + } + }, + + // Private. + // Record matching function used by commitRecords + // IMPORTANT: This is called in the scope of the clientRec being matched + matchClientRec: function(record) { + var clientRec = this, + clientRecordId = clientRec.getId(); + + if(clientRecordId && record.getId() === clientRecordId) { + return true; + } + // if the server record cannot be found by id, find by internalId. + // this allows client records that did not previously exist on the server + // to be updated with the correct server id and data. + return record.internalId === clientRec.internalId; + }, + + /** + * Marks the Operation as started. + */ + setStarted: function() { + this.started = true; + this.running = true; + }, + + /** + * Marks the Operation as completed. + */ + setCompleted: function() { + this.complete = true; + this.running = false; + }, + + /** + * Marks the Operation as successful. + */ + setSuccessful: function() { + this.success = true; + }, + + /** + * Marks the Operation as having experienced an exception. Can be supplied with an option error message/object. + * @param {String/Object} error (optional) error string/object + */ + setException: function(error) { + this.exception = true; + this.success = false; + this.running = false; + this.error = error; + }, + + /** + * Returns true if this Operation encountered an exception (see also {@link #getError}) + * @return {Boolean} True if there was an exception + */ + hasException: function() { + return this.exception === true; + }, + + /** + * Returns the error string or object that was set using {@link #setException} + * @return {String/Object} The error object + */ + getError: function() { + return this.error; + }, + + /** + * Returns the {@link Ext.data.Model record}s associated with this operation. For read operations the records as set by the {@link Ext.data.proxy.Proxy Proxy} will be returned (returns `null` if the proxy has not yet set the records). + * For create, update, and destroy operations the operation's initially configured records will be returned, although the proxy may modify these records' data at some point after the operation is initialized. + * @return {Ext.data.Model[]} + */ + getRecords: function() { + var resultSet = this.getResultSet(); + return this.records || (resultSet ? resultSet.records : null); + }, + + /** + * Returns the ResultSet object (if set by the Proxy). This object will contain the {@link Ext.data.Model model} + * instances as well as meta data such as number of instances fetched, number available etc + * @return {Ext.data.ResultSet} The ResultSet object + */ + getResultSet: function() { + return this.resultSet; + }, + + /** + * Returns true if the Operation has been started. Note that the Operation may have started AND completed, see + * {@link #isRunning} to test if the Operation is currently running. + * @return {Boolean} True if the Operation has started + */ + isStarted: function() { + return this.started === true; + }, + + /** + * Returns true if the Operation has been started but has not yet completed. + * @return {Boolean} True if the Operation is currently running + */ + isRunning: function() { + return this.running === true; + }, + + /** + * Returns true if the Operation has been completed + * @return {Boolean} True if the Operation is complete + */ + isComplete: function() { + return this.complete === true; + }, + + /** + * Returns true if the Operation has completed and was successful + * @return {Boolean} True if successful + */ + wasSuccessful: function() { + return this.isComplete() && this.success === true; + }, + + /** + * @private + * Associates this Operation with a Batch + * @param {Ext.data.Batch} batch The batch + */ + setBatch: function(batch) { + this.batch = batch; + }, + + /** + * Checks whether this operation should cause writing to occur. + * @return {Boolean} Whether the operation should cause a write to occur. + */ + allowWrite: function() { + return this.action != 'read'; + } +}); + +/** + * @author Ed Spencer + * + * Simple class that represents a Request that will be made by any {@link Ext.data.proxy.Server} subclass. + * All this class does is standardize the representation of a Request as used by any ServerProxy subclass, + * it does not contain any actual logic or perform the request itself. + */ +Ext.define('Ext.data.Request', { + /** + * @cfg {String} action + * The name of the action this Request represents. Usually one of 'create', 'read', 'update' or 'destroy'. + */ + action: undefined, + + /** + * @cfg {Object} params + * HTTP request params. The Proxy and its Writer have access to and can modify this object. + */ + params: undefined, + + /** + * @cfg {String} method + * The HTTP method to use on this Request. Should be one of 'GET', 'POST', 'PUT' or 'DELETE'. + */ + method: 'GET', + + /** + * @cfg {String} url + * The url to access on this Request + */ + url: undefined, + + /** + * Creates the Request object. + * @param {Object} [config] Config object. + */ + constructor: function(config) { + Ext.apply(this, config); + } +}); +/** + * @author Ed Spencer + * + * Simple wrapper class that represents a set of records returned by a Proxy. + */ +Ext.define('Ext.data.ResultSet', { + /** + * @cfg {Boolean} loaded + * True if the records have already been loaded. This is only meaningful when dealing with + * SQL-backed proxies. + */ + loaded: true, + + /** + * @cfg {Number} count + * The number of records in this ResultSet. Note that total may differ from this number. + */ + count: 0, + + /** + * @cfg {Number} total + * The total number of records reported by the data source. This ResultSet may form a subset of + * those records (see {@link #count}). + */ + total: 0, + + /** + * @cfg {Boolean} success + * True if the ResultSet loaded successfully, false if any errors were encountered. + */ + success: false, + + /** + * @cfg {Ext.data.Model[]} records (required) + * The array of record instances. + */ + + /** + * Creates the resultSet + * @param {Object} [config] Config object. + */ + constructor: function(config) { + Ext.apply(this, config); + + /** + * @property {Number} totalRecords + * Copy of this.total. + * @deprecated Will be removed in Ext JS 5.0. Use {@link #total} instead. + */ + this.totalRecords = this.total; + + if (config.count === undefined) { + this.count = this.records.length; + } + } +}); +/** + * @author Don Griffin + * + * This class is a sequential id generator. A simple use of this class would be like so: + * + * Ext.define('MyApp.data.MyModel', { + * extend: 'Ext.data.Model', + * idgen: 'sequential' + * }); + * // assign id's of 1, 2, 3, etc. + * + * An example of a configured generator would be: + * + * Ext.define('MyApp.data.MyModel', { + * extend: 'Ext.data.Model', + * idgen: { + * type: 'sequential', + * prefix: 'ID_', + * seed: 1000 + * } + * }); + * // assign id's of ID_1000, ID_1001, ID_1002, etc. + * + */ +Ext.define('Ext.data.SequentialIdGenerator', { + extend: 'Ext.data.IdGenerator', + alias: 'idgen.sequential', + + constructor: function() { + var me = this; + + me.callParent(arguments); + + me.parts = [ me.prefix, '']; + }, + + /** + * @cfg {String} prefix + * The string to place in front of the sequential number for each generated id. The + * default is blank. + */ + prefix: '', + + /** + * @cfg {Number} seed + * The number at which to start generating sequential id's. The default is 1. + */ + seed: 1, + + /** + * Generates and returns the next id. + * @return {String} The next id. + */ + generate: function () { + var me = this, + parts = me.parts; + + parts[1] = me.seed++; + return parts.join(''); + } +}); + +/** + * @class Ext.data.SortTypes + * This class defines a series of static methods that are used on a + * {@link Ext.data.Field} for performing sorting. The methods cast the + * underlying values into a data type that is appropriate for sorting on + * that particular field. If a {@link Ext.data.Field#type} is specified, + * the sortType will be set to a sane default if the sortType is not + * explicitly defined on the field. The sortType will make any necessary + * modifications to the value and return it. + *
      + *
    • asText - Removes any tags and converts the value to a string
    • + *
    • asUCText - Removes any tags and converts the value to an uppercase string
    • + *
    • asUCText - Converts the value to an uppercase string
    • + *
    • asDate - Converts the value into Unix epoch time
    • + *
    • asFloat - Converts the value to a floating point number
    • + *
    • asInt - Converts the value to an integer number
    • + *
    + *

    + * It is also possible to create a custom sortType that can be used throughout + * an application. + *

    
    +Ext.apply(Ext.data.SortTypes, {
    +    asPerson: function(person){
    +        // expects an object with a first and last name property
    +        return person.lastName.toUpperCase() + person.firstName.toLowerCase();
    +    }    
    +});
    +
    +Ext.define('Employee', {
    +    extend: 'Ext.data.Model',
    +    fields: [{
    +        name: 'person',
    +        sortType: 'asPerson'
    +    }, {
    +        name: 'salary',
    +        type: 'float' // sortType set to asFloat
    +    }]
    +});
    + * 
    + *

    + * @singleton + * @docauthor Evan Trimboli + */ +Ext.define('Ext.data.SortTypes', { + + singleton: true, + + /** + * Default sort that does nothing + * @param {Object} s The value being converted + * @return {Object} The comparison value + */ + none : function(s) { + return s; + }, + + /** + * The regular expression used to strip tags + * @type {RegExp} + * @property + */ + stripTagsRE : /<\/?[^>]+>/gi, + + /** + * Strips all HTML tags to sort on text only + * @param {Object} s The value being converted + * @return {String} The comparison value + */ + asText : function(s) { + return String(s).replace(this.stripTagsRE, ""); + }, + + /** + * Strips all HTML tags to sort on text only - Case insensitive + * @param {Object} s The value being converted + * @return {String} The comparison value + */ + asUCText : function(s) { + return String(s).toUpperCase().replace(this.stripTagsRE, ""); + }, + + /** + * Case insensitive string + * @param {Object} s The value being converted + * @return {String} The comparison value + */ + asUCString : function(s) { + return String(s).toUpperCase(); + }, + + /** + * Date sorting + * @param {Object} s The value being converted + * @return {Number} The comparison value + */ + asDate : function(s) { + if(!s){ + return 0; + } + if(Ext.isDate(s)){ + return s.getTime(); + } + return Date.parse(String(s)); + }, + + /** + * Float sorting + * @param {Object} s The value being converted + * @return {Number} The comparison value + */ + asFloat : function(s) { + var val = parseFloat(String(s).replace(/,/g, "")); + return isNaN(val) ? 0 : val; + }, + + /** + * Integer sorting + * @param {Object} s The value being converted + * @return {Number} The comparison value + */ + asInt : function(s) { + var val = parseInt(String(s).replace(/,/g, ""), 10); + return isNaN(val) ? 0 : val; + } +}); +/** + * @class Ext.data.Types + *

    This is a static class containing the system-supplied data types which may be given to a {@link Ext.data.Field Field}.

    + *

    The properties in this class are used as type indicators in the {@link Ext.data.Field Field} class, so to + * test whether a Field is of a certain type, compare the {@link Ext.data.Field#type type} property against properties + * of this class.

    + *

    Developers may add their own application-specific data types to this class. Definition names must be UPPERCASE. + * each type definition must contain three properties:

    + *
      + *
    • convert : Function
      A function to convert raw data values from a data block into the data + * to be stored in the Field. The function is passed the collowing parameters: + *
        + *
      • v : Mixed
        The data value as read by the Reader, if undefined will use + * the configured {@link Ext.data.Field#defaultValue defaultValue}.
      • + *
      • rec : Mixed
        The data object containing the row as read by the Reader. + * Depending on the Reader type, this could be an Array ({@link Ext.data.reader.Array ArrayReader}), an object + * ({@link Ext.data.reader.Json JsonReader}), or an XML element.
      • + *
    • + *
    • sortType : Function
      A function to convert the stored data into comparable form, as defined by {@link Ext.data.SortTypes}.
    • + *
    • type : String
      A textual data type name.
    • + *
    + *

    For example, to create a VELatLong field (See the Microsoft Bing Mapping API) containing the latitude/longitude value of a datapoint on a map from a JsonReader data block + * which contained the properties lat and long, you would define a new data type like this:

    + *
    
    +// Add a new Field data type which stores a VELatLong object in the Record.
    +Ext.data.Types.VELATLONG = {
    +    convert: function(v, data) {
    +        return new VELatLong(data.lat, data.long);
    +    },
    +    sortType: function(v) {
    +        return v.Latitude;  // When sorting, order by latitude
    +    },
    +    type: 'VELatLong'
    +};
    +
    + *

    Then, when declaring a Model, use:

    
    +var types = Ext.data.Types; // allow shorthand type access
    +Ext.define('Unit',
    +    extend: 'Ext.data.Model',
    +    fields: [
    +        { name: 'unitName', mapping: 'UnitName' },
    +        { name: 'curSpeed', mapping: 'CurSpeed', type: types.INT },
    +        { name: 'latitude', mapping: 'lat', type: types.FLOAT },
    +        { name: 'longitude', mapping: 'long', type: types.FLOAT },
    +        { name: 'position', type: types.VELATLONG }
    +    ]
    +});
    +
    + * @singleton + */ +Ext.define('Ext.data.Types', { + singleton: true, + requires: ['Ext.data.SortTypes'] +}, function() { + var st = Ext.data.SortTypes; + + Ext.apply(Ext.data.Types, { + /** + * @property {RegExp} stripRe + * A regular expression for stripping non-numeric characters from a numeric value. Defaults to /[\$,%]/g. + * This should be overridden for localization. + */ + stripRe: /[\$,%]/g, + + /** + * @property {Object} AUTO + * This data type means that no conversion is applied to the raw data before it is placed into a Record. + */ + AUTO: { + sortType: st.none, + type: 'auto' + }, + + /** + * @property {Object} STRING + * This data type means that the raw data is converted into a String before it is placed into a Record. + */ + STRING: { + convert: function(v) { + var defaultValue = this.useNull ? null : ''; + return (v === undefined || v === null) ? defaultValue : String(v); + }, + sortType: st.asUCString, + type: 'string' + }, + + /** + * @property {Object} INT + * This data type means that the raw data is converted into an integer before it is placed into a Record. + *

    The synonym INTEGER is equivalent.

    + */ + INT: { + convert: function(v) { + return v !== undefined && v !== null && v !== '' ? + parseInt(String(v).replace(Ext.data.Types.stripRe, ''), 10) : (this.useNull ? null : 0); + }, + sortType: st.none, + type: 'int' + }, + + /** + * @property {Object} FLOAT + * This data type means that the raw data is converted into a number before it is placed into a Record. + *

    The synonym NUMBER is equivalent.

    + */ + FLOAT: { + convert: function(v) { + return v !== undefined && v !== null && v !== '' ? + parseFloat(String(v).replace(Ext.data.Types.stripRe, ''), 10) : (this.useNull ? null : 0); + }, + sortType: st.none, + type: 'float' + }, + + /** + * @property {Object} BOOL + *

    This data type means that the raw data is converted into a boolean before it is placed into + * a Record. The string "true" and the number 1 are converted to boolean true.

    + *

    The synonym BOOLEAN is equivalent.

    + */ + BOOL: { + convert: function(v) { + if (this.useNull && (v === undefined || v === null || v === '')) { + return null; + } + return v === true || v === 'true' || v == 1; + }, + sortType: st.none, + type: 'bool' + }, + + /** + * @property {Object} DATE + * This data type means that the raw data is converted into a Date before it is placed into a Record. + * The date format is specified in the constructor of the {@link Ext.data.Field} to which this type is + * being applied. + */ + DATE: { + convert: function(v) { + var df = this.dateFormat, + parsed; + + if (!v) { + return null; + } + if (Ext.isDate(v)) { + return v; + } + if (df) { + if (df == 'timestamp') { + return new Date(v*1000); + } + if (df == 'time') { + return new Date(parseInt(v, 10)); + } + return Ext.Date.parse(v, df); + } + + parsed = Date.parse(v); + return parsed ? new Date(parsed) : null; + }, + sortType: st.asDate, + type: 'date' + } + }); + + Ext.apply(Ext.data.Types, { + /** + * @property {Object} BOOLEAN + *

    This data type means that the raw data is converted into a boolean before it is placed into + * a Record. The string "true" and the number 1 are converted to boolean true.

    + *

    The synonym BOOL is equivalent.

    + */ + BOOLEAN: this.BOOL, + + /** + * @property {Object} INTEGER + * This data type means that the raw data is converted into an integer before it is placed into a Record. + *

    The synonym INT is equivalent.

    + */ + INTEGER: this.INT, + + /** + * @property {Object} NUMBER + * This data type means that the raw data is converted into a number before it is placed into a Record. + *

    The synonym FLOAT is equivalent.

    + */ + NUMBER: this.FLOAT + }); +}); + +/** + * @extend Ext.data.IdGenerator + * @author Don Griffin + * + * This class generates UUID's according to RFC 4122. This class has a default id property. + * This means that a single instance is shared unless the id property is overridden. Thus, + * two {@link Ext.data.Model} instances configured like the following share one generator: + * + * Ext.define('MyApp.data.MyModelX', { + * extend: 'Ext.data.Model', + * idgen: 'uuid' + * }); + * + * Ext.define('MyApp.data.MyModelY', { + * extend: 'Ext.data.Model', + * idgen: 'uuid' + * }); + * + * This allows all models using this class to share a commonly configured instance. + * + * # Using Version 1 ("Sequential") UUID's + * + * If a server can provide a proper timestamp and a "cryptographic quality random number" + * (as described in RFC 4122), the shared instance can be configured as follows: + * + * Ext.data.IdGenerator.get('uuid').reconfigure({ + * version: 1, + * clockSeq: clock, // 14 random bits + * salt: salt, // 48 secure random bits (the Node field) + * timestamp: ts // timestamp per Section 4.1.4 + * }); + * + * // or these values can be split into 32-bit chunks: + * + * Ext.data.IdGenerator.get('uuid').reconfigure({ + * version: 1, + * clockSeq: clock, + * salt: { lo: saltLow32, hi: saltHigh32 }, + * timestamp: { lo: timestampLow32, hi: timestamptHigh32 } + * }); + * + * This approach improves the generator's uniqueness by providing a valid timestamp and + * higher quality random data. Version 1 UUID's should not be used unless this information + * can be provided by a server and care should be taken to avoid caching of this data. + * + * See http://www.ietf.org/rfc/rfc4122.txt for details. + */ +Ext.define('Ext.data.UuidGenerator', (function () { + var twoPow14 = Math.pow(2, 14), + twoPow16 = Math.pow(2, 16), + twoPow28 = Math.pow(2, 28), + twoPow32 = Math.pow(2, 32); + + function toHex (value, length) { + var ret = value.toString(16); + if (ret.length > length) { + ret = ret.substring(ret.length - length); // right-most digits + } else if (ret.length < length) { + ret = Ext.String.leftPad(ret, length, '0'); + } + return ret; + } + + function rand (lo, hi) { + var v = Math.random() * (hi - lo + 1); + return Math.floor(v) + lo; + } + + function split (bignum) { + if (typeof(bignum) == 'number') { + var hi = Math.floor(bignum / twoPow32); + return { + lo: Math.floor(bignum - hi * twoPow32), + hi: hi + }; + } + return bignum; + } + + return { + extend: 'Ext.data.IdGenerator', + + alias: 'idgen.uuid', + + id: 'uuid', // shared by default + + /** + * @property {Number/Object} salt + * When created, this value is a 48-bit number. For computation, this value is split + * into 32-bit parts and stored in an object with `hi` and `lo` properties. + */ + + /** + * @property {Number/Object} timestamp + * When created, this value is a 60-bit number. For computation, this value is split + * into 32-bit parts and stored in an object with `hi` and `lo` properties. + */ + + /** + * @cfg {Number} version + * The Version of UUID. Supported values are: + * + * * 1 : Time-based, "sequential" UUID. + * * 4 : Pseudo-random UUID. + * + * The default is 4. + */ + version: 4, + + constructor: function() { + var me = this; + + me.callParent(arguments); + + me.parts = []; + me.init(); + }, + + generate: function () { + var me = this, + parts = me.parts, + ts = me.timestamp; + + /* + The magic decoder ring (derived from RFC 4122 Section 4.2.2): + + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | time_low | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | time_mid | ver | time_hi | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + |res| clock_hi | clock_low | salt 0 |M| salt 1 | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | salt (2-5) | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + + time_mid clock_hi (low 6 bits) + time_low | time_hi |clock_lo + | | | || salt[0] + | | | || | salt[1..5] + v v v vv v v + 0badf00d-aced-1def-b123-dfad0badbeef + ^ ^ ^ + version | multicast (low bit) + | + reserved (upper 2 bits) + */ + parts[0] = toHex(ts.lo, 8); + parts[1] = toHex(ts.hi & 0xFFFF, 4); + parts[2] = toHex(((ts.hi >>> 16) & 0xFFF) | (me.version << 12), 4); + parts[3] = toHex(0x80 | ((me.clockSeq >>> 8) & 0x3F), 2) + + toHex(me.clockSeq & 0xFF, 2); + parts[4] = toHex(me.salt.hi, 4) + toHex(me.salt.lo, 8); + + if (me.version == 4) { + me.init(); // just regenerate all the random values... + } else { + // sequentially increment the timestamp... + ++ts.lo; + if (ts.lo >= twoPow32) { // if (overflow) + ts.lo = 0; + ++ts.hi; + } + } + + return parts.join('-').toLowerCase(); + }, + + getRecId: function (rec) { + return rec.getId(); + }, + + /** + * @private + */ + init: function () { + var me = this, + salt, time; + + if (me.version == 4) { + // See RFC 4122 (Secion 4.4) + // o If the state was unavailable (e.g., non-existent or corrupted), + // or the saved node ID is different than the current node ID, + // generate a random clock sequence value. + me.clockSeq = rand(0, twoPow14-1); + + // we run this on every id generation... + salt = me.salt || (me.salt = {}); + time = me.timestamp || (me.timestamp = {}); + + // See RFC 4122 (Secion 4.4) + salt.lo = rand(0, twoPow32-1); + salt.hi = rand(0, twoPow16-1); + time.lo = rand(0, twoPow32-1); + time.hi = rand(0, twoPow28-1); + } else { + // this is run only once per-instance + me.salt = split(me.salt); + me.timestamp = split(me.timestamp); + + // Set multicast bit: "the least significant bit of the first octet of the + // node ID" (nodeId = salt for this implementation): + me.salt.hi |= 0x100; + } + }, + + /** + * Reconfigures this generator given new config properties. + */ + reconfigure: function (config) { + Ext.apply(this, config); + this.init(); + } + }; +}())); + +/** + * @author Ed Spencer + * + * This singleton contains a set of validation functions that can be used to validate any type of data. They are most + * often used in {@link Ext.data.Model Models}, where they are automatically set up and executed. + */ +Ext.define('Ext.data.validations', { + singleton: true, + + /** + * @property {String} presenceMessage + * The default error message used when a presence validation fails. + */ + presenceMessage: 'must be present', + + /** + * @property {String} lengthMessage + * The default error message used when a length validation fails. + */ + lengthMessage: 'is the wrong length', + + /** + * @property {Boolean} formatMessage + * The default error message used when a format validation fails. + */ + formatMessage: 'is the wrong format', + + /** + * @property {String} inclusionMessage + * The default error message used when an inclusion validation fails. + */ + inclusionMessage: 'is not included in the list of acceptable values', + + /** + * @property {String} exclusionMessage + * The default error message used when an exclusion validation fails. + */ + exclusionMessage: 'is not an acceptable value', + + /** + * @property {String} emailMessage + * The default error message used when an email validation fails + */ + emailMessage: 'is not a valid email address', + + /** + * @property {RegExp} emailRe + * The regular expression used to validate email addresses + */ + emailRe: /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/, + + /** + * Validates that the given value is present. + * For example: + * + * validations: [{type: 'presence', field: 'age'}] + * + * @param {Object} config Config object + * @param {Object} value The value to validate + * @return {Boolean} True if validation passed + */ + presence: function(config, value) { + // No configs read, so allow just value to be passed + if (arguments.length === 1) { + value = config; + } + + //we need an additional check for zero here because zero is an acceptable form of present data + return !!value || value === 0; + }, + + /** + * Returns true if the given value is between the configured min and max values. + * For example: + * + * validations: [{type: 'length', field: 'name', min: 2}] + * + * @param {Object} config Config object + * @param {String} value The value to validate + * @return {Boolean} True if the value passes validation + */ + length: function(config, value) { + if (value === undefined || value === null) { + return false; + } + + var length = value.length, + min = config.min, + max = config.max; + + if ((min && length < min) || (max && length > max)) { + return false; + } else { + return true; + } + }, + + /** + * Validates that an email string is in the correct format + * @param {Object} config Config object + * @param {String} email The email address + * @return {Boolean} True if the value passes validation + */ + email: function(config, email) { + return Ext.data.validations.emailRe.test(email); + }, + + /** + * Returns true if the given value passes validation against the configured `matcher` regex. + * For example: + * + * validations: [{type: 'format', field: 'username', matcher: /([a-z]+)[0-9]{2,3}/}] + * + * @param {Object} config Config object + * @param {String} value The value to validate + * @return {Boolean} True if the value passes the format validation + */ + format: function(config, value) { + return !!(config.matcher && config.matcher.test(value)); + }, + + /** + * Validates that the given value is present in the configured `list`. + * For example: + * + * validations: [{type: 'inclusion', field: 'gender', list: ['Male', 'Female']}] + * + * @param {Object} config Config object + * @param {String} value The value to validate + * @return {Boolean} True if the value is present in the list + */ + inclusion: function(config, value) { + return config.list && Ext.Array.indexOf(config.list,value) != -1; + }, + + /** + * Validates that the given value is present in the configured `list`. + * For example: + * + * validations: [{type: 'exclusion', field: 'username', list: ['Admin', 'Operator']}] + * + * @param {Object} config Config object + * @param {String} value The value to validate + * @return {Boolean} True if the value is not present in the list + */ + exclusion: function(config, value) { + return config.list && Ext.Array.indexOf(config.list,value) == -1; + } +}); +/** + * @author Ed Spencer + * + * Associations enable you to express relationships between different {@link Ext.data.Model Models}. Let's say we're + * writing an ecommerce system where Users can make Orders - there's a relationship between these Models that we can + * express like this: + * + * Ext.define('User', { + * extend: 'Ext.data.Model', + * fields: ['id', 'name', 'email'], + * + * hasMany: {model: 'Order', name: 'orders'} + * }); + * + * Ext.define('Order', { + * extend: 'Ext.data.Model', + * fields: ['id', 'user_id', 'status', 'price'], + * + * belongsTo: 'User' + * }); + * + * We've set up two models - User and Order - and told them about each other. You can set up as many associations on + * each Model as you need using the two default types - {@link Ext.data.HasManyAssociation hasMany} and {@link + * Ext.data.BelongsToAssociation belongsTo}. There's much more detail on the usage of each of those inside their + * documentation pages. If you're not familiar with Models already, {@link Ext.data.Model there is plenty on those too}. + * + * **Further Reading** + * + * - {@link Ext.data.association.HasMany hasMany associations} + * - {@link Ext.data.association.BelongsTo belongsTo associations} + * - {@link Ext.data.association.HasOne hasOne associations} + * - {@link Ext.data.Model using Models} + * + * # Self association models + * + * We can also have models that create parent/child associations between the same type. Below is an example, where + * groups can be nested inside other groups: + * + * // Server Data + * { + * "groups": { + * "id": 10, + * "parent_id": 100, + * "name": "Main Group", + * "parent_group": { + * "id": 100, + * "parent_id": null, + * "name": "Parent Group" + * }, + * "child_groups": [{ + * "id": 2, + * "parent_id": 10, + * "name": "Child Group 1" + * },{ + * "id": 3, + * "parent_id": 10, + * "name": "Child Group 2" + * },{ + * "id": 4, + * "parent_id": 10, + * "name": "Child Group 3" + * }] + * } + * } + * + * // Client code + * Ext.define('Group', { + * extend: 'Ext.data.Model', + * fields: ['id', 'parent_id', 'name'], + * proxy: { + * type: 'ajax', + * url: 'data.json', + * reader: { + * type: 'json', + * root: 'groups' + * } + * }, + * associations: [{ + * type: 'hasMany', + * model: 'Group', + * primaryKey: 'id', + * foreignKey: 'parent_id', + * autoLoad: true, + * associationKey: 'child_groups' // read child data from child_groups + * }, { + * type: 'belongsTo', + * model: 'Group', + * primaryKey: 'id', + * foreignKey: 'parent_id', + * associationKey: 'parent_group' // read parent data from parent_group + * }] + * }); + * + * Ext.onReady(function(){ + * + * Group.load(10, { + * success: function(group){ + * console.log(group.getGroup().get('name')); + * + * group.groups().each(function(rec){ + * console.log(rec.get('name')); + * }); + * } + * }); + * + * }); + * + */ +Ext.define('Ext.data.association.Association', { + alternateClassName: 'Ext.data.Association', + /** + * @cfg {String} ownerModel (required) + * The string name of the model that owns the association. + */ + + /** + * @cfg {String} associatedModel (required) + * The string name of the model that is being associated with. + */ + + /** + * @cfg {String} primaryKey + * The name of the primary key on the associated model. In general this will be the + * {@link Ext.data.Model#idProperty} of the Model. + */ + primaryKey: 'id', + + /** + * @cfg {Ext.data.reader.Reader} reader + * A special reader to read associated data + */ + + /** + * @cfg {String} associationKey + * The name of the property in the data to read the association from. Defaults to the name of the associated model. + */ + + defaultReaderType: 'json', + + statics: { + AUTO_ID: 1000, + + create: function(association){ + if (!association.isAssociation) { + if (Ext.isString(association)) { + association = { + type: association + }; + } + + switch (association.type) { + case 'belongsTo': + return new Ext.data.association.BelongsTo(association); + case 'hasMany': + return new Ext.data.association.HasMany(association); + case 'hasOne': + return new Ext.data.association.HasOne(association); + //TODO Add this back when it's fixed +// case 'polymorphic': +// return Ext.create('Ext.data.PolymorphicAssociation', association); + default: + Ext.Error.raise('Unknown Association type: "' + association.type + '"'); + } + } + return association; + } + }, + + /** + * Creates the Association object. + * @param {Object} [config] Config object. + */ + constructor: function(config) { + Ext.apply(this, config); + + var types = Ext.ModelManager.types, + ownerName = config.ownerModel, + associatedName = config.associatedModel, + ownerModel = types[ownerName], + associatedModel = types[associatedName], + ownerProto; + + if (ownerModel === undefined) { + Ext.Error.raise("The configured ownerModel was not valid (you tried " + ownerName + ")"); + } + if (associatedModel === undefined) { + Ext.Error.raise("The configured associatedModel was not valid (you tried " + associatedName + ")"); + } + + this.ownerModel = ownerModel; + this.associatedModel = associatedModel; + + /** + * @property {String} ownerName + * The name of the model that 'owns' the association + */ + + /** + * @property {String} associatedName + * The name of the model is on the other end of the association (e.g. if a User model hasMany Orders, this is + * 'Order') + */ + + Ext.applyIf(this, { + ownerName : ownerName, + associatedName: associatedName + }); + + this.associationId = 'association' + (++this.statics().AUTO_ID); + }, + + /** + * Get a specialized reader for reading associated data + * @return {Ext.data.reader.Reader} The reader, null if not supplied + */ + getReader: function(){ + var me = this, + reader = me.reader, + model = me.associatedModel; + + if (reader) { + if (Ext.isString(reader)) { + reader = { + type: reader + }; + } + if (reader.isReader) { + reader.setModel(model); + } else { + Ext.applyIf(reader, { + model: model, + type : me.defaultReaderType + }); + } + me.reader = Ext.createByAlias('reader.' + reader.type, reader); + } + return me.reader || null; + } +}); + +/** + * @author Ed Spencer + * @class Ext.data.association.BelongsTo + * + * Represents a many to one association with another model. The owner model is expected to have + * a foreign key which references the primary key of the associated model: + * + * Ext.define('Category', { + * extend: 'Ext.data.Model', + * fields: [ + * { name: 'id', type: 'int' }, + * { name: 'name', type: 'string' } + * ] + * }); + * + * Ext.define('Product', { + * extend: 'Ext.data.Model', + * fields: [ + * { name: 'id', type: 'int' }, + * { name: 'category_id', type: 'int' }, + * { name: 'name', type: 'string' } + * ], + * // we can use the belongsTo shortcut on the model to create a belongsTo association + * associations: [ + * { type: 'belongsTo', model: 'Category' } + * ] + * }); + * + * In the example above we have created models for Products and Categories, and linked them together + * by saying that each Product belongs to a Category. This automatically links each Product to a Category + * based on the Product's category_id, and provides new functions on the Product model: + * + * ## Generated getter function + * + * The first function that is added to the owner model is a getter function: + * + * var product = new Product({ + * id: 100, + * category_id: 20, + * name: 'Sneakers' + * }); + * + * product.getCategory(function(category, operation) { + * // do something with the category object + * alert(category.get('id')); // alerts 20 + * }, this); + * + * The getCategory function was created on the Product model when we defined the association. This uses the + * Category's configured {@link Ext.data.proxy.Proxy proxy} to load the Category asynchronously, calling the provided + * callback when it has loaded. + * + * The new getCategory function will also accept an object containing success, failure and callback properties + * - callback will always be called, success will only be called if the associated model was loaded successfully + * and failure will only be called if the associatied model could not be loaded: + * + * product.getCategory({ + * reload: true, // force a reload if the owner model is already cached + * callback: function(category, operation) {}, // a function that will always be called + * success : function(category, operation) {}, // a function that will only be called if the load succeeded + * failure : function(category, operation) {}, // a function that will only be called if the load did not succeed + * scope : this // optionally pass in a scope object to execute the callbacks in + * }); + * + * In each case above the callbacks are called with two arguments - the associated model instance and the + * {@link Ext.data.Operation operation} object that was executed to load that instance. The Operation object is + * useful when the instance could not be loaded. + * + * Once the getter has been called on the model, it will be cached if the getter is called a second time. To + * force the model to reload, specify reload: true in the options object. + * + * ## Generated setter function + * + * The second generated function sets the associated model instance - if only a single argument is passed to + * the setter then the following two calls are identical: + * + * // this call... + * product.setCategory(10); + * + * // is equivalent to this call: + * product.set('category_id', 10); + * + * An instance of the owner model can also be passed as a parameter. + * + * If we pass in a second argument, the model will be automatically saved and the second argument passed to + * the owner model's {@link Ext.data.Model#save save} method: + * + * product.setCategory(10, function(product, operation) { + * // the product has been saved + * alert(product.get('category_id')); //now alerts 10 + * }); + * + * //alternative syntax: + * product.setCategory(10, { + * callback: function(product, operation), // a function that will always be called + * success : function(product, operation), // a function that will only be called if the load succeeded + * failure : function(product, operation), // a function that will only be called if the load did not succeed + * scope : this //optionally pass in a scope object to execute the callbacks in + * }) + * + * ## Customisation + * + * Associations reflect on the models they are linking to automatically set up properties such as the + * {@link #primaryKey} and {@link #foreignKey}. These can alternatively be specified: + * + * Ext.define('Product', { + * fields: [...], + * + * associations: [ + * { type: 'belongsTo', model: 'Category', primaryKey: 'unique_id', foreignKey: 'cat_id' } + * ] + * }); + * + * Here we replaced the default primary key (defaults to 'id') and foreign key (calculated as 'category_id') + * with our own settings. Usually this will not be needed. + */ +Ext.define('Ext.data.association.BelongsTo', { + extend: 'Ext.data.association.Association', + alternateClassName: 'Ext.data.BelongsToAssociation', + alias: 'association.belongsto', + + /** + * @cfg {String} foreignKey The name of the foreign key on the owner model that links it to the associated + * model. Defaults to the lowercased name of the associated model plus "_id", e.g. an association with a + * model called Product would set up a product_id foreign key. + * + * Ext.define('Order', { + * extend: 'Ext.data.Model', + * fields: ['id', 'date'], + * hasMany: 'Product' + * }); + * + * Ext.define('Product', { + * extend: 'Ext.data.Model', + * fields: ['id', 'name', 'order_id'], // refers to the id of the order that this product belongs to + * belongsTo: 'Group' + * }); + * var product = new Product({ + * id: 1, + * name: 'Product 1', + * order_id: 22 + * }, 1); + * product.getOrder(); // Will make a call to the server asking for order_id 22 + * + */ + + /** + * @cfg {String} getterName The name of the getter function that will be added to the local model's prototype. + * Defaults to 'get' + the name of the foreign model, e.g. getCategory + */ + + /** + * @cfg {String} setterName The name of the setter function that will be added to the local model's prototype. + * Defaults to 'set' + the name of the foreign model, e.g. setCategory + */ + + /** + * @cfg {String} type The type configuration can be used when creating associations using a configuration object. + * Use 'belongsTo' to create a BelongsTo association. + * + * associations: [{ + * type: 'belongsTo', + * model: 'User' + * }] + */ + constructor: function(config) { + this.callParent(arguments); + + var me = this, + ownerProto = me.ownerModel.prototype, + associatedName = me.associatedName, + getterName = me.getterName || 'get' + associatedName, + setterName = me.setterName || 'set' + associatedName; + + Ext.applyIf(me, { + name : associatedName, + foreignKey : associatedName.toLowerCase() + "_id", + instanceName: associatedName + 'BelongsToInstance', + associationKey: associatedName.toLowerCase() + }); + + ownerProto[getterName] = me.createGetter(); + ownerProto[setterName] = me.createSetter(); + }, + + /** + * @private + * Returns a setter function to be placed on the owner model's prototype + * @return {Function} The setter function + */ + createSetter: function() { + var me = this, + foreignKey = me.foreignKey; + + //'this' refers to the Model instance inside this function + return function(value, options, scope) { + // If we pass in an instance, pull the id out + if (value && value.isModel) { + value = value.getId(); + } + this.set(foreignKey, value); + + if (Ext.isFunction(options)) { + options = { + callback: options, + scope: scope || this + }; + } + + if (Ext.isObject(options)) { + return this.save(options); + } + }; + }, + + /** + * @private + * Returns a getter function to be placed on the owner model's prototype. We cache the loaded instance + * the first time it is loaded so that subsequent calls to the getter always receive the same reference. + * @return {Function} The getter function + */ + createGetter: function() { + var me = this, + associatedName = me.associatedName, + associatedModel = me.associatedModel, + foreignKey = me.foreignKey, + primaryKey = me.primaryKey, + instanceName = me.instanceName; + + //'this' refers to the Model instance inside this function + return function(options, scope) { + options = options || {}; + + var model = this, + foreignKeyId = model.get(foreignKey), + success, + instance, + args; + + if (options.reload === true || model[instanceName] === undefined) { + instance = Ext.ModelManager.create({}, associatedName); + instance.set(primaryKey, foreignKeyId); + + if (typeof options == 'function') { + options = { + callback: options, + scope: scope || model + }; + } + + // Overwrite the success handler so we can assign the current instance + success = options.success; + options.success = function(rec){ + model[instanceName] = rec; + if (success) { + success.apply(this, arguments); + } + }; + + associatedModel.load(foreignKeyId, options); + // assign temporarily while we wait for data to return + model[instanceName] = instance; + return instance; + } else { + instance = model[instanceName]; + args = [instance]; + scope = scope || options.scope || model; + + //TODO: We're duplicating the callback invokation code that the instance.load() call above + //makes here - ought to be able to normalize this - perhaps by caching at the Model.load layer + //instead of the association layer. + Ext.callback(options, scope, args); + Ext.callback(options.success, scope, args); + Ext.callback(options.failure, scope, args); + Ext.callback(options.callback, scope, args); + + return instance; + } + }; + }, + + /** + * Read associated data + * @private + * @param {Ext.data.Model} record The record we're writing to + * @param {Ext.data.reader.Reader} reader The reader for the associated model + * @param {Object} associationData The raw associated data + */ + read: function(record, reader, associationData){ + record[this.instanceName] = reader.read([associationData]).records[0]; + } +}); + +/** + * @class Ext.data.association.HasOne + * + * Represents a one to one association with another model. The owner model is expected to have + * a foreign key which references the primary key of the associated model: + * + * Ext.define('Address', { + * extend: 'Ext.data.Model', + * fields: [ + * { name: 'id', type: 'int' }, + * { name: 'number', type: 'string' }, + * { name: 'street', type: 'string' }, + * { name: 'city', type: 'string' }, + * { name: 'zip', type: 'string' }, + * ] + * }); + * + * Ext.define('Person', { + * extend: 'Ext.data.Model', + * fields: [ + * { name: 'id', type: 'int' }, + * { name: 'name', type: 'string' }, + * { name: 'address_id', type: 'int'} + * ], + * // we can use the hasOne shortcut on the model to create a hasOne association + * associations: { type: 'hasOne', model: 'Address' } + * }); + * + * In the example above we have created models for People and Addresses, and linked them together + * by saying that each Person has a single Address. This automatically links each Person to an Address + * based on the Persons address_id, and provides new functions on the Person model: + * + * ## Generated getter function + * + * The first function that is added to the owner model is a getter function: + * + * var person = new Person({ + * id: 100, + * address_id: 20, + * name: 'John Smith' + * }); + * + * person.getAddress(function(address, operation) { + * // do something with the address object + * alert(address.get('id')); // alerts 20 + * }, this); + * + * The getAddress function was created on the Person model when we defined the association. This uses the + * Persons configured {@link Ext.data.proxy.Proxy proxy} to load the Address asynchronously, calling the provided + * callback when it has loaded. + * + * The new getAddress function will also accept an object containing success, failure and callback properties + * - callback will always be called, success will only be called if the associated model was loaded successfully + * and failure will only be called if the associatied model could not be loaded: + * + * person.getAddress({ + * reload: true, // force a reload if the owner model is already cached + * callback: function(address, operation) {}, // a function that will always be called + * success : function(address, operation) {}, // a function that will only be called if the load succeeded + * failure : function(address, operation) {}, // a function that will only be called if the load did not succeed + * scope : this // optionally pass in a scope object to execute the callbacks in + * }); + * + * In each case above the callbacks are called with two arguments - the associated model instance and the + * {@link Ext.data.Operation operation} object that was executed to load that instance. The Operation object is + * useful when the instance could not be loaded. + * + * Once the getter has been called on the model, it will be cached if the getter is called a second time. To + * force the model to reload, specify reload: true in the options object. + * + * ## Generated setter function + * + * The second generated function sets the associated model instance - if only a single argument is passed to + * the setter then the following two calls are identical: + * + * // this call... + * person.setAddress(10); + * + * // is equivalent to this call: + * person.set('address_id', 10); + * + * An instance of the owner model can also be passed as a parameter. + * + * If we pass in a second argument, the model will be automatically saved and the second argument passed to + * the owner model's {@link Ext.data.Model#save save} method: + * + * person.setAddress(10, function(address, operation) { + * // the address has been saved + * alert(address.get('address_id')); //now alerts 10 + * }); + * + * //alternative syntax: + * person.setAddress(10, { + * callback: function(address, operation), // a function that will always be called + * success : function(address, operation), // a function that will only be called if the load succeeded + * failure : function(address, operation), // a function that will only be called if the load did not succeed + * scope : this //optionally pass in a scope object to execute the callbacks in + * }) + * + * ## Customisation + * + * Associations reflect on the models they are linking to automatically set up properties such as the + * {@link #primaryKey} and {@link #foreignKey}. These can alternatively be specified: + * + * Ext.define('Person', { + * fields: [...], + * + * associations: [ + * { type: 'hasOne', model: 'Address', primaryKey: 'unique_id', foreignKey: 'addr_id' } + * ] + * }); + * + * Here we replaced the default primary key (defaults to 'id') and foreign key (calculated as 'address_id') + * with our own settings. Usually this will not be needed. + */ +Ext.define('Ext.data.association.HasOne', { + extend: 'Ext.data.association.Association', + alternateClassName: 'Ext.data.HasOneAssociation', + + alias: 'association.hasone', + + /** + * @cfg {String} foreignKey The name of the foreign key on the owner model that links it to the associated + * model. Defaults to the lowercased name of the associated model plus "_id", e.g. an association with a + * model called Person would set up a address_id foreign key. + * + * Ext.define('Person', { + * extend: 'Ext.data.Model', + * fields: ['id', 'name', 'address_id'], // refers to the id of the address object + * hasOne: 'Address' + * }); + * + * Ext.define('Address', { + * extend: 'Ext.data.Model', + * fields: ['id', 'number', 'street', 'city', 'zip'], + * belongsTo: 'Person' + * }); + * var Person = new Person({ + * id: 1, + * name: 'John Smith', + * address_id: 13 + * }, 1); + * person.getAddress(); // Will make a call to the server asking for address_id 13 + * + */ + + /** + * @cfg {String} getterName The name of the getter function that will be added to the local model's prototype. + * Defaults to 'get' + the name of the foreign model, e.g. getAddress + */ + + /** + * @cfg {String} setterName The name of the setter function that will be added to the local model's prototype. + * Defaults to 'set' + the name of the foreign model, e.g. setAddress + */ + + /** + * @cfg {String} type The type configuration can be used when creating associations using a configuration object. + * Use 'hasOne' to create a HasOne association. + * + * associations: [{ + * type: 'hasOne', + * model: 'Address' + * }] + */ + + constructor: function(config) { + this.callParent(arguments); + + var me = this, + ownerProto = me.ownerModel.prototype, + associatedName = me.associatedName, + getterName = me.getterName || 'get' + associatedName, + setterName = me.setterName || 'set' + associatedName; + + Ext.applyIf(me, { + name : associatedName, + foreignKey : associatedName.toLowerCase() + "_id", + instanceName: associatedName + 'HasOneInstance', + associationKey: associatedName.toLowerCase() + }); + + ownerProto[getterName] = me.createGetter(); + ownerProto[setterName] = me.createSetter(); + }, + + /** + * @private + * Returns a setter function to be placed on the owner model's prototype + * @return {Function} The setter function + */ + createSetter: function() { + var me = this, + ownerModel = me.ownerModel, + foreignKey = me.foreignKey; + + //'this' refers to the Model instance inside this function + return function(value, options, scope) { + if (value && value.isModel) { + value = value.getId(); + } + + this.set(foreignKey, value); + + if (Ext.isFunction(options)) { + options = { + callback: options, + scope: scope || this + }; + } + + if (Ext.isObject(options)) { + return this.save(options); + } + }; + }, + + /** + * @private + * Returns a getter function to be placed on the owner model's prototype. We cache the loaded instance + * the first time it is loaded so that subsequent calls to the getter always receive the same reference. + * @return {Function} The getter function + */ + createGetter: function() { + var me = this, + ownerModel = me.ownerModel, + associatedName = me.associatedName, + associatedModel = me.associatedModel, + foreignKey = me.foreignKey, + primaryKey = me.primaryKey, + instanceName = me.instanceName; + + //'this' refers to the Model instance inside this function + return function(options, scope) { + options = options || {}; + + var model = this, + foreignKeyId = model.get(foreignKey), + success, + instance, + args; + + if (options.reload === true || model[instanceName] === undefined) { + instance = Ext.ModelManager.create({}, associatedName); + instance.set(primaryKey, foreignKeyId); + + if (typeof options == 'function') { + options = { + callback: options, + scope: scope || model + }; + } + + // Overwrite the success handler so we can assign the current instance + success = options.success; + options.success = function(rec){ + model[instanceName] = rec; + if (success) { + success.call(this, arguments); + } + }; + + associatedModel.load(foreignKeyId, options); + // assign temporarily while we wait for data to return + model[instanceName] = instance; + return instance; + } else { + instance = model[instanceName]; + args = [instance]; + scope = scope || model; + + //TODO: We're duplicating the callback invokation code that the instance.load() call above + //makes here - ought to be able to normalize this - perhaps by caching at the Model.load layer + //instead of the association layer. + Ext.callback(options, scope, args); + Ext.callback(options.success, scope, args); + Ext.callback(options.failure, scope, args); + Ext.callback(options.callback, scope, args); + + return instance; + } + }; + }, + + /** + * Read associated data + * @private + * @param {Ext.data.Model} record The record we're writing to + * @param {Ext.data.reader.Reader} reader The reader for the associated model + * @param {Object} associationData The raw associated data + */ + read: function(record, reader, associationData){ + var inverse = this.associatedModel.prototype.associations.findBy(function(assoc){ + return assoc.type === 'belongsTo' && assoc.associatedName === record.$className; + }), newRecord = reader.read([associationData]).records[0]; + + record[this.instanceName] = newRecord; + + //if the inverse association was found, set it now on each record we've just created + if (inverse) { + newRecord[inverse.instanceName] = record; + } + } +}); +/** + * @author Ed Spencer + * + * Base Writer class used by most subclasses of {@link Ext.data.proxy.Server}. This class is responsible for taking a + * set of {@link Ext.data.Operation} objects and a {@link Ext.data.Request} object and modifying that request based on + * the Operations. + * + * For example a Ext.data.writer.Json would format the Operations and their {@link Ext.data.Model} instances based on + * the config options passed to the JsonWriter's constructor. + * + * Writers are not needed for any kind of local storage - whether via a {@link Ext.data.proxy.WebStorage Web Storage + * proxy} (see {@link Ext.data.proxy.LocalStorage localStorage} and {@link Ext.data.proxy.SessionStorage + * sessionStorage}) or just in memory via a {@link Ext.data.proxy.Memory MemoryProxy}. + */ +Ext.define('Ext.data.writer.Writer', { + alias: 'writer.base', + alternateClassName: ['Ext.data.DataWriter', 'Ext.data.Writer'], + + /** + * @cfg {Boolean} writeAllFields + * True to write all fields from the record to the server. If set to false it will only send the fields that were + * modified. Note that any fields that have {@link Ext.data.Field#persist} set to false will still be ignored. + */ + writeAllFields: true, + + /** + * @cfg {String} nameProperty + * This property is used to read the key for each value that will be sent to the server. For example: + * + * Ext.define('Person', { + * extend: 'Ext.data.Model', + * fields: [{ + * name: 'first', + * mapping: 'firstName' + * }, { + * name: 'last', + * mapping: 'lastName' + * }, { + * name: 'age' + * }] + * }); + * new Ext.data.writer.Writer({ + * writeAllFields: true, + * nameProperty: 'mapping' + * }); + * + * // This will be sent to the server + * { + * firstName: 'first name value', + * lastName: 'last name value', + * age: 1 + * } + * + * If the value is not present, the field name will always be used. + */ + nameProperty: 'name', + + /* + * @property {Boolean} isWriter + * `true` in this class to identify an object as an instantiated Writer, or subclass thereof. + */ + isWriter: true, + + /** + * Creates new Writer. + * @param {Object} [config] Config object. + */ + constructor: function(config) { + Ext.apply(this, config); + }, + + /** + * Prepares a Proxy's Ext.data.Request object + * @param {Ext.data.Request} request The request object + * @return {Ext.data.Request} The modified request object + */ + write: function(request) { + var operation = request.operation, + records = operation.records || [], + len = records.length, + i = 0, + data = []; + + for (; i < len; i++) { + data.push(this.getRecordData(records[i], operation)); + } + return this.writeRecords(request, data); + }, + + /** + * Formats the data for each record before sending it to the server. This + * method should be overridden to format the data in a way that differs from the default. + * @param {Ext.data.Model} record The record that we are writing to the server. + * @param {Ext.data.Operation} [operation] An operation object. + * @return {Object} An object literal of name/value keys to be written to the server. + * By default this method returns the data property on the record. + */ + getRecordData: function(record, operation) { + var isPhantom = record.phantom === true, + writeAll = this.writeAllFields || isPhantom, + nameProperty = this.nameProperty, + fields = record.fields, + fieldItems = fields.items, + data = {}, + clientIdProperty = record.clientIdProperty, + changes, + name, + field, + key, + f, fLen; + + if (writeAll) { + fLen = fieldItems.length; + + for (f = 0; f < fLen; f++) { + field = fieldItems[f]; + + if (field.persist) { + name = field[nameProperty] || field.name; + data[name] = record.get(field.name); + } + } + } else { + // Only write the changes + changes = record.getChanges(); + for (key in changes) { + if (changes.hasOwnProperty(key)) { + field = fields.get(key); + name = field[nameProperty] || field.name; + data[name] = changes[key]; + } + } + } + if(isPhantom) { + if(clientIdProperty && operation && operation.records.length > 1) { + // include clientId for phantom records, if multiple records are being written to the server in one operation. + // The server can then return the clientId with each record so the operation can match the server records with the client records + data[clientIdProperty] = record.internalId; + } + } else { + // always include the id for non phantoms + data[record.idProperty] = record.getId(); + } + + return data; + } +}); + +/** + * @author Ed Spencer + * @class Ext.data.writer.Xml + +This class is used to write {@link Ext.data.Model} data to the server in an XML format. +The {@link #documentRoot} property is used to specify the root element in the XML document. +The {@link #record} option is used to specify the element name for each record that will make +up the XML document. + + * @markdown + */ +Ext.define('Ext.data.writer.Xml', { + + /* Begin Definitions */ + + extend: 'Ext.data.writer.Writer', + alternateClassName: 'Ext.data.XmlWriter', + + alias: 'writer.xml', + + /* End Definitions */ + + /** + * @cfg {String} documentRoot The name of the root element of the document. Defaults to 'xmlData'. + * If there is more than 1 record and the root is not specified, the default document root will still be used + * to ensure a valid XML document is created. + */ + documentRoot: 'xmlData', + + /** + * @cfg {String} defaultDocumentRoot The root to be used if {@link #documentRoot} is empty and a root is required + * to form a valid XML document. + */ + defaultDocumentRoot: 'xmlData', + + /** + * @cfg {String} header A header to use in the XML document (such as setting the encoding or version). + * Defaults to ''. + */ + header: '', + + /** + * @cfg {String} record The name of the node to use for each record. Defaults to 'record'. + */ + record: 'record', + + //inherit docs + writeRecords: function(request, data) { + var me = this, + xml = [], + i = 0, + len = data.length, + root = me.documentRoot, + record = me.record, + needsRoot = data.length !== 1, + item, + key; + + // may not exist + xml.push(me.header || ''); + + if (!root && needsRoot) { + root = me.defaultDocumentRoot; + } + + if (root) { + xml.push('<', root, '>'); + } + + for (; i < len; ++i) { + item = data[i]; + xml.push('<', record, '>'); + for (key in item) { + if (item.hasOwnProperty(key)) { + xml.push('<', key, '>', item[key], ''); + } + } + xml.push(''); + } + + if (root) { + xml.push(''); + } + + request.xmlData = xml.join(''); + return request; + } +}); + +/** + * Small utility class used internally to represent a Direct method. + * @private + */ +Ext.define('Ext.direct.RemotingMethod', { + + constructor: function(config){ + var me = this, + params = Ext.isDefined(config.params) ? config.params : config.len, + name, pLen, p, param; + + me.name = config.name; + me.formHandler = config.formHandler; + if (Ext.isNumber(params)) { + // given only the number of parameters + me.len = params; + me.ordered = true; + } else { + /* + * Given an array of either + * a) String + * b) Objects with a name property. We may want to encode extra info in here later + */ + me.params = []; + pLen = params.length; + for (p = 0; p < pLen; p++) { + param = params[p]; + name = Ext.isObject(param) ? param.name : param; + me.params.push(name); + } + } + }, + + getArgs: function(params, paramOrder, paramsAsHash){ + var args = [], + i, + len; + + if (this.ordered) { + if (this.len > 0) { + // If a paramOrder was specified, add the params into the argument list in that order. + if (paramOrder) { + for (i = 0, len = paramOrder.length; i < len; i++) { + args.push(params[paramOrder[i]]); + } + } else if (paramsAsHash) { + // If paramsAsHash was specified, add all the params as a single object argument. + args.push(params); + } + } + } else { + args.push(params); + } + + return args; + }, + + /** + * Takes the arguments for the Direct function and splits the arguments + * from the scope and the callback. + * @param {Array} args The arguments passed to the direct call + * @return {Object} An object with 3 properties, args, callback & scope. + */ + getCallData: function(args){ + var me = this, + data = null, + len = me.len, + params = me.params, + callback, + scope, + name; + + if (me.ordered) { + callback = args[len]; + scope = args[len + 1]; + if (len !== 0) { + data = args.slice(0, len); + } + } else { + data = Ext.apply({}, args[0]); + callback = args[1]; + scope = args[2]; + + // filter out any non-existent properties + for (name in data) { + if (data.hasOwnProperty(name)) { + if (!Ext.Array.contains(params, name)) { + delete data[name]; + } + } + } + } + + return { + data: data, + callback: callback, + scope: scope + }; + } +}); + +/** + * Supporting Class for Ext.Direct (not intended to be used directly). + */ +Ext.define('Ext.direct.Transaction', { + + /* Begin Definitions */ + + alias: 'direct.transaction', + alternateClassName: 'Ext.Direct.Transaction', + + statics: { + TRANSACTION_ID: 0 + }, + + /* End Definitions */ + + /** + * Creates new Transaction. + * @param {Object} [config] Config object. + */ + constructor: function(config){ + var me = this; + + Ext.apply(me, config); + me.id = me.tid = ++me.self.TRANSACTION_ID; + me.retryCount = 0; + }, + + send: function(){ + this.provider.queueTransaction(this); + }, + + retry: function(){ + this.retryCount++; + this.send(); + }, + + getProvider: function(){ + return this.provider; + } +}); + +/** + * Represents an RGB color and provides helper functions get + * color components in HSL color space. + */ +Ext.define('Ext.draw.Color', { + + /* Begin Definitions */ + + /* End Definitions */ + + colorToHexRe: /(.*?)rgb\((\d+),\s*(\d+),\s*(\d+)\)/, + rgbRe: /\s*rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)\s*/, + hexRe: /\s*#([0-9a-fA-F][0-9a-fA-F]?)([0-9a-fA-F][0-9a-fA-F]?)([0-9a-fA-F][0-9a-fA-F]?)\s*/, + + /** + * @cfg {Number} lightnessFactor + * + * The default factor to compute the lighter or darker color. Defaults to 0.2. + */ + lightnessFactor: 0.2, + + /** + * Creates new Color. + * @param {Number} red Red component (0..255) + * @param {Number} green Green component (0..255) + * @param {Number} blue Blue component (0..255) + */ + constructor : function(red, green, blue) { + var me = this, + clamp = Ext.Number.constrain; + me.r = clamp(red, 0, 255); + me.g = clamp(green, 0, 255); + me.b = clamp(blue, 0, 255); + }, + + /** + * Get the red component of the color, in the range 0..255. + * @return {Number} + */ + getRed: function() { + return this.r; + }, + + /** + * Get the green component of the color, in the range 0..255. + * @return {Number} + */ + getGreen: function() { + return this.g; + }, + + /** + * Get the blue component of the color, in the range 0..255. + * @return {Number} + */ + getBlue: function() { + return this.b; + }, + + /** + * Get the RGB values. + * @return {Number[]} + */ + getRGB: function() { + var me = this; + return [me.r, me.g, me.b]; + }, + + /** + * Get the equivalent HSL components of the color. + * @return {Number[]} + */ + getHSL: function() { + var me = this, + r = me.r / 255, + g = me.g / 255, + b = me.b / 255, + max = Math.max(r, g, b), + min = Math.min(r, g, b), + delta = max - min, + h, + s = 0, + l = 0.5 * (max + min); + + // min==max means achromatic (hue is undefined) + if (min != max) { + s = (l < 0.5) ? delta / (max + min) : delta / (2 - max - min); + if (r == max) { + h = 60 * (g - b) / delta; + } else if (g == max) { + h = 120 + 60 * (b - r) / delta; + } else { + h = 240 + 60 * (r - g) / delta; + } + if (h < 0) { + h += 360; + } + if (h >= 360) { + h -= 360; + } + } + return [h, s, l]; + }, + + /** + * Return a new color that is lighter than this color. + * @param {Number} factor Lighter factor (0..1), default to 0.2 + * @return Ext.draw.Color + */ + getLighter: function(factor) { + var hsl = this.getHSL(); + factor = factor || this.lightnessFactor; + hsl[2] = Ext.Number.constrain(hsl[2] + factor, 0, 1); + return this.fromHSL(hsl[0], hsl[1], hsl[2]); + }, + + /** + * Return a new color that is darker than this color. + * @param {Number} factor Darker factor (0..1), default to 0.2 + * @return Ext.draw.Color + */ + getDarker: function(factor) { + factor = factor || this.lightnessFactor; + return this.getLighter(-factor); + }, + + /** + * Return the color in the hex format, i.e. '#rrggbb'. + * @return {String} + */ + toString: function() { + var me = this, + round = Math.round, + r = round(me.r).toString(16), + g = round(me.g).toString(16), + b = round(me.b).toString(16); + r = (r.length == 1) ? '0' + r : r; + g = (g.length == 1) ? '0' + g : g; + b = (b.length == 1) ? '0' + b : b; + return ['#', r, g, b].join(''); + }, + + /** + * Convert a color to hexadecimal format. + * + * **Note:** This method is both static and instance. + * + * @param {String/String[]} color The color value (i.e 'rgb(255, 255, 255)', 'color: #ffffff'). + * Can also be an Array, in this case the function handles the first member. + * @returns {String} The color in hexadecimal format. + * @static + */ + toHex: function(color) { + if (Ext.isArray(color)) { + color = color[0]; + } + if (!Ext.isString(color)) { + return ''; + } + if (color.substr(0, 1) === '#') { + return color; + } + var digits = this.colorToHexRe.exec(color), + red, + green, + blue, + rgb; + + if (Ext.isArray(digits)) { + red = parseInt(digits[2], 10); + green = parseInt(digits[3], 10); + blue = parseInt(digits[4], 10); + rgb = blue | (green << 8) | (red << 16); + return digits[1] + '#' + ("000000" + rgb.toString(16)).slice(-6); + } + else { + return color; + } + }, + + /** + * Parse the string and create a new color. + * + * Supported formats: '#rrggbb', '#rgb', and 'rgb(r,g,b)'. + * + * If the string is not recognized, an undefined will be returned instead. + * + * **Note:** This method is both static and instance. + * + * @param {String} str Color in string. + * @returns Ext.draw.Color + * @static + */ + fromString: function(str) { + var values, r, g, b, + parse = parseInt; + + if ((str.length == 4 || str.length == 7) && str.substr(0, 1) === '#') { + values = str.match(this.hexRe); + if (values) { + r = parse(values[1], 16) >> 0; + g = parse(values[2], 16) >> 0; + b = parse(values[3], 16) >> 0; + if (str.length == 4) { + r += (r * 16); + g += (g * 16); + b += (b * 16); + } + } + } + else { + values = str.match(this.rgbRe); + if (values) { + r = values[1]; + g = values[2]; + b = values[3]; + } + } + + return (typeof r == 'undefined') ? undefined : new Ext.draw.Color(r, g, b); + }, + + /** + * Returns the gray value (0 to 255) of the color. + * + * The gray value is calculated using the formula r*0.3 + g*0.59 + b*0.11. + * + * @returns {Number} + */ + getGrayscale: function() { + // http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale + return this.r * 0.3 + this.g * 0.59 + this.b * 0.11; + }, + + /** + * Create a new color based on the specified HSL values. + * + * **Note:** This method is both static and instance. + * + * @param {Number} h Hue component (0..359) + * @param {Number} s Saturation component (0..1) + * @param {Number} l Lightness component (0..1) + * @returns Ext.draw.Color + * @static + */ + fromHSL: function(h, s, l) { + var C, X, m, i, rgb = [], + abs = Math.abs, + floor = Math.floor; + + if (s == 0 || h == null) { + // achromatic + rgb = [l, l, l]; + } + else { + // http://en.wikipedia.org/wiki/HSL_and_HSV#From_HSL + // C is the chroma + // X is the second largest component + // m is the lightness adjustment + h /= 60; + C = s * (1 - abs(2 * l - 1)); + X = C * (1 - abs(h - 2 * floor(h / 2) - 1)); + m = l - C / 2; + switch (floor(h)) { + case 0: + rgb = [C, X, 0]; + break; + case 1: + rgb = [X, C, 0]; + break; + case 2: + rgb = [0, C, X]; + break; + case 3: + rgb = [0, X, C]; + break; + case 4: + rgb = [X, 0, C]; + break; + case 5: + rgb = [C, 0, X]; + break; + } + rgb = [rgb[0] + m, rgb[1] + m, rgb[2] + m]; + } + return new Ext.draw.Color(rgb[0] * 255, rgb[1] * 255, rgb[2] * 255); + } +}, function() { + var prototype = this.prototype; + + //These functions are both static and instance. TODO: find a more elegant way of copying them + this.addStatics({ + fromHSL: function() { + return prototype.fromHSL.apply(prototype, arguments); + }, + fromString: function() { + return prototype.fromString.apply(prototype, arguments); + }, + toHex: function() { + return prototype.toHex.apply(prototype, arguments); + } + }); +}); + +/** + * @class Ext.draw.Draw + * Base Drawing class. Provides base drawing functions. + * @private + */ +Ext.define('Ext.draw.Draw', { + /* Begin Definitions */ + + singleton: true, + + requires: ['Ext.draw.Color'], + + /* End Definitions */ + + pathToStringRE: /,?([achlmqrstvxz]),?/gi, + pathCommandRE: /([achlmqstvz])[\s,]*((-?\d*\.?\d*(?:e[-+]?\d+)?\s*,?\s*)+)/ig, + pathValuesRE: /(-?\d*\.?\d*(?:e[-+]?\d+)?)\s*,?\s*/ig, + stopsRE: /^(\d+%?)$/, + radian: Math.PI / 180, + + availableAnimAttrs: { + along: "along", + blur: null, + "clip-rect": "csv", + cx: null, + cy: null, + fill: "color", + "fill-opacity": null, + "font-size": null, + height: null, + opacity: null, + path: "path", + r: null, + rotation: "csv", + rx: null, + ry: null, + scale: "csv", + stroke: "color", + "stroke-opacity": null, + "stroke-width": null, + translation: "csv", + width: null, + x: null, + y: null + }, + + is: function(o, type) { + type = String(type).toLowerCase(); + return (type == "object" && o === Object(o)) || + (type == "undefined" && typeof o == type) || + (type == "null" && o === null) || + (type == "array" && Array.isArray && Array.isArray(o)) || + (Object.prototype.toString.call(o).toLowerCase().slice(8, -1)) == type; + }, + + ellipsePath: function(sprite) { + var attr = sprite.attr; + return Ext.String.format("M{0},{1}A{2},{3},0,1,1,{0},{4}A{2},{3},0,1,1,{0},{1}z", attr.x, attr.y - attr.ry, attr.rx, attr.ry, attr.y + attr.ry); + }, + + rectPath: function(sprite) { + var attr = sprite.attr; + if (attr.radius) { + return Ext.String.format("M{0},{1}l{2},0a{3},{3},0,0,1,{3},{3}l0,{5}a{3},{3},0,0,1,{4},{3}l{6},0a{3},{3},0,0,1,{4},{4}l0,{7}a{3},{3},0,0,1,{3},{4}z", attr.x + attr.radius, attr.y, attr.width - attr.radius * 2, attr.radius, -attr.radius, attr.height - attr.radius * 2, attr.radius * 2 - attr.width, attr.radius * 2 - attr.height); + } + else { + return Ext.String.format("M{0},{1}L{2},{1},{2},{3},{0},{3}z", attr.x, attr.y, attr.width + attr.x, attr.height + attr.y); + } + }, + + // To be deprecated, converts itself (an arrayPath) to a proper SVG path string + path2string: function () { + return this.join(",").replace(Ext.draw.Draw.pathToStringRE, "$1"); + }, + + // Convert the passed arrayPath to a proper SVG path string (d attribute) + pathToString: function(arrayPath) { + return arrayPath.join(",").replace(Ext.draw.Draw.pathToStringRE, "$1"); + }, + + parsePathString: function (pathString) { + if (!pathString) { + return null; + } + var paramCounts = {a: 7, c: 6, h: 1, l: 2, m: 2, q: 4, s: 4, t: 2, v: 1, z: 0}, + data = [], + me = this; + if (me.is(pathString, "array") && me.is(pathString[0], "array")) { // rough assumption + data = me.pathClone(pathString); + } + if (!data.length) { + String(pathString).replace(me.pathCommandRE, function (a, b, c) { + var params = [], + name = b.toLowerCase(); + c.replace(me.pathValuesRE, function (a, b) { + b && params.push(+b); + }); + if (name == "m" && params.length > 2) { + data.push([b].concat(Ext.Array.splice(params, 0, 2))); + name = "l"; + b = (b == "m") ? "l" : "L"; + } + while (params.length >= paramCounts[name]) { + data.push([b].concat(Ext.Array.splice(params, 0, paramCounts[name]))); + if (!paramCounts[name]) { + break; + } + } + }); + } + data.toString = me.path2string; + return data; + }, + + mapPath: function (path, matrix) { + if (!matrix) { + return path; + } + var x, y, i, ii, j, jj, pathi; + path = this.path2curve(path); + for (i = 0, ii = path.length; i < ii; i++) { + pathi = path[i]; + for (j = 1, jj = pathi.length; j < jj-1; j += 2) { + x = matrix.x(pathi[j], pathi[j + 1]); + y = matrix.y(pathi[j], pathi[j + 1]); + pathi[j] = x; + pathi[j + 1] = y; + } + } + return path; + }, + + pathClone: function(pathArray) { + var res = [], + j, jj, i, ii; + if (!this.is(pathArray, "array") || !this.is(pathArray && pathArray[0], "array")) { // rough assumption + pathArray = this.parsePathString(pathArray); + } + for (i = 0, ii = pathArray.length; i < ii; i++) { + res[i] = []; + for (j = 0, jj = pathArray[i].length; j < jj; j++) { + res[i][j] = pathArray[i][j]; + } + } + res.toString = this.path2string; + return res; + }, + + pathToAbsolute: function (pathArray) { + if (!this.is(pathArray, "array") || !this.is(pathArray && pathArray[0], "array")) { // rough assumption + pathArray = this.parsePathString(pathArray); + } + var res = [], + x = 0, + y = 0, + mx = 0, + my = 0, + i = 0, + ln = pathArray.length, + r, pathSegment, j, ln2; + // MoveTo initial x/y position + if (ln && pathArray[0][0] == "M") { + x = +pathArray[0][1]; + y = +pathArray[0][2]; + mx = x; + my = y; + i++; + res[0] = ["M", x, y]; + } + for (; i < ln; i++) { + r = res[i] = []; + pathSegment = pathArray[i]; + if (pathSegment[0] != pathSegment[0].toUpperCase()) { + r[0] = pathSegment[0].toUpperCase(); + switch (r[0]) { + // Elliptical Arc + case "A": + r[1] = pathSegment[1]; + r[2] = pathSegment[2]; + r[3] = pathSegment[3]; + r[4] = pathSegment[4]; + r[5] = pathSegment[5]; + r[6] = +(pathSegment[6] + x); + r[7] = +(pathSegment[7] + y); + break; + // Vertical LineTo + case "V": + r[1] = +pathSegment[1] + y; + break; + // Horizontal LineTo + case "H": + r[1] = +pathSegment[1] + x; + break; + case "M": + // MoveTo + mx = +pathSegment[1] + x; + my = +pathSegment[2] + y; + default: + j = 1; + ln2 = pathSegment.length; + for (; j < ln2; j++) { + r[j] = +pathSegment[j] + ((j % 2) ? x : y); + } + } + } + else { + j = 0; + ln2 = pathSegment.length; + for (; j < ln2; j++) { + res[i][j] = pathSegment[j]; + } + } + switch (r[0]) { + // ClosePath + case "Z": + x = mx; + y = my; + break; + // Horizontal LineTo + case "H": + x = r[1]; + break; + // Vertical LineTo + case "V": + y = r[1]; + break; + // MoveTo + case "M": + pathSegment = res[i]; + ln2 = pathSegment.length; + mx = pathSegment[ln2 - 2]; + my = pathSegment[ln2 - 1]; + default: + pathSegment = res[i]; + ln2 = pathSegment.length; + x = pathSegment[ln2 - 2]; + y = pathSegment[ln2 - 1]; + } + } + res.toString = this.path2string; + return res; + }, + + // TO BE DEPRECATED + pathToRelative: function (pathArray) { + if (!this.is(pathArray, "array") || !this.is(pathArray && pathArray[0], "array")) { + pathArray = this.parsePathString(pathArray); + } + var res = [], + x = 0, + y = 0, + mx = 0, + my = 0, + start = 0, + r, + pa, + i, + j, + k, + len, + ii, + jj, + kk; + + if (pathArray[0][0] == "M") { + x = pathArray[0][1]; + y = pathArray[0][2]; + mx = x; + my = y; + start++; + res.push(["M", x, y]); + } + for (i = start, ii = pathArray.length; i < ii; i++) { + r = res[i] = []; + pa = pathArray[i]; + if (pa[0] != pa[0].toLowerCase()) { + r[0] = pa[0].toLowerCase(); + switch (r[0]) { + case "a": + r[1] = pa[1]; + r[2] = pa[2]; + r[3] = pa[3]; + r[4] = pa[4]; + r[5] = pa[5]; + r[6] = +(pa[6] - x).toFixed(3); + r[7] = +(pa[7] - y).toFixed(3); + break; + case "v": + r[1] = +(pa[1] - y).toFixed(3); + break; + case "m": + mx = pa[1]; + my = pa[2]; + default: + for (j = 1, jj = pa.length; j < jj; j++) { + r[j] = +(pa[j] - ((j % 2) ? x : y)).toFixed(3); + } + } + } else { + r = res[i] = []; + if (pa[0] == "m") { + mx = pa[1] + x; + my = pa[2] + y; + } + for (k = 0, kk = pa.length; k < kk; k++) { + res[i][k] = pa[k]; + } + } + len = res[i].length; + switch (res[i][0]) { + case "z": + x = mx; + y = my; + break; + case "h": + x += +res[i][len - 1]; + break; + case "v": + y += +res[i][len - 1]; + break; + default: + x += +res[i][len - 2]; + y += +res[i][len - 1]; + } + } + res.toString = this.path2string; + return res; + }, + + // Returns a path converted to a set of curveto commands + path2curve: function (path) { + var me = this, + points = me.pathToAbsolute(path), + ln = points.length, + attrs = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null}, + i, seg, segLn, point; + + for (i = 0; i < ln; i++) { + points[i] = me.command2curve(points[i], attrs); + if (points[i].length > 7) { + points[i].shift(); + point = points[i]; + while (point.length) { + Ext.Array.splice(points, i++, 0, ["C"].concat(Ext.Array.splice(point, 0, 6))); + } + Ext.Array.erase(points, i, 1); + ln = points.length; + i--; + } + seg = points[i]; + segLn = seg.length; + attrs.x = seg[segLn - 2]; + attrs.y = seg[segLn - 1]; + attrs.bx = parseFloat(seg[segLn - 4]) || attrs.x; + attrs.by = parseFloat(seg[segLn - 3]) || attrs.y; + } + return points; + }, + + interpolatePaths: function (path, path2) { + var me = this, + p = me.pathToAbsolute(path), + p2 = me.pathToAbsolute(path2), + attrs = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null}, + attrs2 = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null}, + fixArc = function (pp, i) { + if (pp[i].length > 7) { + pp[i].shift(); + var pi = pp[i]; + while (pi.length) { + Ext.Array.splice(pp, i++, 0, ["C"].concat(Ext.Array.splice(pi, 0, 6))); + } + Ext.Array.erase(pp, i, 1); + ii = Math.max(p.length, p2.length || 0); + } + }, + fixM = function (path1, path2, a1, a2, i) { + if (path1 && path2 && path1[i][0] == "M" && path2[i][0] != "M") { + Ext.Array.splice(path2, i, 0, ["M", a2.x, a2.y]); + a1.bx = 0; + a1.by = 0; + a1.x = path1[i][1]; + a1.y = path1[i][2]; + ii = Math.max(p.length, p2.length || 0); + } + }, + i, ii, + seg, seg2, seglen, seg2len; + for (i = 0, ii = Math.max(p.length, p2.length || 0); i < ii; i++) { + p[i] = me.command2curve(p[i], attrs); + fixArc(p, i); + (p2[i] = me.command2curve(p2[i], attrs2)); + fixArc(p2, i); + fixM(p, p2, attrs, attrs2, i); + fixM(p2, p, attrs2, attrs, i); + seg = p[i]; + seg2 = p2[i]; + seglen = seg.length; + seg2len = seg2.length; + attrs.x = seg[seglen - 2]; + attrs.y = seg[seglen - 1]; + attrs.bx = parseFloat(seg[seglen - 4]) || attrs.x; + attrs.by = parseFloat(seg[seglen - 3]) || attrs.y; + attrs2.bx = (parseFloat(seg2[seg2len - 4]) || attrs2.x); + attrs2.by = (parseFloat(seg2[seg2len - 3]) || attrs2.y); + attrs2.x = seg2[seg2len - 2]; + attrs2.y = seg2[seg2len - 1]; + } + return [p, p2]; + }, + + //Returns any path command as a curveto command based on the attrs passed + command2curve: function (pathCommand, d) { + var me = this; + if (!pathCommand) { + return ["C", d.x, d.y, d.x, d.y, d.x, d.y]; + } + if (pathCommand[0] != "T" && pathCommand[0] != "Q") { + d.qx = d.qy = null; + } + switch (pathCommand[0]) { + case "M": + d.X = pathCommand[1]; + d.Y = pathCommand[2]; + break; + case "A": + pathCommand = ["C"].concat(me.arc2curve.apply(me, [d.x, d.y].concat(pathCommand.slice(1)))); + break; + case "S": + pathCommand = ["C", d.x + (d.x - (d.bx || d.x)), d.y + (d.y - (d.by || d.y))].concat(pathCommand.slice(1)); + break; + case "T": + d.qx = d.x + (d.x - (d.qx || d.x)); + d.qy = d.y + (d.y - (d.qy || d.y)); + pathCommand = ["C"].concat(me.quadratic2curve(d.x, d.y, d.qx, d.qy, pathCommand[1], pathCommand[2])); + break; + case "Q": + d.qx = pathCommand[1]; + d.qy = pathCommand[2]; + pathCommand = ["C"].concat(me.quadratic2curve(d.x, d.y, pathCommand[1], pathCommand[2], pathCommand[3], pathCommand[4])); + break; + case "L": + pathCommand = ["C"].concat(d.x, d.y, pathCommand[1], pathCommand[2], pathCommand[1], pathCommand[2]); + break; + case "H": + pathCommand = ["C"].concat(d.x, d.y, pathCommand[1], d.y, pathCommand[1], d.y); + break; + case "V": + pathCommand = ["C"].concat(d.x, d.y, d.x, pathCommand[1], d.x, pathCommand[1]); + break; + case "Z": + pathCommand = ["C"].concat(d.x, d.y, d.X, d.Y, d.X, d.Y); + break; + } + return pathCommand; + }, + + quadratic2curve: function (x1, y1, ax, ay, x2, y2) { + var _13 = 1 / 3, + _23 = 2 / 3; + return [ + _13 * x1 + _23 * ax, + _13 * y1 + _23 * ay, + _13 * x2 + _23 * ax, + _13 * y2 + _23 * ay, + x2, + y2 + ]; + }, + + rotate: function (x, y, rad) { + var cos = Math.cos(rad), + sin = Math.sin(rad), + X = x * cos - y * sin, + Y = x * sin + y * cos; + return {x: X, y: Y}; + }, + + arc2curve: function (x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) { + // for more information of where this Math came from visit: + // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes + var me = this, + PI = Math.PI, + radian = me.radian, + _120 = PI * 120 / 180, + rad = radian * (+angle || 0), + res = [], + math = Math, + mcos = math.cos, + msin = math.sin, + msqrt = math.sqrt, + mabs = math.abs, + masin = math.asin, + xy, cos, sin, x, y, h, rx2, ry2, k, cx, cy, f1, f2, df, c1, s1, c2, s2, + t, hx, hy, m1, m2, m3, m4, newres, i, ln, f2old, x2old, y2old; + if (!recursive) { + xy = me.rotate(x1, y1, -rad); + x1 = xy.x; + y1 = xy.y; + xy = me.rotate(x2, y2, -rad); + x2 = xy.x; + y2 = xy.y; + cos = mcos(radian * angle); + sin = msin(radian * angle); + x = (x1 - x2) / 2; + y = (y1 - y2) / 2; + h = (x * x) / (rx * rx) + (y * y) / (ry * ry); + if (h > 1) { + h = msqrt(h); + rx = h * rx; + ry = h * ry; + } + rx2 = rx * rx; + ry2 = ry * ry; + k = (large_arc_flag == sweep_flag ? -1 : 1) * + msqrt(mabs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x))); + cx = k * rx * y / ry + (x1 + x2) / 2; + cy = k * -ry * x / rx + (y1 + y2) / 2; + f1 = masin(((y1 - cy) / ry).toFixed(7)); + f2 = masin(((y2 - cy) / ry).toFixed(7)); + + f1 = x1 < cx ? PI - f1 : f1; + f2 = x2 < cx ? PI - f2 : f2; + if (f1 < 0) { + f1 = PI * 2 + f1; + } + if (f2 < 0) { + f2 = PI * 2 + f2; + } + if (sweep_flag && f1 > f2) { + f1 = f1 - PI * 2; + } + if (!sweep_flag && f2 > f1) { + f2 = f2 - PI * 2; + } + } + else { + f1 = recursive[0]; + f2 = recursive[1]; + cx = recursive[2]; + cy = recursive[3]; + } + df = f2 - f1; + if (mabs(df) > _120) { + f2old = f2; + x2old = x2; + y2old = y2; + f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1); + x2 = cx + rx * mcos(f2); + y2 = cy + ry * msin(f2); + res = me.arc2curve(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [f2, f2old, cx, cy]); + } + df = f2 - f1; + c1 = mcos(f1); + s1 = msin(f1); + c2 = mcos(f2); + s2 = msin(f2); + t = math.tan(df / 4); + hx = 4 / 3 * rx * t; + hy = 4 / 3 * ry * t; + m1 = [x1, y1]; + m2 = [x1 + hx * s1, y1 - hy * c1]; + m3 = [x2 + hx * s2, y2 - hy * c2]; + m4 = [x2, y2]; + m2[0] = 2 * m1[0] - m2[0]; + m2[1] = 2 * m1[1] - m2[1]; + if (recursive) { + return [m2, m3, m4].concat(res); + } + else { + res = [m2, m3, m4].concat(res).join().split(","); + newres = []; + ln = res.length; + for (i = 0; i < ln; i++) { + newres[i] = i % 2 ? me.rotate(res[i - 1], res[i], rad).y : me.rotate(res[i], res[i + 1], rad).x; + } + return newres; + } + }, + + // TO BE DEPRECATED + rotateAndTranslatePath: function (sprite) { + var alpha = sprite.rotation.degrees, + cx = sprite.rotation.x, + cy = sprite.rotation.y, + dx = sprite.translation.x, + dy = sprite.translation.y, + path, + i, + p, + xy, + j, + res = []; + if (!alpha && !dx && !dy) { + return this.pathToAbsolute(sprite.attr.path); + } + dx = dx || 0; + dy = dy || 0; + path = this.pathToAbsolute(sprite.attr.path); + for (i = path.length; i--;) { + p = res[i] = path[i].slice(); + if (p[0] == "A") { + xy = this.rotatePoint(p[6], p[7], alpha, cx, cy); + p[6] = xy.x + dx; + p[7] = xy.y + dy; + } else { + j = 1; + while (p[j + 1] != null) { + xy = this.rotatePoint(p[j], p[j + 1], alpha, cx, cy); + p[j] = xy.x + dx; + p[j + 1] = xy.y + dy; + j += 2; + } + } + } + return res; + }, + + // TO BE DEPRECATED + rotatePoint: function (x, y, alpha, cx, cy) { + if (!alpha) { + return { + x: x, + y: y + }; + } + cx = cx || 0; + cy = cy || 0; + x = x - cx; + y = y - cy; + alpha = alpha * this.radian; + var cos = Math.cos(alpha), + sin = Math.sin(alpha); + return { + x: x * cos - y * sin + cx, + y: x * sin + y * cos + cy + }; + }, + + pathDimensions: function (path) { + if (!path || !(path + "")) { + return {x: 0, y: 0, width: 0, height: 0}; + } + path = this.path2curve(path); + var x = 0, + y = 0, + X = [], + Y = [], + i = 0, + ln = path.length, + p, xmin, ymin, dim; + for (; i < ln; i++) { + p = path[i]; + if (p[0] == "M") { + x = p[1]; + y = p[2]; + X.push(x); + Y.push(y); + } + else { + dim = this.curveDim(x, y, p[1], p[2], p[3], p[4], p[5], p[6]); + X = X.concat(dim.min.x, dim.max.x); + Y = Y.concat(dim.min.y, dim.max.y); + x = p[5]; + y = p[6]; + } + } + xmin = Math.min.apply(0, X); + ymin = Math.min.apply(0, Y); + return { + x: xmin, + y: ymin, + path: path, + width: Math.max.apply(0, X) - xmin, + height: Math.max.apply(0, Y) - ymin + }; + }, + + intersectInside: function(path, cp1, cp2) { + return (cp2[0] - cp1[0]) * (path[1] - cp1[1]) > (cp2[1] - cp1[1]) * (path[0] - cp1[0]); + }, + + intersectIntersection: function(s, e, cp1, cp2) { + var p = [], + dcx = cp1[0] - cp2[0], + dcy = cp1[1] - cp2[1], + dpx = s[0] - e[0], + dpy = s[1] - e[1], + n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0], + n2 = s[0] * e[1] - s[1] * e[0], + n3 = 1 / (dcx * dpy - dcy * dpx); + + p[0] = (n1 * dpx - n2 * dcx) * n3; + p[1] = (n1 * dpy - n2 * dcy) * n3; + return p; + }, + + intersect: function(subjectPolygon, clipPolygon) { + var me = this, + i = 0, + ln = clipPolygon.length, + cp1 = clipPolygon[ln - 1], + outputList = subjectPolygon, + cp2, s, e, point, ln2, inputList, j; + for (; i < ln; ++i) { + cp2 = clipPolygon[i]; + inputList = outputList; + outputList = []; + s = inputList[inputList.length - 1]; + j = 0; + ln2 = inputList.length; + for (; j < ln2; j++) { + e = inputList[j]; + if (me.intersectInside(e, cp1, cp2)) { + if (!me.intersectInside(s, cp1, cp2)) { + outputList.push(me.intersectIntersection(s, e, cp1, cp2)); + } + outputList.push(e); + } + else if (me.intersectInside(s, cp1, cp2)) { + outputList.push(me.intersectIntersection(s, e, cp1, cp2)); + } + s = e; + } + cp1 = cp2; + } + return outputList; + }, + + bezier : function (a, b, c, d, x) { + if (x === 0) { + return a; + } + else if (x === 1) { + return d; + } + var du = 1 - x, + d3 = du * du * du, + r = x / du; + return d3 * (a + r * (3 * b + r * (3 * c + d * r))); + }, + + bezierDim : function (a, b, c, d) { + var points = [], r, + A, top, C, delta, bottom, s, + min, max, i; + // The min and max happens on boundary or b' == 0 + if (a + 3 * c == d + 3 * b) { + r = a - b; + r /= 2 * (a - b - b + c); + if ( r < 1 && r > 0) { + points.push(r); + } + } else { + // b'(x) / -3 = (a-3b+3c-d)x^2+ (-2a+4b-2c)x + (a-b) + // delta = -4 (-b^2+a c+b c-c^2-a d+b d) + A = a - 3 * b + 3 * c - d; + top = 2 * (a - b - b + c); + C = a - b; + delta = top * top - 4 * A * C; + bottom = A + A; + if (delta === 0) { + r = top / bottom; + if (r < 1 && r > 0) { + points.push(r); + } + } else if (delta > 0) { + s = Math.sqrt(delta); + r = (s + top) / bottom; + + if (r < 1 && r > 0) { + points.push(r); + } + + r = (top - s) / bottom; + + if (r < 1 && r > 0) { + points.push(r); + } + } + } + min = Math.min(a, d); + max = Math.max(a, d); + for (i = 0; i < points.length; i++) { + min = Math.min(min, this.bezier(a, b, c, d, points[i])); + max = Math.max(max, this.bezier(a, b, c, d, points[i])); + } + return [min, max]; + }, + + curveDim: function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) { + var x = this.bezierDim(p1x, c1x, c2x, p2x), + y = this.bezierDim(p1y, c1y, c2y, p2y); + return { + min: { + x: x[0], + y: y[0] + }, + max: { + x: x[1], + y: y[1] + } + }; + }, + + /** + * @private + * + * Calculates bezier curve control anchor points for a particular point in a path, with a + * smoothing curve applied. The smoothness of the curve is controlled by the 'value' parameter. + * Note that this algorithm assumes that the line being smoothed is normalized going from left + * to right; it makes special adjustments assuming this orientation. + * + * @param {Number} prevX X coordinate of the previous point in the path + * @param {Number} prevY Y coordinate of the previous point in the path + * @param {Number} curX X coordinate of the current point in the path + * @param {Number} curY Y coordinate of the current point in the path + * @param {Number} nextX X coordinate of the next point in the path + * @param {Number} nextY Y coordinate of the next point in the path + * @param {Number} value A value to control the smoothness of the curve; this is used to + * divide the distance between points, so a value of 2 corresponds to + * half the distance between points (a very smooth line) while higher values + * result in less smooth curves. Defaults to 4. + * @return {Object} Object containing x1, y1, x2, y2 bezier control anchor points; x1 and y1 + * are the control point for the curve toward the previous path point, and + * x2 and y2 are the control point for the curve toward the next path point. + */ + getAnchors: function (prevX, prevY, curX, curY, nextX, nextY, value) { + value = value || 4; + var M = Math, + PI = M.PI, + halfPI = PI / 2, + abs = M.abs, + sin = M.sin, + cos = M.cos, + atan = M.atan, + control1Length, control2Length, control1Angle, control2Angle, + control1X, control1Y, control2X, control2Y, alpha; + + // Find the length of each control anchor line, by dividing the horizontal distance + // between points by the value parameter. + control1Length = (curX - prevX) / value; + control2Length = (nextX - curX) / value; + + // Determine the angle of each control anchor line. If the middle point is a vertical + // turnaround then we force it to a flat horizontal angle to prevent the curve from + // dipping above or below the middle point. Otherwise we use an angle that points + // toward the previous/next target point. + if ((curY >= prevY && curY >= nextY) || (curY <= prevY && curY <= nextY)) { + control1Angle = control2Angle = halfPI; + } else { + control1Angle = atan((curX - prevX) / abs(curY - prevY)); + if (prevY < curY) { + control1Angle = PI - control1Angle; + } + control2Angle = atan((nextX - curX) / abs(curY - nextY)); + if (nextY < curY) { + control2Angle = PI - control2Angle; + } + } + + // Adjust the calculated angles so they point away from each other on the same line + alpha = halfPI - ((control1Angle + control2Angle) % (PI * 2)) / 2; + if (alpha > halfPI) { + alpha -= PI; + } + control1Angle += alpha; + control2Angle += alpha; + + // Find the control anchor points from the angles and length + control1X = curX - control1Length * sin(control1Angle); + control1Y = curY + control1Length * cos(control1Angle); + control2X = curX + control2Length * sin(control2Angle); + control2Y = curY + control2Length * cos(control2Angle); + + // One last adjustment, make sure that no control anchor point extends vertically past + // its target prev/next point, as that results in curves dipping above or below and + // bending back strangely. If we find this happening we keep the control angle but + // reduce the length of the control line so it stays within bounds. + if ((curY > prevY && control1Y < prevY) || (curY < prevY && control1Y > prevY)) { + control1X += abs(prevY - control1Y) * (control1X - curX) / (control1Y - curY); + control1Y = prevY; + } + if ((curY > nextY && control2Y < nextY) || (curY < nextY && control2Y > nextY)) { + control2X -= abs(nextY - control2Y) * (control2X - curX) / (control2Y - curY); + control2Y = nextY; + } + + return { + x1: control1X, + y1: control1Y, + x2: control2X, + y2: control2Y + }; + }, + + /* Smoothing function for a path. Converts a path into cubic beziers. Value defines the divider of the distance between points. + * Defaults to a value of 4. + */ + smooth: function (originalPath, value) { + var path = this.path2curve(originalPath), + newp = [path[0]], + x = path[0][1], + y = path[0][2], + j, + points, + i = 1, + ii = path.length, + beg = 1, + mx = x, + my = y, + cx = 0, + cy = 0, + pathi, + pathil, + pathim, + pathiml, + pathip, + pathipl, + begl; + + for (; i < ii; i++) { + pathi = path[i]; + pathil = pathi.length; + pathim = path[i - 1]; + pathiml = pathim.length; + pathip = path[i + 1]; + pathipl = pathip && pathip.length; + if (pathi[0] == "M") { + mx = pathi[1]; + my = pathi[2]; + j = i + 1; + while (path[j][0] != "C") { + j++; + } + cx = path[j][5]; + cy = path[j][6]; + newp.push(["M", mx, my]); + beg = newp.length; + x = mx; + y = my; + continue; + } + if (pathi[pathil - 2] == mx && pathi[pathil - 1] == my && (!pathip || pathip[0] == "M")) { + begl = newp[beg].length; + points = this.getAnchors(pathim[pathiml - 2], pathim[pathiml - 1], mx, my, newp[beg][begl - 2], newp[beg][begl - 1], value); + newp[beg][1] = points.x2; + newp[beg][2] = points.y2; + } + else if (!pathip || pathip[0] == "M") { + points = { + x1: pathi[pathil - 2], + y1: pathi[pathil - 1] + }; + } else { + points = this.getAnchors(pathim[pathiml - 2], pathim[pathiml - 1], pathi[pathil - 2], pathi[pathil - 1], pathip[pathipl - 2], pathip[pathipl - 1], value); + } + newp.push(["C", x, y, points.x1, points.y1, pathi[pathil - 2], pathi[pathil - 1]]); + x = points.x2; + y = points.y2; + } + return newp; + }, + + findDotAtSegment: function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) { + var t1 = 1 - t; + return { + x: Math.pow(t1, 3) * p1x + Math.pow(t1, 2) * 3 * t * c1x + t1 * 3 * t * t * c2x + Math.pow(t, 3) * p2x, + y: Math.pow(t1, 3) * p1y + Math.pow(t1, 2) * 3 * t * c1y + t1 * 3 * t * t * c2y + Math.pow(t, 3) * p2y + }; + }, + + snapEnds: function (from, to, stepsMax, prettyNumbers) { + if (Ext.isDate(from)) { + return this.snapEndsByDate(from, to, stepsMax); + } + var step = (to - from) / stepsMax, + level = Math.floor(Math.log(step) / Math.LN10) + 1, + m = Math.pow(10, level), + cur, + modulo = Math.round((step % m) * Math.pow(10, 2 - level)), + interval = [[0, 15], [20, 4], [30, 2], [40, 4], [50, 9], [60, 4], [70, 2], [80, 4], [100, 15]], + stepCount = 0, + value, + weight, + i, + topValue, + topWeight = 1e9, + ln = interval.length; + cur = from = Math.floor(from / m) * m; + + if(prettyNumbers){ + for (i = 0; i < ln; i++) { + value = interval[i][0]; + weight = (value - modulo) < 0 ? 1e6 : (value - modulo) / interval[i][1]; + if (weight < topWeight) { + topValue = value; + topWeight = weight; + } + } + step = Math.floor(step * Math.pow(10, -level)) * Math.pow(10, level) + topValue * Math.pow(10, level - 2); + while (cur < to) { + cur += step; + stepCount++; + } + to = +cur.toFixed(10); + }else{ + stepCount = stepsMax; + } + + return { + from: from, + to: to, + power: level, + step: step, + steps: stepCount + }; + }, + + /** + * snapEndsByDate is a utility method to deduce an appropriate tick configuration for the data set of given + * feature. Refer to {@link #snapEnds}. + * + * @param {Date} from The minimum value in the data + * @param {Date} to The maximum value in the data + * @param {Number} stepsMax The maximum number of ticks + * @param {Boolean} lockEnds If true, the 'from' and 'to' parameters will be used as fixed end values + * and will not be adjusted + * @return {Object} The calculated step and ends info; properties are: + * - from: The result start value, which may be lower than the original start value + * - to: The result end value, which may be higher than the original end value + * - step: The value size of each step + * - steps: The number of steps. NOTE: the steps may not divide the from/to range perfectly evenly; + * there may be a smaller distance between the last step and the end value than between prior + * steps, particularly when the `endsLocked` param is true. Therefore it is best to not use + * the `steps` result when finding the axis tick points, instead use the `step`, `to`, and + * `from` to find the correct point for each tick. + */ + snapEndsByDate: function (from, to, stepsMax, lockEnds) { + var selectedStep = false, + scales = [ + [Ext.Date.MILLI, [1, 2, 3, 5, 10, 20, 30, 50, 100, 200, 300, 500]], + [Ext.Date.SECOND, [1, 2, 3, 5, 10, 15, 30]], + [Ext.Date.MINUTE, [1, 2, 3, 5, 10, 20, 30]], + [Ext.Date.HOUR, [1, 2, 3, 4, 6, 12]], + [Ext.Date.DAY, [1, 2, 3, 7, 14]], + [Ext.Date.MONTH, [1, 2, 3, 4, 6]] + ], + sLen = scales.length, + stop = false, + scale, j, yearDiff, s; + + // Find the most desirable scale + for (s = 0; s < sLen; s++) { + scale = scales[s]; + if (!stop) { + for (j = 0; j < scale[1].length; j++) { + if (to < Ext.Date.add(from, scale[0], scale[1][j] * stepsMax)) { + selectedStep = [scale[0], scale[1][j]]; + stop = true; + break; + } + } + } + } + + if (!selectedStep) { + yearDiff = this.snapEnds(from.getFullYear(), to.getFullYear() + 1, stepsMax, lockEnds); + selectedStep = [Date.YEAR, Math.round(yearDiff.step)]; + } + return this.snapEndsByDateAndStep(from, to, selectedStep, lockEnds); + }, + + + /** + * snapEndsByDateAndStep is a utility method to deduce an appropriate tick configuration for the data set of given + * feature and specific step size. + * @param {Date} from The minimum value in the data + * @param {Date} to The maximum value in the data + * @param {Array} step An array with two components: The first is the unit of the step (day, month, year, etc). The second one is the number of units for the step (1, 2, etc.). + * @param {Boolean} lockEnds If true, the 'from' and 'to' parameters will be used as fixed end values + * and will not be adjusted + */ + snapEndsByDateAndStep: function(from, to, step, lockEnds) { + var fromStat = [from.getFullYear(), from.getMonth(), from.getDate(), + from.getHours(), from.getMinutes(), from.getSeconds(), from.getMilliseconds()], + steps = 0, testFrom, testTo; + if (lockEnds) { + testFrom = from; + } else { + switch (step[0]) { + case Ext.Date.MILLI: + testFrom = new Date(fromStat[0], fromStat[1], fromStat[2], fromStat[3], + fromStat[4], fromStat[5], Math.floor(fromStat[6] / step[1]) * step[1]); + break; + case Ext.Date.SECOND: + testFrom = new Date(fromStat[0], fromStat[1], fromStat[2], fromStat[3], + fromStat[4], Math.floor(fromStat[5] / step[1]) * step[1], 0); + break; + case Ext.Date.MINUTE: + testFrom = new Date(fromStat[0], fromStat[1], fromStat[2], fromStat[3], + Math.floor(fromStat[4] / step[1]) * step[1], 0, 0); + break; + case Ext.Date.HOUR: + testFrom = new Date(fromStat[0], fromStat[1], fromStat[2], + Math.floor(fromStat[3] / step[1]) * step[1], 0, 0, 0); + break; + case Ext.Date.DAY: + testFrom = new Date(fromStat[0], fromStat[1], + Math.floor(fromStat[2] - 1 / step[1]) * step[1] + 1, 0, 0, 0, 0); + break; + case Ext.Date.MONTH: + testFrom = new Date(fromStat[0], Math.floor(fromStat[1] / step[1]) * step[1], 1, 0, 0, 0, 0); + break; + default: // Ext.Date.YEAR + testFrom = new Date(Math.floor(fromStat[0] / step[1]) * step[1], 0, 1, 0, 0, 0, 0); + break; + } + } + + testTo = testFrom; + // TODO(zhangbei) : We can do it better somehow... + while (testTo < to) { + testTo = Ext.Date.add(testTo, step[0], step[1]); + steps++; + } + + if (lockEnds) { + testTo = to; + } + return { + from : +testFrom, + to : +testTo, + step : (testTo - testFrom) / steps, + steps : steps + }; + }, + + sorter: function (a, b) { + return a.offset - b.offset; + }, + + rad: function(degrees) { + return degrees % 360 * Math.PI / 180; + }, + + degrees: function(radian) { + return radian * 180 / Math.PI % 360; + }, + + withinBox: function(x, y, bbox) { + bbox = bbox || {}; + return (x >= bbox.x && x <= (bbox.x + bbox.width) && y >= bbox.y && y <= (bbox.y + bbox.height)); + }, + + parseGradient: function(gradient) { + var me = this, + type = gradient.type || 'linear', + angle = gradient.angle || 0, + radian = me.radian, + stops = gradient.stops, + stopsArr = [], + stop, + vector, + max, + stopObj; + + if (type == 'linear') { + vector = [0, 0, Math.cos(angle * radian), Math.sin(angle * radian)]; + max = 1 / (Math.max(Math.abs(vector[2]), Math.abs(vector[3])) || 1); + vector[2] *= max; + vector[3] *= max; + if (vector[2] < 0) { + vector[0] = -vector[2]; + vector[2] = 0; + } + if (vector[3] < 0) { + vector[1] = -vector[3]; + vector[3] = 0; + } + } + + for (stop in stops) { + if (stops.hasOwnProperty(stop) && me.stopsRE.test(stop)) { + stopObj = { + offset: parseInt(stop, 10), + color: Ext.draw.Color.toHex(stops[stop].color) || '#ffffff', + opacity: stops[stop].opacity || 1 + }; + stopsArr.push(stopObj); + } + } + // Sort by pct property + Ext.Array.sort(stopsArr, me.sorter); + if (type == 'linear') { + return { + id: gradient.id, + type: type, + vector: vector, + stops: stopsArr + }; + } + else { + return { + id: gradient.id, + type: type, + centerX: gradient.centerX, + centerY: gradient.centerY, + focalX: gradient.focalX, + focalY: gradient.focalY, + radius: gradient.radius, + vector: vector, + stops: stopsArr + }; + } + } +}); + +/** + * @private + */ +Ext.define('Ext.draw.Matrix', { + + /* Begin Definitions */ + + requires: ['Ext.draw.Draw'], + + /* End Definitions */ + + constructor: function(a, b, c, d, e, f) { + if (a != null) { + this.matrix = [[a, c, e], [b, d, f], [0, 0, 1]]; + } + else { + this.matrix = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]; + } + }, + + add: function(a, b, c, d, e, f) { + var me = this, + out = [[], [], []], + matrix = [[a, c, e], [b, d, f], [0, 0, 1]], + x, + y, + z, + res; + + for (x = 0; x < 3; x++) { + for (y = 0; y < 3; y++) { + res = 0; + for (z = 0; z < 3; z++) { + res += me.matrix[x][z] * matrix[z][y]; + } + out[x][y] = res; + } + } + me.matrix = out; + }, + + prepend: function(a, b, c, d, e, f) { + var me = this, + out = [[], [], []], + matrix = [[a, c, e], [b, d, f], [0, 0, 1]], + x, + y, + z, + res; + + for (x = 0; x < 3; x++) { + for (y = 0; y < 3; y++) { + res = 0; + for (z = 0; z < 3; z++) { + res += matrix[x][z] * me.matrix[z][y]; + } + out[x][y] = res; + } + } + me.matrix = out; + }, + + invert: function() { + var matrix = this.matrix, + a = matrix[0][0], + b = matrix[1][0], + c = matrix[0][1], + d = matrix[1][1], + e = matrix[0][2], + f = matrix[1][2], + x = a * d - b * c; + return new Ext.draw.Matrix(d / x, -b / x, -c / x, a / x, (c * f - d * e) / x, (b * e - a * f) / x); + }, + + clone: function() { + var matrix = this.matrix, + a = matrix[0][0], + b = matrix[1][0], + c = matrix[0][1], + d = matrix[1][1], + e = matrix[0][2], + f = matrix[1][2]; + return new Ext.draw.Matrix(a, b, c, d, e, f); + }, + + translate: function(x, y) { + this.prepend(1, 0, 0, 1, x, y); + }, + + scale: function(x, y, cx, cy) { + var me = this; + if (y == null) { + y = x; + } + me.add(1, 0, 0, 1, cx, cy); + me.add(x, 0, 0, y, 0, 0); + me.add(1, 0, 0, 1, -cx, -cy); + }, + + rotate: function(a, x, y) { + a = Ext.draw.Draw.rad(a); + var me = this, + cos = +Math.cos(a).toFixed(9), + sin = +Math.sin(a).toFixed(9); + me.add(cos, sin, -sin, cos, x, y); + me.add(1, 0, 0, 1, -x, -y); + }, + + x: function(x, y) { + var matrix = this.matrix; + return x * matrix[0][0] + y * matrix[0][1] + matrix[0][2]; + }, + + y: function(x, y) { + var matrix = this.matrix; + return x * matrix[1][0] + y * matrix[1][1] + matrix[1][2]; + }, + + get: function(i, j) { + return + this.matrix[i][j].toFixed(4); + }, + + toString: function() { + var me = this; + return [me.get(0, 0), me.get(0, 1), me.get(1, 0), me.get(1, 1), 0, 0].join(); + }, + + toSvg: function() { + var me = this; + return "matrix(" + [me.get(0, 0), me.get(1, 0), me.get(0, 1), me.get(1, 1), me.get(0, 2), me.get(1, 2)].join() + ")"; + }, + + toFilter: function(dx, dy) { + var me = this; + dx = dx || 0; + dy = dy || 0; + return "progid:DXImageTransform.Microsoft.Matrix(sizingMethod='auto expand', filterType='bilinear', M11=" + me.get(0, 0) + + ", M12=" + me.get(0, 1) + ", M21=" + me.get(1, 0) + ", M22=" + me.get(1, 1) + + ", Dx=" + (me.get(0, 2) + dx) + ", Dy=" + (me.get(1, 2) + dy) + ")"; + }, + + offset: function() { + var matrix = this.matrix; + return [(matrix[0][2] || 0).toFixed(4), (matrix[1][2] || 0).toFixed(4)]; + }, + + // Split matrix into Translate Scale, Shear, and Rotate + split: function () { + function norm(a) { + return a[0] * a[0] + a[1] * a[1]; + } + function normalize(a) { + var mag = Math.sqrt(norm(a)); + a[0] /= mag; + a[1] /= mag; + } + var matrix = this.matrix, + out = { + translateX: matrix[0][2], + translateY: matrix[1][2] + }, + row; + + // scale and shear + row = [[matrix[0][0], matrix[0][1]], [matrix[1][1], matrix[1][1]]]; + out.scaleX = Math.sqrt(norm(row[0])); + normalize(row[0]); + + out.shear = row[0][0] * row[1][0] + row[0][1] * row[1][1]; + row[1] = [row[1][0] - row[0][0] * out.shear, row[1][1] - row[0][1] * out.shear]; + + out.scaleY = Math.sqrt(norm(row[1])); + normalize(row[1]); + out.shear /= out.scaleY; + + // rotation + out.rotate = Math.asin(-row[0][1]); + + out.isSimple = !+out.shear.toFixed(9) && (out.scaleX.toFixed(9) == out.scaleY.toFixed(9) || !out.rotate); + + return out; + } +}); + +/** + * @private + */ +Ext.define('Ext.draw.engine.ImageExporter', { + singleton: true, + + statics: (function(){ + var exportTypes = { + "image/png": 1, + "image/jpeg": 1 + }, + init = function(config){ + + if(config.hasOwnProperty('width')){ + width = config['width']; + } + if(config.hasOwnProperty('height')){ + height = config['height']; + } + if(config.hasOwnProperty('type') && exportTypes[config['type']]){ + type = config['type']; + }else{ + return false; + } + + // if all the elements were set up before + // we don't need to reset their values and reappend them to the form + if(formEl && svgEl && typeEl && widthEl && heightEl){ + return true; + } + + formEl = formEl || Ext.get(document.createElement('form')); + formEl.set({ + action: 'http://svg.sencha.io', + method: 'POST' + }); + + svgEl = svgEl || Ext.get(document.createElement('input')); + svgEl.set({ + name: 'svg', + type: 'hidden' + }); + + typeEl = typeEl || Ext.get(document.createElement('input')); + typeEl.set({ + name: 'type', + type: 'hidden' + }); + widthEl = widthEl || Ext.get(document.createElement('input')); + widthEl.set({ + name: 'width', + type: 'hidden' + }); + heightEl = heightEl || Ext.get(document.createElement('input')); + heightEl.set({ + name: 'height', + type: 'hidden' + }); + + formEl.appendChild(svgEl); + formEl.appendChild(typeEl); + formEl.appendChild(widthEl); + formEl.appendChild(heightEl); + + Ext.getBody().appendChild(formEl); + + return true; + }, + process = function(surface){ + + var svgString = Ext.draw.engine.SvgExporter.self.generate({}, surface); + + widthEl.set({ + value: width || surface.width + }); + + heightEl.set({ + value: height || surface.height + }); + + if(type){ + typeEl.set({ + value: type + }); + } + svgEl.set({ + value: svgString + }); + + formEl.dom.submit(); + + }, + formEl, typeEl, svgEl, widthEl, heightEl, type, width, height; + + return { + generate: function(config, surface){ + if(init(config)){ + process(surface); + }else{ + return false; + } + } + }; + }()) + +}); + +/** + * @private + */ +Ext.define('Ext.draw.engine.SvgExporter', { + singleton: true, + + statics: (function(){ + var surface, len, width, + height, + init = function(s){ + surface = s; + len = surface.length; + width = surface.width; + height = surface.height; + }, + spriteProcessor = { + path: function(sprite){ + + var attr = sprite.attr, + path = attr.path, + pathString = '', + props, p, pLen; + + if(Ext.isArray(path[0])){ + pLen = path.length; + for (p = 0; p < pLen; p++) { + pathString += path[p].join(' '); + } + }else if(Ext.isArray(path)){ + pathString = path.join(' '); + }else{ + pathString = path.replace(/,/g,' '); + } + + props = toPropertyString({ + d: pathString, + fill: attr.fill || 'none', + stroke: attr.stroke, + 'fill-opacity': attr.opacity, + 'stroke-width': attr['stroke-width'], + 'stroke-opacity': attr['stroke-opacity'], + "z-index": attr.zIndex, + transform: sprite.matrix.toSvg() + }); + + return ''; + }, + text: function(sprite){ + + // TODO + // implement multi line support (@see Svg.js tuneText) + + var attr = sprite.attr, + fontRegex = /(-?\d*\.?\d*){1}(em|ex|px|in|cm|mm|pt|pc|%)\s('*.*'*)/, + match = fontRegex.exec(attr.font), + size = (match && match[1]) || "12", + // default font family is Arial + family = (match && match[3]) || 'Arial', + text = attr.text, + factor = (Ext.isFF3_0 || Ext.isFF3_5) ? 2 : 4, + tspanString = '', + props; + + sprite.getBBox(); + tspanString += ''; + tspanString += Ext.htmlEncode(text) + ''; + + + props = toPropertyString({ + x: attr.x, + y: attr.y, + 'font-size': size, + 'font-family': family, + 'font-weight': attr['font-weight'], + 'text-anchor': attr['text-anchor'], + // if no fill property is set it will be black + fill: attr.fill || '#000', + 'fill-opacity': attr.opacity, + transform: sprite.matrix.toSvg() + }); + + + + return '' + tspanString + ''; + }, + rect: function(sprite){ + + var attr = sprite.attr, + props = toPropertyString({ + x: attr.x, + y: attr.y, + rx: attr.rx, + ry: attr.ry, + width: attr.width, + height: attr.height, + fill: attr.fill || 'none', + 'fill-opacity': attr.opacity, + stroke: attr.stroke, + 'stroke-opacity': attr['stroke-opacity'], + 'stroke-width':attr['stroke-width'], + transform: sprite.matrix && sprite.matrix.toSvg() + }); + + return ''; + }, + circle: function(sprite){ + + var attr = sprite.attr, + props = toPropertyString({ + cx: attr.x, + cy: attr.y, + r: attr.radius, + fill: attr.translation.fill || attr.fill || 'none', + 'fill-opacity': attr.opacity, + stroke: attr.stroke, + 'stroke-opacity': attr['stroke-opacity'], + 'stroke-width':attr['stroke-width'], + transform: sprite.matrix.toSvg() + }); + + return ''; + }, + image: function(sprite){ + + var attr = sprite.attr, + props = toPropertyString({ + x: attr.x - (attr.width/2 >> 0), + y: attr.y - (attr.height/2 >> 0), + width: attr.width, + height: attr.height, + 'xlink:href': attr.src, + transform: sprite.matrix.toSvg() + }); + + return ''; + } + }, + svgHeader = function(){ + var svg = ''; + svg += ''; + return svg; + }, + svgContent = function(){ + var svg = '', + defs = '', item, itemsLen, items, gradient, + getSvgString, colorstops, stop, + coll, keys, colls, k, kLen, key, collI, i, j, stopsLen, sortedItems, za, zb; + + items = surface.items.items; + itemsLen = items.length; + + + getSvgString = function(node){ + + var childs = node.childNodes, + childLength = childs.length, + i = 0, + attrLength, + j, + svgString = '', child, attr, tagName, attrItem; + + for(; i < childLength; i++){ + child = childs[i]; + attr = child.attributes; + tagName = child.tagName; + + svgString += '<' +tagName; + + for(j = 0, attrLength = attr.length; j < attrLength; j++){ + attrItem = attr.item(j); + svgString += ' '+attrItem.name+'="'+attrItem.value+'"'; + } + + svgString += '>'; + + if(child.childNodes.length > 0){ + svgString += getSvgString(child); + } + + svgString += ''; + + } + return svgString; + }; + + + if(surface.getDefs){ + defs = getSvgString(surface.getDefs()); + }else{ + // IE + coll = surface.gradientsColl; + if (coll) { + keys = coll.keys; + colls = coll.items; + k = 0; + kLen = keys.length; + } + + for (; k < kLen; k++) { + key = keys[k]; + collI = colls[k]; + + gradient = surface.gradientsColl.getByKey(key); + defs += ''; + + var color = gradient.colors.replace(/rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/g, 'rgb($1|$2|$3)'); + color = color.replace(/rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,([\d\.]+)\)/g, 'rgba($1|$2|$3|$4)') + colorstops = color.split(','); + for(i=0, stopsLen = colorstops.length; i < stopsLen; i++){ + stop = colorstops[i].split(' '); + color = Ext.draw.Color.fromString(stop[1].replace(/\|/g,',')); + defs += ''; + } + defs += ''; + } + } + + svg += '' + defs + ''; + + // thats the background rectangle + svg += spriteProcessor.rect({ + attr: { + width: '100%', + height: '100%', + fill: '#fff', + stroke: 'none', + opacity: '0' + } + }); + + // Sort the items (stable sort guaranteed) + sortedItems = new Array(itemsLen); + for(i = 0; i < itemsLen; i++){ + sortedItems[i] = i; + } + sortedItems.sort(function (a, b) { + za = items[a].attr.zIndex || 0; + zb = items[b].attr.zIndex || 0; + if (za == zb) { + return a - b; + } + return za - zb; + }); + + for(i = 0; i < itemsLen; i++){ + item = items[sortedItems[i]]; + if(!item.attr.hidden){ + svg += spriteProcessor[item.type](item); + } + } + + svg += ''; + + return svg; + }, + toPropertyString = function(obj){ + var propString = '', + key; + + for(key in obj){ + + if(obj.hasOwnProperty(key) && obj[key] != null){ + propString += key +'="'+ obj[key]+'" '; + } + + } + + return propString; + }; + + return { + generate: function(config, surface){ + init(surface); + return svgHeader() + svgContent(); + } + }; + }()) + +}); +/** + * @private + */ +Ext.define('Ext.fx.CubicBezier', { + + /* Begin Definitions */ + + singleton: true, + + /* End Definitions */ + + cubicBezierAtTime: function(t, p1x, p1y, p2x, p2y, duration) { + var cx = 3 * p1x, + bx = 3 * (p2x - p1x) - cx, + ax = 1 - cx - bx, + cy = 3 * p1y, + by = 3 * (p2y - p1y) - cy, + ay = 1 - cy - by; + function sampleCurveX(t) { + return ((ax * t + bx) * t + cx) * t; + } + function solve(x, epsilon) { + var t = solveCurveX(x, epsilon); + return ((ay * t + by) * t + cy) * t; + } + function solveCurveX(x, epsilon) { + var t0, t1, t2, x2, d2, i; + for (t2 = x, i = 0; i < 8; i++) { + x2 = sampleCurveX(t2) - x; + if (Math.abs(x2) < epsilon) { + return t2; + } + d2 = (3 * ax * t2 + 2 * bx) * t2 + cx; + if (Math.abs(d2) < 1e-6) { + break; + } + t2 = t2 - x2 / d2; + } + t0 = 0; + t1 = 1; + t2 = x; + if (t2 < t0) { + return t0; + } + if (t2 > t1) { + return t1; + } + while (t0 < t1) { + x2 = sampleCurveX(t2); + if (Math.abs(x2 - x) < epsilon) { + return t2; + } + if (x > x2) { + t0 = t2; + } else { + t1 = t2; + } + t2 = (t1 - t0) / 2 + t0; + } + return t2; + } + return solve(t, 1 / (200 * duration)); + }, + + cubicBezier: function(x1, y1, x2, y2) { + var fn = function(pos) { + return Ext.fx.CubicBezier.cubicBezierAtTime(pos, x1, y1, x2, y2, 1); + }; + fn.toCSS3 = function() { + return 'cubic-bezier(' + [x1, y1, x2, y2].join(',') + ')'; + }; + fn.reverse = function() { + return Ext.fx.CubicBezier.cubicBezier(1 - x2, 1 - y2, 1 - x1, 1 - y1); + }; + return fn; + } +}); +/** + * @private + */ +Ext.define('Ext.fx.PropertyHandler', { + + /* Begin Definitions */ + + requires: ['Ext.draw.Draw'], + + statics: { + defaultHandler: { + pixelDefaultsRE: /width|height|top$|bottom$|left$|right$/i, + unitRE: /^(-?\d*\.?\d*){1}(em|ex|px|in|cm|mm|pt|pc|%)*$/, + scrollRE: /^scroll/i, + + computeDelta: function(from, end, damper, initial, attr) { + damper = (typeof damper == 'number') ? damper : 1; + var unitRE = this.unitRE, + match = unitRE.exec(from), + start, units; + if (match) { + from = match[1]; + units = match[2]; + if (!this.scrollRE.test(attr) && !units && this.pixelDefaultsRE.test(attr)) { + units = 'px'; + } + } + from = +from || 0; + + match = unitRE.exec(end); + if (match) { + end = match[1]; + units = match[2] || units; + } + end = +end || 0; + start = (initial != null) ? initial : from; + return { + from: from, + delta: (end - start) * damper, + units: units + }; + }, + + get: function(from, end, damper, initialFrom, attr) { + var ln = from.length, + out = [], + i, initial, res, j, len; + for (i = 0; i < ln; i++) { + if (initialFrom) { + initial = initialFrom[i][1].from; + } + if (Ext.isArray(from[i][1]) && Ext.isArray(end)) { + res = []; + j = 0; + len = from[i][1].length; + for (; j < len; j++) { + res.push(this.computeDelta(from[i][1][j], end[j], damper, initial, attr)); + } + out.push([from[i][0], res]); + } + else { + out.push([from[i][0], this.computeDelta(from[i][1], end, damper, initial, attr)]); + } + } + return out; + }, + + set: function(values, easing) { + var ln = values.length, + out = [], + i, val, res, len, j; + for (i = 0; i < ln; i++) { + val = values[i][1]; + if (Ext.isArray(val)) { + res = []; + j = 0; + len = val.length; + for (; j < len; j++) { + res.push(val[j].from + val[j].delta * easing + (val[j].units || 0)); + } + out.push([values[i][0], res]); + } else { + out.push([values[i][0], val.from + val.delta * easing + (val.units || 0)]); + } + } + return out; + } + }, + stringHandler: { + computeDelta: function(from, end, damper, initial, attr) { + return { + from: from, + delta: end + }; + }, + + get: function(from, end, damper, initialFrom, attr) { + var ln = from.length, + out = [], + i, initial, res, j, len; + for (i = 0; i < ln; i++) { + out.push([from[i][0], this.computeDelta(from[i][1], end, damper, initial, attr)]); + } + return out; + }, + + set: function(values, easing) { + var ln = values.length, + out = [], + i, val, res, len, j; + for (i = 0; i < ln; i++) { + val = values[i][1]; + out.push([values[i][0], val.delta]); + } + return out; + } + }, + color: { + rgbRE: /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i, + hexRE: /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i, + hex3RE: /^#?([0-9A-F]{1})([0-9A-F]{1})([0-9A-F]{1})$/i, + + parseColor : function(color, damper) { + damper = (typeof damper == 'number') ? damper : 1; + var out = false, + reList = [this.hexRE, this.rgbRE, this.hex3RE], + length = reList.length, + match, base, re, i; + + for (i = 0; i < length; i++) { + re = reList[i]; + + base = (i % 2 === 0) ? 16 : 10; + match = re.exec(color); + if (match && match.length === 4) { + if (i === 2) { + match[1] += match[1]; + match[2] += match[2]; + match[3] += match[3]; + } + out = { + red: parseInt(match[1], base), + green: parseInt(match[2], base), + blue: parseInt(match[3], base) + }; + break; + } + } + + return out || color; + }, + + computeDelta: function(from, end, damper, initial) { + from = this.parseColor(from); + end = this.parseColor(end, damper); + var start = initial ? initial : from, + tfrom = typeof start, + tend = typeof end; + //Extra check for when the color string is not recognized. + if (tfrom == 'string' || tfrom == 'undefined' + || tend == 'string' || tend == 'undefined') { + return end || start; + } + return { + from: from, + delta: { + red: Math.round((end.red - start.red) * damper), + green: Math.round((end.green - start.green) * damper), + blue: Math.round((end.blue - start.blue) * damper) + } + }; + }, + + get: function(start, end, damper, initialFrom) { + var ln = start.length, + out = [], + i, initial; + for (i = 0; i < ln; i++) { + if (initialFrom) { + initial = initialFrom[i][1].from; + } + out.push([start[i][0], this.computeDelta(start[i][1], end, damper, initial)]); + } + return out; + }, + + set: function(values, easing) { + var ln = values.length, + out = [], + i, val, parsedString, from, delta; + for (i = 0; i < ln; i++) { + val = values[i][1]; + if (val) { + from = val.from; + delta = val.delta; + //multiple checks to reformat the color if it can't recognized by computeDelta. + val = (typeof val == 'object' && 'red' in val)? + 'rgb(' + val.red + ', ' + val.green + ', ' + val.blue + ')' : val; + val = (typeof val == 'object' && val.length)? val[0] : val; + if (typeof val == 'undefined') { + return []; + } + parsedString = typeof val == 'string'? val : + 'rgb(' + [ + (from.red + Math.round(delta.red * easing)) % 256, + (from.green + Math.round(delta.green * easing)) % 256, + (from.blue + Math.round(delta.blue * easing)) % 256 + ].join(',') + ')'; + out.push([ + values[i][0], + parsedString + ]); + } + } + return out; + } + }, + object: { + interpolate: function(prop, damper) { + damper = (typeof damper == 'number') ? damper : 1; + var out = {}, + p; + for(p in prop) { + out[p] = parseFloat(prop[p]) * damper; + } + return out; + }, + + computeDelta: function(from, end, damper, initial) { + from = this.interpolate(from); + end = this.interpolate(end, damper); + var start = initial ? initial : from, + delta = {}, + p; + + for(p in end) { + delta[p] = end[p] - start[p]; + } + return { + from: from, + delta: delta + }; + }, + + get: function(start, end, damper, initialFrom) { + var ln = start.length, + out = [], + i, initial; + for (i = 0; i < ln; i++) { + if (initialFrom) { + initial = initialFrom[i][1].from; + } + out.push([start[i][0], this.computeDelta(start[i][1], end, damper, initial)]); + } + return out; + }, + + set: function(values, easing) { + var ln = values.length, + out = [], + outObject = {}, + i, from, delta, val, p; + for (i = 0; i < ln; i++) { + val = values[i][1]; + from = val.from; + delta = val.delta; + for (p in from) { + outObject[p] = from[p] + delta[p] * easing; + } + out.push([ + values[i][0], + outObject + ]); + } + return out; + } + }, + + path: { + computeDelta: function(from, end, damper, initial) { + damper = (typeof damper == 'number') ? damper : 1; + var start; + from = +from || 0; + end = +end || 0; + start = (initial != null) ? initial : from; + return { + from: from, + delta: (end - start) * damper + }; + }, + + forcePath: function(path) { + if (!Ext.isArray(path) && !Ext.isArray(path[0])) { + path = Ext.draw.Draw.parsePathString(path); + } + return path; + }, + + get: function(start, end, damper, initialFrom) { + var endPath = this.forcePath(end), + out = [], + startLn = start.length, + startPathLn, pointsLn, i, deltaPath, initial, j, k, path, startPath; + for (i = 0; i < startLn; i++) { + startPath = this.forcePath(start[i][1]); + + deltaPath = Ext.draw.Draw.interpolatePaths(startPath, endPath); + startPath = deltaPath[0]; + endPath = deltaPath[1]; + + startPathLn = startPath.length; + path = []; + for (j = 0; j < startPathLn; j++) { + deltaPath = [startPath[j][0]]; + pointsLn = startPath[j].length; + for (k = 1; k < pointsLn; k++) { + initial = initialFrom && initialFrom[0][1][j][k].from; + deltaPath.push(this.computeDelta(startPath[j][k], endPath[j][k], damper, initial)); + } + path.push(deltaPath); + } + out.push([start[i][0], path]); + } + return out; + }, + + set: function(values, easing) { + var ln = values.length, + out = [], + i, j, k, newPath, calcPath, deltaPath, deltaPathLn, pointsLn; + for (i = 0; i < ln; i++) { + deltaPath = values[i][1]; + newPath = []; + deltaPathLn = deltaPath.length; + for (j = 0; j < deltaPathLn; j++) { + calcPath = [deltaPath[j][0]]; + pointsLn = deltaPath[j].length; + for (k = 1; k < pointsLn; k++) { + calcPath.push(deltaPath[j][k].from + deltaPath[j][k].delta * easing); + } + newPath.push(calcPath.join(',')); + } + out.push([values[i][0], newPath.join(',')]); + } + return out; + } + } + /* End Definitions */ + } +}, function() { + //set color properties to color interpolator + var props = [ + 'outlineColor', + 'backgroundColor', + 'borderColor', + 'borderTopColor', + 'borderRightColor', + 'borderBottomColor', + 'borderLeftColor', + 'fill', + 'stroke' + ], + length = props.length, + i = 0, + prop; + + for (; i 0 || height > 0)) { // no need to subtract from 0 + // The width and height values assume the border-box box model, + // so we must remove the padding & border to calculate the content-box. + if (!(me.borderInfo && me.paddingInfo)) { + throw Error("Needed to have gotten the borderInfo and paddingInfo when the width or height was setProp'd"); + } + if(!me.frameBodyContext) { + // Padding needs to be removed only if the element is not framed. + paddingWidth = me.paddingInfo.width; + paddingHeight = me.paddingInfo.height; + } + if (width) { + width = max(parseInt(width, 10) - (me.borderInfo.width + paddingWidth), 0); + styles.width = width + 'px'; + ++styleCount; + } + if (height) { + height = max(parseInt(height, 10) - (me.borderInfo.height + paddingHeight), 0); + styles.height = height + 'px'; + ++styleCount; + } + } + + // we make only one call to setStyle to allow it to optimize itself: + if (styleCount) { + el.setStyle(styles); + } + } +}, function () { + + var px = { dom: true, parseInt: true, suffix: 'px' }, + isDom = { dom: true }, + faux = { dom: false }; + + // If a property exists in styleInfo, it participates in some way with the DOM. It may + // be virtualized (like 'x' and y') and be indirect, but still requires a flush cycle + // to reach the DOM. Properties (like 'contentWidth' and 'contentHeight') have no real + // presence in the DOM and hence have no flush intanglements. + // + // For simple styles, the object value on the right contains properties that help in + // decoding values read by getStyle and preparing values to pass to setStyle. + // + this.prototype.styleInfo = { + childrenDone: faux, + componentChildrenDone: faux, + containerChildrenDone: faux, + containerLayoutDone: faux, + displayed: faux, + done: faux, + x: faux, + y: faux, + + left: px, + top: px, + right: px, + bottom: px, + width: px, + height: px, + + 'border-top-width': px, + 'border-right-width': px, + 'border-bottom-width': px, + 'border-left-width': px, + + 'margin-top': px, + 'margin-right': px, + 'margin-bottom': px, + 'margin-left': px, + + 'padding-top': px, + 'padding-right': px, + 'padding-bottom': px, + 'padding-left': px, + + 'line-height': isDom, + display: isDom + }; +}); + +/** + * This class is used as a mixin. + * + * This class is to be used to provide basic methods for binding/unbinding stores to other + * classes. In general it will not be used directly. + */ +Ext.define('Ext.util.Bindable', { + + /** + * Binds a store to this instance. + * @param {Ext.data.AbstractStore} store The store to bind (may be null to unbind the existing store). + * @param {Boolean} initial (Optional) true to not remove listeners + */ + bindStore: function(store, initial){ + var me = this, + oldStore = me.store; + + if (!initial && me.store) { + if (store !== oldStore && oldStore.autoDestroy) { + oldStore.destroyStore(); + } else { + me.unbindStoreListeners(oldStore); + } + me.onUnbindStore(oldStore, initial); + } + if (store) { + store = Ext.data.StoreManager.lookup(store); + me.bindStoreListeners(store); + me.onBindStore(store, initial); + } + me.store = store || null; + return me; + }, + + /** + * Gets the current store instance. + * @return {Ext.data.AbstractStore} The store, null if one does not exist. + */ + getStore: function(){ + return this.store; + }, + + /** + * Unbinds listeners from this component to the store. By default it will remove + * anything bound by the bindStoreListeners method, however it can be overridden + * in a subclass to provide any more complicated handling. + * @protected + * @param {Ext.data.AbstractStore} store The store to unbind from + */ + unbindStoreListeners: function(store) { + // Can be overridden in the subclass for more complex removal + var listeners = this.storeListeners; + if (listeners) { + store.un(listeners); + } + }, + + /** + * Binds listeners for this component to the store. By default it will add + * anything bound by the getStoreListeners method, however it can be overridden + * in a subclass to provide any more complicated handling. + * @protected + * @param {Ext.data.AbstractStore} store The store to bind to + */ + bindStoreListeners: function(store) { + // Can be overridden in the subclass for more complex binding + var me = this, + listeners = Ext.apply({}, me.getStoreListeners()); + + if (!listeners.scope) { + listeners.scope = me; + } + me.storeListeners = listeners; + store.on(listeners); + }, + + /** + * Gets the listeners to bind to a new store. + * @protected + * @return {Object} The listeners to be bound to the store in object literal form. The scope + * may be omitted, it is assumed to be the current instance. + */ + getStoreListeners: Ext.emptyFn, + + /** + * Template method, it is called when an existing store is unbound + * from the current instance. + * @protected + * @param {Ext.data.AbstractStore} store The store being unbound + * @param {Boolean} initial True if this store is being bound as initialization of the instance. + */ + onUnbindStore: Ext.emptyFn, + + /** + * Template method, it is called when a new store is bound + * to the current instance. + * @protected + * @param {Ext.data.AbstractStore} store The store being bound + * @param {Boolean} initial True if this store is being bound as initialization of the instance. + */ + onBindStore: Ext.emptyFn +}); + +/** + * This mixin enables classes to declare relationships to child elements and provides the + * mechanics for acquiring the {@link Ext.Element elements} and storing them on an object + * instance as properties. + * + * This class is used by {@link Ext.Component components} and {@link Ext.layout.container.Container container layouts} to + * manage their child elements. + * + * A typical component that uses these features might look something like this: + * + * Ext.define('Ext.ux.SomeComponent', { + * extend: 'Ext.Component', + * + * childEls: [ + * 'bodyEl' + * ], + * + * renderTpl: [ + * '<div id="{id}-bodyEl"></div>' + * ], + * + * // ... + * }); + * + * The `childEls` array lists one or more relationships to child elements managed by the + * component. The items in this array can be either of the following types: + * + * - String: the id suffix and property name in one. For example, "bodyEl" in the above + * example means a "bodyEl" property will be added to the instance with the result of + * {@link Ext#get} given "componentId-bodyEl" where "componentId" is the component instance's + * id. + * - Object: with a `name` property that names the instance property for the element, and + * one of the following additional properties: + * - `id`: The full id of the child element. + * - `itemId`: The suffix part of the id to which "componentId-" is prepended. + * - `select`: A selector that will be passed to {@link Ext#select}. + * - `selectNode`: A selector that will be passed to {@link Ext.DomQuery#selectNode}. + * + * The example above could have used this instead to achieve the same result: + * + * childEls: [ + * { name: 'bodyEl', itemId: 'bodyEl' } + * ] + * + * When using `select`, the property will be an instance of {@link Ext.CompositeElement}. In + * all other cases, the property will be an {@link Ext.Element} or `null` if not found. + * + * Care should be taken when using `select` or `selectNode` to find child elements. The + * following issues should be considered: + * + * - Performance: using selectors can be slower than id lookup by a factor 10x or more. + * - Over-selecting: selectors are applied after the DOM elements for all children have + * been rendered, so selectors can match elements from child components (including nested + * versions of the same component) accidentally. + * + * This above issues are most important when using `select` since it returns multiple + * elements. + * + * **IMPORTANT** + * Unlike a `renderTpl` where there is a single value for an instance, `childEls` are aggregated + * up the class hierarchy so that they are effectively inherited. In other words, if a + * class where to derive from `Ext.ux.SomeComponent` in the example above, it could also + * have a `childEls` property in the same way as `Ext.ux.SomeComponent`. + * + * Ext.define('Ext.ux.AnotherComponent', { + * extend: 'Ext.ux.SomeComponent', + * + * childEls: [ + * // 'bodyEl' is inherited + * 'innerEl' + * ], + * + * renderTpl: [ + * '<div id="{id}-bodyEl">' + * '<div id="{id}-innerEl"></div>' + * '</div>' + * ], + * + * // ... + * }); + * + * The `renderTpl` contains both child elements and unites them in the desired markup, but + * the `childEls` only contains the new child element. The {@link #applyChildEls} method + * takes care of looking up all `childEls` for an instance and considers `childEls` + * properties on all the super classes and mixins. + * + * @private + */ +Ext.define('Ext.util.ElementContainer', { + + childEls: [ + // empty - this solves a couple problems: + // 1. It ensures that all classes have a childEls (avoid null ptr) + // 2. It prevents mixins from smashing on their own childEls (these are gathered + // specifically) + ], + + constructor: function () { + var me = this, + childEls; + + // if we have configured childEls, we need to merge them with those from this + // class, its bases and the set of mixins... + if (me.hasOwnProperty('childEls')) { + childEls = me.childEls; + delete me.childEls; + + me.addChildEls.apply(me, childEls); + } + }, + + destroy: function () { + var me = this, + childEls = me.getChildEls(), + child, childName, i, k; + + for (i = childEls.length; i--; ) { + childName = childEls[i]; + if (typeof childName != 'string') { + childName = childName.name; + } + + child = me[childName]; + if (child) { + me[childName] = null; // better than delete since that changes the "shape" + child.remove(); + } + } + }, + + /** + * Adds each argument passed to this method to the {@link #childEls} array. + */ + addChildEls: function () { + var me = this, + args = arguments; + + if (me.hasOwnProperty('childEls')) { + me.childEls.push.apply(me.childEls, args); + } else { + me.childEls = me.getChildEls().concat(Array.prototype.slice.call(args)); + } + + me.prune(me.childEls, false); + }, + + /** + * Sets references to elements inside the component. + * @private + */ + applyChildEls: function(el, id) { + var me = this, + childEls = me.getChildEls(), + baseId, childName, i, selector, value; + + baseId = (id || me.id) + '-'; + for (i = childEls.length; i--; ) { + childName = childEls[i]; + + if (typeof childName == 'string') { + // We don't use Ext.get because that is 3x (or more) slower on IE6-8. Since + // we know the el's are children of our el we use getById instead: + value = el.getById(baseId + childName); + } else { + if ((selector = childName.select)) { + value = Ext.select(selector, true, el.dom); // a CompositeElement + } else if ((selector = childName.selectNode)) { + value = Ext.get(Ext.DomQuery.selectNode(selector, el.dom)); + } else { + // see above re:getById... + value = el.getById(childName.id || (baseId + childName.itemId)); + } + + childName = childName.name; + } + + me[childName] = value; + } + }, + + getChildEls: function () { + var me = this, + self; + + // If an instance has its own childEls, that is the complete set: + if (me.hasOwnProperty('childEls')) { + return me.childEls; + } + + // Typically, however, the childEls is a class-level concept, so check to see if + // we have cached the complete set on the class: + self = me.self; + return self.$childEls || me.getClassChildEls(self); + }, + + getClassChildEls: function (cls) { + var me = this, + result = cls.$childEls, + childEls, i, length, forked, mixin, mixins, name, parts, proto, supr, superMixins; + + if (!result) { + // We put the various childEls arrays into parts in the order of superclass, + // new mixins and finally from cls. These parts can be null or undefined and + // we will skip them later. + + supr = cls.superclass; + if (supr) { + supr = supr.self; + parts = [supr.$childEls || me.getClassChildEls(supr)]; // super+mixins + superMixins = supr.prototype.mixins || {}; + } else { + parts = []; + superMixins = {}; + } + + proto = cls.prototype; + mixins = proto.mixins; // since we are a mixin, there will be at least us + for (name in mixins) { + if (mixins.hasOwnProperty(name) && !superMixins.hasOwnProperty(name)) { + mixin = mixins[name].self; + parts.push(mixin.$childEls || me.getClassChildEls(mixin)); + } + } + + parts.push(proto.hasOwnProperty('childEls') && proto.childEls); + + for (i = 0, length = parts.length; i < length; ++i) { + childEls = parts[i]; + if (childEls && childEls.length) { + if (!result) { + result = childEls; + } else { + if (!forked) { + forked = true; + result = result.slice(0); + } + result.push.apply(result, childEls); + } + } + } + + cls.$childEls = result = (result ? me.prune(result, !forked) : []); + } + + return result; + }, + + prune: function (childEls, shared) { + var index = childEls.length, + map = {}, + name; + + while (index--) { + name = childEls[index]; + if (typeof name != 'string') { + name = name.name; + } + + if (!map[name]) { + map[name] = 1; + } else { + if (shared) { + shared = false; + childEls = childEls.slice(0); + } + Ext.Array.erase(childEls, index, 1); + } + } + + return childEls; + }, + + /** + * Removes items in the childEls array based on the return value of a supplied test + * function. The function is called with a entry in childEls and if the test function + * return true, that entry is removed. If false, that entry is kept. + * + * @param {Function} testFn The test function. + */ + removeChildEls: function (testFn) { + var me = this, + old = me.getChildEls(), + keepers = (me.childEls = []), + n, i, cel; + + for (i = 0, n = old.length; i < n; ++i) { + cel = old[i]; + if (!testFn(cel)) { + keepers.push(cel); + } + } + } +}); + +/** + * Represents a filter that can be applied to a {@link Ext.util.MixedCollection MixedCollection}. Can either simply + * filter on a property/value pair or pass in a filter function with custom logic. Filters are always used in the + * context of MixedCollections, though {@link Ext.data.Store Store}s frequently create them when filtering and searching + * on their records. Example usage: + * + * //set up a fictional MixedCollection containing a few people to filter on + * var allNames = new Ext.util.MixedCollection(); + * allNames.addAll([ + * {id: 1, name: 'Ed', age: 25}, + * {id: 2, name: 'Jamie', age: 37}, + * {id: 3, name: 'Abe', age: 32}, + * {id: 4, name: 'Aaron', age: 26}, + * {id: 5, name: 'David', age: 32} + * ]); + * + * var ageFilter = new Ext.util.Filter({ + * property: 'age', + * value : 32 + * }); + * + * var longNameFilter = new Ext.util.Filter({ + * filterFn: function(item) { + * return item.name.length > 4; + * } + * }); + * + * //a new MixedCollection with the 3 names longer than 4 characters + * var longNames = allNames.filter(longNameFilter); + * + * //a new MixedCollection with the 2 people of age 32: + * var youngFolk = allNames.filter(ageFilter); + * + */ +Ext.define('Ext.util.Filter', { + + /* Begin Definitions */ + + /* End Definitions */ + /** + * @cfg {String} property + * The property to filter on. Required unless a {@link #filterFn} is passed + */ + + /** + * @cfg {Function} filterFn + * A custom filter function which is passed each item in the {@link Ext.util.MixedCollection} in turn. Should return + * true to accept each item or false to reject it + */ + + /** + * @cfg {Boolean} anyMatch + * True to allow any match - no regex start/end line anchors will be added. + */ + anyMatch: false, + + /** + * @cfg {Boolean} exactMatch + * True to force exact match (^ and $ characters added to the regex). Ignored if anyMatch is true. + */ + exactMatch: false, + + /** + * @cfg {Boolean} caseSensitive + * True to make the regex case sensitive (adds 'i' switch to regex). + */ + caseSensitive: false, + + /** + * @cfg {String} root + * Optional root property. This is mostly useful when filtering a Store, in which case we set the root to 'data' to + * make the filter pull the {@link #property} out of the data object of each item + */ + + /** + * Creates new Filter. + * @param {Object} [config] Config object + */ + constructor: function(config) { + var me = this; + Ext.apply(me, config); + + //we're aliasing filter to filterFn mostly for API cleanliness reasons, despite the fact it dirties the code here. + //Ext.util.Sorter takes a sorterFn property but allows .sort to be called - we do the same here + me.filter = me.filter || me.filterFn; + + if (me.filter === undefined) { + if (me.property === undefined || me.value === undefined) { + // Commented this out temporarily because it stops us using string ids in models. TODO: Remove this once + // Model has been updated to allow string ids + + // Ext.Error.raise("A Filter requires either a property or a filterFn to be set"); + } else { + me.filter = me.createFilterFn(); + } + + me.filterFn = me.filter; + } + }, + + /** + * @private + * Creates a filter function for the configured property/value/anyMatch/caseSensitive options for this Filter + */ + createFilterFn: function() { + var me = this, + matcher = me.createValueMatcher(), + property = me.property; + + return function(item) { + var value = me.getRoot.call(me, item)[property]; + return matcher === null ? value === null : matcher.test(value); + }; + }, + + /** + * @private + * Returns the root property of the given item, based on the configured {@link #root} property + * @param {Object} item The item + * @return {Object} The root property of the object + */ + getRoot: function(item) { + var root = this.root; + return root === undefined ? item : item[root]; + }, + + /** + * @private + * Returns a regular expression based on the given value and matching options + */ + createValueMatcher : function() { + var me = this, + value = me.value, + anyMatch = me.anyMatch, + exactMatch = me.exactMatch, + caseSensitive = me.caseSensitive, + escapeRe = Ext.String.escapeRegex; + + if (value === null) { + return value; + } + + if (!value.exec) { // not a regex + value = String(value); + + if (anyMatch === true) { + value = escapeRe(value); + } else { + value = '^' + escapeRe(value); + if (exactMatch === true) { + value += '$'; + } + } + value = new RegExp(value, caseSensitive ? '' : 'i'); + } + + return value; + } +}); +/** + * General purpose inflector class that {@link #pluralize pluralizes}, {@link #singularize singularizes} and + * {@link #ordinalize ordinalizes} words. Sample usage: + * + * //turning singular words into plurals + * Ext.util.Inflector.pluralize('word'); //'words' + * Ext.util.Inflector.pluralize('person'); //'people' + * Ext.util.Inflector.pluralize('sheep'); //'sheep' + * + * //turning plurals into singulars + * Ext.util.Inflector.singularize('words'); //'word' + * Ext.util.Inflector.singularize('people'); //'person' + * Ext.util.Inflector.singularize('sheep'); //'sheep' + * + * //ordinalizing numbers + * Ext.util.Inflector.ordinalize(11); //"11th" + * Ext.util.Inflector.ordinalize(21); //"21th" + * Ext.util.Inflector.ordinalize(1043); //"1043rd" + * + * # Customization + * + * The Inflector comes with a default set of US English pluralization rules. These can be augmented with additional + * rules if the default rules do not meet your application's requirements, or swapped out entirely for other languages. + * Here is how we might add a rule that pluralizes "ox" to "oxen": + * + * Ext.util.Inflector.plural(/^(ox)$/i, "$1en"); + * + * Each rule consists of two items - a regular expression that matches one or more rules, and a replacement string. In + * this case, the regular expression will only match the string "ox", and will replace that match with "oxen". Here's + * how we could add the inverse rule: + * + * Ext.util.Inflector.singular(/^(ox)en$/i, "$1"); + * + * Note that the ox/oxen rules are present by default. + */ +Ext.define('Ext.util.Inflector', { + + /* Begin Definitions */ + + singleton: true, + + /* End Definitions */ + + /** + * @private + * The registered plural tuples. Each item in the array should contain two items - the first must be a regular + * expression that matchers the singular form of a word, the second must be a String that replaces the matched + * part of the regular expression. This is managed by the {@link #plural} method. + * @property {Array} plurals + */ + plurals: [ + [(/(quiz)$/i), "$1zes" ], + [(/^(ox)$/i), "$1en" ], + [(/([m|l])ouse$/i), "$1ice" ], + [(/(matr|vert|ind)ix|ex$/i), "$1ices" ], + [(/(x|ch|ss|sh)$/i), "$1es" ], + [(/([^aeiouy]|qu)y$/i), "$1ies" ], + [(/(hive)$/i), "$1s" ], + [(/(?:([^f])fe|([lr])f)$/i), "$1$2ves"], + [(/sis$/i), "ses" ], + [(/([ti])um$/i), "$1a" ], + [(/(buffal|tomat|potat)o$/i), "$1oes" ], + [(/(bu)s$/i), "$1ses" ], + [(/(alias|status|sex)$/i), "$1es" ], + [(/(octop|vir)us$/i), "$1i" ], + [(/(ax|test)is$/i), "$1es" ], + [(/^person$/), "people" ], + [(/^man$/), "men" ], + [(/^(child)$/), "$1ren" ], + [(/s$/i), "s" ], + [(/$/), "s" ] + ], + + /** + * @private + * The set of registered singular matchers. Each item in the array should contain two items - the first must be a + * regular expression that matches the plural form of a word, the second must be a String that replaces the + * matched part of the regular expression. This is managed by the {@link #singular} method. + * @property {Array} singulars + */ + singulars: [ + [(/(quiz)zes$/i), "$1" ], + [(/(matr)ices$/i), "$1ix" ], + [(/(vert|ind)ices$/i), "$1ex" ], + [(/^(ox)en/i), "$1" ], + [(/(alias|status)es$/i), "$1" ], + [(/(octop|vir)i$/i), "$1us" ], + [(/(cris|ax|test)es$/i), "$1is" ], + [(/(shoe)s$/i), "$1" ], + [(/(o)es$/i), "$1" ], + [(/(bus)es$/i), "$1" ], + [(/([m|l])ice$/i), "$1ouse" ], + [(/(x|ch|ss|sh)es$/i), "$1" ], + [(/(m)ovies$/i), "$1ovie" ], + [(/(s)eries$/i), "$1eries"], + [(/([^aeiouy]|qu)ies$/i), "$1y" ], + [(/([lr])ves$/i), "$1f" ], + [(/(tive)s$/i), "$1" ], + [(/(hive)s$/i), "$1" ], + [(/([^f])ves$/i), "$1fe" ], + [(/(^analy)ses$/i), "$1sis" ], + [(/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i), "$1$2sis"], + [(/([ti])a$/i), "$1um" ], + [(/(n)ews$/i), "$1ews" ], + [(/people$/i), "person" ], + [(/s$/i), "" ] + ], + + /** + * @private + * The registered uncountable words + * @property {String[]} uncountable + */ + uncountable: [ + "sheep", + "fish", + "series", + "species", + "money", + "rice", + "information", + "equipment", + "grass", + "mud", + "offspring", + "deer", + "means" + ], + + /** + * Adds a new singularization rule to the Inflector. See the intro docs for more information + * @param {RegExp} matcher The matcher regex + * @param {String} replacer The replacement string, which can reference matches from the matcher argument + */ + singular: function(matcher, replacer) { + this.singulars.unshift([matcher, replacer]); + }, + + /** + * Adds a new pluralization rule to the Inflector. See the intro docs for more information + * @param {RegExp} matcher The matcher regex + * @param {String} replacer The replacement string, which can reference matches from the matcher argument + */ + plural: function(matcher, replacer) { + this.plurals.unshift([matcher, replacer]); + }, + + /** + * Removes all registered singularization rules + */ + clearSingulars: function() { + this.singulars = []; + }, + + /** + * Removes all registered pluralization rules + */ + clearPlurals: function() { + this.plurals = []; + }, + + /** + * Returns true if the given word is transnumeral (the word is its own singular and plural form - e.g. sheep, fish) + * @param {String} word The word to test + * @return {Boolean} True if the word is transnumeral + */ + isTransnumeral: function(word) { + return Ext.Array.indexOf(this.uncountable, word) != -1; + }, + + /** + * Returns the pluralized form of a word (e.g. Ext.util.Inflector.pluralize('word') returns 'words') + * @param {String} word The word to pluralize + * @return {String} The pluralized form of the word + */ + pluralize: function(word) { + if (this.isTransnumeral(word)) { + return word; + } + + var plurals = this.plurals, + length = plurals.length, + tuple, regex, i; + + for (i = 0; i < length; i++) { + tuple = plurals[i]; + regex = tuple[0]; + + if (regex == word || (regex.test && regex.test(word))) { + return word.replace(regex, tuple[1]); + } + } + + return word; + }, + + /** + * Returns the singularized form of a word (e.g. Ext.util.Inflector.singularize('words') returns 'word') + * @param {String} word The word to singularize + * @return {String} The singularized form of the word + */ + singularize: function(word) { + if (this.isTransnumeral(word)) { + return word; + } + + var singulars = this.singulars, + length = singulars.length, + tuple, regex, i; + + for (i = 0; i < length; i++) { + tuple = singulars[i]; + regex = tuple[0]; + + if (regex == word || (regex.test && regex.test(word))) { + return word.replace(regex, tuple[1]); + } + } + + return word; + }, + + /** + * Returns the correct {@link Ext.data.Model Model} name for a given string. Mostly used internally by the data + * package + * @param {String} word The word to classify + * @return {String} The classified version of the word + */ + classify: function(word) { + return Ext.String.capitalize(this.singularize(word)); + }, + + /** + * Ordinalizes a given number by adding a prefix such as 'st', 'nd', 'rd' or 'th' based on the last digit of the + * number. 21 -> 21st, 22 -> 22nd, 23 -> 23rd, 24 -> 24th etc + * @param {Number} number The number to ordinalize + * @return {String} The ordinalized number + */ + ordinalize: function(number) { + var parsed = parseInt(number, 10), + mod10 = parsed % 10, + mod100 = parsed % 100; + + //11 through 13 are a special case + if (11 <= mod100 && mod100 <= 13) { + return number + "th"; + } else { + switch(mod10) { + case 1 : return number + "st"; + case 2 : return number + "nd"; + case 3 : return number + "rd"; + default: return number + "th"; + } + } + } +}, function() { + //aside from the rules above, there are a number of words that have irregular pluralization so we add them here + var irregulars = { + alumnus: 'alumni', + cactus : 'cacti', + focus : 'foci', + nucleus: 'nuclei', + radius: 'radii', + stimulus: 'stimuli', + ellipsis: 'ellipses', + paralysis: 'paralyses', + oasis: 'oases', + appendix: 'appendices', + index: 'indexes', + beau: 'beaux', + bureau: 'bureaux', + tableau: 'tableaux', + woman: 'women', + child: 'children', + man: 'men', + corpus: 'corpora', + criterion: 'criteria', + curriculum: 'curricula', + genus: 'genera', + memorandum: 'memoranda', + phenomenon: 'phenomena', + foot: 'feet', + goose: 'geese', + tooth: 'teeth', + antenna: 'antennae', + formula: 'formulae', + nebula: 'nebulae', + vertebra: 'vertebrae', + vita: 'vitae' + }, + singular; + + for (singular in irregulars) { + this.plural(singular, irregulars[singular]); + this.singular(irregulars[singular], singular); + } +}); +/** + * @class Ext.util.Memento + * This class manages a set of captured properties from an object. These captured properties + * can later be restored to an object. + */ +Ext.define('Ext.util.Memento', (function () { + + function captureOne (src, target, prop, prefix) { + src[prefix ? prefix + prop : prop] = target[prop]; + } + + function removeOne (src, target, prop) { + delete src[prop]; + } + + function restoreOne (src, target, prop, prefix) { + var name = prefix ? prefix + prop : prop, + value = src[name]; + + if (value || src.hasOwnProperty(name)) { + restoreValue(target, prop, value); + } + } + + function restoreValue (target, prop, value) { + if (Ext.isDefined(value)) { + target[prop] = value; + } else { + delete target[prop]; + } + } + + function doMany (doOne, src, target, props, prefix) { + if (src) { + if (Ext.isArray(props)) { + var p, pLen = props.length; + for (p = 0; p < pLen; p++) { + doOne(src, target, props[p], prefix); + } + } else { + doOne(src, target, props, prefix); + } + } + } + + return { + /** + * @property data + * The collection of captured properties. + * @private + */ + data: null, + + /** + * @property target + * The default target object for capture/restore (passed to the constructor). + */ + target: null, + + /** + * Creates a new memento and optionally captures properties from the target object. + * @param {Object} target The target from which to capture properties. If specified in the + * constructor, this target becomes the default target for all other operations. + * @param {String/String[]} props The property or array of properties to capture. + */ + constructor: function (target, props) { + if (target) { + this.target = target; + if (props) { + this.capture(props); + } + } + }, + + /** + * Captures the specified properties from the target object in this memento. + * @param {String/String[]} props The property or array of properties to capture. + * @param {Object} target The object from which to capture properties. + */ + capture: function (props, target, prefix) { + var me = this; + doMany(captureOne, me.data || (me.data = {}), target || me.target, props, prefix); + }, + + /** + * Removes the specified properties from this memento. These properties will not be + * restored later without re-capturing their values. + * @param {String/String[]} props The property or array of properties to remove. + */ + remove: function (props) { + doMany(removeOne, this.data, null, props); + }, + + /** + * Restores the specified properties from this memento to the target object. + * @param {String/String[]} props The property or array of properties to restore. + * @param {Boolean} clear True to remove the restored properties from this memento or + * false to keep them (default is true). + * @param {Object} target The object to which to restore properties. + */ + restore: function (props, clear, target, prefix) { + doMany(restoreOne, this.data, target || this.target, props, prefix); + if (clear !== false) { + this.remove(props); + } + }, + + /** + * Restores all captured properties in this memento to the target object. + * @param {Boolean} clear True to remove the restored properties from this memento or + * false to keep them (default is true). + * @param {Object} target The object to which to restore properties. + */ + restoreAll: function (clear, target) { + var me = this, + t = target || this.target, + data = me.data, + prop; + + for (prop in data) { + if (data.hasOwnProperty(prop)) { + restoreValue(t, prop, data[prop]); + } + } + + if (clear !== false) { + delete me.data; + } + } + }; +}())); + +/** + * 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: + * + * Ext.define('Employee', { + * mixins: { + * observable: 'Ext.util.Observable' + * }, + * + * constructor: function (config) { + * // The Observable constructor copies all of the properties of `config` on + * // to `this` using {@link Ext#apply}. Further, the `listeners` property is + * // processed to add listeners. + * // + * this.mixins.observable.constructor.call(this, config); + * + * this.addEvents( + * 'fired', + * 'quit' + * ); + * } + * }); + * + * 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!"); + * } + * } + * }); + */ +Ext.define('Ext.util.Observable', { + + /* Begin Definitions */ + + requires: ['Ext.util.Event'], + + statics: { + /** + * Removes **all** added captures from the Observable. + * + * @param {Ext.util.Observable} o The Observable to release + * @static + */ + releaseCapture: function(o) { + o.fireEvent = this.prototype.fireEvent; + }, + + /** + * 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 {Ext.util.Observable} o The Observable to capture events from. + * @param {Function} fn The function to call when an event is fired. + * @param {Object} scope (optional) The scope (`this` reference) in which the function is executed. Defaults to + * the Observable firing the event. + * @static + */ + capture: function(o, fn, scope) { + o.fireEvent = Ext.Function.createInterceptor(o.fireEvent, 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.observe(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. + * @param {Object} listeners An object containing a series of listeners to add. See {@link #addListener}. + * @static + */ + observe: function(cls, listeners) { + if (cls) { + if (!cls.isObservable) { + Ext.applyIf(cls, new this()); + this.capture(cls.prototype, cls.fireEvent, cls); + } + if (Ext.isObject(listeners)) { + cls.on(listeners); + } + } + return cls; + }, + + /** + * Prepares a given class for observable instances. This method is called when a + * class derives from this class or uses this class as a mixin. + * @param {Function} T The class constructor to prepare. + * @private + */ + prepareClass: function (T, mixin) { + // T.hasListeners is the object to track listeners on class T. This object's + // prototype (__proto__) is the "hasListeners" of T.superclass. + + // Instances of T will create "hasListeners" that have T.hasListeners as their + // immediate prototype (__proto__). + + if (!T.HasListeners) { + // We create a HasListeners "class" for this class. The "prototype" of the + // HasListeners class is an instance of the HasListeners class associated + // with this class's super class (or with Observable). + var Observable = Ext.util.Observable, + HasListeners = function () {}, + SuperHL = T.superclass.HasListeners || (mixin && mixin.HasListeners) || + Observable.HasListeners; + + // Make the HasListener class available on the class and its prototype: + T.prototype.HasListeners = T.HasListeners = HasListeners; + + // And connect its "prototype" to the new HasListeners of our super class + // (which is also the class-level "hasListeners" instance). + HasListeners.prototype = T.hasListeners = new SuperHL(); + } + } + }, + + /* End Definitions */ + + /** + * @cfg {Object} listeners + * + * 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 Ext JS {@link Ext.Component Components}** + * + * While _some_ Ext JS 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.view.View DataView}'s **`{@link + * Ext.view.View#itemclick itemclick}`** event passing the node clicked on. To access DOM events directly from a + * child element of a Component, we need to specify the `element` option to identify the Component property to add a + * DOM listener to: + * + * new Ext.panel.Panel({ + * width: 400, + * height: 200, + * dockedItems: [{ + * xtype: 'toolbar' + * }], + * listeners: { + * click: { + * element: 'el', //bind to the underlying el property on the panel + * fn: function(){ console.log('click el'); } + * }, + * dblclick: { + * element: 'body', //bind to the underlying body property on the panel + * fn: function(){ console.log('dblclick body'); } + * } + * } + * }); + */ + + /** + * @property {Boolean} isObservable + * `true` in this class to identify an object as an instantiated Observable, or subclass thereof. + */ + isObservable: true, + + /** + * @property {Object} hasListeners + * @readonly + * This object holds a key for any event that has a listener. The listener may be set + * directly on the instance, or on its class or a super class (via {@link #observe}) or + * on the {@link Ext.app.EventBus MVC EventBus}. The values of this object are truthy + * (a non-zero number) and falsy (0 or undefined). They do not represent an exact count + * of listeners. The value for an event is truthy if the event must be fired and is + * falsy if there is no need to fire the event. + * + * The intended use of this property is to avoid the expense of fireEvent calls when + * there are no listeners. This can be particularly helpful when one would otherwise + * have to call fireEvent hundreds or thousands of times. It is used like this: + * + * if (this.hasListeners.foo) { + * this.fireEvent('foo', this, arg1); + * } + */ + + constructor: function(config) { + var me = this; + + Ext.apply(me, config); + + // The subclass may have already initialized it. + if (!me.hasListeners) { + me.hasListeners = new me.HasListeners(); + } + + me.events = me.events || {}; + if (me.listeners) { + me.on(me.listeners); + me.listeners = null; //Set as an instance property to pre-empt the prototype in case any are set there. + } + + if (me.bubbleEvents) { + me.enableBubble(me.bubbleEvents); + } + }, + + onClassExtended: function (T) { + if (!T.HasListeners) { + // Some classes derive from us and some others derive from those classes. All + // of these are passed to this method. + Ext.util.Observable.prepareClass(T); + } + }, + + // @private + eventOptionsRe : /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate|element|vertical|horizontal|freezeEvent)$/, + + /** + * Adds listeners to any Observable object (or Ext.Element) which are automatically removed when this Component is + * destroyed. + * + * @param {Ext.util.Observable/Ext.Element} item The item to which to add a listener/listeners. + * @param {Object/String} ename The event name, or an object containing event name properties. + * @param {Function} fn (optional) If the `ename` parameter was an event name, this is the handler function. + * @param {Object} scope (optional) If the `ename` parameter was an event name, this is the scope (`this` reference) + * in which the handler function is executed. + * @param {Object} opt (optional) If the `ename` parameter was an event name, this is the + * {@link Ext.util.Observable#addListener addListener} options. + */ + addManagedListener : function(item, ename, fn, scope, options) { + var me = this, + managedListeners = me.managedListeners = me.managedListeners || [], + config; + + if (typeof ename !== 'string') { + options = ename; + for (ename in options) { + if (options.hasOwnProperty(ename)) { + config = options[ename]; + if (!me.eventOptionsRe.test(ename)) { + me.addManagedListener(item, ename, config.fn || config, config.scope || options.scope, config.fn ? config : options); + } + } + } + } + else { + managedListeners.push({ + item: item, + ename: ename, + fn: fn, + scope: scope, + options: options + }); + + item.on(ename, fn, scope, options); + } + }, + + /** + * Removes listeners that were added by the {@link #mon} method. + * + * @param {Ext.util.Observable/Ext.Element} item The item from which to remove a listener/listeners. + * @param {Object/String} ename The event name, or an object containing event name properties. + * @param {Function} fn (optional) If the `ename` parameter was an event name, this is the handler function. + * @param {Object} scope (optional) If the `ename` parameter was an event name, this is the scope (`this` reference) + * in which the handler function is executed. + */ + removeManagedListener : function(item, ename, fn, scope) { + var me = this, + options, + config, + managedListeners, + length, + i; + + if (typeof ename !== 'string') { + options = ename; + for (ename in options) { + if (options.hasOwnProperty(ename)) { + config = options[ename]; + if (!me.eventOptionsRe.test(ename)) { + me.removeManagedListener(item, ename, config.fn || config, config.scope || options.scope); + } + } + } + } + + managedListeners = me.managedListeners ? me.managedListeners.slice() : []; + + for (i = 0, length = managedListeners.length; i < length; i++) { + me.removeManagedListenerItem(false, managedListeners[i], item, ename, fn, scope); + } + }, + + /** + * Fires the specified event with the passed parameters (minus the event name, plus the `options` object passed + * to {@link #addListener}). + * + * 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(eventName) { + eventName = eventName.toLowerCase(); + var me = this, + events = me.events, + event = events && events[eventName], + ret = true; + + // Only continue firing the event if there are listeners to be informed. + // Bubbled events will always have a listener count, so will be fired. + if (event && me.hasListeners[eventName]) { + ret = me.continueFireEvent(eventName, Ext.Array.slice(arguments, 1), event.bubble); + } + return ret; + }, + + /** + * Continue to fire event. + * @private + * + * @param {String} eventName + * @param {Array} args + * @param {Boolean} bubbles + */ + continueFireEvent: function(eventName, args, bubbles) { + var target = this, + queue, event, + ret = true; + + do { + if (target.eventsSuspended) { + if ((queue = target.eventQueue)) { + queue.push([eventName, args, bubbles]); + } + return ret; + } else { + event = target.events[eventName]; + // Continue bubbling if event exists and it is `true` or the handler didn't returns false and it + // configure to bubble. + if (event && event != true) { + if ((ret = event.fire.apply(event, args)) === false) { + break; + } + } + } + } while (bubbles && (target = target.getBubbleParent())); + return ret; + }, + + /** + * Gets the bubbling parent for an Observable + * @private + * @return {Ext.util.Observable} The bubble parent. null is returned if no bubble target exists + */ + getBubbleParent: function(){ + var me = this, parent = me.getBubbleTarget && me.getBubbleTarget(); + if (parent && parent.isObservable) { + return parent; + } + return null; + }, + + /** + * Appends an event handler to this object. For example: + * + * myGridPanel.on("mouseover", this.onMouseOver, this); + * + * The method also allows for a single argument to be passed which is a config object + * containing properties which specify multiple events. For example: + * + * myGridPanel.on({ + * cellClick: this.onCellClick, + * mouseover: this.onMouseOver, + * mouseout: this.onMouseOut, + * scope: this // Important. Ensure "this" is correct during handler execution + * }); + * + * One can also specify options for each event handler separately: + * + * myGridPanel.on({ + * cellClick: {fn: this.onCellClick, scope: this, single: true}, + * mouseover: {fn: panel.onMouseOver, scope: panel} + * }); + * + * *Names* of methods in a specified scope may also be used. Note that + * `scope` MUST be specified to use this option: + * + * myGridPanel.on({ + * cellClick: {fn: 'onCellClick', scope: this, single: true}, + * mouseover: {fn: 'onMouseOver', scope: panel} + * }); + * + * @param {String/Object} eventName The name of the event to listen for. + * May also be an object who's property names are event names. + * + * @param {Function} [fn] The method the event invokes, or *if `scope` is specified, the *name* of the method within + * the specified `scope`. Will be called with arguments + * given to {@link #fireEvent} plus the `options` parameter described below. + * + * @param {Object} [scope] The scope (`this` reference) in which the handler function is + * executed. **If omitted, defaults to the object which fired the event.** + * + * @param {Object} [options] An object containing handler configuration. + * + * **Note:** Unlike in ExtJS 3.x, the options object will also be passed as the last + * argument to every event handler. + * + * This object may contain any of the following properties: + * + * @param {Object} options.scope + * The scope (`this` reference) in which the handler function is executed. **If omitted, + * defaults to the object which fired the event.** + * + * @param {Number} options.delay + * The number of milliseconds to delay the invocation of the handler after the event fires. + * + * @param {Boolean} options.single + * True to add a handler to handle just the next firing of the event, and then remove itself. + * + * @param {Number} options.buffer + * Causes the handler to be scheduled to run in an {@link Ext.util.DelayedTask} delayed + * by the specified number of milliseconds. If the event fires again within that time, + * the original handler is _not_ invoked, but the new handler is scheduled in its place. + * + * @param {Ext.util.Observable} options.target + * Only call the handler if the event was fired on the target Observable, _not_ if the event + * was bubbled up from a child Observable. + * + * @param {String} options.element + * **This option is only valid for listeners bound to {@link Ext.Component Components}.** + * The name of a Component property which references an element to add a listener to. + * + * This option is useful during Component construction to add DOM event listeners to elements of + * {@link Ext.Component Components} which will exist only after the Component is rendered. + * For example, to add a click listener to a Panel's body: + * + * new Ext.panel.Panel({ + * title: 'The title', + * listeners: { + * click: this.handlePanelClick, + * element: 'body' + * } + * }); + * + * **Combining Options** + * + * Using the options argument, it is possible to combine different types of listeners: + * + * A delayed, one-time listener. + * + * myPanel.on('hide', this.handleClick, this, { + * single: true, + * delay: 100 + * }); + * + */ + addListener: function(ename, fn, scope, options) { + var me = this, + config, event, hasListeners; + + if (typeof ename !== 'string') { + options = ename; + for (ename in options) { + if (options.hasOwnProperty(ename)) { + config = options[ename]; + if (!me.eventOptionsRe.test(ename)) { + me.addListener(ename, config.fn || config, config.scope || options.scope, config.fn ? config : options); + } + } + } + } else { + ename = ename.toLowerCase(); + me.events[ename] = me.events[ename] || true; + event = me.events[ename] || true; + if (Ext.isBoolean(event)) { + me.events[ename] = event = new Ext.util.Event(me, ename); + } + + // Allow listeners: { click: 'onClick', scope: myObject } + if (typeof fn === 'string') { + if (!(scope[fn] || me[fn])) { + Ext.Error.raise('No method named "' + fn + '"'); + } + fn = scope[fn] || me[fn]; + } + event.addListener(fn, scope, Ext.isObject(options) ? options : {}); + + hasListeners = me.hasListeners; + if (hasListeners.hasOwnProperty(ename)) { + // if we already have listeners at this level, just increment the count... + ++hasListeners[ename]; + } else { + // otherwise, start the count at 1 (which hides whatever is in our prototype + // chain)... + hasListeners[ename] = 1; + } + } + }, + + /** + * Removes an event handler. + * + * @param {String} eventName The type of event the handler was associated with. + * @param {Function} fn 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. It must be the same as the + * scope argument specified in the original call to {@link #addListener} or the listener will not be removed. + */ + removeListener: function(ename, fn, scope) { + var me = this, + config, + event, + options; + + if (typeof ename !== 'string') { + options = ename; + for (ename in options) { + if (options.hasOwnProperty(ename)) { + config = options[ename]; + if (!me.eventOptionsRe.test(ename)) { + me.removeListener(ename, config.fn || config, config.scope || options.scope); + } + } + } + } else { + ename = ename.toLowerCase(); + event = me.events[ename]; + if (event && event.isEvent) { + event.removeListener(fn, scope); + + if (! --me.hasListeners[ename]) { + // Delete this entry, since 0 does not mean no one is listening, just + // that no one is *directly& listening. This allows the eventBus or + // class observers to "poke" through and expose their presence. + delete me.hasListeners[ename]; + } + } + } + }, + + /** + * Removes all listeners for this object including the managed listeners + */ + clearListeners: function() { + var events = this.events, + event, + key; + + for (key in events) { + if (events.hasOwnProperty(key)) { + event = events[key]; + if (event.isEvent) { + event.clearListeners(); + } + } + } + + this.clearManagedListeners(); + }, + + purgeListeners : function() { + if (Ext.global.console) { + Ext.global.console.warn('Observable: purgeListeners has been deprecated. Please use clearListeners.'); + } + return this.clearListeners.apply(this, arguments); + }, + + /** + * Removes all managed listeners for this object. + */ + clearManagedListeners : function() { + var managedListeners = this.managedListeners || [], + i = 0, + len = managedListeners.length; + + for (; i < len; i++) { + this.removeManagedListenerItem(true, managedListeners[i]); + } + + this.managedListeners = []; + }, + + /** + * Remove a single managed listener item + * @private + * @param {Boolean} isClear True if this is being called during a clear + * @param {Object} managedListener The managed listener item + * See removeManagedListener for other args + */ + removeManagedListenerItem: function(isClear, managedListener, item, ename, fn, scope){ + if (isClear || (managedListener.item === item && managedListener.ename === ename && (!fn || managedListener.fn === fn) && (!scope || managedListener.scope === scope))) { + managedListener.item.un(managedListener.ename, managedListener.fn, managedListener.scope); + if (!isClear) { + Ext.Array.remove(this.managedListeners, managedListener); + } + } + }, + + purgeManagedListeners : function() { + if (Ext.global.console) { + Ext.global.console.warn('Observable: purgeManagedListeners has been deprecated. Please use clearManagedListeners.'); + } + return this.clearManagedListeners.apply(this, arguments); + }, + + /** + * Adds the specified events to the list of events which this Observable may fire. + * + * @param {Object/String...} eventNames Either an object with event names as properties with + * a value of `true`. For example: + * + * this.addEvents({ + * storeloaded: true, + * storecleared: true + * }); + * + * Or any number of event names as separate parameters. For example: + * + * this.addEvents('storeloaded', 'storecleared'); + * + */ + addEvents: function(o) { + var me = this, + events = me.events || (me.events = {}), + arg, args, i; + + if (typeof o == 'string') { + for (args = arguments, i = args.length; i--; ) { + arg = args[i]; + if (!events[arg]) { + events[arg] = true; + } + } + } else { + Ext.applyIf(me.events, o); + } + }, + + /** + * Checks to see if this object has any listeners for a specified event, or whether the event bubbles. The answer + * indicates whether the event needs firing or not. + * + * @param {String} eventName The name of the event to check for + * @return {Boolean} `true` if the event is being listened for or bubbles, else `false` + */ + hasListener: function(ename) { + return !!this.hasListeners[ename.toLowerCase()]; + }, + + /** + * Suspends the firing of all events. (see {@link #resumeEvents}) + * + * @param {Boolean} queueSuspended Pass as true to queue up suspended events to be fired + * after the {@link #resumeEvents} call instead of discarding all suspended events. + */ + suspendEvents: function(queueSuspended) { + this.eventsSuspended = true; + if (queueSuspended && !this.eventQueue) { + this.eventQueue = []; + } + }, + + /** + * Resumes 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, + qLen, q; + + me.eventsSuspended = false; + delete me.eventQueue; + + if (queued) { + qLen = queued.length; + for (q = 0; q < qLen; q++) { + me.continueFireEvent.apply(me, queued[q]); + } + } + }, + + /** + * Relays selected events from the specified Observable as if the events were fired by `this`. + * + * For example if you are extending Grid, you might decide to forward some events from store. + * So you can do this inside your initComponent: + * + * this.relayEvents(this.getStore(), ['load']); + * + * The grid instance will then have an observable 'load' event which will be passed the + * parameters of the store's load event and any function fired with the grid's load event + * would have access to the grid using the `this` keyword. + * + * @param {Object} origin The Observable whose events this object is to relay. + * @param {String[]} events Array of event names to relay. + * @param {String} [prefix] A common prefix to attach to the event names. For example: + * + * this.relayEvents(this.getStore(), ['load', 'clear'], 'store'); + * + * Now the grid will forward 'load' and 'clear' events of store as 'storeload' and 'storeclear'. + */ + relayEvents : function(origin, events, prefix) { + prefix = prefix || ''; + var me = this, + len = events.length, + i = 0, + oldName, + newName; + + for (; i < len; i++) { + oldName = events[i]; + newName = prefix + oldName; + me.events[newName] = me.events[newName] || true; + origin.on(oldName, me.createRelayer(newName)); + } + }, + + /** + * @private + * Creates an event handling function which refires the event from this object as the passed event name. + * @param newName + * @param {Array} beginEnd (optional) The caller can specify on which indices to slice + * @returns {Function} + */ + createRelayer: function(newName, beginEnd){ + var me = this; + return function(){ + return me.fireEvent.apply(me, [newName].concat(Array.prototype.slice.apply(arguments, beginEnd || [0, -1]))); + }; + }, + + /** + * 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.Base, { + * // Add functionality to Field's initComponent to enable the change event to bubble + * initComponent : Ext.Function.createSequence(Ext.form.field.Base.prototype.initComponent, 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 {String/String[]} eventNames The event name to bubble, or an Array of event names. + */ + enableBubble: function(eventNames) { + if (eventNames) { + var me = this, + names = (typeof eventNames == 'string') ? arguments : eventNames, + length = names.length, + events = me.events, + ename, event, i; + + for (i = 0; i < length; ++i) { + ename = names[i].toLowerCase(); + event = events[ename]; + + if (!event || typeof event == 'boolean') { + events[ename] = event = new Ext.util.Event(me, ename); + } + + // Event must fire if it bubbles (We don't know if anyone up the bubble hierarchy has listeners added) + me.hasListeners[ename] = (me.hasListeners[ename]||0) + 1; + + event.bubble = true; + } + } + } +}, function() { + var Observable = this, + proto = Observable.prototype, + HasListeners = function () {}, + prepareMixin = function (T) { + if (!T.HasListeners) { + var proto = T.prototype; + + // Classes that use us as a mixin (best practice) need to be prepared. + Observable.prepareClass(T, this); + + // Now that we are mixed in to class T, we need to watch T for derivations + // and prepare them also. + T.onExtended(function (U) { + Observable.prepareClass(U); + }); + + // Also, if a class uses us as a mixin and that class is then used as + // a mixin, we need to be notified of that as well. + if (proto.onClassMixedIn) { + // play nice with other potential overrides... + Ext.override(T, { + onClassMixedIn: function (U) { + prepareMixin.call(this, U); + this.callParent(arguments); + } + }); + } else { + // just us chickens, so add the method... + proto.onClassMixedIn = function (U) { + prepareMixin.call(this, U); + }; + } + } + }; + + HasListeners.prototype = { + //$$: 42 // to make sure we have a proper prototype + }; + + proto.HasListeners = Observable.HasListeners = HasListeners; + + Observable.createAlias({ + /** + * @method + * Shorthand for {@link #addListener}. + * @inheritdoc Ext.util.Observable#addListener + */ + on: 'addListener', + /** + * @method + * Shorthand for {@link #removeListener}. + * @inheritdoc Ext.util.Observable#removeListener + */ + un: 'removeListener', + /** + * @method + * Shorthand for {@link #addManagedListener}. + * @inheritdoc Ext.util.Observable#addManagedListener + */ + mon: 'addManagedListener', + /** + * @method + * Shorthand for {@link #removeManagedListener}. + * @inheritdoc Ext.util.Observable#removeManagedListener + */ + mun: 'removeManagedListener' + }); + + //deprecated, will be removed in 5.0 + Observable.observeClass = Observable.observe; + + // 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, + makeCall; + + if (!e) { + this.methodEvents[method] = e = {}; + e.originalFn = this[method]; + e.methodName = method; + e.before = []; + e.after = []; + + makeCall = function(fn, scope, args){ + if((v = fn.apply(scope || obj, args)) !== undefined){ + if (typeof v == 'object') { + if(v.returnValue !== undefined){ + returnValue = v.returnValue; + }else{ + returnValue = v; + } + cancel = !!v.cancel; + } + else + if (v === false) { + cancel = true; + } + else { + returnValue = v; + } + } + }; + + this[method] = function(){ + var args = Array.prototype.slice.call(arguments, 0), + b, i, len; + returnValue = v = undefined; + cancel = false; + + for(i = 0, len = e.before.length; i < len; i++){ + b = e.before[i]; + makeCall(b.fn, b.scope, args); + if (cancel) { + return returnValue; + } + } + + if((v = e.originalFn.apply(obj, args)) !== undefined){ + returnValue = v; + } + + for(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; + } + + Ext.apply(proto, { + onClassMixedIn: prepareMixin, + + // these are considered experimental + // allows for easier interceptor and sequences, including cancelling and overwriting the return value of the call + // adds an 'interceptor' called before the original method + beforeMethod : function(method, fn, scope){ + getMethodEvent.call(this, method).before.push({ + fn: fn, + scope: scope + }); + }, + + // adds a 'sequence' called after the original method + afterMethod : function(method, fn, scope){ + getMethodEvent.call(this, method).after.push({ + fn: fn, + scope: scope + }); + }, + + removeMethodListener: function(method, fn, scope){ + var e = this.getMethodEvent(method), + i, len; + for(i = 0, len = e.before.length; i < len; i++){ + if(e.before[i].fn == fn && e.before[i].scope == scope){ + Ext.Array.erase(e.before, i, 1); + return; + } + } + for(i = 0, len = e.after.length; i < len; i++){ + if(e.after[i].fn == fn && e.after[i].scope == scope){ + Ext.Array.erase(e.after, i, 1); + return; + } + } + }, + + toggleEventLogging: function(toggle) { + Ext.util.Observable[toggle ? 'capture' : 'releaseCapture'](this, function(en) { + if (Ext.isDefined(Ext.global.console)) { + Ext.global.console.log(en, arguments); + } + }); + } + }); +}); + +/** + * @private + */ +Ext.define('Ext.util.Offset', { + + /* Begin Definitions */ + + statics: { + fromObject: function(obj) { + return new this(obj.x, obj.y); + } + }, + + /* End Definitions */ + + constructor: function(x, y) { + this.x = (x != null && !isNaN(x)) ? x : 0; + this.y = (y != null && !isNaN(y)) ? y : 0; + + return this; + }, + + copy: function() { + return new Ext.util.Offset(this.x, this.y); + }, + + copyFrom: function(p) { + this.x = p.x; + this.y = p.y; + }, + + toString: function() { + return "Offset[" + this.x + "," + this.y + "]"; + }, + + equals: function(offset) { + if(!(offset instanceof this.statics())) { + Ext.Error.raise('Offset must be an instance of Ext.util.Offset'); + } + + return (this.x == offset.x && this.y == offset.y); + }, + + round: function(to) { + if (!isNaN(to)) { + var factor = Math.pow(10, to); + this.x = Math.round(this.x * factor) / factor; + this.y = Math.round(this.y * factor) / factor; + } else { + this.x = Math.round(this.x); + this.y = Math.round(this.y); + } + }, + + isZero: function() { + return this.x == 0 && this.y == 0; + } +}); + +/* + * The dirty implementation in this class is quite naive. The reasoning for this is that the dirty state + * will only be used in very specific circumstances, specifically, after the render process has begun but + * the component is not yet rendered to the DOM. As such, we want it to perform as quickly as possible + * so it's not as fully featured as you may expect. + */ + +/** + * Manages certain element-like data prior to rendering. These values are passed + * on to the render process. This is currently used to manage the "class" and "style" attributes + * of a component's primary el as well as the bodyEl of panels. This allows things like + * addBodyCls in Panel to share logic with addCls in AbstractComponent. + * @private + */ +Ext.define('Ext.util.ProtoElement', (function () { + var splitWords = Ext.String.splitWords, + toMap = Ext.Array.toMap; + + return { + + isProtoEl: true, + + /** + * The property name for the className on the data object passed to {@link #writeTo}. + */ + clsProp: 'cls', + + /** + * The property name for the style on the data object passed to {@link #writeTo}. + */ + styleProp: 'style', + + /** + * The property name for the removed classes on the data object passed to {@link #writeTo}. + */ + removedProp: 'removed', + + /** + * True if the style must be converted to text during {@link #writeTo}. When used to + * populate tpl data, this will be true. When used to populate {@link Ext.DomHelper} + * specs, this will be false (the default). + */ + styleIsText: false, + + constructor: function (config) { + var me = this; + + Ext.apply(me, config); + + me.classList = splitWords(me.cls); + me.classMap = toMap(me.classList); + delete me.cls; + + if (Ext.isFunction(me.style)) { + me.styleFn = me.style; + delete me.style; + } else if (typeof me.style == 'string') { + me.style = Ext.Element.parseStyles(me.style); + } else if (me.style) { + me.style = Ext.apply({}, me.style); // don't edit the given object + } + }, + + /** + * Indicates that the current state of the object has been flushed to the DOM, so we need + * to track any subsequent changes + */ + flush: function(){ + this.flushClassList = []; + this.removedClasses = {}; + // clear the style, it will be recreated if we add anything new + delete this.style; + }, + + /** + * Adds class to the element. + * @param {String} cls One or more classnames separated with spaces. + * @return {Ext.util.ProtoElement} this + */ + addCls: function (cls) { + var me = this, + add = splitWords(cls), + length = add.length, + list = me.classList, + map = me.classMap, + flushList = me.flushClassList, + i = 0, + c; + + for (; i < length; ++i) { + c = add[i]; + if (!map[c]) { + map[c] = true; + list.push(c); + if (flushList) { + flushList.push(c); + delete me.removedClasses[c]; + } + } + } + + return me; + }, + + /** + * True if the element has given class. + * @param {String} cls + * @return {Boolean} + */ + hasCls: function (cls) { + return cls in this.classMap; + }, + + /** + * Removes class from the element. + * @param {String} cls One or more classnames separated with spaces. + * @return {Ext.util.ProtoElement} this + */ + removeCls: function (cls) { + var me = this, + list = me.classList, + newList = (me.classList = []), + remove = toMap(splitWords(cls)), + length = list.length, + map = me.classMap, + removedClasses = me.removedClasses, + i, c; + + for (i = 0; i < length; ++i) { + c = list[i]; + if (remove[c]) { + if (removedClasses) { + if (map[c]) { + removedClasses[c] = true; + Ext.Array.remove(me.flushClassList, c); + } + } + delete map[c]; + } else { + newList.push(c); + } + } + + return me; + }, + + /** + * Adds styles to the element. + * @param {String/Object} prop The style property to be set, or an object of multiple styles. + * @param {String} [value] The value to apply to the given property. + * @return {Ext.util.ProtoElement} this + */ + setStyle: function (prop, value) { + var me = this, + style = me.style || (me.style = {}); + + if (typeof prop == 'string') { + if (arguments.length === 1) { + me.setStyle(Ext.Element.parseStyles(prop)); + } else { + style[prop] = value; + } + } else { + Ext.apply(style, prop); + } + + return me; + }, + + /** + * Writes style and class properties to given object. + * Styles will be written to {@link #styleProp} and class names to {@link #clsProp}. + * @param {Object} to + * @return {Object} to + */ + writeTo: function (to) { + var me = this, + classList = me.flushClassList || me.classList, + removedClasses = me.removedClasses, + style; + + if (me.styleFn) { + style = Ext.apply({}, me.styleFn()); + Ext.apply(style, me.style); + } else { + style = me.style; + } + + to[me.clsProp] = classList.join(' '); + + if (style) { + to[me.styleProp] = me.styleIsText ? Ext.DomHelper.generateStyles(style) : style; + } + + if (removedClasses) { + removedClasses = Ext.Object.getKeys(removedClasses); + if (removedClasses.length) { + to[me.removedProp] = removedClasses.join(' '); + } + } + + return to; + } + }; +}())); + +/** + * An internal Queue class. + * @private + */ +Ext.define('Ext.util.Queue', { + + constructor: function() { + this.clear(); + }, + + add : function(obj) { + var me = this, + key = me.getKey(obj); + + if (!me.map[key]) { + ++me.length; + me.items.push(obj); + me.map[key] = obj; + } + + return obj; + }, + + /** + * Removes all items from the collection. + */ + clear : function(){ + var me = this, + items = me.items; + + me.items = []; + me.map = {}; + me.length = 0; + + return items; + }, + + contains: function (obj) { + var key = this.getKey(obj); + + return this.map.hasOwnProperty(key); + }, + + /** + * Returns the number of items in the collection. + * @return {Number} the number of items in the collection. + */ + getCount : function(){ + return this.length; + }, + + getKey : function(obj){ + return obj.id; + }, + + /** + * Remove an item from the collection. + * @param {Object} obj The item to remove. + * @return {Object} The item removed or false if no item was removed. + */ + remove : function(obj){ + var me = this, + key = me.getKey(obj), + items = me.items, + index; + + if (me.map[key]) { + index = Ext.Array.indexOf(items, obj); + Ext.Array.erase(items, index, 1); + delete me.map[key]; + --me.length; + } + + return obj; + } +}); +/** + * This class represents a rectangular region in X,Y space, and performs geometric + * transformations or tests upon the region. + * + * This class may be used to compare the document regions occupied by elements. + */ +Ext.define('Ext.util.Region', { + + /* Begin Definitions */ + + requires: ['Ext.util.Offset'], + + statics: { + /** + * @static + * Retrieves an Ext.util.Region for a particular element. + * @param {String/HTMLElement/Ext.Element} el An element ID, htmlElement or Ext.Element representing an element in the document. + * @returns {Ext.util.Region} region + */ + getRegion: function(el) { + return Ext.fly(el).getPageBox(true); + }, + + /** + * @static + * Creates a Region from a "box" Object which contains four numeric properties `top`, `right`, `bottom` and `left`. + * @param {Object} o An object with `top`, `right`, `bottom` and `left` properties. + * @return {Ext.util.Region} region The Region constructed based on the passed object + */ + from: function(o) { + return new this(o.top, o.right, o.bottom, o.left); + } + }, + + /* End Definitions */ + + /** + * Creates a region from the bounding sides. + * @param {Number} top Top The topmost pixel of the Region. + * @param {Number} right Right The rightmost pixel of the Region. + * @param {Number} bottom Bottom The bottom pixel of the Region. + * @param {Number} left Left The leftmost pixel of the Region. + */ + constructor : function(t, r, b, l) { + var me = this; + me.y = me.top = me[1] = t; + me.right = r; + me.bottom = b; + me.x = me.left = me[0] = l; + }, + + /** + * Checks if this region completely contains the region that is passed in. + * @param {Ext.util.Region} region + * @return {Boolean} + */ + contains : function(region) { + var me = this; + return (region.x >= me.x && + region.right <= me.right && + region.y >= me.y && + region.bottom <= me.bottom); + + }, + + /** + * Checks if this region intersects the region passed in. + * @param {Ext.util.Region} region + * @return {Ext.util.Region/Boolean} Returns the intersected region or false if there is no intersection. + */ + intersect : function(region) { + var me = this, + t = Math.max(me.y, region.y), + r = Math.min(me.right, region.right), + b = Math.min(me.bottom, region.bottom), + l = Math.max(me.x, region.x); + + if (b > t && r > l) { + return new this.self(t, r, b, l); + } + else { + return false; + } + }, + + /** + * Returns the smallest region that contains the current AND targetRegion. + * @param {Ext.util.Region} region + * @return {Ext.util.Region} a new region + */ + union : function(region) { + var me = this, + t = Math.min(me.y, region.y), + r = Math.max(me.right, region.right), + b = Math.max(me.bottom, region.bottom), + l = Math.min(me.x, region.x); + + return new this.self(t, r, b, l); + }, + + /** + * Modifies the current region to be constrained to the targetRegion. + * @param {Ext.util.Region} targetRegion + * @return {Ext.util.Region} this + */ + constrainTo : function(r) { + var me = this, + constrain = Ext.Number.constrain; + me.top = me.y = constrain(me.top, r.y, r.bottom); + me.bottom = constrain(me.bottom, r.y, r.bottom); + me.left = me.x = constrain(me.left, r.x, r.right); + me.right = constrain(me.right, r.x, r.right); + return me; + }, + + /** + * Modifies the current region to be adjusted by offsets. + * @param {Number} top top offset + * @param {Number} right right offset + * @param {Number} bottom bottom offset + * @param {Number} left left offset + * @return {Ext.util.Region} this + */ + adjust : function(t, r, b, l) { + var me = this; + me.top = me.y += t; + me.left = me.x += l; + me.right += r; + me.bottom += b; + return me; + }, + + /** + * Get the offset amount of a point outside the region + * @param {String} [axis] + * @param {Ext.util.Point} [p] the point + * @return {Ext.util.Offset} + */ + getOutOfBoundOffset: function(axis, p) { + if (!Ext.isObject(axis)) { + if (axis == 'x') { + return this.getOutOfBoundOffsetX(p); + } else { + return this.getOutOfBoundOffsetY(p); + } + } else { + p = axis; + var d = new Ext.util.Offset(); + d.x = this.getOutOfBoundOffsetX(p.x); + d.y = this.getOutOfBoundOffsetY(p.y); + return d; + } + + }, + + /** + * Get the offset amount on the x-axis + * @param {Number} p the offset + * @return {Number} + */ + getOutOfBoundOffsetX: function(p) { + if (p <= this.x) { + return this.x - p; + } else if (p >= this.right) { + return this.right - p; + } + + return 0; + }, + + /** + * Get the offset amount on the y-axis + * @param {Number} p the offset + * @return {Number} + */ + getOutOfBoundOffsetY: function(p) { + if (p <= this.y) { + return this.y - p; + } else if (p >= this.bottom) { + return this.bottom - p; + } + + return 0; + }, + + /** + * Check whether the point / offset is out of bound + * @param {String} [axis] + * @param {Ext.util.Point/Number} [p] the point / offset + * @return {Boolean} + */ + isOutOfBound: function(axis, p) { + if (!Ext.isObject(axis)) { + if (axis == 'x') { + return this.isOutOfBoundX(p); + } else { + return this.isOutOfBoundY(p); + } + } else { + p = axis; + return (this.isOutOfBoundX(p.x) || this.isOutOfBoundY(p.y)); + } + }, + + /** + * Check whether the offset is out of bound in the x-axis + * @param {Number} p the offset + * @return {Boolean} + */ + isOutOfBoundX: function(p) { + return (p < this.x || p > this.right); + }, + + /** + * Check whether the offset is out of bound in the y-axis + * @param {Number} p the offset + * @return {Boolean} + */ + isOutOfBoundY: function(p) { + return (p < this.y || p > this.bottom); + }, + + /** + * Restrict a point within the region by a certain factor. + * @param {String} [axis] + * @param {Ext.util.Point/Ext.util.Offset/Object} [p] + * @param {Number} [factor] + * @return {Ext.util.Point/Ext.util.Offset/Object/Number} + * @private + */ + restrict: function(axis, p, factor) { + if (Ext.isObject(axis)) { + var newP; + + factor = p; + p = axis; + + if (p.copy) { + newP = p.copy(); + } + else { + newP = { + x: p.x, + y: p.y + }; + } + + newP.x = this.restrictX(p.x, factor); + newP.y = this.restrictY(p.y, factor); + return newP; + } else { + if (axis == 'x') { + return this.restrictX(p, factor); + } else { + return this.restrictY(p, factor); + } + } + }, + + /** + * Restrict an offset within the region by a certain factor, on the x-axis + * @param {Number} p + * @param {Number} [factor=1] The factor. + * @return {Number} + * @private + */ + restrictX : function(p, factor) { + if (!factor) { + factor = 1; + } + + if (p <= this.x) { + p -= (p - this.x) * factor; + } + else if (p >= this.right) { + p -= (p - this.right) * factor; + } + return p; + }, + + /** + * Restrict an offset within the region by a certain factor, on the y-axis + * @param {Number} p + * @param {Number} [factor] The factor, defaults to 1 + * @return {Number} + * @private + */ + restrictY : function(p, factor) { + if (!factor) { + factor = 1; + } + + if (p <= this.y) { + p -= (p - this.y) * factor; + } + else if (p >= this.bottom) { + p -= (p - this.bottom) * factor; + } + return p; + }, + + /** + * Get the width / height of this region + * @return {Object} an object with width and height properties + * @private + */ + getSize: function() { + return { + width: this.right - this.x, + height: this.bottom - this.y + }; + }, + + /** + * Create a copy of this Region. + * @return {Ext.util.Region} + */ + copy: function() { + return new this.self(this.y, this.right, this.bottom, this.x); + }, + + /** + * Copy the values of another Region to this Region + * @param {Ext.util.Region} p The region to copy from. + * @return {Ext.util.Region} This Region + */ + copyFrom: function(p) { + var me = this; + me.top = me.y = me[1] = p.y; + me.right = p.right; + me.bottom = p.bottom; + me.left = me.x = me[0] = p.x; + + return this; + }, + + /* + * Dump this to an eye-friendly string, great for debugging + * @return {String} + */ + toString: function() { + return "Region[" + this.top + "," + this.right + "," + this.bottom + "," + this.left + "]"; + }, + + /** + * Translate this region by the given offset amount + * @param {Ext.util.Offset/Object} x Object containing the `x` and `y` properties. + * Or the x value is using the two argument form. + * @param {Number} y The y value unless using an Offset object. + * @return {Ext.util.Region} this This Region + */ + translateBy: function(x, y) { + if (arguments.length == 1) { + y = x.y; + x = x.x; + } + var me = this; + me.top = me.y += y; + me.right += x; + me.bottom += y; + me.left = me.x += x; + + return me; + }, + + /** + * Round all the properties of this region + * @return {Ext.util.Region} this This Region + */ + round: function() { + var me = this; + me.top = me.y = Math.round(me.y); + me.right = Math.round(me.right); + me.bottom = Math.round(me.bottom); + me.left = me.x = Math.round(me.x); + + return me; + }, + + /** + * Check whether this region is equivalent to the given region + * @param {Ext.util.Region} region The region to compare with + * @return {Boolean} + */ + equals: function(region) { + return (this.top == region.top && this.right == region.right && this.bottom == region.bottom && this.left == region.left); + } +}); + +/** + * Given a component hierarchy of this: + * + * { + * xtype: 'panel', + * id: 'ContainerA', + * layout: 'hbox', + * renderTo: Ext.getBody(), + * items: [ + * { + * id: 'ContainerB', + * xtype: 'container', + * items: [ + * { id: 'ComponentA' } + * ] + * } + * ] + * } + * + * The rendering of the above proceeds roughly like this: + * + * - ContainerA's initComponent calls #render passing the `renderTo` property as the + * container argument. + * - `render` calls the `getRenderTree` method to get a complete {@link Ext.DomHelper} spec. + * - `getRenderTree` fires the "beforerender" event and calls the #beforeRender + * method. Its result is obtained by calling #getElConfig. + * - The #getElConfig method uses the `renderTpl` and its render data as the content + * of the `autoEl` described element. + * - The result of `getRenderTree` is passed to {@link Ext.DomHelper#append}. + * - The `renderTpl` contains calls to render things like docked items, container items + * and raw markup (such as the `html` or `tpl` config properties). These calls are to + * methods added to the {@link Ext.XTemplate} instance by #setupRenderTpl. + * - The #setupRenderTpl method adds methods such as `renderItems`, `renderContent`, etc. + * to the template. These are directed to "doRenderItems", "doRenderContent" etc.. + * - The #setupRenderTpl calls traverse from components to their {@link Ext.layout.Layout} + * object. + * - When a container is rendered, it also has a `renderTpl`. This is processed when the + * `renderContainer` method is called in the component's `renderTpl`. This call goes to + * Ext.layout.container.Container#doRenderContainer. This method repeats this + * process for all components in the container. + * - After the top-most component's markup is generated and placed in to the DOM, the next + * step is to link elements to their components and finish calling the component methods + * `onRender` and `afterRender` as well as fire the corresponding events. + * - The first step in this is to call #finishRender. This method descends the + * component hierarchy and calls `onRender` and fires the `render` event. These calls + * are delivered top-down to approximate the timing of these calls/events from previous + * versions. + * - During the pass, the component's `el` is set. Likewise, the `renderSelectors` and + * `childEls` are applied to capture references to the component's elements. + * - These calls are also made on the {@link Ext.layout.container.Container} layout to + * capture its elements. Both of these classes use {@link Ext.util.ElementContainer} to + * handle `childEls` processing. + * - Once this is complete, a similar pass is made by calling #finishAfterRender. + * This call also descends the component hierarchy, but this time the calls are made in + * a bottom-up order to `afterRender`. + * + * @private + */ +Ext.define('Ext.util.Renderable', { + requires: [ + 'Ext.dom.Element' + ], + + frameCls: Ext.baseCSSPrefix + 'frame', + + frameIdRegex: /[\-]frame\d+[TMB][LCR]$/, + + frameElementCls: { + tl: [], + tc: [], + tr: [], + ml: [], + mc: [], + mr: [], + bl: [], + bc: [], + br: [] + }, + + frameElNames: ['TL','TC','TR','ML','MC','MR','BL','BC','BR'], + + frameTpl: [ + '{%this.renderDockedItems(out,values,0);%}', + '', + '
    {parent.baseCls}-{parent.ui}-{.}-tl" style="background-position: {tl}; padding-left: {frameWidth}px" role="presentation">', + '
    {parent.baseCls}-{parent.ui}-{.}-tr" style="background-position: {tr}; padding-right: {frameWidth}px" role="presentation">', + '
    {parent.baseCls}-{parent.ui}-{.}-tc" style="background-position: {tc}; height: {frameWidth}px" role="presentation">
    ', + '
    ', + '
    ', + '
    ', + '
    {parent.baseCls}-{parent.ui}-{.}-ml" style="background-position: {ml}; padding-left: {frameWidth}px" role="presentation">', + '
    {parent.baseCls}-{parent.ui}-{.}-mr" style="background-position: {mr}; padding-right: {frameWidth}px" role="presentation">', + '
    {parent.baseCls}-{parent.ui}-{.}-mc" role="presentation">', + '{%this.applyRenderTpl(out, values)%}', + '
    ', + '
    ', + '
    ', + '', + '
    {parent.baseCls}-{parent.ui}-{.}-bl" style="background-position: {bl}; padding-left: {frameWidth}px" role="presentation">', + '
    {parent.baseCls}-{parent.ui}-{.}-br" style="background-position: {br}; padding-right: {frameWidth}px" role="presentation">', + '
    {parent.baseCls}-{parent.ui}-{.}-bc" style="background-position: {bc}; height: {frameWidth}px" role="presentation">
    ', + '
    ', + '
    ', + '
    ', + '{%this.renderDockedItems(out,values,1);%}' + ], + + frameTableTpl: [ + '{%this.renderDockedItems(out,values,0);%}', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '
    {parent.baseCls}-{parent.ui}-{.}-tl" style="background-position: {tl}; padding-left:{frameWidth}px" role="presentation"> {parent.baseCls}-{parent.ui}-{.}-tc" style="background-position: {tc}; height: {frameWidth}px" role="presentation"> {parent.baseCls}-{parent.ui}-{.}-tr" style="background-position: {tr}; padding-left: {frameWidth}px" role="presentation">
    {parent.baseCls}-{parent.ui}-{.}-ml" style="background-position: {ml}; padding-left: {frameWidth}px" role="presentation"> {parent.baseCls}-{parent.ui}-{.}-mc" style="background-position: 0 0;" role="presentation">', + '{%this.applyRenderTpl(out, values)%}', + ' {parent.baseCls}-{parent.ui}-{.}-mr" style="background-position: {mr}; padding-left: {frameWidth}px" role="presentation">
    {parent.baseCls}-{parent.ui}-{.}-bl" style="background-position: {bl}; padding-left: {frameWidth}px" role="presentation"> {parent.baseCls}-{parent.ui}-{.}-bc" style="background-position: {bc}; height: {frameWidth}px" role="presentation"> {parent.baseCls}-{parent.ui}-{.}-br" style="background-position: {br}; padding-left: {frameWidth}px" role="presentation">
    ', + '{%this.renderDockedItems(out,values,1);%}' + ], + + /** + * Allows addition of behavior after rendering is complete. At this stage the Component’s Element + * will have been styled according to the configuration, will have had any configured CSS class + * names added, and will be in the configured visibility and the configured enable state. + * + * @template + * @protected + */ + afterRender : function() { + var me = this, + data = {}, + protoEl = me.protoEl, + target = me.getTargetEl(), + item; + + me.finishRenderChildren(); + + if (me.styleHtmlContent) { + target.addCls(me.styleHtmlCls); + } + + protoEl.writeTo(data); + + // Here we apply any styles that were set on the protoEl during the rendering phase + // A majority of times this will not happen, but we still need to handle it + + item = data.removed; + if (item) { + target.removeCls(item); + } + + item = data.cls; + if (item.length) { + target.addCls(item); + } + + item = data.style; + if (data.style) { + target.setStyle(item); + } + + me.protoEl = null; + + // If this is the outermost Container, lay it out as soon as it is rendered. + if (!me.ownerCt) { + me.updateLayout(); + } + }, + + afterFirstLayout : function(width, height) { + var me = this, + hasX = Ext.isDefined(me.x), + hasY = Ext.isDefined(me.y), + pos, xy; + + // For floaters, calculate x and y if they aren't defined by aligning + // the sized element to the center of either the container or the ownerCt + if (me.floating && (!hasX || !hasY)) { + if (me.floatParent) { + xy = me.el.getAlignToXY(me.floatParent.getTargetEl(), 'c-c'); + pos = me.floatParent.getTargetEl().translatePoints(xy[0], xy[1]); + } else { + xy = me.el.getAlignToXY(me.container, 'c-c'); + pos = me.container.translatePoints(xy[0], xy[1]); + } + me.x = hasX ? me.x : pos.left; + me.y = hasY ? me.y : pos.top; + hasX = hasY = true; + } + + if (hasX || hasY) { + me.setPosition(me.x, me.y); + } + me.onBoxReady(width, height); + if (me.hasListeners.boxready) { + me.fireEvent('boxready', me, width, height); + } + }, + + onBoxReady: Ext.emptyFn, + + /** + * Sets references to elements inside the component. This applies {@link #renderSelectors} + * as well as {@link #childEls}. + * @private + */ + applyRenderSelectors: function() { + var me = this, + selectors = me.renderSelectors, + el = me.el, + dom = el.dom, + selector; + + me.applyChildEls(el); + + // We still support renderSelectors. There are a few places in the framework that + // need them and they are a documented part of the API. In fact, we support mixing + // childEls and renderSelectors (no reason not to). + if (selectors) { + for (selector in selectors) { + if (selectors.hasOwnProperty(selector) && selectors[selector]) { + me[selector] = Ext.get(Ext.DomQuery.selectNode(selectors[selector], dom)); + } + } + } + }, + + beforeRender: function () { + var me = this, + target = me.getTargetEl(), + layout = me.getComponentLayout(); + + // Just before rendering, set the frame flag if we are an always-framed component like Window or Tip. + me.frame = me.frame || me.alwaysFramed; + + if (!layout.initialized) { + layout.initLayout(); + } + + // Attempt to set overflow style prior to render if the targetEl can be accessed. + // If the targetEl does not exist yet, this will take place in finishRender + if (target) { + target.setStyle(me.getOverflowStyle()); + me.overflowStyleSet = true; + } + + me.setUI(me.ui); + + if (me.disabled) { + // pass silent so the event doesn't fire the first time. + me.disable(true); + } + }, + + /** + * @private + * Called from the selected frame generation template to insert this Component's inner structure inside the framing structure. + * + * When framing is used, a selected frame generation template is used as the primary template of the #getElConfig instead + * of the configured {@link #renderTpl}. The {@link #renderTpl} is invoked by this method which is injected into the framing template. + */ + doApplyRenderTpl: function(out, values) { + // Careful! This method is bolted on to the frameTpl so all we get for context is + // the renderData! The "this" pointer is the frameTpl instance! + + var me = values.$comp, + tpl; + + // Don't do this if the component is already rendered: + if (!me.rendered) { + tpl = me.initRenderTpl(); + tpl.applyOut(values.renderData, out); + } + }, + + /** + * Handles autoRender. + * Floating Components may have an ownerCt. If they are asking to be constrained, constrain them within that + * ownerCt, and have their z-index managed locally. Floating Components are always rendered to document.body + */ + doAutoRender: function() { + var me = this; + if (!me.rendered) { + if (me.floating) { + me.render(document.body); + } else { + me.render(Ext.isBoolean(me.autoRender) ? Ext.getBody() : me.autoRender); + } + } + }, + + doRenderContent: function (out, renderData) { + // Careful! This method is bolted on to the renderTpl so all we get for context is + // the renderData! The "this" pointer is the renderTpl instance! + + var me = renderData.$comp; + + if (me.html) { + Ext.DomHelper.generateMarkup(me.html, out); + delete me.html; + } + + if (me.tpl) { + // Make sure this.tpl is an instantiated XTemplate + if (!me.tpl.isTemplate) { + me.tpl = new Ext.XTemplate(me.tpl); + } + + if (me.data) { + //me.tpl[me.tplWriteMode](target, me.data); + me.tpl.applyOut(me.data, out); + delete me.data; + } + } + }, + + doRenderFramingDockedItems: function (out, renderData, after) { + // Careful! This method is bolted on to the frameTpl so all we get for context is + // the renderData! The "this" pointer is the frameTpl instance! + + var me = renderData.$comp; + + // Most components don't have dockedItems, so check for doRenderDockedItems on the + // component (also, don't do this if the component is already rendered): + if (!me.rendered && me.doRenderDockedItems) { + // The "renderData" property is placed in scope for the renderTpl, but we don't + // want to render docked items at that level in addition to the framing level: + renderData.renderData.$skipDockedItems = true; + + // doRenderDockedItems requires the $comp property on renderData, but this is + // set on the frameTpl's renderData as well: + me.doRenderDockedItems.call(this, out, renderData, after); + } + }, + + /** + * This method visits the rendered component tree in a "top-down" order. That is, this + * code runs on a parent component before running on a child. This method calls the + * {@link #onRender} method of each component. + * @param {Number} containerIdx The index into the Container items of this Component. + * + * @private + */ + finishRender: function(containerIdx) { + var me = this, + tpl, data, contentEl, el, pre, hide; + + // We are typically called w/me.el==null as a child of some ownerCt that is being + // rendered. We are also called by render for a normal component (w/o a configured + // me.el). In this case, render sets me.el and me.rendering (indirectly). Lastly + // we are also called on a component (like a Viewport) that has a configured me.el + // (body for a Viewport) when render is called. In this case, it is not flagged as + // "me.rendering" yet becasue it does not produce a renderTree. We use this to know + // not to regen the renderTpl. + + if (!me.el || me.$pid) { + if (me.container) { + el = me.container.getById(me.id, true); + } else { + el = Ext.getDom(me.id); + } + + if (!me.el) { + // Typical case: we produced the el during render + me.wrapPrimaryEl(el); + } else { + // We were configured with an el and created a proxy, so now we can swap + // the proxy for me.el: + delete me.$pid; + + if (!me.el.dom) { + // make sure me.el is an Element + me.wrapPrimaryEl(me.el); + } + el.parentNode.insertBefore(me.el.dom, el); + Ext.removeNode(el); // remove placeholder el + // TODO - what about class/style? + } + } else if (!me.rendering) { + // We were configured with an el and then told to render (e.g., Viewport). We + // need to generate the proper DOM. Insert first because the layout system + // insists that child Component elements indices match the Component indices. + tpl = me.initRenderTpl(); + if (tpl) { + data = me.initRenderData(); + tpl.insertFirst(me.getTargetEl(), data); + } + } + // else we are rendering + + if (!me.container) { + // top-level rendered components will already have me.container set up + me.container = Ext.get(me.el.dom.parentNode); + } + + if (me.ctCls) { + me.container.addCls(me.ctCls); + } + + // Sets the rendered flag and clears the redering flag + me.onRender(me.container, containerIdx); + + // If we could not access a target protoEl in bewforeRender, we have to set the overflow styles here. + if (!me.overflowStyleSet) { + me.getTargetEl().setStyle(me.getOverflowStyle()); + } + + // Tell the encapsulating element to hide itself in the way the Component is configured to hide + // This means DISPLAY, VISIBILITY or OFFSETS. + me.el.setVisibilityMode(Ext.Element[me.hideMode.toUpperCase()]); + + if (me.overCls) { + me.el.hover(me.addOverCls, me.removeOverCls, me); + } + + if (me.hasListeners.render) { + me.fireEvent('render', me); + } + + if (me.contentEl) { + pre = Ext.baseCSSPrefix; + hide = pre + 'hide-'; + contentEl = Ext.get(me.contentEl); + contentEl.removeCls([pre+'hidden', hide+'display', hide+'offsets', hide+'nosize']); + me.getTargetEl().appendChild(contentEl.dom); + } + + me.afterRender(); // this can cause a layout + if (me.hasListeners.afterrender) { + me.fireEvent('afterrender', me); + } + me.initEvents(); + + if (me.hidden) { + // Hiding during the render process should not perform any ancillary + // actions that the full hide process does; It is not hiding, it begins in a hidden state.' + // So just make the element hidden according to the configured hideMode + me.el.hide(); + } + }, + + finishRenderChildren: function () { + var layout = this.getComponentLayout(); + + layout.finishRender(); + }, + + getElConfig : function() { + var me = this, + autoEl = me.autoEl, + frameInfo = me.getFrameInfo(), + config = { + tag: 'div', + id: me.id, + tpl: frameInfo ? me.initFramingTpl(frameInfo.table) : me.initRenderTpl() + }, + i, frameElNames, len, suffix, frameGenId; + + me.initStyles(me.protoEl); + me.protoEl.writeTo(config); + me.protoEl.flush(); + + if (Ext.isString(autoEl)) { + config.tag = autoEl; + } else { + Ext.apply(config, autoEl); // harmless if !autoEl + } + + if (config.tpl) { + // Use the framingTpl as the main content creating template. It will call out to this.applyRenderTpl(out, values) + if (frameInfo) { + frameElNames = me.frameElNames; + len = frameElNames.length; + frameGenId = me.id + '-frame1'; + + me.frameGenId = 1; + config.tplData = Ext.apply({}, { + $comp: me, + fgid: frameGenId, + ui: me.ui, + uiCls: me.uiCls, + frameCls: me.frameCls, + baseCls: me.baseCls, + frameWidth: frameInfo.maxWidth, + top: !!frameInfo.top, + left: !!frameInfo.left, + right: !!frameInfo.right, + bottom: !!frameInfo.bottom, + renderData: me.initRenderData() + }, me.getFramePositions(frameInfo)); + + // Add the childEls for each of the frame elements + for (i = 0; i < len; i++) { + suffix = frameElNames[i]; + me.addChildEls({ name: 'frame' + suffix, id: frameGenId + suffix }); + } + + // Panel must have a frameBody + me.addChildEls({ + name: 'frameBody', + id: frameGenId + 'MC' + }); + } else { + config.tplData = me.initRenderData(); + } + } + + return config; + }, + + // Create the framingTpl from the string. + // Poke in a reference to applyRenderTpl(frameInfo, out) + initFramingTpl: function(table) { + var tpl = table ? this.getTpl('frameTableTpl') : this.getTpl('frameTpl'); + + if (tpl && !tpl.applyRenderTpl) { + this.setupFramingTpl(tpl); + } + + return tpl; + }, + + /** + * @private + * Inject a reference to the function which applies the render template into the framing template. The framing template + * wraps the content. + */ + setupFramingTpl: function(frameTpl) { + frameTpl.applyRenderTpl = this.doApplyRenderTpl; + frameTpl.renderDockedItems = this.doRenderFramingDockedItems; + }, + + /** + * This function takes the position argument passed to onRender and returns a + * DOM element that you can use in the insertBefore. + * @param {String/Number/Ext.dom.Element/HTMLElement} position Index, element id or element you want + * to put this component before. + * @return {HTMLElement} DOM element that you can use in the insertBefore + */ + getInsertPosition: function(position) { + // Convert the position to an element to insert before + if (position !== undefined) { + if (Ext.isNumber(position)) { + position = this.container.dom.childNodes[position]; + } + else { + position = Ext.getDom(position); + } + } + + return position; + }, + + getRenderTree: function() { + var me = this; + + if (!me.hasListeners.beforerender || me.fireEvent('beforerender', me) !== false) { + me.beforeRender(); + + // Flag to let the layout's finishRenderItems and afterFinishRenderItems + // know which items to process + me.rendering = true; + + if (me.el) { + // Since we are producing a render tree, we produce a "proxy el" that will + // sit in the rendered DOM precisely where me.el belongs. We replace the + // proxy el in the finishRender phase. + return { + tag: 'div', + id: (me.$pid = Ext.id()) + }; + } + + return me.getElConfig(); + } + + return null; + }, + + initContainer: function(container) { + var me = this; + + // If you render a component specifying the el, we get the container + // of the el, and make sure we dont move the el around in the dom + // during the render + if (!container && me.el) { + container = me.el.dom.parentNode; + me.allowDomMove = false; + } + me.container = container.dom ? container : Ext.get(container); + + return me.container; + }, + + /** + * Initialized the renderData to be used when rendering the renderTpl. + * @return {Object} Object with keys and values that are going to be applied to the renderTpl + * @private + */ + initRenderData: function() { + var me = this; + + return Ext.apply({ + $comp: me, + id: me.id, + ui: me.ui, + uiCls: me.uiCls, + baseCls: me.baseCls, + componentCls: me.componentCls, + frame: me.frame + }, me.renderData); + }, + + /** + * Initializes the renderTpl. + * @return {Ext.XTemplate} The renderTpl XTemplate instance. + * @private + */ + initRenderTpl: function() { + var tpl = this.getTpl('renderTpl'); + + if (tpl && !tpl.renderContent) { + this.setupRenderTpl(tpl); + } + + return tpl; + }, + + /** + * Template method called when this Component's DOM structure is created. + * + * At this point, this Component's (and all descendants') DOM structure *exists* but it has not + * been layed out (positioned and sized). + * + * Subclasses which override this to gain access to the structure at render time should + * call the parent class's method before attempting to access any child elements of the Component. + * + * @param {Ext.core.Element} parentNode The parent Element in which this Component's encapsulating element is contained. + * @param {Number} containerIdx The index within the parent Container's child collection of this Component. + * + * @template + * @protected + */ + onRender: function(parentNode, containerIdx) { + var me = this, + x = me.x, + y = me.y, + lastBox, width, height, + el = me.el; + + // After the container property has been collected, we can wrap the Component in a reset wraper if necessary + if (Ext.scopeResetCSS && !me.ownerCt) { + // If this component's el is the body element, we add the reset class to the html tag + if (el.dom == Ext.getBody().dom) { + el.parent().addCls(Ext.resetCls); + } + else { + // Else we wrap this element in an element that adds the reset class. + me.resetEl = el.wrap({ + cls: Ext.resetCls + }); + } + } + + me.applyRenderSelectors(); + + // Flag set on getRenderTree to flag to the layout's postprocessing routine that + // the Component is in the process of being rendered and needs postprocessing. + delete me.rendering; + + me.rendered = true; + + // We need to remember these to avoid writing them during the initial layout: + lastBox = null; + + if (x !== undefined) { + lastBox = lastBox || {}; + lastBox.x = x; + } + if (y !== undefined) { + lastBox = lastBox || {}; + lastBox.y = y; + } + // Framed components need their width/height to apply to the frame, which is + // best handled in layout at present. + // If we're using the content box model, we also cannot assign initial sizes since we do not know the border widths to subtract + if (!me.getFrameInfo() && Ext.isBorderBox) { + width = me.width; + height = me.height; + + if (typeof width == 'number') { + lastBox = lastBox || {}; + lastBox.width = width; + } + if (typeof height == 'number') { + lastBox = lastBox || {}; + lastBox.height = height; + } + } + + me.lastBox = me.el.lastBox = lastBox; + }, + + render: function(container, position) { + var me = this, + el = me.el && (me.el = Ext.get(me.el)), // ensure me.el is wrapped + tree, + nextSibling; + + Ext.suspendLayouts(); + + container = me.initContainer(container); + + nextSibling = me.getInsertPosition(position); + + if (!el) { + tree = me.getRenderTree(); + + // tree will be null if a beforerender listener returns false + if (tree) { + if (nextSibling) { + el = Ext.DomHelper.insertBefore(nextSibling, tree); + } else { + el = Ext.DomHelper.append(container, tree); + } + + me.wrapPrimaryEl(el); + } + } else { + // Set configured styles on pre-rendered Component's element + me.initStyles(el); + if (me.allowDomMove !== false) { + //debugger; // TODO + if (nextSibling) { + container.dom.insertBefore(el.dom, nextSibling); + } else { + container.dom.appendChild(el.dom); + } + } + } + + if (el) { + me.finishRender(position); + } + + Ext.resumeLayouts(!container.isDetachedBody); + }, + + /** + * Ensures that this component is attached to `document.body`. If the component was + * rendered to {@link Ext#getDetachedBody}, then it will be appended to `document.body`. + * Any configured position is also restored. + * @param {Boolean} [runLayout=false] True to run the component's layout. + */ + ensureAttachedToBody: function (runLayout) { + var comp = this, + body; + + while (comp.ownerCt) { + comp = comp.ownerCt; + } + + if (comp.container.isDetachedBody) { + comp.container = body = Ext.getBody(); + body.appendChild(comp.el.dom); + if (runLayout) { + comp.updateLayout(); + } + if (typeof comp.x == 'number' || typeof comp.y == 'number') { + comp.setPosition(comp.x, comp.y); + } + } + }, + + setupRenderTpl: function (renderTpl) { + renderTpl.renderBody = renderTpl.renderContent = this.doRenderContent; + }, + + wrapPrimaryEl: function (dom) { + this.el = Ext.get(dom, true); + }, + + /** + * @private + */ + initFrame : function() { + if (Ext.supports.CSS3BorderRadius || !this.frame) { + return; + } + + var me = this, + frameInfo = me.getFrameInfo(), + frameWidth, frameTpl, frameGenId, + i, + frameElNames = me.frameElNames, + len = frameElNames.length, + suffix; + + if (frameInfo) { + frameWidth = frameInfo.maxWidth; + frameTpl = me.getFrameTpl(frameInfo.table); + + // since we render id's into the markup and id's NEED to be unique, we have a + // simple strategy for numbering their generations. + me.frameGenId = frameGenId = (me.frameGenId || 0) + 1; + frameGenId = me.id + '-frame' + frameGenId; + + // Here we render the frameTpl to this component. This inserts the 9point div or the table framing. + frameTpl.insertFirst(me.el, Ext.apply({ + $comp: me, + fgid: frameGenId, + ui: me.ui, + uiCls: me.uiCls, + frameCls: me.frameCls, + baseCls: me.baseCls, + frameWidth: frameWidth, + top: !!frameInfo.top, + left: !!frameInfo.left, + right: !!frameInfo.right, + bottom: !!frameInfo.bottom + }, me.getFramePositions(frameInfo))); + + // The frameBody is returned in getTargetEl, so that layouts render items to the correct target. + me.frameBody = me.el.down('.' + me.frameCls + '-mc'); + + // Clean out the childEls for the old frame elements (the majority of the els) + me.removeChildEls(function (c) { + return c.id && me.frameIdRegex.test(c.id); + }); + + // Grab references to the childEls for each of the new frame elements + for (i = 0; i < len; i++) { + suffix = frameElNames[i]; + me['frame' + suffix] = me.el.getById(frameGenId + suffix); + } + } + }, + + updateFrame: function() { + if (Ext.supports.CSS3BorderRadius || !this.frame) { + return; + } + + var me = this, + wasTable = this.frameSize && this.frameSize.table, + oldFrameTL = this.frameTL, + oldFrameBL = this.frameBL, + oldFrameML = this.frameML, + oldFrameMC = this.frameMC, + newMCClassName; + + this.initFrame(); + + if (oldFrameMC) { + if (me.frame) { + + // Store the class names set on the new MC + newMCClassName = this.frameMC.dom.className; + + // Framing elements have been selected in initFrame, no need to run applyRenderSelectors + // Replace the new mc with the old mc + oldFrameMC.insertAfter(this.frameMC); + this.frameMC.remove(); + + // Restore the reference to the old frame mc as the framebody + this.frameBody = this.frameMC = oldFrameMC; + + // Apply the new mc classes to the old mc element + oldFrameMC.dom.className = newMCClassName; + + // Remove the old framing + if (wasTable) { + me.el.query('> table')[1].remove(); + } + else { + if (oldFrameTL) { + oldFrameTL.remove(); + } + if (oldFrameBL) { + oldFrameBL.remove(); + } + if (oldFrameML) { + oldFrameML.remove(); + } + } + } + } + else if (me.frame) { + this.applyRenderSelectors(); + } + }, + + /** + * @private + * On render, reads an encoded style attribute, "background-position" from the style of this Component's element. + * This information is memoized based upon the CSS class name of this Component's element. + * Because child Components are rendered as textual HTML as part of the topmost Container, a dummy div is inserted + * into the document to receive the document element's CSS class name, and therefore style attributes. + */ + getFrameInfo: function() { + // If native framing can be used, or this component is not going to be framed, then do not attempt to read CSS framing info. + if (Ext.supports.CSS3BorderRadius || !this.frame) { + return false; + } + + var me = this, + frameInfoCache = me.frameInfoCache, + el = me.el || me.protoEl, + cls = el.dom ? el.dom.className : el.classList.join(' '), + frameInfo = frameInfoCache[cls], + styleEl, left, top, info; + + if (frameInfo == null) { + // Get the singleton frame style proxy with our el class name stamped into it. + styleEl = Ext.fly(me.getStyleProxy(cls), 'frame-style-el'); + left = styleEl.getStyle('background-position-x'); + top = styleEl.getStyle('background-position-y'); + + // Some browsers don't support background-position-x and y, so for those + // browsers let's split background-position into two parts. + if (!left && !top) { + info = styleEl.getStyle('background-position').split(' '); + left = info[0]; + top = info[1]; + } + + frameInfo = me.calculateFrame(left, top); + + if (frameInfo) { + // Just to be sure we set the background image of the el to none. + el.setStyle('background-image', 'none'); + } + + // This happens when you set frame: true explicitly without using the x-frame mixin in sass. + // This way IE can't figure out what sizes to use and thus framing can't work. + if (me.frame === true && !frameInfo) { + Ext.log.error('You have set frame: true explicity on this component (' + me.getXType() + ') and it ' + + 'does not have any framing defined in the CSS template. In this case IE cannot figure out ' + + 'what sizes to use and thus framing on this component will be disabled.'); + } + + frameInfoCache[cls] = frameInfo; + } + + me.frame = !!frameInfo; + me.frameSize = frameInfo; + + return frameInfo; + }, + + calculateFrame: function(left, top){ + // We actually pass a string in the form of '[type][tl][tr]px [direction][br][bl]px' as + // the background position of this.el from the CSS to indicate to IE that this component needs + // framing. We parse it here. + if (!(parseInt(left, 10) >= 1000000 && parseInt(top, 10) >= 1000000)) { + return false; + } + var max = Math.max, + tl = parseInt(left.substr(3, 2), 10), + tr = parseInt(left.substr(5, 2), 10), + br = parseInt(top.substr(3, 2), 10), + bl = parseInt(top.substr(5, 2), 10), + frameInfo = { + // Table markup starts with 110, div markup with 100. + table: left.substr(0, 3) == '110', + + // Determine if we are dealing with a horizontal or vertical component + vertical: top.substr(0, 3) == '110', + + // Get and parse the different border radius sizes + top: max(tl, tr), + right: max(tr, br), + bottom: max(bl, br), + left: max(tl, bl) + }; + + frameInfo.maxWidth = max(frameInfo.top, frameInfo.right, frameInfo.bottom, frameInfo.left); + frameInfo.width = frameInfo.left + frameInfo.right; + frameInfo.height = frameInfo.top + frameInfo.bottom; + return frameInfo; + }, + + /** + * @private + * Returns an offscreen div with the same class name as the element this is being rendered. + * This is because child item rendering takes place in a detached div which, being not part of the document, has no styling. + */ + getStyleProxy: function(cls) { + var result = this.styleProxyEl || (Ext.AbstractComponent.prototype.styleProxyEl = Ext.getBody().createChild({ + style: { + position: 'absolute', + top: '-10000px' + } + }, null, true)); + + result.className = cls; + return result; + }, + + getFramePositions: function(frameInfo) { + var me = this, + frameWidth = frameInfo.maxWidth, + dock = me.dock, + positions, tc, bc, ml, mr; + + if (frameInfo.vertical) { + tc = '0 -' + (frameWidth * 0) + 'px'; + bc = '0 -' + (frameWidth * 1) + 'px'; + + if (dock && dock == "right") { + tc = 'right -' + (frameWidth * 0) + 'px'; + bc = 'right -' + (frameWidth * 1) + 'px'; + } + + positions = { + tl: '0 -' + (frameWidth * 0) + 'px', + tr: '0 -' + (frameWidth * 1) + 'px', + bl: '0 -' + (frameWidth * 2) + 'px', + br: '0 -' + (frameWidth * 3) + 'px', + + ml: '-' + (frameWidth * 1) + 'px 0', + mr: 'right 0', + + tc: tc, + bc: bc + }; + } else { + ml = '-' + (frameWidth * 0) + 'px 0'; + mr = 'right 0'; + + if (dock && dock == "bottom") { + ml = 'left bottom'; + mr = 'right bottom'; + } + + positions = { + tl: '0 -' + (frameWidth * 2) + 'px', + tr: 'right -' + (frameWidth * 3) + 'px', + bl: '0 -' + (frameWidth * 4) + 'px', + br: 'right -' + (frameWidth * 5) + 'px', + + ml: ml, + mr: mr, + + tc: '0 -' + (frameWidth * 0) + 'px', + bc: '0 -' + (frameWidth * 1) + 'px' + }; + } + + return positions; + }, + + /** + * @private + */ + getFrameTpl : function(table) { + return this.getTpl(table ? 'frameTableTpl' : 'frameTpl'); + }, + + // Cache the frame information object so as not to cause style recalculations + frameInfoCache: {} +}); + +/** + * Represents a single sorter that can be applied to a Store. The sorter is used + * to compare two values against each other for the purpose of ordering them. Ordering + * is achieved by specifying either: + * + * - {@link #property A sorting property} + * - {@link #sorterFn A sorting function} + * + * As a contrived example, we can specify a custom sorter that sorts by rank: + * + * Ext.define('Person', { + * extend: 'Ext.data.Model', + * fields: ['name', 'rank'] + * }); + * + * Ext.create('Ext.data.Store', { + * model: 'Person', + * proxy: 'memory', + * sorters: [{ + * sorterFn: function(o1, o2){ + * var getRank = function(o){ + * var name = o.get('rank'); + * if (name === 'first') { + * return 1; + * } else if (name === 'second') { + * return 2; + * } else { + * return 3; + * } + * }, + * rank1 = getRank(o1), + * rank2 = getRank(o2); + * + * if (rank1 === rank2) { + * return 0; + * } + * + * return rank1 < rank2 ? -1 : 1; + * } + * }], + * data: [{ + * name: 'Person1', + * rank: 'second' + * }, { + * name: 'Person2', + * rank: 'third' + * }, { + * name: 'Person3', + * rank: 'first' + * }] + * }); + */ +Ext.define('Ext.util.Sorter', { + + /** + * @cfg {String} property + * The property to sort by. Required unless {@link #sorterFn} is provided. The property is extracted from the object + * directly and compared for sorting using the built in comparison operators. + */ + + /** + * @cfg {Function} sorterFn + * A specific sorter function to execute. Can be passed instead of {@link #property}. This sorter function allows + * for any kind of custom/complex comparisons. The sorterFn receives two arguments, the objects being compared. The + * function should return: + * + * - -1 if o1 is "less than" o2 + * - 0 if o1 is "equal" to o2 + * - 1 if o1 is "greater than" o2 + */ + + /** + * @cfg {String} root + * Optional root property. This is mostly useful when sorting a Store, in which case we set the root to 'data' to + * make the filter pull the {@link #property} out of the data object of each item + */ + + /** + * @cfg {Function} transform + * A function that will be run on each value before it is compared in the sorter. The function will receive a single + * argument, the value. + */ + + /** + * @cfg {String} direction + * The direction to sort by. + */ + direction: "ASC", + + constructor: function(config) { + var me = this; + + Ext.apply(me, config); + + if (me.property === undefined && me.sorterFn === undefined) { + Ext.Error.raise("A Sorter requires either a property or a sorter function"); + } + + me.updateSortFunction(); + }, + + /** + * @private + * Creates and returns a function which sorts an array by the given property and direction + * @return {Function} A function which sorts by the property/direction combination provided + */ + createSortFunction: function(sorterFn) { + var me = this, + property = me.property, + direction = me.direction || "ASC", + modifier = direction.toUpperCase() == "DESC" ? -1 : 1; + + //create a comparison function. Takes 2 objects, returns 1 if object 1 is greater, + //-1 if object 2 is greater or 0 if they are equal + return function(o1, o2) { + return modifier * sorterFn.call(me, o1, o2); + }; + }, + + /** + * @private + * Basic default sorter function that just compares the defined property of each object + */ + defaultSorterFn: function(o1, o2) { + var me = this, + transform = me.transform, + v1 = me.getRoot(o1)[me.property], + v2 = me.getRoot(o2)[me.property]; + + if (transform) { + v1 = transform(v1); + v2 = transform(v2); + } + + return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0); + }, + + /** + * @private + * Returns the root property of the given item, based on the configured {@link #root} property + * @param {Object} item The item + * @return {Object} The root property of the object + */ + getRoot: function(item) { + return this.root === undefined ? item : item[this.root]; + }, + + /** + * Set the sorting direction for this sorter. + * @param {String} direction The direction to sort in. Should be either 'ASC' or 'DESC'. + */ + setDirection: function(direction) { + var me = this; + me.direction = direction; + me.updateSortFunction(); + }, + + /** + * Toggles the sorting direction for this sorter. + */ + toggle: function() { + var me = this; + me.direction = Ext.String.toggle(me.direction, "ASC", "DESC"); + me.updateSortFunction(); + }, + + /** + * Update the sort function for this sorter. + * @param {Function} [fn] A new sorter function for this sorter. If not specified it will use the default + * sorting function. + */ + updateSortFunction: function(fn) { + var me = this; + fn = fn || me.sorterFn || me.defaultSorterFn; + me.sort = me.createSortFunction(fn); + } +}); +/** + * 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.Toolbar}, + * {@link Ext.button.Button} and {@link Ext.menu.Menu} components). + * + * Use a single Action instance as the config object for any number of UI Components which share the same configuration. The + * Action not only supplies the configuration, but allows all Components based upon it to have a common set of methods + * called at once through a single call to the Action. + * + * Any Component that is to be configured with an Action must also support + * the following methods: + * + * - setText(string) + * - setIconCls(string) + * - setDisabled(boolean) + * - setVisible(boolean) + * - setHandler(function) + * + * This allows the Action to control its associated Components. + * + * 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.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.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'); + */ +Ext.define('Ext.Action', { + + /* Begin Definitions */ + + /* End Definitions */ + + /** + * @cfg {String} [text=''] + * The text to set for all components configured by this Action. + */ + /** + * @cfg {String} [iconCls=''] + * The CSS class selector that specifies a background image to be used as the header icon for + * all components configured by this Action. + * + * 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=false] + * True to disable all components configured by this Action, false to enable them. + */ + /** + * @cfg {Boolean} [hidden=false] + * True to hide all components configured by this Action, false to show them. + */ + /** + * @cfg {Function} handler + * The function that will be invoked by each component tied to this Action + * when the component's primary event is triggered. + */ + /** + * @cfg {String} itemId + * See {@link Ext.Component}.{@link Ext.Component#itemId itemId}. + */ + /** + * @cfg {Object} scope + * The scope (this reference) in which the {@link #handler} is executed. + * Defaults to the browser window. + */ + + /** + * Creates new Action. + * @param {Object} config Config object. + */ + constructor : function(config){ + this.initialConfig = config; + this.itemId = config.itemId = (config.itemId || config.id || Ext.id()); + this.items = []; + }, + + /* + * @property {Boolean} isAction + * `true` in this class to identify an object as an instantiated Action, or subclass thereof. + */ + isAction : true, + + /** + * Sets the text to be displayed by all components configured by 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 configured by this Action. + */ + getText : function(){ + return this.initialConfig.text; + }, + + /** + * Sets the icon CSS class for all components configured by 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 + */ + setIconCls : function(cls){ + this.initialConfig.iconCls = cls; + this.callEach('setIconCls', [cls]); + }, + + /** + * Gets the icon CSS class currently used by all components configured by this Action. + */ + getIconCls : function(){ + return this.initialConfig.iconCls; + }, + + /** + * Sets the disabled state of all components configured by 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 configured by this Action. + */ + enable : function(){ + this.setDisabled(false); + }, + + /** + * Disables all components configured by 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 configured by 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 configured by this Action. + */ + show : function(){ + this.setHidden(false); + }, + + /** + * Hides all components configured by this Action. + */ + hide : function(){ + this.setHidden(true); + }, + + /** + * Returns true if the components configured by 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 (this reference) in which the function is executed. Defaults to the Component + * firing the event. + */ + setHandler : function(fn, scope){ + this.initialConfig.handler = fn; + this.initialConfig.scope = scope; + this.callEach('setHandler', [fn, scope]); + }, + + /** + * Executes the specified function once for each Component currently tied to this Action. The function passed + * in should accept a single argument that will be an object that supports the basic Action config/method interface. + * @param {Function} fn The function to execute for each component + * @param {Object} scope The scope (this reference) in which the function is executed. + * Defaults to the Component. + */ + each : function(fn, scope){ + Ext.each(this.items, fn, scope); + }, + + // private + callEach : function(fnName, args){ + var items = this.items, + i = 0, + len = items.length; + + for(; i < len; i++){ + items[i][fnName].apply(items[i], args); + } + }, + + // private + addComponent : function(comp){ + this.items.push(comp); + comp.on('destroy', this.removeComponent, this); + }, + + // private + removeComponent : function(comp){ + Ext.Array.remove(this.items, 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 {Object...} args Variable number of arguments passed to the handler function + */ + execute : function(){ + this.initialConfig.handler.apply(this.initialConfig.scope || Ext.global, arguments); + } +}); + +/** + * An extended {@link Ext.Element} object that supports a shadow and shim, constrain to viewport and + * automatic maintaining of shadow/shim positions. + */ +Ext.define('Ext.Layer', { + extend: 'Ext.Element', + uses: ['Ext.Shadow'], + + /** + * @cfg {Boolean} [shim=true] + * False to disable the iframe shim in browsers which need one. + */ + + /** + * @cfg {String/Boolean} [shadow=false] + * 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. + */ + + /** + * @cfg {Object} [dh={tag: 'div', cls: 'x-layer'}] + * DomHelper object config to create element with. + */ + + /** + * @cfg {Boolean} [constrain=true] + * False to disable constrain to viewport. + */ + + /** + * @cfg {String} cls + * CSS class to add to the element + */ + + /** + * @cfg {Number} [zindex=11000] + * Starting z-index. + */ + + /** + * @cfg {Number} [shadowOffset=4] + * Number of pixels to offset the shadow + */ + + /** + * @cfg {Boolean} [useDisplay=false] + * Defaults to use css offsets to hide the Layer. Specify true + * to use css style 'display:none;' to hide the Layer. + */ + + /** + * @cfg {String} visibilityCls + * The CSS class name to add in order to hide this Layer if this layer + * is configured with {@link #hideMode}: 'asclass' + */ + + /** + * @cfg {String} hideMode + * A String which specifies how this Layer will be hidden. + * Values may be: + * + * - `'display'` : The Component will be hidden using the `display: none` style. + * - `'visibility'` : The Component will be hidden using the `visibility: hidden` style. + * - `'offsets'` : The Component will be hidden by absolutely positioning it out of the visible area + * of the document. This is useful when a hidden Component must maintain measurable dimensions. + * Hiding using `display` results in a Component having zero dimensions. + */ + + // shims are shared among layer to keep from having 100 iframes + statics: { + shims: [] + }, + + isLayer: true, + + /** + * Creates new Layer. + * @param {Object} [config] An object with config options. + * @param {String/HTMLElement} [existingEl] Uses an existing DOM element. + * If the element is not found it creates it. + */ + constructor: function(config, existingEl) { + config = config || {}; + var me = this, + dh = Ext.DomHelper, + cp = config.parentEl, + pel = cp ? Ext.getDom(cp) : document.body, + hm = config.hideMode; + + if (existingEl) { + me.dom = Ext.getDom(existingEl); + } + if (!me.dom) { + me.dom = dh.append(pel, config.dh || { + tag: 'div', + cls: Ext.baseCSSPrefix + 'layer' // primarily to give el 'position:absolute' + }); + } else { + me.addCls(Ext.baseCSSPrefix + 'layer'); + if (!me.dom.parentNode) { + pel.appendChild(me.dom); + } + } + + if (config.id) { + me.id = me.dom.id = config.id; + } else { + me.id = Ext.id(me.dom); + } + + Ext.Element.addToCache(me); + + if (config.cls) { + me.addCls(config.cls); + } + me.constrain = config.constrain !== false; + + // Allow Components to pass their hide mode down to the Layer if they are floating. + // Otherwise, allow useDisplay to override the default hiding method which is visibility. + // TODO: Have ExtJS's Element implement visibilityMode by using classes as in Mobile. + if (hm) { + me.setVisibilityMode(Ext.Element[hm.toUpperCase()]); + if (me.visibilityMode == Ext.Element.ASCLASS) { + me.visibilityCls = config.visibilityCls; + } + } else if (config.useDisplay) { + me.setVisibilityMode(Ext.Element.DISPLAY); + } else { + me.setVisibilityMode(Ext.Element.VISIBILITY); + } + + if (config.shadow) { + me.shadowOffset = config.shadowOffset || 4; + me.shadow = new Ext.Shadow({ + offset: me.shadowOffset, + mode: config.shadow + }); + me.disableShadow(); + } else { + me.shadowOffset = 0; + } + me.useShim = config.shim !== false && Ext.useShims; + if (config.hidden === true) { + me.hide(); + } else { + me.show(); + } + }, + + getZIndex: function() { + return parseInt((this.getShim() || this).getStyle('z-index'), 10); + }, + + getShim: function() { + var me = this, + shim, pn; + + if (!me.useShim) { + return null; + } + if (!me.shim) { + shim = me.self.shims.shift(); + if (!shim) { + shim = me.createShim(); + shim.enableDisplayMode('block'); + shim.hide(); + } + pn = me.dom.parentNode; + if (shim.dom.parentNode != pn) { + pn.insertBefore(shim.dom, me.dom); + } + me.shim = shim; + } + return me.shim; + }, + + hideShim: function() { + var me = this; + + if (me.shim) { + me.shim.setDisplayed(false); + me.self.shims.push(me.shim); + delete me.shim; + } + }, + + disableShadow: function() { + var me = this; + + if (me.shadow && !me.shadowDisabled) { + me.shadowDisabled = true; + me.shadow.hide(); + me.lastShadowOffset = me.shadowOffset; + me.shadowOffset = 0; + } + }, + + enableShadow: function(show) { + var me = this; + + if (me.shadow && me.shadowDisabled) { + me.shadowDisabled = false; + me.shadowOffset = me.lastShadowOffset; + delete me.lastShadowOffset; + if (show) { + me.sync(true); + } + } + }, + + /** + * @private + * Synchronize this Layer's associated elements, the shadow, and possibly the shim. + * + * This code can execute repeatedly in milliseconds, + * eg: dragging a Component configured liveDrag: true, or which has no ghost method + * so code size was sacrificed for efficiency (e.g. no getBox/setBox, no XY calls) + * + * @param {Boolean} doShow Pass true to ensure that the shadow is shown. + */ + sync: function(doShow) { + var me = this, + shadow = me.shadow, + shadowPos, shimStyle, shadowSize, + shim, l, t, w, h, shimIndex; + + if (!me.updating && me.isVisible() && (shadow || me.useShim)) { + shim = me.getShim(); + l = me.getLeft(true); + t = me.getTop(true); + w = me.dom.offsetWidth; + h = me.dom.offsetHeight; + + if (shadow && !me.shadowDisabled) { + if (doShow && !shadow.isVisible()) { + shadow.show(me); + } else { + shadow.realign(l, t, w, h); + } + if (shim) { + // TODO: Determine how the shims zIndex is above the layer zIndex at this point + shimIndex = shim.getStyle('z-index'); + if (shimIndex > me.zindex) { + me.shim.setStyle('z-index', me.zindex - 2); + } + shim.show(); + // fit the shim behind the shadow, so it is shimmed too + if (shadow.isVisible()) { + shadowPos = shadow.el.getXY(); + shimStyle = shim.dom.style; + shadowSize = shadow.el.getSize(); + if (Ext.supports.CSS3BoxShadow) { + shadowSize.height += 6; + shadowSize.width += 4; + shadowPos[0] -= 2; + shadowPos[1] -= 4; + } + shimStyle.left = (shadowPos[0]) + 'px'; + shimStyle.top = (shadowPos[1]) + 'px'; + shimStyle.width = (shadowSize.width) + 'px'; + shimStyle.height = (shadowSize.height) + 'px'; + } else { + shim.setSize(w, h); + shim.setLeftTop(l, t); + } + } + } else if (shim) { + // TODO: Determine how the shims zIndex is above the layer zIndex at this point + shimIndex = shim.getStyle('z-index'); + if (shimIndex > me.zindex) { + me.shim.setStyle('z-index', me.zindex - 2); + } + shim.show(); + shim.setSize(w, h); + shim.setLeftTop(l, t); + } + } + return me; + }, + + remove: function() { + this.hideUnders(); + this.callParent(); + }, + + // private + beginUpdate: function() { + this.updating = true; + }, + + // private + endUpdate: function() { + this.updating = false; + this.sync(true); + }, + + // private + hideUnders: function() { + if (this.shadow) { + this.shadow.hide(); + } + this.hideShim(); + }, + + // private + constrainXY: function() { + if (this.constrain) { + var vw = Ext.Element.getViewWidth(), + vh = Ext.Element.getViewHeight(), + s = Ext.getDoc().getScroll(), + xy = this.getXY(), + x = xy[0], + y = xy[1], + so = this.shadowOffset, + w = this.dom.offsetWidth + so, + h = this.dom.offsetHeight + so, + moved = false; // only move it if it needs it + // first validate right/bottom + if ((x + w) > vw + s.left) { + x = vw - w - so; + moved = true; + } + if ((y + h) > vh + s.top) { + y = vh - h - so; + moved = true; + } + // then make sure top/left isn't negative + if (x < s.left) { + x = s.left; + moved = true; + } + if (y < s.top) { + y = s.top; + moved = true; + } + if (moved) { + Ext.Layer.superclass.setXY.call(this, [x, y]); + this.sync(); + } + } + return this; + }, + + getConstrainOffset: function() { + return this.shadowOffset; + }, + + // overridden Element method + setVisible: function(visible, animate, duration, callback, easing) { + var me = this, + cb; + + // post operation processing + cb = function() { + if (visible) { + me.sync(true); + } + if (callback) { + callback(); + } + }; + + // Hide shadow and shim if hiding + if (!visible) { + me.hideUnders(true); + } + me.callParent([visible, animate, duration, callback, easing]); + if (!animate) { + cb(); + } + return me; + }, + + // private + beforeFx: function() { + this.beforeAction(); + return this.callParent(arguments); + }, + + // private + afterFx: function() { + this.callParent(arguments); + this.sync(this.isVisible()); + }, + + // private + beforeAction: function() { + if (!this.updating && this.shadow) { + this.shadow.hide(); + } + }, + + // overridden Element method + setLeft: function(left) { + this.callParent(arguments); + return this.sync(); + }, + + setTop: function(top) { + this.callParent(arguments); + return this.sync(); + }, + + setLeftTop: function(left, top) { + this.callParent(arguments); + return this.sync(); + }, + + setXY: function(xy, animate, duration, callback, easing) { + var me = this; + + // Callback will restore shadow state and call the passed callback + callback = me.createCB(callback); + + me.fixDisplay(); + me.beforeAction(); + me.callParent([xy, animate, duration, callback, easing]); + if (!animate) { + callback(); + } + return me; + }, + + // private + createCB: function(callback) { + var me = this, + showShadow = me.shadow && me.shadow.isVisible(); + + return function() { + me.constrainXY(); + me.sync(showShadow); + if (callback) { + callback(); + } + }; + }, + + // overridden Element method + setX: function(x, animate, duration, callback, easing) { + this.setXY([x, this.getY()], animate, duration, callback, easing); + return this; + }, + + // overridden Element method + setY: function(y, animate, duration, callback, easing) { + this.setXY([this.getX(), y], animate, duration, callback, easing); + return this; + }, + + // overridden Element method + setSize: function(w, h, animate, duration, callback, easing) { + var me = this; + + // Callback will restore shadow state and call the passed callback + callback = me.createCB(callback); + + me.beforeAction(); + me.callParent([w, h, animate, duration, callback, easing]); + if (!animate) { + callback(); + } + return me; + }, + + // overridden Element method + setWidth: function(w, animate, duration, callback, easing) { + var me = this; + + // Callback will restore shadow state and call the passed callback + callback = me.createCB(callback); + + me.beforeAction(); + me.callParent([w, animate, duration, callback, easing]); + if (!animate) { + callback(); + } + return me; + }, + + // overridden Element method + setHeight: function(h, animate, duration, callback, easing) { + var me = this; + + // Callback will restore shadow state and call the passed callback + callback = me.createCB(callback); + + me.beforeAction(); + me.callParent([h, animate, duration, callback, easing]); + if (!animate) { + callback(); + } + return me; + }, + + // overridden Element method + setBounds: function(x, y, width, height, animate, duration, callback, easing) { + var me = this; + + // Callback will restore shadow state and call the passed callback + callback = me.createCB(callback); + + me.beforeAction(); + if (!animate) { + Ext.Layer.superclass.setXY.call(me, [x, y]); + Ext.Layer.superclass.setSize.call(me, width, height); + callback(); + } else { + me.callParent([x, y, width, height, animate, duration, callback, easing]); + } + return me; + }, + + /** + * Sets the z-index of this layer and adjusts any shadow and shim z-indexes. The layer + * z-index is automatically incremented depending upon the presence of a shim or a + * shadow in so that it always shows above those two associated elements. + * + * Any shim, will be assigned the passed z-index. A shadow will be assigned the next + * highet z-index, and the Layer's element will receive the highest z-index. + * + * @param {Number} zindex The new z-index to set + * @return {Ext.Layer} The Layer + */ + setZIndex: function(zindex) { + var me = this; + + me.zindex = zindex; + if (me.getShim()) { + me.shim.setStyle('z-index', zindex++); + } + if (me.shadow) { + me.shadow.setZIndex(zindex++); + } + return me.setStyle('z-index', zindex); + }, + + onOpacitySet: function(opacity){ + var shadow = this.shadow; + if (shadow) { + shadow.setOpacity(opacity); + } + } +}); + +/** + * Private utility class that manages the internal Shadow cache. + * @private + */ +Ext.define('Ext.ShadowPool', { + singleton: true, + requires: ['Ext.DomHelper'], + + markup: (function() { + return Ext.String.format( + '', + Ext.baseCSSPrefix, + Ext.isIE && !Ext.supports.CSS3BoxShadow ? 'ie' : 'css' + ); + }()), + + shadows: [], + + pull: function() { + var sh = this.shadows.shift(); + if (!sh) { + sh = Ext.get(Ext.DomHelper.insertHtml("beforeBegin", document.body.firstChild, this.markup)); + sh.autoBoxAdjust = false; + } + return sh; + }, + + push: function(sh) { + this.shadows.push(sh); + }, + + reset: function() { + var shadows = [].concat(this.shadows), + s, + sLen = shadows.length; + + for (s = 0; s < sLen; s++) { + shadows[s].remove(); + } + + this.shadows = []; + } +}); +/** + * A class that manages a group of {@link Ext.Component#floating} Components and provides z-order management, + * and Component activation behavior, including masking below the active (topmost) Component. + * + * {@link Ext.Component#floating Floating} Components which are rendered directly into the document (such as + * {@link Ext.window.Window Window}s) which are {@link Ext.Component#method-show show}n are managed by a + * {@link Ext.WindowManager global instance}. + * + * {@link Ext.Component#floating Floating} Components which are descendants of {@link Ext.Component#floating floating} + * *Containers* (for example a {@link Ext.view.BoundList BoundList} within an {@link Ext.window.Window Window}, + * or a {@link Ext.menu.Menu Menu}), are managed by a ZIndexManager owned by that floating Container. Therefore + * ComboBox dropdowns within Windows will have managed z-indices guaranteed to be correct, relative to the Window. + */ +Ext.define('Ext.ZIndexManager', { + alternateClassName: 'Ext.WindowGroup', + + statics: { + zBase : 9000 + }, + + constructor: function(container) { + var me = this; + + me.list = {}; + me.zIndexStack = []; + me.front = null; + + if (container) { + + // This is the ZIndexManager for an Ext.container.Container, base its zseed on the zIndex of the Container's element + if (container.isContainer) { + container.on('resize', me._onContainerResize, me); + me.zseed = Ext.Number.from(me.rendered ? container.getEl().getStyle('zIndex') : undefined, me.getNextZSeed()); + // The containing element we will be dealing with (eg masking) is the content target + me.targetEl = container.getTargetEl(); + me.container = container; + } + // This is the ZIndexManager for a DOM element + else { + Ext.EventManager.onWindowResize(me._onContainerResize, me); + me.zseed = me.getNextZSeed(); + me.targetEl = Ext.get(container); + } + } + // No container passed means we are the global WindowManager. Our target is the doc body. + // DOM must be ready to collect that ref. + else { + Ext.EventManager.onWindowResize(me._onContainerResize, me); + me.zseed = me.getNextZSeed(); + Ext.onDocumentReady(function() { + me.targetEl = Ext.getBody(); + }); + } + }, + + getNextZSeed: function() { + return (Ext.ZIndexManager.zBase += 10000); + }, + + setBase: function(baseZIndex) { + this.zseed = baseZIndex; + var result = this.assignZIndices(); + this._activateLast(); + return result; + }, + + // private + assignZIndices: function() { + var a = this.zIndexStack, + len = a.length, + i = 0, + zIndex = this.zseed, + comp; + + for (; i < len; i++) { + comp = a[i]; + if (comp && !comp.hidden) { + + // Setting the zIndex of a Component returns the topmost zIndex consumed by + // that Component. + // If it's just a plain floating Component such as a BoundList, then the + // return value is the passed value plus 10, ready for the next item. + // If a floating *Container* has its zIndex set, it re-orders its managed + // floating children, starting from that new base, and returns a value 10000 above + // the highest zIndex which it allocates. + zIndex = comp.setZIndex(zIndex); + } + } + + // Activate new topmost + this._activateLast(); + return zIndex; + }, + + // private + _setActiveChild: function(comp, oldFront) { + var front = this.front; + if (comp !== front) { + + if (front && !front.destroying) { + front.setActive(false, comp); + } + this.front = comp; + if (comp && comp != oldFront) { + comp.setActive(true); + if (comp.modal) { + this._showModalMask(comp); + } + } + } + }, + + onComponentHide: function(comp){ + comp.setActive(false); + this._activateLast(); + }, + + // private + _activateLast: function() { + var me = this, + stack = me.zIndexStack, + i = stack.length - 1, + oldFront = me.front, + comp; + + // There may be no visible floater to activate + me.front = undefined; + + // Go down through the z-index stack. + // Activate the next visible one down. + // If that was modal, then we're done + for (; i >= 0 && stack[i].hidden; --i); + if ((comp = stack[i])) { + me._setActiveChild(comp, oldFront); + if (comp.modal) { + return; + } + } + + // If the new top one was not modal, keep going down to find the next visible + // modal one to shift the modal mask down under + for (; i >= 0; --i) { + comp = stack[i]; + // If we find a visible modal further down the zIndex stack, move the mask to just under it. + if (comp.isVisible() && comp.modal) { + me._showModalMask(comp); + return; + } + } + + // No visible modal Component was found in the run down the stack. + // So hide the modal mask + me._hideModalMask(); + }, + + _showModalMask: function(comp) { + var me = this, + zIndex = comp.el.getStyle('zIndex') - 4, + maskTarget = comp.floatParent ? comp.floatParent.getTargetEl() : comp.container, + viewSize = maskTarget.getBox(); + + if (maskTarget.dom === document.body) { + viewSize.height = Math.max(document.body.scrollHeight, Ext.dom.Element.getDocumentHeight()); + viewSize.width = Math.max(document.body.scrollWidth, viewSize.width); + } + if (!me.mask) { + me.mask = Ext.getBody().createChild({ + cls: Ext.baseCSSPrefix + 'mask' + }); + me.mask.setVisibilityMode(Ext.Element.DISPLAY); + me.mask.on('click', me._onMaskClick, me); + } + me.mask.maskTarget = maskTarget; + maskTarget.addCls(Ext.baseCSSPrefix + 'body-masked'); + me.mask.setBox(viewSize); + me.mask.setStyle('zIndex', zIndex); + me.mask.show(); + }, + + _hideModalMask: function() { + var mask = this.mask; + if (mask && mask.isVisible()) { + mask.maskTarget.removeCls(Ext.baseCSSPrefix + 'body-masked'); + mask.maskTarget = undefined; + mask.hide(); + } + }, + + _onMaskClick: function() { + if (this.front) { + this.front.focus(); + } + }, + + _onContainerResize: function() { + var mask = this.mask, + maskTarget, + viewSize; + + if (mask && mask.isVisible()) { + + // At the new container size, the mask might be *causing* the scrollbar, so to find the valid + // client size to mask, we must temporarily unmask the parent node. + mask.hide(); + maskTarget = mask.maskTarget; + + if (maskTarget.dom === document.body) { + viewSize = { + height: Math.max(document.body.scrollHeight, Ext.dom.Element.getDocumentHeight()), + width: Math.max(document.body.scrollWidth, document.documentElement.clientWidth) + }; + } else { + viewSize = maskTarget.getViewSize(true); + } + mask.setSize(viewSize); + mask.show(); + } + }, + + /** + * Registers a floating {@link Ext.Component} with this ZIndexManager. This should not + * need to be called under normal circumstances. Floating Components (such as Windows, + * BoundLists and Menus) are automatically registered with a + * {@link Ext.Component#zIndexManager zIndexManager} at render time. + * + * Where this may be useful is moving Windows between two ZIndexManagers. For example, + * to bring the Ext.MessageBox dialog under the same manager as the Desktop's + * ZIndexManager in the desktop sample app: + * + * MyDesktop.getDesktop().getManager().register(Ext.MessageBox); + * + * @param {Ext.Component} comp The Component to register. + */ + register : function(comp) { + var me = this; + + if (comp.zIndexManager) { + comp.zIndexManager.unregister(comp); + } + comp.zIndexManager = me; + + me.list[comp.id] = comp; + me.zIndexStack.push(comp); + comp.on('hide', me.onComponentHide, me); + }, + + /** + * Unregisters a {@link Ext.Component} from this ZIndexManager. This should not + * need to be called. Components are automatically unregistered upon destruction. + * See {@link #register}. + * @param {Ext.Component} comp The Component to unregister. + */ + unregister : function(comp) { + var me = this, + list = me.list; + + delete comp.zIndexManager; + if (list && list[comp.id]) { + delete list[comp.id]; + comp.un('hide', me.onComponentHide); + Ext.Array.remove(me.zIndexStack, comp); + + // Destruction requires that the topmost visible floater be activated. Same as hiding. + me._activateLast(); + } + }, + + /** + * Gets a registered Component by id. + * @param {String/Object} id The id of the Component or a {@link Ext.Component} instance + * @return {Ext.Component} + */ + get : function(id) { + return id.isComponent ? id : this.list[id]; + }, + + /** + * Brings the specified Component to the front of any other active Components in this ZIndexManager. + * @param {String/Object} comp The id of the Component or a {@link Ext.Component} instance + * @return {Boolean} True if the dialog was brought to the front, else false + * if it was already in front + */ + bringToFront : function(comp) { + var me = this, + result = false, + zIndexStack = me.zIndexStack; + + comp = me.get(comp); + if (comp !== me.front) { + Ext.Array.remove(zIndexStack, comp); + if (comp.preventBringToFront) { + // this takes care of cases where a load mask should be displayed under a floated component + zIndexStack.unshift(comp); + } else { + // the default behavior is to push onto the stack + zIndexStack.push(comp); + } + + me.assignZIndices(); + result = true; + this.front = comp; + } + if (result && comp.modal) { + me._showModalMask(comp); + } + return result; + }, + + /** + * Sends the specified Component to the back of other active Components in this ZIndexManager. + * @param {String/Object} comp The id of the Component or a {@link Ext.Component} instance + * @return {Ext.Component} The Component + */ + sendToBack : function(comp) { + var me = this; + + comp = me.get(comp); + Ext.Array.remove(me.zIndexStack, comp); + me.zIndexStack.unshift(comp); + me.assignZIndices(); + this._activateLast(); + return comp; + }, + + /** + * Hides all Components managed by this ZIndexManager. + */ + hideAll : function() { + var list = this.list, + item, + id; + + for (id in list) { + if (list.hasOwnProperty(id)) { + item = list[id]; + if (item.isComponent && item.isVisible()) { + item.hide(); + } + } + } + }, + + /** + * @private + * Temporarily hides all currently visible managed Components. This is for when + * dragging a Window which may manage a set of floating descendants in its ZIndexManager; + * they should all be hidden just for the duration of the drag. + */ + hide: function() { + var i = 0, + stack = this.zIndexStack, + len = stack.length, + comp; + + this.tempHidden = []; + for (; i < len; i++) { + comp = stack[i]; + if (comp.isVisible()) { + this.tempHidden.push(comp); + comp.el.hide(); + } + } + }, + + /** + * @private + * Restores temporarily hidden managed Components to visibility. + */ + show: function() { + var i = 0, + tempHidden = this.tempHidden, + len = tempHidden ? tempHidden.length : 0, + comp; + + for (; i < len; i++) { + comp = tempHidden[i]; + comp.el.show(); + comp.setPosition(comp.x, comp.y); + } + delete this.tempHidden; + }, + + /** + * Gets the currently-active Component in this ZIndexManager. + * @return {Ext.Component} The active Component + */ + getActive : function() { + return this.front; + }, + + /** + * Returns zero or more Components in this ZIndexManager using the custom search function passed to this method. + * The function should accept a single {@link Ext.Component} reference as its only argument and should + * return true if the Component matches the search criteria, otherwise it should return false. + * @param {Function} fn The search function + * @param {Object} [scope] The scope (this reference) in which the function is executed. + * Defaults to the Component being tested. That gets passed to the function if not specified. + * @return {Array} An array of zero or more matching windows + */ + getBy : function(fn, scope) { + var r = [], + i = 0, + stack = this.zIndexStack, + len = stack.length, + comp; + + for (; i < len; i++) { + comp = stack[i]; + if (fn.call(scope||comp, comp) !== false) { + r.push(comp); + } + } + return r; + }, + + /** + * Executes the specified function once for every Component in this ZIndexManager, passing each + * Component as the only parameter. Returning false from the function will stop the iteration. + * @param {Function} fn The function to execute for each item + * @param {Object} [scope] The scope (this reference) in which the function + * is executed. Defaults to the current Component in the iteration. + */ + each : function(fn, scope) { + var list = this.list, + id, + comp; + + for (id in list) { + if (list.hasOwnProperty(id)) { + comp = list[id]; + if (comp.isComponent && fn.call(scope || comp, comp) === false) { + return; + } + } + } + }, + + /** + * Executes the specified function once for every Component in this ZIndexManager, passing each + * Component as the only parameter. Returning false from the function will stop the iteration. + * The components are passed to the function starting at the bottom and proceeding to the top. + * @param {Function} fn The function to execute for each item + * @param {Object} scope (optional) The scope (this reference) in which the function + * is executed. Defaults to the current Component in the iteration. + */ + eachBottomUp: function (fn, scope) { + var stack = this.zIndexStack, + i = 0, + len = stack.length, + comp; + + for (; i < len; i++) { + comp = stack[i]; + if (comp.isComponent && fn.call(scope || comp, comp) === false) { + return; + } + } + }, + + /** + * Executes the specified function once for every Component in this ZIndexManager, passing each + * Component as the only parameter. Returning false from the function will stop the iteration. + * The components are passed to the function starting at the top and proceeding to the bottom. + * @param {Function} fn The function to execute for each item + * @param {Object} [scope] The scope (this reference) in which the function + * is executed. Defaults to the current Component in the iteration. + */ + eachTopDown: function (fn, scope) { + var stack = this.zIndexStack, + i = stack.length, + comp; + + for (; i-- > 0; ) { + comp = stack[i]; + if (comp.isComponent && fn.call(scope || comp, comp) === false) { + return; + } + } + }, + + destroy: function() { + var me = this, + list = me.list, + comp, + id; + + for (id in list) { + if (list.hasOwnProperty(id)) { + comp = list[id]; + + if (comp.isComponent) { + comp.destroy(); + } + } + } + + delete me.zIndexStack; + delete me.list; + delete me.container; + delete me.targetEl; + } +}, function() { + /** + * @class Ext.WindowManager + * @extends Ext.ZIndexManager + * + * The default global floating Component group that is available automatically. + * + * This manages instances of floating Components which were rendered programatically without + * being added to a {@link Ext.container.Container Container}, and for floating Components + * which were added into non-floating Containers. + * + * *Floating* Containers create their own instance of ZIndexManager, and floating Components + * added at any depth below there are managed by that ZIndexManager. + * + * @singleton + */ + Ext.WindowManager = Ext.WindowMgr = new this(); +}); + +/* + * This is a derivative of the similarly named class 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 + */ + + +/** + * DragDropManager 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. + */ +Ext.define('Ext.dd.DragDropManager', { + singleton: true, + + requires: ['Ext.util.Region'], + + uses: ['Ext.tip.QuickTipManager'], + + // shorter ClassName, to save bytes and use internally + alternateClassName: ['Ext.dd.DragDropMgr', 'Ext.dd.DDM'], + + /** + * @property {String[]} ids + * Two dimensional Array of registered DragDrop objects. The first + * dimension is the DragDrop item group, the second the DragDrop + * object. + * @private + */ + ids: {}, + + /** + * @property {String[]} handleIds + * 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. + * @private + */ + handleIds: {}, + + /** + * @property {Ext.dd.DragDrop} dragCurrent + * the DragDrop object that is currently being dragged + * @private + */ + dragCurrent: null, + + /** + * @property {Ext.dd.DragDrop[]} dragOvers + * the DragDrop object(s) that are being hovered over + * @private + */ + dragOvers: {}, + + /** + * @property {Number} deltaX + * the X distance between the cursor and the object being dragged + * @private + */ + deltaX: 0, + + /** + * @property {Number} deltaY + * the Y distance between the cursor and the object being dragged + * @private + */ + deltaY: 0, + + /** + * @property {Boolean} preventDefault + * 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) + */ + preventDefault: true, + + /** + * @property {Boolean} stopPropagation + * 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. + */ + stopPropagation: true, + + /** + * Internal flag that is set to true when drag and drop has been + * intialized + * @property initialized + * @private + */ + initialized: false, + + /** + * All drag and drop can be disabled. + * @property locked + * @private + */ + locked: false, + + /** + * Called the first time an element is registered. + * @private + */ + init: function() { + this.initialized = true; + }, + + /** + * @property {Number} POINT + * In point mode, drag and drop interaction is defined by the + * location of the cursor during the drag/drop + */ + POINT: 0, + + /** + * @property {Number} INTERSECT + * In intersect mode, drag and drop interaction is defined by the + * overlap of two or more drag and drop objects. + */ + INTERSECT: 1, + + /** + * @property {Number} mode + * The current drag and drop mode. Default: POINT + */ + mode: 0, + + /** + * @property {Boolean} [notifyOccluded=false] + * This config is only provided to provide old, usually unwanted drag/drop behaviour. + * + * From ExtJS 4.1.0 onwards, when drop targets are contained in floating, absolutely positioned elements + * such as in {@link Ext.window.Window Windows}, which may overlap each other, `over` and `drop` events + * are only delivered to the topmost drop target at the mouse position. + * + * If all targets below that in zIndex order should also receive notifications, set + * `notifyOccluded` to `true`. + */ + notifyOccluded: false, + + /** + * Runs method on all drag and drop objects + * @private + */ + _execOnAll: function(sMethod, args) { + var i, j, oDD; + for (i in this.ids) { + for (j in this.ids[i]) { + oDD = this.ids[i][j]; + if (! this.isTypeOfDD(oDD)) { + continue; + } + oDD[sMethod].apply(oDD, args); + } + } + }, + + /** + * Drag and drop initialization. Sets up the global event handlers + * @private + */ + _onLoad: function() { + + this.init(); + + var Event = Ext.EventManager; + Event.on(document, "mouseup", this.handleMouseUp, this, true); + Event.on(document, "mousemove", this.handleMouseMove, this, true); + Event.on(window, "unload", this._onUnload, this, true); + Event.on(window, "resize", this._onResize, this, true); + // Event.on(window, "mouseout", this._test); + + }, + + /** + * Reset constraints on all drag and drop objs + * @private + */ + _onResize: function(e) { + this._execOnAll("resetConstraints", []); + }, + + /** + * Lock all drag and drop functionality + */ + lock: function() { this.locked = true; }, + + /** + * Unlock all drag and drop functionality + */ + unlock: function() { this.locked = false; }, + + /** + * Is drag and drop locked? + * @return {Boolean} True if drag and drop is locked, false otherwise. + */ + isLocked: function() { return this.locked; }, + + /** + * @property {Object} locationCache + * Location cache that is set for all drag drop objects when a drag is + * initiated, cleared when the drag is finished. + * @private + */ + locationCache: {}, + + /** + * @property {Boolean} useCache + * Set useCache to false if you want to force object the lookup of each + * drag and drop linked element constantly during a drag. + */ + useCache: true, + + /** + * @property {Number} clickPixelThresh + * The number of pixels that the mouse needs to move after the + * mousedown before the drag is initiated. Default=3; + */ + clickPixelThresh: 3, + + /** + * @property {Number} clickTimeThresh + * The number of milliseconds after the mousedown event to initiate the + * drag if we don't get a mouseup event. Default=350 + */ + clickTimeThresh: 350, + + /** + * @property {Boolean} dragThreshMet + * Flag that indicates that either the drag pixel threshold or the + * mousdown time threshold has been met + * @private + */ + dragThreshMet: false, + + /** + * @property {Object} clickTimeout + * Timeout used for the click time threshold + * @private + */ + clickTimeout: null, + + /** + * @property {Number} startX + * The X position of the mousedown event stored for later use when a + * drag threshold is met. + * @private + */ + startX: 0, + + /** + * @property {Number} startY + * The Y position of the mousedown event stored for later use when a + * drag threshold is met. + * @private + */ + startY: 0, + + /** + * Each DragDrop instance must be registered with the DragDropManager. + * This is executed in DragDrop.init() + * @param {Ext.dd.DragDrop} oDD the DragDrop object to register + * @param {String} sGroup the name of the group this element belongs to + */ + regDragDrop: function(oDD, sGroup) { + if (!this.initialized) { this.init(); } + + if (!this.ids[sGroup]) { + this.ids[sGroup] = {}; + } + this.ids[sGroup][oDD.id] = oDD; + }, + + /** + * Removes the supplied dd instance from the supplied group. Executed + * by DragDrop.removeFromGroup, so don't call this function directly. + * @private + */ + removeDDFromGroup: function(oDD, sGroup) { + if (!this.ids[sGroup]) { + this.ids[sGroup] = {}; + } + + var obj = this.ids[sGroup]; + if (obj && obj[oDD.id]) { + delete obj[oDD.id]; + } + }, + + /** + * Unregisters a drag and drop item. This is executed in + * DragDrop.unreg, use that method instead of calling this directly. + * @private + */ + _remove: function(oDD) { + for (var g in oDD.groups) { + if (g && this.ids[g] && this.ids[g][oDD.id]) { + delete this.ids[g][oDD.id]; + } + } + delete this.handleIds[oDD.id]; + }, + + /** + * Each DragDrop handle element must be registered. This is done + * automatically when executing DragDrop.setHandleElId() + * @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 + */ + regHandle: function(sDDId, sHandleId) { + if (!this.handleIds[sDDId]) { + this.handleIds[sDDId] = {}; + } + this.handleIds[sDDId][sHandleId] = sHandleId; + }, + + /** + * Utility function to determine if a given element has been + * registered as a drag drop item. + * @param {String} id the element id to check + * @return {Boolean} true if this element is a DragDrop item, + * false otherwise + */ + 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. + * @param {Ext.dd.DragDrop} p_oDD the obj to get related data for + * @param {Boolean} bTargetsOnly if true, only return targetable objs + * @return {Ext.dd.DragDrop[]} the related instances + */ + getRelated: function(p_oDD, bTargetsOnly) { + var oDDs = [], + i, j, dd; + for (i in p_oDD.groups) { + for (j in this.ids[i]) { + dd = this.ids[i][j]; + if (! this.isTypeOfDD(dd)) { + continue; + } + if (!bTargetsOnly || dd.isTarget) { + oDDs[oDDs.length] = dd; + } + } + } + + return oDDs; + }, + + /** + * Returns true if the specified dd target is a legal target for + * the specifice drag obj + * @param {Ext.dd.DragDrop} oDD the drag obj + * @param {Ext.dd.DragDrop} oTargetDD the target + * @return {Boolean} true if the target is a legal target for the + * dd obj + */ + isLegalTarget: function (oDD, oTargetDD) { + var targets = this.getRelated(oDD, true), + i, len; + for (i=0, len=targets.length;i this.clickPixelThresh || + diffY > this.clickPixelThresh) { + this.startDrag(this.startX, this.startY); + } + } + + if (this.dragThreshMet) { + this.dragCurrent.b4Drag(e); + this.dragCurrent.onDrag(e); + if(!this.dragCurrent.moveOnly){ + this.fireEvents(e, false); + } + } + + this.stopEvent(e); + + return true; + }, + + /** + * Iterates over all of the DragDrop elements to find ones we are + * hovering over or dropping on + * @param {Event} e the event + * @param {Boolean} isDrop is this a drop op or a mouseover op? + * @private + */ + fireEvents: function(e, isDrop) { + var me = this, + dragCurrent = me.dragCurrent, + mousePoint = e.getPoint(), + overTarget, + overTargetEl, + allTargets = [], + oldOvers = [], // cache the previous dragOver array + outEvts = [], + overEvts = [], + dropEvts = [], + enterEvts = [], + needsSort, + i, + len, + sGroup; + + // If the user did the mouse up outside of the window, we could + // get here even though we have ended the drag. + if (!dragCurrent || dragCurrent.isLocked()) { + return; + } + + // Check to see if the object(s) we were hovering over is no longer + // being hovered over so we can fire the onDragOut event + for (i in me.dragOvers) { + + overTarget = me.dragOvers[i]; + + if (! me.isTypeOfDD(overTarget)) { + continue; + } + + if (! this.isOverTarget(mousePoint, overTarget, me.mode)) { + outEvts.push( overTarget ); + } + + oldOvers[i] = true; + delete me.dragOvers[i]; + } + + // Collect all targets which are members of the same ddGoups that the dragCurrent is a member of, and which may recieve mouseover and drop notifications. + // This is preparatory to seeing which one(s) we are currently over + // Begin by iterating through the ddGroups of which the dragCurrent is a member + for (sGroup in dragCurrent.groups) { + + if ("string" != typeof sGroup) { + continue; + } + + // Loop over the registered members of each group, testing each as a potential target + for (i in me.ids[sGroup]) { + overTarget = me.ids[sGroup][i]; + + // The target is valid if it is a DD type + // And it's got a DOM element + // And it's configured to be a drop target + // And it's not locked + // And the DOM element is fully visible with no hidden ancestors + // And it's either not the dragCurrent, or, if it is, tha dragCurrent is configured to not ignore itself. + if (me.isTypeOfDD(overTarget) && + (overTargetEl = overTarget.getEl()) && + (overTarget.isTarget) && + (!overTarget.isLocked()) && + (Ext.fly(overTargetEl).isVisible(true)) && + ((overTarget != dragCurrent) || (dragCurrent.ignoreSelf === false))) { + + // Only sort by zIndex if there were some which had a floating zIndex value + if ((overTarget.zIndex = me.getZIndex(overTargetEl)) !== -1) { + needsSort = true; + } + allTargets.push(overTarget); + } + } + } + + // If there were floating targets, sort the highest zIndex to the top + if (needsSort) { + Ext.Array.sort(allTargets, me.byZIndex); + } + + // Loop through possible targets, notifying the one(s) we are over. + // Usually we only deliver events to the topmost. + for (i = 0, len = allTargets.length; i < len; i++) { + overTarget = allTargets[i]; + + // If we are over the overTarget, queue it up to recieve an event of whatever type we are handling + if (me.isOverTarget(mousePoint, overTarget, me.mode)) { + // look for drop interactions + if (isDrop) { + dropEvts.push( overTarget ); + // look for drag enter and drag over interactions + } else { + + // initial drag over: dragEnter fires + if (!oldOvers[overTarget.id]) { + enterEvts.push( overTarget ); + // subsequent drag overs: dragOver fires + } else { + overEvts.push( overTarget ); + } + me.dragOvers[overTarget.id] = overTarget; + } + + // Unless this DragDropManager has been explicitly configured to deliver events to multiple targets, then we are done. + if (!me.notifyOccluded) { + break; + } + } + } + + if (me.mode) { + if (outEvts.length) { + dragCurrent.b4DragOut(e, outEvts); + dragCurrent.onDragOut(e, outEvts); + } + + if (enterEvts.length) { + dragCurrent.onDragEnter(e, enterEvts); + } + + if (overEvts.length) { + dragCurrent.b4DragOver(e, overEvts); + dragCurrent.onDragOver(e, overEvts); + } + + if (dropEvts.length) { + dragCurrent.b4DragDrop(e, dropEvts); + dragCurrent.onDragDrop(e, dropEvts); + } + + } else { + // fire dragout events + for (i=0, len=outEvts.length; i this.tolerance) { + this.triggerStart(e); + } else { + return; + } + } + + // Returning false from a mousemove listener deactivates + if (this.fireEvent('mousemove', this, e) === false) { + this.onMouseUp(e); + } else { + this.onDrag(e); + this.fireEvent('drag', this, e); + } + }, + + onMouseUp: function(e) { + // Clear the flag which ensures onMouseOut fires only after the mouse button + // is lifted if the mouseout happens *during* a drag. + this.mouseIsDown = false; + + // If we mouseouted the el *during* the drag, the onMouseOut method will not have fired. Ensure that it gets processed. + if (this.mouseIsOut) { + this.mouseIsOut = false; + this.onMouseOut(e); + } + e.preventDefault(); + this.fireEvent('mouseup', this, e); + this.endDrag(e); + }, + + /** + * @private + * Stop the drag operation, and remove active mouse listeners. + */ + endDrag: function(e) { + var doc = Ext.getDoc(), + wasActive = this.active; + + doc.un('mousemove', this.onMouseMove, this); + doc.un('mouseup', this.onMouseUp, this); + doc.un('selectstart', this.stopSelect, this); + this.clearStart(); + this.active = false; + if (wasActive) { + this.onEnd(e); + this.fireEvent('dragend', this, e); + } + // Private property calculated when first required and only cached during a drag + delete this._constrainRegion; + + // Remove flag from event singleton. Using "Ext.EventObject" here since "endDrag" is called directly in some cases without an "e" param + delete Ext.EventObject.dragTracked; + }, + + triggerStart: function(e) { + this.clearStart(); + this.active = true; + this.onStart(e); + this.fireEvent('dragstart', this, e); + }, + + clearStart : function() { + if (this.timer) { + clearTimeout(this.timer); + delete this.timer; + } + }, + + stopSelect : function(e) { + e.stopEvent(); + return false; + }, + + /** + * Template method which should be overridden by each DragTracker instance. Called when the user first clicks and + * holds the mouse button down. Return false to disallow the drag + * @param {Ext.EventObject} e The event object + * @template + */ + onBeforeStart : function(e) { + + }, + + /** + * Template method which should be overridden by each DragTracker instance. Called when a drag operation starts + * (e.g. the user has moved the tracked element beyond the specified tolerance) + * @param {Ext.EventObject} e The event object + * @template + */ + onStart : function(xy) { + + }, + + /** + * Template method which should be overridden by each DragTracker instance. Called whenever a drag has been detected. + * @param {Ext.EventObject} e The event object + * @template + */ + onDrag : function(e) { + + }, + + /** + * Template method which should be overridden by each DragTracker instance. Called when a drag operation has been completed + * (e.g. the user clicked and held the mouse down, dragged the element and then released the mouse button) + * @param {Ext.EventObject} e The event object + * @template + */ + onEnd : function(e) { + + }, + + /** + * Returns the drag target. This is usually the DragTracker's encapsulating element. + * + * If the {@link #delegate} option is being used, this may be a child element which matches the + * {@link #delegate} selector. + * + * @return {Ext.Element} The element currently being tracked. + */ + getDragTarget : function(){ + return this.dragTarget; + }, + + /** + * @private + * @returns {Ext.Element} The DragTracker's encapsulating element. + */ + getDragCt : function(){ + return this.el; + }, + + /** + * @private + * Return the Region into which the drag operation is constrained. + * Either the XY pointer itself can be constrained, or the dragTarget element + * The private property _constrainRegion is cached until onMouseUp + */ + getConstrainRegion: function() { + if (this.constrainTo) { + if (this.constrainTo instanceof Ext.util.Region) { + return this.constrainTo; + } + if (!this._constrainRegion) { + this._constrainRegion = Ext.fly(this.constrainTo).getViewRegion(); + } + } else { + if (!this._constrainRegion) { + this._constrainRegion = this.getDragCt().getViewRegion(); + } + } + return this._constrainRegion; + }, + + getXY : function(constrain){ + return constrain ? this.constrainModes[constrain](this, this.lastXY) : this.lastXY; + }, + + /** + * Returns the X, Y offset of the current mouse position from the mousedown point. + * + * This method may optionally constrain the real offset values, and returns a point coerced in one + * of two modes: + * + * - `point` + * The current mouse position is coerced into the constrainRegion and the resulting position is returned. + * - `dragTarget` + * The new {@link Ext.util.Region Region} of the {@link #getDragTarget dragTarget} is calculated + * based upon the current mouse position, and then coerced into the constrainRegion. The returned + * mouse position is then adjusted by the same delta as was used to coerce the region.\ + * + * @param constrainMode {String} (Optional) If omitted the true mouse position is returned. May be passed + * as `point` or `dragTarget`. See above. + * @returns {Number[]} The `X, Y` offset from the mousedown point, optionally constrained. + */ + getOffset : function(constrain){ + var xy = this.getXY(constrain), + s = this.startXY; + + return [xy[0]-s[0], xy[1]-s[1]]; + }, + + constrainModes: { + // Constrain the passed point to within the constrain region + point: function(me, xy) { + var dr = me.dragRegion, + constrainTo = me.getConstrainRegion(); + + // No constraint + if (!constrainTo) { + return xy; + } + + dr.x = dr.left = dr[0] = dr.right = xy[0]; + dr.y = dr.top = dr[1] = dr.bottom = xy[1]; + dr.constrainTo(constrainTo); + + return [dr.left, dr.top]; + }, + + // Constrain the dragTarget to within the constrain region. Return the passed xy adjusted by the same delta. + dragTarget: function(me, xy) { + var s = me.startXY, + dr = me.startRegion.copy(), + constrainTo = me.getConstrainRegion(), + adjust; + + // No constraint + if (!constrainTo) { + return xy; + } + + // See where the passed XY would put the dragTarget if translated by the unconstrained offset. + // If it overflows, we constrain the passed XY to bring the potential + // region back within the boundary. + dr.translateBy(xy[0]-s[0], xy[1]-s[1]); + + // Constrain the X coordinate by however much the dragTarget overflows + if (dr.right > constrainTo.right) { + xy[0] += adjust = (constrainTo.right - dr.right); // overflowed the right + dr.left += adjust; + } + if (dr.left < constrainTo.left) { + xy[0] += (constrainTo.left - dr.left); // overflowed the left + } + + // Constrain the Y coordinate by however much the dragTarget overflows + if (dr.bottom > constrainTo.bottom) { + xy[1] += adjust = (constrainTo.bottom - dr.bottom); // overflowed the bottom + dr.top += adjust; + } + if (dr.top < constrainTo.top) { + xy[1] += (constrainTo.top - dr.top); // overflowed the top + } + return xy; + } + } +}); +/** + * Provides easy access to all drag drop components that are registered on a page. Items can be retrieved either + * directly by DOM node id, or by passing in the drag drop event that occurred and looking up the event target. + */ +Ext.define('Ext.dd.Registry', { + singleton: true, + constructor: function() { + this.elements = {}; + this.handles = {}; + this.autoIdSeed = 0; + }, + + getId: function(el, autogen){ + if(typeof el == "string"){ + return el; + } + var id = el.id; + if(!id && autogen !== false){ + id = "extdd-" + (++this.autoIdSeed); + el.id = id; + } + return id; + }, + + /** + * Registers a drag drop element. + * + * @param {String/HTMLElement} element The id or DOM node to register + * @param {Object} data An custom data object that will be passed between the elements that are involved in drag + * drop operations. You can populate this object with any arbitrary properties that your own code knows how to + * interpret, plus there are some specific properties known to the Registry that should be populated in the data + * object (if applicable): + * @param {HTMLElement[]} data.handles Array of DOM nodes that trigger dragging for the element being registered. + * @param {Boolean} data.isHandle True if the element passed in triggers dragging itself, else false. + */ + register : function(el, data){ + data = data || {}; + if (typeof el == "string") { + el = document.getElementById(el); + } + data.ddel = el; + this.elements[this.getId(el)] = data; + if (data.isHandle !== false) { + this.handles[data.ddel.id] = data; + } + if (data.handles) { + var hs = data.handles, + i, len; + for (i = 0, len = hs.length; i < len; i++) { + this.handles[this.getId(hs[i])] = data; + } + } + }, + + /** + * Unregister a drag drop element + * @param {String/HTMLElement} element The id or DOM node to unregister + */ + unregister : function(el){ + var id = this.getId(el, false), + data = this.elements[id], + hs, i, len; + if(data){ + delete this.elements[id]; + if(data.handles){ + hs = data.handles; + for (i = 0, len = hs.length; i < len; i++) { + delete this.handles[this.getId(hs[i], false)]; + } + } + } + }, + + /** + * Returns the handle registered for a DOM Node by id + * @param {String/HTMLElement} id The DOM node or id to look up + * @return {Object} handle The custom handle data + */ + getHandle : function(id){ + if(typeof id != "string"){ // must be element? + id = id.id; + } + return this.handles[id]; + }, + + /** + * Returns the handle that is registered for the DOM node that is the target of the event + * @param {Event} e The event + * @return {Object} handle The custom handle data + */ + getHandleFromEvent : function(e){ + var t = e.getTarget(); + return t ? this.handles[t.id] : null; + }, + + /** + * Returns a custom data object that is registered for a DOM node by id + * @param {String/HTMLElement} id The DOM node or id to look up + * @return {Object} data The custom data + */ + getTarget : function(id){ + if(typeof id != "string"){ // must be element? + id = id.id; + } + return this.elements[id]; + }, + + /** + * Returns a custom data object that is registered for the DOM node that is the target of the event + * @param {Event} e The event + * @return {Object} data The custom data + */ + getTargetFromEvent : function(e){ + var t = e.getTarget(); + return t ? this.elements[t.id] || this.handles[t.id] : null; + } +}); +/** + * Provides automatic scrolling of overflow regions in the page during drag operations. + * + * The ScrollManager configs will be used as the defaults for any scroll container registered with it, but you can also + * override most of the configs per scroll container by adding a ddScrollConfig object to the target element that + * contains these properties: {@link #hthresh}, {@link #vthresh}, {@link #increment} and {@link #frequency}. Example + * usage: + * + * var el = Ext.get('scroll-ct'); + * el.ddScrollConfig = { + * vthresh: 50, + * hthresh: -1, + * frequency: 100, + * increment: 200 + * }; + * Ext.dd.ScrollManager.register(el); + * + * Note: This class is designed to be used in "Point Mode + */ +Ext.define('Ext.dd.ScrollManager', { + singleton: true, + requires: [ + 'Ext.dd.DragDropManager' + ], + + constructor: function() { + var ddm = Ext.dd.DragDropManager; + ddm.fireEvents = Ext.Function.createSequence(ddm.fireEvents, this.onFire, this); + ddm.stopDrag = Ext.Function.createSequence(ddm.stopDrag, this.onStop, this); + this.doScroll = Ext.Function.bind(this.doScroll, this); + this.ddmInstance = ddm; + this.els = {}; + this.dragEl = null; + this.proc = {}; + }, + + onStop: function(e){ + var sm = Ext.dd.ScrollManager; + sm.dragEl = null; + sm.clearProc(); + }, + + triggerRefresh: function() { + if (this.ddmInstance.dragCurrent) { + this.ddmInstance.refreshCache(this.ddmInstance.dragCurrent.groups); + } + }, + + doScroll: function() { + if (this.ddmInstance.dragCurrent) { + var proc = this.proc, + procEl = proc.el, + ddScrollConfig = proc.el.ddScrollConfig, + inc = ddScrollConfig ? ddScrollConfig.increment : this.increment; + + if (!this.animate) { + if (procEl.scroll(proc.dir, inc)) { + this.triggerRefresh(); + } + } else { + procEl.scroll(proc.dir, inc, true, this.animDuration, this.triggerRefresh); + } + } + }, + + clearProc: function() { + var proc = this.proc; + if (proc.id) { + clearInterval(proc.id); + } + proc.id = 0; + proc.el = null; + proc.dir = ""; + }, + + startProc: function(el, dir) { + this.clearProc(); + this.proc.el = el; + this.proc.dir = dir; + var group = el.ddScrollConfig ? el.ddScrollConfig.ddGroup : undefined, + freq = (el.ddScrollConfig && el.ddScrollConfig.frequency) + ? el.ddScrollConfig.frequency + : this.frequency; + + if (group === undefined || this.ddmInstance.dragCurrent.ddGroup == group) { + this.proc.id = setInterval(this.doScroll, freq); + } + }, + + onFire: function(e, isDrop) { + if (isDrop || !this.ddmInstance.dragCurrent) { + return; + } + if (!this.dragEl || this.dragEl != this.ddmInstance.dragCurrent) { + this.dragEl = this.ddmInstance.dragCurrent; + // refresh regions on drag start + this.refreshCache(); + } + + var xy = e.getXY(), + pt = e.getPoint(), + proc = this.proc, + els = this.els, + id, el, r, c; + + for (id in els) { + el = els[id]; + r = el._region; + c = el.ddScrollConfig ? el.ddScrollConfig : this; + if (r && r.contains(pt) && el.isScrollable()) { + if (r.bottom - pt.y <= c.vthresh) { + if(proc.el != el){ + this.startProc(el, "down"); + } + return; + }else if (r.right - pt.x <= c.hthresh) { + if (proc.el != el) { + this.startProc(el, "left"); + } + return; + } else if(pt.y - r.top <= c.vthresh) { + if (proc.el != el) { + this.startProc(el, "up"); + } + return; + } else if(pt.x - r.left <= c.hthresh) { + if (proc.el != el) { + this.startProc(el, "right"); + } + return; + } + } + } + this.clearProc(); + }, + + /** + * Registers new overflow element(s) to auto scroll + * @param {String/HTMLElement/Ext.Element/String[]/HTMLElement[]/Ext.Element[]} el + * The id of or the element to be scrolled or an array of either + */ + register : function(el){ + if (Ext.isArray(el)) { + for(var i = 0, len = el.length; i < len; i++) { + this.register(el[i]); + } + } else { + el = Ext.get(el); + this.els[el.id] = el; + } + }, + + /** + * Unregisters overflow element(s) so they are no longer scrolled + * @param {String/HTMLElement/Ext.Element/String[]/HTMLElement[]/Ext.Element[]} el + * The id of or the element to be removed or an array of either + */ + unregister : function(el){ + if(Ext.isArray(el)){ + for (var i = 0, len = el.length; i < len; i++) { + this.unregister(el[i]); + } + }else{ + el = Ext.get(el); + delete this.els[el.id]; + } + }, + + /** + * The number of pixels from the top or bottom edge of a container the pointer needs to be to trigger scrolling + */ + vthresh : 25, + + /** + * The number of pixels from the right or left edge of a container the pointer needs to be to trigger scrolling + */ + hthresh : 25, + + /** + * The number of pixels to scroll in each scroll increment + */ + increment : 100, + + /** + * The frequency of scrolls in milliseconds + */ + frequency : 500, + + /** + * True to animate the scroll + */ + animate: true, + + /** + * The animation duration in seconds - MUST BE less than Ext.dd.ScrollManager.frequency! + */ + animDuration: 0.4, + + /** + * @property {String} ddGroup + * The named drag drop {@link Ext.dd.DragSource#ddGroup group} to which this container belongs. If a ddGroup is + * specified, then container scrolling will only occur when a dragged object is in the same ddGroup. + */ + ddGroup: undefined, + + /** + * Manually trigger a cache refresh. + */ + refreshCache : function(){ + var els = this.els, + id; + for (id in els) { + if(typeof els[id] == 'object'){ // for people extending the object prototype + els[id]._region = els[id].getRegion(); + } + } + } +}); + +/** + * A mixin for {@link Ext.container.Container} components that are likely to have form fields in their + * items subtree. Adds the following capabilities: + * + * - Methods for handling the addition and removal of {@link Ext.form.Labelable} and {@link Ext.form.field.Field} + * instances at any depth within the container. + * - Events ({@link #fieldvaliditychange} and {@link #fielderrorchange}) for handling changes to the state + * of individual fields at the container level. + * - Automatic application of {@link #fieldDefaults} config properties to each field added within the + * container, to facilitate uniform configuration of all fields. + * + * This mixin is primarily for internal use by {@link Ext.form.Panel} and {@link Ext.form.FieldContainer}, + * and should not normally need to be used directly. @docauthor Jason Johnston + */ +Ext.define('Ext.form.FieldAncestor', { + + /** + * @cfg {Object} fieldDefaults + * If specified, the properties in this object are used as default config values for each {@link Ext.form.Labelable} + * instance (e.g. {@link Ext.form.field.Base} or {@link Ext.form.FieldContainer}) that is added as a descendant of + * this container. Corresponding values specified in an individual field's own configuration, or from the {@link + * Ext.container.Container#defaults defaults config} of its parent container, will take precedence. See the + * documentation for {@link Ext.form.Labelable} to see what config options may be specified in the fieldDefaults. + * + * Example: + * + * new Ext.form.Panel({ + * fieldDefaults: { + * labelAlign: 'left', + * labelWidth: 100 + * }, + * items: [{ + * xtype: 'fieldset', + * defaults: { + * labelAlign: 'top' + * }, + * items: [{ + * name: 'field1' + * }, { + * name: 'field2' + * }] + * }, { + * xtype: 'fieldset', + * items: [{ + * name: 'field3', + * labelWidth: 150 + * }, { + * name: 'field4' + * }] + * }] + * }); + * + * In this example, field1 and field2 will get labelAlign:'top' (from the fieldset's defaults) and labelWidth:100 + * (from fieldDefaults), field3 and field4 will both get labelAlign:'left' (from fieldDefaults and field3 will use + * the labelWidth:150 from its own config. + */ + + + /** + * Initializes the FieldAncestor's state; this must be called from the initComponent method of any components + * importing this mixin. + * @protected + */ + initFieldAncestor: function() { + var me = this, + onSubtreeChange = me.onFieldAncestorSubtreeChange; + + me.addEvents( + /** + * @event fieldvaliditychange + * Fires when the validity state of any one of the {@link Ext.form.field.Field} instances within this + * container changes. + * @param {Ext.form.FieldAncestor} this + * @param {Ext.form.Labelable} The Field instance whose validity changed + * @param {String} isValid The field's new validity state + */ + 'fieldvaliditychange', + + /** + * @event fielderrorchange + * Fires when the active error message is changed for any one of the {@link Ext.form.Labelable} instances + * within this container. + * @param {Ext.form.FieldAncestor} this + * @param {Ext.form.Labelable} The Labelable instance whose active error was changed + * @param {String} error The active error message + */ + 'fielderrorchange' + ); + + // Catch addition and removal of descendant fields + me.on('add', onSubtreeChange, me); + me.on('remove', onSubtreeChange, me); + + me.initFieldDefaults(); + }, + + /** + * @private Initialize the {@link #fieldDefaults} object + */ + initFieldDefaults: function() { + if (!this.fieldDefaults) { + this.fieldDefaults = {}; + } + }, + + /** + * @private + * Handle the addition and removal of components in the FieldAncestor component's child tree. + */ + onFieldAncestorSubtreeChange: function(parent, child) { + var me = this, + isAdding = !!child.ownerCt; + + function handleCmp(cmp) { + var isLabelable = cmp.isFieldLabelable, + isField = cmp.isFormField; + if (isLabelable || isField) { + if (isLabelable) { + me['onLabelable' + (isAdding ? 'Added' : 'Removed')](cmp); + } + if (isField) { + me['onField' + (isAdding ? 'Added' : 'Removed')](cmp); + } + } + else if (cmp.isContainer) { + Ext.Array.forEach(cmp.getRefItems(), handleCmp); + } + } + handleCmp(child); + }, + + /** + * Called when a {@link Ext.form.Labelable} instance is added to the container's subtree. + * @param {Ext.form.Labelable} labelable The instance that was added + * @protected + */ + onLabelableAdded: function(labelable) { + var me = this; + + // buffer slightly to avoid excessive firing while sub-fields are changing en masse + me.mon(labelable, 'errorchange', me.handleFieldErrorChange, me, {buffer: 10}); + + labelable.setFieldDefaults(me.fieldDefaults); + }, + + /** + * Called when a {@link Ext.form.field.Field} instance is added to the container's subtree. + * @param {Ext.form.field.Field} field The field which was added + * @protected + */ + onFieldAdded: function(field) { + var me = this; + me.mon(field, 'validitychange', me.handleFieldValidityChange, me); + }, + + /** + * Called when a {@link Ext.form.Labelable} instance is removed from the container's subtree. + * @param {Ext.form.Labelable} labelable The instance that was removed + * @protected + */ + onLabelableRemoved: function(labelable) { + var me = this; + me.mun(labelable, 'errorchange', me.handleFieldErrorChange, me); + }, + + /** + * Called when a {@link Ext.form.field.Field} instance is removed from the container's subtree. + * @param {Ext.form.field.Field} field The field which was removed + * @protected + */ + onFieldRemoved: function(field) { + var me = this; + me.mun(field, 'validitychange', me.handleFieldValidityChange, me); + }, + + /** + * @private Handle validitychange events on sub-fields; invoke the aggregated event and method + */ + handleFieldValidityChange: function(field, isValid) { + var me = this; + me.fireEvent('fieldvaliditychange', me, field, isValid); + me.onFieldValidityChange(field, isValid); + }, + + /** + * @private Handle errorchange events on sub-fields; invoke the aggregated event and method + */ + handleFieldErrorChange: function(labelable, activeError) { + var me = this; + me.fireEvent('fielderrorchange', me, labelable, activeError); + me.onFieldErrorChange(labelable, activeError); + }, + + /** + * Fired when the validity of any field within the container changes. + * @param {Ext.form.field.Field} field The sub-field whose validity changed + * @param {Boolean} valid The new validity state + * @protected + */ + onFieldValidityChange: Ext.emptyFn, + + /** + * Fired when the error message of any field within the container changes. + * @param {Ext.form.Labelable} field The sub-field whose active error changed + * @param {String} error The new active error message + * @protected + */ + onFieldErrorChange: Ext.emptyFn + +}); +/** + * The subclasses of this class provide actions to perform upon {@link Ext.form.Basic Form}s. + * + * Instances of this class are only created by a {@link Ext.form.Basic 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.Basic#submit submit}, {@link Ext.form.Basic#load load} and {@link Ext.form.Basic#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.Basic#submit submit}, {@link Ext.form.Basic#load load} and + * {@link Ext.form.Basic#doAction doAction}), and to the {@link Ext.form.Basic#actioncomplete actioncomplete} and + * {@link Ext.form.Basic#actionfailed actionfailed} event handlers. + */ +Ext.define('Ext.form.action.Action', { + alternateClassName: 'Ext.form.Action', + + /** + * @cfg {Ext.form.Basic} form + * The {@link Ext.form.Basic BasicForm} instance that is invoking this Action. Required. + */ + + /** + * @cfg {String} url + * The URL that the Action is to invoke. Will default to the {@link Ext.form.Basic#url url} configured on the + * {@link #form}. + */ + + /** + * @cfg {Boolean} reset + * When set to **true**, causes the Form to be {@link Ext.form.Basic#reset reset} on Action success. If specified, + * this happens before the {@link #success} callback is called and before the Form's + * {@link Ext.form.Basic#actioncomplete actioncomplete} event fires. + */ + + /** + * @cfg {String} method + * The HTTP method to use to access the requested URL. + * Defaults to the {@link Ext.form.Basic#method BasicForm's method}, or 'POST' if not specified. + */ + + /** + * @cfg {Object/String} params + * Extra parameter values to pass. These are added to the Form's {@link Ext.form.Basic#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 Ext.Object.toQueryString}. + */ + + /** + * @cfg {Object} headers + * Extra headers to be sent in the AJAX request for submit and load actions. + * See {@link Ext.data.proxy.Ajax#headers}. + */ + + /** + * @cfg {Number} timeout + * The number of seconds to wait for a server response before failing with the {@link #failureType} as + * {@link Ext.form.action.Action#CONNECT_FAILURE}. If not specified, defaults to the configured + * {@link Ext.form.Basic#timeout timeout} of the {@link #form}. + */ + + /** + * @cfg {Function} success + * The function to call when a valid success return packet is received. + * @cfg {Ext.form.Basic} success.form The form that requested the action + * @cfg {Ext.form.action.Action} success.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 received, or when an error ocurred in the Ajax communication. + * @cfg {Ext.form.Basic} failure.form The form that requested the action + * @cfg {Ext.form.action.Action} failure.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 configured #success and #failure callback functions + * (the `this` reference for the callback functions). + */ + + /** + * @cfg {String} waitMsg + * The message to be displayed by a call to {@link Ext.window.MessageBox#wait} during the time the action is being + * processed. + */ + + /** + * @cfg {String} waitTitle + * The title to be displayed by a call to {@link Ext.window.MessageBox#wait} during the time the action is being + * processed. + */ + + /** + * @cfg {Boolean} submitEmptyText + * If set to true, the emptyText value will be sent with the form when it is submitted. + */ + submitEmptyText : true, + + /** + * @property {String} type + * The type of action this Action instance performs. Currently only "submit" and "load" are supported. + */ + + /** + * @property {String} failureType + * 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.Panel({ + * ... + * 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.Action.CONNECT_FAILURE) { + * Ext.Msg.alert('Error', + * 'Status:'+action.{@link #response}.status+': '+ + * action.{@link #response}.statusText); + * } + * if (action.failureType === Ext.form.action.Action.SERVER_INVALID){ + * // server responded with success = false + * Ext.Msg.alert('Invalid', action.{@link #result}.errormsg); + * } + * } + * }); + * } + * } + * },{ + * text: 'Reset', + * handler: function(){ + * fp.getForm().reset(); + * } + * }] + */ + + /** + * @property {Object} response + * The raw XMLHttpRequest object used to perform the action. + */ + + /** + * @property {Object} result + * The decoded response object containing a boolean `success` property and other, action-specific properties. + */ + + /** + * Creates new Action. + * @param {Object} [config] Config object. + */ + constructor: function(config) { + if (config) { + Ext.apply(this, config); + } + + // Normalize the params option to an Object + var params = config.params; + if (Ext.isString(params)) { + this.params = Ext.Object.fromQueryString(params); + } + }, + + /** + * @method + * Invokes this action using the current configuration. + */ + run: Ext.emptyFn, + + /** + * @private + * @method onSuccess + * Callback method that gets invoked when the action completes successfully. Must be implemented by subclasses. + * @param {Object} response + */ + + /** + * @private + * @method handleResponse + * Handles the raw response and builds a result object from it. Must be implemented by subclasses. + * @param {Object} response + */ + + /** + * @private + * Handles a failure response. + * @param {Object} response + */ + onFailure : function(response){ + this.response = response; + this.failureType = Ext.form.action.Action.CONNECT_FAILURE; + this.form.afterAction(this, false); + }, + + /** + * @private + * Validates that a response contains either responseText or responseXML and invokes + * {@link #handleResponse} to build the result object. + * @param {Object} response The raw response object. + * @return {Object/Boolean} The result object as built by handleResponse, or `true` if + * the response had empty responseText and responseXML. + */ + processResponse : function(response){ + this.response = response; + if (!response.responseText && !response.responseXML) { + return true; + } + return (this.result = this.handleResponse(response)); + }, + + /** + * @private + * Build the URL for the AJAX request. Used by the standard AJAX submit and load actions. + * @return {String} The URL. + */ + getUrl: function() { + return this.url || this.form.url; + }, + + /** + * @private + * Determine the HTTP method to be used for the request. + * @return {String} The HTTP method + */ + getMethod: function() { + return (this.method || this.form.method || 'POST').toUpperCase(); + }, + + /** + * @private + * Get the set of parameters specified in the BasicForm's baseParams and/or the params option. + * Items in params override items of the same name in baseParams. + * @return {Object} the full set of parameters + */ + getParams: function() { + return Ext.apply({}, this.params, this.form.baseParams); + }, + + /** + * @private + * Creates a callback object. + */ + createCallback: function() { + var me = this, + undef, + form = me.form; + return { + success: me.onSuccess, + failure: me.onFailure, + scope: me, + timeout: (this.timeout * 1000) || (form.timeout * 1000), + upload: form.fileUpload ? me.onSuccess : undef + }; + }, + + statics: { + /** + * @property + * Failure type returned when client side validation of the Form fails thus aborting a submit action. Client + * side validation is performed unless {@link Ext.form.action.Submit#clientValidation} is explicitly set to + * false. + * @static + */ + CLIENT_INVALID: 'client', + + /** + * @property + * 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. + * @static + */ + SERVER_INVALID: 'server', + + /** + * @property + * 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. + * @static + */ + CONNECT_FAILURE: 'connect', + + /** + * @property + * 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. + * @static + */ + LOAD_FAILURE: 'load' + + + } +}); + +/** + * A class which handles submission of data from {@link Ext.form.Basic Form}s and processes the returned response. + * + * Instances of this class are only created by a {@link Ext.form.Basic Form} when + * {@link Ext.form.Basic#submit submit}ting. + * + * # Response Packet Criteria + * + * A response packet may contain: + * + * - **`success`** property : Boolean - required. + * + * - **`errors`** property : Object - 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.Basic}'s callback or event handler + * methods. The object decoded from this JSON is available in the {@link Ext.form.action.Action#result result} property. + * + * Alternatively, if an {@link Ext.form.Basic#errorReader errorReader} is specified as an + * {@link Ext.data.reader.Xml XmlReader}: + * + * errorReader: new Ext.data.reader.Xml({ + * record : 'field', + * success: '@success' + * }, [ + * 'id', 'msg' + * ] + * ) + * + * then the results may be sent back in XML format: + * + * + * + * + * + * clientCode + * This is a test validation message from the server ]]> + * + * + * portOfLoading + * This is a test validation message from the server ]]> + * + * + * + * + * Other elements may be placed into the response XML for processing by the {@link Ext.form.Basic}'s callback or event + * handler methods. The XML document is available in the {@link Ext.form.Basic#errorReader errorReader}'s + * {@link Ext.data.reader.Xml#xmlData xmlData} property. + */ +Ext.define('Ext.form.action.Submit', { + extend:'Ext.form.action.Action', + alternateClassName: 'Ext.form.Action.Submit', + alias: 'formaction.submit', + + type: 'submit', + + /** + * @cfg {Boolean} [clientValidation=true] + * Determines whether a Form's fields are validated in a final call to {@link Ext.form.Basic#isValid isValid} prior + * to submission. Pass false in the Form's submit options to prevent this. + */ + + // inherit docs + run : function(){ + var form = this.form; + if (this.clientValidation === false || form.isValid()) { + this.doSubmit(); + } else { + // client validation failed + this.failureType = Ext.form.action.Action.CLIENT_INVALID; + form.afterAction(this, false); + } + }, + + /** + * @private + * Performs the submit of the form data. + */ + doSubmit: function() { + var formEl, + ajaxOptions = Ext.apply(this.createCallback(), { + url: this.getUrl(), + method: this.getMethod(), + headers: this.headers + }); + + // For uploads we need to create an actual form that contains the file upload fields, + // and pass that to the ajax call so it can do its iframe-based submit method. + if (this.form.hasUpload()) { + formEl = ajaxOptions.form = this.buildForm(); + ajaxOptions.isUpload = true; + } else { + ajaxOptions.params = this.getParams(); + } + + Ext.Ajax.request(ajaxOptions); + + if (formEl) { + Ext.removeNode(formEl); + } + }, + + /** + * @private + * Builds the full set of parameters from the field values plus any additional configured params. + */ + getParams: function() { + var nope = false, + configParams = this.callParent(), + fieldParams = this.form.getValues(nope, nope, this.submitEmptyText !== nope); + return Ext.apply({}, fieldParams, configParams); + }, + + /** + * @private + * Builds a form element containing fields corresponding to all the parameters to be + * submitted (everything returned by {@link #getParams}. + * + * NOTE: the form element is automatically added to the DOM, so any code that uses + * it must remove it from the DOM after finishing with it. + * + * @return {HTMLElement} + */ + buildForm: function() { + var fieldsSpec = [], + formSpec, + formEl, + basicForm = this.form, + params = this.getParams(), + uploadFields = [], + fields = basicForm.getFields().items, + f, + fLen = fields.length, + field, key, value, v, vLen, + u, uLen; + + for (f = 0; f < fLen; f++) { + field = fields[f]; + + if (field.isFileUpload()) { + uploadFields.push(field); + } + } + + function addField(name, val) { + fieldsSpec.push({ + tag: 'input', + type: 'hidden', + name: name, + value: Ext.String.htmlEncode(val) + }); + } + + for (key in params) { + if (params.hasOwnProperty(key)) { + value = params[key]; + + if (Ext.isArray(value)) { + vLen = value.length; + for (v = 0; v < vLen; v++) { + addField(key, value[v]); + } + } else { + addField(key, value); + } + } + } + + formSpec = { + tag: 'form', + action: this.getUrl(), + method: this.getMethod(), + target: this.target || '_self', + style: 'display:none', + cn: fieldsSpec + }; + + // Set the proper encoding for file uploads + if (uploadFields.length) { + formSpec.encoding = formSpec.enctype = 'multipart/form-data'; + } + + // Create the form + formEl = Ext.DomHelper.append(Ext.getBody(), formSpec); + + // Special handling for file upload fields: since browser security measures prevent setting + // their values programatically, and prevent carrying their selected values over when cloning, + // we have to move the actual field instances out of their components and into the form. + uLen = uploadFields.length; + + for (u = 0; u < uLen; u++) { + field = uploadFields[u]; + if (field.rendered) { // can only have a selected file value after being rendered + formEl.appendChild(field.extractFileInput()); + } + } + + return formEl; + }, + + + + /** + * @private + */ + onSuccess: function(response) { + var form = this.form, + success = true, + result = this.processResponse(response); + if (result !== true && !result.success) { + if (result.errors) { + form.markInvalid(result.errors); + } + this.failureType = Ext.form.action.Action.SERVER_INVALID; + success = false; + } + form.afterAction(this, success); + }, + + /** + * @private + */ + handleResponse: function(response) { + var form = this.form, + errorReader = form.errorReader, + rs, errors, i, len, records; + if (errorReader) { + rs = errorReader.read(response); + records = rs.records; + errors = []; + if (records) { + for(i = 0, len = records.length; i < len; i++) { + errors[i] = records[i].data; + } + } + if (errors.length < 1) { + errors = null; + } + return { + success : rs.success, + errors : errors + }; + } + return Ext.decode(response.responseText); + } +}); + +/** + * @docauthor Jason Johnston + * + * This mixin provides a common interface for the logical behavior and state of form fields, including: + * + * - Getter and setter methods for field values + * - Events and methods for tracking value and validity changes + * - Methods for triggering validation + * + * **NOTE**: When implementing custom fields, it is most likely that you will want to extend the {@link Ext.form.field.Base} + * component class rather than using this mixin directly, as BaseField contains additional logic for generating an + * actual DOM complete with {@link Ext.form.Labelable label and error message} display and a form input field, + * plus methods that bind the Field value getters and setters to the input field's value. + * + * If you do want to implement this mixin directly and don't want to extend {@link Ext.form.field.Base}, then + * you will most likely want to override the following methods with custom implementations: {@link #getValue}, + * {@link #setValue}, and {@link #getErrors}. Other methods may be overridden as needed but their base + * implementations should be sufficient for common cases. You will also need to make sure that {@link #initField} + * is called during the component's initialization. + */ +Ext.define('Ext.form.field.Field', { + /** + * @property {Boolean} isFormField + * Flag denoting that this component is a Field. Always true. + */ + isFormField : true, + + /** + * @cfg {Object} value + * A value to initialize this field with. + */ + + /** + * @cfg {String} name + * The name of the field. By default this is used as the parameter name when including the + * {@link #getSubmitData field value} in a {@link Ext.form.Basic#submit form submit()}. To prevent the field from + * being included in the form submit, set {@link #submitValue} to false. + */ + + /** + * @cfg {Boolean} disabled + * True to disable the field. Disabled Fields will not be {@link Ext.form.Basic#submit submitted}. + */ + disabled : false, + + /** + * @cfg {Boolean} submitValue + * Setting this to false will prevent the field from being {@link Ext.form.Basic#submit submitted} even when it is + * not disabled. + */ + submitValue: true, + + /** + * @cfg {Boolean} validateOnChange + * Specifies whether this field should be validated immediately whenever a change in its value is detected. + * If the validation results in a change in the field's validity, a {@link #validitychange} event will be + * fired. This allows the field to show feedback about the validity of its contents immediately as the user is + * typing. + * + * When set to false, feedback will not be immediate. However the form will still be validated before submitting if + * the clientValidation option to {@link Ext.form.Basic#doAction} is enabled, or if the field or form are validated + * manually. + * + * See also {@link Ext.form.field.Base#checkChangeEvents} for controlling how changes to the field's value are + * detected. + */ + validateOnChange: true, + + /** + * @private + */ + suspendCheckChange: 0, + + /** + * Initializes this Field mixin on the current instance. Components using this mixin should call this method during + * their own initialization process. + */ + initField: function() { + this.addEvents( + /** + * @event change + * Fires when the value of a field is changed via the {@link #setValue} method. + * @param {Ext.form.field.Field} this + * @param {Object} newValue The new value + * @param {Object} oldValue The original value + */ + 'change', + /** + * @event validitychange + * Fires when a change in the field's validity is detected. + * @param {Ext.form.field.Field} this + * @param {Boolean} isValid Whether or not the field is now valid + */ + 'validitychange', + /** + * @event dirtychange + * Fires when a change in the field's {@link #isDirty} state is detected. + * @param {Ext.form.field.Field} this + * @param {Boolean} isDirty Whether or not the field is now dirty + */ + 'dirtychange' + ); + + this.initValue(); + }, + + /** + * Initializes the field's value based on the initial config. + */ + initValue: function() { + var me = this; + + /** + * @property {Object} originalValue + * The original value of the field as configured in the {@link #value} configuration, or as loaded by the last + * form load operation if the form's {@link Ext.form.Basic#trackResetOnLoad trackResetOnLoad} setting is `true`. + */ + me.originalValue = me.lastValue = me.value; + + // Set the initial value - prevent validation on initial set + me.suspendCheckChange++; + me.setValue(me.value); + me.suspendCheckChange--; + }, + + /** + * Returns the {@link Ext.form.field.Field#name name} attribute of the field. This is used as the parameter name + * when including the field value in a {@link Ext.form.Basic#submit form submit()}. + * @return {String} name The field {@link Ext.form.field.Field#name name} + */ + getName: function() { + return this.name; + }, + + /** + * Returns the current data value of the field. The type of value returned is particular to the type of the + * particular field (e.g. a Date object for {@link Ext.form.field.Date}). + * @return {Object} value The field value + */ + getValue: function() { + return this.value; + }, + + /** + * Sets a data value into the field and runs the change detection and validation. + * @param {Object} value The value to set + * @return {Ext.form.field.Field} this + */ + setValue: function(value) { + var me = this; + me.value = value; + me.checkChange(); + return me; + }, + + /** + * Returns whether two field {@link #getValue values} are logically equal. Field implementations may override this + * to provide custom comparison logic appropriate for the particular field's data type. + * @param {Object} value1 The first value to compare + * @param {Object} value2 The second value to compare + * @return {Boolean} True if the values are equal, false if inequal. + */ + isEqual: function(value1, value2) { + return String(value1) === String(value2); + }, + + /** + * Returns whether two values are logically equal. + * Similar to {@link #isEqual}, however null or undefined values will be treated as empty strings. + * @private + * @param {Object} value1 The first value to compare + * @param {Object} value2 The second value to compare + * @return {Boolean} True if the values are equal, false if inequal. + */ + isEqualAsString: function(value1, value2){ + return String(Ext.value(value1, '')) === String(Ext.value(value2, '')); + }, + + /** + * Returns the parameter(s) that would be included in a standard form submit for this field. Typically this will be + * an object with a single name-value pair, the name being this field's {@link #getName name} and the value being + * its current stringified value. More advanced field implementations may return more than one name-value pair. + * + * Note that the values returned from this method are not guaranteed to have been successfully {@link #validate + * validated}. + * + * @return {Object} A mapping of submit parameter names to values; each value should be a string, or an array of + * strings if that particular name has multiple values. It can also return null if there are no parameters to be + * submitted. + */ + getSubmitData: function() { + var me = this, + data = null; + if (!me.disabled && me.submitValue && !me.isFileUpload()) { + data = {}; + data[me.getName()] = '' + me.getValue(); + } + return data; + }, + + /** + * Returns the value(s) that should be saved to the {@link Ext.data.Model} instance for this field, when {@link + * Ext.form.Basic#updateRecord} is called. Typically this will be an object with a single name-value pair, the name + * being this field's {@link #getName name} and the value being its current data value. More advanced field + * implementations may return more than one name-value pair. The returned values will be saved to the corresponding + * field names in the Model. + * + * Note that the values returned from this method are not guaranteed to have been successfully {@link #validate + * validated}. + * + * @return {Object} A mapping of submit parameter names to values; each value should be a string, or an array of + * strings if that particular name has multiple values. It can also return null if there are no parameters to be + * submitted. + */ + getModelData: function() { + var me = this, + data = null; + if (!me.disabled && !me.isFileUpload()) { + data = {}; + data[me.getName()] = me.getValue(); + } + return data; + }, + + /** + * Resets the current field value to the originally loaded value and clears any validation messages. See {@link + * Ext.form.Basic}.{@link Ext.form.Basic#trackResetOnLoad trackResetOnLoad} + */ + reset : function(){ + var me = this; + + me.setValue(me.originalValue); + me.clearInvalid(); + // delete here so we reset back to the original state + delete me.wasValid; + }, + + /** + * Resets the field's {@link #originalValue} property so it matches the current {@link #getValue value}. This is + * called by {@link Ext.form.Basic}.{@link Ext.form.Basic#setValues setValues} if the form's + * {@link Ext.form.Basic#trackResetOnLoad trackResetOnLoad} property is set to true. + */ + resetOriginalValue: function() { + this.originalValue = this.getValue(); + this.checkDirty(); + }, + + /** + * Checks whether the value of the field has changed since the last time it was checked. + * If the value has changed, it: + * + * 1. Fires the {@link #change change event}, + * 2. Performs validation if the {@link #validateOnChange} config is enabled, firing the + * {@link #validitychange validitychange event} if the validity has changed, and + * 3. Checks the {@link #isDirty dirty state} of the field and fires the {@link #dirtychange dirtychange event} + * if it has changed. + */ + checkChange: function() { + if (!this.suspendCheckChange) { + var me = this, + newVal = me.getValue(), + oldVal = me.lastValue; + if (!me.isEqual(newVal, oldVal) && !me.isDestroyed) { + me.lastValue = newVal; + me.fireEvent('change', me, newVal, oldVal); + me.onChange(newVal, oldVal); + } + } + }, + + /** + * @private + * Called when the field's value changes. Performs validation if the {@link #validateOnChange} + * config is enabled, and invokes the dirty check. + */ + onChange: function(newVal, oldVal) { + if (this.validateOnChange) { + this.validate(); + } + this.checkDirty(); + }, + + /** + * Returns true if the value of this Field has been changed from its {@link #originalValue}. + * Will always return false if the field is disabled. + * + * Note that if the owning {@link Ext.form.Basic form} was configured with + * {@link Ext.form.Basic#trackResetOnLoad trackResetOnLoad} then the {@link #originalValue} is updated when + * the values are loaded by {@link Ext.form.Basic}.{@link Ext.form.Basic#setValues setValues}. + * @return {Boolean} True if this field has been changed from its original value (and is not disabled), + * false otherwise. + */ + isDirty : function() { + var me = this; + return !me.disabled && !me.isEqual(me.getValue(), me.originalValue); + }, + + /** + * Checks the {@link #isDirty} state of the field and if it has changed since the last time it was checked, + * fires the {@link #dirtychange} event. + */ + checkDirty: function() { + var me = this, + isDirty = me.isDirty(); + if (isDirty !== me.wasDirty) { + me.fireEvent('dirtychange', me, isDirty); + me.onDirtyChange(isDirty); + me.wasDirty = isDirty; + } + }, + + /** + * @private Called when the field's dirty state changes. + * @param {Boolean} isDirty + */ + onDirtyChange: Ext.emptyFn, + + /** + * Runs this field's validators and returns an array of error messages for any validation failures. This is called + * internally during validation and would not usually need to be used manually. + * + * Each subclass should override or augment the return value to provide their own errors. + * + * @param {Object} value The value to get errors for (defaults to the current field value) + * @return {String[]} All error messages for this field; an empty Array if none. + */ + getErrors: function(value) { + return []; + }, + + /** + * Returns whether or not the field value is currently valid by {@link #getErrors validating} the field's current + * value. The {@link #validitychange} event will not be fired; use {@link #validate} instead if you want the event + * to fire. **Note**: {@link #disabled} fields are always treated as valid. + * + * Implementations are encouraged to ensure that this method does not have side-effects such as triggering error + * message display. + * + * @return {Boolean} True if the value is valid, else false + */ + isValid : function() { + var me = this; + return me.disabled || Ext.isEmpty(me.getErrors()); + }, + + /** + * Returns whether or not the field value is currently valid by {@link #getErrors validating} the field's current + * value, and fires the {@link #validitychange} event if the field's validity has changed since the last validation. + * **Note**: {@link #disabled} fields are always treated as valid. + * + * Custom implementations of this method are allowed to have side-effects such as triggering error message display. + * To validate without side-effects, use {@link #isValid}. + * + * @return {Boolean} True if the value is valid, else false + */ + validate : function() { + var me = this, + isValid = me.isValid(); + if (isValid !== me.wasValid) { + me.wasValid = isValid; + me.fireEvent('validitychange', me, isValid); + } + return isValid; + }, + + /** + * A utility for grouping a set of modifications which may trigger value changes into a single transaction, to + * prevent excessive firing of {@link #change} events. This is useful for instance if the field has sub-fields which + * are being updated as a group; you don't want the container field to check its own changed state for each subfield + * change. + * @param {Object} fn A function containing the transaction code + */ + batchChanges: function(fn) { + try { + this.suspendCheckChange++; + fn(); + } catch(e){ + throw e; + } finally { + this.suspendCheckChange--; + } + this.checkChange(); + }, + + /** + * Returns whether this Field is a file upload field; if it returns true, forms will use special techniques for + * {@link Ext.form.Basic#submit submitting the form} via AJAX. See {@link Ext.form.Basic#hasUpload} for details. If + * this returns true, the {@link #extractFileInput} method must also be implemented to return the corresponding file + * input element. + * @return {Boolean} + */ + isFileUpload: function() { + return false; + }, + + /** + * Only relevant if the instance's {@link #isFileUpload} method returns true. Returns a reference to the file input + * DOM element holding the user's selected file. The input will be appended into the submission form and will not be + * returned, so this method should also create a replacement. + * @return {HTMLElement} + */ + extractFileInput: function() { + return null; + }, + + /** + * @method markInvalid + * Associate one or more error messages with this field. Components using this mixin should implement this method to + * update the component's rendering to display the messages. + * + * **Note**: this method does not cause the Field's {@link #validate} or {@link #isValid} methods to return `false` + * if the value does _pass_ validation. So simply marking a Field as invalid will not prevent submission of forms + * submitted with the {@link Ext.form.action.Submit#clientValidation} option set. + * + * @param {String/String[]} errors The error message(s) for the field. + */ + markInvalid: Ext.emptyFn, + + /** + * @method clearInvalid + * Clear any invalid styles/messages for this field. Components using this mixin should implement this method to + * update the components rendering to clear any existing messages. + * + * **Note**: this method does not cause the Field's {@link #validate} or {@link #isValid} methods to return `true` + * if the value does not _pass_ validation. So simply clearing a field's errors will not necessarily allow + * submission of forms submitted with the {@link Ext.form.action.Submit#clientValidation} option set. + */ + clearInvalid: Ext.emptyFn + +}); + +/** + * @singleton + * @alternateClassName Ext.form.VTypes + * + * This is a singleton object which contains a set of commonly used field validation functions + * and provides a mechanism for creating reusable custom field validations. + * The following field validation functions are provided out of the box: + * + * - {@link #alpha} + * - {@link #alphanum} + * - {@link #email} + * - {@link #url} + * + * VTypes can be applied to a {@link Ext.form.field.Text Text Field} using the `{@link Ext.form.field.Text#vtype vtype}` configuration: + * + * Ext.create('Ext.form.field.Text', { + * fieldLabel: 'Email Address', + * name: 'email', + * vtype: 'email' // applies email validation rules to this field + * }); + * + * To create custom VTypes: + * + * // 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.field.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 + * }); + * + * In the above example the `time` function is the validator that will run when field validation occurs, + * `timeText` is the error message, and `timeMask` limits what characters can be typed into the field. + * Note that the `Text` and `Mask` functions must begin with the same name as the validator function. + * + * Using a custom validator is the same as using one of the build-in validators - just use the name of the validator function + * as the `{@link Ext.form.field.Text#vtype vtype}` configuration on a {@link Ext.form.field.Text Text Field}: + * + * Ext.create('Ext.form.field.Text', { + * fieldLabel: 'Departure Time', + * name: 'departureTime', + * vtype: 'time' // applies custom time validation rules to this field + * }); + * + * Another example of a custom validator: + * + * // custom Vtype for vtype:'IPAddress' + * Ext.apply(Ext.form.field.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 + * }); + * + * It's important to note that using {@link Ext#apply Ext.apply()} means that the custom validator function + * as well as `Text` and `Mask` fields are added as properties of the `Ext.form.field.VTypes` singleton. + */ +Ext.define('Ext.form.field.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,6}$/, + url = /(((^https?)|(^ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i; + + // All these messages and functions are configurable + return { + singleton: true, + alternateClassName: 'Ext.form.VTypes', + + /** + * 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][1] 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` + * + * [1]: http://en.wikipedia.org/wiki/E-mail_address + * + * @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); + }, + /** + * @property {String} emailText + * 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"' + */ + // + 'emailText' : 'This field should be an e-mail address in the format "user@example.com"', + // + /** + * @property {RegExp} emailMask + * 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 + */ + 'emailMask' : /[a-z0-9_\.\-@\+]/i, + + /** + * 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); + }, + /** + * @property {String} urlText + * 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"' + */ + // + 'urlText' : 'This field should be a URL in the format "http:/'+'/www.example.com"', + // + + /** + * 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); + }, + /** + * @property {String} alphaText + * The error text to display when the alpha validation function returns false. + * Defaults to: 'This field should only contain letters and _' + */ + // + 'alphaText' : 'This field should only contain letters and _', + // + /** + * @property {RegExp} alphaMask + * The keystroke filter mask to be applied on alpha input. Defaults to: /[a-z_]/i + */ + 'alphaMask' : /[a-z_]/i, + + /** + * 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); + }, + /** + * @property {String} alphanumText + * The error text to display when the alphanumeric validation function returns false. + * Defaults to: 'This field should only contain letters, numbers and _' + */ + // + 'alphanumText' : 'This field should only contain letters, numbers and _', + // + /** + * @property {RegExp} alphanumMask + * The keystroke filter mask to be applied on alphanumeric input. Defaults to: /[a-z0-9_]/i + */ + 'alphanumMask' : /[a-z0-9_]/i + }; +}())); + +/** + * This class is used internally to provide a single interface when using + * a locking grid. Internally, the locking grid creates two separate grids, + * so this class is used to map calls appropriately. + * @private + */ +Ext.define('Ext.grid.LockingView', { + + mixins: { + observable: 'Ext.util.Observable' + }, + + eventRelayRe: /^(beforeitem|beforecontainer|item|container|cell)/, + + constructor: function(config){ + var me = this, + eventNames = [], + eventRe = me.eventRelayRe, + locked = config.locked.getView(), + normal = config.normal.getView(), + events, + event; + + Ext.apply(me, { + lockedView: locked, + normalView: normal, + lockedGrid: config.locked, + normalGrid: config.normal, + panel: config.panel + }); + me.mixins.observable.constructor.call(me, config); + + // relay events + events = locked.events; + for (event in events) { + if (events.hasOwnProperty(event) && eventRe.test(event)) { + eventNames.push(event); + } + } + me.relayEvents(locked, eventNames); + me.relayEvents(normal, eventNames); + + normal.on({ + scope: me, + itemmouseleave: me.onItemMouseLeave, + itemmouseenter: me.onItemMouseEnter + }); + + locked.on({ + scope: me, + itemmouseleave: me.onItemMouseLeave, + itemmouseenter: me.onItemMouseEnter + }); + }, + + getGridColumns: function() { + var cols = this.lockedGrid.headerCt.getGridColumns(); + return cols.concat(this.normalGrid.headerCt.getGridColumns()); + }, + + getEl: function(column){ + return this.getViewForColumn(column).getEl(); + }, + + getViewForColumn: function(column) { + var view = this.lockedView, + inLocked; + + view.headerCt.cascade(function(col){ + if (col === column) { + inLocked = true; + return false; + } + }); + + return inLocked ? view : this.normalView; + }, + + onItemMouseEnter: function(view, record){ + var me = this, + locked = me.lockedView, + other = me.normalView, + item; + + if (view.trackOver) { + if (view !== locked) { + other = locked; + } + item = other.getNode(record); + other.highlightItem(item); + } + }, + + onItemMouseLeave: function(view, record){ + var me = this, + locked = me.lockedView, + other = me.normalView; + + if (view.trackOver) { + if (view !== locked) { + other = locked; + } + other.clearHighlight(); + } + }, + + relayFn: function(name, args){ + args = args || []; + + var view = this.lockedView; + view[name].apply(view, args || []); + view = this.normalView; + view[name].apply(view, args || []); + }, + + getSelectionModel: function(){ + return this.panel.getSelectionModel(); + }, + + getStore: function(){ + return this.panel.store; + }, + + getNode: function(nodeInfo){ + // default to the normal view + return this.normalView.getNode(nodeInfo); + }, + + getCell: function(record, column){ + var view = this.getViewForColumn(column), + row; + + row = view.getNode(record); + return Ext.fly(row).down(column.getCellSelector()); + }, + + getRecord: function(node){ + var result = this.lockedView.getRecord(node); + if (!node) { + result = this.normalView.getRecord(node); + } + return result; + }, + + addElListener: function(eventName, fn, scope){ + this.relayFn('addElListener', arguments); + }, + + refreshNode: function(){ + this.relayFn('refreshNode', arguments); + }, + + refresh: function(){ + this.relayFn('refresh', arguments); + }, + + bindStore: function(){ + this.relayFn('bindStore', arguments); + }, + + addRowCls: function(){ + this.relayFn('addRowCls', arguments); + }, + + removeRowCls: function(){ + this.relayFn('removeRowCls', arguments); + } + +}); +/** + * This class monitors scrolling of the {@link Ext.view.Table TableView} within a + * {@link Ext.grid.Panel GridPanel} which is using a buffered store to only cache + * and render a small section of a very large dataset. + * + * The GridPanel will instantiate this to perform monitoring, this class should + * never be instantiated by user code. + */ +Ext.define('Ext.grid.PagingScroller', { + + /** + * @cfg + * @deprecated This config is now ignored. + */ + percentageFromEdge: 0.35, + + /** + * @cfg + * The zone which causes a refresh of the rendered viewport. As soon as the edge + * of the rendered grid is this number of rows from the edge of the viewport, the view is moved. + */ + numFromEdge: 2, + + /** + * @cfg + * The number of extra rows to render on the trailing side of scrolling + * **outside the {@link #numFromEdge}** buffer as scrolling proceeds. + */ + trailingBufferZone: 5, + + /** + * @cfg + * The number of extra rows to render on the leading side of scrolling + * **outside the {@link #numFromEdge}** buffer as scrolling proceeds. + */ + leadingBufferZone: 15, + + /** + * @cfg + * This is the time in milliseconds to buffer load requests when scrolling the PagingScrollbar. + */ + scrollToLoadBuffer: 200, + + // private. Initial value of zero. + viewSize: 0, + // private. Start at default value + rowHeight: 21, + // private. Table extent at startup time + tableStart: 0, + tableEnd: 0, + + constructor: function(config) { + var me = this; + me.variableRowHeight = config.variableRowHeight; + me.bindView(config.view); + Ext.apply(me, config); + me.callParent(arguments); + }, + + bindView: function(view) { + var me = this, + viewListeners = { + scroll: { + fn: me.onViewScroll, + element: 'el', + scope: me + }, + render: me.onViewRender, + resize: me.onViewResize, + boxready: { + fn: me.onViewResize, + scope: me, + single: true + }, + refresh: me.onViewRefresh, + scope: me + }, + storeListeners = { + guaranteedrange: me.onGuaranteedRange, + scope: me + }, + gridListeners = { + reconfigure: me.onGridReconfigure, + scope: me + }; + + // If there are variable row heights, then in beforeRefresh, we have to find a common + // row so that we can synchronize the table's top position after the refresh + if (me.variableRowHeight) { + viewListeners.beforerefresh = me.beforeViewRefresh; + } + + // If we need unbinding... + if (me.view) { + me.view.el.un('scroll', me.onViewScroll, me); // un does not understand the element options + me.view.un(viewListeners); + me.store.un(storeListeners); + if (me.grid) { + me.grid.un(gridListeners); + } + delete me.view.refreshSize; // Remove the injected refreshSize implementation + } + + me.view = view; + me.grid = me.view.up('tablepanel'); + me.store = view.store; + if (view.rendered) { + me.viewSize = me.store.viewSize = Math.ceil(view.getHeight() / me.rowHeight) + me.trailingBufferZone + (me.numFromEdge * 2) + me.leadingBufferZone; + } + + // During scrolling we do not need to refresh the height - the Grid height must be set by config or layout in order to create a scrollable + // table just larger than that, so removing the layout call improves efficiency and removes the flicker when the + // HeaderContainer is reset to scrollLeft:0, and then resynced on the very next "scroll" event. + me.view.refreshSize = Ext.Function.createInterceptor(me.view.refreshSize, me.beforeViewrefreshSize, me); + + /** + * @property {Number} position + * Current pixel scroll position of the associated {@link Ext.view.Table View}. + */ + me.position = 0; + + // We are created in View constructor. There won't be an ownerCt at this time. + if (me.grid) { + me.grid.on(gridListeners); + } else { + me.view.on({ + added: function() { + me.grid = me.view.up('tablepanel'); + me.grid.on(gridListeners); + }, + single: true + }); + } + + me.view.on(me.viewListeners = viewListeners); + me.store.on(storeListeners); + }, + + onGridReconfigure: function (grid) { + this.bindView(grid.view); + }, + + // Ensure that the stretcher element is inserted into the View as the first element. + onViewRender: function() { + var me = this, + el = me.view.el; + + el.setStyle('position', 'relative'); + me.stretcher = el.createChild({ + style:{ + position: 'absolute', + width: '1px', + height: 0, + top: 0, + left: 0 + } + }, el.dom.firstChild); + }, + + onViewResize: function(view, width, height) { + var me = this, + newViewSize; + + newViewSize = Math.ceil(height / me.rowHeight) + me.trailingBufferZone + (me.numFromEdge * 2) + me.leadingBufferZone; + if (newViewSize > me.viewSize) { + me.viewSize = me.store.viewSize = newViewSize; + me.handleViewScroll(me.lastScrollDirection || 1); + } + }, + + // Used for variable row heights. Try to find the offset from scrollTop of a common row + beforeViewRefresh: function() { + var me = this, + view = me.view, + rows, + direction = me.lastScrollDirection; + + me.commonRecordIndex = undefined; + + // If we are refreshing in response to a scroll, + // And we know where the previous start was, + // and we're not teleporting out of visible range + if (direction && (me.previousStart !== undefined) && (me.scrollProportion === undefined)) { + rows = view.getNodes(); + + // We have scrolled downwards + if (direction === 1) { + + // If the ranges overlap, we are going to be able to position the table exactly + if (me.tableStart <= me.previousEnd) { + me.commonRecordIndex = rows.length - 1; + + } + } + // We have scrolled upwards + else if (direction === -1) { + + // If the ranges overlap, we are going to be able to position the table exactly + if (me.tableEnd >= me.previousStart) { + me.commonRecordIndex = 0; + } + } + // Cache the old offset of the common row from the scrollTop + me.scrollOffset = -view.el.getOffsetsTo(rows[me.commonRecordIndex])[1]; + + // In the new table the common row is at a different index + me.commonRecordIndex -= (me.tableStart - me.previousStart); + } else { + me.scrollOffset = undefined; + } + }, + + // Used for variable row heights. Try to find the offset from scrollTop of a common row + // Ensure, upon each refresh, that the stretcher element is the correct height + onViewRefresh: function() { + var me = this, + store = me.store, + newScrollHeight, + view = me.view, + viewEl = view.el, + viewDom = viewEl.dom, + rows, + newScrollOffset, + scrollDelta, + table = viewEl.child('table', true), + tableTop, + scrollTop; + + // Scroll events caused by processing in here must be ignored, so disable for the duration + me.disabled = true; + + // No scroll monitoring is needed if + // All data is in view OR + // Store is filtered locally. + // - scrolling a locally filtered page is obv a local operation within the context of a huge set of pages + // so local scrolling is appropriate. + if (store.getCount() === store.getTotalCount() || (store.isFiltered() && !store.remoteFilter)) { + me.stretcher.setHeight(0); + me.position = viewDom.scrollTop = 0; + + // Chrome's scrolling went crazy upon zeroing of the stretcher, and left the view's scrollTop stuck at -15 + // This is the only thing that fixes that + table.style.position = 'absolute'; + + // We remain disabled now because no scrolling is needed - we have the full dataset in the Store + return; + } + + me.stretcher.setHeight(newScrollHeight = me.getScrollHeight()); + + scrollTop = viewDom.scrollTop; + + // Flag to the refreshSize interceptor that regular refreshSize postprocessing should be vetoed. + me.isScrollRefresh = (scrollTop > 0); + + // If we have had to calculate the store position from the pure scroll bar position, + // then we must calculate the table's vertical position from the scrollProportion + if (me.scrollProportion !== undefined) { + me.scrollProportion = scrollTop / (newScrollHeight - table.offsetHeight); + table.style.position = 'absolute'; + table.style.top = (me.scrollProportion ? (newScrollHeight * me.scrollProportion) - (table.offsetHeight * me.scrollProportion) : 0) + 'px'; + } + else { + table.style.position = 'absolute'; + table.style.top = (tableTop = (me.tableStart||0) * me.rowHeight) + 'px'; + + // ScrollOffset to a common row was calculated in beforeViewRefresh, so we can synch table position with how it was before + if (me.scrollOffset) { + rows = view.getNodes(); + newScrollOffset = -viewEl.getOffsetsTo(rows[me.commonRecordIndex])[1]; + scrollDelta = newScrollOffset - me.scrollOffset; + me.position = (scrollTop += scrollDelta); + } + + // If the table is not fully in view view, scroll to where it is in view. + // This will happen when the page goes out of view unexpectedly, outside the + // control of the PagingScroller. For example, a refresh caused by a remote sort or filter reverting + // back to page 1. + // Note that with buffered Stores, only remote sorting is allowed, otherwise the locally + // sorted page will be out of order with the whole dataset. + else if ((tableTop > scrollTop) || ((tableTop + table.offsetHeight) < scrollTop + viewDom.clientHeight)) { + me.lastScrollDirection = -1; + me.position = viewDom.scrollTop = tableTop; + } + } + + // Re-enable upon function exit + me.disabled = false; + }, + + beforeViewrefreshSize: function() { + // Veto the refreshSize if the refresh is due to a scroll. + if (this.isScrollRefresh) { + return (this.isScrollRefresh = false); + } + }, + + onGuaranteedRange: function(range, start, end) { + var me = this, + ds = me.store; + + // this should never happen + if (range.length && me.visibleStart < range[0].index) { + return; + } + + // Cache last table position in dataset so that if we are using variableRowHeight, + // we can attempt to locate a common row to align the table on. + me.previousStart = me.tableStart; + me.previousEnd = me.tableEnd; + + me.tableStart = start; + me.tableEnd = end; + ds.loadRecords(range); + }, + + onViewScroll: function(e, t) { + var me = this, + view = me.view, + lastPosition = me.position; + + me.position = view.el.dom.scrollTop; + + // Only check for nearing the edge if we are enabled. + // If there is no paging to be done (Store's dataset is all in memory) we will be disabled. + if (!me.disabled) { + me.lastScrollDirection = me.position > lastPosition ? 1 : -1; + // Check the position so we ignore horizontal scrolling + if (lastPosition !== me.position) { + me.handleViewScroll(me.lastScrollDirection); + } + } + }, + + handleViewScroll: function(direction) { + var me = this, + store = me.store, + view = me.view, + viewSize = me.viewSize, + totalCount = store.getTotalCount(), + highestStartPoint = totalCount - viewSize, + visibleStart = me.getFirstVisibleRowIndex(), + visibleEnd = me.getLastVisibleRowIndex(), + requestStart, + requestEnd; + + // Only process if the total rows is larger than the visible page size + if (totalCount >= viewSize) { + + // This is only set if we are using variable row height, and the thumb is dragged so that + // There are no remaining visible rows to vertically anchor the new table to. + // In this case we use the scrollProprtion to anchor the table to the correct relative + // position on the vertical axis. + me.scrollProportion = undefined; + + // We're scrolling up + if (direction == -1) { + if (visibleStart !== undefined) { + if (visibleStart < (me.tableStart + me.numFromEdge)) { + requestStart = Math.max(0, visibleEnd + me.trailingBufferZone - viewSize); + } + } + + // The only way we can end up without a visible start is if, in variableRowHeight mode, the user drags + // the thumb up out of the visible range. In this case, we have to estimate the start row index + else { + // If we have no visible rows to orientate with, then use the scroll proportion + me.scrollProportion = view.el.dom.scrollTop / (view.el.dom.scrollHeight - view.el.dom.clientHeight); + requestStart = Math.max(0, totalCount * me.scrollProportion - (viewSize / 2) - me.numFromEdge - ((me.leadingBufferZone + me.trailingBufferZone) / 2)); + } + } + // We're scrolling down + else { + if (visibleStart !== undefined) { + if (visibleEnd > (me.tableEnd - me.numFromEdge)) { + requestStart = Math.max(0, visibleStart - me.trailingBufferZone); + } + } + + // The only way we can end up without a visible end is if, in variableRowHeight mode, the user drags + // the thumb down out of the visible range. In this case, we have to estimate the start row index + else { + // If we have no visible rows to orientate with, then use the scroll proportion + me.scrollProportion = view.el.dom.scrollTop / (view.el.dom.scrollHeight - view.el.dom.clientHeight); + requestStart = totalCount * me.scrollProportion - (viewSize / 2) - me.numFromEdge - ((me.leadingBufferZone + me.trailingBufferZone) / 2); + } + } + + // We scrolled close to the edge and the Store needs reloading + if (requestStart !== undefined) { + // The calculation walked off the end; Request the highest possible chunk which starts on an even row count (Because of row striping) + if (requestStart > highestStartPoint) { + requestStart = highestStartPoint & ~1; + requestEnd = totalCount - 1; + } + // Make sure first row is even to ensure correct even/odd row striping + else { + requestStart = requestStart & ~1; + requestEnd = requestStart + viewSize - 1; + } + + // If range is satsfied within the prefetch buffer, then just draw it from the prefetch buffer + if (store.rangeCached(requestStart, requestEnd)) { + me.cancelLoad(); + store.guaranteeRange(requestStart, requestEnd); + } + + // Required range is not in the prefetch buffer. Ask the store to prefetch it. + // We will recieve a guaranteedrange event when that is done. + else { + me.attemptLoad(requestStart, requestEnd); + } + } + } + }, + + getFirstVisibleRowIndex: function() { + var me = this, + store = me.store, + view = me.view, + scrollTop = view.el.dom.scrollTop, + rows, + count, + i, + rowBottom; + + if (me.variableRowHeight) { + rows = view.getNodes(); + count = store.getCount(); + for (i = 0; i < count; i++) { + rowBottom = Ext.fly(rows[i]).getOffsetsTo(view.el)[1] + rows[i].offsetHeight; + + // Searching for the first visible row, and off the bottom of the clientArea, then there's no visible first row! + if (rowBottom > view.el.dom.clientHeight) { + return; + } + + if (rowBottom > 0) { + return i + me.tableStart; + } + } + } else { + return Math.floor(scrollTop / me.rowHeight); + } + }, + + getLastVisibleRowIndex: function() { + var me = this, + store = me.store, + view = me.view, + clientHeight = view.el.dom.clientHeight, + rows, + count, + i, + rowTop; + + if (me.variableRowHeight) { + rows = view.getNodes(); + count = store.getCount(); + for (i = count - 1; i >= 0; i--) { + rowTop = Ext.fly(rows[i]).getOffsetsTo(view.el)[1]; + + // Searching for the last visible row, and off the top of the clientArea, then there's no visible last row! + if (rowTop < 0) { + return; + } + if (rowTop < clientHeight) { + return i + me.tableStart; + } + } + } else { + return me.getFirstVisibleRowIndex() + Math.ceil(clientHeight / me.rowHeight) + 1; + } + }, + + getScrollHeight: function() { + var me = this, + view = me.view, + table, + firstRow, + store = me.store, + deltaHeight = 0, + doCalcHeight = !me.hasOwnProperty('rowHeight'); + + if (me.variableRowHeight) { + table = me.view.el.down('table', true); + if (doCalcHeight) { + me.initialTableHeight = table.offsetHeight; + me.rowHeight = me.initialTableHeight / me.store.getCount(); + } else { + deltaHeight = table.offsetHeight - me.initialTableHeight; + } + } else if (doCalcHeight) { + firstRow = view.el.down(view.getItemSelector()); + if (firstRow) { + me.rowHeight = firstRow.getHeight(false, true); + } + } + + return Math.floor(store.getTotalCount() * me.rowHeight) + deltaHeight; + }, + + attemptLoad: function(start, end) { + var me = this; + if (me.scrollToLoadBuffer) { + if (!me.loadTask) { + me.loadTask = new Ext.util.DelayedTask(me.doAttemptLoad, me, []); + } + me.loadTask.delay(me.scrollToLoadBuffer, me.doAttemptLoad, me, [start, end]); + } else { + me.store.guaranteeRange(start, end); + } + }, + + cancelLoad: function() { + if (this.loadTask) { + this.loadTask.cancel(); + } + }, + + doAttemptLoad: function(start, end) { + this.store.guaranteeRange(start, end); + }, + + destroy: function() { + var me = this, + scrollListener = me.viewListeners.scroll; + + me.store.un({ + guaranteedrange: me.onGuaranteedRange, + scope: me + }); + me.view.un(me.viewListeners); + if (me.view.rendered) { + me.stretcher.remove(); + me.view.el.un('scroll', scrollListener.fn, scrollListener.scope); + } + } +}); + +Ext.define('Ext.grid.Scroller', { + constructor: Ext.deprecated() +}); + +/** + * A feature is a type of plugin that is specific to the {@link Ext.grid.Panel}. It provides several + * hooks that allows the developer to inject additional functionality at certain points throughout the + * grid creation cycle. This class provides the base template methods that are available to the developer, + * it should be extended. + * + * There are several built in features that extend this class, for example: + * + * - {@link Ext.grid.feature.Grouping} - Shows grid rows in groups as specified by the {@link Ext.data.Store} + * - {@link Ext.grid.feature.RowBody} - Adds a body section for each grid row that can contain markup. + * - {@link Ext.grid.feature.Summary} - Adds a summary row at the bottom of the grid with aggregate totals for a column. + * + * ## Using Features + * A feature is added to the grid by specifying it an array of features in the configuration: + * + * var groupingFeature = Ext.create('Ext.grid.feature.Grouping'); + * Ext.create('Ext.grid.Panel', { + * // other options + * features: [groupingFeature] + * }); + * + * @abstract + */ +Ext.define('Ext.grid.feature.Feature', { + extend: 'Ext.util.Observable', + alias: 'feature.feature', + + /* + * @property {Boolean} isFeature + * `true` in this class to identify an object as an instantiated Feature, or subclass thereof. + */ + isFeature: true, + + /** + * True when feature is disabled. + */ + disabled: false, + + /** + * @property {Boolean} + * Most features will expose additional events, some may not and will + * need to change this to false. + */ + hasFeatureEvent: true, + + /** + * @property {String} + * Prefix to use when firing events on the view. + * For example a prefix of group would expose "groupclick", "groupcontextmenu", "groupdblclick". + */ + eventPrefix: null, + + /** + * @property {String} + * Selector used to determine when to fire the event with the eventPrefix. + */ + eventSelector: null, + + /** + * @property {Ext.view.Table} + * Reference to the TableView. + */ + view: null, + + /** + * @property {Ext.grid.Panel} + * Reference to the grid panel + */ + grid: null, + + /** + * Most features will not modify the data returned to the view. + * This is limited to one feature that manipulates the data per grid view. + */ + collectData: false, + + init: Ext.emptyFn, + + getFeatureTpl: function() { + return ''; + }, + + /** + * Abstract method to be overriden when a feature should add additional + * arguments to its event signature. By default the event will fire: + * + * - view - The underlying Ext.view.Table + * - featureTarget - The matched element by the defined {@link #eventSelector} + * + * The method must also return the eventName as the first index of the array + * to be passed to fireEvent. + * @template + */ + getFireEventArgs: function(eventName, view, featureTarget, e) { + return [eventName, view, featureTarget, e]; + }, + + /** + * Approriate place to attach events to the view, selectionmodel, headerCt, etc + * @template + */ + attachEvents: function() { + + }, + + getFragmentTpl: Ext.emptyFn, + + /** + * Allows a feature to mutate the metaRowTpl. + * The array received as a single argument can be manipulated to add things + * on the end/begining of a particular row. + * @param {Array} metaRowTplArray A String array to be used constructing an {@link Ext.XTemplate XTemplate} + * to render the rows. This Array may be changed to provide extra DOM structure. + * @template + */ + mutateMetaRowTpl: Ext.emptyFn, + + /** + * Allows a feature to inject member methods into the metaRowTpl. This is + * important for embedding functionality which will become part of the proper + * row tpl. + * @template + */ + getMetaRowTplFragments: function() { + return {}; + }, + + getTableFragments: function() { + return {}; + }, + + /** + * Provide additional data to the prepareData call within the grid view. + * @param {Object} data The data for this particular record. + * @param {Number} idx The row index for this record. + * @param {Ext.data.Model} record The record instance + * @param {Object} orig The original result from the prepareData call to massage. + * @template + */ + getAdditionalData: function(data, idx, record, orig) { + return {}; + }, + + /** + * Enables the feature. + */ + enable: function() { + this.disabled = false; + }, + + /** + * Disables the feature. + */ + disable: function() { + this.disabled = true; + } + +}); +/** + * This feature allows to display the grid rows aggregated into groups as specified by the {@link Ext.data.Store#groupers} + * specified on the Store. The group will show the title for the group name and then the appropriate records for the group + * underneath. The groups can also be expanded and collapsed. + * + * ## Extra Events + * This feature adds several extra events that will be fired on the grid to interact with the groups: + * + * - {@link #groupclick} + * - {@link #groupdblclick} + * - {@link #groupcontextmenu} + * - {@link #groupexpand} + * - {@link #groupcollapse} + * + * ## Menu Augmentation + * This feature adds extra options to the grid column menu to provide the user with functionality to modify the grouping. + * This can be disabled by setting the {@link #enableGroupingMenu} option. The option to disallow grouping from being turned off + * by thew user is {@link #enableNoGroups}. + * + * ## Controlling Group Text + * The {@link #groupHeaderTpl} is used to control the rendered title for each group. It can modified to customized + * the default display. + * + * ## Example Usage + * + * var groupingFeature = Ext.create('Ext.grid.feature.Grouping', { + * groupHeaderTpl: 'Group: {name} ({rows.length})', //print the number of items in the group + * startCollapsed: true // start all groups collapsed + * }); + * + * @author Nicolas Ferrero + */ +Ext.define('Ext.grid.feature.Grouping', { + extend: 'Ext.grid.feature.Feature', + alias: 'feature.grouping', + + eventPrefix: 'group', + eventSelector: '.' + Ext.baseCSSPrefix + 'grid-group-hd', + bodySelector: '.' + Ext.baseCSSPrefix + 'grid-group-body', + + constructor: function() { + var me = this; + + me.collapsedState = {}; + me.callParent(arguments); + }, + + /** + * @event groupclick + * @param {Ext.view.Table} view + * @param {HTMLElement} node + * @param {String} group The name of the group + * @param {Ext.EventObject} e + */ + + /** + * @event groupdblclick + * @param {Ext.view.Table} view + * @param {HTMLElement} node + * @param {String} group The name of the group + * @param {Ext.EventObject} e + */ + + /** + * @event groupcontextmenu + * @param {Ext.view.Table} view + * @param {HTMLElement} node + * @param {String} group The name of the group + * @param {Ext.EventObject} e + */ + + /** + * @event groupcollapse + * @param {Ext.view.Table} view + * @param {HTMLElement} node + * @param {String} group The name of the group + * @param {Ext.EventObject} e + */ + + /** + * @event groupexpand + * @param {Ext.view.Table} view + * @param {HTMLElement} node + * @param {String} group The name of the group + * @param {Ext.EventObject} e + */ + + /** + * @cfg {String/Array/Ext.Template} groupHeaderTpl + * A string Template snippet, an array of strings (optionally followed by an object containing Template methods) to be used to construct a Template, or a Template instance. + * + * - Example 1 (Template snippet): + * + * groupHeaderTpl: 'Group: {name}' + * + * - Example 2 (Array): + * + * groupHeaderTpl: [ + * 'Group: ', + * '
    {name:this.formatName}
    ', + * { + * formatName: function(name) { + * return Ext.String.trim(name); + * } + * } + * ] + * + * - Example 3 (Template Instance): + * + * groupHeaderTpl: Ext.create('Ext.XTemplate', + * 'Group: ', + * '
    {name:this.formatName}
    ', + * { + * formatName: function(name) { + * return Ext.String.trim(name); + * } + * } + * ) + * + * @cfg {String} groupHeaderTpl.groupField The field name being grouped by. + * @cfg {String} groupHeaderTpl.columnName The column header associated with the field being grouped by *if there is a column for the field*, falls back to the groupField name. + * @cfg {Mixed} groupHeaderTpl.groupValue The value of the {@link Ext.data.Store#groupField groupField} for the group header being rendered. + * @cfg {String} groupHeaderTpl.renderedGroupValue The rendered value of the {@link Ext.data.Store#groupField groupField} for the group header being rendered, as produced by the column renderer. + * @cfg {String} groupHeaderTpl.name An alias for renderedGroupValue + * @cfg {Object[]} groupHeaderTpl.rows An array of child row data objects as returned by the View's {@link Ext.view.AbstractView#prepareData prepareData} method. + * @cfg {Ext.data.Model[]} groupHeaderTpl.children An array containing the child records for the group being rendered. + */ + groupHeaderTpl: '{columnName}: {name}', + + /** + * @cfg {Number} depthToIndent + * Number of pixels to indent per grouping level + */ + depthToIndent: 17, + + collapsedCls: Ext.baseCSSPrefix + 'grid-group-collapsed', + hdCollapsedCls: Ext.baseCSSPrefix + 'grid-group-hd-collapsed', + + // + /** + * @cfg + * Text displayed in the grid header menu for grouping by header. + */ + groupByText : 'Group By This Field', + // + // + /** + * @cfg + * Text displayed in the grid header for enabling/disabling grouping. + */ + showGroupsText : 'Show in Groups', + // + + /** + * @cfg + * True to hide the header that is currently grouped. + */ + hideGroupedHeader : false, + + /** + * @cfg + * True to start all groups collapsed. + */ + startCollapsed : false, + + /** + * @cfg + * True to enable the grouping control in the header menu. + */ + enableGroupingMenu : true, + + /** + * @cfg + * True to allow the user to turn off grouping. + */ + enableNoGroups : true, + + enable: function() { + var me = this, + view = me.view, + store = view.store, + groupToggleMenuItem; + + me.lastGroupField = me.getGroupField(); + + if (me.lastGroupIndex) { + store.group(me.lastGroupIndex); + } + me.callParent(); + groupToggleMenuItem = me.view.headerCt.getMenu().down('#groupToggleMenuItem'); + groupToggleMenuItem.setChecked(true, true); + me.refreshIf(); + }, + + disable: function() { + var me = this, + view = me.view, + store = view.store, + remote = store.remoteGroup, + groupToggleMenuItem, + lastGroup; + + lastGroup = store.groupers.first(); + if (lastGroup) { + me.lastGroupIndex = lastGroup.property; + me.block(); + store.clearGrouping(); + me.unblock(); + } + + me.callParent(); + groupToggleMenuItem = me.view.headerCt.getMenu().down('#groupToggleMenuItem'); + groupToggleMenuItem.setChecked(true, true); + groupToggleMenuItem.setChecked(false, true); + if (!remote) { + view.refresh(); + } + }, + + refreshIf: function() { + if (this.blockRefresh !== true) { + + // We are one side of a lockable grid, so refresh the locking view + if (this.grid.ownerCt && this.grid.ownerCt.lockable) { + this.grid.ownerCt.view.refresh(); + } + // Refresh our view + else { + this.view.refresh(); + } + } + }, + + getFeatureTpl: function(values, parent, x, xcount) { + var me = this; + return [ + '', + // group row tpl + '
    {collapsed}{[this.renderGroupHeaderTpl(values)]}
    ', + // this is the rowbody + '{[this.recurse(values)]}', + '
    ' + ].join(''); + }, + + getFragmentTpl: function() { + var me = this; + return { + indentByDepth: me.indentByDepth, + depthToIndent: me.depthToIndent, + renderGroupHeaderTpl: function(values) { + return Ext.XTemplate.getTpl(me, 'groupHeaderTpl').apply(values); + } + }; + }, + + indentByDepth: function(values) { + return 'style="padding-left:'+ ((values.depth || 0) * this.depthToIndent) + 'px;"'; + }, + + // Containers holding these components are responsible for + // destroying them, we are just deleting references. + destroy: function() { + delete this.view; + delete this.prunedHeader; + }, + + // perhaps rename to afterViewRender + attachEvents: function() { + var me = this, + view = me.view; + + view.on({ + scope: me, + groupclick: me.onGroupClick, + rowfocus: me.onRowFocus + }); + + view.mon(view.store, { + scope: me, + groupchange: me.onGroupChange, + remove: me.onRemove, + add: me.onAdd, + update: me.onUpdate + }); + + if (me.enableGroupingMenu) { + me.injectGroupingMenu(); + } + + me.pruneGroupedHeader(); + + me.lastGroupField = me.getGroupField(); + me.block(); + me.onGroupChange(); + me.unblock(); + }, + + // If we add a new item that doesn't belong to a rendered group, refresh the view + onAdd: function(store, records){ + var me = this, + view = me.view, + groupField = me.getGroupField(), + i = 0, + len = records.length, + activeGroups, + addedGroups, + groups, + needsRefresh, + group; + + if (view.rendered) { + addedGroups = {}; + activeGroups = {}; + + for (; i < len; ++i) { + group = records[i].get(groupField); + if (addedGroups[group] === undefined) { + addedGroups[group] = 0; + } + addedGroups[group] += 1; + } + groups = store.getGroups(); + for (i = 0, len = groups.length; i < len; ++i) { + group = groups[i]; + activeGroups[group.name] = group.children.length; + } + + for (group in addedGroups) { + if (addedGroups[group] === activeGroups[group]) { + needsRefresh = true; + break; + } + } + + if (needsRefresh) { + view.refresh(); + } + } + }, + + onUpdate: function(store, record, type, changedFields){ + var view = this.view; + if (view.rendered && !changedFields || Ext.Array.contains(changedFields, this.getGroupField())) { + view.refresh(); + } + }, + + onRemove: function(store, record) { + var me = this, + groupField = me.getGroupField(), + removedGroup = record.get(groupField), + view = me.view; + + if (view.rendered) { + // If that was the last one in the group, force a refresh + if (store.findExact(groupField, removedGroup) === -1) { + me.view.refresh(); + } + } + }, + + injectGroupingMenu: function() { + var me = this, + view = me.view, + headerCt = view.headerCt; + headerCt.showMenuBy = me.showMenuBy; + headerCt.getMenuItems = me.getMenuItems(); + }, + + showMenuBy: function(t, header) { + var menu = this.getMenu(), + groupMenuItem = menu.down('#groupMenuItem'), + groupableMth = header.groupable === false ? 'disable' : 'enable'; + + groupMenuItem[groupableMth](); + Ext.grid.header.Container.prototype.showMenuBy.apply(this, arguments); + }, + + getMenuItems: function() { + var me = this, + groupByText = me.groupByText, + disabled = me.disabled || !me.getGroupField(), + showGroupsText = me.showGroupsText, + enableNoGroups = me.enableNoGroups, + groupMenuItemClick = Ext.Function.bind(me.onGroupMenuItemClick, me), + groupToggleMenuItemClick = Ext.Function.bind(me.onGroupToggleMenuItemClick, me); + + // runs in the scope of headerCt + return function() { + var o = Ext.grid.header.Container.prototype.getMenuItems.call(this); + o.push('-', { + iconCls: Ext.baseCSSPrefix + 'group-by-icon', + itemId: 'groupMenuItem', + text: groupByText, + handler: groupMenuItemClick + }); + if (enableNoGroups) { + o.push({ + itemId: 'groupToggleMenuItem', + text: showGroupsText, + checked: !disabled, + checkHandler: groupToggleMenuItemClick + }); + } + return o; + }; + }, + + /** + * Group by the header the user has clicked on. + * @private + */ + onGroupMenuItemClick: function(menuItem, e) { + var me = this, + menu = menuItem.parentMenu, + hdr = menu.activeHeader, + view = me.view, + store = view.store, + remote = store.remoteGroup; + + delete me.lastGroupIndex; + me.block(); + me.enable(); + store.group(hdr.dataIndex); + me.pruneGroupedHeader(); + me.unblock(); + if (!remote) { + view.refresh(); + } + }, + + block: function(){ + this.blockRefresh = this.view.blockRefresh = true; + }, + + unblock: function(){ + this.blockRefresh = this.view.blockRefresh = false; + }, + + /** + * Turn on and off grouping via the menu + * @private + */ + onGroupToggleMenuItemClick: function(menuItem, checked) { + this[checked ? 'enable' : 'disable'](); + }, + + /** + * Prunes the grouped header from the header container + * @private + */ + pruneGroupedHeader: function() { + var me = this, + header = me.getGroupedHeader(); + + if (me.hideGroupedHeader && header) { + if (me.prunedHeader) { + me.prunedHeader.show(); + } + me.prunedHeader = header; + header.hide(); + } + }, + + getGroupedHeader: function(){ + var groupField = this.getGroupField(), + headerCt = this.view.headerCt; + + return groupField ? headerCt.down('[dataIndex=' + groupField + ']') : null; + }, + + getGroupField: function(){ + var group = this.view.store.groupers.first(); + if (group) { + return group.property; + } + return ''; + }, + + /** + * When a row gains focus, expand the groups above it + * @private + */ + onRowFocus: function(rowIdx) { + var node = this.view.getNode(rowIdx), + groupBd = Ext.fly(node).up('.' + this.collapsedCls); + + if (groupBd) { + // for multiple level groups, should expand every groupBd + // above + this.expand(groupBd); + } + }, + + /** + * Expand a group + * @param {String/Ext.Element} groupName The group name, or the element that contains + * the group body + */ + expand: function(groupName, /*private*/ preventSizeCalculation) { + var me = this, + view = me.view, + groupBody, + lockingPartner = me.lockingPartner; + + // We've been passed the group name + if (Ext.isString(groupName)) { + groupBody = Ext.fly(me.getGroupBodyId(groupName), '_grouping'); + } + // We've been passed an element + else { + groupBody = Ext.fly(groupName, '_grouping') + groupName = me.getGroupName(groupBody); + } + + // If we are collapsed... + if (me.collapsedState[groupName]) { + groupBody.removeCls(me.collapsedCls); + groupBody.prev().removeCls(me.hdCollapsedCls); + + if (preventSizeCalculation !== true) { + view.refreshSize(); + } + view.fireEvent('groupexpand'); + me.collapsedState[groupName] = false; + + // If we are one side of a locking view, the other side has to stay in sync + if (lockingPartner) { + lockingPartner.expand(groupName, preventSizeCalculation); + } + } + }, + + /** + * Expand all groups + */ + expandAll: function(){ + var me = this, + view = me.view, + els = view.el.select(me.eventSelector).elements, + e, + eLen = els.length; + + for (e = 0; e < eLen; e++) { + me.expand(Ext.fly(els[e]).next(), true); + } + + view.refreshSize(); + }, + + /** + * Collapse a group + * @param {String/Ext.Element} groupName The group name, or the element that contains + * group body + */ + collapse: function(groupName, /*private*/ preventSizeCalculation) { + var me = this, + view = me.view, + groupBody, + lockingPartner = me.lockingPartner; + + // We've been passed the group name + if (Ext.isString(groupName)) { + groupBody = Ext.fly(me.getGroupBodyId(groupName), '_grouping'); + } + // We've been passed an element + else { + groupBody = Ext.fly(groupName, '_grouping') + groupName = me.getGroupName(groupBody); + } + + // If we are not collapsed... + if (!me.collapsedState[groupName]) { + groupBody.addCls(me.collapsedCls); + groupBody.prev().addCls(me.hdCollapsedCls); + + if (preventSizeCalculation !== true) { + view.refreshSize(); + } + view.fireEvent('groupcollapse'); + me.collapsedState[groupName] = true; + + // If we are one side of a locking view, the other side has to stay in sync + if (lockingPartner) { + lockingPartner.collapse(groupName, preventSizeCalculation); + } + } + }, + + /** + * Collapse all groups + */ + collapseAll: function() { + var me = this, + view = me.view, + els = view.el.select(me.eventSelector).elements, + e, + eLen = els.length; + + for (e = 0; e < eLen; e++) { + me.collapse(Ext.fly(els[e]).next(), true); + } + + view.refreshSize(); + }, + + onGroupChange: function(){ + var me = this, + field = me.getGroupField(), + menuItem, + visibleGridColumns, + groupingByLastVisibleColumn; + + if (me.hideGroupedHeader) { + if (me.lastGroupField) { + menuItem = me.getMenuItem(me.lastGroupField); + if (menuItem) { + menuItem.setChecked(true); + } + } + if (field) { + visibleGridColumns = me.view.headerCt.getVisibleGridColumns(); + + // See if we are being asked to group by the sole remaining visible column. + // If so, then do not hide that column. + groupingByLastVisibleColumn = ((visibleGridColumns.length === 1) && (visibleGridColumns[0].dataIndex == field)); + menuItem = me.getMenuItem(field); + if (menuItem && !groupingByLastVisibleColumn) { + menuItem.setChecked(false); + } + } + } + if (me.blockRefresh !== true) { + me.view.refresh(); + } + me.lastGroupField = field; + }, + + /** + * Gets the related menu item for a dataIndex + * @private + * @return {Ext.grid.header.Container} The header + */ + getMenuItem: function(dataIndex){ + var view = this.view, + header = view.headerCt.down('gridcolumn[dataIndex=' + dataIndex + ']'), + menu = view.headerCt.getMenu(); + + return header ? menu.down('menuitem[headerId='+ header.id +']') : null; + }, + + /** + * Toggle between expanded/collapsed state when clicking on + * the group. + * @private + */ + onGroupClick: function(view, rowElement, groupName, e) { + var me = this; + + if (me.collapsedState[groupName]) { + me.expand(groupName); + } else { + me.collapse(groupName); + } + }, + + // Injects isRow and closeRow into the metaRowTpl. + getMetaRowTplFragments: function() { + return { + isRow: this.isRow, + closeRow: this.closeRow + }; + }, + + // injected into rowtpl and wrapped around metaRowTpl + // becomes part of the standard tpl + isRow: function() { + return ''; + }, + + // injected into rowtpl and wrapped around metaRowTpl + // becomes part of the standard tpl + closeRow: function() { + return ''; + }, + + // isRow and closeRow are injected via getMetaRowTplFragments + mutateMetaRowTpl: function(metaRowTpl) { + metaRowTpl.unshift('{[this.isRow()]}'); + metaRowTpl.push('{[this.closeRow()]}'); + }, + + // injects an additional style attribute via tdAttrKey with the proper + // amount of padding + getAdditionalData: function(data, idx, record, orig) { + var view = this.view, + hCt = view.headerCt, + col = hCt.items.getAt(0), + o = {}, + tdAttrKey; + + // If there *are* any columne in this grid (possible empty side of a locking grid)... + // Add the padding-left style to indent the row according to grouping depth. + // Preserve any current tdAttr that a user may have set. + if (col) { + tdAttrKey = col.id + '-tdAttr'; + o[tdAttrKey] = this.indentByDepth(data) + " " + (orig[tdAttrKey] ? orig[tdAttrKey] : ''); + o.collapsed = 'true'; + o.data = record.getData(); + } + return o; + }, + + // return matching preppedRecords + getGroupRows: function(group, records, preppedRecords, fullWidth) { + var me = this, + children = group.children, + rows = group.rows = [], + view = me.view, + header = me.getGroupedHeader(), + groupField = me.getGroupField(), + index = -1, + r, + rLen = records.length, + record; + + group.viewId = view.id; + + for (r = 0; r < rLen; r++) { + record = records[r]; + + if (record.get(groupField) == group.name) { + index = r; + } + if (Ext.Array.indexOf(children, record) != -1) { + rows.push(Ext.apply(preppedRecords[r], { + depth : 1 + })); + } + } + + group.groupHeaderId = me.getGroupHeaderId(group.name); + group.groupBodyId = me.getGroupBodyId(group.name); + group.fullWidth = fullWidth; + group.columnName = header ? header.text : groupField; + group.groupValue = group.name; + + // Here we attempt to overwrite the group name value from the Store with + // the get the rendered value of the column from the *prepped* record + if (header && index > -1) { + group.name = group.renderedValue = preppedRecords[index][header.id]; + } + if (me.collapsedState[group.name]) { + group.collapsedCls = me.collapsedCls; + group.hdCollapsedCls = me.hdCollapsedCls; + } + + return group; + }, + + // Create an associated DOM id for the group's header element given the group name + getGroupHeaderId: function(groupName) { + return this.view.id + '-hd-' + groupName; + }, + + // Create an associated DOM id for the group's body element given the group name + getGroupBodyId: function(groupName) { + return this.view.id + '-bd-' + groupName; + }, + + // Get the group name from an associated element whether it's within a header or a body + getGroupName: function(element) { + var me = this, + targetEl; + + // See if element is, or is within a group header. If so, we can extract its name + targetEl = Ext.fly(element).findParent(me.eventSelector); + if (targetEl) { + return targetEl.id.split(this.view.id + '-hd-')[1]; + } + + // See if element is, or is within a group body. If so, we can extract its name + targetEl = Ext.fly(element).findParent(me.bodySelector); + if (targetEl) { + return targetEl.id.split(this.view.id + '-bd-')[1]; + } + }, + + // return the data in a grouped format. + collectData: function(records, preppedRecords, startIndex, fullWidth, o) { + var me = this, + store = me.view.store, + g, + groups, gLen, group; + + if (!me.disabled && store.isGrouped()) { + groups = store.getGroups(); + gLen = groups.length; + + for (g = 0; g < gLen; g++) { + group = groups[g]; + + me.getGroupRows(group, records, preppedRecords, fullWidth); + } + + return { + rows: groups, + fullWidth: fullWidth + }; + } + return o; + }, + + // adds the groupName to the groupclick, groupdblclick, groupcontextmenu + // events that are fired on the view. Chose not to return the actual + // group itself because of its expense and because developers can simply + // grab the group via store.getGroups(groupName) + getFireEventArgs: function(type, view, targetEl, e) { + return [type, view, targetEl, this.getGroupName(targetEl), e]; + } +}); + +/** + * The rowbody feature enhances the grid's markup to have an additional + * tr -> td -> div which spans the entire width of the original row. + * + * This is useful to to associate additional information with a particular + * record in a grid. + * + * Rowbodies are initially hidden unless you override getAdditionalData. + * + * Will expose additional events on the gridview with the prefix of 'rowbody'. + * For example: 'rowbodyclick', 'rowbodydblclick', 'rowbodycontextmenu'. + * + * # Example + * + * @example + * Ext.define('Animal', { + * extend: 'Ext.data.Model', + * fields: ['name', 'latin', 'desc'] + * }); + * + * Ext.create('Ext.grid.Panel', { + * width: 400, + * height: 300, + * renderTo: Ext.getBody(), + * store: { + * model: 'Animal', + * data: [ + * {name: 'Tiger', latin: 'Panthera tigris', + * desc: 'The largest cat species, weighing up to 306 kg (670 lb).'}, + * {name: 'Roman snail', latin: 'Helix pomatia', + * desc: 'A species of large, edible, air-breathing land snail.'}, + * {name: 'Yellow-winged darter', latin: 'Sympetrum flaveolum', + * desc: 'A dragonfly found in Europe and mid and Northern China.'}, + * {name: 'Superb Fairy-wren', latin: 'Malurus cyaneus', + * desc: 'Common and familiar across south-eastern Australia.'} + * ] + * }, + * columns: [{ + * dataIndex: 'name', + * text: 'Common name', + * width: 125 + * }, { + * dataIndex: 'latin', + * text: 'Scientific name', + * flex: 1 + * }], + * features: [{ + * ftype: 'rowbody', + * getAdditionalData: function(data, rowIndex, record, orig) { + * var headerCt = this.view.headerCt, + * colspan = headerCt.getColumnCount(); + * // Usually you would style the my-body-class in CSS file + * return { + * rowBody: '
    '+record.get("desc")+'
    ', + * rowBodyCls: "my-body-class", + * rowBodyColspan: colspan + * }; + * } + * }] + * }); + */ +Ext.define('Ext.grid.feature.RowBody', { + extend: 'Ext.grid.feature.Feature', + alias: 'feature.rowbody', + rowBodyHiddenCls: Ext.baseCSSPrefix + 'grid-row-body-hidden', + rowBodyTrCls: Ext.baseCSSPrefix + 'grid-rowbody-tr', + rowBodyTdCls: Ext.baseCSSPrefix + 'grid-cell-rowbody', + rowBodyDivCls: Ext.baseCSSPrefix + 'grid-rowbody', + + eventPrefix: 'rowbody', + eventSelector: '.' + Ext.baseCSSPrefix + 'grid-rowbody-tr', + + getRowBody: function(values) { + return [ + '', + '', + '
    {rowBody}
    ', + '', + '' + ].join(''); + }, + + // injects getRowBody into the metaRowTpl. + getMetaRowTplFragments: function() { + return { + getRowBody: this.getRowBody, + rowBodyTrCls: this.rowBodyTrCls, + rowBodyTdCls: this.rowBodyTdCls, + rowBodyDivCls: this.rowBodyDivCls + }; + }, + + mutateMetaRowTpl: function(metaRowTpl) { + metaRowTpl.push('{[this.getRowBody(values)]}'); + }, + + /** + * Provides additional data to the prepareData call within the grid view. + * The rowbody feature adds 3 additional variables into the grid view's template. + * These are rowBodyCls, rowBodyColspan, and rowBody. + * @param {Object} data The data for this particular record. + * @param {Number} idx The row index for this record. + * @param {Ext.data.Model} record The record instance + * @param {Object} orig The original result from the prepareData call to massage. + */ + getAdditionalData: function(data, idx, record, orig) { + var headerCt = this.view.headerCt, + colspan = headerCt.getColumnCount(); + + return { + rowBody: "", + rowBodyCls: this.rowBodyCls, + rowBodyColspan: colspan + }; + } +}); +/** + * @private + */ +Ext.define('Ext.grid.feature.RowWrap', { + extend: 'Ext.grid.feature.Feature', + alias: 'feature.rowwrap', + + // turn off feature events. + hasFeatureEvent: false, + + init: function() { + if (!this.disabled) { + this.enable(); + } + }, + + getRowSelector: function(){ + return 'tr:has(> ' + this.view.cellSelector + ')'; + }, + + enable: function(){ + var me = this, + view = me.view; + + me.callParent(); + // we need to mutate the rowSelector since the template changes the ordering + me.savedRowSelector = view.rowSelector; + view.rowSelector = me.getRowSelector(); + + // Extra functionality needed on header resize when row is wrapped: + // Every individual cell in a column needs its width syncing. + view.onHeaderResize = Ext.Function.createSequence(view.onHeaderResize, me.onHeaderResize, me); + }, + + disable: function(){ + var me = this, + view = me.view, + saved = me.savedRowSelector; + + me.callParent(); + if (saved) { + view.rowSelector = saved; + } + delete me.savedRowSelector; + delete view.onHeaderResize; + }, + + mutateMetaRowTpl: function(metaRowTpl) { + var prefix = Ext.baseCSSPrefix; + // Remove "x-grid-row" from the first row, note this could be wrong + // if some other feature unshifted things in front. + metaRowTpl[0] = metaRowTpl[0].replace(prefix + 'grid-row', ''); + metaRowTpl[0] = metaRowTpl[0].replace("{[this.embedRowCls()]}", ""); + // 2 + metaRowTpl.unshift(''); + // 1 + metaRowTpl.unshift('
    '); + + // 3 + metaRowTpl.push('
    '); + // 4 + metaRowTpl.push(''); + }, + + embedColSpan: function() { + return '{colspan}'; + }, + + embedFullWidth: function() { + return '{fullWidth}'; + }, + + getAdditionalData: function(data, idx, record, orig) { + var headerCt = this.view.headerCt, + colspan = headerCt.getColumnCount(), + fullWidth = headerCt.getFullWidth(), + items = headerCt.query('gridcolumn'), + itemsLn = items.length, + i = 0, + o = { + colspan: colspan, + fullWidth: fullWidth + }, + id, + tdClsKey, + colResizerCls; + + for (; i < itemsLn; i++) { + id = items[i].id; + tdClsKey = id + '-tdCls'; + colResizerCls = Ext.baseCSSPrefix + 'grid-col-resizer-'+id; + // give the inner td's the resizer class + // while maintaining anything a user may have injected via a custom + // renderer + o[tdClsKey] = colResizerCls + " " + (orig[tdClsKey] ? orig[tdClsKey] : ''); + // TODO: Unhackify the initial rendering width's + o[id+'-tdAttr'] = " style=\"width: " + (items[i].hidden ? 0 : items[i].getDesiredWidth()) + "px;\" "/* + (i === 0 ? " rowspan=\"2\"" : "")*/; + if (orig[id+'-tdAttr']) { + o[id+'-tdAttr'] += orig[id+'-tdAttr']; + } + } + + return o; + }, + + getMetaRowTplFragments: function() { + return { + embedFullWidth: this.embedFullWidth, + embedColSpan: this.embedColSpan + }; + }, + + // When row is wrapped, every individual cell in a column needs its width syncing + onHeaderResize: function(header, w, suppressFocus) { + var el = this.view.el; + if (el) { + el.select('td.' + Ext.baseCSSPrefix + 'grid-col-resizer-' + header.id).setWidth(w); + } + } +}); +/** + * This plugin provides drag and/or drop functionality for a GridView. + * + * It creates a specialized instance of {@link Ext.dd.DragZone DragZone} which knows how to drag out of a {@link + * Ext.grid.View GridView} and loads the data object which is passed to a cooperating {@link Ext.dd.DragZone DragZone}'s + * methods with the following properties: + * + * - `copy` : Boolean + * + * The value of the GridView's `copy` property, or `true` if the GridView was configured with `allowCopy: true` _and_ + * the control key was pressed when the drag operation was begun. + * + * - `view` : GridView + * + * The source GridView from which the drag originated. + * + * - `ddel` : HtmlElement + * + * The drag proxy element which moves with the mouse + * + * - `item` : HtmlElement + * + * The GridView node upon which the mousedown event was registered. + * + * - `records` : Array + * + * An Array of {@link Ext.data.Model Model}s representing the selected data being dragged from the source GridView. + * + * It also creates a specialized instance of {@link Ext.dd.DropZone} which cooperates with other DropZones which are + * members of the same ddGroup which processes such data objects. + * + * Adding this plugin to a view means that two new events may be fired from the client GridView, `{@link #beforedrop + * beforedrop}` and `{@link #drop drop}` + * + * @example + * Ext.create('Ext.data.Store', { + * storeId:'simpsonsStore', + * fields:['name'], + * data: [["Lisa"], ["Bart"], ["Homer"], ["Marge"]], + * proxy: { + * type: 'memory', + * reader: 'array' + * } + * }); + * + * Ext.create('Ext.grid.Panel', { + * store: 'simpsonsStore', + * columns: [ + * {header: 'Name', dataIndex: 'name', flex: true} + * ], + * viewConfig: { + * plugins: { + * ptype: 'gridviewdragdrop', + * dragText: 'Drag and drop to reorganize' + * } + * }, + * height: 200, + * width: 400, + * renderTo: Ext.getBody() + * }); + */ +Ext.define('Ext.grid.plugin.DragDrop', { + extend: 'Ext.AbstractPlugin', + alias: 'plugin.gridviewdragdrop', + + uses: [ + 'Ext.view.DragZone', + 'Ext.grid.ViewDropZone' + ], + + /** + * @event beforedrop + * **This event is fired through the GridView. Add listeners to the GridView object** + * + * Fired when a drop gesture has been triggered by a mouseup event in a valid drop position in the GridView. + * + * @param {HTMLElement} node The GridView node **if any** over which the mouse was positioned. + * + * Returning `false` to this event signals that the drop gesture was invalid, and if the drag proxy will animate + * back to the point from which the drag began. + * + * Returning `0` To this event signals that the data transfer operation should not take place, but that the gesture + * was valid, and that the repair operation should not take place. + * + * Any other return value continues with the data transfer operation. + * + * @param {Object} data The data object gathered at mousedown time by the cooperating {@link Ext.dd.DragZone + * DragZone}'s {@link Ext.dd.DragZone#getDragData getDragData} method it contains the following properties: + * + * - copy : Boolean + * + * The value of the GridView's `copy` property, or `true` if the GridView was configured with `allowCopy: true` and + * the control key was pressed when the drag operation was begun + * + * - view : GridView + * + * The source GridView from which the drag originated. + * + * - ddel : HtmlElement + * + * The drag proxy element which moves with the mouse + * + * - item : HtmlElement + * + * The GridView node upon which the mousedown event was registered. + * + * - records : Array + * + * An Array of {@link Ext.data.Model Model}s representing the selected data being dragged from the source GridView. + * + * @param {Ext.data.Model} overModel The Model over which the drop gesture took place. + * + * @param {String} dropPosition `"before"` or `"after"` depending on whether the mouse is above or below the midline + * of the node. + * + * @param {Function} dropFunction + * + * A function to call to complete the data transfer operation and either move or copy Model instances from the + * source View's Store to the destination View's Store. + * + * This is useful when you want to perform some kind of asynchronous processing before confirming the drop, such as + * an {@link Ext.window.MessageBox#confirm confirm} call, or an Ajax request. + * + * Return `0` from this event handler, and call the `dropFunction` at any time to perform the data transfer. + */ + + /** + * @event drop + * **This event is fired through the GridView. Add listeners to the GridView object** Fired when a drop operation + * has been completed and the data has been moved or copied. + * + * @param {HTMLElement} node The GridView node **if any** over which the mouse was positioned. + * + * @param {Object} data The data object gathered at mousedown time by the cooperating {@link Ext.dd.DragZone + * DragZone}'s {@link Ext.dd.DragZone#getDragData getDragData} method it contains the following properties: + * + * - copy : Boolean + * + * The value of the GridView's `copy` property, or `true` if the GridView was configured with `allowCopy: true` and + * the control key was pressed when the drag operation was begun + * + * - view : GridView + * + * The source GridView from which the drag originated. + * + * - ddel : HtmlElement + * + * The drag proxy element which moves with the mouse + * + * - item : HtmlElement + * + * The GridView node upon which the mousedown event was registered. + * + * - records : Array + * + * An Array of {@link Ext.data.Model Model}s representing the selected data being dragged from the source GridView. + * + * @param {Ext.data.Model} overModel The Model over which the drop gesture took place. + * + * @param {String} dropPosition `"before"` or `"after"` depending on whether the mouse is above or below the midline + * of the node. + */ + // + dragText : '{0} selected row{1}', + // + + /** + * @cfg {String} ddGroup + * A named drag drop group to which this object belongs. If a group is specified, then both the DragZones and + * DropZone used by this plugin will only interact with other drag drop objects in the same group. + */ + ddGroup : "GridDD", + + /** + * @cfg {String} dragGroup + * The ddGroup to which the DragZone will belong. + * + * This defines which other DropZones the DragZone will interact with. Drag/DropZones only interact with other + * Drag/DropZones which are members of the same ddGroup. + */ + + /** + * @cfg {String} dropGroup + * The ddGroup to which the DropZone will belong. + * + * This defines which other DragZones the DropZone will interact with. Drag/DropZones only interact with other + * Drag/DropZones which are members of the same ddGroup. + */ + + /** + * @cfg {Boolean} enableDrop + * False to disallow the View from accepting drop gestures. + */ + enableDrop: true, + + /** + * @cfg {Boolean} enableDrag + * False to disallow dragging items from the View. + */ + enableDrag: true, + + init : function(view) { + view.on('render', this.onViewRender, this, {single: true}); + }, + + /** + * @private + * AbstractComponent calls destroy on all its plugins at destroy time. + */ + destroy: function() { + Ext.destroy(this.dragZone, this.dropZone); + }, + + enable: function() { + var me = this; + if (me.dragZone) { + me.dragZone.unlock(); + } + if (me.dropZone) { + me.dropZone.unlock(); + } + me.callParent(); + }, + + disable: function() { + var me = this; + if (me.dragZone) { + me.dragZone.lock(); + } + if (me.dropZone) { + me.dropZone.lock(); + } + me.callParent(); + }, + + onViewRender : function(view) { + var me = this; + + if (me.enableDrag) { + me.dragZone = new Ext.view.DragZone({ + view: view, + ddGroup: me.dragGroup || me.ddGroup, + dragText: me.dragText + }); + } + + if (me.enableDrop) { + me.dropZone = new Ext.grid.ViewDropZone({ + view: view, + ddGroup: me.dropGroup || me.ddGroup + }); + } + } +}); +/** + * Plugin to add header resizing functionality to a HeaderContainer. + * Always resizing header to the left of the splitter you are resizing. + */ +Ext.define('Ext.grid.plugin.HeaderResizer', { + extend: 'Ext.util.Observable', + requires: ['Ext.dd.DragTracker', 'Ext.util.Region'], + alias: 'plugin.gridheaderresizer', + + disabled: false, + + config: { + /** + * @cfg {Boolean} dynamic + * True to resize on the fly rather than using a proxy marker. + * @accessor + */ + dynamic: false + }, + + colHeaderCls: Ext.baseCSSPrefix + 'column-header', + + minColWidth: 40, + maxColWidth: 1000, + wResizeCursor: 'col-resize', + eResizeCursor: 'col-resize', + // not using w and e resize bc we are only ever resizing one + // column + //wResizeCursor: Ext.isWebKit ? 'w-resize' : 'col-resize', + //eResizeCursor: Ext.isWebKit ? 'e-resize' : 'col-resize', + + init: function(headerCt) { + this.headerCt = headerCt; + headerCt.on('render', this.afterHeaderRender, this, {single: true}); + }, + + /** + * @private + * AbstractComponent calls destroy on all its plugins at destroy time. + */ + destroy: function() { + if (this.tracker) { + this.tracker.destroy(); + } + }, + + afterHeaderRender: function() { + var headerCt = this.headerCt, + el = headerCt.el; + + headerCt.mon(el, 'mousemove', this.onHeaderCtMouseMove, this); + + this.tracker = new Ext.dd.DragTracker({ + disabled: this.disabled, + onBeforeStart: Ext.Function.bind(this.onBeforeStart, this), + onStart: Ext.Function.bind(this.onStart, this), + onDrag: Ext.Function.bind(this.onDrag, this), + onEnd: Ext.Function.bind(this.onEnd, this), + tolerance: 3, + autoStart: 300, + el: el + }); + }, + + // As we mouse over individual headers, change the cursor to indicate + // that resizing is available, and cache the resize target header for use + // if/when they mousedown. + onHeaderCtMouseMove: function(e, t) { + var me = this, + prevSiblings, + headerEl, overHeader, resizeHeader, resizeHeaderOwnerGrid, ownerGrid; + + if (me.headerCt.dragging) { + if (me.activeHd) { + me.activeHd.el.dom.style.cursor = ''; + delete me.activeHd; + } + } else { + headerEl = e.getTarget('.' + me.colHeaderCls, 3, true); + + if (headerEl){ + overHeader = Ext.getCmp(headerEl.id); + + // On left edge, go back to the previous non-hidden header. + if (overHeader.isOnLeftEdge(e)) { + resizeHeader = overHeader.previousNode('gridcolumn:not([hidden]):not([isGroupHeader])') + // There may not *be* a previous non-hidden header. + if (resizeHeader) { + + ownerGrid = me.headerCt.up('tablepanel'); + resizeHeaderOwnerGrid = resizeHeader.up('tablepanel'); + + // Need to check that previousNode didn't go outside the current grid/tree + // But in the case of a Grid which contains a locked and normal grid, allow previousNode to jump + // from the first column of the normalGrid to the last column of the lockedGrid + if (!((resizeHeaderOwnerGrid === ownerGrid) || ((ownerGrid.ownerCt.isXType('tablepanel')) && ownerGrid.ownerCt.view.lockedGrid === resizeHeaderOwnerGrid))) { + resizeHeader = null; + } + } + } + // Else, if on the right edge, we're resizing the column we are over + else if (overHeader.isOnRightEdge(e)) { + resizeHeader = overHeader; + } + // Between the edges: we are not resizing + else { + resizeHeader = null; + } + + // We *are* resizing + if (resizeHeader) { + // If we're attempting to resize a group header, that cannot be resized, + // so find its last visible leaf header; Group headers are sized + // by the size of their child headers. + if (resizeHeader.isGroupHeader) { + prevSiblings = resizeHeader.getGridColumns(); + resizeHeader = prevSiblings[prevSiblings.length - 1]; + } + + // Check if the header is resizable. Continue checking the old "fixed" property, bug also + // check whether the resizablwe property is set to false. + if (resizeHeader && !(resizeHeader.fixed || (resizeHeader.resizable === false) || me.disabled)) { + me.activeHd = resizeHeader; + overHeader.el.dom.style.cursor = me.eResizeCursor; + } + // reset + } else { + overHeader.el.dom.style.cursor = ''; + delete me.activeHd; + } + } + } + }, + + // only start when there is an activeHd + onBeforeStart : function(e){ + var t = e.getTarget(); + // cache the activeHd because it will be cleared. + this.dragHd = this.activeHd; + + if (!!this.dragHd && !Ext.fly(t).hasCls(Ext.baseCSSPrefix + 'column-header-trigger') && !this.headerCt.dragging) { + //this.headerCt.dragging = true; + this.tracker.constrainTo = this.getConstrainRegion(); + return true; + } else { + this.headerCt.dragging = false; + return false; + } + }, + + // get the region to constrain to, takes into account max and min col widths + getConstrainRegion: function() { + var me = this, + dragHdEl = me.dragHd.el, + region = Ext.util.Region.getRegion(dragHdEl), + nextHd; + + // If forceFit, then right constraint is based upon not being able to force the next header + // beyond the minColWidth. If there is no next header, then the header may not be expanded. + if (me.headerCt.forceFit) { + nextHd = me.dragHd.nextNode('gridcolumn:not([hidden]):not([isGroupHeader])'); + } + + return region.adjust( + 0, + me.headerCt.forceFit ? (nextHd ? nextHd.getWidth() - me.minColWidth : 0) : me.maxColWidth - dragHdEl.getWidth(), + 0, + me.minColWidth + ); + }, + + // initialize the left and right hand side markers around + // the header that we are resizing + onStart: function(e){ + var me = this, + dragHd = me.dragHd, + dragHdEl = dragHd.el, + width = dragHdEl.getWidth(), + headerCt = me.headerCt, + t = e.getTarget(), + xy, gridSection, dragHct, firstSection, lhsMarker, rhsMarker, el, offsetLeft, offsetTop, topLeft, markerHeight, top; + + if (me.dragHd && !Ext.fly(t).hasCls(Ext.baseCSSPrefix + 'column-header-trigger')) { + headerCt.dragging = true; + } + + me.origWidth = width; + + // setup marker proxies + if (!me.dynamic) { + xy = dragHdEl.getXY(); + gridSection = headerCt.up('[scrollerOwner]'); + dragHct = me.dragHd.up(':not([isGroupHeader])'); + firstSection = dragHct.up(); + lhsMarker = gridSection.getLhsMarker(); + rhsMarker = gridSection.getRhsMarker(); + el = rhsMarker.parent(); + offsetLeft = el.getLeft(true); + offsetTop = el.getTop(true); + topLeft = el.translatePoints(xy); + markerHeight = firstSection.body.getHeight() + headerCt.getHeight(); + top = topLeft.top - offsetTop; + + lhsMarker.setTop(top); + rhsMarker.setTop(top); + lhsMarker.setHeight(markerHeight); + rhsMarker.setHeight(markerHeight); + lhsMarker.setLeft(topLeft.left - offsetLeft); + rhsMarker.setLeft(topLeft.left + width - offsetLeft); + } + }, + + // synchronize the rhsMarker with the mouse movement + onDrag: function(e){ + if (!this.dynamic) { + var xy = this.tracker.getXY('point'), + gridSection = this.headerCt.up('[scrollerOwner]'), + rhsMarker = gridSection.getRhsMarker(), + el = rhsMarker.parent(), + topLeft = el.translatePoints(xy), + offsetLeft = el.getLeft(true); + + rhsMarker.setLeft(topLeft.left - offsetLeft); + // Resize as user interacts + } else { + this.doResize(); + } + }, + + onEnd: function(e){ + this.headerCt.dragging = false; + if (this.dragHd) { + if (!this.dynamic) { + var dragHd = this.dragHd, + gridSection = this.headerCt.up('[scrollerOwner]'), + lhsMarker = gridSection.getLhsMarker(), + rhsMarker = gridSection.getRhsMarker(), + offscreen = -9999; + + // hide markers + lhsMarker.setLeft(offscreen); + rhsMarker.setLeft(offscreen); + } + this.doResize(); + } + }, + + doResize: function() { + if (this.dragHd) { + var dragHd = this.dragHd, + nextHd, + offset = this.tracker.getOffset('point'); + + // resize the dragHd + if (dragHd.flex) { + delete dragHd.flex; + } + + Ext.suspendLayouts(); + + // Set the new column width. + dragHd.setWidth(this.origWidth + offset[0]); + + // In the case of forceFit, change the following Header width. + // Constraining so that neither neighbour can be sized to below minWidth is handled in getConstrainRegion + if (this.headerCt.forceFit) { + nextHd = dragHd.nextNode('gridcolumn:not([hidden]):not([isGroupHeader])'); + if (nextHd) { + delete nextHd.flex; + nextHd.setWidth(nextHd.getWidth() - offset[0]); + } + } + + // Apply the two width changes by laying out the owning HeaderContainer + Ext.resumeLayouts(true); + } + }, + + disable: function() { + this.disabled = true; + if (this.tracker) { + this.tracker.disable(); + } + }, + + enable: function() { + this.disabled = false; + if (this.tracker) { + this.tracker.enable(); + } + } +}); +/** + * @private + * Base class for Box Layout overflow handlers. These specialized classes are invoked when a Box Layout + * (either an HBox or a VBox) has child items that are either too wide (for HBox) or too tall (for VBox) + * for its container. + */ +Ext.define('Ext.layout.container.boxOverflow.None', { + alternateClassName: 'Ext.layout.boxOverflow.None', + + constructor: function(layout, config) { + this.layout = layout; + Ext.apply(this, config); + }, + + handleOverflow: Ext.emptyFn, + + clearOverflow: Ext.emptyFn, + + beginLayout: Ext.emptyFn, + beginLayoutCycle: Ext.emptyFn, + finishedLayout: Ext.emptyFn, + + completeLayout: function (ownerContext) { + var me = this, + plan = ownerContext.state.boxPlan, + overflow; + + if (plan && plan.tooNarrow) { + overflow = me.handleOverflow(ownerContext); + + if (overflow) { + if (overflow.reservedSpace) { + me.layout.publishInnerCtSize(ownerContext, overflow.reservedSpace); + } + + // TODO: If we need to use the code below then we will need to pass along + // the new targetSize as state and use it calculate somehow... + // + //if (overflow.recalculate) { + // ownerContext.invalidate({ + // state: { + // overflow: overflow + // } + // }); + //} + } + } else { + me.clearOverflow(); + } + }, + + onRemove: Ext.emptyFn, + + /** + * @private + * Normalizes an item reference, string id or numerical index into a reference to the item + * @param {Ext.Component/String/Number} item The item reference, id or index + * @return {Ext.Component} The item + */ + getItem: function(item) { + return this.layout.owner.getComponent(item); + }, + + getOwnerType: function(owner){ + var type = ''; + + if (owner.is('toolbar')) { + type = 'toolbar'; + } else if (owner.is('tabbar')) { + type = 'tabbar'; + } else { + type = owner.getXType(); + } + + return type; + }, + + getPrefixConfig: Ext.emptyFn, + getSuffixConfig: Ext.emptyFn, + getOverflowCls: function() { + return ''; + } +}); +/** + * A custom drag proxy implementation specific to {@link Ext.panel.Panel}s. This class + * is primarily used internally for the Panel's drag drop implementation, and + * should never need to be created directly. + * @private + */ +Ext.define('Ext.panel.Proxy', { + + alternateClassName: 'Ext.dd.PanelProxy', + + /** + * @cfg {Boolean} [moveOnDrag=true] + * True to move the panel to the dragged position when dropped + */ + moveOnDrag: true, + + /** + * Creates new panel proxy. + * @param {Ext.panel.Panel} panel The {@link Ext.panel.Panel} to proxy for + * @param {Object} [config] Config object + */ + constructor: function(panel, config){ + var me = this; + + /** + * @property panel + * @type Ext.panel.Panel + */ + me.panel = panel; + me.id = me.panel.id +'-ddproxy'; + Ext.apply(me, config); + }, + + /** + * @cfg {Boolean} insertProxy + * True to insert a placeholder proxy element while dragging the panel, false to drag with no proxy. + * Most Panels are not absolute positioned and therefore we need to reserve this space. + */ + insertProxy: true, + + // private overrides + setStatus: Ext.emptyFn, + reset: Ext.emptyFn, + update: Ext.emptyFn, + stop: Ext.emptyFn, + sync: Ext.emptyFn, + + /** + * Gets the proxy's element + * @return {Ext.Element} The proxy's element + */ + getEl: function(){ + return this.ghost.el; + }, + + /** + * Gets the proxy's ghost Panel + * @return {Ext.panel.Panel} The proxy's ghost Panel + */ + getGhost: function(){ + return this.ghost; + }, + + /** + * Gets the proxy element. This is the element that represents where the + * Panel was before we started the drag operation. + * @return {Ext.Element} The proxy's element + */ + getProxy: function(){ + return this.proxy; + }, + + /** + * Hides the proxy + */ + hide : function(){ + var me = this; + + if (me.ghost) { + if (me.proxy) { + me.proxy.remove(); + delete me.proxy; + } + + // Unghost the Panel, do not move the Panel to where the ghost was + me.panel.unghost(null, me.moveOnDrag); + delete me.ghost; + } + }, + + /** + * Shows the proxy + */ + show: function(){ + var me = this, + panelSize; + + if (!me.ghost) { + panelSize = me.panel.getSize(); + me.panel.el.setVisibilityMode(Ext.Element.DISPLAY); + me.ghost = me.panel.ghost(); + if (me.insertProxy) { + // bc Panels aren't absolute positioned we need to take up the space + // of where the panel previously was + me.proxy = me.panel.el.insertSibling({cls: Ext.baseCSSPrefix + 'panel-dd-spacer'}); + me.proxy.setSize(panelSize); + } + } + }, + + // private + repair: function(xy, callback, scope) { + this.hide(); + Ext.callback(callback, scope || this); + }, + + /** + * Moves the proxy to a different position in the DOM. This is typically + * called while dragging the Panel to keep the proxy sync'd to the Panel's + * location. + * @param {HTMLElement} parentNode The proxy's parent DOM node + * @param {HTMLElement} [before] The sibling node before which the + * proxy should be inserted. Defaults to the parent's last child if not + * specified. + */ + moveProxy : function(parentNode, before){ + if (this.proxy) { + parentNode.insertBefore(this.proxy.dom, before); + } + } +}); + +/** + * Applies drag handles to an element or component to make it resizable. The drag handles are inserted into the element + * (or component's element) and positioned absolute. + * + * Textarea and img elements will be wrapped with an additional div because these elements do not support child nodes. + * The original element can be accessed through the originalTarget property. + * + * Here is the list of valid resize handles: + * + * Value Description + * ------ ------------------- + * 'n' north + * 's' south + * 'e' east + * 'w' west + * 'nw' northwest + * 'sw' southwest + * 'se' southeast + * 'ne' northeast + * 'all' all + * + * {@img Ext.resizer.Resizer/Ext.resizer.Resizer.png Ext.resizer.Resizer component} + * + * Here's an example showing the creation of a typical Resizer: + * + * Ext.create('Ext.resizer.Resizer', { + * el: 'elToResize', + * handles: 'all', + * minWidth: 200, + * minHeight: 100, + * maxWidth: 500, + * maxHeight: 400, + * pinned: true + * }); + */ +Ext.define('Ext.resizer.Resizer', { + mixins: { + observable: 'Ext.util.Observable' + }, + uses: ['Ext.resizer.ResizeTracker', 'Ext.Component'], + + alternateClassName: 'Ext.Resizable', + + handleCls: Ext.baseCSSPrefix + 'resizable-handle', + pinnedCls: Ext.baseCSSPrefix + 'resizable-pinned', + overCls: Ext.baseCSSPrefix + 'resizable-over', + wrapCls: Ext.baseCSSPrefix + 'resizable-wrap', + + /** + * @cfg {Boolean} dynamic + * Specify as true to update the {@link #target} (Element or {@link Ext.Component Component}) dynamically during + * dragging. This is `true` by default, but the {@link Ext.Component Component} class passes `false` when it is + * configured as {@link Ext.Component#resizable}. + * + * If specified as `false`, a proxy element is displayed during the resize operation, and the {@link #target} is + * updated on mouseup. + */ + dynamic: true, + + /** + * @cfg {String} handles + * String consisting of the resize handles to display. Defaults to 's e se' for Elements and fixed position + * Components. Defaults to 8 point resizing for floating Components (such as Windows). Specify either `'all'` or any + * of `'n s e w ne nw se sw'`. + */ + handles: 's e se', + + /** + * @cfg {Number} height + * Optional. The height to set target to in pixels + */ + height : null, + + /** + * @cfg {Number} width + * Optional. The width to set the target to in pixels + */ + width : null, + + /** + * @cfg {Number} heightIncrement + * The increment to snap the height resize in pixels. + */ + heightIncrement : 0, + + /** + * @cfg {Number} widthIncrement + * The increment to snap the width resize in pixels. + */ + widthIncrement : 0, + + /** + * @cfg {Number} minHeight + * The minimum height for the element + */ + minHeight : 20, + + /** + * @cfg {Number} minWidth + * The minimum width for the element + */ + minWidth : 20, + + /** + * @cfg {Number} maxHeight + * The maximum height for the element + */ + maxHeight : 10000, + + /** + * @cfg {Number} maxWidth + * The maximum width for the element + */ + maxWidth : 10000, + + /** + * @cfg {Boolean} pinned + * True to ensure that the resize handles are always visible, false indicates resizing by cursor changes only + */ + pinned: false, + + /** + * @cfg {Boolean} preserveRatio + * True to preserve the original ratio between height and width during resize + */ + preserveRatio: false, + + /** + * @cfg {Boolean} transparent + * True for transparent handles. This is only applied at config time. + */ + transparent: false, + + /** + * @cfg {Ext.Element/Ext.util.Region} constrainTo + * An element, or a {@link Ext.util.Region Region} into which the resize operation must be constrained. + */ + + possiblePositions: { + n: 'north', + s: 'south', + e: 'east', + w: 'west', + se: 'southeast', + sw: 'southwest', + nw: 'northwest', + ne: 'northeast' + }, + + /** + * @cfg {Ext.Element/Ext.Component} target + * The Element or Component to resize. + */ + + /** + * @property {Ext.Element} el + * Outer element for resizing behavior. + */ + + constructor: function(config) { + var me = this, + target, + targetEl, + tag, + handles = me.handles, + handleCls, + possibles, + len, + i = 0, + pos, + handleEls = [], + eastWestStyle, style, + box; + + me.addEvents( + /** + * @event beforeresize + * Fired before resize is allowed. Return false to cancel resize. + * @param {Ext.resizer.Resizer} this + * @param {Number} width The start width + * @param {Number} height The start height + * @param {Ext.EventObject} e The mousedown event + */ + 'beforeresize', + /** + * @event resizedrag + * Fires during resizing. Return false to cancel resize. + * @param {Ext.resizer.Resizer} this + * @param {Number} width The new width + * @param {Number} height The new height + * @param {Ext.EventObject} e The mousedown event + */ + 'resizedrag', + /** + * @event resize + * Fired after a resize. + * @param {Ext.resizer.Resizer} this + * @param {Number} width The new width + * @param {Number} height The new height + * @param {Ext.EventObject} e The mouseup event + */ + 'resize' + ); + + if (Ext.isString(config) || Ext.isElement(config) || config.dom) { + target = config; + config = arguments[1] || {}; + config.target = target; + } + // will apply config to this + me.mixins.observable.constructor.call(me, config); + + // If target is a Component, ensure that we pull the element out. + // Resizer must examine the underlying Element. + target = me.target; + if (target) { + if (target.isComponent) { + me.el = target.getEl(); + if (target.minWidth) { + me.minWidth = target.minWidth; + } + if (target.minHeight) { + me.minHeight = target.minHeight; + } + if (target.maxWidth) { + me.maxWidth = target.maxWidth; + } + if (target.maxHeight) { + me.maxHeight = target.maxHeight; + } + if (target.floating) { + if (!me.hasOwnProperty('handles')) { + me.handles = 'n ne e se s sw w nw'; + } + } + } else { + me.el = me.target = Ext.get(target); + } + } + // Backwards compatibility with Ext3.x's Resizable which used el as a config. + else { + me.target = me.el = Ext.get(me.el); + } + + // Tags like textarea and img cannot + // have children and therefore must + // be wrapped + tag = me.el.dom.tagName.toUpperCase(); + if (tag == 'TEXTAREA' || tag == 'IMG' || tag == 'TABLE') { + /** + * @property {Ext.Element/Ext.Component} originalTarget + * Reference to the original resize target if the element of the original resize target was a + * {@link Ext.form.field.Field Field}, or an IMG or a TEXTAREA which must be wrapped in a DIV. + */ + me.originalTarget = me.target; + targetEl = me.el; + box = targetEl.getBox(); + me.target = me.el = me.el.wrap({ + cls: me.wrapCls, + id: me.el.id + '-rzwrap', + style: targetEl.getStyles('margin-top', 'margin-bottom') + }); + + // Transfer originalTarget's positioning+sizing+margins + me.el.setPositioning(targetEl.getPositioning()); + targetEl.clearPositioning(); + me.el.setBox(box); + + // Position the wrapped element absolute so that it does not stretch the wrapper + targetEl.setStyle('position', 'absolute'); + } + + // Position the element, this enables us to absolute position + // the handles within this.el + me.el.position(); + if (me.pinned) { + me.el.addCls(me.pinnedCls); + } + + /** + * @property {Ext.resizer.ResizeTracker} resizeTracker + */ + me.resizeTracker = new Ext.resizer.ResizeTracker({ + disabled: me.disabled, + target: me.target, + constrainTo: me.constrainTo, + overCls: me.overCls, + throttle: me.throttle, + originalTarget: me.originalTarget, + delegate: '.' + me.handleCls, + dynamic: me.dynamic, + preserveRatio: me.preserveRatio, + heightIncrement: me.heightIncrement, + widthIncrement: me.widthIncrement, + minHeight: me.minHeight, + maxHeight: me.maxHeight, + minWidth: me.minWidth, + maxWidth: me.maxWidth + }); + + // Relay the ResizeTracker's superclass events as our own resize events + me.resizeTracker.on({ + mousedown: me.onBeforeResize, + drag: me.onResize, + dragend: me.onResizeEnd, + scope: me + }); + + if (me.handles == 'all') { + me.handles = 'n s e w ne nw se sw'; + } + + handles = me.handles = me.handles.split(/ |\s*?[,;]\s*?/); + possibles = me.possiblePositions; + len = handles.length; + handleCls = me.handleCls + ' ' + (me.target.isComponent ? (me.target.baseCls + '-handle ') : '') + me.handleCls + '-'; + + // Needs heighting on IE6! + eastWestStyle = Ext.isIE6 ? ' style="height:' + me.el.getHeight() + 'px"' : ''; + + for (; i < len; i++){ + // if specified and possible, create + if (handles[i] && possibles[handles[i]]) { + pos = possibles[handles[i]]; + if (pos === 'east' || pos === 'west') { + style = eastWestStyle; + } else { + style = ''; + } + handleEls.push('
    '); + } + } + Ext.DomHelper.append(me.el, handleEls.join('')); + + // store a reference to each handle elelemtn in this.east, this.west, etc + for (i = 0; i < len; i++){ + // if specified and possible, create + if (handles[i] && possibles[handles[i]]) { + pos = possibles[handles[i]]; + me[pos] = me.el.getById(me.el.id + '-' + pos + '-handle'); + me[pos].region = pos; + me[pos].unselectable(); + if (me.transparent) { + me[pos].setOpacity(0); + } + } + } + + // Constrain within configured maxima + if (Ext.isNumber(me.width)) { + me.width = Ext.Number.constrain(me.width, me.minWidth, me.maxWidth); + } + if (Ext.isNumber(me.height)) { + me.height = Ext.Number.constrain(me.height, me.minHeight, me.maxHeight); + } + + // Size the target (and originalTarget) + if (me.width !== null || me.height !== null) { + if (me.originalTarget) { + me.originalTarget.setWidth(me.width); + me.originalTarget.setHeight(me.height); + } + me.resizeTo(me.width, me.height); + } + + me.forceHandlesHeight(); + }, + + disable: function() { + this.resizeTracker.disable(); + }, + + enable: function() { + this.resizeTracker.enable(); + }, + + /** + * @private Relay the Tracker's mousedown event as beforeresize + * @param tracker The Resizer + * @param e The Event + */ + onBeforeResize: function(tracker, e) { + var box = this.el.getBox(); + return this.fireEvent('beforeresize', this, box.width, box.height, e); + }, + + /** + * @private Relay the Tracker's drag event as resizedrag + * @param tracker The Resizer + * @param e The Event + */ + onResize: function(tracker, e) { + var me = this, + box = me.el.getBox(); + + me.forceHandlesHeight(); + return me.fireEvent('resizedrag', me, box.width, box.height, e); + }, + + /** + * @private Relay the Tracker's dragend event as resize + * @param tracker The Resizer + * @param e The Event + */ + onResizeEnd: function(tracker, e) { + var me = this, + box = me.el.getBox(); + + me.forceHandlesHeight(); + return me.fireEvent('resize', me, box.width, box.height, e); + }, + + /** + * Perform a manual resize and fires the 'resize' event. + * @param {Number} width + * @param {Number} height + */ + resizeTo : function(width, height) { + var me = this; + me.target.setSize(width, height); + me.fireEvent('resize', me, width, height, null); + }, + + /** + * Returns the element that was configured with the el or target config property. If a component was configured with + * the target property then this will return the element of this component. + * + * Textarea and img elements will be wrapped with an additional div because these elements do not support child + * nodes. The original element can be accessed through the originalTarget property. + * @return {Ext.Element} element + */ + getEl : function() { + return this.el; + }, + + /** + * Returns the element or component that was configured with the target config property. + * + * Textarea and img elements will be wrapped with an additional div because these elements do not support child + * nodes. The original element can be accessed through the originalTarget property. + * @return {Ext.Element/Ext.Component} + */ + getTarget: function() { + return this.target; + }, + + destroy: function() { + var i = 0, + handles = this.handles, + len = handles.length, + positions = this.possiblePositions; + + for (; i < len; i++) { + this[positions[handles[i]]].remove(); + } + }, + + /** + * @private + * Fix IE6 handle height issue. + */ + forceHandlesHeight : function() { + var me = this, + handle; + if (Ext.isIE6) { + handle = me.east; + if (handle) { + handle.setHeight(me.el.getHeight()); + } + handle = me.west; + if (handle) { + handle.setHeight(me.el.getHeight()); + } + me.el.repaint(); + } + } +}); + +/** + * Private utility class for Ext.resizer.Resizer. + * @private + */ +Ext.define('Ext.resizer.ResizeTracker', { + extend: 'Ext.dd.DragTracker', + dynamic: true, + preserveRatio: false, + + // Default to no constraint + constrainTo: null, + + proxyCls: Ext.baseCSSPrefix + 'resizable-proxy', + + constructor: function(config) { + var me = this, + widthRatio, heightRatio, + throttledResizeFn; + + if (!config.el) { + if (config.target.isComponent) { + me.el = config.target.getEl(); + } else { + me.el = config.target; + } + } + this.callParent(arguments); + + // Ensure that if we are preserving aspect ratio, the largest minimum is honoured + if (me.preserveRatio && me.minWidth && me.minHeight) { + widthRatio = me.minWidth / me.el.getWidth(); + heightRatio = me.minHeight / me.el.getHeight(); + + // largest ratio of minimum:size must be preserved. + // So if a 400x200 pixel image has + // minWidth: 50, maxWidth: 50, the maxWidth will be 400 * (50/200)... that is 100 + if (heightRatio > widthRatio) { + me.minWidth = me.el.getWidth() * heightRatio; + } else { + me.minHeight = me.el.getHeight() * widthRatio; + } + } + + // If configured as throttled, create an instance version of resize which calls + // a throttled function to perform the resize operation. + if (me.throttle) { + throttledResizeFn = Ext.Function.createThrottled(function() { + Ext.resizer.ResizeTracker.prototype.resize.apply(me, arguments); + }, me.throttle); + + me.resize = function(box, direction, atEnd) { + if (atEnd) { + Ext.resizer.ResizeTracker.prototype.resize.apply(me, arguments); + } else { + throttledResizeFn.apply(null, arguments); + } + }; + } + }, + + onBeforeStart: function(e) { + // record the startBox + this.startBox = this.el.getBox(); + }, + + /** + * @private + * Returns the object that will be resized on every mousemove event. + * If dynamic is false, this will be a proxy, otherwise it will be our actual target. + */ + getDynamicTarget: function() { + var me = this, + target = me.target; + + if (me.dynamic) { + return target; + } else if (!me.proxy) { + me.proxy = me.createProxy(target); + } + me.proxy.show(); + return me.proxy; + }, + + /** + * Create a proxy for this resizer + * @param {Ext.Component/Ext.Element} target The target + * @return {Ext.Element} A proxy element + */ + createProxy: function(target){ + var proxy, + cls = this.proxyCls, + renderTo; + + if (target.isComponent) { + proxy = target.getProxy().addCls(cls); + } else { + renderTo = Ext.getBody(); + if (Ext.scopeResetCSS) { + renderTo = Ext.getBody().createChild({ + cls: Ext.resetCls + }); + } + proxy = target.createProxy({ + tag: 'div', + cls: cls, + id: target.id + '-rzproxy' + }, renderTo); + } + proxy.removeCls(Ext.baseCSSPrefix + 'proxy-el'); + return proxy; + }, + + onStart: function(e) { + // returns the Ext.ResizeHandle that the user started dragging + this.activeResizeHandle = Ext.get(this.getDragTarget().id); + + // If we are using a proxy, ensure it is sized. + if (!this.dynamic) { + this.resize(this.startBox, { + horizontal: 'none', + vertical: 'none' + }); + } + }, + + onDrag: function(e) { + // dynamic resizing, update dimensions during resize + if (this.dynamic || this.proxy) { + this.updateDimensions(e); + } + }, + + updateDimensions: function(e, atEnd) { + var me = this, + region = me.activeResizeHandle.region, + offset = me.getOffset(me.constrainTo ? 'dragTarget' : null), + box = me.startBox, + ratio, + widthAdjust = 0, + heightAdjust = 0, + snappedWidth, + snappedHeight, + adjustX = 0, + adjustY = 0, + dragRatio, + horizDir = offset[0] < 0 ? 'right' : 'left', + vertDir = offset[1] < 0 ? 'down' : 'up', + oppositeCorner, + axis, // 1 = x, 2 = y, 3 = x and y. + newBox, + newHeight, newWidth; + + switch (region) { + case 'south': + heightAdjust = offset[1]; + axis = 2; + break; + case 'north': + heightAdjust = -offset[1]; + adjustY = -heightAdjust; + axis = 2; + break; + case 'east': + widthAdjust = offset[0]; + axis = 1; + break; + case 'west': + widthAdjust = -offset[0]; + adjustX = -widthAdjust; + axis = 1; + break; + case 'northeast': + heightAdjust = -offset[1]; + adjustY = -heightAdjust; + widthAdjust = offset[0]; + oppositeCorner = [box.x, box.y + box.height]; + axis = 3; + break; + case 'southeast': + heightAdjust = offset[1]; + widthAdjust = offset[0]; + oppositeCorner = [box.x, box.y]; + axis = 3; + break; + case 'southwest': + widthAdjust = -offset[0]; + adjustX = -widthAdjust; + heightAdjust = offset[1]; + oppositeCorner = [box.x + box.width, box.y]; + axis = 3; + break; + case 'northwest': + heightAdjust = -offset[1]; + adjustY = -heightAdjust; + widthAdjust = -offset[0]; + adjustX = -widthAdjust; + oppositeCorner = [box.x + box.width, box.y + box.height]; + axis = 3; + break; + } + + newBox = { + width: box.width + widthAdjust, + height: box.height + heightAdjust, + x: box.x + adjustX, + y: box.y + adjustY + }; + + // Snap value between stops according to configured increments + snappedWidth = Ext.Number.snap(newBox.width, me.widthIncrement); + snappedHeight = Ext.Number.snap(newBox.height, me.heightIncrement); + if (snappedWidth != newBox.width || snappedHeight != newBox.height){ + switch (region) { + case 'northeast': + newBox.y -= snappedHeight - newBox.height; + break; + case 'north': + newBox.y -= snappedHeight - newBox.height; + break; + case 'southwest': + newBox.x -= snappedWidth - newBox.width; + break; + case 'west': + newBox.x -= snappedWidth - newBox.width; + break; + case 'northwest': + newBox.x -= snappedWidth - newBox.width; + newBox.y -= snappedHeight - newBox.height; + } + newBox.width = snappedWidth; + newBox.height = snappedHeight; + } + + // out of bounds + if (newBox.width < me.minWidth || newBox.width > me.maxWidth) { + newBox.width = Ext.Number.constrain(newBox.width, me.minWidth, me.maxWidth); + + // Re-adjust the X position if we were dragging the west side + if (adjustX) { + newBox.x = box.x + (box.width - newBox.width); + } + } else { + me.lastX = newBox.x; + } + if (newBox.height < me.minHeight || newBox.height > me.maxHeight) { + newBox.height = Ext.Number.constrain(newBox.height, me.minHeight, me.maxHeight); + + // Re-adjust the Y position if we were dragging the north side + if (adjustY) { + newBox.y = box.y + (box.height - newBox.height); + } + } else { + me.lastY = newBox.y; + } + + // If this is configured to preserve the aspect ratio, or they are dragging using the shift key + if (me.preserveRatio || e.shiftKey) { + ratio = me.startBox.width / me.startBox.height; + + // Calculate aspect ratio constrained values. + newHeight = Math.min(Math.max(me.minHeight, newBox.width / ratio), me.maxHeight); + newWidth = Math.min(Math.max(me.minWidth, newBox.height * ratio), me.maxWidth); + + // X axis: width-only change, height must obey + if (axis == 1) { + newBox.height = newHeight; + } + + // Y axis: height-only change, width must obey + else if (axis == 2) { + newBox.width = newWidth; + } + + // Corner drag. + else { + // Drag ratio is the ratio of the mouse point from the opposite corner. + // Basically what edge we are dragging, a horizontal edge or a vertical edge. + dragRatio = Math.abs(oppositeCorner[0] - this.lastXY[0]) / Math.abs(oppositeCorner[1] - this.lastXY[1]); + + // If drag ratio > aspect ratio then width is dominant and height must obey + if (dragRatio > ratio) { + newBox.height = newHeight; + } else { + newBox.width = newWidth; + } + + // Handle dragging start coordinates + if (region == 'northeast') { + newBox.y = box.y - (newBox.height - box.height); + } else if (region == 'northwest') { + newBox.y = box.y - (newBox.height - box.height); + newBox.x = box.x - (newBox.width - box.width); + } else if (region == 'southwest') { + newBox.x = box.x - (newBox.width - box.width); + } + } + } + + if (heightAdjust === 0) { + vertDir = 'none'; + } + if (widthAdjust === 0) { + horizDir = 'none'; + } + me.resize(newBox, { + horizontal: horizDir, + vertical: vertDir + }, atEnd); + }, + + getResizeTarget: function(atEnd) { + return atEnd ? this.target : this.getDynamicTarget(); + }, + + resize: function(box, direction, atEnd) { + var target = this.getResizeTarget(atEnd); + if (target.isComponent) { + target.setSize(box.width, box.height); + if (target.floating) { + target.setPagePosition(box.x, box.y); + } + } else { + target.setBox(box); + } + + // update the originalTarget if it was wrapped, and the target passed in was the wrap el. + target = this.originalTarget; + if (target && (this.dynamic || atEnd)) { + if (target.isComponent) { + target.setSize(box.width, box.height); + if (target.floating) { + target.setPagePosition(box.x, box.y); + } + } else { + target.setBox(box); + } + } + }, + + onEnd: function(e) { + this.updateDimensions(e, true); + if (this.proxy) { + this.proxy.hide(); + } + } +}); + +/** + * Private utility class for Ext.Splitter. + * @private + */ +Ext.define('Ext.resizer.SplitterTracker', { + extend: 'Ext.dd.DragTracker', + requires: ['Ext.util.Region'], + enabled: true, + + overlayCls: Ext.baseCSSPrefix + 'resizable-overlay', + + createDragOverlay: function () { + var overlay; + + overlay = this.overlay = Ext.getBody().createChild({ + cls: this.overlayCls, + html: ' ' + }); + + overlay.unselectable(); + overlay.setSize(Ext.Element.getViewWidth(true), Ext.Element.getViewHeight(true)); + overlay.show(); + }, + + getPrevCmp: function() { + var splitter = this.getSplitter(); + return splitter.previousSibling(); + }, + + getNextCmp: function() { + var splitter = this.getSplitter(); + return splitter.nextSibling(); + }, + + // ensure the tracker is enabled, store boxes of previous and next + // components and calculate the constrain region + onBeforeStart: function(e) { + var me = this, + prevCmp = me.getPrevCmp(), + nextCmp = me.getNextCmp(), + collapseEl = me.getSplitter().collapseEl, + target = e.getTarget(), + box; + + if (collapseEl && target === me.getSplitter().collapseEl.dom) { + return false; + } + + // SplitterTracker is disabled if any of its adjacents are collapsed. + if (nextCmp.collapsed || prevCmp.collapsed) { + return false; + } + + // store boxes of previous and next + me.prevBox = prevCmp.getEl().getBox(); + me.nextBox = nextCmp.getEl().getBox(); + me.constrainTo = box = me.calculateConstrainRegion(); + + if (!box) { + return false; + } + + me.createDragOverlay(); + + return box; + }, + + // We move the splitter el. Add the proxy class. + onStart: function(e) { + var splitter = this.getSplitter(); + splitter.addCls(splitter.baseCls + '-active'); + }, + + // calculate the constrain Region in which the splitter el may be moved. + calculateConstrainRegion: function() { + var me = this, + splitter = me.getSplitter(), + splitWidth = splitter.getWidth(), + defaultMin = splitter.defaultSplitMin, + orient = splitter.orientation, + prevBox = me.prevBox, + prevCmp = me.getPrevCmp(), + nextBox = me.nextBox, + nextCmp = me.getNextCmp(), + // prev and nextConstrainRegions are the maximumBoxes minus the + // minimumBoxes. The result is always the intersection + // of these two boxes. + prevConstrainRegion, nextConstrainRegion; + + // vertical splitters, so resizing left to right + if (orient === 'vertical') { + + // Region constructor accepts (top, right, bottom, left) + // anchored/calculated from the left + prevConstrainRegion = new Ext.util.Region( + prevBox.y, + // Right boundary is x + maxWidth if there IS a maxWidth. + // Otherwise it is calculated based upon the minWidth of the next Component + (prevCmp.maxWidth ? prevBox.x + prevCmp.maxWidth : nextBox.right - (nextCmp.minWidth || defaultMin)) + splitWidth, + prevBox.bottom, + prevBox.x + (prevCmp.minWidth || defaultMin) + ); + // anchored/calculated from the right + nextConstrainRegion = new Ext.util.Region( + nextBox.y, + nextBox.right - (nextCmp.minWidth || defaultMin), + nextBox.bottom, + // Left boundary is right - maxWidth if there IS a maxWidth. + // Otherwise it is calculated based upon the minWidth of the previous Component + (nextCmp.maxWidth ? nextBox.right - nextCmp.maxWidth : prevBox.x + (prevBox.minWidth || defaultMin)) - splitWidth + ); + } else { + // anchored/calculated from the top + prevConstrainRegion = new Ext.util.Region( + prevBox.y + (prevCmp.minHeight || defaultMin), + prevBox.right, + // Bottom boundary is y + maxHeight if there IS a maxHeight. + // Otherwise it is calculated based upon the minWidth of the next Component + (prevCmp.maxHeight ? prevBox.y + prevCmp.maxHeight : nextBox.bottom - (nextCmp.minHeight || defaultMin)) + splitWidth, + prevBox.x + ); + // anchored/calculated from the bottom + nextConstrainRegion = new Ext.util.Region( + // Top boundary is bottom - maxHeight if there IS a maxHeight. + // Otherwise it is calculated based upon the minHeight of the previous Component + (nextCmp.maxHeight ? nextBox.bottom - nextCmp.maxHeight : prevBox.y + (prevCmp.minHeight || defaultMin)) - splitWidth, + nextBox.right, + nextBox.bottom - (nextCmp.minHeight || defaultMin), + nextBox.x + ); + } + + // intersection of the two regions to provide region draggable + return prevConstrainRegion.intersect(nextConstrainRegion); + }, + + // Performs the actual resizing of the previous and next components + performResize: function(e, offset) { + var me = this, + splitter = me.getSplitter(), + orient = splitter.orientation, + prevCmp = me.getPrevCmp(), + nextCmp = me.getNextCmp(), + owner = splitter.ownerCt, + flexedSiblings = owner.query('>[flex]'), + len = flexedSiblings.length, + i = 0, + dimension, + size, + totalFlex = 0; + + // Convert flexes to pixel values proportional to the total pixel width of all flexes. + for (; i < len; i++) { + size = flexedSiblings[i].getWidth(); + totalFlex += size; + flexedSiblings[i].flex = size; + } + + offset = offset || me.getOffset('dragTarget'); + + if (orient === 'vertical') { + offset = offset[0]; + dimension = 'width'; + } else { + dimension = 'height'; + offset = offset[1]; + } + if (prevCmp) { + size = me.prevBox[dimension] + offset; + if (prevCmp.flex) { + prevCmp.flex = size; + } else { + prevCmp[dimension] = size; + } + } + if (nextCmp) { + size = me.nextBox[dimension] - offset; + if (nextCmp.flex) { + nextCmp.flex = size; + } else { + nextCmp[dimension] = size; + } + } + + owner.updateLayout(); + }, + + // Cleans up the overlay (if we have one) and calls the base. This cannot be done in + // onEnd, because onEnd is only called if a drag is detected but the overlay is created + // regardless (by onBeforeStart). + endDrag: function () { + var me = this; + + if (me.overlay) { + me.overlay.remove(); + delete me.overlay; + } + + me.callParent(arguments); // this calls onEnd + }, + + // perform the resize and remove the proxy class from the splitter el + onEnd: function(e) { + var me = this, + splitter = me.getSplitter(); + + splitter.removeCls(splitter.baseCls + '-active'); + me.performResize(e, me.getOffset('dragTarget')); + }, + + // Track the proxy and set the proper XY coordinates + // while constraining the drag + onDrag: function(e) { + var me = this, + offset = me.getOffset('dragTarget'), + splitter = me.getSplitter(), + splitEl = splitter.getEl(), + orient = splitter.orientation; + + if (orient === "vertical") { + splitEl.setX(me.startRegion.left + offset[0]); + } else { + splitEl.setY(me.startRegion.top + offset[1]); + } + }, + + getSplitter: function() { + return this.splitter; + } +}); +/** + * @class Ext.slider.Thumb + * @private + * Represents a single thumb element on a Slider. This would not usually be created manually and would instead + * be created internally by an {@link Ext.slider.Multi Multi slider}. + */ +Ext.define('Ext.slider.Thumb', { + requires: ['Ext.dd.DragTracker', 'Ext.util.Format'], + /** + * @private + * @property {Number} topThumbZIndex + * The number used internally to set the z index of the top thumb (see promoteThumb for details) + */ + topZIndex: 10000, + + /** + * @cfg {Ext.slider.MultiSlider} slider (required) + * The Slider to render to. + */ + + /** + * Creates new slider thumb. + * @param {Object} [config] Config object. + */ + constructor: function(config) { + var me = this; + + /** + * @property {Ext.slider.MultiSlider} slider + * The slider this thumb is contained within + */ + Ext.apply(me, config || {}, { + cls: Ext.baseCSSPrefix + 'slider-thumb', + + /** + * @cfg {Boolean} constrain True to constrain the thumb so that it cannot overlap its siblings + */ + constrain: false + }); + me.callParent([config]); + }, + + /** + * Renders the thumb into a slider + */ + render: function() { + var me = this; + me.el = me.slider.innerEl.insertFirst(me.getElConfig()); + me.onRender(); + }, + + onRender: function() { + if (this.disabled) { + this.disable(); + } + this.initEvents(); + }, + + getElConfig: function() { + var me = this, + slider = me.slider, + style = {}; + + style[slider.vertical ? 'bottom' : 'left'] = slider.calculateThumbPosition(slider.normalizeValue(me.value)) + '%'; + return { + style: style, + id : this.id, + cls : this.cls + }; + }, + + /** + * @private + * move the thumb + */ + move: function(v, animate) { + var el = this.el, + styleProp = this.slider.vertical ? 'bottom' : 'left', + to, + from; + + v += '%'; + + if (!animate) { + el.dom.style[styleProp] = v; + } else { + to = {}; + to[styleProp] = v; + + if (!Ext.supports.GetPositionPercentage) { + from = {}; + from[styleProp] = el.dom.style[styleProp]; + } + + new Ext.fx.Anim({ + target: el, + duration: 350, + from: from, + to: to + }); + } + }, + + /** + * @private + * Bring thumb dom element to front. + */ + bringToFront: function() { + this.el.setStyle('zIndex', this.topZIndex); + }, + + /** + * @private + * Send thumb dom element to back. + */ + sendToBack: function() { + this.el.setStyle('zIndex', ''); + }, + + /** + * Enables the thumb if it is currently disabled + */ + enable: function() { + var me = this; + + me.disabled = false; + if (me.el) { + me.el.removeCls(me.slider.disabledCls); + } + }, + + /** + * Disables the thumb if it is currently enabled + */ + disable: function() { + var me = this; + + me.disabled = true; + if (me.el) { + me.el.addCls(me.slider.disabledCls); + } + }, + + /** + * Sets up an Ext.dd.DragTracker for this thumb + */ + initEvents: function() { + var me = this, + el = me.el; + + me.tracker = new Ext.dd.DragTracker({ + onBeforeStart: Ext.Function.bind(me.onBeforeDragStart, me), + onStart : Ext.Function.bind(me.onDragStart, me), + onDrag : Ext.Function.bind(me.onDrag, me), + onEnd : Ext.Function.bind(me.onDragEnd, me), + tolerance : 3, + autoStart : 300, + overCls : Ext.baseCSSPrefix + 'slider-thumb-over' + }); + + me.tracker.initEl(el); + }, + + /** + * @private + * This is tied into the internal Ext.dd.DragTracker. If the slider is currently disabled, + * this returns false to disable the DragTracker too. + * @return {Boolean} False if the slider is currently disabled + */ + onBeforeDragStart : function(e) { + if (this.disabled) { + return false; + } else { + this.slider.promoteThumb(this); + return true; + } + }, + + /** + * @private + * This is tied into the internal Ext.dd.DragTracker's onStart template method. Adds the drag CSS class + * to the thumb and fires the 'dragstart' event + */ + onDragStart: function(e){ + var me = this; + + me.el.addCls(Ext.baseCSSPrefix + 'slider-thumb-drag'); + me.dragging = me.slider.dragging = true; + me.dragStartValue = me.value; + + me.slider.fireEvent('dragstart', me.slider, e, me); + }, + + /** + * @private + * This is tied into the internal Ext.dd.DragTracker's onDrag template method. This is called every time + * the DragTracker detects a drag movement. It updates the Slider's value using the position of the drag + */ + onDrag: function(e) { + var me = this, + slider = me.slider, + index = me.index, + newValue = me.getValueFromTracker(), + above, + below; + + // If dragged out of range, value will be undefined + if (newValue !== undefined) { + if (me.constrain) { + above = slider.thumbs[index + 1]; + below = slider.thumbs[index - 1]; + + if (below !== undefined && newValue <= below.value) { + newValue = below.value; + } + + if (above !== undefined && newValue >= above.value) { + newValue = above.value; + } + } + slider.setValue(index, newValue, false); + slider.fireEvent('drag', slider, e, me); + } + }, + + getValueFromTracker: function() { + var slider = this.slider, + trackPoint = slider.getTrackpoint(this.tracker.getXY()); + + // If dragged out of range, value will be undefined + if (trackPoint !== undefined) { + return slider.reversePixelValue(trackPoint); + } + }, + + /** + * @private + * This is tied to the internal Ext.dd.DragTracker's onEnd template method. Removes the drag CSS class and + * fires the 'changecomplete' event with the new value + */ + onDragEnd: function(e) { + var me = this, + slider = me.slider, + value = me.value; + + me.el.removeCls(Ext.baseCSSPrefix + 'slider-thumb-drag'); + + me.dragging = slider.dragging = false; + slider.fireEvent('dragend', slider, e); + + if (me.dragStartValue != value) { + slider.fireEvent('changecomplete', slider, value, me); + } + }, + + destroy: function() { + Ext.destroy(this.tracker); + } +}); + +/** + * This plugin provides drag and/or drop functionality for a TreeView. + * + * It creates a specialized instance of {@link Ext.dd.DragZone DragZone} which knows how to drag out of a + * {@link Ext.tree.View TreeView} and loads the data object which is passed to a cooperating + * {@link Ext.dd.DragZone DragZone}'s methods with the following properties: + * + * - copy : Boolean + * + * The value of the TreeView's `copy` property, or `true` if the TreeView was configured with `allowCopy: true` *and* + * the control key was pressed when the drag operation was begun. + * + * - view : TreeView + * + * The source TreeView from which the drag originated. + * + * - ddel : HtmlElement + * + * The drag proxy element which moves with the mouse + * + * - item : HtmlElement + * + * The TreeView node upon which the mousedown event was registered. + * + * - records : Array + * + * An Array of {@link Ext.data.Model Models} representing the selected data being dragged from the source TreeView. + * + * It also creates a specialized instance of {@link Ext.dd.DropZone} which cooperates with other DropZones which are + * members of the same ddGroup which processes such data objects. + * + * Adding this plugin to a view means that two new events may be fired from the client TreeView, {@link #beforedrop} and + * {@link #drop}. + * + * Note that the plugin must be added to the tree view, not to the tree panel. For example using viewConfig: + * + * viewConfig: { + * plugins: { ptype: 'treeviewdragdrop' } + * } + */ +Ext.define('Ext.tree.plugin.TreeViewDragDrop', { + extend: 'Ext.AbstractPlugin', + alias: 'plugin.treeviewdragdrop', + + uses: [ + 'Ext.tree.ViewDragZone', + 'Ext.tree.ViewDropZone' + ], + + /** + * @event beforedrop + * + * **This event is fired through the TreeView. Add listeners to the TreeView object** + * + * Fired when a drop gesture has been triggered by a mouseup event in a valid drop position in the TreeView. + * + * @param {HTMLElement} node The TreeView node **if any** over which the mouse was positioned. + * + * Returning `false` to this event signals that the drop gesture was invalid, and if the drag proxy will animate + * back to the point from which the drag began. + * + * Returning `0` To this event signals that the data transfer operation should not take place, but that the gesture + * was valid, and that the repair operation should not take place. + * + * Any other return value continues with the data transfer operation. + * + * @param {Object} data The data object gathered at mousedown time by the cooperating + * {@link Ext.dd.DragZone DragZone}'s {@link Ext.dd.DragZone#getDragData getDragData} method it contains the following + * properties: + * @param {Boolean} data.copy The value of the TreeView's `copy` property, or `true` if the TreeView was configured with + * `allowCopy: true` and the control key was pressed when the drag operation was begun + * @param {Ext.tree.View} data.view The source TreeView from which the drag originated. + * @param {HTMLElement} data.ddel The drag proxy element which moves with the mouse + * @param {HTMLElement} data.item The TreeView node upon which the mousedown event was registered. + * @param {Ext.data.Model[]} data.records An Array of {@link Ext.data.Model Model}s representing the selected data being + * dragged from the source TreeView. + * + * @param {Ext.data.Model} overModel The Model over which the drop gesture took place. + * + * @param {String} dropPosition `"before"`, `"after"` or `"append"` depending on whether the mouse is above or below + * the midline of the node, or the node is a branch node which accepts new child nodes. + * + * @param {Object} dropHandler An object containing methods to complete/cancel the data transfer operation and either + * move or copy Model instances from the source View's Store to the destination View's Store. + * + * This is useful when you want to perform some kind of asynchronous processing before confirming/cancelling + * the drop, such as an {@link Ext.window.MessageBox#confirm confirm} call, or an Ajax request. + * + * Set dropHandler.wait = true in this event handler to delay processing. When you want to complete the event, call + * dropHandler.processDrop(). To cancel the drop, call dropHandler.cancelDrop. + */ + + /** + * @event drop + * + * **This event is fired through the TreeView. Add listeners to the TreeView object** Fired when a drop operation + * has been completed and the data has been moved or copied. + * + * @param {HTMLElement} node The TreeView node **if any** over which the mouse was positioned. + * + * @param {Object} data The data object gathered at mousedown time by the cooperating + * {@link Ext.dd.DragZone DragZone}'s {@link Ext.dd.DragZone#getDragData getDragData} method it contains the following + * properties: + * @param {Boolean} data.copy The value of the TreeView's `copy` property, or `true` if the TreeView was configured with + * `allowCopy: true` and the control key was pressed when the drag operation was begun + * @param {Ext.tree.View} data.view The source TreeView from which the drag originated. + * @param {HTMLElement} data.ddel The drag proxy element which moves with the mouse + * @param {HTMLElement} data.item The TreeView node upon which the mousedown event was registered. + * @param {Ext.data.Model[]} data.records An Array of {@link Ext.data.Model Model}s representing the selected data being + * dragged from the source TreeView. + * + * @param {Ext.data.Model} overModel The Model over which the drop gesture took place. + * + * @param {String} dropPosition `"before"`, `"after"` or `"append"` depending on whether the mouse is above or below + * the midline of the node, or the node is a branch node which accepts new child nodes. + */ + // + dragText : '{0} selected node{1}', + // + + /** + * @cfg {Boolean} allowParentInsert + * Allow inserting a dragged node between an expanded parent node and its first child that will become a sibling of + * the parent when dropped. + */ + allowParentInserts: false, + + /** + * @cfg {String} allowContainerDrop + * True if drops on the tree container (outside of a specific tree node) are allowed. + */ + allowContainerDrops: false, + + /** + * @cfg {String} appendOnly + * True if the tree should only allow append drops (use for trees which are sorted). + */ + appendOnly: false, + + /** + * @cfg {String} ddGroup + * A named drag drop group to which this object belongs. If a group is specified, then both the DragZones and + * DropZone used by this plugin will only interact with other drag drop objects in the same group. + */ + ddGroup : "TreeDD", + + /** + * @cfg {String} dragGroup + * The ddGroup to which the DragZone will belong. + * + * This defines which other DropZones the DragZone will interact with. Drag/DropZones only interact with other + * Drag/DropZones which are members of the same ddGroup. + */ + + /** + * @cfg {String} dropGroup + * The ddGroup to which the DropZone will belong. + * + * This defines which other DragZones the DropZone will interact with. Drag/DropZones only interact with other + * Drag/DropZones which are members of the same ddGroup. + */ + + /** + * @cfg {String} expandDelay + * The delay in milliseconds to wait before expanding a target tree node while dragging a droppable node over the + * target. + */ + expandDelay : 1000, + + /** + * @cfg {Boolean} enableDrop + * Set to `false` to disallow the View from accepting drop gestures. + */ + enableDrop: true, + + /** + * @cfg {Boolean} enableDrag + * Set to `false` to disallow dragging items from the View. + */ + enableDrag: true, + + /** + * @cfg {String} nodeHighlightColor + * The color to use when visually highlighting the dragged or dropped node (default value is light blue). + * The color must be a 6 digit hex value, without a preceding '#'. See also {@link #nodeHighlightOnDrop} and + * {@link #nodeHighlightOnRepair}. + */ + nodeHighlightColor: 'c3daf9', + + /** + * @cfg {Boolean} nodeHighlightOnDrop + * Whether or not to highlight any nodes after they are + * successfully dropped on their target. Defaults to the value of `Ext.enableFx`. + * See also {@link #nodeHighlightColor} and {@link #nodeHighlightOnRepair}. + */ + nodeHighlightOnDrop: Ext.enableFx, + + /** + * @cfg {Boolean} nodeHighlightOnRepair + * Whether or not to highlight any nodes after they are + * repaired from an unsuccessful drag/drop. Defaults to the value of `Ext.enableFx`. + * See also {@link #nodeHighlightColor} and {@link #nodeHighlightOnDrop}. + */ + nodeHighlightOnRepair: Ext.enableFx, + + init : function(view) { + view.on('render', this.onViewRender, this, {single: true}); + }, + + /** + * @private + * AbstractComponent calls destroy on all its plugins at destroy time. + */ + destroy: function() { + Ext.destroy(this.dragZone, this.dropZone); + }, + + onViewRender : function(view) { + var me = this; + + if (me.enableDrag) { + me.dragZone = new Ext.tree.ViewDragZone({ + view: view, + ddGroup: me.dragGroup || me.ddGroup, + dragText: me.dragText, + repairHighlightColor: me.nodeHighlightColor, + repairHighlight: me.nodeHighlightOnRepair + }); + } + + if (me.enableDrop) { + me.dropZone = new Ext.tree.ViewDropZone({ + view: view, + ddGroup: me.dropGroup || me.ddGroup, + allowContainerDrops: me.allowContainerDrops, + appendOnly: me.appendOnly, + allowParentInserts: me.allowParentInserts, + expandDelay: me.expandDelay, + dropHighlightColor: me.nodeHighlightColor, + dropHighlight: me.nodeHighlightOnDrop + }); + } + } +}); + +/** + * This animation class is a mixin. + * + * Ext.util.Animate provides an API for the creation of animated transitions of properties and styles. + * This class is used as a mixin and currently applied to {@link Ext.Element}, {@link Ext.CompositeElement}, + * {@link Ext.draw.Sprite}, {@link Ext.draw.CompositeSprite}, and {@link Ext.Component}. Note that Components + * have a limited subset of what attributes can be animated such as top, left, x, y, height, width, and + * opacity (color, paddings, and margins can not be animated). + * + * ## Animation Basics + * + * All animations require three things - `easing`, `duration`, and `to` (the final end value for each property) + * you wish to animate. Easing and duration are defaulted values specified below. + * Easing describes how the intermediate values used during a transition will be calculated. + * {@link Ext.fx.Anim#easing Easing} allows for a transition to change speed over its duration. + * You may use the defaults for easing and duration, but you must always set a + * {@link Ext.fx.Anim#to to} property which is the end value for all animations. + * + * Popular element 'to' configurations are: + * + * - opacity + * - x + * - y + * - color + * - height + * - width + * + * Popular sprite 'to' configurations are: + * + * - translation + * - path + * - scale + * - stroke + * - rotation + * + * The default duration for animations is 250 (which is a 1/4 of a second). Duration is denoted in + * milliseconds. Therefore 1 second is 1000, 1 minute would be 60000, and so on. The default easing curve + * used for all animations is 'ease'. Popular easing functions are included and can be found in {@link Ext.fx.Anim#easing Easing}. + * + * For example, a simple animation to fade out an element with a default easing and duration: + * + * var p1 = Ext.get('myElementId'); + * + * p1.animate({ + * to: { + * opacity: 0 + * } + * }); + * + * To make this animation fade out in a tenth of a second: + * + * var p1 = Ext.get('myElementId'); + * + * p1.animate({ + * duration: 100, + * to: { + * opacity: 0 + * } + * }); + * + * ## Animation Queues + * + * By default all animations are added to a queue which allows for animation via a chain-style API. + * For example, the following code will queue 4 animations which occur sequentially (one right after the other): + * + * p1.animate({ + * to: { + * x: 500 + * } + * }).animate({ + * to: { + * y: 150 + * } + * }).animate({ + * to: { + * backgroundColor: '#f00' //red + * } + * }).animate({ + * to: { + * opacity: 0 + * } + * }); + * + * You can change this behavior by calling the {@link Ext.util.Animate#syncFx syncFx} method and all + * subsequent animations for the specified target will be run concurrently (at the same time). + * + * p1.syncFx(); //this will make all animations run at the same time + * + * p1.animate({ + * to: { + * x: 500 + * } + * }).animate({ + * to: { + * y: 150 + * } + * }).animate({ + * to: { + * backgroundColor: '#f00' //red + * } + * }).animate({ + * to: { + * opacity: 0 + * } + * }); + * + * This works the same as: + * + * p1.animate({ + * to: { + * x: 500, + * y: 150, + * backgroundColor: '#f00' //red + * opacity: 0 + * } + * }); + * + * The {@link Ext.util.Animate#stopAnimation stopAnimation} method can be used to stop any + * currently running animations and clear any queued animations. + * + * ## Animation Keyframes + * + * You can also set up complex animations with {@link Ext.fx.Anim#keyframes keyframes} which follow the + * CSS3 Animation configuration pattern. Note rotation, translation, and scaling can only be done for sprites. + * The previous example can be written with the following syntax: + * + * p1.animate({ + * duration: 1000, //one second total + * keyframes: { + * 25: { //from 0 to 250ms (25%) + * x: 0 + * }, + * 50: { //from 250ms to 500ms (50%) + * y: 0 + * }, + * 75: { //from 500ms to 750ms (75%) + * backgroundColor: '#f00' //red + * }, + * 100: { //from 750ms to 1sec + * opacity: 0 + * } + * } + * }); + * + * ## Animation Events + * + * Each animation you create has events for {@link Ext.fx.Anim#beforeanimate beforeanimate}, + * {@link Ext.fx.Anim#afteranimate afteranimate}, and {@link Ext.fx.Anim#lastframe lastframe}. + * Keyframed animations adds an additional {@link Ext.fx.Animator#keyframe keyframe} event which + * fires for each keyframe in your animation. + * + * All animations support the {@link Ext.util.Observable#listeners listeners} configuration to attact functions to these events. + * + * startAnimate: function() { + * var p1 = Ext.get('myElementId'); + * p1.animate({ + * duration: 100, + * to: { + * opacity: 0 + * }, + * listeners: { + * beforeanimate: function() { + * // Execute my custom method before the animation + * this.myBeforeAnimateFn(); + * }, + * afteranimate: function() { + * // Execute my custom method after the animation + * this.myAfterAnimateFn(); + * }, + * scope: this + * }); + * }, + * myBeforeAnimateFn: function() { + * // My custom logic + * }, + * myAfterAnimateFn: function() { + * // My custom logic + * } + * + * Due to the fact that animations run asynchronously, you can determine if an animation is currently + * running on any target by using the {@link Ext.util.Animate#getActiveAnimation getActiveAnimation} + * method. This method will return false if there are no active animations or return the currently + * running {@link Ext.fx.Anim} instance. + * + * In this example, we're going to wait for the current animation to finish, then stop any other + * queued animations before we fade our element's opacity to 0: + * + * var curAnim = p1.getActiveAnimation(); + * if (curAnim) { + * curAnim.on('afteranimate', function() { + * p1.stopAnimation(); + * p1.animate({ + * to: { + * opacity: 0 + * } + * }); + * }); + * } + */ +Ext.define('Ext.util.Animate', { + + uses: ['Ext.fx.Manager', 'Ext.fx.Anim'], + + /** + * Perform custom animation on this object. + * + * This method is applicable to both the {@link Ext.Component Component} class and the {@link Ext.Element Element} + * class. It performs animated transitions of certain properties of this object over a specified timeline. + * + * The sole parameter is an object which specifies start property values, end property values, and properties which + * describe the timeline. + * + * ### Animating an {@link Ext.Element Element} + * + * When animating an Element, the following properties may be specified in `from`, `to`, and `keyframe` objects: + * + * - `x` - The page X position in pixels. + * + * - `y` - The page Y position in pixels + * + * - `left` - The element's CSS `left` value. Units must be supplied. + * + * - `top` - The element's CSS `top` value. Units must be supplied. + * + * - `width` - The element's CSS `width` value. Units must be supplied. + * + * - `height` - The element's CSS `height` value. Units must be supplied. + * + * - `scrollLeft` - The element's `scrollLeft` value. + * + * - `scrollTop` - The element's `scrollLeft` value. + * + * - `opacity` - The element's `opacity` value. This must be a value between `0` and `1`. + * + * **Be aware than animating an Element which is being used by an Ext Component without in some way informing the + * Component about the changed element state will result in incorrect Component behaviour. This is because the + * Component will be using the old state of the element. To avoid this problem, it is now possible to directly + * animate certain properties of Components.** + * + * ### Animating a {@link Ext.Component Component} + * + * When animating a Component, the following properties may be specified in `from`, `to`, and `keyframe` objects: + * + * - `x` - The Component's page X position in pixels. + * + * - `y` - The Component's page Y position in pixels + * + * - `left` - The Component's `left` value in pixels. + * + * - `top` - The Component's `top` value in pixels. + * + * - `width` - The Component's `width` value in pixels. + * + * - `width` - The Component's `width` value in pixels. + * + * - `dynamic` - Specify as true to update the Component's layout (if it is a Container) at every frame of the animation. + * *Use sparingly as laying out on every intermediate size change is an expensive operation.* + * + * For example, to animate a Window to a new size, ensuring that its internal layout, and any shadow is correct: + * + * myWindow = Ext.create('Ext.window.Window', { + * title: 'Test Component animation', + * width: 500, + * height: 300, + * layout: { + * type: 'hbox', + * align: 'stretch' + * }, + * items: [{ + * title: 'Left: 33%', + * margins: '5 0 5 5', + * flex: 1 + * }, { + * title: 'Left: 66%', + * margins: '5 5 5 5', + * flex: 2 + * }] + * }); + * myWindow.show(); + * myWindow.header.el.on('click', function() { + * myWindow.animate({ + * to: { + * width: (myWindow.getWidth() == 500) ? 700 : 500, + * height: (myWindow.getHeight() == 300) ? 400 : 300, + * } + * }); + * }); + * + * For performance reasons, by default, the internal layout is only updated when the Window reaches its final `"to"` + * size. If dynamic updating of the Window's child Components is required, then configure the animation with + * `dynamic: true` and the two child items will maintain their proportions during the animation. + * + * @param {Object} config An object containing properties which describe the animation's start and end states, and + * the timeline of the animation. Of the properties listed below, only **`to`** is mandatory. + * + * Properties include: + * + * @param {Object} config.from + * An object which specifies start values for the properties being animated. If not supplied, properties are + * animated from current settings. The actual properties which may be animated depend upon ths object being + * animated. See the sections below on Element and Component animation. + * + * @param {Object} config.to + * An object which specifies end values for the properties being animated. + * + * @param {Number} config.duration + * The duration **in milliseconds** for which the animation will run. + * + * @param {String} config.easing + * A string value describing an easing type to modify the rate of change from the default linear to non-linear. + * Values may be one of: + * + * - ease + * - easeIn + * - easeOut + * - easeInOut + * - backIn + * - backOut + * - elasticIn + * - elasticOut + * - bounceIn + * - bounceOut + * + * @param {Object} config.keyframes + * This is an object which describes the state of animated properties at certain points along the timeline. it is an + * object containing properties who's names are the percentage along the timeline being described and who's values + * specify the animation state at that point. + * + * @param {Object} config.listeners + * This is a standard {@link Ext.util.Observable#listeners listeners} configuration object which may be used to + * inject behaviour at either the `beforeanimate` event or the `afteranimate` event. + * + * @return {Object} this + */ + animate: function(animObj) { + var me = this; + if (Ext.fx.Manager.hasFxBlock(me.id)) { + return me; + } + Ext.fx.Manager.queueFx(new Ext.fx.Anim(me.anim(animObj))); + return this; + }, + + // @private - process the passed fx configuration. + anim: function(config) { + if (!Ext.isObject(config)) { + return (config) ? {} : false; + } + + var me = this; + + if (config.stopAnimation) { + me.stopAnimation(); + } + + Ext.applyIf(config, Ext.fx.Manager.getFxDefaults(me.id)); + + return Ext.apply({ + target: me, + paused: true + }, config); + }, + + /** + * Stops any running effects and clears this object's internal effects queue if it contains any additional effects + * that haven't started yet. + * @deprecated 4.0 Replaced by {@link #stopAnimation} + * @return {Ext.Element} The Element + * @method + */ + stopFx: Ext.Function.alias(Ext.util.Animate, 'stopAnimation'), + + /** + * Stops any running effects and clears this object's internal effects queue if it contains any additional effects + * that haven't started yet. + * @return {Ext.Element} The Element + */ + stopAnimation: function() { + Ext.fx.Manager.stopAnimation(this.id); + return this; + }, + + /** + * Ensures that all effects queued after syncFx is called on this object are run concurrently. This is the opposite + * of {@link #sequenceFx}. + * @return {Object} this + */ + syncFx: function() { + Ext.fx.Manager.setFxDefaults(this.id, { + concurrent: true + }); + return this; + }, + + /** + * Ensures that all effects queued after sequenceFx is called on this object are run in sequence. This is the + * opposite of {@link #syncFx}. + * @return {Object} this + */ + sequenceFx: function() { + Ext.fx.Manager.setFxDefaults(this.id, { + concurrent: false + }); + return this; + }, + + /** + * @deprecated 4.0 Replaced by {@link #getActiveAnimation} + * @inheritdoc Ext.util.Animate#getActiveAnimation + * @method + */ + hasActiveFx: Ext.Function.alias(Ext.util.Animate, 'getActiveAnimation'), + + /** + * Returns the current animation if this object has any effects actively running or queued, else returns false. + * @return {Ext.fx.Anim/Boolean} Anim if element has active effects, else false + */ + getActiveAnimation: function() { + return Ext.fx.Manager.getActiveAnimation(this.id); + } +}, function(){ + // Apply Animate mixin manually until Element is defined in the proper 4.x way + Ext.applyIf(Ext.Element.prototype, this.prototype); + // We need to call this again so the animation methods get copied over to CE + Ext.CompositeElementLite.importElementMethods(); +}); +/** + * 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. + */ +Ext.define('Ext.util.ClickRepeater', { + extend: 'Ext.util.Observable', + + /** + * Creates new ClickRepeater. + * @param {String/HTMLElement/Ext.Element} el The element or its ID to listen on + * @param {Object} [config] Config object. + */ + constructor : function(el, config){ + var me = this; + + me.el = Ext.get(el); + me.el.unselectable(); + + Ext.apply(me, config); + + me.callParent(); + + me.addEvents( + /** + * @event mousedown + * Fires when the mouse button is depressed. + * @param {Ext.util.ClickRepeater} this + * @param {Ext.EventObject} e + */ + "mousedown", + /** + * @event click + * Fires on a specified interval during the time the element is pressed. + * @param {Ext.util.ClickRepeater} this + * @param {Ext.EventObject} e + */ + "click", + /** + * @event mouseup + * Fires when the mouse key is released. + * @param {Ext.util.ClickRepeater} this + * @param {Ext.EventObject} e + */ + "mouseup" + ); + + if(!me.disabled){ + me.disabled = true; + me.enable(); + } + + // allow inline handler + if(me.handler){ + me.on("click", me.handler, me.scope || me); + } + }, + + /** + * @cfg {String/HTMLElement/Ext.Element} el + * The element to act as a button. + */ + + /** + * @cfg {String} pressedCls + * 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 {Number} interval + * The interval between firings of the "click" event (in milliseconds). + */ + interval : 20, + + /** + * @cfg {Number} delay + * The initial delay before the repeating event begins firing. + * Similar to an autorepeat key delay. + */ + delay: 250, + + /** + * @cfg {Boolean} preventDefault + * True to prevent the default click event + */ + preventDefault : true, + + /** + * @cfg {Boolean} stopDefault + * True to stop the default click event + */ + stopDefault : false, + + timer : 0, + + /** + * Enables the repeater and allows events to fire. + */ + enable: function(){ + if(this.disabled){ + this.el.on('mousedown', this.handleMouseDown, this); + if (Ext.isIE){ + this.el.on('dblclick', this.handleDblClick, this); + } + if(this.preventDefault || this.stopDefault){ + this.el.on('click', this.eventOptions, this); + } + } + this.disabled = false; + }, + + /** + * Disables the repeater and stops events from firing. + */ + disable: function(/* private */ force){ + if(force || !this.disabled){ + clearTimeout(this.timer); + if(this.pressedCls){ + this.el.removeCls(this.pressedCls); + } + Ext.getDoc().un('mouseup', this.handleMouseUp, this); + this.el.removeAllListeners(); + } + this.disabled = true; + }, + + /** + * Convenience function for setting disabled/enabled by boolean. + * @param {Boolean} disabled + */ + setDisabled: function(disabled){ + this[disabled ? 'disable' : 'enable'](); + }, + + eventOptions: function(e){ + if(this.preventDefault){ + e.preventDefault(); + } + if(this.stopDefault){ + e.stopEvent(); + } + }, + + // private + destroy : function() { + this.disable(true); + Ext.destroy(this.el); + this.clearListeners(); + }, + + handleDblClick : function(e){ + clearTimeout(this.timer); + this.el.blur(); + + this.fireEvent("mousedown", this, e); + this.fireEvent("click", this, e); + }, + + // private + handleMouseDown : function(e){ + clearTimeout(this.timer); + this.el.blur(); + if(this.pressedCls){ + this.el.addCls(this.pressedCls); + } + this.mousedownTime = new Date(); + + Ext.getDoc().on("mouseup", this.handleMouseUp, this); + this.el.on("mouseout", this.handleMouseOut, this); + + this.fireEvent("mousedown", this, e); + this.fireEvent("click", this, e); + + // Do not honor delay or interval if acceleration wanted. + if (this.accelerate) { + this.delay = 400; + } + + // Re-wrap the event object in a non-shared object, so it doesn't lose its context if + // the global shared EventObject gets a new Event put into it before the timer fires. + e = new Ext.EventObjectImpl(e); + + this.timer = Ext.defer(this.click, this.delay || this.interval, this, [e]); + }, + + // private + click : function(e){ + this.fireEvent("click", this, e); + this.timer = Ext.defer(this.click, this.accelerate ? + this.easeOutExpo(Ext.Date.getElapsed(this.mousedownTime), + 400, + -390, + 12000) : + this.interval, this, [e]); + }, + + easeOutExpo : function (t, b, c, d) { + return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b; + }, + + // private + handleMouseOut : function(){ + clearTimeout(this.timer); + if(this.pressedCls){ + this.el.removeCls(this.pressedCls); + } + this.el.on("mouseover", this.handleMouseReturn, this); + }, + + // private + handleMouseReturn : function(){ + this.el.un("mouseover", this.handleMouseReturn, this); + if(this.pressedCls){ + this.el.addCls(this.pressedCls); + } + this.click(); + }, + + // private + 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); + if(this.pressedCls){ + this.el.removeCls(this.pressedCls); + } + this.fireEvent("mouseup", this, e); + } +}); + +/** + * A subclass of Ext.dd.DragTracker which handles dragging any Component. + * + * This is configured with a Component to be made draggable, and a config object for the {@link Ext.dd.DragTracker} + * class. + * + * A {@link #delegate} may be provided which may be either the element to use as the mousedown target or a {@link + * Ext.DomQuery} selector to activate multiple mousedown targets. + * + * When the Component begins to be dragged, its `beginDrag` method will be called if implemented. + * + * When the drag ends, its `endDrag` method will be called if implemented. + */ +Ext.define('Ext.util.ComponentDragger', { + extend: 'Ext.dd.DragTracker', + + /** + * @cfg {Boolean} constrain + * Specify as `true` to constrain the Component to within the bounds of the {@link #constrainTo} region. + */ + + /** + * @cfg {String/Ext.Element} delegate + * A {@link Ext.DomQuery DomQuery} selector which identifies child elements within the Component's encapsulating + * Element which are the drag handles. This limits dragging to only begin when the matching elements are + * mousedowned. + * + * This may also be a specific child element within the Component's encapsulating element to use as the drag handle. + */ + + /** + * @cfg {Boolean} constrainDelegate + * Specify as `true` to constrain the drag handles within the {@link #constrainTo} region. + */ + + autoStart: 500, + + /** + * Creates new ComponentDragger. + * @param {Object} comp The Component to provide dragging for. + * @param {Object} [config] Config object + */ + constructor: function(comp, config) { + this.comp = comp; + this.initialConstrainTo = config.constrainTo; + this.callParent([ config ]); + }, + + onStart: function(e) { + var me = this, + comp = me.comp; + + // Cache the start [X, Y] array + this.startPosition = comp.el.getXY(); + + // If client Component has a ghost method to show a lightweight version of itself + // then use that as a drag proxy unless configured to liveDrag. + if (comp.ghost && !comp.liveDrag) { + me.proxy = comp.ghost(); + me.dragTarget = me.proxy.header.el; + } + + // Set the constrainTo Region before we start dragging. + if (me.constrain || me.constrainDelegate) { + me.constrainTo = me.calculateConstrainRegion(); + } + + if (comp.beginDrag) { + comp.beginDrag(); + } + }, + + calculateConstrainRegion: function() { + var me = this, + comp = me.comp, + c = me.initialConstrainTo, + delegateRegion, + elRegion, + shadowSize = comp.el.shadow ? comp.el.shadow.offset : 0; + + // The configured constrainTo might be a Region or an element + if (!(c instanceof Ext.util.Region)) { + c = Ext.fly(c).getViewRegion(); + } + + // Reduce the constrain region to allow for shadow + if (shadowSize) { + c.adjust(0, -shadowSize, -shadowSize, shadowSize); + } + + // If they only want to constrain the *delegate* to within the constrain region, + // adjust the region to be larger based on the insets of the delegate from the outer + // edges of the Component. + if (!me.constrainDelegate) { + delegateRegion = Ext.fly(me.dragTarget).getRegion(); + elRegion = me.proxy ? me.proxy.el.getRegion() : comp.el.getRegion(); + + c.adjust( + delegateRegion.top - elRegion.top, + delegateRegion.right - elRegion.right, + delegateRegion.bottom - elRegion.bottom, + delegateRegion.left - elRegion.left + ); + } + return c; + }, + + // Move either the ghost Component or the target Component to its new position on drag + onDrag: function(e) { + var me = this, + comp = (me.proxy && !me.comp.liveDrag) ? me.proxy : me.comp, + offset = me.getOffset(me.constrain || me.constrainDelegate ? 'dragTarget' : null); + + comp.setPagePosition(me.startPosition[0] + offset[0], me.startPosition[1] + offset[1]); + }, + + onEnd: function(e) { + var comp = this.comp; + if (this.proxy && !comp.liveDrag) { + comp.unghost(); + } + if (comp.endDrag) { + comp.endDrag(); + } + } +}); +/** + * Utility class for setting/reading values from browser cookies. + * Values can be written using the {@link #set} method. + * Values can be read using the {@link #get} method. + * A cookie can be invalidated on the client machine using the {@link #clear} method. + */ +Ext.define('Ext.util.Cookies', { + singleton: true, + + /** + * Creates 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 {Object} value The value to set for the cookie. + * @param {Object} [expires] 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] Setting a path on the cookie restricts access to pages that match that path. Defaults to all + * pages ('/'). + * @param {String} [domain] Setting a domain restricts access to pages on a given domain (typically used to allow + * cookie access across subdomains). For example, "sencha.com" will create a cookie that can be accessed from any + * subdomain of sencha.com, including www.sencha.com, support.sencha.com, etc. + * @param {Boolean} [secure] 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, + argc = arguments.length, + expires = (argc > 2) ? argv[2] : null, + path = (argc > 3) ? argv[3] : '/', + domain = (argc > 4) ? argv[4] : null, + 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 {Object} Returns the cookie value for the specified name; + * null if the cookie name does not exist. + */ + get : function(name){ + var arg = name + "=", + alen = arg.length, + clen = document.cookie.length, + i = 0, + j = 0; + + while(i < clen){ + j = i + alen; + if(document.cookie.substring(i, j) == arg){ + return this.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 + * @param {String} [path] The path for the cookie. + * This must be included if you included a path while setting the cookie. + */ + clear : function(name, path){ + if(this.get(name)){ + path = path || '/'; + document.cookie = name + '=' + '; expires=Thu, 01-Jan-70 00:00:01 GMT; path=' + path; + } + }, + + /** + * @private + */ + getCookieVal : function(offset){ + var endstr = document.cookie.indexOf(";", offset); + if(endstr == -1){ + endstr = document.cookie.length; + } + return unescape(document.cookie.substring(offset, endstr)); + } +}); + +/** + * Utility class for manipulating CSS rules + * @singleton + */ +Ext.define('Ext.util.CSS', (function() { + var rules = null, + doc = document, + camelRe = /(-[a-z])/gi, + camelFn = function(m, a){ return a.charAt(1).toUpperCase(); }; + + return { + + singleton: true, + + constructor: function() { + this.rules = {}; + this.initialized = false; + }, + + /** + * 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 {CSSStyleSheet} + */ + createStyleSheet : function(cssText, id) { + var ss, + head = doc.getElementsByTagName("head")[0], + styleEl = doc.createElement("style"); + + styleEl.setAttribute("type", "text/css"); + if (id) { + styleEl.setAttribute("id", id); + } + + if (Ext.isIE) { + head.appendChild(styleEl); + ss = styleEl.styleSheet; + ss.cssText = cssText; + } else { + try{ + styleEl.appendChild(doc.createTextNode(cssText)); + } catch(e) { + styleEl.cssText = cssText; + } + head.appendChild(styleEl); + ss = styleEl.styleSheet ? styleEl.styleSheet : (styleEl.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 = document.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) { + var doc = document, + ss; + this.removeStyleSheet(id); + 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, + selectorText, + i = ssRules.length - 1, + j, + selectors; + + for (; i >= 0; --i) { + selectorText = ssRules[i].selectorText; + if (selectorText) { + + // Split in case there are multiple, comma-delimited selectors + selectorText = selectorText.split(','); + selectors = selectorText.length; + for (j = 0; j < selectors; j++) { + rules[Ext.String.trim(selectorText[j]).toLowerCase()] = ssRules[i]; + } + } + } + } 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, + i = 0, + len = ds.length; + + for (; i < len; i++) { + try { + if (!ds[i].disabled) { + this.cacheStyleSheet(ds[i]); + } + } catch(e) {} + } + } + return rules; + }, + + /** + * Gets an an individual CSS rule by selector(s) + * @param {String/String[]} 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 {CSSStyleRule} The CSS rule or null if one is not found + */ + getRule: function(selector, refreshCache) { + var rs = this.getRules(refreshCache), + i; + if (!Ext.isArray(selector)) { + return rs[selector.toLowerCase()]; + } + for (i = 0; i < selector.length; i++) { + if (rs[selector[i]]) { + return rs[selector[i].toLowerCase()]; + } + } + return null; + }, + + /** + * Updates a rule property + * @param {String/String[]} 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){ + var rule, i; + if (!Ext.isArray(selector)) { + rule = this.getRule(selector); + if (rule) { + rule.style[property.replace(camelRe, camelFn)] = value; + return true; + } + } else { + for (i = 0; i < selector.length; i++) { + if (this.updateRule(selector[i], property, value)) { + return true; + } + } + } + return false; + } + }; +}())); +/** + * A mixin to add floating capability to a Component. + */ +Ext.define('Ext.util.Floating', { + + uses: ['Ext.Layer', 'Ext.window.Window'], + + /** + * @cfg {Boolean} focusOnToFront + * Specifies whether the floated component should be automatically {@link Ext.Component#method-focus focused} when + * it is {@link #toFront brought to the front}. + */ + focusOnToFront: true, + + /** + * @cfg {String/Boolean} shadow + * Specifies whether the floating component should be given a shadow. Set to true to automatically create an + * {@link Ext.Shadow}, or a string indicating the shadow's display {@link Ext.Shadow#mode}. Set to false to + * disable the shadow. + */ + shadow: 'sides', + + /** + * @cfg {String/Boolean} shadowOffset + * Number of pixels to offset the shadow. + */ + + constructor: function (dom) { + var me = this; + + me.el = new Ext.Layer(Ext.apply({ + hideMode : me.hideMode, + hidden : me.hidden, + shadow : (typeof me.shadow != 'undefined') ? me.shadow : 'sides', + shadowOffset : me.shadowOffset, + constrain : false, + shim : (me.shim === false) ? false : undefined + }, me.floating), dom); + + // release config object (if it was one) + me.floating = true; + + // Register with the configured ownerCt. + // With this we acquire a floatParent for relative positioning, and a zIndexParent which is an + // ancestor floater which provides zIndex management. + me.registerWithOwnerCt(); + }, + + registerWithOwnerCt: function() { + var me = this; + + if (me.zIndexParent) { + me.zIndexParent.unregisterFloatingItem(me); + } + + // Acquire a zIndexParent by traversing the ownerCt axis for the nearest floating ancestor + me.zIndexParent = me.up('[floating]'); + me.setFloatParent(me.ownerCt); + delete me.ownerCt; + + if (me.zIndexParent) { + me.zIndexParent.registerFloatingItem(me); + } else { + Ext.WindowManager.register(me); + } + }, + + setFloatParent: function(floatParent) { + var me = this; + + // Remove listeners from previous floatParent + if (me.floatParent) { + me.mun(me.floatParent, { + hide: me.onFloatParentHide, + show: me.onFloatParentShow, + scope: me + }); + } + + me.floatParent = floatParent; + + // Floating Components as children of Containers must hide when their parent hides. + if (floatParent) { + me.mon(me.floatParent, { + hide: me.onFloatParentHide, + show: me.onFloatParentShow, + scope: me + }); + } + + // If a floating Component is configured to be constrained, but has no configured + // constrainTo setting, set its constrainTo to be it's ownerCt before rendering. + if ((me.constrain || me.constrainHeader) && !me.constrainTo) { + me.constrainTo = floatParent ? floatParent.getTargetEl() : me.container; + } + }, + + onAfterFloatLayout: function(){ + this.syncShadow(); + }, + + onFloatParentHide: function() { + var me = this; + + if (me.hideOnParentHide !== false && me.isVisible()) { + me.hide(); + me.showOnParentShow = true; + } + }, + + onFloatParentShow: function() { + if (this.showOnParentShow) { + delete this.showOnParentShow; + this.show(); + } + }, + + // private + // z-index is managed by the zIndexManager and may be overwritten at any time. + // Returns the next z-index to be used. + // If this is a Container, then it will have rebased any managed floating Components, + // and so the next available z-index will be approximately 10000 above that. + setZIndex: function(index) { + var me = this; + + me.el.setZIndex(index); + + // Next item goes 10 above; + index += 10; + + // When a Container with floating items has its z-index set, it rebases any floating items it is managing. + // The returned value is a round number approximately 10000 above the last z-index used. + if (me.floatingItems) { + index = Math.floor(me.floatingItems.setBase(index) / 100) * 100 + 10000; + } + return index; + }, + + /** + * Moves this floating Component into a constrain region. + * + * By default, this Component is constrained to be within the container it was added to, or the element it was + * rendered to. + * + * An alternative constraint may be passed. + * @param {String/HTMLElement/Ext.Element/Ext.util.Region} [constrainTo] The Element or {@link Ext.util.Region Region} + * into which this Component is to be constrained. Defaults to the element into which this floating Component + * was rendered. + */ + doConstrain: function(constrainTo) { + var me = this, + + // Calculate the constrain vector to coerce our position to within our + // constrainTo setting. getConstrainVector will provide a default constraint + // region if there is no explicit constrainTo, *and* there is no floatParent owner Component. + vector = me.getConstrainVector(constrainTo), + xy; + + if (vector) { + xy = me.getPosition(); + xy[0] += vector[0]; + xy[1] += vector[1]; + me.setPosition(xy); + } + }, + + + /** + * Gets the x/y offsets to constrain this float + * @private + * @param {String/HTMLElement/Ext.Element/Ext.util.Region} [constrainTo] The Element or {@link Ext.util.Region Region} + * into which this Component is to be constrained. + * @return {Number[]} The x/y constraints + */ + getConstrainVector: function(constrainTo){ + var me = this; + + if (me.constrain || me.constrainHeader) { + constrainTo = constrainTo || (me.floatParent && me.floatParent.getTargetEl()) || me.container || me.el.getScopeParent(); + return (me.constrainHeader ? me.header.el : me.el).getConstrainVector(constrainTo); + } + }, + + /** + * Aligns this floating Component to the specified element + * + * @param {Ext.Component/Ext.Element/HTMLElement/String} element + * The element or {@link Ext.Component} to align to. If passing a component, it must be a + * component instance. If a string id is passed, it will be used as an element id. + * @param {String} [position="tl-bl?"] The position to align to + * (see {@link Ext.Element#alignTo} for more details). + * @param {Number[]} [offsets] Offset the positioning by [x, y] + * @return {Ext.Component} this + */ + alignTo: function(element, position, offsets) { + + // element may be a Component, so first attempt to use its el to align to. + // When aligning to an Element's X,Y position, we must use setPagePosition which disregards any floatParent + this.setPagePosition(this.el.getAlignToXY(element.el || element, position, offsets)); + return this; + }, + + /** + * Brings this floating Component to the front of any other visible, floating Components managed by the same + * {@link Ext.ZIndexManager ZIndexManager} + * + * If this Component is modal, inserts the modal mask just below this Component in the z-index stack. + * + * @param {Boolean} [preventFocus=false] Specify `true` to prevent the Component from being focused. + * @return {Ext.Component} this + */ + toFront: function(preventFocus) { + var me = this; + + // Find the floating Component which provides the base for this Component's zIndexing. + // That must move to front to then be able to rebase its zIndex stack and move this to the front + if (me.zIndexParent && me.bringParentToFront !== false) { + me.zIndexParent.toFront(true); + } + + if (!Ext.isDefined(preventFocus)) { + preventFocus = !me.focusOnToFront; + } + + if (preventFocus) { + me.preventFocusOnActivate = true; + } + if (me.zIndexManager.bringToFront(me)) { + if (!preventFocus) { + // Kick off a delayed focus request. + // If another floating Component is toFronted before the delay expires + // this will not receive focus. + me.focus(false, true); + } + } + delete me.preventFocusOnActivate; + return me; + }, + + /** + * This method is called internally by {@link Ext.ZIndexManager} to signal that a floating Component has either been + * moved to the top of its zIndex stack, or pushed from the top of its zIndex stack. + * + * If a _Window_ is superceded by another Window, deactivating it hides its shadow. + * + * This method also fires the {@link Ext.Component#activate activate} or + * {@link Ext.Component#deactivate deactivate} event depending on which action occurred. + * + * @param {Boolean} [active=false] True to activate the Component, false to deactivate it. + * @param {Ext.Component} [newActive] The newly active Component which is taking over topmost zIndex position. + */ + setActive: function(active, newActive) { + var me = this; + + if (active) { + if (me.el.shadow && !me.maximized) { + me.el.enableShadow(true); + } + if (me.modal && !me.preventFocusOnActivate) { + me.focus(false, true); + } + me.fireEvent('activate', me); + } else { + // Only the *Windows* in a zIndex stack share a shadow. All other types of floaters + // can keep their shadows all the time + if (me.isWindow && (newActive && newActive.isWindow)) { + me.el.disableShadow(); + } + me.fireEvent('deactivate', me); + } + }, + + /** + * Sends this Component to the back of (lower z-index than) any other visible windows + * @return {Ext.Component} this + */ + toBack: function() { + this.zIndexManager.sendToBack(this); + return this; + }, + + /** + * Center this Component in its container. + * @return {Ext.Component} this + */ + center: function() { + var me = this, + xy; + + if (me.isVisible()) { + xy = me.el.getAlignToXY(me.container, 'c-c'); + me.setPagePosition(xy); + } else { + me.needsCenter = true; + } + return me; + }, + + onFloatShow: function(){ + if (this.needsCenter) { + this.center(); + } + delete this.needsCenter; + }, + + // private + syncShadow : function(){ + if (this.floating) { + this.el.sync(true); + } + }, + + // private + fitContainer: function() { + var parent = this.floatParent, + container = parent ? parent.getTargetEl() : this.container, + size = container.getViewSize(false); + + this.setSize(size); + } +}); + +/** + * History management component that allows you to register arbitrary tokens that signify application + * history state on navigation actions. You can then handle the history {@link #change} event in order + * to reset your application UI to the appropriate state when the user navigates forward or backward through + * the browser history stack. + * + * ## Initializing + * + * The {@link #init} method of the History object must be called before using History. This sets up the internal + * state and must be the first thing called before using History. + */ +Ext.define('Ext.util.History', { + singleton: true, + alternateClassName: 'Ext.History', + mixins: { + observable: 'Ext.util.Observable' + }, + + /** + * @cfg {Boolean} useTopWindow + * True to use `window.top.location.hash` or false to use `window.location.hash`. + */ + useTopWindow: true, + + /** + * @property + * The id of the hidden field required for storing the current history token. + */ + fieldId: Ext.baseCSSPrefix + 'history-field', + /** + * @property + * The id of the iframe required by IE to manage the history stack. + */ + iframeId: Ext.baseCSSPrefix + 'history-frame', + + constructor: function() { + var me = this; + me.oldIEMode = Ext.isIE6 || Ext.isIE7 || !Ext.isStrict && Ext.isIE8; + me.iframe = null; + me.hiddenField = null; + me.ready = false; + me.currentToken = null; + me.mixins.observable.constructor.call(me); + }, + + getHash: function() { + var href = window.location.href, + i = href.indexOf("#"); + + return i >= 0 ? href.substr(i + 1) : null; + }, + + setHash: function (hash) { + var me = this, + win = me.useTopWindow ? window.top : window; + try { + win.location.hash = hash; + } catch (e) { + // IE can give Access Denied (esp. in popup windows) + } + }, + + doSave: function() { + this.hiddenField.value = this.currentToken; + }, + + + handleStateChange: function(token) { + this.currentToken = token; + this.fireEvent('change', token); + }, + + updateIFrame: function(token) { + var html = '
    ' + + Ext.util.Format.htmlEncode(token) + + '
    ', + doc; + + try { + doc = this.iframe.contentWindow.document; + doc.open(); + doc.write(html); + doc.close(); + return true; + } catch (e) { + return false; + } + }, + + checkIFrame: function () { + var me = this, + contentWindow = me.iframe.contentWindow, + doc, elem, oldToken, oldHash; + + if (!contentWindow || !contentWindow.document) { + Ext.Function.defer(this.checkIFrame, 10, this); + return; + } + + doc = contentWindow.document; + elem = doc.getElementById("state"); + oldToken = elem ? elem.innerText : null; + oldHash = me.getHash(); + + Ext.TaskManager.start({ + run: function () { + var doc = contentWindow.document, + elem = doc.getElementById("state"), + newToken = elem ? elem.innerText : null, + newHash = me.getHash(); + + if (newToken !== oldToken) { + oldToken = newToken; + me.handleStateChange(newToken); + me.setHash(newToken); + oldHash = newToken; + me.doSave(); + } else if (newHash !== oldHash) { + oldHash = newHash; + me.updateIFrame(newHash); + } + }, + interval: 50, + scope: me + }); + me.ready = true; + me.fireEvent('ready', me); + }, + + startUp: function () { + var me = this, + hash; + + me.currentToken = me.hiddenField.value || this.getHash(); + + if (me.oldIEMode) { + me.checkIFrame(); + } else { + hash = me.getHash(); + Ext.TaskManager.start({ + run: function () { + var newHash = me.getHash(); + if (newHash !== hash) { + hash = newHash; + me.handleStateChange(hash); + me.doSave(); + } + }, + interval: 50, + scope: me + }); + me.ready = true; + me.fireEvent('ready', me); + } + + }, + + /** + * Initializes the global History instance. + * @param {Function} [onReady] A callback function that will be called once the history + * component is fully initialized. + * @param {Object} [scope] The scope (`this` reference) in which the callback is executed. + * Defaults to the browser window. + */ + init: function (onReady, scope) { + var me = this, + DomHelper = Ext.DomHelper; + + if (me.ready) { + Ext.callback(onReady, scope, [me]); + return; + } + + if (!Ext.isReady) { + Ext.onReady(function() { + me.init(onReady, scope); + }); + return; + } + + /* +
    + + +
    + */ + me.hiddenField = Ext.getDom(me.fieldId); + if (!me.hiddenField) { + me.hiddenField = Ext.getBody().createChild({ + id: Ext.id(), + tag: 'form', + cls: Ext.baseCSSPrefix + 'hide-display', + children: [{ + tag: 'input', + type: 'hidden', + id: me.fieldId + }] + }, false, true).firstChild; + } + + if (me.oldIEMode) { + me.iframe = Ext.getDom(me.iframeId); + if (!me.iframe) { + me.iframe = DomHelper.append(me.hiddenField.parentNode, { + tag: 'iframe', + id: me.iframeId + }); + } + } + + me.addEvents( + /** + * @event ready + * Fires when the Ext.util.History singleton has been initialized and is ready for use. + * @param {Ext.util.History} The Ext.util.History singleton. + */ + 'ready', + /** + * @event change + * Fires when navigation back or forwards within the local page's history occurs. + * @param {String} token An identifier associated with the page state at that point in its history. + */ + 'change' + ); + + if (onReady) { + me.on('ready', onReady, scope, {single: true}); + } + me.startUp(); + }, + + /** + * Add a new token to the history stack. This can be any arbitrary value, although it would + * commonly be the concatenation of a component id and another id marking the specific history + * state of that component. Example usage: + * + * // Handle tab changes on a TabPanel + * tabPanel.on('tabchange', function(tabPanel, tab){ + * Ext.History.add(tabPanel.id + ':' + tab.id); + * }); + * + * @param {String} token The value that defines a particular application-specific history state + * @param {Boolean} [preventDuplicates=true] When true, if the passed token matches the current token + * it will not save a new history step. Set to false if the same state can be saved more than once + * at the same history stack location. + */ + add: function (token, preventDup) { + var me = this; + + if (preventDup !== false) { + if (me.getToken() === token) { + return true; + } + } + + if (me.oldIEMode) { + return me.updateIFrame(token); + } else { + me.setHash(token); + return true; + } + }, + + /** + * Programmatically steps back one step in browser history (equivalent to the user pressing the Back button). + */ + back: function() { + window.history.go(-1); + }, + + /** + * Programmatically steps forward one step in browser history (equivalent to the user pressing the Forward button). + */ + forward: function(){ + window.history.go(1); + }, + + /** + * Retrieves the currently-active history token. + * @return {String} The token + */ + getToken: function() { + return this.ready ? this.currentToken : this.getHash(); + } +}); +/** + * Handles mapping key events to handling functions for an element or a Component. One KeyMap can be used for multiple + * actions. + * + * A KeyMap must be configured with a {@link #target} as an event source which may be an Element or a Component. + * + * If the target is an element, then the `keydown` event will trigger the invocation of {@link #binding}s. + * + * It is possible to configure the KeyMap with a custom {@link #eventName} to listen for. This may be useful when the + * {@link #target} is a Component. + * + * The KeyMap's event handling requires that the first parameter passed is a key event. So if the Component's event + * signature is different, specify a {@link #processEvent} configuration which accepts the event's parameters and + * returns a key event. + * + * Functions specified in {@link #binding}s are called with this signature : `(String key, Ext.EventObject e)` (if the + * match is a multi-key combination the callback will still be called only once). A KeyMap can also handle a string + * representation of keys. By default KeyMap starts enabled. + * + * Usage: + * + * // map one key by key code + * var map = new Ext.util.KeyMap({ + * target: "my-element", + * key: 13, // or Ext.EventObject.ENTER + * fn: myHandler, + * scope: myObject + * }); + * + * // map multiple keys to one action by string + * var map = new Ext.util.KeyMap({ + * target: "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.util.KeyMap({ + * target: "my-element", + * binding: [{ + * 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.'); } + * }] + * }); + * + * Since 4.1.0, KeyMaps can bind to Components and process key-based events fired by Components. + * + * To bind to a Component, use the single parameter form of constructor: + * + * var map = new Ext.util.KeyMap({ + * target: myGridView, + * eventName: 'itemkeydown', + * processEvent: function(view, record, node, index, event) { + * + * // Load the event with the extra information needed by the mappings + * event.view = view; + * event.store = view.getStore(); + * event.record = record; + * event.index = index; + * return event; + * }, + * binding: { + * key: Ext.EventObject.DELETE, + * fn: function(keyCode, e) { + * e.store.remove(e.record); + * + * // Attempt to select the record that's now in its place + * e.view.getSelectionModel().select(e,index); + * e.view.el.focus(); + * } + * } + * }); + */ +Ext.define('Ext.util.KeyMap', { + alternateClassName: 'Ext.KeyMap', + + /** + * @cfg {Ext.Component/Ext.Element/HTMLElement/String} target + * The object on which to listen for the event specified by the {@link #eventName} config option. + */ + + /** + * @cfg {Object/Object[][]} binding + * Either a single object describing a handling function for s specified key (or set of keys), or + * an array of such objects. + * @cfg {String/String[]} binding.key A single keycode or an array of keycodes to handle + * @cfg {Boolean} binding.shift True to handle key only when shift is pressed, False to handle the + * key only when shift is not pressed (defaults to undefined) + * @cfg {Boolean} binding.ctrl True to handle key only when ctrl is pressed, False to handle the + * key only when ctrl is not pressed (defaults to undefined) + * @cfg {Boolean} binding.alt True to handle key only when alt is pressed, False to handle the key + * only when alt is not pressed (defaults to undefined) + * @cfg {Function} binding.handler The function to call when KeyMap finds the expected key combination + * @cfg {Function} binding.fn Alias of handler (for backwards-compatibility) + * @cfg {Object} binding.scope The scope of the callback function + * @cfg {String} binding.defaultEventAction A default action to apply to the event. Possible values + * are: stopEvent, stopPropagation, preventDefault. If no value is set no action is performed. + */ + + /** + * @cfg {Object} [processEventScope=this] + * The scope (`this` context) in which the {@link #processEvent} method is executed. + */ + + /** + * @cfg {String} eventName + * The event to listen for to pick up key events. + */ + eventName: 'keydown', + + constructor: function(config) { + var me = this; + + // Handle legacy arg list in which the first argument is the target. + // TODO: Deprecate in V5 + if ((arguments.length !== 1) || (typeof config === 'string') || config.dom || config.tagName || config === document || config.isComponent) { + me.legacyConstructor.apply(me, arguments); + return; + } + + Ext.apply(me, config); + me.bindings = []; + + if (!me.target.isComponent) { + me.target = Ext.get(me.target); + } + + if (me.binding) { + me.addBinding(me.binding); + } else if (config.key) { + me.addBinding(config); + } + me.enable(); + }, + + /** + * @private + * Old constructor signature + * @param {String/HTMLElement/Ext.Element/Ext.Component} el The element or its ID, or Component to bind to + * @param {Object} binding The binding (see {@link #addBinding}) + * @param {String} [eventName="keydown"] The event to bind to + */ + legacyConstructor: function(el, binding, eventName){ + var me = this; + + Ext.apply(me, { + target: Ext.get(el), + eventName: eventName || me.eventName, + bindings: [] + }); + if (binding) { + me.addBinding(binding); + } + me.enable(); + }, + + /** + * Add a new binding to this KeyMap. + * + * Usage: + * + * // Create a KeyMap + * var map = new Ext.util.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/Object[]} binding A single KeyMap config or an array of configs. + * The following config object properties are supported: + * @param {String/Array} binding.key A single keycode or an array of keycodes to handle. + * @param {Boolean} binding.shift True to handle key only when shift is pressed, + * False to handle the keyonly when shift is not pressed (defaults to undefined). + * @param {Boolean} binding.ctrl True to handle key only when ctrl is pressed, + * False to handle the key only when ctrl is not pressed (defaults to undefined). + * @param {Boolean} binding.alt True to handle key only when alt is pressed, + * False to handle the key only when alt is not pressed (defaults to undefined). + * @param {Function} binding.handler The function to call when KeyMap finds the + * expected key combination. + * @param {Function} binding.fn Alias of handler (for backwards-compatibility). + * @param {Object} binding.scope The scope of the callback function. + * @param {String} binding.defaultEventAction A default action to apply to the event. + * Possible values are: stopEvent, stopPropagation, preventDefault. If no value is + * set no action is performed.. + */ + addBinding : function(binding){ + var keyCode = binding.key, + processed = false, + key, + keys, + keyString, + i, + len; + + if (Ext.isArray(binding)) { + for (i = 0, len = binding.length; i < len; i++) { + this.addBinding(binding[i]); + } + return; + } + + if (Ext.isString(keyCode)) { + keys = []; + keyString = keyCode.toUpperCase(); + + for (i = 0, len = keyString.length; i < len; ++i){ + keys.push(keyString.charCodeAt(i)); + } + keyCode = keys; + processed = true; + } + + if (!Ext.isArray(keyCode)) { + keyCode = [keyCode]; + } + + if (!processed) { + for (i = 0, len = keyCode.length; i < len; ++i) { + key = keyCode[i]; + if (Ext.isString(key)) { + keyCode[i] = key.toUpperCase().charCodeAt(0); + } + } + } + + this.bindings.push(Ext.apply({ + keyCode: keyCode + }, binding)); + }, + + /** + * Process any keydown events on the element + * @private + * @param {Ext.EventObject} event + */ + handleKeyDown: function(event) { + var me = this, + bindings, i, len; + + if (this.enabled) { //just in case + bindings = this.bindings; + i = 0; + len = bindings.length; + + // Process the event + event = me.processEvent.apply(me||me.processEventScope, arguments); + + // If the processor does not return a keyEvent, we can't process it. + // Allow them to return false to cancel processing of the event + if (!event.getKey) { + return event; + } + for(; i < len; ++i){ + this.processBinding(bindings[i], event); + } + } + }, + + /** + * @cfg {Function} processEvent + * An optional event processor function which accepts the argument list provided by the + * {@link #eventName configured event} of the {@link #target}, and returns a keyEvent for processing by the KeyMap. + * + * This may be useful when the {@link #target} is a Component with s complex event signature. Extra information from + * the event arguments may be injected into the event for use by the handler functions before returning it. + */ + processEvent: function(event){ + return event; + }, + + /** + * Process a particular binding and fire the handler if necessary. + * @private + * @param {Object} binding The binding information + * @param {Ext.EventObject} event + */ + processBinding: function(binding, event){ + if (this.checkModifiers(binding, event)) { + var key = event.getKey(), + handler = binding.fn || binding.handler, + scope = binding.scope || this, + keyCode = binding.keyCode, + defaultEventAction = binding.defaultEventAction, + i, + len, + keydownEvent = new Ext.EventObjectImpl(event); + + + for (i = 0, len = keyCode.length; i < len; ++i) { + if (key === keyCode[i]) { + if (handler.call(scope, key, event) !== true && defaultEventAction) { + keydownEvent[defaultEventAction](); + } + break; + } + } + } + }, + + /** + * Check if the modifiers on the event match those on the binding + * @private + * @param {Object} binding + * @param {Ext.EventObject} event + * @return {Boolean} True if the event matches the binding + */ + checkModifiers: function(binding, e) { + var keys = ['shift', 'ctrl', 'alt'], + i = 0, + len = keys.length, + val, key; + + for (; i < len; ++i){ + key = keys[i]; + val = binding[key]; + if (!(val === undefined || (val === e[key + 'Key']))) { + return false; + } + } + return true; + }, + + /** + * Shorthand for adding a single key listener. + * + * @param {Number/Number[]/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] The scope (`this` reference) in which the function is executed. + * Defaults to the browser window. + */ + on: function(key, fn, scope) { + var keyCode, shift, ctrl, alt; + if (Ext.isObject(key) && !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 + }); + }, + + /** + * Returns true if this KeyMap is enabled + * @return {Boolean} + */ + isEnabled : function() { + return this.enabled; + }, + + /** + * Enables this KeyMap + */ + enable: function() { + var me = this; + + if (!me.enabled) { + me.target.on(me.eventName, me.handleKeyDown, me); + me.enabled = true; + } + }, + + /** + * Disable this KeyMap + */ + disable: function() { + var me = this; + + if (me.enabled) { + me.target.removeListener(me.eventName, me.handleKeyDown, me); + me.enabled = false; + } + }, + + /** + * Convenience function for setting disabled/enabled by boolean. + * @param {Boolean} disabled + */ + setDisabled : function(disabled) { + if (disabled) { + this.disable(); + } else { + this.enable(); + } + }, + + /** + * Destroys the KeyMap instance and removes all handlers. + * @param {Boolean} removeTarget True to also remove the {@link #target} + */ + destroy: function(removeTarget) { + var me = this; + + me.bindings = []; + me.disable(); + if (removeTarget === true) { + me.target.isComponent ? me.target.destroy() : me.target.remove(); + } + delete me.target; + } +}); +/** + * 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, space, left, right, up, down, tab, esc, + * pageUp, pageDown, del, backspace, home, end. + * + * Usage: + * + * var nav = new Ext.util.KeyNav({ + * target : "my-element", + * left : function(e){ + * this.moveLeft(e.ctrlKey); + * }, + * right : function(e){ + * this.moveRight(e.ctrlKey); + * }, + * enter : function(e){ + * this.save(); + * }, + * + * // Binding may be a function specifiying fn, scope and defaultAction + * esc: { + * fn: this.onEsc, + * defaultEventAction: false + * }, + * scope : this + * }); + */ +Ext.define('Ext.util.KeyNav', { + alternateClassName: 'Ext.KeyNav', + + requires: ['Ext.util.KeyMap'], + + statics: { + keyOptions: { + left: 37, + right: 39, + up: 38, + down: 40, + space: 32, + pageUp: 33, + pageDown: 34, + del: 46, + backspace: 8, + home: 36, + end: 35, + enter: 13, + esc: 27, + tab: 9 + } + }, + + constructor: function(config) { + var me = this; + if (arguments.length === 2) { + me.legacyConstructor.apply(me, arguments); + return; + } + me.setConfig(config); + }, + + /** + * @private + * Old constructor signature. + * @param {String/HTMLElement/Ext.Element} el The element or its ID to bind to + * @param {Object} config The config + */ + legacyConstructor: function(el, config) { + this.setConfig(Ext.apply({ + target: el + }, config)); + }, + + /** + * Sets up a configuration for the KeyNav. + * @private + * @param {String/HTMLElement/Ext.Element} el The element or its ID to bind to + * @param {Object} config A configuration object as specified in the constructor. + */ + setConfig: function(config) { + var me = this, + keymapCfg = { + target: config.target, + eventName: me.getKeyEvent('forceKeyDown' in config ? config.forceKeyDown : me.forceKeyDown, config.eventName) + }, + map, keyCodes, defaultScope, keyName, binding; + + if (me.map) { + me.map.destroy(); + } + + if (config.processEvent) { + keymapCfg.processEvent = config.processEvent; + keymapCfg.processEventScope = config.processEventScope||me; + } + map = me.map = new Ext.util.KeyMap(keymapCfg); + keyCodes = Ext.util.KeyNav.keyOptions; + defaultScope = config.scope || me; + + for (keyName in keyCodes) { + if (keyCodes.hasOwnProperty(keyName)) { + + // There is a property named after a key name. + // It may be a function or an binding spec containing handler, scope and defaultAction configs + if (binding = config[keyName]) { + if (typeof binding === 'function') { + binding = { + handler: binding, + defaultAction: (config.defaultEventAction !== undefined) ? config.defaultEventAction : me.defaultEventAction + }; + } + map.addBinding({ + key: keyCodes[keyName], + handler: Ext.Function.bind(me.handleEvent, binding.scope||defaultScope, binding.handler||binding.fn, true), + defaultEventAction: (binding.defaultEventAction !== undefined) ? binding.defaultAction : me.defaultEventAction + }); + } + } + } + + map.disable(); + if (!config.disabled) { + map.enable(); + } + }, + + /** + * Method for filtering out the map argument + * @private + * @param {Number} keyCode + * @param {Ext.EventObject} event + * @param {Object} options Contains the handler to call + */ + handleEvent: function(keyCode, event, handler){ + return handler.call(this, event); + }, + + /** + * @cfg {Boolean} disabled + * True to disable this KeyNav instance. + */ + 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}. + * + * If a falsy value is specified, no method is called on the key event. + */ + defaultEventAction: "stopEvent", + + /** + * @cfg {Boolean} forceKeyDown + * Handle the keydown event instead of keypress. 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, + + /** + * @cfg {Ext.Component/Ext.Element/HTMLElement/String} target + * The object on which to listen for the event specified by the {@link #eventName} config option. + */ + + /** + * @cfg {String} eventName + * The event to listen for to pick up key events. + */ + eventName: 'keypress', + + /** + * @cfg {Function} processEvent + * An optional event processor function which accepts the argument list provided by the {@link #eventName configured + * event} of the {@link #target}, and returns a keyEvent for processing by the KeyMap. + * + * This may be useful when the {@link #target} is a Component with s complex event signature. Extra information from + * the event arguments may be injected into the event for use by the handler functions before returning it. + */ + + /** + * @cfg {Object} [processEventScope=this] + * The scope (`this` context) in which the {@link #processEvent} method is executed. + */ + + /** + * Destroy this KeyNav (this is the same as calling disable). + * @param {Boolean} removeEl True to remove the element associated with this KeyNav. + */ + destroy: function(removeEl){ + this.map.destroy(removeEl); + delete this.map; + }, + + /** + * Enables this KeyNav. + */ + enable: function() { + this.map.enable(); + this.disabled = false; + }, + + /** + * Disables this KeyNav. + */ + disable: function() { + this.map.disable(); + this.disabled = true; + }, + + /** + * Convenience function for setting disabled/enabled by boolean. + * @param {Boolean} disabled + */ + setDisabled : function(disabled){ + this.map.setDisabled(disabled); + this.disabled = disabled; + }, + + /** + * @private + * Determines the event to bind to listen for keys. Defaults to the {@link #eventName} value, but + * may be overridden the {@link #forceKeyDown} setting. + * + * The useKeyDown option on the EventManager modifies the default {@link #eventName} to be `keydown`, + * but a configured {@link #eventName} takes priority over this. + * + * @return {String} The type of event to listen for. + */ + getKeyEvent: function(forceKeyDown, configuredEventName){ + if (forceKeyDown || (Ext.EventManager.useKeyDown && !configuredEventName)) { + return 'keydown'; + } else { + return configuredEventName||this.eventName; + } + } +}); +/** + * 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. + * + * The measurement works by copying the relevant CSS styles that can affect the font related display, + * then checking the size of an element that is auto-sized. Note that if the text is multi-lined, you must + * provide a **fixed width** when doing the measurement. + * + * If multiple measurements are being done on the same element, you create a new instance to initialize + * to avoid the overhead of copying the styles to the element repeatedly. + */ +Ext.define('Ext.util.TextMetrics', { + statics: { + shared: null, + /** + * 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)}` + * @static + */ + measure: function(el, text, fixedWidth){ + var me = this, + shared = me.shared; + + if(!shared){ + shared = me.shared = new me(el, fixedWidth); + } + shared.bind(el); + shared.setFixedWidth(fixedWidth || 'auto'); + return shared.getSize(text); + }, + + /** + * Destroy the TextMetrics instance created by {@link #measure}. + * @static + */ + destroy: function(){ + var me = this; + Ext.destroy(me.shared); + me.shared = null; + } + }, + + /** + * Creates new TextMetrics. + * @param {String/HTMLElement/Ext.Element} bindTo The element or its ID to bind to. + * @param {Number} [fixedWidth] A fixed width to apply to the measuring element. + */ + constructor: function(bindTo, fixedWidth){ + var measure = this.measure = Ext.getBody().createChild({ + cls: Ext.baseCSSPrefix + 'textmetrics' + }); + this.el = Ext.get(bindTo); + + measure.position('absolute'); + measure.setLeftTop(-1000, -1000); + measure.hide(); + + if (fixedWidth) { + measure.setWidth(fixedWidth); + } + }, + + /** + * 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){ + var measure = this.measure, + size; + + measure.update(text); + size = measure.getSize(); + measure.update(''); + return size; + }, + + /** + * Binds this TextMetrics instance to a new element + * @param {String/HTMLElement/Ext.Element} el The element or its ID. + */ + bind: function(el){ + var me = this; + + me.el = Ext.get(el); + me.measure.setStyle( + me.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){ + this.measure.setWidth(width); + }, + + /** + * 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){ + this.measure.dom.style.width = 'auto'; + return this.getSize(text).width; + }, + + /** + * Returns the measured height of the specified text + * @param {String} text The text to measure + * @return {Number} height The height in pixels + */ + getHeight : function(text){ + return this.getSize(text).height; + }, + + /** + * Destroy this instance + */ + destroy: function(){ + var me = this; + me.measure.remove(); + delete me.el; + delete me.measure; + } +}, function(){ + 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] The minumum value to return. + * @param {Number} [max] The maximum value to return. + * @return {Number} The text width in pixels. + * @member Ext.dom.Element + */ + getTextWidth : function(text, min, max){ + return Ext.Number.constrain(Ext.util.TextMetrics.measure(this.dom, Ext.value(text, this.dom.innerHTML, true)).width, min || 0, max || 1000000); + } + }); +}); + +/** + * A class used to load remote content to an Element. Sample usage: + * + * Ext.get('el').load({ + * url: 'myPage.php', + * scripts: true, + * params: { + * id: 1 + * } + * }); + * + * In general this class will not be instanced directly, rather the {@link Ext.Element#method-load} method + * will be used. + */ +Ext.define('Ext.ElementLoader', { + + /* Begin Definitions */ + + mixins: { + observable: 'Ext.util.Observable' + }, + + uses: [ + 'Ext.data.Connection', + 'Ext.Ajax' + ], + + statics: { + Renderer: { + Html: function(loader, response, active){ + loader.getTarget().update(response.responseText, active.scripts === true); + return true; + } + } + }, + + /* End Definitions */ + + /** + * @cfg {String} url + * The url to retrieve the content from. + */ + url: null, + + /** + * @cfg {Object} params + * Any params to be attached to the Ajax request. These parameters will + * be overridden by any params in the load options. + */ + params: null, + + /** + * @cfg {Object} baseParams Params that will be attached to every request. These parameters + * will not be overridden by any params in the load options. + */ + baseParams: null, + + /** + * @cfg {Boolean/Object} autoLoad + * True to have the loader make a request as soon as it is created. + * This argument can also be a set of options that will be passed to {@link #method-load} is called. + */ + autoLoad: false, + + /** + * @cfg {HTMLElement/Ext.Element/String} target + * The target element for the loader. It can be the DOM element, the id or an {@link Ext.Element}. + */ + target: null, + + /** + * @cfg {Boolean/String} loadMask + * True or a string to show when the element is loading. + */ + loadMask: false, + + /** + * @cfg {Object} ajaxOptions + * Any additional options to be passed to the request, for example timeout or headers. + */ + ajaxOptions: null, + + /** + * @cfg {Boolean} scripts + * True to parse any inline script tags in the response. + */ + scripts: false, + + /** + * @cfg {Function} success + * A function to be called when a load request is successful. + * Will be called with the following config parameters: + * + * - this - The ElementLoader instance. + * - response - The response object. + * - options - Ajax options. + */ + + /** + * @cfg {Function} failure A function to be called when a load request fails. + * Will be called with the following config parameters: + * + * - this - The ElementLoader instance. + * - response - The response object. + * - options - Ajax options. + */ + + /** + * @cfg {Function} callback A function to be called when a load request finishes. + * Will be called with the following config parameters: + * + * - this - The ElementLoader instance. + * - success - True if successful request. + * - response - The response object. + * - options - Ajax options. + */ + + /** + * @cfg {Object} scope + * The scope to execute the {@link #success} and {@link #failure} functions in. + */ + + /** + * @cfg {Function} renderer + * A custom function to render the content to the element. The function should + * return false if the renderer could not be applied. The passed parameters are: + * + * - The loader + * - The response + * - The active request + */ + + /** + * @property {Boolean} isLoader + * `true` in this class to identify an object as an instantiated ElementLoader, or subclass thereof. + */ + isLoader: true, + + constructor: function(config) { + var me = this, + autoLoad; + + config = config || {}; + Ext.apply(me, config); + me.setTarget(me.target); + me.addEvents( + /** + * @event beforeload + * Fires before a load request is made to the server. + * Returning false from an event listener can prevent the load + * from occurring. + * @param {Ext.ElementLoader} this + * @param {Object} options The options passed to the request + */ + 'beforeload', + + /** + * @event exception + * Fires after an unsuccessful load. + * @param {Ext.ElementLoader} this + * @param {Object} response The response from the server + * @param {Object} options The options passed to the request + */ + 'exception', + + /** + * @event load + * Fires after a successful load. + * @param {Ext.ElementLoader} this + * @param {Object} response The response from the server + * @param {Object} options The options passed to the request + */ + 'load' + ); + + // don't pass config because we have already applied it. + me.mixins.observable.constructor.call(me); + + if (me.autoLoad) { + autoLoad = me.autoLoad; + if (autoLoad === true) { + autoLoad = {}; + } + me.load(autoLoad); + } + }, + + /** + * Sets an {@link Ext.Element} as the target of this loader. + * Note that if the target is changed, any active requests will be aborted. + * @param {String/HTMLElement/Ext.Element} target The element or its ID. + */ + setTarget: function(target){ + var me = this; + target = Ext.get(target); + if (me.target && me.target != target) { + me.abort(); + } + me.target = target; + }, + + /** + * Returns the target of this loader. + * @return {Ext.Component} The target or null if none exists. + */ + getTarget: function(){ + return this.target || null; + }, + + /** + * Aborts the active load request + */ + abort: function(){ + var active = this.active; + if (active !== undefined) { + Ext.Ajax.abort(active.request); + if (active.mask) { + this.removeMask(); + } + delete this.active; + } + }, + + /** + * Removes the mask on the target + * @private + */ + removeMask: function(){ + this.target.unmask(); + }, + + /** + * Adds the mask on the target + * @private + * @param {Boolean/Object} mask The mask configuration + */ + addMask: function(mask){ + this.target.mask(mask === true ? null : mask); + }, + + /** + * Loads new data from the server. + * @param {Object} options The options for the request. They can be any configuration option that can be specified for + * the class, with the exception of the target option. Note that any options passed to the method will override any + * class defaults. + */ + load: function(options) { + if (!this.target) { + Ext.Error.raise('A valid target is required when loading content'); + } + + options = Ext.apply({}, options); + + var me = this, + target = me.target, + mask = Ext.isDefined(options.loadMask) ? options.loadMask : me.loadMask, + params = Ext.apply({}, options.params), + ajaxOptions = Ext.apply({}, options.ajaxOptions), + callback = options.callback || me.callback, + scope = options.scope || me.scope || me, + request; + + Ext.applyIf(ajaxOptions, me.ajaxOptions); + Ext.applyIf(options, ajaxOptions); + + Ext.applyIf(params, me.params); + Ext.apply(params, me.baseParams); + + Ext.applyIf(options, { + url: me.url + }); + + if (!options.url) { + Ext.Error.raise('You must specify the URL from which content should be loaded'); + } + + Ext.apply(options, { + scope: me, + params: params, + callback: me.onComplete + }); + + if (me.fireEvent('beforeload', me, options) === false) { + return; + } + + if (mask) { + me.addMask(mask); + } + + request = Ext.Ajax.request(options); + me.active = { + request: request, + options: options, + mask: mask, + scope: scope, + callback: callback, + success: options.success || me.success, + failure: options.failure || me.failure, + renderer: options.renderer || me.renderer, + scripts: Ext.isDefined(options.scripts) ? options.scripts : me.scripts + }; + me.setOptions(me.active, options); + }, + + /** + * Sets any additional options on the active request + * @private + * @param {Object} active The active request + * @param {Object} options The initial options + */ + setOptions: Ext.emptyFn, + + /** + * Parses the response after the request completes + * @private + * @param {Object} options Ajax options + * @param {Boolean} success Success status of the request + * @param {Object} response The response object + */ + onComplete: function(options, success, response) { + var me = this, + active = me.active, + scope = active.scope, + renderer = me.getRenderer(active.renderer); + + + if (success) { + success = renderer.call(me, me, response, active) !== false; + } + + if (success) { + Ext.callback(active.success, scope, [me, response, options]); + me.fireEvent('load', me, response, options); + } else { + Ext.callback(active.failure, scope, [me, response, options]); + me.fireEvent('exception', me, response, options); + } + Ext.callback(active.callback, scope, [me, success, response, options]); + + if (active.mask) { + me.removeMask(); + } + + delete me.active; + }, + + /** + * Gets the renderer to use + * @private + * @param {String/Function} renderer The renderer to use + * @return {Function} A rendering function to use. + */ + getRenderer: function(renderer){ + if (Ext.isFunction(renderer)) { + return renderer; + } + return this.statics().Renderer.Html; + }, + + /** + * Automatically refreshes the content over a specified period. + * @param {Number} interval The interval to refresh in ms. + * @param {Object} options (optional) The options to pass to the load method. See {@link #method-load} + */ + startAutoRefresh: function(interval, options){ + var me = this; + me.stopAutoRefresh(); + me.autoRefresh = setInterval(function(){ + me.load(options); + }, interval); + }, + + /** + * Clears any auto refresh. See {@link #startAutoRefresh}. + */ + stopAutoRefresh: function(){ + clearInterval(this.autoRefresh); + delete this.autoRefresh; + }, + + /** + * Checks whether the loader is automatically refreshing. See {@link #startAutoRefresh}. + * @return {Boolean} True if the loader is automatically refreshing + */ + isAutoRefreshing: function(){ + return Ext.isDefined(this.autoRefresh); + }, + + /** + * Destroys the loader. Any active requests will be aborted. + */ + destroy: function(){ + var me = this; + me.stopAutoRefresh(); + delete me.target; + me.abort(); + me.clearListeners(); + } +}); + +/** + * @class Ext.ComponentLoader + * + * This class is used to load content via Ajax into a {@link Ext.Component}. In general + * this class will not be instanced directly, rather a loader configuration will be passed to the + * constructor of the {@link Ext.Component}. + * + * ## HTML Renderer + * By default, the content loaded will be processed as raw html. The response text + * from the request is taken and added to the component. This can be used in + * conjunction with the {@link #scripts} option to execute any inline scripts in + * the resulting content. Using this renderer has the same effect as passing the + * {@link Ext.Component#html} configuration option. + * + * ## Data Renderer + * This renderer allows content to be added by using JSON data and a {@link Ext.XTemplate}. + * The content received from the response is passed to the {@link Ext.Component#update} method. + * This content is run through the attached {@link Ext.Component#tpl} and the data is added to + * the Component. Using this renderer has the same effect as using the {@link Ext.Component#data} + * configuration in conjunction with a {@link Ext.Component#tpl}. + * + * ## Component Renderer + * This renderer can only be used with a {@link Ext.container.Container} and subclasses. It allows for + * Components to be loaded remotely into a Container. The response is expected to be a single/series of + * {@link Ext.Component} configuration objects. When the response is received, the data is decoded + * and then passed to {@link Ext.container.Container#method-add}. Using this renderer has the same effect as specifying + * the {@link Ext.container.Container#cfg-items} configuration on a Container. + * + * ## Custom Renderer + * A custom function can be passed to handle any other special case, see the {@link #renderer} option. + * + * ## Example Usage + * new Ext.Component({ + * tpl: '{firstName} - {lastName}', + * loader: { + * url: 'myPage.php', + * renderer: 'data', + * params: { + * userId: 1 + * } + * } + * }); + */ +Ext.define('Ext.ComponentLoader', { + + /* Begin Definitions */ + + extend: 'Ext.ElementLoader', + + statics: { + Renderer: { + Data: function(loader, response, active){ + var success = true; + try { + loader.getTarget().update(Ext.decode(response.responseText)); + } catch (e) { + success = false; + } + return success; + }, + + Component: function(loader, response, active){ + var success = true, + target = loader.getTarget(), + items = []; + + if (!target.isContainer) { + Ext.Error.raise({ + target: target, + msg: 'Components can only be loaded into a container' + }); + } + + try { + items = Ext.decode(response.responseText); + } catch (e) { + success = false; + } + + if (success) { + target.suspendLayouts(); + if (active.removeAll) { + target.removeAll(); + } + target.add(items); + target.resumeLayouts(true); + } + return success; + } + } + }, + + /* End Definitions */ + + /** + * @cfg {Ext.Component/String} target The target {@link Ext.Component} for the loader. + * If a string is passed it will be looked up via the id. + */ + target: null, + + /** + * @cfg {Boolean/Object} loadMask True or a {@link Ext.LoadMask} configuration to enable masking during loading. + */ + loadMask: false, + + /** + * @cfg {Boolean} scripts True to parse any inline script tags in the response. This only used when using the html + * {@link #renderer}. + */ + + /** + * @cfg {String/Function} renderer + +The type of content that is to be loaded into, which can be one of 3 types: + ++ **html** : Loads raw html content, see {@link Ext.Component#html} ++ **data** : Loads raw html content, see {@link Ext.Component#data} ++ **component** : Loads child {Ext.Component} instances. This option is only valid when used with a Container. + +Alternatively, you can pass a function which is called with the following parameters. + ++ loader - Loader instance ++ response - The server response ++ active - The active request + +The function must return false is loading is not successful. Below is a sample of using a custom renderer: + + new Ext.Component({ + loader: { + url: 'myPage.php', + renderer: function(loader, response, active) { + var text = response.responseText; + loader.getTarget().update('The response is ' + text); + return true; + } + } + }); + */ + renderer: 'html', + + /** + * Set a {Ext.Component} as the target of this loader. Note that if the target is changed, + * any active requests will be aborted. + * @param {String/Ext.Component} target The component to be the target of this loader. If a string is passed + * it will be looked up via its id. + */ + setTarget: function(target){ + var me = this; + + if (Ext.isString(target)) { + target = Ext.getCmp(target); + } + + if (me.target && me.target != target) { + me.abort(); + } + me.target = target; + }, + + // inherit docs + removeMask: function(){ + this.target.setLoading(false); + }, + + /** + * Add the mask on the target + * @private + * @param {Boolean/Object} mask The mask configuration + */ + addMask: function(mask){ + this.target.setLoading(mask); + }, + + + setOptions: function(active, options){ + active.removeAll = Ext.isDefined(options.removeAll) ? options.removeAll : this.removeAll; + }, + + /** + * Gets the renderer to use + * @private + * @param {String/Function} renderer The renderer to use + * @return {Function} A rendering function to use. + */ + getRenderer: function(renderer){ + if (Ext.isFunction(renderer)) { + return renderer; + } + + var renderers = this.statics().Renderer; + switch (renderer) { + case 'component': + return renderers.Component; + case 'data': + return renderers.Data; + default: + return Ext.ElementLoader.Renderer.Html; + } + } +}); + +/** + * This class compiles the XTemplate syntax into a function object. The function is used + * like so: + * + * function (out, values, parent, xindex, xcount) { + * // out is the output array to store results + * // values, parent, xindex and xcount have their historical meaning + * } + * + * @markdown + * @private + */ +Ext.define('Ext.XTemplateCompiler', { + extend: 'Ext.XTemplateParser', + + // Chrome really likes "new Function" to realize the code block (as in it is + // 2x-3x faster to call it than using eval), but Firefox chokes on it badly. + // IE and Opera are also fine with the "new Function" technique. + useEval: Ext.isGecko, + + // See http://jsperf.com/nige-array-append for quickest way to append to an array of unknown length + // (Due to arbitrary code execution inside a template, we cannot easily track the length in var) + // On IE6 and 7 myArray[myArray.length]='foo' is better. On other browsers myArray.push('foo') is better. + useIndex: Ext.isIE6 || Ext.isIE7, + + useFormat: true, + + propNameRe: /^[\w\d\$]*$/, + + compile: function (tpl) { + var me = this, + code = me.generate(tpl); + + // When using "new Function", we have to pass our "Ext" variable to it in order to + // support sandboxing. If we did not, the generated function would use the global + // "Ext", not the "Ext" from our sandbox (scope chain). + // + return me.useEval ? me.evalTpl(code) : (new Function('Ext', code))(Ext); + }, + + generate: function (tpl) { + var me = this, + // note: Ext here is properly sandboxed + definitions = 'var fm=Ext.util.Format,ts=Object.prototype.toString;', + code; + + // Track how many levels we use, so that we only "var" each level's variables once + me.maxLevel = 0; + + me.body = [ + 'var c0=values, a0=' + me.createArrayTest(0) + ', p0=parent, n0=xcount, i0=xindex, v;\n' + ]; + if (me.definitions) { + if (typeof me.definitions === 'string') { + me.definitions = [me.definitions, definitions ]; + } else { + me.definitions.push(definitions); + } + } else { + me.definitions = [ definitions ]; + } + me.switches = []; + + me.parse(tpl); + + me.definitions.push( + (me.useEval ? '$=' : 'return') + ' function (' + me.fnArgs + ') {', + me.body.join(''), + '}' + ); + + code = me.definitions.join('\n'); + + // Free up the arrays. + me.definitions.length = me.body.length = me.switches.length = 0; + delete me.definitions; + delete me.body; + delete me.switches; + + return code; + }, + + //----------------------------------- + // XTemplateParser callouts + + doText: function (text) { + var me = this, + out = me.body; + + text = text.replace(me.aposRe, "\\'").replace(me.newLineRe, '\\n'); + if (me.useIndex) { + out.push('out[out.length]=\'', text, '\'\n'); + } else { + out.push('out.push(\'', text, '\')\n'); + } + }, + + doExpr: function (expr) { + var out = this.body; + out.push('if ((v=' + expr + ')!==undefined) out'); + + // Coerce value to string using concatenation of an empty string literal. + // See http://jsperf.com/tostringvscoercion/5 + if (this.useIndex) { + out.push('[out.length]=v+\'\'\n'); + } else { + out.push('.push(v+\'\')\n'); + } + }, + + doTag: function (tag) { + this.doExpr(this.parseTag(tag)); + }, + + doElse: function () { + this.body.push('} else {\n'); + }, + + doEval: function (text) { + this.body.push(text, '\n'); + }, + + doIf: function (action, actions) { + var me = this; + + // If it's just a propName, use it directly in the if + if (action === '.') { + me.body.push('if (values) {\n'); + } else if (me.propNameRe.test(action)) { + me.body.push('if (', me.parseTag(action), ') {\n'); + } + // Otherwise, it must be an expression, and needs to be returned from an fn which uses with(values) + else { + me.body.push('if (', me.addFn(action), me.callFn, ') {\n'); + } + if (actions.exec) { + me.doExec(actions.exec); + } + }, + + doElseIf: function (action, actions) { + var me = this; + + // If it's just a propName, use it directly in the else if + if (action === '.') { + me.body.push('else if (values) {\n'); + } else if (me.propNameRe.test(action)) { + me.body.push('} else if (', me.parseTag(action), ') {\n'); + } + // Otherwise, it must be an expression, and needs to be returned from an fn which uses with(values) + else { + me.body.push('} else if (', me.addFn(action), me.callFn, ') {\n'); + } + if (actions.exec) { + me.doExec(actions.exec); + } + }, + + doSwitch: function (action) { + var me = this; + + // If it's just a propName, use it directly in the switch + if (action === '.') { + me.body.push('switch (values) {\n'); + } else if (me.propNameRe.test(action)) { + me.body.push('switch (', me.parseTag(action), ') {\n'); + } + // Otherwise, it must be an expression, and needs to be returned from an fn which uses with(values) + else { + me.body.push('switch (', me.addFn(action), me.callFn, ') {\n'); + } + me.switches.push(0); + }, + + doCase: function (action) { + var me = this, + cases = Ext.isArray(action) ? action : [action], + n = me.switches.length - 1, + match, i; + + if (me.switches[n]) { + me.body.push('break;\n'); + } else { + me.switches[n]++; + } + + for (i = 0, n = cases.length; i < n; ++i) { + match = me.intRe.exec(cases[i]); + cases[i] = match ? match[1] : ("'" + cases[i].replace(me.aposRe,"\\'") + "'"); + } + + me.body.push('case ', cases.join(': case '), ':\n'); + }, + + doDefault: function () { + var me = this, + n = me.switches.length - 1; + + if (me.switches[n]) { + me.body.push('break;\n'); + } else { + me.switches[n]++; + } + + me.body.push('default:\n'); + }, + + doEnd: function (type, actions) { + var me = this, + L = me.level-1; + + if (type == 'for') { + /* + To exit a for loop we must restore the outer loop's context. The code looks + like this (which goes with that produced by doFor: + + for (...) { // the part generated by doFor + ... // the body of the for loop + + // ... any tpl for exec statement goes here... + } + parent = p1; + values = r2; + xcount = n1; + xindex = i1 + */ + if (actions.exec) { + me.doExec(actions.exec); + } + + me.body.push('}\n'); + me.body.push('parent=p',L,';values=r',L+1,';xcount=n',L,';xindex=i',L,'\n'); + } else if (type == 'if' || type == 'switch') { + me.body.push('}\n'); + } + }, + + doFor: function (action, actions) { + var me = this, + s, + L = me.level, + up = L-1, + pL = 'p' + L, + parentAssignment; + + // If it's just a propName, use it directly in the switch + if (action === '.') { + s = 'values'; + } else if (me.propNameRe.test(action)) { + s = me.parseTag(action); + } + // Otherwise, it must be an expression, and needs to be returned from an fn which uses with(values) + else { + s = me.addFn(action) + me.callFn; + } + + /* + We are trying to produce a block of code that looks like below. We use the nesting + level to uniquely name the control variables. + + // Omit "var " if we have already been through level 2 + var i2 = 0, + n2 = 0, + c2 = values['propName'], + // c2 is the context object for the for loop + a2 = Array.isArray(c2); + p2 = c1, + // p2 is the parent context (of the outer for loop) + r2 = values + // r2 is the values object to + + // If iterating over the current data, the parent is always set to c2 + parent = c2; + // If iterating over a property in an object, set the parent to the object + parent = a1 ? c1[i1] : p2 // set parent + if (c2) { + if (a2) { + n2 = c2.length; + } else if (c2.isMixedCollection) { + c2 = c2.items; + n2 = c2.length; + } else if (c2.isStore) { + c2 = c2.data.items; + n2 = c2.length; + } else { + c2 = [ c2 ]; + n2 = 1; + } + } + // i2 is the loop index and n2 is the number (xcount) of this for loop + for (xcount = n2; i2 < n2; ++i2) { + values = c2[i2] // adjust special vars to inner scope + xindex = i2 + 1 // xindex is 1-based + + The body of the loop is whatever comes between the tpl and /tpl statements (which + is handled by doEnd). + */ + + // Declare the vars for a particular level only if we have not already declared them. + if (me.maxLevel < L) { + me.maxLevel = L; + me.body.push('var '); + } + + if (action == '.') { + parentAssignment = 'c' + L; + } else { + parentAssignment = 'a' + up + '?c' + up + '[i' + up + ']:p' + L; + } + + me.body.push('i',L,'=0,n', L, '=0,c',L,'=',s,',a',L,'=', me.createArrayTest(L), ',p',L,'=c',up,',r',L,'=values;\n', + 'parent=',parentAssignment,'\n', + 'if (c',L,'){if(a',L,'){n', L,'=c', L, '.length;}else if (c', L, '.isMixedCollection){c',L,'=c',L,'.items;n',L,'=c',L,'.length;}else if(c',L,'.isStore){c',L,'=c',L,'.data.items;n',L,'=c',L,'.length;}else{c',L,'=[c',L,'];n',L,'=1;}}\n', + 'for (xcount=n',L,';i',L,'...
    // loop through array at root node + * ... // loop through array at foo node + * ... // loop through array at foo.bar node + * + * Using the sample data above: + * + * var tpl = new Ext.XTemplate( + * '

    Kids: ', + * '', // process the data.kids node + * '

    {#}. {name}

    ', // use current array index to autonumber + * '

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

    Name: {name}

    ', + * '

    Title: {title}

    ', + * '

    Company: {company}

    ', + * '

    Kids: ', + * '', // interrogate the kids property within the data + * '

    {name}

    ', + * '

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

    {name}\'s favorite beverages:

    ', + * '', + * '
    - {.}
    ', + * '
    ' + * ); + * 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( + * '

    Name: {name}

    ', + * '

    Kids: ', + * '', + * '', + * '

    {name}

    ', + * '

    Dad: {parent.name}

    ', + * '
    ', + * '

    ' + * ); + * 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. + * + * Using the sample data above: + * + * var tpl = new Ext.XTemplate( + * '

    Name: {name}

    ', + * '

    Kids: ', + * '', + * '', + * '

    {name}

    ', + * '
    ', + * '

    ' + * ); + * tpl.overwrite(panel.body, data); + * + * More advanced conditionals are also supported: + * + * var tpl = new Ext.XTemplate( + * '

    Name: {name}

    ', + * '

    Kids: ', + * '', + * '

    {name} is a ', + * '', + * '

    teenager

    ', + * '', + * '

    kid

    ', + * '', + * '

    baby

    ', + * '
    ', + * '

    ' + * ); + * + * var tpl = new Ext.XTemplate( + * '

    Name: {name}

    ', + * '

    Kids: ', + * '', + * '

    {name} is a ', + * '', + * '', + * '

    girl

    ', + * '', + * '

    boy

    ', + * '
    ', + * '

    ' + * ); + * + * A `break` is implied between each case and default, however, multiple cases can be listed + * in a single <tpl> tag. + * + * # Using double quotes + * + * Examples: + * + * var tpl = new Ext.XTemplate( + * "Child", + * "Teenager", + * "...", + * '...', + * "", + * "Hello" + * ); + * + * # Basic math support + * + * The following basic math operators may be applied directly on numeric data values: + * + * + - * / + * + * For example: + * + * var tpl = new Ext.XTemplate( + * '

    Name: {name}

    ', + * '

    Kids: ', + * '', + * '', // <-- Note that the > is encoded + * '

    {#}: {name}

    ', // <-- Auto-number each item + * '

    In 5 Years: {age+5}

    ', // <-- Basic math + * '

    Dad: {parent.name}

    ', + * '
    ', + * '

    ' + * ); + * 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. + * The expression is evaluated and the result is included in the generated result. There are + * some special variables available in that code: + * + * - **out**: The output array into which the template is being appended (using `push` to later + * `join`). + * - **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. + * + * This example demonstrates basic row striping using an inline code block and the xindex variable: + * + * var tpl = new Ext.XTemplate( + * '

    Name: {name}

    ', + * '

    Company: {[values.company.toUpperCase() + ", " + values.title]}

    ', + * '

    Kids: ', + * '', + * '

    ', + * '{name}', + * '
    ', + * '

    ' + * ); + * + * Any code contained in "verbatim" blocks (using "{% ... %}") will be inserted directly in + * the generated code for the template. These blocks are not included in the output. This + * can be used for simple things like break/continue in a loop, or control structures or + * method calls (when they don't produce output). The `this` references the template instance. + * + * var tpl = new Ext.XTemplate( + * '

    Name: {name}

    ', + * '

    Company: {[values.company.toUpperCase() + ", " + values.title]}

    ', + * '

    Kids: ', + * '', + * '{% if (xindex % 2 === 0) continue; %}', + * '{name}', + * '{% if (xindex > 100) break; %}', + * '', + * '

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

    Name: {name}

    ', + * '

    Kids: ', + * '', + * '', + * '

    Girl: {name} - {age}

    ', + * '', + * '

    Boy: {name} - {age}

    ', + * '
    ', + * '', + * '

    {name} is a baby!

    ', + * '
    ', + * '

    ', + * { + * // XTemplate configuration: + * disableFormats: true, + * // member functions: + * isGirl: function(name){ + * return name == 'Sara Grace'; + * }, + * isBaby: function(age){ + * return age < 1; + * } + * } + * ); + * tpl.overwrite(panel.body, data); + */ +Ext.define('Ext.XTemplate', { + extend: 'Ext.Template', + + requires: 'Ext.XTemplateCompiler', + + /** + * @cfg {Boolean} compiled + * Only applies to {@link Ext.Template}, XTemplates are compiled automatically on the + * first call to {@link #apply} or {@link #applyOut}. + */ + + /** + * @cfg {String/Array} definitions + * Optional. A statement, or array of statements which set up `var`s which may then + * be accessed within the scope of the generated function. + */ + + apply: function(values) { + return this.applyOut(values, []).join(''); + }, + + applyOut: function(values, out) { + var me = this, + compiler; + + if (!me.fn) { + compiler = new Ext.XTemplateCompiler({ + useFormat: me.disableFormats !== true, + definitions: me.definitions + }); + + me.fn = compiler.compile(me.html); + } + + try { + me.fn.call(me, out, values, {}, 1, 1); + } catch (e) { + Ext.log('Error: ' + e.message); + } + + return out; + }, + + /** + * Does nothing. XTemplates are compiled automatically, so this function simply returns this. + * @return {Ext.XTemplate} this + */ + compile: function() { + return this; + }, + + statics: { + /** + * Gets an `XTemplate` from an object (an instance of an {@link Ext#define}'d class). + * Many times, templates are configured high in the class hierarchy and are to be + * shared by all classes that derive from that base. To further complicate matters, + * these templates are seldom actual instances but are rather configurations. For + * example: + * + * Ext.define('MyApp.Class', { + * someTpl: [ + * 'tpl text here' + * ] + * }); + * + * The goal being to share that template definition with all instances and even + * instances of derived classes, until `someTpl` is overridden. This method will + * "upgrade" these configurations to be real `XTemplate` instances *in place* (to + * avoid creating one instance per object). + * + * @param {Object} instance The object from which to get the `XTemplate` (must be + * an instance of an {@link Ext#define}'d class). + * @param {String} name The name of the property by which to get the `XTemplate`. + * @return {Ext.XTemplate} The `XTemplate` instance or null if not found. + * @protected + */ + getTpl: function (instance, name) { + var tpl = instance[name], // go for it! 99% of the time we will get it! + proto; + + if (tpl && !tpl.isTemplate) { // tpl is just a configuration (not an instance) + // create the template instance from the configuration: + tpl = Ext.ClassManager.dynInstantiate('Ext.XTemplate', tpl); + + // and replace the reference with the new instance: + if (instance.hasOwnProperty(name)) { // the tpl is on the instance + instance[name] = tpl; + } else { // must be somewhere in the prototype chain + for (proto = instance.self.prototype; proto; proto = proto.superclass) { + if (proto.hasOwnProperty(name)) { + proto[name] = tpl; + break; + } + } + } + } + // else !tpl (no such tpl) or the tpl is an instance already... either way, tpl + // is ready to return + + return tpl || null; + } + } +}); + +/** + * @class Ext.app.Controller + * + * Controllers are the glue that binds an application together. All they really do is listen for events (usually from + * views) and take some action. Here's how we might create a Controller to manage Users: + * + * Ext.define('MyApp.controller.Users', { + * extend: 'Ext.app.Controller', + * + * init: function() { + * console.log('Initialized Users! This happens before the Application launch function is called'); + * } + * }); + * + * The init function is a special method that is called when your application boots. It is called before the + * {@link Ext.app.Application Application}'s launch function is executed so gives a hook point to run any code before + * your Viewport is created. + * + * The init function is a great place to set up how your controller interacts with the view, and is usually used in + * conjunction with another Controller function - {@link Ext.app.Controller#control control}. The control function + * makes it easy to listen to events on your view classes and take some action with a handler function. Let's update + * our Users controller to tell us when the panel is rendered: + * + * Ext.define('MyApp.controller.Users', { + * extend: 'Ext.app.Controller', + * + * init: function() { + * this.control({ + * 'viewport > panel': { + * render: this.onPanelRendered + * } + * }); + * }, + * + * onPanelRendered: function() { + * console.log('The panel was rendered'); + * } + * }); + * + * We've updated the init function to use this.control to set up listeners on views in our application. The control + * function uses the new ComponentQuery engine to quickly and easily get references to components on the page. If you + * are not familiar with ComponentQuery yet, be sure to check out the {@link Ext.ComponentQuery documentation}. In brief though, + * it allows us to pass a CSS-like selector that will find every matching component on the page. + * + * In our init function above we supplied 'viewport > panel', which translates to "find me every Panel that is a direct + * child of a Viewport". We then supplied an object that maps event names (just 'render' in this case) to handler + * functions. The overall effect is that whenever any component that matches our selector fires a 'render' event, our + * onPanelRendered function is called. + * + * Using refs + * + * One of the most useful parts of Controllers is the new ref system. These use the new {@link Ext.ComponentQuery} to + * make it really easy to get references to Views on your page. Let's look at an example of this now: + * + * Ext.define('MyApp.controller.Users', { + * extend: 'Ext.app.Controller', + * + * refs: [ + * { + * ref: 'list', + * selector: 'grid' + * } + * ], + * + * init: function() { + * this.control({ + * 'button': { + * click: this.refreshGrid + * } + * }); + * }, + * + * refreshGrid: function() { + * this.getList().store.load(); + * } + * }); + * + * This example assumes the existence of a {@link Ext.grid.Panel Grid} on the page, which contains a single button to + * refresh the Grid when clicked. In our refs array, we set up a reference to the grid. There are two parts to this - + * the 'selector', which is a {@link Ext.ComponentQuery ComponentQuery} selector which finds any grid on the page and + * assigns it to the reference 'list'. + * + * By giving the reference a name, we get a number of things for free. The first is the getList function that we use in + * the refreshGrid method above. This is generated automatically by the Controller based on the name of our ref, which + * was capitalized and prepended with get to go from 'list' to 'getList'. + * + * The way this works is that the first time getList is called by your code, the ComponentQuery selector is run and the + * first component that matches the selector ('grid' in this case) will be returned. All future calls to getList will + * use a cached reference to that grid. Usually it is advised to use a specific ComponentQuery selector that will only + * match a single View in your application (in the case above our selector will match any grid on the page). + * + * Bringing it all together, our init function is called when the application boots, at which time we call this.control + * to listen to any click on a {@link Ext.button.Button button} and call our refreshGrid function (again, this will + * match any button on the page so we advise a more specific selector than just 'button', but have left it this way for + * simplicity). When the button is clicked we use out getList function to refresh the grid. + * + * You can create any number of refs and control any number of components this way, simply adding more functions to + * your Controller as you go. For an example of real-world usage of Controllers see the Feed Viewer example in the + * examples/app/feed-viewer folder in the SDK download. + * + * Generated getter methods + * + * Refs aren't the only thing that generate convenient getter methods. Controllers often have to deal with Models and + * Stores so the framework offers a couple of easy ways to get access to those too. Let's look at another example: + * + * Ext.define('MyApp.controller.Users', { + * extend: 'Ext.app.Controller', + * + * models: ['User'], + * stores: ['AllUsers', 'AdminUsers'], + * + * init: function() { + * var User = this.getUserModel(), + * allUsers = this.getAllUsersStore(); + * + * var ed = new User({name: 'Ed'}); + * allUsers.add(ed); + * } + * }); + * + * By specifying Models and Stores that the Controller cares about, it again dynamically loads them from the appropriate + * locations (app/model/User.js, app/store/AllUsers.js and app/store/AdminUsers.js in this case) and creates getter + * functions for them all. The example above will create a new User model instance and add it to the AllUsers Store. + * Of course, you could do anything in this function but in this case we just did something simple to demonstrate the + * functionality. + * + * Further Reading + * + * For more information about writing Ext JS 4 applications, please see the + * [application architecture guide](#/guide/application_architecture). Also see the {@link Ext.app.Application} documentation. + * + * @docauthor Ed Spencer + */ +Ext.define('Ext.app.Controller', { + + mixins: { + observable: 'Ext.util.Observable' + }, + + /** + * @cfg {String} id The id of this controller. You can use this id when dispatching. + */ + + /** + * @cfg {String[]} models + * Array of models to require from AppName.model namespace. For example: + * + * Ext.define("MyApp.controller.Foo", { + * extend: "Ext.app.Controller", + * models: ['User', 'Vehicle'] + * }); + * + * This is equivalent of: + * + * Ext.define("MyApp.controller.Foo", { + * extend: "Ext.app.Controller", + * requires: ['MyApp.model.User', 'MyApp.model.Vehicle'] + * }); + * + */ + + /** + * @cfg {String[]} views + * Array of views to require from AppName.view namespace. For example: + * + * Ext.define("MyApp.controller.Foo", { + * extend: "Ext.app.Controller", + * views: ['List', 'Detail'] + * }); + * + * This is equivalent of: + * + * Ext.define("MyApp.controller.Foo", { + * extend: "Ext.app.Controller", + * requires: ['MyApp.view.List', 'MyApp.view.Detail'] + * }); + * + */ + + /** + * @cfg {String[]} stores + * Array of stores to require from AppName.store namespace. For example: + * + * Ext.define("MyApp.controller.Foo", { + * extend: "Ext.app.Controller", + * stores: ['Users', 'Vehicles'] + * }); + * + * This is equivalent of: + * + * Ext.define("MyApp.controller.Foo", { + * extend: "Ext.app.Controller", + * requires: ['MyApp.store.Users', 'MyApp.store.Vehicles'] + * }); + * + */ + + /** + * @cfg {Object[]} refs + * Array of configs to build up references to views on page. For example: + * + * Ext.define("MyApp.controller.Foo", { + * extend: "Ext.app.Controller", + * refs: [ + * { + * ref: 'list', + * selector: 'grid' + * } + * ], + * }); + * + * This will add method `getList` to the controller which will internally use + * Ext.ComponentQuery to reference the grid component on page. + */ + + onClassExtended: function(cls, data, hooks) { + var className = Ext.getClassName(cls), + match = className.match(/^(.*)\.controller\./), + namespace, + onBeforeClassCreated, + requires, + modules, + namespaceAndModule; + + if (match !== null) { + namespace = Ext.Loader.getPrefix(className) || match[1]; + onBeforeClassCreated = hooks.onBeforeCreated; + requires = []; + modules = ['model', 'view', 'store']; + + hooks.onBeforeCreated = function(cls, data) { + var i, ln, module, + items, j, subLn, item; + + for (i = 0,ln = modules.length; i < ln; i++) { + module = modules[i]; + namespaceAndModule = namespace + '.' + module + '.'; + + items = Ext.Array.from(data[module + 's']); + + for (j = 0,subLn = items.length; j < subLn; j++) { + item = items[j]; + // Deciding if a class name must be qualified: + // 1 - if the name doesn't contains at least one dot, we must definitely qualify it + // 2 - the name may be a qualified name of a known class, but: + // 2.1 - in runtime, the loader may not know the class - specially in production - so we must check the class manager + // 2.2 - in build time, the class manager may not know the class, but the loader does, so we check the second one + // (the loader check assures it's really a class, and not a namespace, so we can have 'Books.controller.Books', + // and requesting a controller called Books will not be underqualified) + if (item.indexOf('.') !== -1 && (Ext.ClassManager.isCreated(item) || Ext.Loader.isAClassNameWithAKnownPrefix(item))) { + requires.push(item); + } else { + requires.push(namespaceAndModule + item); + } + } + } + + Ext.require(requires, Ext.Function.pass(onBeforeClassCreated, arguments, this)); + }; + } + }, + + /** + * Creates new Controller. + * @param {Object} config (optional) Config object. + */ + constructor: function(config) { + this.mixins.observable.constructor.call(this, config); + + Ext.apply(this, config || {}); + this.createGetters('model', this.models); + this.createGetters('store', this.stores); + this.createGetters('view', this.views); + + if (this.refs) { + this.ref(this.refs); + } + }, + + /** + * A template method that is called when your application boots. It is called before the + * {@link Ext.app.Application Application}'s launch function is executed so gives a hook point to run any code before + * your Viewport is created. + * + * @param {Ext.app.Application} application + * @template + */ + init: function(application) {}, + + /** + * A template method like {@link #init}, but called after the viewport is created. + * This is called after the {@link Ext.app.Application#launch launch} method of Application is executed. + * + * @param {Ext.app.Application} application + * @template + */ + onLaunch: function(application) {}, + + createGetters: function(type, refs) { + type = Ext.String.capitalize(type); + + var i = 0, + length = (refs) ? refs.length : 0, + fn, ref, parts, x, numParts; + + for (; i < length; i++) { + fn = 'get'; + ref = refs[i]; + parts = ref.split('.'); + numParts = parts.length; + + // Handle namespaced class names. E.g. feed.Add becomes getFeedAddView etc. + for (x = 0 ; x < numParts; x++) { + fn += Ext.String.capitalize(parts[x]); + } + + fn += type; + + if (!this[fn]) { + this[fn] = Ext.Function.pass(this['get' + type], [ref], this); + } + // Execute it right away + this[fn](ref); + } + }, + + ref: function(refs) { + refs = Ext.Array.from(refs); + + var me = this, + i = 0, + length = refs.length, + info, ref, fn; + + for (; i < length; i++) { + info = refs[i]; + ref = info.ref; + fn = 'get' + Ext.String.capitalize(ref); + + if (!me[fn]) { + me[fn] = Ext.Function.pass(me.getRef, [ref, info], me); + } + me.references = me.references || []; + me.references.push(ref.toLowerCase()); + } + }, + + addRef: function(ref) { + return this.ref([ref]); + }, + + getRef: function(ref, info, config) { + this.refCache = this.refCache || {}; + info = info || {}; + config = config || {}; + + Ext.apply(info, config); + + if (info.forceCreate) { + return Ext.ComponentManager.create(info, 'component'); + } + + var me = this, + cached = me.refCache[ref]; + + if (!cached) { + me.refCache[ref] = cached = Ext.ComponentQuery.query(info.selector)[0]; + if (!cached && info.autoCreate) { + me.refCache[ref] = cached = Ext.ComponentManager.create(info, 'component'); + } + if (cached) { + cached.on('beforedestroy', function() { + me.refCache[ref] = null; + }); + } + } + + return cached; + }, + + hasRef: function(ref) { + return this.references && this.references.indexOf(ref.toLowerCase()) !== -1; + }, + + /** + * Adds listeners to components selected via {@link Ext.ComponentQuery}. Accepts an + * object containing component paths mapped to a hash of listener functions. + * + * In the following example the `updateUser` function is mapped to to the `click` + * event on a button component, which is a child of the `useredit` component. + * + * Ext.define('AM.controller.Users', { + * init: function() { + * this.control({ + * 'useredit button[action=save]': { + * click: this.updateUser + * } + * }); + * }, + * + * updateUser: function(button) { + * console.log('clicked the Save button'); + * } + * }); + * + * See {@link Ext.ComponentQuery} for more information on component selectors. + * + * @param {String/Object} selectors If a String, the second argument is used as the + * listeners, otherwise an object of selectors -> listeners is assumed + * @param {Object} listeners + */ + control: function(selectors, listeners) { + this.application.control(selectors, listeners, this); + }, + + /** + * Returns instance of a {@link Ext.app.Controller controller} with the given name. + * When controller doesn't exist yet, it's created. + * @param {String} name + * @return {Ext.app.Controller} a controller instance. + */ + getController: function(name) { + return this.application.getController(name); + }, + + /** + * Returns instance of a {@link Ext.data.Store Store} with the given name. + * When store doesn't exist yet, it's created. + * @param {String} name + * @return {Ext.data.Store} a store instance. + */ + getStore: function(name) { + return this.application.getStore(name); + }, + + /** + * Returns a {@link Ext.data.Model Model} class with the given name. + * A shorthand for using {@link Ext.ModelManager#getModel}. + * @param {String} name + * @return {Ext.data.Model} a model class. + */ + getModel: function(model) { + return this.application.getModel(model); + }, + + /** + * Returns a View class with the given name. To create an instance of the view, + * you can use it like it's used by Application to create the Viewport: + * + * this.getView('Viewport').create(); + * + * @param {String} name + * @return {Ext.Base} a view class. + */ + getView: function(view) { + return this.application.getView(view); + } +}); + +/** + * @class Ext.chart.Label + * + * Labels is a mixin to the Series class. Labels methods are implemented + * in each of the Series (Pie, Bar, etc) for label creation and placement. + * + * The methods implemented by the Series are: + * + * - **`onCreateLabel(storeItem, item, i, display)`** Called each time a new label is created. + * The arguments of the method are: + * - *`storeItem`* The element of the store that is related to the label sprite. + * - *`item`* The item related to the label sprite. An item is an object containing the position of the shape + * used to describe the visualization and also pointing to the actual shape (circle, rectangle, path, etc). + * - *`i`* The index of the element created (i.e the first created label, second created label, etc) + * - *`display`* The display type. May be false if the label is hidden + * + * - **`onPlaceLabel(label, storeItem, item, i, display, animate)`** Called for updating the position of the label. + * The arguments of the method are: + * - *`label`* The sprite label. + * - *`storeItem`* The element of the store that is related to the label sprite + * - *`item`* The item related to the label sprite. An item is an object containing the position of the shape + * used to describe the visualization and also pointing to the actual shape (circle, rectangle, path, etc). + * - *`i`* The index of the element to be updated (i.e. whether it is the first, second, third from the labelGroup) + * - *`display`* The display type. May be false if the label is hidden. + * - *`animate`* A boolean value to set or unset animations for the labels. + */ +Ext.define('Ext.chart.Label', { + + /* Begin Definitions */ + + requires: ['Ext.draw.Color'], + + /* End Definitions */ + + /** + * @cfg {Object} label + * Object with the following properties: + * + * - **display** : String + * + * Specifies the presence and position of labels for each pie slice. Either "rotate", "middle", "insideStart", + * "insideEnd", "outside", "over", "under", or "none" to prevent label rendering. + * Default value: 'none'. + * + * - **color** : String + * + * The color of the label text. + * Default value: '#000' (black). + * + * - **contrast** : Boolean + * + * True to render the label in contrasting color with the backround. + * Default value: false. + * + * - **field** : String + * + * The name of the field to be displayed in the label. + * Default value: 'name'. + * + * - **minMargin** : Number + * + * Specifies the minimum distance from a label to the origin of the visualization. + * This parameter is useful when using PieSeries width variable pie slice lengths. + * Default value: 50. + * + * - **font** : String + * + * The font used for the labels. + * Default value: "11px Helvetica, sans-serif". + * + * - **orientation** : String + * + * Either "horizontal" or "vertical". + * Dafault value: "horizontal". + * + * - **renderer** : Function + * + * Optional function for formatting the label into a displayable value. + * Default value: function(v) { return v; } + */ + + // @private a regex to parse url type colors. + colorStringRe: /url\s*\(\s*#([^\/)]+)\s*\)/, + + // @private the mixin constructor. Used internally by Series. + constructor: function(config) { + var me = this; + me.label = Ext.applyIf(me.label || {}, + { + display: "none", + color: "#000", + field: "name", + minMargin: 50, + font: "11px Helvetica, sans-serif", + orientation: "horizontal", + renderer: function(v) { + return v; + } + }); + + if (me.label.display !== 'none') { + me.labelsGroup = me.chart.surface.getGroup(me.seriesId + '-labels'); + } + }, + + // @private a method to render all labels in the labelGroup + renderLabels: function() { + var me = this, + chart = me.chart, + gradients = chart.gradients, + items = me.items, + animate = chart.animate, + config = me.label, + display = config.display, + color = config.color, + field = [].concat(config.field), + group = me.labelsGroup, + groupLength = (group || 0) && group.length, + store = me.chart.getChartStore(), + len = store.getCount(), + itemLength = (items || 0) && items.length, + ratio = itemLength / len, + gradientsCount = (gradients || 0) && gradients.length, + Color = Ext.draw.Color, + hides = [], + gradient, i, count, groupIndex, index, j, k, colorStopTotal, colorStopIndex, colorStop, item, label, + storeItem, sprite, spriteColor, spriteBrightness, labelColor, colorString; + + if (display == 'none') { + return; + } + // no items displayed, hide all labels + if(itemLength == 0){ + while(groupLength--) { + hides.push(groupLength); + } + } else { + for (i = 0, count = 0, groupIndex = 0; i < len; i++) { + index = 0; + for (j = 0; j < ratio; j++) { + item = items[count]; + label = group.getAt(groupIndex); + storeItem = store.getAt(i); + //check the excludes + while(this.__excludes && this.__excludes[index]) { + index++; + } + + if (!item && label) { + label.hide(true); + groupIndex++; + } + + if (item && field[j]) { + if (!label) { + label = me.onCreateLabel(storeItem, item, i, display, j, index); + } + me.onPlaceLabel(label, storeItem, item, i, display, animate, j, index); + groupIndex++; + + //set contrast + if (config.contrast && item.sprite) { + sprite = item.sprite; + //set the color string to the color to be set. + if (sprite._endStyle) { + colorString = sprite._endStyle.fill; + } + else if (sprite._to) { + colorString = sprite._to.fill; + } + else { + colorString = sprite.attr.fill; + } + colorString = colorString || sprite.attr.fill; + + spriteColor = Color.fromString(colorString); + //color wasn't parsed property maybe because it's a gradient id + if (colorString && !spriteColor) { + colorString = colorString.match(me.colorStringRe)[1]; + for (k = 0; k < gradientsCount; k++) { + gradient = gradients[k]; + if (gradient.id == colorString) { + //avg color stops + colorStop = 0; colorStopTotal = 0; + for (colorStopIndex in gradient.stops) { + colorStop++; + colorStopTotal += Color.fromString(gradient.stops[colorStopIndex].color).getGrayscale(); + } + spriteBrightness = (colorStopTotal / colorStop) / 255; + break; + } + } + } + else { + spriteBrightness = spriteColor.getGrayscale() / 255; + } + if (label.isOutside) { + spriteBrightness = 1; + } + labelColor = Color.fromString(label.attr.color || label.attr.fill).getHSL(); + labelColor[2] = spriteBrightness > 0.5 ? 0.2 : 0.8; + label.setAttributes({ + fill: String(Color.fromHSL.apply({}, labelColor)) + }, true); + } + + } + count++; + index++; + } + } + groupLength = group.length; + + while(groupLength > groupIndex){ + hides.push(groupIndex); + groupIndex++; + } + } + me.hideLabels(hides); + }, + + hideLabels: function(hides){ + var labelsGroup = this.labelsGroup, + hlen = !!hides && hides.length; + + if (!labelsGroup) { + return; + } + + if (hlen === false) { + hlen = labelsGroup.getCount(); + while (hlen--) { + labelsGroup.getAt(hlen).hide(true); + } + } else { + while(hlen--) { + labelsGroup.getAt(hides[hlen]).hide(true); + } + } + } +}); + +/** + * @class Ext.chart.theme.Theme + * + * Provides chart theming. + * + * Used as mixins by Ext.chart.Chart. + */ +Ext.define('Ext.chart.theme.Theme', { + + /* Begin Definitions */ + + requires: ['Ext.draw.Color'], + + /* End Definitions */ + + theme: 'Base', + themeAttrs: false, + + initTheme: function(theme) { + var me = this, + themes = Ext.chart.theme, + key, gradients; + if (theme) { + theme = theme.split(':'); + for (key in themes) { + if (key == theme[0]) { + gradients = theme[1] == 'gradients'; + me.themeAttrs = new themes[key]({ + useGradients: gradients + }); + if (gradients) { + me.gradients = me.themeAttrs.gradients; + } + if (me.themeAttrs.background) { + me.background = me.themeAttrs.background; + } + return; + } + } + Ext.Error.raise('No theme found named "' + theme + '"'); + } + } +}, +// This callback is executed right after when the class is created. This scope refers to the newly created class itself +function() { + /* Theme constructor: takes either a complex object with styles like: + + { + axis: { + fill: '#000', + 'stroke-width': 1 + }, + axisLabelTop: { + fill: '#000', + font: '11px Arial' + }, + axisLabelLeft: { + fill: '#000', + font: '11px Arial' + }, + axisLabelRight: { + fill: '#000', + font: '11px Arial' + }, + axisLabelBottom: { + fill: '#000', + font: '11px Arial' + }, + axisTitleTop: { + fill: '#000', + font: '11px Arial' + }, + axisTitleLeft: { + fill: '#000', + font: '11px Arial' + }, + axisTitleRight: { + fill: '#000', + font: '11px Arial' + }, + axisTitleBottom: { + fill: '#000', + font: '11px Arial' + }, + series: { + 'stroke-width': 1 + }, + seriesLabel: { + font: '12px Arial', + fill: '#333' + }, + marker: { + stroke: '#555', + fill: '#000', + radius: 3, + size: 3 + }, + seriesThemes: [{ + fill: '#C6DBEF' + }, { + fill: '#9ECAE1' + }, { + fill: '#6BAED6' + }, { + fill: '#4292C6' + }, { + fill: '#2171B5' + }, { + fill: '#084594' + }], + markerThemes: [{ + fill: '#084594', + type: 'circle' + }, { + fill: '#2171B5', + type: 'cross' + }, { + fill: '#4292C6', + type: 'plus' + }] + } + + ...or also takes just an array of colors and creates the complex object: + + { + colors: ['#aaa', '#bcd', '#eee'] + } + + ...or takes just a base color and makes a theme from it + + { + baseColor: '#bce' + } + + To create a new theme you may add it to the Themes object: + + Ext.chart.theme.MyNewTheme = Ext.extend(Object, { + constructor: function(config) { + Ext.chart.theme.call(this, config, { + baseColor: '#mybasecolor' + }); + } + }); + + //Proposal: + Ext.chart.theme.MyNewTheme = Ext.chart.createTheme('#basecolor'); + + ...and then to use it provide the name of the theme (as a lower case string) in the chart config. + + { + theme: 'mynewtheme' + } + */ + +(function() { + Ext.chart.theme = function(config, base) { + config = config || {}; + var i = 0, d = +new Date(), l, colors, color, + seriesThemes, markerThemes, + seriesTheme, markerTheme, + key, gradients = [], + midColor, midL; + + if (config.baseColor) { + midColor = Ext.draw.Color.fromString(config.baseColor); + midL = midColor.getHSL()[2]; + if (midL < 0.15) { + midColor = midColor.getLighter(0.3); + } else if (midL < 0.3) { + midColor = midColor.getLighter(0.15); + } else if (midL > 0.85) { + midColor = midColor.getDarker(0.3); + } else if (midL > 0.7) { + midColor = midColor.getDarker(0.15); + } + config.colors = [ midColor.getDarker(0.3).toString(), + midColor.getDarker(0.15).toString(), + midColor.toString(), + midColor.getLighter(0.15).toString(), + midColor.getLighter(0.3).toString()]; + + delete config.baseColor; + } + if (config.colors) { + colors = config.colors.slice(); + markerThemes = base.markerThemes; + seriesThemes = base.seriesThemes; + l = colors.length; + base.colors = colors; + for (; i < l; i++) { + color = colors[i]; + markerTheme = markerThemes[i] || {}; + seriesTheme = seriesThemes[i] || {}; + markerTheme.fill = seriesTheme.fill = markerTheme.stroke = seriesTheme.stroke = color; + markerThemes[i] = markerTheme; + seriesThemes[i] = seriesTheme; + } + base.markerThemes = markerThemes.slice(0, l); + base.seriesThemes = seriesThemes.slice(0, l); + //the user is configuring something in particular (either markers, series or pie slices) + } + for (key in base) { + if (key in config) { + if (Ext.isObject(config[key]) && Ext.isObject(base[key])) { + Ext.apply(base[key], config[key]); + } else { + base[key] = config[key]; + } + } + } + if (config.useGradients) { + colors = base.colors || (function () { + var ans = []; + for (i = 0, seriesThemes = base.seriesThemes, l = seriesThemes.length; i < l; i++) { + ans.push(seriesThemes[i].fill || seriesThemes[i].stroke); + } + return ans; + }()); + for (i = 0, l = colors.length; i < l; i++) { + midColor = Ext.draw.Color.fromString(colors[i]); + if (midColor) { + color = midColor.getDarker(0.1).toString(); + midColor = midColor.toString(); + key = 'theme-' + midColor.substr(1) + '-' + color.substr(1) + '-' + d; + gradients.push({ + id: key, + angle: 45, + stops: { + 0: { + color: midColor.toString() + }, + 100: { + color: color.toString() + } + } + }); + colors[i] = 'url(#' + key + ')'; + } + } + base.gradients = gradients; + base.colors = colors; + } + /* + base.axis = Ext.apply(base.axis || {}, config.axis || {}); + base.axisLabel = Ext.apply(base.axisLabel || {}, config.axisLabel || {}); + base.axisTitle = Ext.apply(base.axisTitle || {}, config.axisTitle || {}); + */ + Ext.apply(this, base); + }; +}()); +}); + +/** + * Provides default colors for non-specified things. Should be sub-classed when creating new themes. + * @private + */ +Ext.define('Ext.chart.theme.Base', { + + /* Begin Definitions */ + + requires: ['Ext.chart.theme.Theme'], + + /* End Definitions */ + + constructor: function(config) { + Ext.chart.theme.call(this, config, { + background: false, + axis: { + stroke: '#444', + 'stroke-width': 1 + }, + axisLabelTop: { + fill: '#444', + font: '12px Arial, Helvetica, sans-serif', + spacing: 2, + padding: 5, + renderer: function(v) { return v; } + }, + axisLabelRight: { + fill: '#444', + font: '12px Arial, Helvetica, sans-serif', + spacing: 2, + padding: 5, + renderer: function(v) { return v; } + }, + axisLabelBottom: { + fill: '#444', + font: '12px Arial, Helvetica, sans-serif', + spacing: 2, + padding: 5, + renderer: function(v) { return v; } + }, + axisLabelLeft: { + fill: '#444', + font: '12px Arial, Helvetica, sans-serif', + spacing: 2, + padding: 5, + renderer: function(v) { return v; } + }, + axisTitleTop: { + font: 'bold 18px Arial', + fill: '#444' + }, + axisTitleRight: { + font: 'bold 18px Arial', + fill: '#444', + rotate: { + x:0, y:0, + degrees: 270 + } + }, + axisTitleBottom: { + font: 'bold 18px Arial', + fill: '#444' + }, + axisTitleLeft: { + font: 'bold 18px Arial', + fill: '#444', + rotate: { + x:0, y:0, + degrees: 270 + } + }, + series: { + 'stroke-width': 0 + }, + seriesLabel: { + font: '12px Arial', + fill: '#333' + }, + marker: { + stroke: '#555', + radius: 3, + size: 3 + }, + colors: [ "#94ae0a", "#115fa6","#a61120", "#ff8809", "#ffd13e", "#a61187", "#24ad9a", "#7c7474", "#a66111"], + seriesThemes: [{ + fill: "#115fa6" + }, { + fill: "#94ae0a" + }, { + fill: "#a61120" + }, { + fill: "#ff8809" + }, { + fill: "#ffd13e" + }, { + fill: "#a61187" + }, { + fill: "#24ad9a" + }, { + fill: "#7c7474" + }, { + fill: "#115fa6" + }, { + fill: "#94ae0a" + }, { + fill: "#a61120" + }, { + fill: "#ff8809" + }, { + fill: "#ffd13e" + }, { + fill: "#a61187" + }, { + fill: "#24ad9a" + }, { + fill: "#7c7474" + }, { + fill: "#a66111" + }], + markerThemes: [{ + fill: "#115fa6", + type: 'circle' + }, { + fill: "#94ae0a", + type: 'cross' + }, { + fill: "#115fa6", + type: 'plus' + }, { + fill: "#94ae0a", + type: 'circle' + }, { + fill: "#a61120", + type: 'cross' + }] + }); + } +}, function() { + var palette = ['#b1da5a', '#4ce0e7', '#e84b67', '#da5abd', '#4d7fe6', '#fec935'], + names = ['Green', 'Sky', 'Red', 'Purple', 'Blue', 'Yellow'], + i = 0, j = 0, l = palette.length, themes = Ext.chart.theme, + categories = [['#f0a50a', '#c20024', '#2044ba', '#810065', '#7eae29'], + ['#6d9824', '#87146e', '#2a9196', '#d39006', '#1e40ac'], + ['#fbbc29', '#ce2e4e', '#7e0062', '#158b90', '#57880e'], + ['#ef5773', '#fcbd2a', '#4f770d', '#1d3eaa', '#9b001f'], + ['#7eae29', '#fdbe2a', '#910019', '#27b4bc', '#d74dbc'], + ['#44dce1', '#0b2592', '#996e05', '#7fb325', '#b821a1']], + cats = categories.length; + + //Create themes from base colors + for (; i < l; i++) { + themes[names[i]] = (function(color) { + return Ext.extend(themes.Base, { + constructor: function(config) { + themes.Base.prototype.constructor.call(this, Ext.apply({ + baseColor: color + }, config)); + } + }); + }(palette[i])); + } + + //Create theme from color array + for (i = 0; i < cats; i++) { + themes['Category' + (i + 1)] = (function(category) { + return Ext.extend(themes.Base, { + constructor: function(config) { + themes.Base.prototype.constructor.call(this, Ext.apply({ + colors: category + }, config)); + } + }); + }(categories[i])); + } +}); + +/** + * @author Ed Spencer + * @class Ext.data.Batch + * + *

    Provides a mechanism to run one or more {@link Ext.data.Operation operations} in a given order. Fires the 'operationcomplete' event + * after the completion of each Operation, and the 'complete' event when all Operations have been successfully executed. Fires an 'exception' + * event if any of the Operations encounter an exception.

    + * + *

    Usually these are only used internally by {@link Ext.data.proxy.Proxy} classes

    + * + */ +Ext.define('Ext.data.Batch', { + mixins: { + observable: 'Ext.util.Observable' + }, + + /** + * @cfg {Boolean} autoStart + * True to immediately start processing the batch as soon as it is constructed (defaults to false) + */ + autoStart: false, + + /** + * @cfg {Boolean} pauseOnException + * True to pause the execution of the batch if any operation encounters an exception + * (defaults to false). If you set this to true you are responsible for implementing the appropriate + * handling logic and restarting or discarding the batch as needed. There are different ways you could + * do this, e.g. by handling the batch's {@link #exception} event directly, or perhaps by overriding + * {@link Ext.data.AbstractStore#onBatchException onBatchException} at the store level. If you do pause + * and attempt to handle the exception you can call {@link #retry} to process the same operation again. + * + * Note that {@link Ext.data.Operation operations} are atomic, so any operations that may have succeeded + * prior to an exception (and up until pausing the batch) will be finalized at the server level and will + * not be automatically reversible. Any transactional / rollback behavior that might be desired would have + * to be implemented at the application level. Pausing on exception will likely be most beneficial when + * used in coordination with such a scheme, where an exception might actually affect subsequent operations + * in the same batch and so should be handled before continuing with the next operation. + * + * If you have not implemented transactional operation handling then this option should typically be left + * to the default of false (e.g. process as many operations as possible, and handle any exceptions + * asynchronously without holding up the rest of the batch). + */ + pauseOnException: false, + + /** + * @property {Number} current + * The index of the current operation being executed. Read only + */ + current: -1, + + /** + * @property {Number} total + * The total number of operations in this batch. Read only + */ + total: 0, + + /** + * @property {Boolean} isRunning + * True if the batch is currently running. Read only + */ + isRunning: false, + + /** + * @property {Boolean} isComplete + * True if this batch has been executed completely. Read only + */ + isComplete: false, + + /** + * @property {Boolean} hasException + * True if this batch has encountered an exception. This is cleared at the start of each operation. Read only + */ + hasException: false, + + /** + * Creates new Batch object. + * @param {Object} [config] Config object + */ + constructor: function(config) { + var me = this; + + /** + * @event complete + * Fired when all operations of this batch have been completed + * @param {Ext.data.Batch} batch The batch object + * @param {Object} operation The last operation that was executed + */ + + /** + * @event exception + * Fired when a operation encountered an exception + * @param {Ext.data.Batch} batch The batch object + * @param {Object} operation The operation that encountered the exception + */ + + /** + * @event operationcomplete + * Fired when each operation of the batch completes + * @param {Ext.data.Batch} batch The batch object + * @param {Object} operation The operation that just completed + */ + + me.mixins.observable.constructor.call(me, config); + + /** + * Ordered array of operations that will be executed by this batch + * @property {Ext.data.Operation[]} operations + */ + me.operations = []; + + /** + * Ordered array of operations that raised an exception during the most recent + * batch execution and did not successfully complete + * @property {Ext.data.Operation[]} exceptions + */ + me.exceptions = []; + }, + + /** + * Adds a new operation to this batch at the end of the {@link #operations} array + * @param {Object} operation The {@link Ext.data.Operation Operation} object + * @return {Ext.data.Batch} this + */ + add: function(operation) { + this.total++; + + operation.setBatch(this); + + this.operations.push(operation); + + return this; + }, + + /** + * Kicks off execution of the batch, continuing from the next operation if the previous + * operation encountered an exception, or if execution was paused. Use this method to start + * the batch for the first time or to restart a paused batch by skipping the current + * unsuccessful operation. + * + * To retry processing the current operation before continuing to the rest of the batch (e.g. + * because you explicitly handled the operation's exception), call {@link #retry} instead. + * + * Note that if the batch is already running any call to start will be ignored. + * + * @return {Ext.data.Batch} this + */ + start: function(/* private */ index) { + var me = this; + + if (me.isRunning) { + return me; + } + + me.exceptions.length = 0; + me.hasException = false; + me.isRunning = true; + + return me.runOperation(Ext.isDefined(index) ? index : me.current + 1); + }, + + /** + * Kicks off execution of the batch, continuing from the current operation. This is intended + * for restarting a {@link #pause paused} batch after an exception, and the operation that raised + * the exception will now be retried. The batch will then continue with its normal processing until + * all operations are complete or another exception is encountered. + * + * Note that if the batch is already running any call to retry will be ignored. + * + * @return {Ext.data.Batch} this + */ + retry: function() { + return this.start(this.current); + }, + + /** + * @private + * Runs the next operation, relative to this.current. + * @return {Ext.data.Batch} this + */ + runNextOperation: function() { + return this.runOperation(this.current + 1); + }, + + /** + * Pauses execution of the batch, but does not cancel the current operation + * @return {Ext.data.Batch} this + */ + pause: function() { + this.isRunning = false; + return this; + }, + + /** + * Executes an operation by its numeric index in the {@link #operations} array + * @param {Number} index The operation index to run + * @return {Ext.data.Batch} this + */ + runOperation: function(index) { + var me = this, + operations = me.operations, + operation = operations[index], + onProxyReturn; + + if (operation === undefined) { + me.isRunning = false; + me.isComplete = true; + me.fireEvent('complete', me, operations[operations.length - 1]); + } else { + me.current = index; + + onProxyReturn = function(operation) { + var hasException = operation.hasException(); + + if (hasException) { + me.hasException = true; + me.exceptions.push(operation); + me.fireEvent('exception', me, operation); + } + + if (hasException && me.pauseOnException) { + me.pause(); + } else { + operation.setCompleted(); + me.fireEvent('operationcomplete', me, operation); + me.runNextOperation(); + } + }; + + operation.setStarted(); + + me.proxy[operation.action](operation, onProxyReturn, me); + } + + return me; + } +}); + +/** + * The Connection 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 `<`, `&` as + * `&` 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. + * + * Also note that it's not possible to check the response code of the hidden iframe, so the success handler will ALWAYS fire. + */ +Ext.define('Ext.data.Connection', { + mixins: { + observable: 'Ext.util.Observable' + }, + + statics: { + requestId: 0 + }, + + url: null, + async: true, + method: null, + username: '', + password: '', + + /** + * @cfg {Boolean} disableCaching + * True to add a unique cache-buster param to GET requests. + */ + disableCaching: true, + + /** + * @cfg {Boolean} withCredentials + * True to set `withCredentials = true` on the XHR object + */ + withCredentials: false, + + /** + * @cfg {Boolean} cors + * True to enable CORS support on the XHR object. Currently the only effect of this option + * is to use the XDomainRequest object instead of XMLHttpRequest if the browser is IE8 or above. + */ + cors: false, + + /** + * @cfg {String} disableCachingParam + * Change the parameter which is sent went disabling caching through a cache buster. + */ + disableCachingParam: '_dc', + + /** + * @cfg {Number} timeout + * The timeout in milliseconds to be used for requests. + */ + timeout : 30000, + + /** + * @cfg {Object} extraParams + * Any parameters to be appended to the request. + */ + + /** + * @cfg {Boolean} [autoAbort=false] + * Whether this request should abort any pending requests. + */ + + /** + * @cfg {String} method + * The default HTTP method to be used for requests. + * + * If not set, but {@link #request} params are present, POST will be used; + * otherwise, GET will be used. + */ + + /** + * @cfg {Object} defaultHeaders + * An object containing request headers which are added to each request made by this object. + */ + + useDefaultHeader : true, + defaultPostHeader : 'application/x-www-form-urlencoded; charset=UTF-8', + useDefaultXhrHeader : true, + defaultXhrHeader : 'XMLHttpRequest', + + constructor : function(config) { + config = config || {}; + Ext.apply(this, config); + + /** + * @event beforerequest + * Fires before a network request is made to retrieve a data object. + * @param {Ext.data.Connection} conn This Connection object. + * @param {Object} options The options config object passed to the {@link #request} method. + */ + /** + * @event requestcomplete + * Fires if the request was successfully completed. + * @param {Ext.data.Connection} conn This Connection object. + * @param {Object} response The XHR object containing the response data. + * See [The XMLHttpRequest Object](http://www.w3.org/TR/XMLHttpRequest/) for details. + * @param {Object} options The options config object passed to the {@link #request} method. + */ + /** + * @event requestexception + * Fires if an error HTTP status was returned from the server. + * See [HTTP Status Code Definitions](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html) + * for details of HTTP status codes. + * @param {Ext.data.Connection} conn This Connection object. + * @param {Object} response The XHR object containing the response data. + * See [The XMLHttpRequest Object](http://www.w3.org/TR/XMLHttpRequest/) for details. + * @param {Object} options The options config object passed to the {@link #request} method. + */ + this.requests = {}; + this.mixins.observable.constructor.call(this); + }, + + /** + * 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: + * + * (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.) + * + * @param {String/Function} options.url 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 `url`. + * + * @param {Object/String/Function} options.params 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. + * + * @param {String} options.method 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. + * + * @param {Function} options.callback 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: + * @param {Object} options.callback.options The parameter to the request call. + * @param {Boolean} options.callback.success True if the request succeeded. + * @param {Object} options.callback.response The XMLHttpRequest object containing the response data. + * See [www.w3.org/TR/XMLHttpRequest/](http://www.w3.org/TR/XMLHttpRequest/) for details about + * accessing elements of the response. + * + * @param {Function} options.success The function to be called upon success of the request. + * The callback is passed the following parameters: + * @param {Object} options.success.response The XMLHttpRequest object containing the response data. + * @param {Object} options.success.options The parameter to the request call. + * + * @param {Function} options.failure The function to be called upon success of the request. + * The callback is passed the following parameters: + * @param {Object} options.failure.response The XMLHttpRequest object containing the response data. + * @param {Object} options.failure.options The parameter to the request call. + * + * @param {Object} options.scope 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. + * + * @param {Number} options.timeout The timeout in milliseconds to be used for this request. + * Defaults to 30 seconds. + * + * @param {Ext.Element/HTMLElement/String} options.form The `
    ` Element or the id of the `` + * to pull parameters from. + * + * @param {Boolean} options.isUpload **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 `` element temporarily modified to have its [target][] set to refer to a dynamically + * generated, hidden `', + '{afterIFrameTpl}', + { + disableFormats: true + } + ], + + subTplInsertions: [ + /** + * @cfg {String/Array/Ext.XTemplate} beforeTextAreaTpl + * An optional string or `XTemplate` configuration to insert in the field markup + * before the textarea element. If an `XTemplate` is used, the component's + * {@link Ext.form.field.Base#getSubTplData subTpl data} serves as the context. + */ + 'beforeTextAreaTpl', + + /** + * @cfg {String/Array/Ext.XTemplate} afterTextAreaTpl + * An optional string or `XTemplate` configuration to insert in the field markup + * after the textarea element. If an `XTemplate` is used, the component's + * {@link Ext.form.field.Base#getSubTplData subTpl data} serves as the context. + */ + 'afterTextAreaTpl', + + /** + * @cfg {String/Array/Ext.XTemplate} beforeIFrameTpl + * An optional string or `XTemplate` configuration to insert in the field markup + * before the iframe element. If an `XTemplate` is used, the component's + * {@link Ext.form.field.Base#getSubTplData subTpl data} serves as the context. + */ + 'beforeIFrameTpl', + + /** + * @cfg {String/Array/Ext.XTemplate} afterIFrameTpl + * An optional string or `XTemplate` configuration to insert in the field markup + * after the iframe element. If an `XTemplate` is used, the component's + * {@link Ext.form.field.Base#getSubTplData subTpl data} serves as the context. + */ + 'afterIFrameTpl', + + /** + * @cfg {String/Array/Ext.XTemplate} iframeAttrTpl + * An optional string or `XTemplate` configuration to insert in the field markup + * inside the iframe element (as attributes). If an `XTemplate` is used, the component's + * {@link Ext.form.field.Base#getSubTplData subTpl data} serves as the context. + */ + 'iframeAttrTpl', + + // inherited + 'inputAttrTpl' + ], + + /** + * @cfg {Boolean} enableFormat + * Enable the bold, italic and underline buttons + */ + enableFormat : true, + /** + * @cfg {Boolean} enableFontSize + * Enable the increase/decrease font size buttons + */ + enableFontSize : true, + /** + * @cfg {Boolean} enableColors + * Enable the fore/highlight color buttons + */ + enableColors : true, + /** + * @cfg {Boolean} enableAlignments + * Enable the left, center, right alignment buttons + */ + enableAlignments : true, + /** + * @cfg {Boolean} enableLists + * Enable the bullet and numbered list buttons. Not available in Safari. + */ + enableLists : true, + /** + * @cfg {Boolean} enableSourceEdit + * Enable the switch to source edit button. Not available in Safari. + */ + enableSourceEdit : true, + /** + * @cfg {Boolean} enableLinks + * Enable the create link button. Not available in Safari. + */ + enableLinks : true, + /** + * @cfg {Boolean} enableFont + * Enable font selection. Not available in Safari. + */ + enableFont : true, + /** + * @cfg {String} createLinkText + * The default text for the create link prompt + */ + // + createLinkText : 'Please enter the URL for the link:', + // + /** + * @cfg {String} [defaultLinkValue='http://'] + * The default value for the create link prompt + */ + defaultLinkValue : 'http:/'+'/', + /** + * @cfg {String[]} 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 (Non-breaking space) in Opera and IE6, + * (Zero-width space) in all other browsers. + */ + defaultValue: (Ext.isOpera || Ext.isIE6) ? ' ' : '​', + + fieldBodyCls: Ext.baseCSSPrefix + 'html-editor-wrap', + + componentLayout: 'htmleditor', + + // private properties + initialized : false, + activated : false, + sourceEditMode : false, + iframePad:3, + hideMode:'offsets', + + maskOnDisable: true, + + // private + initComponent : function(){ + var me = this; + + me.addEvents( + /** + * @event initialize + * Fires when the editor is fully initialized (including the iframe) + * @param {Ext.form.field.HtmlEditor} this + */ + 'initialize', + /** + * @event activate + * Fires when the editor is first receives the focus. Any insertion must wait until after this event. + * @param {Ext.form.field.HtmlEditor} this + */ + 'activate', + /** + * @event beforesync + * Fires before the textarea is updated with content from the editor iframe. Return false to cancel the + * sync. + * @param {Ext.form.field.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 {Ext.form.field.HtmlEditor} this + * @param {String} html + */ + 'beforepush', + /** + * @event sync + * Fires when the textarea is updated with content from the editor iframe. + * @param {Ext.form.field.HtmlEditor} this + * @param {String} html + */ + 'sync', + /** + * @event push + * Fires when the iframe editor is updated with content from the textarea. + * @param {Ext.form.field.HtmlEditor} this + * @param {String} html + */ + 'push', + /** + * @event editmodechange + * Fires when the editor switches edit modes + * @param {Ext.form.field.HtmlEditor} this + * @param {Boolean} sourceEdit True if source edit, false if standard editing. + */ + 'editmodechange' + ); + + me.callParent(arguments); + me.createToolbar(me); + + // Init mixins + me.initLabelable(); + me.initField(); + }, + + /** + * @private + * Must define this function to allow the Layout base class to collect all descendant layouts to be run. + */ + getRefItems: function() { + return [ this.toolbar ]; + }, + + /* + * Called when the editor creates its toolbar. Override this method if you need to + * add custom toolbar buttons. + * @param {Ext.form.field.HtmlEditor} editor + * @protected + */ + createToolbar : function(editor){ + var me = this, + items = [], i, + tipsEnabled = Ext.tip.QuickTipManager && Ext.tip.QuickTipManager.isEnabled(), + baseCSSPrefix = Ext.baseCSSPrefix, + fontSelectItem, toolbar, undef; + + function btn(id, toggle, handler){ + return { + itemId : id, + cls : baseCSSPrefix + 'btn-icon', + iconCls: baseCSSPrefix + 'edit-'+id, + enableToggle:toggle !== false, + scope: editor, + handler:handler||editor.relayBtnCmd, + clickEvent: 'mousedown', + tooltip: tipsEnabled ? editor.buttonTips[id] || undef : undef, + overflowText: editor.buttonTips[id].title || undef, + tabIndex: -1 + }; + } + + + if (me.enableFont && !Ext.isSafari2) { + fontSelectItem = Ext.widget('component', { + renderTpl: [ + '' + ], + renderData: { + cls: baseCSSPrefix + 'font-select', + fonts: me.fontFamilies, + defaultFont: me.defaultFont + }, + childEls: ['selectEl'], + afterRender: function() { + me.fontSelect = this.selectEl; + Ext.Component.prototype.afterRender.apply(this, arguments); + }, + onDisable: function() { + var selectEl = this.selectEl; + if (selectEl) { + selectEl.dom.disabled = true; + } + Ext.Component.prototype.onDisable.apply(this, arguments); + }, + onEnable: function() { + var selectEl = this.selectEl; + if (selectEl) { + selectEl.dom.disabled = false; + } + Ext.Component.prototype.onEnable.apply(this, arguments); + }, + listeners: { + change: function() { + me.relayCmd('fontname', me.fontSelect.dom.value); + me.deferFocus(); + }, + element: 'selectEl' + } + }); + + items.push( + fontSelectItem, + '-' + ); + } + + if (me.enableFormat) { + items.push( + btn('bold'), + btn('italic'), + btn('underline') + ); + } + + if (me.enableFontSize) { + items.push( + '-', + btn('increasefontsize', false, me.adjustFont), + btn('decreasefontsize', false, me.adjustFont) + ); + } + + if (me.enableColors) { + items.push( + '-', { + itemId: 'forecolor', + cls: baseCSSPrefix + 'btn-icon', + iconCls: baseCSSPrefix + 'edit-forecolor', + overflowText: editor.buttonTips.forecolor.title, + tooltip: tipsEnabled ? editor.buttonTips.forecolor || undef : undef, + tabIndex:-1, + menu : Ext.widget('menu', { + plain: true, + items: [{ + xtype: 'colorpicker', + allowReselect: true, + focus: Ext.emptyFn, + value: '000000', + plain: true, + clickEvent: 'mousedown', + handler: function(cp, color) { + me.execCmd('forecolor', Ext.isWebKit || Ext.isIE ? '#'+color : color); + me.deferFocus(); + this.up('menu').hide(); + } + }] + }) + }, { + itemId: 'backcolor', + cls: baseCSSPrefix + 'btn-icon', + iconCls: baseCSSPrefix + 'edit-backcolor', + overflowText: editor.buttonTips.backcolor.title, + tooltip: tipsEnabled ? editor.buttonTips.backcolor || undef : undef, + tabIndex:-1, + menu : Ext.widget('menu', { + plain: true, + items: [{ + xtype: 'colorpicker', + focus: Ext.emptyFn, + value: 'FFFFFF', + plain: true, + allowReselect: true, + clickEvent: 'mousedown', + handler: function(cp, color) { + if (Ext.isGecko) { + me.execCmd('useCSS', false); + me.execCmd('hilitecolor', color); + me.execCmd('useCSS', true); + me.deferFocus(); + } else { + me.execCmd(Ext.isOpera ? 'hilitecolor' : 'backcolor', Ext.isWebKit || Ext.isIE ? '#'+color : color); + me.deferFocus(); + } + this.up('menu').hide(); + } + }] + }) + } + ); + } + + if (me.enableAlignments) { + items.push( + '-', + btn('justifyleft'), + btn('justifycenter'), + btn('justifyright') + ); + } + + if (!Ext.isSafari2) { + if (me.enableLinks) { + items.push( + '-', + btn('createlink', false, me.createLink) + ); + } + + if (me.enableLists) { + items.push( + '-', + btn('insertorderedlist'), + btn('insertunorderedlist') + ); + } + if (me.enableSourceEdit) { + items.push( + '-', + btn('sourceedit', true, function(btn){ + me.toggleSourceEdit(!me.sourceEditMode); + }) + ); + } + } + + // Everything starts disabled. + for (i = 0; i < items.length; i++) { + if (items[i].itemId !== 'sourceedit') { + items[i].disabled = true; + } + } + + // build the toolbar + // Automatically rendered in AbstractComponent.afterRender's renderChildren call + toolbar = Ext.widget('toolbar', { + id: me.id + '-toolbar', + ownerCt: me, + cls: Ext.baseCSSPrefix + 'html-editor-tb', + enableOverflow: true, + items: items, + ownerLayout: me.getComponentLayout(), + + // stop form submits + listeners: { + click: function(e){ + e.preventDefault(); + }, + element: 'el' + } + }); + + me.toolbar = toolbar; + }, + + getMaskTarget: function(){ + return this.bodyEl; + }, + + /** + * Sets the read only state of this field. + * @param {Boolean} readOnly Whether the field should be read only. + */ + setReadOnly: function(readOnly) { + var me = this, + textareaEl = me.textareaEl, + iframeEl = me.iframeEl, + body; + + me.readOnly = readOnly; + + if (textareaEl) { + textareaEl.dom.readOnly = readOnly; + } + + if (me.initialized) { + body = me.getEditorBody(); + if (Ext.isIE) { + // Hide the iframe while setting contentEditable so it doesn't grab focus + iframeEl.setDisplayed(false); + body.contentEditable = !readOnly; + iframeEl.setDisplayed(true); + } else { + me.setDesignMode(!readOnly); + } + if (body) { + body.style.cursor = readOnly ? 'default' : 'text'; + } + me.disableItems(readOnly); + } + }, + + /** + * 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). + * + * **Note:** IE8-Standards has unwanted scroller behavior, so the default meta tag forces IE7 compatibility. + * Also note that forcing IE7 mode works when the page is loaded normally, but if you are using IE's Web + * Developer Tools to manually set the document mode, that will take precedence and override what this + * code sets by default. This can be confusing when developing, but is not a user-facing issue. + * @protected + */ + getDocMarkup: function() { + var me = this, + h = me.iframeEl.getHeight() - me.iframePad * 2; + return Ext.String.format('', me.iframePad, h); + }, + + // private + getEditorBody: function() { + var doc = this.getDoc(); + return doc.body || doc.documentElement; + }, + + // private + getDoc: function() { + return (!Ext.isIE && this.iframeEl.dom.contentDocument) || this.getWin().document; + }, + + // private + getWin: function() { + return Ext.isIE ? this.iframeEl.dom.contentWindow : window.frames[this.iframeEl.dom.name]; + }, + + // Do the job of a container layout at this point even though we are not a Container. + // TODO: Refactor as a Container. + finishRenderChildren: function () { + this.callParent(); + this.toolbar.finishRender(); + }, + + // private + onRender: function() { + var me = this; + + me.callParent(arguments); + + // The input element is interrogated by the layout to extract height when labelAlign is 'top' + // It must be set, and then switched between the iframe and the textarea + me.inputEl = me.iframeEl; + + // Start polling for when the iframe document is ready to be manipulated + me.monitorTask = Ext.TaskManager.start({ + run: me.checkDesignMode, + scope: me, + interval: 100 + }); + }, + + initRenderTpl: function() { + var me = this; + if (!me.hasOwnProperty('renderTpl')) { + me.renderTpl = me.getTpl('labelableRenderTpl'); + } + return me.callParent(); + }, + + initRenderData: function() { + return Ext.applyIf(this.callParent(), this.getLabelableRenderData()); + }, + + getSubTplData: function() { + return { + $comp : this, + cmpId : this.id, + id : this.getInputId(), + textareaCls : Ext.baseCSSPrefix + 'hidden', + value : this.value, + iframeName : Ext.id(), + iframeSrc : Ext.SSL_SECURE_URL, + size : 'height:100px;width:100%' + }; + }, + + getSubTplMarkup: function() { + return this.getTpl('fieldSubTpl').apply(this.getSubTplData()); + }, + + initFrameDoc: function() { + var me = this, + doc, task; + + Ext.TaskManager.stop(me.monitorTask); + + doc = me.getDoc(); + me.win = me.getWin(); + + doc.open(); + doc.write(me.getDocMarkup()); + doc.close(); + + task = { // must defer to wait for browser to be ready + run: function() { + var doc = me.getDoc(); + if (doc.body || doc.readyState === 'complete') { + Ext.TaskManager.stop(task); + me.setDesignMode(true); + Ext.defer(me.initEditor, 10, me); + } + }, + interval : 10, + duration:10000, + scope: me + }; + Ext.TaskManager.start(task); + }, + + checkDesignMode: function() { + var me = this, + doc = me.getDoc(); + if (doc && (!doc.editorInitialized || me.getDesignMode() !== 'on')) { + me.initFrameDoc(); + } + }, + + /** + * @private + * Sets current design mode. To enable, mode can be true or 'on', off otherwise + */ + setDesignMode: function(mode) { + var me = this, + doc = me.getDoc(); + if (doc) { + if (me.readOnly) { + mode = false; + } + doc.designMode = (/on|true/i).test(String(mode).toLowerCase()) ?'on':'off'; + } + }, + + // private + getDesignMode: function() { + var doc = this.getDoc(); + return !doc ? '' : String(doc.designMode).toLowerCase(); + }, + + disableItems: function(disabled) { + var items = this.getToolbar().items.items, + i, + iLen = items.length, + item; + + for (i = 0; i < iLen; i++) { + item = items[i]; + + if (item.getItemId() !== 'sourceedit') { + item.setDisabled(disabled); + } + } + }, + + /** + * Toggles the editor between standard and source edit mode. + * @param {Boolean} [sourceEditMode] True for source edit, false for standard + */ + toggleSourceEdit: function(sourceEditMode) { + var me = this, + iframe = me.iframeEl, + textarea = me.textareaEl, + hiddenCls = Ext.baseCSSPrefix + 'hidden', + btn = me.getToolbar().getComponent('sourceedit'); + + if (!Ext.isBoolean(sourceEditMode)) { + sourceEditMode = !me.sourceEditMode; + } + me.sourceEditMode = sourceEditMode; + + if (btn.pressed !== sourceEditMode) { + btn.toggle(sourceEditMode); + } + if (sourceEditMode) { + me.disableItems(true); + me.syncValue(); + iframe.addCls(hiddenCls); + textarea.removeCls(hiddenCls); + textarea.dom.removeAttribute('tabIndex'); + textarea.focus(); + me.inputEl = textarea; + } + else { + if (me.initialized) { + me.disableItems(me.readOnly); + } + me.pushValue(); + iframe.removeCls(hiddenCls); + textarea.addCls(hiddenCls); + textarea.dom.setAttribute('tabIndex', -1); + me.deferFocus(); + me.inputEl = iframe; + } + me.fireEvent('editmodechange', me, sourceEditMode); + me.updateLayout(); + }, + + // private used internally + createLink : function() { + var url = prompt(this.createLinkText, this.defaultLinkValue); + if (url && url !== 'http:/'+'/') { + this.relayCmd('createlink', url); + } + }, + + clearInvalid: Ext.emptyFn, + + // docs inherit from Field + setValue: function(value) { + var me = this, + textarea = me.textareaEl; + me.mixins.field.setValue.call(me, value); + if (value === null || value === undefined) { + value = ''; + } + if (textarea) { + textarea.dom.value = value; + } + me.pushValue(); + return this; + }, + + /** + * 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 + * @protected + */ + 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. We need the + * parseInt here because charCodeAt will return a number. + */ + if (html.charCodeAt(0) === parseInt(this.defaultValue.replace(/\D/g, ''), 10)) { + html = html.substring(1); + } + return html; + }, + + /** + * Syncs the contents of the editor iframe with the textarea. + * @protected + */ + syncValue : function(){ + var me = this, + body, changed, html, bodyStyle, match, oldValue; + + if (me.initialized) { + body = me.getEditorBody(); + html = body.innerHTML; + if (Ext.isWebKit) { + bodyStyle = body.getAttribute('style'); // Safari puts text-align styles on the body element! + match = bodyStyle.match(/text-align:(.*?);/i); + if (match && match[1]) { + html = '
    ' + html + '
    '; + } + } + html = me.cleanHtml(html); + if (me.fireEvent('beforesync', me, html) !== false) { + if (me.textareaEl.dom.value != html) { + me.textareaEl.dom.value = html; + changed = true; + } + + me.fireEvent('sync', me, html); + + if (changed) { + // we have to guard this to avoid infinite recursion because getValue + // calls this method... + me.checkChange(); + } + } + } + }, + + //docs inherit from Field + getValue : function() { + var me = this, + value; + if (!me.sourceEditMode) { + me.syncValue(); + } + value = me.rendered ? me.textareaEl.dom.value : me.value; + me.value = value; + return value; + }, + + /** + * Pushes the value of the textarea into the iframe editor. + * @protected + */ + pushValue: function() { + var me = this, + v; + if(me.initialized){ + v = me.textareaEl.dom.value || ''; + if (!me.activated && v.length < 1) { + v = me.defaultValue; + } + if (me.fireEvent('beforepush', me, v) !== false) { + me.getEditorBody().innerHTML = v; + if (Ext.isGecko) { + // Gecko hack, see: https://bugzilla.mozilla.org/show_bug.cgi?id=232791#c8 + me.setDesignMode(false); //toggle off first + me.setDesignMode(true); + } + me.fireEvent('push', me, v); + } + } + }, + + // private + deferFocus : function(){ + this.focus(false, true); + }, + + getFocusEl: function() { + var me = this, + win = me.win; + return win && !me.sourceEditMode ? win : me.textareaEl; + }, + + // private + initEditor : function(){ + //Destroying the component during/before initEditor can cause issues. + try { + var me = this, + dbody = me.getEditorBody(), + ss = me.textareaEl.getStyles('font-size', 'font-family', 'background-image', 'background-repeat', 'background-color', 'color'), + doc, + fn; + + ss['background-attachment'] = 'fixed'; // w3c + dbody.bgProperties = 'fixed'; // ie + + Ext.DomHelper.applyStyles(dbody, ss); + + doc = me.getDoc(); + + if (doc) { + try { + Ext.EventManager.removeAll(doc); + } catch(e) {} + } + + /* + * We need to use createDelegate here, because when using buffer, the delayed task is added + * as a property to the function. When the listener is removed, the task is deleted from the function. + * Since onEditorEvent is shared on the prototype, if we have multiple html editors, the first time one of the editors + * is destroyed, it causes the fn to be deleted from the prototype, which causes errors. Essentially, we're just anonymizing the function. + */ + fn = Ext.Function.bind(me.onEditorEvent, me); + Ext.EventManager.on(doc, { + mousedown: fn, + dblclick: fn, + click: fn, + keyup: fn, + buffer:100 + }); + + // These events need to be relayed from the inner document (where they stop + // bubbling) up to the outer document. This has to be done at the DOM level so + // the event reaches listeners on elements like the document body. The effected + // mechanisms that depend on this bubbling behavior are listed to the right + // of the event. + fn = me.onRelayedEvent; + Ext.EventManager.on(doc, { + mousedown: fn, // menu dismisal (MenuManager) and Window onMouseDown (toFront) + mousemove: fn, // window resize drag detection + mouseup: fn, // window resize termination + click: fn, // not sure, but just to be safe + dblclick: fn, // not sure again + scope: me + }); + + if (Ext.isGecko) { + Ext.EventManager.on(doc, 'keypress', me.applyCommand, me); + } + if (me.fixKeys) { + Ext.EventManager.on(doc, 'keydown', me.fixKeys, me); + } + + // We need to be sure we remove all our events from the iframe on unload or we're going to LEAK! + Ext.EventManager.on(window, 'unload', me.beforeDestroy, me); + doc.editorInitialized = true; + + me.initialized = true; + me.pushValue(); + me.setReadOnly(me.readOnly); + me.fireEvent('initialize', me); + } catch(ex) { + // ignore (why?) + } + }, + + // private + beforeDestroy : function(){ + var me = this, + monitorTask = me.monitorTask, + doc, prop; + + if (monitorTask) { + Ext.TaskManager.stop(monitorTask); + } + if (me.rendered) { + try { + doc = me.getDoc(); + if (doc) { + Ext.EventManager.removeAll(doc); + for (prop in doc) { + if (doc.hasOwnProperty && doc.hasOwnProperty(prop)) { + delete doc[prop]; + } + } + } + } catch(e) { + // ignore (why?) + } + Ext.destroyMembers(me, 'toolbar', 'iframeEl', 'textareaEl'); + } + me.callParent(); + }, + + // private + onRelayedEvent: function (event) { + // relay event from the iframe's document to the document that owns the iframe... + + var iframeEl = this.iframeEl, + iframeXY = iframeEl.getXY(), + eventXY = event.getXY(); + + // the event from the inner document has XY relative to that document's origin, + // so adjust it to use the origin of the iframe in the outer document: + event.xy = [iframeXY[0] + eventXY[0], iframeXY[1] + eventXY[1]]; + + event.injectEvent(iframeEl); // blame the iframe for the event... + + event.xy = eventXY; // restore the original XY (just for safety) + }, + + // private + onFirstFocus : function(){ + var me = this, + selection, range; + me.activated = true; + me.disableItems(me.readOnly); + if (Ext.isGecko) { // prevent silly gecko errors + me.win.focus(); + selection = me.win.getSelection(); + if (!selection.focusNode || selection.focusNode.nodeType !== 3) { + range = selection.getRangeAt(0); + range.selectNodeContents(me.getEditorBody()); + range.collapse(true); + me.deferFocus(); + } + try { + me.execCmd('useCSS', true); + me.execCmd('styleWithCSS', false); + } catch(e) { + // ignore (why?) + } + } + me.fireEvent('activate', me); + }, + + // private + adjustFont: function(btn) { + var adjust = btn.getItemId() === 'increasefontsize' ? 1 : -1, + size = this.getDoc().queryCommandValue('FontSize') || '2', + isPxSize = Ext.isString(size) && size.indexOf('px') !== -1, + isSafari; + size = parseInt(size, 10); + if (isPxSize) { + // Safari 3 values + // 1 = 10px, 2 = 13px, 3 = 16px, 4 = 18px, 5 = 24px, 6 = 32px + if (size <= 10) { + size = 1 + adjust; + } + else if (size <= 13) { + size = 2 + adjust; + } + else if (size <= 16) { + size = 3 + adjust; + } + else if (size <= 18) { + size = 4 + adjust; + } + else if (size <= 24) { + size = 5 + adjust; + } + else { + size = 6 + adjust; + } + size = Ext.Number.constrain(size, 1, 6); + } else { + isSafari = Ext.isSafari; + if (isSafari) { // safari + adjust *= 2; + } + size = Math.max(1, size + adjust) + (isSafari ? 'px' : 0); + } + this.execCmd('FontSize', size); + }, + + // private + onEditorEvent: function(e) { + this.updateToolbar(); + }, + + /** + * Triggers a toolbar update by reading the markup state of the current selection in the editor. + * @protected + */ + updateToolbar: function() { + var me = this, + btns, doc, name, fontSelect; + + if (me.readOnly) { + return; + } + + if (!me.activated) { + me.onFirstFocus(); + return; + } + + btns = me.getToolbar().items.map; + doc = me.getDoc(); + + if (me.enableFont && !Ext.isSafari2) { + name = (doc.queryCommandValue('FontName') || me.defaultFont).toLowerCase(); + fontSelect = me.fontSelect.dom; + if (name !== fontSelect.value) { + fontSelect.value = name; + } + } + + function updateButtons() { + for (var i = 0, l = arguments.length, name; i < l; i++) { + name = arguments[i]; + btns[name].toggle(doc.queryCommandState(name)); + } + } + if(me.enableFormat){ + updateButtons('bold', 'italic', 'underline'); + } + if(me.enableAlignments){ + updateButtons('justifyleft', 'justifycenter', 'justifyright'); + } + if(!Ext.isSafari2 && me.enableLists){ + updateButtons('insertorderedlist', 'insertunorderedlist'); + } + + Ext.menu.Manager.hideAll(); + + me.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=null] The value to pass to the command + */ + relayCmd: function(cmd, value) { + Ext.defer(function() { + var me = this; + me.focus(); + me.execCmd(cmd, value); + me.updateToolbar(); + }, 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=null] The value to pass to the command + */ + execCmd : function(cmd, value){ + var me = this, + doc = me.getDoc(), + undef; + doc.execCommand(cmd, false, value === undef ? null : value); + me.syncValue(); + }, + + // private + applyCommand : function(e){ + if (e.ctrlKey) { + var me = this, + 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) { + me.win.focus(); + me.execCmd(cmd); + me.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){ + var me = this, + range; + + if (me.activated) { + me.win.focus(); + if (Ext.isIE) { + range = me.getDoc().selection.createRange(); + if (range) { + range.pasteHTML(text); + me.syncValue(); + me.deferFocus(); + } + }else{ + me.execCmd('InsertHTML', text); + me.deferFocus(); + } + } + }, + + // private + fixKeys: (function() { // load time branching for fastest keydown performance + if (Ext.isIE) { + return function(e){ + var me = this, + k = e.getKey(), + doc = me.getDoc(), + readOnly = me.readOnly, + range, target; + + if (k === e.TAB) { + e.stopEvent(); + if (!readOnly) { + range = doc.selection.createRange(); + if(range){ + range.collapse(true); + range.pasteHTML('    '); + me.deferFocus(); + } + } + } + else if (k === e.ENTER) { + if (!readOnly) { + range = doc.selection.createRange(); + if (range) { + target = range.parentElement(); + if(!target || target.tagName.toLowerCase() !== 'li'){ + e.stopEvent(); + range.pasteHTML('
    '); + range.collapse(false); + range.select(); + } + } + } + } + }; + } + + if (Ext.isOpera) { + return function(e){ + var me = this; + if (e.getKey() === e.TAB) { + e.stopEvent(); + if (!me.readOnly) { + me.win.focus(); + me.execCmd('InsertHTML','    '); + me.deferFocus(); + } + } + }; + } + + if (Ext.isWebKit) { + return function(e){ + var me = this, + k = e.getKey(), + readOnly = me.readOnly; + + if (k === e.TAB) { + e.stopEvent(); + if (!readOnly) { + me.execCmd('InsertText','\t'); + me.deferFocus(); + } + } + else if (k === e.ENTER) { + e.stopEvent(); + if (!readOnly) { + me.execCmd('InsertHtml','

    '); + me.deferFocus(); + } + } + }; + } + + return null; // not needed, so null + }()), + + /** + * Returns the editor's toolbar. **This is only available after the editor has been rendered.** + * @return {Ext.toolbar.Toolbar} + */ + getToolbar : function(){ + return this.toolbar; + }, + + /** + * @property {Object} buttonTips + * 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' + * }, + * ... + */ + // + buttonTips : { + bold : { + title: 'Bold (Ctrl+B)', + text: 'Make the selected text bold.', + cls: Ext.baseCSSPrefix + 'html-editor-tip' + }, + italic : { + title: 'Italic (Ctrl+I)', + text: 'Make the selected text italic.', + cls: Ext.baseCSSPrefix + 'html-editor-tip' + }, + underline : { + title: 'Underline (Ctrl+U)', + text: 'Underline the selected text.', + cls: Ext.baseCSSPrefix + 'html-editor-tip' + }, + increasefontsize : { + title: 'Grow Text', + text: 'Increase the font size.', + cls: Ext.baseCSSPrefix + 'html-editor-tip' + }, + decreasefontsize : { + title: 'Shrink Text', + text: 'Decrease the font size.', + cls: Ext.baseCSSPrefix + 'html-editor-tip' + }, + backcolor : { + title: 'Text Highlight Color', + text: 'Change the background color of the selected text.', + cls: Ext.baseCSSPrefix + 'html-editor-tip' + }, + forecolor : { + title: 'Font Color', + text: 'Change the color of the selected text.', + cls: Ext.baseCSSPrefix + 'html-editor-tip' + }, + justifyleft : { + title: 'Align Text Left', + text: 'Align text to the left.', + cls: Ext.baseCSSPrefix + 'html-editor-tip' + }, + justifycenter : { + title: 'Center Text', + text: 'Center text in the editor.', + cls: Ext.baseCSSPrefix + 'html-editor-tip' + }, + justifyright : { + title: 'Align Text Right', + text: 'Align text to the right.', + cls: Ext.baseCSSPrefix + 'html-editor-tip' + }, + insertunorderedlist : { + title: 'Bullet List', + text: 'Start a bulleted list.', + cls: Ext.baseCSSPrefix + 'html-editor-tip' + }, + insertorderedlist : { + title: 'Numbered List', + text: 'Start a numbered list.', + cls: Ext.baseCSSPrefix + 'html-editor-tip' + }, + createlink : { + title: 'Hyperlink', + text: 'Make the selected text a hyperlink.', + cls: Ext.baseCSSPrefix + 'html-editor-tip' + }, + sourceedit : { + title: 'Source Edit', + text: 'Switch to source editing mode.', + cls: Ext.baseCSSPrefix + 'html-editor-tip' + } + } + // + + // hide stuff that is not compatible + /** + * @event blur + * @private + */ + /** + * @event focus + * @private + */ + /** + * @event specialkey + * @private + */ + /** + * @cfg {String} fieldCls + * @private + */ + /** + * @cfg {String} focusCls + * @private + */ + /** + * @cfg {String} autoCreate + * @private + */ + /** + * @cfg {String} inputType + * @private + */ + /** + * @cfg {String} invalidCls + * @private + */ + /** + * @cfg {String} invalidText + * @private + */ + /** + * @cfg {String} msgFx + * @private + */ + /** + * @cfg {Boolean} allowDomMove + * @private + */ + /** + * @cfg {String} applyTo + * @private + */ + /** + * @cfg {String} readOnly + * @private + */ + /** + * @cfg {String} tabIndex + * @private + */ + /** + * @method validate + * @private + */ +}); + +/** + * This class is used to display small visual icons in the header of a panel. There are a set of + * 25 icons that can be specified by using the {@link #type} config. The {@link #handler} config + * can be used to provide a function that will respond to any click events. In general, this class + * will not be instantiated directly, rather it will be created by specifying the {@link Ext.panel.Panel#tools} + * configuration on the Panel itself. + * + * @example + * Ext.create('Ext.panel.Panel', { + * width: 200, + * height: 200, + * renderTo: document.body, + * title: 'A Panel', + * tools: [{ + * type: 'help', + * handler: function(){ + * // show help here + * } + * }, { + * itemId: 'refresh', + * type: 'refresh', + * hidden: true, + * handler: function(){ + * // do refresh + * } + * }, { + * type: 'search', + * handler: function(event, target, owner, tool){ + * // do search + * owner.child('#refresh').show(); + * } + * }] + * }); + */ +Ext.define('Ext.panel.Tool', { + extend: 'Ext.Component', + requires: ['Ext.tip.QuickTipManager'], + alias: 'widget.tool', + + baseCls: Ext.baseCSSPrefix + 'tool', + disabledCls: Ext.baseCSSPrefix + 'tool-disabled', + toolPressedCls: Ext.baseCSSPrefix + 'tool-pressed', + toolOverCls: Ext.baseCSSPrefix + 'tool-over', + ariaRole: 'button', + + childEls: [ + 'toolEl' + ], + + renderTpl: [ + '' + ], + + /** + * @cfg {Function} handler + * A function to execute when the tool is clicked. Arguments passed are: + * + * - **event** : Ext.EventObject - The click event. + * - **toolEl** : Ext.Element - The tool Element. + * - **owner** : Ext.panel.Header - The host panel header. + * - **tool** : Ext.panel.Tool - The tool object + */ + + /** + * @cfg {Object} scope + * The scope to execute the {@link #handler} function. Defaults to the tool. + */ + + /** + * @cfg {String} type + * The type of tool to render. The following types are available: + * + * - close + * - minimize + * - maximize + * - restore + * - toggle + * - gear + * - prev + * - next + * - pin + * - unpin + * - right + * - left + * - down + * - up + * - refresh + * - plus + * - minus + * - search + * - save + * - help + * - print + * - expand + * - collapse + */ + + /** + * @cfg {String/Object} tooltip + * The tooltip for the tool - can be a string to be used as innerHTML (html tags are accepted) or QuickTips config + * object + */ + + /** + * @cfg {String} tooltipType + * The type of tooltip to use. Either 'qtip' (default) for QuickTips or 'title' for title attribute. + */ + tooltipType: 'qtip', + + /** + * @cfg {Boolean} stopEvent + * Specify as false to allow click event to propagate. + */ + stopEvent: true, + + height: 15, + width: 15, + + _toolTypes: { + close:1, + collapse:1, + down:1, + expand:1, + gear:1, + help:1, + left:1, + maximize:1, + minimize:1, + minus:1, + //move:1, + next:1, + pin:1, + plus:1, + prev:1, + print:1, + refresh:1, + //resize:1, + restore:1, + right:1, + save:1, + search:1, + toggle:1, + unpin:1, + up:1 + }, + + initComponent: function() { + var me = this; + me.addEvents( + /** + * @event click + * Fires when the tool is clicked + * @param {Ext.panel.Tool} this + * @param {Ext.EventObject} e The event object + */ + 'click' + ); + + if (me.id && me._toolTypes[me.id] && Ext.global.console) { + Ext.global.console.warn('When specifying a tool you should use the type option, the id can conflict now that tool is a Component'); + } + + me.type = me.type || me.id; + + Ext.applyIf(me.renderData, { + baseCls: me.baseCls, + blank: Ext.BLANK_IMAGE_URL, + type: me.type + }); + + // alias qtip, should use tooltip since it's what we have in the docs + me.tooltip = me.tooltip || me.qtip; + me.callParent(); + me.on({ + element: 'toolEl', + click: me.onClick, + mousedown: me.onMouseDown, + mouseover: me.onMouseOver, + mouseout: me.onMouseOut, + scope: me + }); + }, + + // inherit docs + afterRender: function() { + var me = this, + attr; + + me.callParent(arguments); + if (me.tooltip) { + if (Ext.isObject(me.tooltip)) { + Ext.tip.QuickTipManager.register(Ext.apply({ + target: me.id + }, me.tooltip)); + } + else { + attr = me.tooltipType == 'qtip' ? 'data-qtip' : 'title'; + me.toolEl.dom.setAttribute(attr, me.tooltip); + } + } + }, + + getFocusEl: function() { + return this.el; + }, + + /** + * Sets the type of the tool. Allows the icon to be changed. + * @param {String} type The new type. See the {@link #type} config. + * @return {Ext.panel.Tool} this + */ + setType: function(type) { + var me = this; + + me.type = type; + if (me.rendered) { + me.toolEl.dom.className = me.baseCls + '-' + type; + } + return me; + }, + + /** + * Binds this tool to a component. + * @private + * @param {Ext.Component} component The component + */ + bindTo: function(component) { + this.owner = component; + }, + + /** + * Called when the tool element is clicked + * @private + * @param {Ext.EventObject} e + * @param {HTMLElement} target The target element + */ + onClick: function(e, target) { + var me = this, + owner; + + if (me.disabled) { + return false; + } + owner = me.owner || me.ownerCt; + + //remove the pressed + over class + me.el.removeCls(me.toolPressedCls); + me.el.removeCls(me.toolOverCls); + + if (me.stopEvent !== false) { + e.stopEvent(); + } + + Ext.callback(me.handler, me.scope || me, [e, target, owner, me]); + me.fireEvent('click', me, e); + return true; + }, + + // inherit docs + onDestroy: function(){ + if (Ext.isObject(this.tooltip)) { + Ext.tip.QuickTipManager.unregister(this.id); + } + this.callParent(); + }, + + /** + * Called when the user presses their mouse button down on a tool + * Adds the press class ({@link #toolPressedCls}) + * @private + */ + onMouseDown: function() { + if (this.disabled) { + return false; + } + + this.el.addCls(this.toolPressedCls); + }, + + /** + * Called when the user rolls over a tool + * Adds the over class ({@link #toolOverCls}) + * @private + */ + onMouseOver: function() { + if (this.disabled) { + return false; + } + this.el.addCls(this.toolOverCls); + }, + + /** + * Called when the user rolls out from a tool. + * Removes the over class ({@link #toolOverCls}) + * @private + */ + onMouseOut: function() { + this.el.removeCls(this.toolOverCls); + } +}); + +/** + * As the number of records increases, the time required for the browser to render them increases. Paging is used to + * reduce the amount of data exchanged with the client. Note: if there are more records/rows than can be viewed in the + * available screen area, vertical scrollbars will be added. + * + * Paging is typically handled on the server side (see exception below). The client sends parameters to the server side, + * which the server needs to interpret and then respond with the appropriate data. + * + * Ext.toolbar.Paging is a specialized toolbar that is bound to a {@link Ext.data.Store} and provides automatic + * paging control. This Component {@link Ext.data.Store#method-load load}s blocks of data into the {@link #store} by passing + * parameters used for paging criteria. + * + * {@img Ext.toolbar.Paging/Ext.toolbar.Paging.png Ext.toolbar.Paging component} + * + * Paging Toolbar is typically used as one of the Grid's toolbars: + * + * @example + * var itemsPerPage = 2; // set the number of items you want per page + * + * var store = Ext.create('Ext.data.Store', { + * id:'simpsonsStore', + * autoLoad: false, + * fields:['name', 'email', 'phone'], + * pageSize: itemsPerPage, // items per page + * proxy: { + * type: 'ajax', + * url: 'pagingstore.js', // url that will load data with respect to start and limit params + * reader: { + * type: 'json', + * root: 'items', + * totalProperty: 'total' + * } + * } + * }); + * + * // specify segment of data you want to load using params + * store.load({ + * params:{ + * start:0, + * limit: itemsPerPage + * } + * }); + * + * Ext.create('Ext.grid.Panel', { + * title: 'Simpsons', + * store: store, + * columns: [ + * { header: 'Name', dataIndex: 'name' }, + * { header: 'Email', dataIndex: 'email', flex: 1 }, + * { header: 'Phone', dataIndex: 'phone' } + * ], + * width: 400, + * height: 125, + * dockedItems: [{ + * xtype: 'pagingtoolbar', + * store: store, // same store GridPanel is using + * dock: 'bottom', + * displayInfo: true + * }], + * renderTo: Ext.getBody() + * }); + * + * To use paging, pass the paging requirements to the server when the store is first loaded. + * + * store.load({ + * params: { + * // specify params for the first page load if using paging + * start: 0, + * limit: myPageSize, + * // other params + * foo: 'bar' + * } + * }); + * + * If using {@link Ext.data.Store#autoLoad store's autoLoad} configuration: + * + * var myStore = Ext.create('Ext.data.Store', { + * {@link Ext.data.Store#autoLoad autoLoad}: {start: 0, limit: 25}, + * ... + * }); + * + * The packet sent back from the server would have this form: + * + * { + * "success": true, + * "results": 2000, + * "rows": [ // ***Note:** this must be an Array + * { "id": 1, "name": "Bill", "occupation": "Gardener" }, + * { "id": 2, "name": "Ben", "occupation": "Horticulturalist" }, + * ... + * { "id": 25, "name": "Sue", "occupation": "Botanist" } + * ] + * } + * + * ## Paging with Local Data + * + * Paging can also be accomplished with local data using extensions: + * + * - [Ext.ux.data.PagingStore][1] + * - Paging Memory Proxy (examples/ux/PagingMemoryProxy.js) + * + * [1]: http://sencha.com/forum/showthread.php?t=71532 + */ +Ext.define('Ext.toolbar.Paging', { + extend: 'Ext.toolbar.Toolbar', + alias: 'widget.pagingtoolbar', + alternateClassName: 'Ext.PagingToolbar', + requires: ['Ext.toolbar.TextItem', 'Ext.form.field.Number'], + mixins: { + bindable: 'Ext.util.Bindable' + }, + /** + * @cfg {Ext.data.Store} store (required) + * The {@link Ext.data.Store} the paging toolbar should use as its data source. + */ + + /** + * @cfg {Boolean} displayInfo + * true to display the displayMsg + */ + displayInfo: false, + + /** + * @cfg {Boolean} prependButtons + * true to insert any configured items _before_ the paging buttons. + */ + prependButtons: false, + + /** + * @cfg {String} displayMsg + * The paging status message to display. Note that this string is + * formatted using the braced numbers {0}-{2} as tokens that are replaced by the values for start, end and total + * respectively. These tokens should be preserved when overriding this string if showing those values is desired. + */ + // + displayMsg : 'Displaying {0} - {1} of {2}', + // + + /** + * @cfg {String} emptyMsg + * The message to display when no records are found. + */ + // + emptyMsg : 'No data to display', + // + + /** + * @cfg {String} beforePageText + * The text displayed before the input item. + */ + // + beforePageText : 'Page', + // + + /** + * @cfg {String} afterPageText + * Customizable piece of the default paging text. Note that this string is formatted using + * {0} as a token that is replaced by the number of total pages. This token should be preserved when overriding this + * string if showing the total page count is desired. + */ + // + afterPageText : 'of {0}', + // + + /** + * @cfg {String} firstText + * The quicktip text displayed for the first page button. + * **Note**: quick tips must be initialized for the quicktip to show. + */ + // + firstText : 'First Page', + // + + /** + * @cfg {String} prevText + * The quicktip text displayed for the previous page button. + * **Note**: quick tips must be initialized for the quicktip to show. + */ + // + prevText : 'Previous Page', + // + + /** + * @cfg {String} nextText + * The quicktip text displayed for the next page button. + * **Note**: quick tips must be initialized for the quicktip to show. + */ + // + nextText : 'Next Page', + // + + /** + * @cfg {String} lastText + * The quicktip text displayed for the last page button. + * **Note**: quick tips must be initialized for the quicktip to show. + */ + // + lastText : 'Last Page', + // + + /** + * @cfg {String} refreshText + * The quicktip text displayed for the Refresh button. + * **Note**: quick tips must be initialized for the quicktip to show. + */ + // + refreshText : 'Refresh', + // + + /** + * @cfg {Number} inputItemWidth + * The width in pixels of the input field used to display and change the current page number. + */ + inputItemWidth : 30, + + /** + * Gets the standard paging items in the toolbar + * @private + */ + getPagingItems: function() { + var me = this; + + return [{ + itemId: 'first', + tooltip: me.firstText, + overflowText: me.firstText, + iconCls: Ext.baseCSSPrefix + 'tbar-page-first', + disabled: true, + handler: me.moveFirst, + scope: me + },{ + itemId: 'prev', + tooltip: me.prevText, + overflowText: me.prevText, + iconCls: Ext.baseCSSPrefix + 'tbar-page-prev', + disabled: true, + handler: me.movePrevious, + scope: me + }, + '-', + me.beforePageText, + { + xtype: 'numberfield', + itemId: 'inputItem', + name: 'inputItem', + cls: Ext.baseCSSPrefix + 'tbar-page-number', + allowDecimals: false, + minValue: 1, + hideTrigger: true, + enableKeyEvents: true, + keyNavEnabled: false, + selectOnFocus: true, + submitValue: false, + // mark it as not a field so the form will not catch it when getting fields + isFormField: false, + width: me.inputItemWidth, + margins: '-1 2 3 2', + listeners: { + scope: me, + keydown: me.onPagingKeyDown, + blur: me.onPagingBlur + } + },{ + xtype: 'tbtext', + itemId: 'afterTextItem', + text: Ext.String.format(me.afterPageText, 1) + }, + '-', + { + itemId: 'next', + tooltip: me.nextText, + overflowText: me.nextText, + iconCls: Ext.baseCSSPrefix + 'tbar-page-next', + disabled: true, + handler: me.moveNext, + scope: me + },{ + itemId: 'last', + tooltip: me.lastText, + overflowText: me.lastText, + iconCls: Ext.baseCSSPrefix + 'tbar-page-last', + disabled: true, + handler: me.moveLast, + scope: me + }, + '-', + { + itemId: 'refresh', + tooltip: me.refreshText, + overflowText: me.refreshText, + iconCls: Ext.baseCSSPrefix + 'tbar-loading', + handler: me.doRefresh, + scope: me + }]; + }, + + initComponent : function(){ + var me = this, + pagingItems = me.getPagingItems(), + userItems = me.items || me.buttons || []; + + if (me.prependButtons) { + me.items = userItems.concat(pagingItems); + } else { + me.items = pagingItems.concat(userItems); + } + delete me.buttons; + + if (me.displayInfo) { + me.items.push('->'); + me.items.push({xtype: 'tbtext', itemId: 'displayItem'}); + } + + me.callParent(); + + me.addEvents( + /** + * @event change + * Fires after the active page has been changed. + * @param {Ext.toolbar.Paging} this + * @param {Object} pageData An object that has these properties: + * + * - `total` : Number + * + * The total number of records in the dataset as returned by the server + * + * - `currentPage` : Number + * + * The current page number + * + * - `pageCount` : Number + * + * The total number of pages (calculated from the total number of records in the dataset as returned by the + * server and the current {@link Ext.data.Store#pageSize pageSize}) + * + * - `toRecord` : Number + * + * The starting record index for the current page + * + * - `fromRecord` : Number + * + * The ending record index for the current page + */ + 'change', + + /** + * @event beforechange + * Fires just before the active page is changed. Return false to prevent the active page from being changed. + * @param {Ext.toolbar.Paging} this + * @param {Number} page The page number that will be loaded on change + */ + 'beforechange' + ); + me.on('beforerender', me.onLoad, me, {single: true}); + + me.bindStore(me.store || 'ext-empty-store', true); + }, + // private + updateInfo : function(){ + var me = this, + displayItem = me.child('#displayItem'), + store = me.store, + pageData = me.getPageData(), + count, msg; + + if (displayItem) { + count = store.getCount(); + if (count === 0) { + msg = me.emptyMsg; + } else { + msg = Ext.String.format( + me.displayMsg, + pageData.fromRecord, + pageData.toRecord, + pageData.total + ); + } + displayItem.setText(msg); + } + }, + + // private + onLoad : function(){ + var me = this, + pageData, + currPage, + pageCount, + afterText, + count, + isEmpty; + + count = me.store.getCount(); + isEmpty = count === 0; + if (!isEmpty) { + pageData = me.getPageData(); + currPage = pageData.currentPage; + pageCount = pageData.pageCount; + afterText = Ext.String.format(me.afterPageText, isNaN(pageCount) ? 1 : pageCount); + } else { + currPage = 0; + pageCount = 0; + afterText = Ext.String.format(me.afterPageText, 0); + } + + Ext.suspendLayouts(); + me.child('#afterTextItem').setText(afterText); + me.child('#inputItem').setDisabled(isEmpty).setValue(currPage); + me.child('#first').setDisabled(currPage === 1 || isEmpty); + me.child('#prev').setDisabled(currPage === 1 || isEmpty); + me.child('#next').setDisabled(currPage === pageCount || isEmpty); + me.child('#last').setDisabled(currPage === pageCount || isEmpty); + me.child('#refresh').enable(); + me.updateInfo(); + Ext.resumeLayouts(true); + + if (me.rendered) { + me.fireEvent('change', me, pageData); + } + }, + + // private + getPageData : function(){ + var store = this.store, + totalCount = store.getTotalCount(); + + return { + total : totalCount, + currentPage : store.currentPage, + pageCount: Math.ceil(totalCount / store.pageSize), + fromRecord: ((store.currentPage - 1) * store.pageSize) + 1, + toRecord: Math.min(store.currentPage * store.pageSize, totalCount) + + }; + }, + + // private + onLoadError : function(){ + if (!this.rendered) { + return; + } + this.child('#refresh').enable(); + }, + + // private + readPageFromInput : function(pageData){ + var v = this.child('#inputItem').getValue(), + pageNum = parseInt(v, 10); + + if (!v || isNaN(pageNum)) { + this.child('#inputItem').setValue(pageData.currentPage); + return false; + } + return pageNum; + }, + + onPagingFocus : function(){ + this.child('#inputItem').select(); + }, + + //private + onPagingBlur : function(e){ + var curPage = this.getPageData().currentPage; + this.child('#inputItem').setValue(curPage); + }, + + // private + onPagingKeyDown : function(field, e){ + var me = this, + k = e.getKey(), + pageData = me.getPageData(), + increment = e.shiftKey ? 10 : 1, + pageNum; + + if (k == e.RETURN) { + e.stopEvent(); + pageNum = me.readPageFromInput(pageData); + if (pageNum !== false) { + pageNum = Math.min(Math.max(1, pageNum), pageData.pageCount); + if(me.fireEvent('beforechange', me, pageNum) !== false){ + me.store.loadPage(pageNum); + } + } + } else if (k == e.HOME || k == e.END) { + e.stopEvent(); + pageNum = k == e.HOME ? 1 : pageData.pageCount; + field.setValue(pageNum); + } else if (k == e.UP || k == e.PAGE_UP || k == e.DOWN || k == e.PAGE_DOWN) { + e.stopEvent(); + pageNum = me.readPageFromInput(pageData); + if (pageNum) { + if (k == e.DOWN || k == e.PAGE_DOWN) { + increment *= -1; + } + pageNum += increment; + if (pageNum >= 1 && pageNum <= pageData.pageCount) { + field.setValue(pageNum); + } + } + } + }, + + // private + beforeLoad : function(){ + if(this.rendered && this.refresh){ + this.refresh.disable(); + } + }, + + /** + * Move to the first page, has the same effect as clicking the 'first' button. + */ + moveFirst : function(){ + if (this.fireEvent('beforechange', this, 1) !== false){ + this.store.loadPage(1); + } + }, + + /** + * Move to the previous page, has the same effect as clicking the 'previous' button. + */ + movePrevious : function(){ + var me = this, + prev = me.store.currentPage - 1; + + if (prev > 0) { + if (me.fireEvent('beforechange', me, prev) !== false) { + me.store.previousPage(); + } + } + }, + + /** + * Move to the next page, has the same effect as clicking the 'next' button. + */ + moveNext : function(){ + var me = this, + total = me.getPageData().pageCount, + next = me.store.currentPage + 1; + + if (next <= total) { + if (me.fireEvent('beforechange', me, next) !== false) { + me.store.nextPage(); + } + } + }, + + /** + * Move to the last page, has the same effect as clicking the 'last' button. + */ + moveLast : function(){ + var me = this, + last = me.getPageData().pageCount; + + if (me.fireEvent('beforechange', me, last) !== false) { + me.store.loadPage(last); + } + }, + + /** + * Refresh the current page, has the same effect as clicking the 'refresh' button. + */ + doRefresh : function(){ + var me = this, + current = me.store.currentPage; + + if (me.fireEvent('beforechange', me, current) !== false) { + me.store.loadPage(current); + } + }, + + getStoreListeners: function() { + return { + beforeload: this.beforeLoad, + load: this.onLoad, + exception: this.onLoadError + }; + }, + + /** + * Unbinds the paging toolbar from the specified {@link Ext.data.Store} **(deprecated)** + * @param {Ext.data.Store} store The data store to unbind + */ + unbind : function(store){ + this.bindStore(null); + }, + + /** + * Binds the paging toolbar to the specified {@link Ext.data.Store} **(deprecated)** + * @param {Ext.data.Store} store The data store to bind + */ + bind : function(store){ + this.bindStore(store); + }, + + // private + onDestroy : function(){ + this.unbind(); + this.callParent(); + } +}); + +/** + * Provides indentation and folder structure markup for a Tree taking into account + * depth and position within the tree hierarchy. + * + * @private + */ +Ext.define('Ext.tree.Column', { + extend: 'Ext.grid.column.Column', + alias: 'widget.treecolumn', + + tdCls: Ext.baseCSSPrefix + 'grid-cell-treecolumn', + + initComponent: function() { + var origRenderer = this.renderer || this.defaultRenderer, + origScope = this.scope || window; + + this.renderer = function(value, metaData, record, rowIdx, colIdx, store, view) { + var buf = [], + format = Ext.String.format, + depth = record.getDepth(), + treePrefix = Ext.baseCSSPrefix + 'tree-', + elbowPrefix = treePrefix + 'elbow-', + expanderCls = treePrefix + 'expander', + imgText = '', + checkboxText= '', + formattedValue = origRenderer.apply(origScope, arguments), + href = record.get('href'), + target = record.get('hrefTarget'), + cls = record.get('cls'); + + while (record) { + if (!record.isRoot() || (record.isRoot() && view.rootVisible)) { + if (record.getDepth() === depth) { + buf.unshift(format(imgText, + treePrefix + 'icon ' + + treePrefix + 'icon' + (record.get('icon') ? '-inline ' : (record.isLeaf() ? '-leaf ' : '-parent ')) + + (record.get('iconCls') || ''), + record.get('icon') || Ext.BLANK_IMAGE_URL + )); + if (record.get('checked') !== null) { + buf.unshift(format( + checkboxText, + (treePrefix + 'checkbox') + (record.get('checked') ? ' ' + treePrefix + 'checkbox-checked' : ''), + record.get('checked') ? 'aria-checked="true"' : '' + )); + if (record.get('checked')) { + metaData.tdCls += (' ' + treePrefix + 'checked'); + } + } + if (record.isLast()) { + if (record.isExpandable()) { + buf.unshift(format(imgText, (elbowPrefix + 'end-plus ' + expanderCls), Ext.BLANK_IMAGE_URL)); + } else { + buf.unshift(format(imgText, (elbowPrefix + 'end'), Ext.BLANK_IMAGE_URL)); + } + + } else { + if (record.isExpandable()) { + buf.unshift(format(imgText, (elbowPrefix + 'plus ' + expanderCls), Ext.BLANK_IMAGE_URL)); + } else { + buf.unshift(format(imgText, (treePrefix + 'elbow'), Ext.BLANK_IMAGE_URL)); + } + } + } else { + if (record.isLast() || record.getDepth() === 0) { + buf.unshift(format(imgText, (elbowPrefix + 'empty'), Ext.BLANK_IMAGE_URL)); + } else if (record.getDepth() !== 0) { + buf.unshift(format(imgText, (elbowPrefix + 'line'), Ext.BLANK_IMAGE_URL)); + } + } + } + record = record.parentNode; + } + if (href) { + buf.push('', formattedValue, ''); + } else { + buf.push(formattedValue); + } + if (cls) { + metaData.tdCls += ' ' + cls; + } + return buf.join(''); + }; + this.callParent(arguments); + }, + + defaultRenderer: function(value) { + return value; + } +}); +/** + * @private + */ +Ext.define('Ext.view.DragZone', { + extend: 'Ext.dd.DragZone', + containerScroll: false, + + constructor: function(config) { + var me = this; + + Ext.apply(me, config); + + // Create a ddGroup unless one has been configured. + // User configuration of ddGroups allows users to specify which + // DD instances can interact with each other. Using one + // based on the id of the View would isolate it and mean it can only + // interact with a DropZone on the same View also using a generated ID. + if (!me.ddGroup) { + me.ddGroup = 'view-dd-zone-' + me.view.id; + } + + // Ext.dd.DragDrop instances are keyed by the ID of their encapsulating element. + // So a View's DragZone cannot use the View's main element because the DropZone must use that + // because the DropZone may need to scroll on hover at a scrolling boundary, and it is the View's + // main element which handles scrolling. + // We use the View's parent element to drag from. Ideally, we would use the internal structure, but that + // is transient; DataView's recreate the internal structure dynamically as data changes. + // TODO: Ext 5.0 DragDrop must allow multiple DD objects to share the same element. + me.callParent([me.view.el.dom.parentNode]); + + me.ddel = Ext.get(document.createElement('div')); + me.ddel.addCls(Ext.baseCSSPrefix + 'grid-dd-wrap'); + }, + + init: function(id, sGroup, config) { + this.initTarget(id, sGroup, config); + this.view.mon(this.view, { + itemmousedown: this.onItemMouseDown, + scope: this + }); + }, + + onItemMouseDown: function(view, record, item, index, e) { + if (!this.isPreventDrag(e, record, item, index)) { + this.handleMouseDown(e); + + // If we want to allow dragging of multi-selections, then veto the following handlers (which, in the absence of ctrlKey, would deselect) + // if the mousedowned record is selected + if (view.getSelectionModel().selectionMode == 'MULTI' && !e.ctrlKey && view.getSelectionModel().isSelected(record)) { + return false; + } + } + }, + + // private template method + isPreventDrag: function(e) { + return false; + }, + + getDragData: function(e) { + var view = this.view, + item = e.getTarget(view.getItemSelector()); + + if (item) { + return { + copy: view.copy || (view.allowCopy && e.ctrlKey), + event: new Ext.EventObjectImpl(e), + view: view, + ddel: this.ddel, + item: item, + records: view.getSelectionModel().getSelection(), + fromPosition: Ext.fly(item).getXY() + }; + } + }, + + onInitDrag: function(x, y) { + var me = this, + data = me.dragData, + view = data.view, + selectionModel = view.getSelectionModel(), + record = view.getRecord(data.item), + e = data.event; + + // Update the selection to match what would have been selected if the user had + // done a full click on the target node rather than starting a drag from it + if (!selectionModel.isSelected(record) || e.hasModifier()) { + selectionModel.selectWithEvent(record, e, true); + } + data.records = selectionModel.getSelection(); + + me.ddel.update(me.getDragText()); + me.proxy.update(me.ddel.dom); + me.onStartDrag(x, y); + return true; + }, + + getDragText: function() { + var count = this.dragData.records.length; + return Ext.String.format(this.dragText, count, count == 1 ? '' : 's'); + }, + + getRepairXY : function(e, data){ + return data ? data.fromPosition : false; + } +}); +/** + * @private + */ +Ext.define('Ext.tree.ViewDragZone', { + extend: 'Ext.view.DragZone', + + isPreventDrag: function(e, record) { + return (record.get('allowDrag') === false) || !!e.getTarget(this.view.expanderSelector); + }, + + afterRepair: function() { + var me = this, + view = me.view, + selectedRowCls = view.selectedItemCls, + records = me.dragData.records, + r, + rLen = records.length, + fly = Ext.fly, + item; + + if (Ext.enableFx && me.repairHighlight) { + // Roll through all records and highlight all the ones we attempted to drag. + for (r = 0; r < rLen; r++) { + // anonymous fns below, don't hoist up unless below is wrapped in + // a self-executing function passing in item. + item = view.getNode(records[r]); + + // We must remove the selected row class before animating, because + // the selected row class declares !important on its background-color. + fly(item.firstChild).highlight(me.repairHighlightColor, { + listeners: { + beforeanimate: function() { + if (view.isSelected(item)) { + fly(item).removeCls(selectedRowCls); + } + }, + afteranimate: function() { + if (view.isSelected(item)) { + fly(item).addCls(selectedRowCls); + } + } + } + }); + } + + } + me.dragging = false; + } +}); +/** + * @private + */ +Ext.define('Ext.view.DropZone', { + extend: 'Ext.dd.DropZone', + + indicatorHtml: '
    ', + indicatorCls: Ext.baseCSSPrefix + 'grid-drop-indicator', + + constructor: function(config) { + var me = this; + Ext.apply(me, config); + + // Create a ddGroup unless one has been configured. + // User configuration of ddGroups allows users to specify which + // DD instances can interact with each other. Using one + // based on the id of the View would isolate it and mean it can only + // interact with a DragZone on the same View also using a generated ID. + if (!me.ddGroup) { + me.ddGroup = 'view-dd-zone-' + me.view.id; + } + + // The DropZone's encapsulating element is the View's main element. It must be this because drop gestures + // may require scrolling on hover near a scrolling boundary. In Ext 4.x two DD instances may not use the + // same element, so a DragZone on this same View must use the View's parent element as its element. + me.callParent([me.view.el]); + }, + +// Fire an event through the client DataView. Lock this DropZone during the event processing so that +// its data does not become corrupted by processing mouse events. + fireViewEvent: function() { + var me = this, + result; + + me.lock(); + result = me.view.fireEvent.apply(me.view, arguments); + me.unlock(); + return result; + }, + + getTargetFromEvent : function(e) { + var node = e.getTarget(this.view.getItemSelector()), + mouseY, nodeList, testNode, i, len, box; + +// Not over a row node: The content may be narrower than the View's encapsulating element, so return the closest. +// If we fall through because the mouse is below the nodes (or there are no nodes), we'll get an onContainerOver call. + if (!node) { + mouseY = e.getPageY(); + for (i = 0, nodeList = this.view.getNodes(), len = nodeList.length; i < len; i++) { + testNode = nodeList[i]; + box = Ext.fly(testNode).getBox(); + if (mouseY <= box.bottom) { + return testNode; + } + } + } + return node; + }, + + getIndicator: function() { + var me = this; + + if (!me.indicator) { + me.indicator = new Ext.Component({ + html: me.indicatorHtml, + cls: me.indicatorCls, + ownerCt: me.view, + floating: true, + shadow: false + }); + } + return me.indicator; + }, + + getPosition: function(e, node) { + var y = e.getXY()[1], + region = Ext.fly(node).getRegion(), + pos; + + if ((region.bottom - y) >= (region.bottom - region.top) / 2) { + pos = "before"; + } else { + pos = "after"; + } + return pos; + }, + + /** + * @private Determines whether the record at the specified offset from the passed record + * is in the drag payload. + * @param records + * @param record + * @param offset + * @returns {Boolean} True if the targeted record is in the drag payload + */ + containsRecordAtOffset: function(records, record, offset) { + if (!record) { + return false; + } + var view = this.view, + recordIndex = view.indexOf(record), + nodeBefore = view.getNode(recordIndex + offset), + recordBefore = nodeBefore ? view.getRecord(nodeBefore) : null; + + return recordBefore && Ext.Array.contains(records, recordBefore); + }, + + positionIndicator: function(node, data, e) { + var me = this, + view = me.view, + pos = me.getPosition(e, node), + overRecord = view.getRecord(node), + draggingRecords = data.records, + indicatorY; + + if (!Ext.Array.contains(draggingRecords, overRecord) && ( + pos == 'before' && !me.containsRecordAtOffset(draggingRecords, overRecord, -1) || + pos == 'after' && !me.containsRecordAtOffset(draggingRecords, overRecord, 1) + )) { + me.valid = true; + + if (me.overRecord != overRecord || me.currentPosition != pos) { + + indicatorY = Ext.fly(node).getY() - view.el.getY() - 1; + if (pos == 'after') { + indicatorY += Ext.fly(node).getHeight(); + } + me.getIndicator().setWidth(Ext.fly(view.el).getWidth()).showAt(0, indicatorY); + + // Cache the overRecord and the 'before' or 'after' indicator. + me.overRecord = overRecord; + me.currentPosition = pos; + } + } else { + me.invalidateDrop(); + } + }, + + invalidateDrop: function() { + if (this.valid) { + this.valid = false; + this.getIndicator().hide(); + } + }, + + // The mouse is over a View node + onNodeOver: function(node, dragZone, e, data) { + var me = this; + + if (!Ext.Array.contains(data.records, me.view.getRecord(node))) { + me.positionIndicator(node, data, e); + } + return me.valid ? me.dropAllowed : me.dropNotAllowed; + }, + + // Moved out of the DropZone without dropping. + // Remove drop position indicator + notifyOut: function(node, dragZone, e, data) { + var me = this; + + me.callParent(arguments); + delete me.overRecord; + delete me.currentPosition; + if (me.indicator) { + me.indicator.hide(); + } + }, + + // The mouse is past the end of all nodes (or there are no nodes) + onContainerOver : function(dd, e, data) { + var me = this, + view = me.view, + count = view.store.getCount(); + + // There are records, so position after the last one + if (count) { + me.positionIndicator(view.getNode(count - 1), data, e); + } + + // No records, position the indicator at the top + else { + delete me.overRecord; + delete me.currentPosition; + me.getIndicator().setWidth(Ext.fly(view.el).getWidth()).showAt(0, 0); + me.valid = true; + } + return me.dropAllowed; + }, + + onContainerDrop : function(dd, e, data) { + return this.onNodeDrop(dd, null, e, data); + }, + + onNodeDrop: function(node, dragZone, e, data) { + var me = this, + dropHandled = false, + + // Create a closure to perform the operation which the event handler may use. + // Users may now set the wait parameter in the beforedrop handler, and perform any kind + // of asynchronous processing such as an Ext.Msg.confirm, or an Ajax request, + // and complete the drop gesture at some point in the future by calling either the + // processDrop or cancelDrop methods. + dropHandlers = { + wait: false, + processDrop: function () { + me.invalidateDrop(); + me.handleNodeDrop(data, me.overRecord, me.currentPosition); + dropHandled = true; + me.fireViewEvent('drop', node, data, me.overRecord, me.currentPosition); + }, + + cancelDrop: function() { + me.invalidateDrop(); + dropHandled = true; + } + }, + performOperation = false; + + if (me.valid) { + performOperation = me.fireViewEvent('beforedrop', node, data, me.overRecord, me.currentPosition, dropHandlers); + if (dropHandlers.wait) { + return; + } + + if (performOperation !== false) { + // If either of the drop handlers were called in the event handler, do not do it again. + if (!dropHandled) { + dropHandlers.processDrop(); + } + } + } + return performOperation; + }, + + destroy: function(){ + Ext.destroy(this.indicator); + delete this.indicator; + this.callParent(); + } +}); + +/** + * @private + */ +Ext.define('Ext.grid.ViewDropZone', { + extend: 'Ext.view.DropZone', + + indicatorHtml: '
    ', + indicatorCls: Ext.baseCSSPrefix + 'grid-drop-indicator', + + handleNodeDrop : function(data, record, position) { + var view = this.view, + store = view.getStore(), + index, records, i, len; + + // If the copy flag is set, create a copy of the Models with the same IDs + if (data.copy) { + records = data.records; + data.records = []; + for (i = 0, len = records.length; i < len; i++) { + data.records.push(records[i].copy(records[i].getId())); + } + } else { + /* + * Remove from the source store. We do this regardless of whether the store + * is the same bacsue the store currently doesn't handle moving records + * within the store. In the future it should be possible to do this. + * Here was pass the isMove parameter if we're moving to the same view. + */ + data.view.store.remove(data.records, data.view === view); + } + + index = store.indexOf(record); + + // 'after', or undefined (meaning a drop at index -1 on an empty View)... + if (position !== 'before') { + index++; + } + store.insert(index, data.records); + view.getSelectionModel().select(data.records); + } +}); +/** + * @private + */ +Ext.define('Ext.tree.ViewDropZone', { + extend: 'Ext.view.DropZone', + + /** + * @cfg {Boolean} allowParentInsert + * Allow inserting a dragged node between an expanded parent node and its first child that will become a + * sibling of the parent when dropped. + */ + allowParentInserts: false, + + /** + * @cfg {String} allowContainerDrop + * True if drops on the tree container (outside of a specific tree node) are allowed. + */ + allowContainerDrops: false, + + /** + * @cfg {String} appendOnly + * True if the tree should only allow append drops (use for trees which are sorted). + */ + appendOnly: false, + + /** + * @cfg {String} expandDelay + * The delay in milliseconds to wait before expanding a target tree node while dragging a droppable node + * over the target. + */ + expandDelay : 500, + + indicatorCls: Ext.baseCSSPrefix + 'tree-ddindicator', + + // private + expandNode : function(node) { + var view = this.view; + if (!node.isLeaf() && !node.isExpanded()) { + view.expand(node); + this.expandProcId = false; + } + }, + + // private + queueExpand : function(node) { + this.expandProcId = Ext.Function.defer(this.expandNode, this.expandDelay, this, [node]); + }, + + // private + cancelExpand : function() { + if (this.expandProcId) { + clearTimeout(this.expandProcId); + this.expandProcId = false; + } + }, + + getPosition: function(e, node) { + var view = this.view, + record = view.getRecord(node), + y = e.getPageY(), + noAppend = record.isLeaf(), + noBelow = false, + region = Ext.fly(node).getRegion(), + fragment; + + // If we are dragging on top of the root node of the tree, we always want to append. + if (record.isRoot()) { + return 'append'; + } + + // Return 'append' if the node we are dragging on top of is not a leaf else return false. + if (this.appendOnly) { + return noAppend ? false : 'append'; + } + + if (!this.allowParentInsert) { + noBelow = record.hasChildNodes() && record.isExpanded(); + } + + fragment = (region.bottom - region.top) / (noAppend ? 2 : 3); + if (y >= region.top && y < (region.top + fragment)) { + return 'before'; + } + else if (!noBelow && (noAppend || (y >= (region.bottom - fragment) && y <= region.bottom))) { + return 'after'; + } + else { + return 'append'; + } + }, + + isValidDropPoint : function(node, position, dragZone, e, data) { + if (!node || !data.item) { + return false; + } + + var view = this.view, + targetNode = view.getRecord(node), + draggedRecords = data.records, + dataLength = draggedRecords.length, + ln = draggedRecords.length, + i, record; + + // No drop position, or dragged records: invalid drop point + if (!(targetNode && position && dataLength)) { + return false; + } + + // If the targetNode is within the folder we are dragging + for (i = 0; i < ln; i++) { + record = draggedRecords[i]; + if (record.isNode && record.contains(targetNode)) { + return false; + } + } + + // Respect the allowDrop field on Tree nodes + if (position === 'append' && targetNode.get('allowDrop') === false) { + return false; + } + else if (position != 'append' && targetNode.parentNode.get('allowDrop') === false) { + return false; + } + + // If the target record is in the dragged dataset, then invalid drop + if (Ext.Array.contains(draggedRecords, targetNode)) { + return false; + } + + // @TODO: fire some event to notify that there is a valid drop possible for the node you're dragging + // Yes: this.fireViewEvent(blah....) fires an event through the owning View. + return true; + }, + + onNodeOver : function(node, dragZone, e, data) { + var position = this.getPosition(e, node), + returnCls = this.dropNotAllowed, + view = this.view, + targetNode = view.getRecord(node), + indicator = this.getIndicator(), + indicatorX = 0, + indicatorY = 0; + + // auto node expand check + this.cancelExpand(); + if (position == 'append' && !this.expandProcId && !Ext.Array.contains(data.records, targetNode) && !targetNode.isLeaf() && !targetNode.isExpanded()) { + this.queueExpand(targetNode); + } + + + if (this.isValidDropPoint(node, position, dragZone, e, data)) { + this.valid = true; + this.currentPosition = position; + this.overRecord = targetNode; + + indicator.setWidth(Ext.fly(node).getWidth()); + indicatorY = Ext.fly(node).getY() - Ext.fly(view.el).getY() - 1; + + /* + * In the code below we show the proxy again. The reason for doing this is showing the indicator will + * call toFront, causing it to get a new z-index which can sometimes push the proxy behind it. We always + * want the proxy to be above, so calling show on the proxy will call toFront and bring it forward. + */ + if (position == 'before') { + returnCls = targetNode.isFirst() ? Ext.baseCSSPrefix + 'tree-drop-ok-above' : Ext.baseCSSPrefix + 'tree-drop-ok-between'; + indicator.showAt(0, indicatorY); + dragZone.proxy.show(); + } else if (position == 'after') { + returnCls = targetNode.isLast() ? Ext.baseCSSPrefix + 'tree-drop-ok-below' : Ext.baseCSSPrefix + 'tree-drop-ok-between'; + indicatorY += Ext.fly(node).getHeight(); + indicator.showAt(0, indicatorY); + dragZone.proxy.show(); + } else { + returnCls = Ext.baseCSSPrefix + 'tree-drop-ok-append'; + // @TODO: set a class on the parent folder node to be able to style it + indicator.hide(); + } + } else { + this.valid = false; + } + + this.currentCls = returnCls; + return returnCls; + }, + + onContainerOver : function(dd, e, data) { + return e.getTarget('.' + this.indicatorCls) ? this.currentCls : this.dropNotAllowed; + }, + + notifyOut: function() { + this.callParent(arguments); + this.cancelExpand(); + }, + + handleNodeDrop : function(data, targetNode, position) { + var me = this, + view = me.view, + parentNode = targetNode.parentNode, + store = view.getStore(), + recordDomNodes = [], + records, i, len, + insertionMethod, argList, + needTargetExpand, + transferData, + processDrop; + + // If the copy flag is set, create a copy of the Models with the same IDs + if (data.copy) { + records = data.records; + data.records = []; + for (i = 0, len = records.length; i < len; i++) { + data.records.push(Ext.apply({}, records[i].data)); + } + } + + // Cancel any pending expand operation + me.cancelExpand(); + + // Grab a reference to the correct node insertion method. + // Create an arg list array intended for the apply method of the + // chosen node insertion method. + // Ensure the target object for the method is referenced by 'targetNode' + if (position == 'before') { + insertionMethod = parentNode.insertBefore; + argList = [null, targetNode]; + targetNode = parentNode; + } + else if (position == 'after') { + if (targetNode.nextSibling) { + insertionMethod = parentNode.insertBefore; + argList = [null, targetNode.nextSibling]; + } + else { + insertionMethod = parentNode.appendChild; + argList = [null]; + } + targetNode = parentNode; + } + else { + if (!targetNode.isExpanded()) { + needTargetExpand = true; + } + insertionMethod = targetNode.appendChild; + argList = [null]; + } + + // A function to transfer the data into the destination tree + transferData = function() { + var node, + r, rLen, color, n; + for (i = 0, len = data.records.length; i < len; i++) { + argList[0] = data.records[i]; + node = insertionMethod.apply(targetNode, argList); + + if (Ext.enableFx && me.dropHighlight) { + recordDomNodes.push(view.getNode(node)); + } + } + + // Kick off highlights after everything's been inserted, so they are + // more in sync without insertion/render overhead. + if (Ext.enableFx && me.dropHighlight) { + //FIXME: the check for n.firstChild is not a great solution here. Ideally the line should simply read + //Ext.fly(n.firstChild) but this yields errors in IE6 and 7. See ticket EXTJSIV-1705 for more details + rLen = recordDomNodes.length; + color = me.dropHighlightColor; + + for (r = 0; r < rLen; r++) { + n = recordDomNodes[r]; + + if (n) { + Ext.fly(n.firstChild ? n.firstChild : n).highlight(color); + } + } + } + }; + + // If dropping right on an unexpanded node, transfer the data after it is expanded. + if (needTargetExpand) { + targetNode.expand(false, transferData); + } + // Otherwise, call the data transfer function immediately + else { + transferData(); + } + } +}); +/** + * Produces optimized XTemplates for chunks of tables to be + * used in grids, trees and other table based widgets. + */ +Ext.define('Ext.view.TableChunker', { + singleton: true, + requires: ['Ext.XTemplate'], + metaTableTpl: [ + '{%if (this.openTableWrap)out.push(this.openTableWrap())%}', + '', + '', + '', + '', + '', + '', + '', + '{[this.openRows()]}', + '{row}', + '', + '{[this.embedFeature(values, parent, xindex, xcount)]}', + '', + '{[this.closeRows()]}', + '', + '
    ', + '{%if (this.closeTableWrap)out.push(this.closeTableWrap())%}' + ], + + constructor: function() { + Ext.XTemplate.prototype.recurse = function(values, reference) { + return this.apply(reference ? values[reference] : values); + }; + }, + + embedFeature: function(values, parent, x, xcount) { + var tpl = ''; + if (!values.disabled) { + tpl = values.getFeatureTpl(values, parent, x, xcount); + } + return tpl; + }, + + embedFullWidth: function(values) { + var result = 'style="width:{fullWidth}px;'; + + // If there are no records, we need to give the table a height so that it + // is displayed and causes q scrollbar if the width exceeds the View's width. + if (!values.rowCount) { + result += 'height:1px;'; + } + return result + '"'; + }, + + openRows: function() { + return ''; + }, + + closeRows: function() { + return ''; + }, + + metaRowTpl: [ + '', + '', + '', + '
    {{id}}
    ', + '', + '
    ', + '' + ], + + firstOrLastCls: function(xindex, xcount) { + if (xindex === 1) { + return Ext.view.Table.prototype.firstCls; + } else if (xindex === xcount) { + return Ext.view.Table.prototype.lastCls; + } + }, + + embedRowCls: function() { + return '{rowCls}'; + }, + + embedRowAttr: function() { + return '{rowAttr}'; + }, + + openTableWrap: undefined, + + closeTableWrap: undefined, + + getTableTpl: function(cfg, textOnly) { + var tpl, + tableTplMemberFns = { + openRows: this.openRows, + closeRows: this.closeRows, + embedFeature: this.embedFeature, + embedFullWidth: this.embedFullWidth, + openTableWrap: this.openTableWrap, + closeTableWrap: this.closeTableWrap + }, + tplMemberFns = {}, + features = cfg.features || [], + ln = features.length, + i = 0, + memberFns = { + embedRowCls: this.embedRowCls, + embedRowAttr: this.embedRowAttr, + firstOrLastCls: this.firstOrLastCls, + unselectableAttr: cfg.enableTextSelection ? '' : 'unselectable="on"', + unselectableCls: cfg.enableTextSelection ? '' : Ext.baseCSSPrefix + 'unselectable' + }, + // copy the default + metaRowTpl = Array.prototype.slice.call(this.metaRowTpl, 0), + metaTableTpl; + + for (; i < ln; i++) { + if (!features[i].disabled) { + features[i].mutateMetaRowTpl(metaRowTpl); + Ext.apply(memberFns, features[i].getMetaRowTplFragments()); + Ext.apply(tplMemberFns, features[i].getFragmentTpl()); + Ext.apply(tableTplMemberFns, features[i].getTableFragments()); + } + } + + metaRowTpl = new Ext.XTemplate(metaRowTpl.join(''), memberFns); + cfg.row = metaRowTpl.applyTemplate(cfg); + + metaTableTpl = new Ext.XTemplate(this.metaTableTpl.join(''), tableTplMemberFns); + + tpl = metaTableTpl.applyTemplate(cfg); + + // TODO: Investigate eliminating. + if (!textOnly) { + tpl = new Ext.XTemplate(tpl, tplMemberFns); + } + return tpl; + + } +}); + +/** + * A mechanism for displaying data using custom layout templates and formatting. + * + * The View uses an {@link Ext.XTemplate} as its internal templating mechanism, and is bound to an + * {@link Ext.data.Store} so that as the data in the store changes the view is automatically updated + * to reflect the changes. The view also provides built-in behavior for many common events that can + * occur for its contained items including click, doubleclick, mouseover, mouseout, etc. as well as a + * built-in selection model. **In order to use these features, an {@link #itemSelector} config must + * be provided for the DataView to determine what nodes it will be working with.** + * + * The example below binds a View to a {@link Ext.data.Store} and renders it into an {@link Ext.panel.Panel}. + * + * @example + * Ext.define('Image', { + * extend: 'Ext.data.Model', + * fields: [ + * { name:'src', type:'string' }, + * { name:'caption', type:'string' } + * ] + * }); + * + * Ext.create('Ext.data.Store', { + * id:'imagesStore', + * model: 'Image', + * data: [ + * { src:'http://www.sencha.com/img/20110215-feat-drawing.png', caption:'Drawing & Charts' }, + * { src:'http://www.sencha.com/img/20110215-feat-data.png', caption:'Advanced Data' }, + * { src:'http://www.sencha.com/img/20110215-feat-html5.png', caption:'Overhauled Theme' }, + * { src:'http://www.sencha.com/img/20110215-feat-perf.png', caption:'Performance Tuned' } + * ] + * }); + * + * var imageTpl = new Ext.XTemplate( + * '', + * '
    ', + * '', + * '
    {caption}', + * '
    ', + * '
    ' + * ); + * + * Ext.create('Ext.view.View', { + * store: Ext.data.StoreManager.lookup('imagesStore'), + * tpl: imageTpl, + * itemSelector: 'div.thumb-wrap', + * emptyText: 'No images available', + * renderTo: Ext.getBody() + * }); + */ +Ext.define('Ext.view.View', { + extend: 'Ext.view.AbstractView', + alternateClassName: 'Ext.DataView', + alias: 'widget.dataview', + + inheritableStatics: { + EventMap: { + mousedown: 'MouseDown', + mouseup: 'MouseUp', + click: 'Click', + dblclick: 'DblClick', + contextmenu: 'ContextMenu', + mouseover: 'MouseOver', + mouseout: 'MouseOut', + mouseenter: 'MouseEnter', + mouseleave: 'MouseLeave', + keydown: 'KeyDown', + focus: 'Focus' + } + }, + + addCmpEvents: function() { + this.addEvents( + /** + * @event beforeitemmousedown + * Fires before the mousedown event on an item is processed. Returns false to cancel the default action. + * @param {Ext.view.View} this + * @param {Ext.data.Model} record The record that belongs to the item + * @param {HTMLElement} item The item's element + * @param {Number} index The item's index + * @param {Ext.EventObject} e The raw event object + */ + 'beforeitemmousedown', + /** + * @event beforeitemmouseup + * Fires before the mouseup event on an item is processed. Returns false to cancel the default action. + * @param {Ext.view.View} this + * @param {Ext.data.Model} record The record that belongs to the item + * @param {HTMLElement} item The item's element + * @param {Number} index The item's index + * @param {Ext.EventObject} e The raw event object + */ + 'beforeitemmouseup', + /** + * @event beforeitemmouseenter + * Fires before the mouseenter event on an item is processed. Returns false to cancel the default action. + * @param {Ext.view.View} this + * @param {Ext.data.Model} record The record that belongs to the item + * @param {HTMLElement} item The item's element + * @param {Number} index The item's index + * @param {Ext.EventObject} e The raw event object + */ + 'beforeitemmouseenter', + /** + * @event beforeitemmouseleave + * Fires before the mouseleave event on an item is processed. Returns false to cancel the default action. + * @param {Ext.view.View} this + * @param {Ext.data.Model} record The record that belongs to the item + * @param {HTMLElement} item The item's element + * @param {Number} index The item's index + * @param {Ext.EventObject} e The raw event object + */ + 'beforeitemmouseleave', + /** + * @event beforeitemclick + * Fires before the click event on an item is processed. Returns false to cancel the default action. + * @param {Ext.view.View} this + * @param {Ext.data.Model} record The record that belongs to the item + * @param {HTMLElement} item The item's element + * @param {Number} index The item's index + * @param {Ext.EventObject} e The raw event object + */ + 'beforeitemclick', + /** + * @event beforeitemdblclick + * Fires before the dblclick event on an item is processed. Returns false to cancel the default action. + * @param {Ext.view.View} this + * @param {Ext.data.Model} record The record that belongs to the item + * @param {HTMLElement} item The item's element + * @param {Number} index The item's index + * @param {Ext.EventObject} e The raw event object + */ + 'beforeitemdblclick', + /** + * @event beforeitemcontextmenu + * Fires before the contextmenu event on an item is processed. Returns false to cancel the default action. + * @param {Ext.view.View} this + * @param {Ext.data.Model} record The record that belongs to the item + * @param {HTMLElement} item The item's element + * @param {Number} index The item's index + * @param {Ext.EventObject} e The raw event object + */ + 'beforeitemcontextmenu', + /** + * @event beforeitemkeydown + * Fires before the keydown event on an item is processed. Returns false to cancel the default action. + * @param {Ext.view.View} this + * @param {Ext.data.Model} record The record that belongs to the item + * @param {HTMLElement} item The item's element + * @param {Number} index The item's index + * @param {Ext.EventObject} e The raw event object. Use {@link Ext.EventObject#getKey getKey()} to retrieve the key that was pressed. + */ + 'beforeitemkeydown', + /** + * @event itemmousedown + * Fires when there is a mouse down on an item + * @param {Ext.view.View} this + * @param {Ext.data.Model} record The record that belongs to the item + * @param {HTMLElement} item The item's element + * @param {Number} index The item's index + * @param {Ext.EventObject} e The raw event object + */ + 'itemmousedown', + /** + * @event itemmouseup + * Fires when there is a mouse up on an item + * @param {Ext.view.View} this + * @param {Ext.data.Model} record The record that belongs to the item + * @param {HTMLElement} item The item's element + * @param {Number} index The item's index + * @param {Ext.EventObject} e The raw event object + */ + 'itemmouseup', + /** + * @event itemmouseenter + * Fires when the mouse enters an item. + * @param {Ext.view.View} this + * @param {Ext.data.Model} record The record that belongs to the item + * @param {HTMLElement} item The item's element + * @param {Number} index The item's index + * @param {Ext.EventObject} e The raw event object + */ + 'itemmouseenter', + /** + * @event itemmouseleave + * Fires when the mouse leaves an item. + * @param {Ext.view.View} this + * @param {Ext.data.Model} record The record that belongs to the item + * @param {HTMLElement} item The item's element + * @param {Number} index The item's index + * @param {Ext.EventObject} e The raw event object + */ + 'itemmouseleave', + /** + * @event itemclick + * Fires when an item is clicked. + * @param {Ext.view.View} this + * @param {Ext.data.Model} record The record that belongs to the item + * @param {HTMLElement} item The item's element + * @param {Number} index The item's index + * @param {Ext.EventObject} e The raw event object + */ + 'itemclick', + /** + * @event itemdblclick + * Fires when an item is double clicked. + * @param {Ext.view.View} this + * @param {Ext.data.Model} record The record that belongs to the item + * @param {HTMLElement} item The item's element + * @param {Number} index The item's index + * @param {Ext.EventObject} e The raw event object + */ + 'itemdblclick', + /** + * @event itemcontextmenu + * Fires when an item is right clicked. + * @param {Ext.view.View} this + * @param {Ext.data.Model} record The record that belongs to the item + * @param {HTMLElement} item The item's element + * @param {Number} index The item's index + * @param {Ext.EventObject} e The raw event object + */ + 'itemcontextmenu', + /** + * @event itemkeydown + * Fires when a key is pressed while an item is currently selected. + * @param {Ext.view.View} this + * @param {Ext.data.Model} record The record that belongs to the item + * @param {HTMLElement} item The item's element + * @param {Number} index The item's index + * @param {Ext.EventObject} e The raw event object. Use {@link Ext.EventObject#getKey getKey()} to retrieve the key that was pressed. + */ + 'itemkeydown', + /** + * @event beforecontainermousedown + * Fires before the mousedown event on the container is processed. Returns false to cancel the default action. + * @param {Ext.view.View} this + * @param {Ext.EventObject} e The raw event object + */ + 'beforecontainermousedown', + /** + * @event beforecontainermouseup + * Fires before the mouseup event on the container is processed. Returns false to cancel the default action. + * @param {Ext.view.View} this + * @param {Ext.EventObject} e The raw event object + */ + 'beforecontainermouseup', + /** + * @event beforecontainermouseover + * Fires before the mouseover event on the container is processed. Returns false to cancel the default action. + * @param {Ext.view.View} this + * @param {Ext.EventObject} e The raw event object + */ + 'beforecontainermouseover', + /** + * @event beforecontainermouseout + * Fires before the mouseout event on the container is processed. Returns false to cancel the default action. + * @param {Ext.view.View} this + * @param {Ext.EventObject} e The raw event object + */ + 'beforecontainermouseout', + /** + * @event beforecontainerclick + * Fires before the click event on the container is processed. Returns false to cancel the default action. + * @param {Ext.view.View} this + * @param {Ext.EventObject} e The raw event object + */ + 'beforecontainerclick', + /** + * @event beforecontainerdblclick + * Fires before the dblclick event on the container is processed. Returns false to cancel the default action. + * @param {Ext.view.View} this + * @param {Ext.EventObject} e The raw event object + */ + 'beforecontainerdblclick', + /** + * @event beforecontainercontextmenu + * Fires before the contextmenu event on the container is processed. Returns false to cancel the default action. + * @param {Ext.view.View} this + * @param {Ext.EventObject} e The raw event object + */ + 'beforecontainercontextmenu', + /** + * @event beforecontainerkeydown + * Fires before the keydown event on the container is processed. Returns false to cancel the default action. + * @param {Ext.view.View} this + * @param {Ext.EventObject} e The raw event object. Use {@link Ext.EventObject#getKey getKey()} to retrieve the key that was pressed. + */ + 'beforecontainerkeydown', + /** + * @event containermouseup + * Fires when there is a mouse up on the container + * @param {Ext.view.View} this + * @param {Ext.EventObject} e The raw event object + */ + 'containermouseup', + /** + * @event containermouseover + * Fires when you move the mouse over the container. + * @param {Ext.view.View} this + * @param {Ext.EventObject} e The raw event object + */ + 'containermouseover', + /** + * @event containermouseout + * Fires when you move the mouse out of the container. + * @param {Ext.view.View} this + * @param {Ext.EventObject} e The raw event object + */ + 'containermouseout', + /** + * @event containerclick + * Fires when the container is clicked. + * @param {Ext.view.View} this + * @param {Ext.EventObject} e The raw event object + */ + 'containerclick', + /** + * @event containerdblclick + * Fires when the container is double clicked. + * @param {Ext.view.View} this + * @param {Ext.EventObject} e The raw event object + */ + 'containerdblclick', + /** + * @event containercontextmenu + * Fires when the container is right clicked. + * @param {Ext.view.View} this + * @param {Ext.EventObject} e The raw event object + */ + 'containercontextmenu', + /** + * @event containerkeydown + * Fires when a key is pressed while the container is focused, and no item is currently selected. + * @param {Ext.view.View} this + * @param {Ext.EventObject} e The raw event object. Use {@link Ext.EventObject#getKey getKey()} to retrieve the key that was pressed. + */ + 'containerkeydown', + + /** + * @event selectionchange + * Fires when the selected nodes change. Relayed event from the underlying selection model. + * @param {Ext.view.View} this + * @param {HTMLElement[]} selections Array of the selected nodes + */ + 'selectionchange', + /** + * @event beforeselect + * Fires before a selection is made. If any handlers return false, the selection is cancelled. + * @param {Ext.view.View} this + * @param {HTMLElement} node The node to be selected + * @param {HTMLElement[]} selections Array of currently selected nodes + */ + 'beforeselect', + + /** + * @event highlightitem + * Fires when a node is highlighted using keyboard navigation, or mouseover. + * @param {Ext.view.View} view This View Component. + * @param {Ext.Element} node The highlighted node. + */ + 'highlightitem', + + /** + * @event unhighlightitem + * Fires when a node is unhighlighted using keyboard navigation, or mouseout. + * @param {Ext.view.View} view This View Component. + * @param {Ext.Element} node The previously highlighted node. + */ + 'unhighlightitem' + ); + }, + + getFocusEl: function() { + return this.getTargetEl(); + }, + + // private + afterRender: function(){ + var me = this; + me.callParent(); + me.mon(me.getTargetEl(), { + scope: me, + /* + * We need to make copies of this since some of the events fired here will end up triggering + * a new event to be called and the shared event object will be mutated. In future we should + * investigate if there are any issues with creating a new event object for each event that + * is fired. + */ + freezeEvent: true, + click: me.handleEvent, + mousedown: me.handleEvent, + mouseup: me.handleEvent, + dblclick: me.handleEvent, + contextmenu: me.handleEvent, + mouseover: me.handleEvent, + mouseout: me.handleEvent, + keydown: me.handleEvent + }); + }, + + handleEvent: function(e) { + var key = e.type == 'keydown' && e.getKey(); + + if (this.processUIEvent(e) !== false) { + this.processSpecialEvent(e); + } + + // After all listeners have processed the event, prevent browser's default action + // on SPACE which is to focus the event's target element. + // Focusing causes the browser to attempt to scroll the element into view. + if (key === e.SPACE) { + e.stopEvent(); + } + }, + + // Private template method + processItemEvent: Ext.emptyFn, + processContainerEvent: Ext.emptyFn, + processSpecialEvent: Ext.emptyFn, + + /* + * Returns true if this mouseover/out event is still over the overItem. + */ + stillOverItem: function (event, overItem) { + var nowOver; + + // There is this weird bug when you hover over the border of a cell it is saying + // the target is the table. + // BrowserBug: IE6 & 7. If me.mouseOverItem has been removed and is no longer + // in the DOM then accessing .offsetParent will throw an "Unspecified error." exception. + // typeof'ng and checking to make sure the offsetParent is an object will NOT throw + // this hard exception. + if (overItem && typeof(overItem.offsetParent) === "object") { + // mouseout : relatedTarget == nowOver, target == wasOver + // mouseover: relatedTarget == wasOver, target == nowOver + nowOver = (event.type == 'mouseout') ? event.getRelatedTarget() : event.getTarget(); + return Ext.fly(overItem).contains(nowOver); + } + + return false; + }, + + processUIEvent: function(e) { + var me = this, + item = e.getTarget(me.getItemSelector(), me.getTargetEl()), + map = this.statics().EventMap, + index, record, + type = e.type, + overItem = me.mouseOverItem, + newType; + + if (!item) { + if (type == 'mouseover' && me.stillOverItem(e, overItem)) { + item = overItem; + } + + // Try to get the selected item to handle the keydown event, otherwise we'll just fire a container keydown event + if (type == 'keydown') { + record = me.getSelectionModel().getLastSelected(); + if (record) { + item = me.getNode(record); + } + } + } + + if (item) { + index = me.indexOf(item); + if (!record) { + record = me.getRecord(item); + } + + // It is possible for an event to arrive for which there is no record... this + // can happen with dblclick where the clicks are on removal actions (think a + // grid w/"delete row" action column) + if (!record || me.processItemEvent(record, item, index, e) === false) { + return false; + } + + newType = me.isNewItemEvent(item, e); + if (newType === false) { + return false; + } + + if ( + (me['onBeforeItem' + map[newType]](record, item, index, e) === false) || + (me.fireEvent('beforeitem' + newType, me, record, item, index, e) === false) || + (me['onItem' + map[newType]](record, item, index, e) === false) + ) { + return false; + } + + me.fireEvent('item' + newType, me, record, item, index, e); + } + else { + if ( + (me.processContainerEvent(e) === false) || + (me['onBeforeContainer' + map[type]](e) === false) || + (me.fireEvent('beforecontainer' + type, me, e) === false) || + (me['onContainer' + map[type]](e) === false) + ) { + return false; + } + + me.fireEvent('container' + type, me, e); + } + + return true; + }, + + isNewItemEvent: function (item, e) { + var me = this, + overItem = me.mouseOverItem, + type = e.type; + + switch (type) { + case 'mouseover': + if (item === overItem) { + return false; + } + me.mouseOverItem = item; + return 'mouseenter'; + + case 'mouseout': + // If the currently mouseovered item contains the mouseover target, it's *NOT* a mouseleave + if (me.stillOverItem(e, overItem)) { + return false; + } + me.mouseOverItem = null; + return 'mouseleave'; + } + return type; + }, + + // private + onItemMouseEnter: function(record, item, index, e) { + if (this.trackOver) { + this.highlightItem(item); + } + }, + + // private + onItemMouseLeave : function(record, item, index, e) { + if (this.trackOver) { + this.clearHighlight(); + } + }, + + // @private, template methods + onItemMouseDown: Ext.emptyFn, + onItemMouseUp: Ext.emptyFn, + onItemFocus: Ext.emptyFn, + onItemClick: Ext.emptyFn, + onItemDblClick: Ext.emptyFn, + onItemContextMenu: Ext.emptyFn, + onItemKeyDown: Ext.emptyFn, + onBeforeItemMouseDown: Ext.emptyFn, + onBeforeItemMouseUp: Ext.emptyFn, + onBeforeItemFocus: Ext.emptyFn, + onBeforeItemMouseEnter: Ext.emptyFn, + onBeforeItemMouseLeave: Ext.emptyFn, + onBeforeItemClick: Ext.emptyFn, + onBeforeItemDblClick: Ext.emptyFn, + onBeforeItemContextMenu: Ext.emptyFn, + onBeforeItemKeyDown: Ext.emptyFn, + + // @private, template methods + onContainerMouseDown: Ext.emptyFn, + onContainerMouseUp: Ext.emptyFn, + onContainerMouseOver: Ext.emptyFn, + onContainerMouseOut: Ext.emptyFn, + onContainerClick: Ext.emptyFn, + onContainerDblClick: Ext.emptyFn, + onContainerContextMenu: Ext.emptyFn, + onContainerKeyDown: Ext.emptyFn, + onBeforeContainerMouseDown: Ext.emptyFn, + onBeforeContainerMouseUp: Ext.emptyFn, + onBeforeContainerMouseOver: Ext.emptyFn, + onBeforeContainerMouseOut: Ext.emptyFn, + onBeforeContainerClick: Ext.emptyFn, + onBeforeContainerDblClick: Ext.emptyFn, + onBeforeContainerContextMenu: Ext.emptyFn, + onBeforeContainerKeyDown: Ext.emptyFn, + + /** + * Highlights a given item in the DataView. This is called by the mouseover handler if {@link #overItemCls} + * and {@link #trackOver} are configured, but can also be called manually by other code, for instance to + * handle stepping through the list via keyboard navigation. + * @param {HTMLElement} item The item to highlight + */ + highlightItem: function(item) { + var me = this; + me.clearHighlight(); + me.highlightedItem = item; + Ext.fly(item).addCls(me.overItemCls); + me.fireEvent('highlightitem', me, item); + }, + + /** + * Un-highlights the currently highlighted item, if any. + */ + clearHighlight: function() { + var me = this, + highlighted = me.highlightedItem; + + if (highlighted) { + Ext.fly(highlighted).removeCls(me.overItemCls); + me.fireEvent('unhighlightitem', me, highlighted); + delete me.highlightedItem; + } + }, + + onUpdate: function(store, record){ + var me = this, + node, + newNode, + highlighted; + + if (me.rendered) { + node = me.getNode(record); + newNode = me.callParent(arguments); + highlighted = me.highlightedItem; + + if (highlighted && highlighted === node) { + delete me.highlightedItem; + if (newNode) { + me.highlightItem(newNode); + } + } + } + }, + + refresh: function() { + this.clearHighlight(); + this.callParent(arguments); + } +}); +/** + * An internally used DataView for {@link Ext.form.field.ComboBox ComboBox}. + */ +Ext.define('Ext.view.BoundList', { + extend: 'Ext.view.View', + alias: 'widget.boundlist', + alternateClassName: 'Ext.BoundList', + requires: ['Ext.layout.component.BoundList', 'Ext.toolbar.Paging'], + + /** + * @cfg {Number} [pageSize=0] + * If greater than `0`, a {@link Ext.toolbar.Paging} is displayed at the bottom of the list and store + * queries will execute with page {@link Ext.data.Operation#start start} and + * {@link Ext.data.Operation#limit limit} parameters. + */ + pageSize: 0, + + /** + * @cfg {String} [displayField=""] + * The field from the store to show in the view. + */ + + /** + * @property {Ext.toolbar.Paging} pagingToolbar + * A reference to the PagingToolbar instance in this view. Only populated if {@link #pageSize} is greater + * than zero and the BoundList has been rendered. + */ + + // private overrides + baseCls: Ext.baseCSSPrefix + 'boundlist', + itemCls: Ext.baseCSSPrefix + 'boundlist-item', + listItemCls: '', + shadow: false, + trackOver: true, + refreshed: 0, + + // This Component is used as a popup, not part of a complex layout. Display data immediately. + deferInitialRefresh: false, + + componentLayout: 'boundlist', + + childEls: [ + 'listEl' + ], + + renderTpl: [ + '
    ', + '{%', + 'var me=values.$comp, pagingToolbar=me.pagingToolbar;', + 'if (pagingToolbar) {', + 'pagingToolbar.ownerLayout = me.componentLayout;', + 'Ext.DomHelper.generateMarkup(pagingToolbar.getRenderTree(), out);', + '}', + '%}', + { + disableFormats: true + } + ], + + /** + * @cfg {String/Ext.XTemplate} tpl + * A String or Ext.XTemplate instance to apply to inner template. + * + * {@link Ext.view.BoundList} is used for the dropdown list of {@link Ext.form.field.ComboBox}. + * To customize the template you can do this: + * + * Ext.create('Ext.form.field.ComboBox', { + * fieldLabel : 'State', + * queryMode : 'local', + * displayField : 'text', + * valueField : 'abbr', + * store : Ext.create('StateStore', { + * fields : ['abbr', 'text'], + * data : [ + * {"abbr":"AL", "name":"Alabama"}, + * {"abbr":"AK", "name":"Alaska"}, + * {"abbr":"AZ", "name":"Arizona"} + * //... + * ] + * }), + * listConfig : { + * tpl : '
    {abbr}
    ' + * } + * }); + * + * Defaults to: + * + * Ext.create('Ext.XTemplate', + * '
      ', + * '
    • ' + me.getInnerTpl(me.displayField) + '
    • ', + * '
    ' + * ); + * + */ + + initComponent: function() { + var me = this, + baseCls = me.baseCls, + itemCls = me.itemCls; + + me.selectedItemCls = baseCls + '-selected'; + me.overItemCls = baseCls + '-item-over'; + me.itemSelector = "." + itemCls; + + if (me.floating) { + me.addCls(baseCls + '-floating'); + } + + if (!me.tpl) { + // should be setting aria-posinset based on entire set of data + // not filtered set + me.tpl = new Ext.XTemplate( + '
      ', + '
    • ' + me.getInnerTpl(me.displayField) + '
    • ', + '
    ' + ); + } else if (Ext.isString(me.tpl)) { + me.tpl = new Ext.XTemplate(me.tpl); + } + + if (me.pageSize) { + me.pagingToolbar = me.createPagingToolbar(); + } + + me.callParent(); + }, + + /** + * @private + * Boundlist-specific implementation of the up ComponentQuery method. + * This links first to the owning input field so that the FocusManager, when receiving notification of a hide event, + * can find a focusable parent. + */ + up: function(selector) { + var result = this.pickerField; + if (selector) { + for (; result; result = result.ownerCt) { + if (Ext.ComponentQuery.is(result, selector)) { + return result; + } + } + } + return result; + }, + + createPagingToolbar: function() { + return Ext.widget('pagingtoolbar', { + id: this.id + '-paging-toolbar', + pageSize: this.pageSize, + store: this.store, + border: false + }); + }, + + // Do the job of a container layout at this point even though we are not a Container. + // TODO: Refactor as a Container. + finishRenderChildren: function () { + var toolbar = this.pagingToolbar; + + this.callParent(arguments); + + if (toolbar) { + toolbar.finishRender(); + } + }, + + refresh: function(){ + var me = this, + toolbar = me.pagingToolbar; + + me.callParent(); + // The view removes the targetEl from the DOM before updating the template + // Ensure the toolbar goes to the end + if (me.rendered && toolbar && !me.preserveScrollOnRefresh) { + me.el.appendChild(toolbar.el); + } + }, + + bindStore : function(store, initial) { + var toolbar = this.pagingToolbar; + + this.callParent(arguments); + if (toolbar) { + toolbar.bindStore(this.store, initial); + } + }, + + getTargetEl: function() { + return this.listEl || this.el; + }, + + /** + * A method that returns the inner template for displaying items in the list. + * This method is useful to override when using a more complex display value, for example + * inserting an icon along with the text. + * @param {String} displayField The {@link #displayField} for the BoundList. + * @return {String} The inner template + */ + getInnerTpl: function(displayField) { + return '{' + displayField + '}'; + }, + + onDestroy: function() { + Ext.destroyMembers(this, 'pagingToolbar', 'listEl'); + this.callParent(); + } +}); + +/** + * A time picker which provides a list of times from which to choose. This is used by the Ext.form.field.Time + * class to allow browsing and selection of valid times, but could also be used with other components. + * + * By default, all times starting at midnight and incrementing every 15 minutes will be presented. This list of + * available times can be controlled using the {@link #minValue}, {@link #maxValue}, and {@link #increment} + * configuration properties. The format of the times presented in the list can be customized with the {@link #format} + * config. + * + * To handle when the user selects a time from the list, you can subscribe to the {@link #selectionchange} event. + * + * @example + * Ext.create('Ext.picker.Time', { + * width: 60, + * minValue: Ext.Date.parse('04:30:00 AM', 'h:i:s A'), + * maxValue: Ext.Date.parse('08:00:00 AM', 'h:i:s A'), + * renderTo: Ext.getBody() + * }); + */ +Ext.define('Ext.picker.Time', { + extend: 'Ext.view.BoundList', + alias: 'widget.timepicker', + requires: ['Ext.data.Store', 'Ext.Date'], + + /** + * @cfg {Date} minValue + * The minimum time to be shown in the list of times. This must be a Date object (only the time fields will be + * used); no parsing of String values will be done. + */ + + /** + * @cfg {Date} maxValue + * The maximum time to be shown in the list of times. This must be a Date object (only the time fields will be + * used); no parsing of String values will be done. + */ + + /** + * @cfg {Number} increment + * The number of minutes between each time value in the list. + */ + increment: 15, + + /** + * @cfg {String} [format=undefined] + * The default time format string which can be overriden for localization support. The format must be valid + * according to {@link Ext.Date#parse}. + * + * Defaults to `'g:i A'`, e.g., `'3:15 PM'`. For 24-hour time format try `'H:i'` instead. + */ + // + format : "g:i A", + // + + /** + * @private + * The field in the implicitly-generated Model objects that gets displayed in the list. This is + * an internal field name only and is not useful to change via config. + */ + displayField: 'disp', + + /** + * @private + * Year, month, and day that all times will be normalized into internally. + */ + initDate: [2008,0,1], + + componentCls: Ext.baseCSSPrefix + 'timepicker', + + /** + * @cfg + * @private + */ + loadMask: false, + + initComponent: function() { + var me = this, + dateUtil = Ext.Date, + clearTime = dateUtil.clearTime, + initDate = me.initDate; + + // Set up absolute min and max for the entire day + me.absMin = clearTime(new Date(initDate[0], initDate[1], initDate[2])); + me.absMax = dateUtil.add(clearTime(new Date(initDate[0], initDate[1], initDate[2])), 'mi', (24 * 60) - 1); + + me.store = me.createStore(); + me.updateList(); + + me.callParent(); + }, + + /** + * Set the {@link #minValue} and update the list of available times. This must be a Date object (only the time + * fields will be used); no parsing of String values will be done. + * @param {Date} value + */ + setMinValue: function(value) { + this.minValue = value; + this.updateList(); + }, + + /** + * Set the {@link #maxValue} and update the list of available times. This must be a Date object (only the time + * fields will be used); no parsing of String values will be done. + * @param {Date} value + */ + setMaxValue: function(value) { + this.maxValue = value; + this.updateList(); + }, + + /** + * @private + * Sets the year/month/day of the given Date object to the {@link #initDate}, so that only + * the time fields are significant. This makes values suitable for time comparison. + * @param {Date} date + */ + normalizeDate: function(date) { + var initDate = this.initDate; + date.setFullYear(initDate[0], initDate[1], initDate[2]); + return date; + }, + + /** + * Update the list of available times in the list to be constrained within the {@link #minValue} + * and {@link #maxValue}. + */ + updateList: function() { + var me = this, + min = me.normalizeDate(me.minValue || me.absMin), + max = me.normalizeDate(me.maxValue || me.absMax); + + me.store.filterBy(function(record) { + var date = record.get('date'); + return date >= min && date <= max; + }); + }, + + /** + * @private + * Creates the internal {@link Ext.data.Store} that contains the available times. The store + * is loaded with all possible times, and it is later filtered to hide those times outside + * the minValue/maxValue. + */ + createStore: function() { + var me = this, + utilDate = Ext.Date, + times = [], + min = me.absMin, + max = me.absMax; + + while(min <= max){ + times.push({ + disp: utilDate.dateFormat(min, me.format), + date: min + }); + min = utilDate.add(min, 'mi', me.increment); + } + + return new Ext.data.Store({ + fields: ['disp', 'date'], + data: times + }); + } + +}); + +/** + * A specialized {@link Ext.util.KeyNav} implementation for navigating a {@link Ext.view.BoundList} using + * the keyboard. The up, down, pageup, pagedown, home, and end keys move the active highlight + * through the list. The enter key invokes the selection model's select action using the highlighted item. + */ +Ext.define('Ext.view.BoundListKeyNav', { + extend: 'Ext.util.KeyNav', + requires: 'Ext.view.BoundList', + + /** + * @cfg {Ext.view.BoundList} boundList (required) + * The {@link Ext.view.BoundList} instance for which key navigation will be managed. + */ + + constructor: function(el, config) { + var me = this; + me.boundList = config.boundList; + me.callParent([el, Ext.apply({}, config, me.defaultHandlers)]); + }, + + defaultHandlers: { + up: function() { + var me = this, + boundList = me.boundList, + allItems = boundList.all, + oldItem = boundList.highlightedItem, + oldItemIdx = oldItem ? boundList.indexOf(oldItem) : -1, + newItemIdx = oldItemIdx > 0 ? oldItemIdx - 1 : allItems.getCount() - 1; //wraps around + me.highlightAt(newItemIdx); + }, + + down: function() { + var me = this, + boundList = me.boundList, + allItems = boundList.all, + oldItem = boundList.highlightedItem, + oldItemIdx = oldItem ? boundList.indexOf(oldItem) : -1, + newItemIdx = oldItemIdx < allItems.getCount() - 1 ? oldItemIdx + 1 : 0; //wraps around + me.highlightAt(newItemIdx); + }, + + pageup: function() { + //TODO + }, + + pagedown: function() { + //TODO + }, + + home: function() { + this.highlightAt(0); + }, + + end: function() { + var me = this; + me.highlightAt(me.boundList.all.getCount() - 1); + }, + + enter: function(e) { + this.selectHighlighted(e); + } + }, + + /** + * Highlights the item at the given index. + * @param {Number} index + */ + highlightAt: function(index) { + var boundList = this.boundList, + item = boundList.all.item(index); + if (item) { + item = item.dom; + boundList.highlightItem(item); + boundList.getTargetEl().scrollChildIntoView(item, false); + } + }, + + /** + * Triggers selection of the currently highlighted item according to the behavior of + * the configured SelectionModel. + */ + selectHighlighted: function(e) { + var me = this, + boundList = me.boundList, + highlighted = boundList.highlightedItem, + selModel = boundList.getSelectionModel(); + if (highlighted) { + selModel.selectWithEvent(boundList.getRecord(highlighted), e); + } + } + +}); +/** + * @docauthor Jason Johnston + * + * A combobox control with support for autocomplete, remote loading, and many other features. + * + * A ComboBox is like a combination of a traditional HTML text `` field and a ` value="{[Ext.util.Format.htmlEncode(values.value)]}"', + ' name="{name}"', + ' placeholder="{placeholder}"', + ' size="{size}"', + ' maxlength="{maxLength}"', + ' readonly="readonly"', + ' disabled="disabled"', + ' tabIndex="{tabIdx}"', + ' style="{fieldStyle}"', + '/>', + { + compiled: true, + disableFormats: true + } + ], + + getSubTplData: function(){ + var me = this; + Ext.applyIf(me.subTplData, { + hiddenDataCls: me.hiddenDataCls + }); + return me.callParent(arguments); + }, + + afterRender: function(){ + var me = this; + me.callParent(arguments); + me.setHiddenValue(me.value); + }, + + /** + * @cfg {Ext.data.Store/Array} store + * The data source to which this combo is bound. Acceptable values for this property are: + * + * - **any {@link Ext.data.Store Store} subclass** + * - **an Array** : Arrays will be converted to a {@link Ext.data.Store} internally, automatically generating + * {@link Ext.data.Field#name field names} to work with all data components. + * + * - **1-dimensional array** : (e.g., `['Foo','Bar']`) + * + * A 1-dimensional array will automatically be expanded (each array item will be used for both the combo + * {@link #valueField} and {@link #displayField}) + * + * - **2-dimensional array** : (e.g., `[['f','Foo'],['b','Bar']]`) + * + * For a multi-dimensional array, the value in index 0 of each item will be assumed to be the combo + * {@link #valueField}, while the value at index 1 is assumed to be the combo {@link #displayField}. + * + * See also {@link #queryMode}. + */ + + /** + * @cfg {Boolean} multiSelect + * If set to `true`, allows the combo field to hold more than one value at a time, and allows selecting multiple + * items from the dropdown list. The combo's text field will show all selected values separated by the + * {@link #delimiter}. + */ + multiSelect: false, + + /** + * @cfg {String} delimiter + * The character(s) used to separate the {@link #displayField display values} of multiple selected items when + * `{@link #multiSelect} = true`. + */ + // + delimiter: ', ', + // + + /** + * @cfg {String} displayField + * The underlying {@link Ext.data.Field#name data field name} to bind to this ComboBox. + * + * See also `{@link #valueField}`. + */ + displayField: 'text', + + /** + * @cfg {String} valueField (required) + * The underlying {@link Ext.data.Field#name data value name} to bind to this ComboBox. + * + * **Note**: use of a `valueField` requires the user to make a selection in order for a value to be mapped. See also + * `{@link #displayField}`. + * + * Defaults to match the value of the {@link #displayField} config. + */ + + /** + * @cfg {String} triggerAction + * The action to execute when the trigger is clicked. + * + * - **`'all'`** : + * + * {@link #doQuery run the query} specified by the `{@link #allQuery}` config option + * + * - **`'query'`** : + * + * {@link #doQuery run the query} using the {@link Ext.form.field.Base#getRawValue raw value}. + * + * See also `{@link #queryParam}`. + */ + triggerAction: 'all', + + /** + * @cfg {String} allQuery + * The text query to send to the server to return all records for the list with no filtering + */ + allQuery: '', + + /** + * @cfg {String} queryParam + * Name of the parameter used by the Store to pass the typed string when the ComboBox is configured with + * `{@link #queryMode}: 'remote'`. If explicitly set to a falsy value it will not be sent. + */ + queryParam: 'query', + + /** + * @cfg {String} queryMode + * The mode in which the ComboBox uses the configured Store. Acceptable values are: + * + * - **`'remote'`** : + * + * In `queryMode: 'remote'`, the ComboBox loads its Store dynamically based upon user interaction. + * + * This is typically used for "autocomplete" type inputs, and after the user finishes typing, the Store is {@link + * Ext.data.Store#method-load load}ed. + * + * A parameter containing the typed string is sent in the load request. The default parameter name for the input + * string is `query`, but this can be configured using the {@link #queryParam} config. + * + * In `queryMode: 'remote'`, the Store may be configured with `{@link Ext.data.Store#remoteFilter remoteFilter}: + * true`, and further filters may be _programatically_ added to the Store which are then passed with every load + * request which allows the server to further refine the returned dataset. + * + * Typically, in an autocomplete situation, {@link #hideTrigger} is configured `true` because it has no meaning for + * autocomplete. + * + * - **`'local'`** : + * + * ComboBox loads local data + * + * var combo = new Ext.form.field.ComboBox({ + * renderTo: document.body, + * queryMode: 'local', + * store: new Ext.data.ArrayStore({ + * id: 0, + * fields: [ + * 'myId', // numeric value is the key + * 'displayText' + * ], + * data: [[1, 'item1'], [2, 'item2']] // data is local + * }), + * valueField: 'myId', + * displayField: 'displayText', + * triggerAction: 'all' + * }); + */ + queryMode: 'remote', + + /** + * @cfg {Boolean} [queryCaching=true] + * When true, this prevents the combo from re-querying (either locally or remotely) when the current query + * is the same as the previous query. + */ + queryCaching: true, + + /** + * @cfg {Number} pageSize + * If greater than `0`, a {@link Ext.toolbar.Paging} is displayed in the footer of the dropdown list and the + * {@link #doQuery filter queries} will execute with page start and {@link Ext.view.BoundList#pageSize limit} + * parameters. Only applies when `{@link #queryMode} = 'remote'`. + */ + pageSize: 0, + + /** + * @cfg {Number} queryDelay + * The length of time in milliseconds to delay between the start of typing and sending the query to filter the + * dropdown list. + * + * Defaults to `500` if `{@link #queryMode} = 'remote'` or `10` if `{@link #queryMode} = 'local'` + */ + + /** + * @cfg {Number} minChars + * The minimum number of characters the user must type before autocomplete and {@link #typeAhead} activate. + * + * Defaults to `4` if `{@link #queryMode} = 'remote'` or `0` if `{@link #queryMode} = 'local'`, + * does not apply if `{@link Ext.form.field.Trigger#editable editable} = false`. + */ + + /** + * @cfg {Boolean} autoSelect + * `true` to automatically highlight the first result gathered by the data store in the dropdown list when it is + * opened. A false value would cause nothing in the list to be highlighted automatically, so + * the user would have to manually highlight an item before pressing the enter or {@link #selectOnTab tab} key to + * select it (unless the value of ({@link #typeAhead}) were true), or use the mouse to select a value. + */ + autoSelect: true, + + /** + * @cfg {Boolean} typeAhead + * `true` to populate and autoselect the remainder of the text being typed after a configurable delay + * ({@link #typeAheadDelay}) if it matches a known value. + */ + typeAhead: false, + + /** + * @cfg {Number} typeAheadDelay + * The length of time in milliseconds to wait until the typeahead text is displayed if `{@link #typeAhead} = true` + */ + typeAheadDelay: 250, + + /** + * @cfg {Boolean} selectOnTab + * Whether the Tab key should select the currently highlighted item. + */ + selectOnTab: true, + + /** + * @cfg {Boolean} forceSelection + * `true` to restrict the selected value to one of the values in the list, `false` to allow the user to set + * arbitrary text into the field. + */ + forceSelection: false, + + /** + * @cfg {Boolean} growToLongestValue + * `false` to not allow the component to resize itself when its data changes + * (and its {@link #grow} property is `true`) + */ + growToLongestValue: true, + + /** + * @cfg {String} valueNotFoundText + * When using a name/value combo, if the value passed to setValue is not found in the store, valueNotFoundText will + * be displayed as the field text if defined. If this default text is used, it means there + * is no value set and no validation will occur on this field. + */ + + /** + * @property {String} lastQuery + * The value of the match string used to filter the store. Delete this property to force a requery. Example use: + * + * var combo = new Ext.form.field.ComboBox({ + * ... + * queryMode: 'remote', + * listeners: { + * // delete the previous query in the beforequery event or set + * // combo.lastQuery = null (this will reload the store the next time it expands) + * beforequery: function(qe){ + * delete qe.combo.lastQuery; + * } + * } + * }); + * + * To make sure the filter in the store is not cleared the first time the ComboBox trigger is used configure the + * combo with `lastQuery=''`. Example use: + * + * var combo = new Ext.form.field.ComboBox({ + * ... + * queryMode: 'local', + * triggerAction: 'all', + * lastQuery: '' + * }); + */ + + /** + * @cfg {Object} defaultListConfig + * Set of options that will be used as defaults for the user-configured {@link #listConfig} object. + */ + defaultListConfig: { + loadingHeight: 70, + minWidth: 70, + maxHeight: 300, + shadow: 'sides' + }, + + /** + * @cfg {String/HTMLElement/Ext.Element} transform + * The id, DOM node or {@link Ext.Element} of an existing HTML ` name="{name}"',' value="{[Ext.util.Format.htmlEncode(values.value)]}"',' placeholder="{placeholder}"',' maxlength="{maxLength}"',' readonly="readonly"',' disabled="disabled"',' tabIndex="{tabIdx}"',' style="{fieldStyle}"',' class="{fieldCls} {typeCls} {editableCls}" autocomplete="off"/>',{disableFormats:true}],subTplInsertions:["inputAttrTpl"],inputType:"text",invalidText:"The value in this field is invalid",fieldCls:Ext.baseCSSPrefix+"form-field",focusCls:"form-focus",dirtyCls:Ext.baseCSSPrefix+"form-dirty",checkChangeEvents:Ext.isIE&&(!document.documentMode||document.documentMode<9)?["change","propertychange"]:["change","input","textInput","keyup","dragdrop"],checkChangeBuffer:50,componentLayout:"field",readOnly:false,readOnlyCls:Ext.baseCSSPrefix+"form-readonly",validateOnBlur:true,hasFocus:false,baseCls:Ext.baseCSSPrefix+"field",maskOnDisable:false,initComponent:function(){var a=this;a.callParent();a.subTplData=a.subTplData||{};a.addEvents("specialkey","writeablechange");a.initLabelable();a.initField();if(!a.name){a.name=a.getInputId()}},beforeRender:function(){var a=this;a.callParent(arguments);a.beforeLabelableRender(arguments);if(a.readOnly){a.addCls(a.readOnlyCls)}},getInputId:function(){return this.inputId||(this.inputId=this.id+"-inputEl")},getSubTplData:function(){var c=this,b=c.inputType,a=c.getInputId(),d;d=Ext.apply({id:a,cmpId:c.id,name:c.name||a,disabled:c.disabled,readOnly:c.readOnly,value:c.getRawValue(),type:b,fieldCls:c.fieldCls,fieldStyle:c.getFieldStyle(),tabIdx:c.tabIndex,typeCls:Ext.baseCSSPrefix+"form-"+(b==="password"?"text":b)},c.subTplData);c.getInsertionRenderData(d,c.subTplInsertions);return d},afterFirstLayout:function(){this.callParent();var a=this.inputEl;if(a){a.selectable()}},applyRenderSelectors:function(){var a=this;a.callParent();a.inputEl=a.el.getById(a.getInputId())},getSubTplMarkup:function(){return this.getTpl("fieldSubTpl").apply(this.getSubTplData())},initRenderTpl:function(){var a=this;if(!a.hasOwnProperty("renderTpl")){a.renderTpl=a.getTpl("labelableRenderTpl")}return a.callParent()},initRenderData:function(){return Ext.applyIf(this.callParent(),this.getLabelableRenderData())},setFieldStyle:function(a){var b=this,c=b.inputEl;if(c){c.applyStyles(a)}b.fieldStyle=a},getFieldStyle:function(){return"width:100%;"+(Ext.isObject(this.fieldStyle)?Ext.DomHelper.generateStyles(this.fieldStyle):this.fieldStyle||"")},onRender:function(){var a=this;a.callParent(arguments);a.onLabelableRender();a.renderActiveError()},getFocusEl:function(){return this.inputEl},isFileUpload:function(){return this.inputType==="file"},extractFileInput:function(){var b=this,a=b.isFileUpload()?b.inputEl.dom:null,c;if(a){c=a.cloneNode(true);a.parentNode.replaceChild(c,a);b.inputEl=Ext.get(c)}return a},getSubmitData:function(){var a=this,b=null,c;if(!a.disabled&&a.submitValue&&!a.isFileUpload()){c=a.getSubmitValue();if(c!==null){b={};b[a.getName()]=c}}return b},getSubmitValue:function(){return this.processRawValue(this.getRawValue())},getRawValue:function(){var b=this,a=(b.inputEl?b.inputEl.getValue():Ext.value(b.rawValue,""));b.rawValue=a;return a},setRawValue:function(b){var a=this;b=Ext.value(b,"");a.rawValue=b;if(a.inputEl){a.inputEl.dom.value=b}return b},valueToRaw:function(a){return""+Ext.value(a,"")},rawToValue:function(a){return a},processRawValue:function(a){return a},getValue:function(){var a=this,b=a.rawToValue(a.processRawValue(a.getRawValue()));a.value=b;return b},setValue:function(b){var a=this;a.setRawValue(a.valueToRaw(b));return a.mixins.field.setValue.call(a,b)},onBoxReady:function(){var a=this;a.callParent();if(a.setReadOnlyOnBoxReady){a.setReadOnly(a.readOnly)}},onDisable:function(){var a=this,b=a.inputEl;a.callParent();if(b){b.dom.disabled=true;if(a.hasActiveError()){a.clearInvalid();a.needsValidateOnEnable=true}}},onEnable:function(){var a=this,b=a.inputEl;a.callParent();if(b){b.dom.disabled=false;if(a.needsValidateOnEnable){delete a.needsValidateOnEnable;a.forceValidation=true;a.isValid();delete a.forceValidation}}},setReadOnly:function(c){var a=this,b=a.inputEl;c=!!c;a[c?"addCls":"removeCls"](a.readOnlyCls);a.readOnly=c;if(b){b.dom.readOnly=c}else{if(a.rendering){a.setReadOnlyOnBoxReady=true}}a.fireEvent("writeablechange",a,c)},fireKey:function(a){if(a.isSpecialKey()){this.fireEvent("specialkey",this,new Ext.EventObjectImpl(a))}},initEvents:function(){var g=this,i=g.inputEl,b,j,c=g.checkChangeEvents,h,a=c.length,d;if(g.inEditor){g.onBlur=Ext.Function.createBuffered(g.onBlur,10)}if(i){g.mon(i,Ext.EventManager.getKeyEvent(),g.fireKey,g);b=new Ext.util.DelayedTask(g.checkChange,g);g.onChangeEvent=j=function(){b.delay(g.checkChangeBuffer)};for(h=0;h","{beforeBoxLabelTpl}",'","{afterBoxLabelTpl}","",' tabIndex="{tabIdx}"',' disabled="disabled"',' style="{fieldStyle}"',' class="{fieldCls} {typeCls}" autocomplete="off" hidefocus="true" />',"","{beforeBoxLabelTpl}",'","{afterBoxLabelTpl}","",{disableFormats:true,compiled:true}],subTplInsertions:["beforeBoxLabelTpl","afterBoxLabelTpl","beforeBoxLabelTextTpl","afterBoxLabelTextTpl","boxLabelAttrTpl","inputAttrTpl"],isCheckbox:true,focusCls:"form-cb-focus",fieldBodyCls:Ext.baseCSSPrefix+"form-cb-wrap",checked:false,checkedCls:Ext.baseCSSPrefix+"form-cb-checked",boxLabelCls:Ext.baseCSSPrefix+"form-cb-label",boxLabelAlign:"after",inputValue:"on",checkChangeEvents:[],inputType:"checkbox",onRe:/^on$/i,initComponent:function(){this.callParent(arguments);this.getManager().add(this)},initValue:function(){var b=this,a=!!b.checked;b.originalValue=b.lastValue=a;b.setValue(a)},getElConfig:function(){var a=this;if(a.isChecked(a.rawValue,a.inputValue)){a.addCls(a.checkedCls)}return a.callParent()},getFieldStyle:function(){return Ext.isObject(this.fieldStyle)?Ext.DomHelper.generateStyles(this.fieldStyle):this.fieldStyle||""},getSubTplData:function(){var a=this;return Ext.apply(a.callParent(),{disabled:a.readOnly||a.disabled,boxLabel:a.boxLabel,boxLabelCls:a.boxLabelCls,boxLabelAlign:a.boxLabelAlign})},initEvents:function(){var a=this;a.callParent();a.mon(a.inputEl,"click",a.onBoxClick,a)},onBoxClick:function(b){var a=this;if(!a.disabled&&!a.readOnly){this.setValue(!this.checked)}},getRawValue:function(){return this.checked},getValue:function(){return this.checked},getSubmitValue:function(){var a=this.uncheckedValue,b=Ext.isDefined(a)?a:null;return this.checked?this.inputValue:b},isChecked:function(b,a){return(b===true||b==="true"||b==="1"||b===1||(((Ext.isString(b)||Ext.isNumber(b))&&a)?b==a:this.onRe.test(b)))},setRawValue:function(c){var b=this,d=b.inputEl,a=b.isChecked(c,b.inputValue);if(d){b[a?"addCls":"removeCls"](b.checkedCls)}b.checked=b.rawValue=a;return a},setValue:function(g){var e=this,c,b,a,d;if(Ext.isArray(g)){c=e.getManager().getByName(e.name,e.getFormId()).items;a=c.length;for(b=0;b style="{fieldStyle}"',' class="{fieldCls}">{value}',{compiled:true,disableFormats:true}],fieldCls:Ext.baseCSSPrefix+"form-display-field",htmlEncode:false,validateOnChange:false,initEvents:Ext.emptyFn,submitValue:false,isDirty:function(){return false},isValid:function(){return true},validate:function(){return true},getRawValue:function(){return this.rawValue},setRawValue:function(b){var a=this,c;b=Ext.value(b,"");a.rawValue=b;if(a.rendered){a.inputEl.dom.innerHTML=a.getDisplayValue()}return b},getDisplayValue:function(){var a=this,b=this.getRawValue(),c;if(a.renderer){c=a.renderer.call(a.scope||a,b,a)}else{c=a.htmlEncode?Ext.util.Format.htmlEncode(b):b}return c},getSubTplData:function(){var a=this.callParent(arguments);a.value=this.getDisplayValue();return a}});Ext.define("Ext.form.field.Hidden",{extend:"Ext.form.field.Base",alias:["widget.hiddenfield","widget.hidden"],alternateClassName:"Ext.form.Hidden",inputType:"hidden",hideLabel:true,initComponent:function(){this.formItemCls+="-hidden";this.callParent()},isEqual:function(b,a){return this.isEqualAsString(b,a)},initEvents:Ext.emptyFn,setSize:Ext.emptyFn,setWidth:Ext.emptyFn,setHeight:Ext.emptyFn,setPosition:Ext.emptyFn,setPagePosition:Ext.emptyFn,markInvalid:Ext.emptyFn,clearInvalid:Ext.emptyFn});Ext.define("Ext.form.field.Radio",{extend:"Ext.form.field.Checkbox",alias:["widget.radiofield","widget.radio"],alternateClassName:"Ext.form.Radio",requires:["Ext.form.RadioManager"],isRadio:true,inputType:"radio",ariaRole:"radio",formId:null,getGroupValue:function(){var a=this.getManager().getChecked(this.name,this.getFormId());return a?a.inputValue:null},onBoxClick:function(b){var a=this;if(!a.disabled&&!a.readOnly){this.setValue(true)}},onRemoved:function(){this.callParent(arguments);this.formId=null},setValue:function(a){var b=this,c;if(Ext.isBoolean(a)){b.callParent(arguments)}else{c=b.getManager().getWithValue(b.name,a,b.getFormId()).getAt(0);if(c){c.setValue(true)}}return b},getSubmitValue:function(){return this.checked?this.inputValue:null},getModelData:function(){return this.getSubmitData()},onChange:function(c,a){var g=this,e,d,b,h;g.callParent(arguments);if(c){h=g.getManager().getByName(g.name,g.getFormId()).items;d=h.length;for(e=0;eg.maxLength){k.push(j(g.maxLengthText,g.maxLength))}if(e){if(!h[e](l,g)){k.push(g.vtypeText||h[e+"Text"])}}if(i&&!i.test(l)){k.push(g.regexText||g.invalidText)}return k},selectText:function(i,a){var h=this,c=h.getRawValue(),d=true,g=h.inputEl.dom,e,b;if(c.length>0){i=i===e?0:i;a=a===e?c.length:a;if(g.setSelectionRange){g.setSelectionRange(i,a)}else{if(g.createTextRange){b=g.createTextRange();b.moveStart("character",i);b.moveEnd("character",a-c.length);b.select()}}d=Ext.isGecko||Ext.isOpera}if(d){h.focus()}},autoSize:function(){var a=this;if(a.grow&&a.rendered){a.autoSizing=true;a.updateLayout()}},afterComponentLayout:function(){var b=this,a;b.callParent(arguments);if(b.autoSizing){a=b.inputEl.getWidth();if(a!==b.lastInputWidth){b.fireEvent("autosize",b,a);b.lastInputWidth=a;delete b.autoSizing}}}});Ext.define("Ext.layout.component.field.TextArea",{extend:"Ext.layout.component.field.Text",alias:"layout.textareafield",type:"textareafield",canGrowWidth:false,beginLayout:function(a){this.callParent(arguments);a.target.inputEl.setStyle("height","")},measureContentHeight:function(b){var e=this,a=e.owner,k=e.callParent(arguments),c,i,h,g,d,j;if(a.grow&&!b.state.growHandled){c=b.inputContext;i=a.inputEl;d=i.getWidth(true);h=Ext.util.Format.htmlEncode(i.dom.value)||" ";h+=a.growAppend;h=h.replace(/\n/g,"
    ");j=Ext.util.TextMetrics.measure(i,h,d).height+c.getBorderInfo().height+c.getPaddingInfo().height;j=Ext.Number.constrain(j,a.growMin,a.growMax);c.setHeight(j);b.state.growHandled=true;c.domBlock(e,"height");k=NaN}return k}});Ext.define("Ext.form.field.TextArea",{extend:"Ext.form.field.Text",alias:["widget.textareafield","widget.textarea"],alternateClassName:"Ext.form.TextArea",requires:["Ext.XTemplate","Ext.layout.component.field.TextArea","Ext.util.DelayedTask"],fieldSubTpl:['",{disableFormats:true}],growMin:60,growMax:1000,growAppend:"\n-",cols:20,rows:4,enterIsSpecial:false,preventScrollbars:false,componentLayout:"textareafield",setGrowSizePolicy:Ext.emptyFn,getSubTplData:function(){var c=this,b=c.getFieldStyle(),a=c.callParent();if(c.grow){if(c.preventScrollbars){a.fieldStyle=(b||"")+";overflow:hidden;height:"+c.growMin+"px"}}Ext.applyIf(a,{cols:c.cols,rows:c.rows});return a},afterRender:function(){var a=this;a.callParent(arguments);a.needsMaxCheck=a.enforceMaxLength&&!Ext.supports.TextAreaMaxLength;if(a.needsMaxCheck){a.inputEl.on("paste",a.onPaste,a)}},onPaste:function(b){var a=this;if(!a.pasteTask){a.pasteTask=new Ext.util.DelayedTask(a.pasteCheck,a)}a.pasteTask.delay(1)},pasteCheck:function(){var b=this,c=b.getValue(),a=b.maxLength;if(c.length>a){c=c.substr(0,a);b.setValue(c)}},fireKey:function(c){var a=this,b;if(c.isSpecialKey()&&(a.enterIsSpecial||(c.getKey()!==c.ENTER||c.hasModifier()))){a.fireEvent("specialkey",a,c)}if(a.needsMaxCheck&&c.getKey()!==c.BACKSPACE&&!c.isNavKeyPress()){b=a.getValue();if(b.length>=a.maxLength){c.stopEvent()}}},autoSize:function(){var b=this,a;if(b.grow&&b.rendered){b.updateLayout();a=b.inputEl.getHeight();if(a!==b.lastInputHeight){b.fireEvent("autosize",b,a);b.lastInputHeight=a}}},initAria:function(){this.callParent(arguments);this.getActionEl().dom.setAttribute("aria-multiline",true)},beforeDestroy:function(){var a=this.pasteTask;if(a){a.delay()}this.callParent()}});Ext.define("Ext.layout.component.field.Trigger",{alias:"layout.triggerfield",extend:"Ext.layout.component.field.Field",type:"triggerfield",beginLayout:function(d){var c=this,a=c.owner,b;d.triggerWrap=d.getEl("triggerWrap");c.callParent(arguments);b=a.getTriggerStateFlags();if(b!=a.lastTriggerStateFlags){a.lastTriggerStateFlags=b;c.updateEditState()}},beginLayoutFixed:function(e,b,g){var c=this,a=e.target,d=c.ieInputWidthAdjustment,h="100%";c.callParent(arguments);a.inputCell.setStyle("width","100%");if(d){a.inputCell.setStyle("padding-right",d+"px");if(g==="px"){h=b-d-a.getTriggerWidth()}}a.inputEl.setStyle("width",h);a.triggerWrap.setStyle("width",b+g);a.triggerWrap.setStyle("table-layout","fixed")},beginLayoutShrinkWrap:function(b){var a=b.target,c="";this.callParent(arguments);a.triggerWrap.setStyle("width",c);a.inputCell.setStyle("width",c);a.inputEl.setStyle("width",c);a.triggerWrap.setStyle("table-layout","auto")},getTextWidth:function(){var b=this,a=b.owner,d=a.inputEl,c;c=(d.dom.value||(a.hasFocus?"":a.emptyText)||"")+a.growAppend;return d.getTextWidth(c)},measureContentWidth:function(h){var g=this,b=g.owner,e=g.callParent(arguments),i=h.inputContext,d,a,c;if(b.grow&&!h.state.growHandled){d=g.getTextWidth()+h.inputContext.getFrameInfo().width;a=b.growMax;c=Math.min(a,e);a=Math.max(b.growMin,a,c);d=Ext.Number.constrain(d,b.growMin,a);i.setWidth(d);h.state.growHandled=true;i.domBlock(g,"width");e=NaN}return e},updateEditState:function(){var c=this,a=c.owner,e=a.inputEl,d=Ext.baseCSSPrefix+"trigger-noedit",b,g;if(c.owner.readOnly){e.addCls(d);g=true;b=false}else{if(c.owner.editable){e.removeCls(d);g=false}else{e.addCls(d);g=true}b=!c.owner.hideTrigger}a.triggerCell.setDisplayed(b);e.dom.readOnly=g}});Ext.define("Ext.form.field.Trigger",{extend:"Ext.form.field.Text",alias:["widget.triggerfield","widget.trigger"],requires:["Ext.DomHelper","Ext.util.ClickRepeater","Ext.layout.component.field.Trigger"],alternateClassName:["Ext.form.TriggerField","Ext.form.TwinTriggerField","Ext.form.Trigger"],childEls:[{name:"triggerCell",select:"."+Ext.baseCSSPrefix+"trigger-cell"},{name:"triggerEl",select:"."+Ext.baseCSSPrefix+"form-trigger"},"triggerWrap","inputCell"],triggerBaseCls:Ext.baseCSSPrefix+"form-trigger",triggerWrapCls:Ext.baseCSSPrefix+"form-trigger-wrap",hideTrigger:false,editable:true,readOnly:false,repeatTriggerClick:false,autoSize:Ext.emptyFn,monitorTab:true,mimicing:false,triggerIndexRe:/trigger-index-(\d+)/,componentLayout:"triggerfield",initComponent:function(){this.wrapFocusCls=this.triggerWrapCls+"-focus";this.callParent(arguments)},getSubTplMarkup:function(){var a=this,b=a.callParent(arguments);return'"+a.getTriggerMarkup()+"
    '+b+"
    "},getSubTplData:function(){var b=this,c=b.callParent(),d=b.readOnly===true,a=b.editable!==false;return Ext.apply(c,{editableCls:(d||!a)?" "+Ext.baseCSSPrefix+"trigger-noedit":"",readOnly:!a||d})},getLabelableRenderData:function(){var b=this,c=b.triggerWrapCls,a=b.callParent(arguments);return Ext.applyIf(a,{triggerWrapCls:c,triggerMarkup:b.getTriggerMarkup()})},getTriggerMarkup:function(){var c=this,b=0,d=(c.readOnly||c.hideTrigger),g,e=c.triggerBaseCls,a=[];if(!c.trigger1Cls){c.trigger1Cls=c.triggerCls}for(b=0;(g=c["trigger"+(b+1)+"Cls"])||b<1;b++){a.push({tag:"td",valign:"top",cls:Ext.baseCSSPrefix+"trigger-cell",style:"width:"+c.triggerWidth+(d?"px;display:none":"px"),cn:{cls:[Ext.baseCSSPrefix+"trigger-index-"+b,e,g].join(" "),role:"button"}})}a[b-1].cn.cls+=" "+e+"-last";return Ext.DomHelper.markup(a)},disableCheck:function(){return !this.disabled},beforeRender:function(){var a=this,b=a.triggerBaseCls,c;if(!a.triggerWidth){c=Ext.getBody().createChild({style:"position: absolute;",cls:Ext.baseCSSPrefix+"form-trigger"});Ext.form.field.Trigger.prototype.triggerWidth=c.getWidth();c.remove()}a.callParent();if(b!=Ext.baseCSSPrefix+"form-trigger"){a.addChildEls({name:"triggerEl",select:"."+b})}a.lastTriggerStateFlags=a.getTriggerStateFlags()},onRender:function(){var a=this;a.callParent(arguments);a.doc=Ext.getDoc();a.initTrigger();a.triggerEl.unselectable()},getTriggerWidth:function(){var b=this,a=0;if(b.triggerWrap&&!b.hideTrigger&&!b.readOnly){a=b.triggerEl.getCount()*b.triggerWidth}return a},setHideTrigger:function(a){if(a!=this.hideTrigger){this.hideTrigger=a;this.updateLayout()}},setEditable:function(a){if(a!=this.editable){this.editable=a;this.updateLayout()}},setReadOnly:function(a){if(a!=this.readOnly){this.readOnly=a;this.updateLayout()}},initTrigger:function(){var h=this,i=h.triggerWrap,k=h.triggerEl,a=h.disableCheck,d,c,b,g,j;if(h.repeatTriggerClick){h.triggerRepeater=new Ext.util.ClickRepeater(i,{preventDefault:true,handler:h.onTriggerWrapClick,listeners:{mouseup:h.onTriggerWrapMousup,scope:h},scope:h})}else{h.mon(i,{click:h.onTriggerWrapClick,mouseup:h.onTriggerWrapMousup,scope:h})}k.setVisibilityMode(Ext.Element.DISPLAY);k.addClsOnOver(h.triggerBaseCls+"-over",a,h);d=k.elements;c=d.length;for(g=0;g'+Ext.DomHelper.markup(b)+"";c.destroy();return a},createFileInput:function(){var a=this;a.fileInputEl=a.buttonEl.createChild({name:a.getName(),id:a.id+"-fileInputEl",cls:Ext.baseCSSPrefix+"form-file-input",tag:"input",type:"file",size:1});a.fileInputEl.on({scope:a,change:a.onFileChange})},onFileChange:function(){this.lastValue=null;Ext.form.field.File.superclass.setValue.call(this,this.fileInputEl.dom.value)},setValue:Ext.emptyFn,reset:function(){var a=this;if(a.rendered){a.fileInputEl.remove();a.createFileInput();a.inputEl.dom.value=""}a.callParent()},onDisable:function(){this.callParent();this.disableItems()},disableItems:function(){var a=this.fileInputEl;if(a){a.dom.disabled=true}this["buttonEl-btnEl"].dom.disabled=true},onEnable:function(){var a=this;a.callParent();a.fileInputEl.dom.disabled=false;this["buttonEl-btnEl"].dom.disabled=true},isFileUpload:function(){return true},extractFileInput:function(){var a=this.fileInputEl.dom;this.reset();return a},onDestroy:function(){Ext.destroyMembers(this,"fileInputEl","buttonEl");this.callParent()}});Ext.define("Ext.form.field.Picker",{extend:"Ext.form.field.Trigger",alias:"widget.pickerfield",alternateClassName:"Ext.form.Picker",requires:["Ext.util.KeyNav"],matchFieldWidth:true,pickerAlign:"tl-bl?",openCls:Ext.baseCSSPrefix+"pickerfield-open",editable:true,initComponent:function(){this.callParent();this.addEvents("expand","collapse","select")},initEvents:function(){var a=this;a.callParent();a.keyNav=new Ext.util.KeyNav(a.inputEl,{down:a.onDownArrow,esc:{handler:a.onEsc,scope:a,defaultEventAction:false},scope:a,forceKeyDown:true});if(!a.editable){a.mon(a.inputEl,"click",a.onTriggerClick,a)}if(Ext.isGecko){a.inputEl.dom.setAttribute("autocomplete","off")}},onEsc:function(b){var a=this;if(a.isExpanded){a.collapse();b.stopEvent()}else{if(a.up("window")){a.blur()}else{if((!Ext.FocusManager||!Ext.FocusManager.enabled)){b.stopEvent()}}}},onDownArrow:function(a){if(!this.isExpanded){this.onTriggerClick()}},expand:function(){var c=this,a,b,d;if(c.rendered&&!c.isExpanded&&!c.isDestroyed){a=c.bodyEl;b=c.getPicker();d=c.collapseIf;b.show();c.isExpanded=true;c.alignPicker();a.addCls(c.openCls);c.mon(Ext.getDoc(),{mousewheel:d,mousedown:d,scope:c});Ext.EventManager.onWindowResize(c.alignPicker,c);c.fireEvent("expand",c);c.onExpand()}},onExpand:Ext.emptyFn,alignPicker:function(){var b=this,a=b.getPicker();if(b.isExpanded){if(b.matchFieldWidth){a.setWidth(b.bodyEl.getWidth())}if(a.isFloating()){b.doAlign()}}},doAlign:function(){var d=this,c=d.picker,a="-above",b;d.picker.alignTo(d.inputEl,d.pickerAlign,d.pickerOffset);b=c.el.getY()
    ',initComponent:function(){this.callParent();this.addEvents("spin","spinup","spindown")},onRender:function(){var b=this,a;b.callParent(arguments);a=b.triggerEl;b.spinUpEl=a.item(0);b.spinDownEl=a.item(1);b.setSpinUpEnabled(b.spinUpEnabled);b.setSpinDownEnabled(b.spinDownEnabled);if(b.keyNavEnabled){b.spinnerKeyNav=new Ext.util.KeyNav(b.inputEl,{scope:b,up:b.spinUp,down:b.spinDown})}if(b.mouseWheelEnabled){b.mon(b.bodyEl,"mousewheel",b.onMouseWheel,b)}},getSubTplMarkup:function(){var a=this,b=Ext.form.field.Base.prototype.getSubTplMarkup.apply(a,arguments);return'"+a.getTriggerMarkup()+"
    '+b+"
    "},getTriggerMarkup:function(){var a=this,b=(a.readOnly||a.hideTrigger);return a.getTpl("triggerTpl").apply({triggerStyle:"width:"+a.triggerWidth+(b?"px;display:none":"px")})},getTriggerWidth:function(){var b=this,a=0;if(b.triggerWrap&&!b.hideTrigger&&!b.readOnly){a=b.triggerWidth}return a},onTrigger1Click:function(){this.spinUp()},onTrigger2Click:function(){this.spinDown()},onTriggerWrapMousup:function(){this.inputEl.focus()},spinUp:function(){var a=this;if(a.spinUpEnabled&&!a.disabled){a.fireEvent("spin",a,"up");a.fireEvent("spinup",a);a.onSpinUp()}},spinDown:function(){var a=this;if(a.spinDownEnabled&&!a.disabled){a.fireEvent("spin",a,"down");a.fireEvent("spindown",a);a.onSpinDown()}},setSpinUpEnabled:function(a){var b=this,c=b.spinUpEnabled;b.spinUpEnabled=a;if(c!==a&&b.rendered){b.spinUpEl[a?"removeCls":"addCls"](b.trigger1Cls+"-disabled")}},setSpinDownEnabled:function(a){var b=this,c=b.spinDownEnabled;b.spinDownEnabled=a;if(c!==a&&b.rendered){b.spinDownEl[a?"removeCls":"addCls"](b.trigger2Cls+"-disabled")}},onMouseWheel:function(b){var a=this,c;if(a.hasFocus){c=b.getWheelDelta();if(c>0){a.spinUp()}else{if(c<0){a.spinDown()}}b.stopEvent()}},onDestroy:function(){Ext.destroyMembers(this,"spinnerKeyNav","spinUpEl","spinDownEl");this.callParent()}});Ext.define("Ext.form.field.Number",{extend:"Ext.form.field.Spinner",alias:"widget.numberfield",alternateClassName:["Ext.form.NumberField","Ext.form.Number"],allowDecimals:true,decimalSeparator:".",submitLocaleSeparator:true,decimalPrecision:2,minValue:Number.NEGATIVE_INFINITY,maxValue:Number.MAX_VALUE,step:1,minText:"The minimum value for this field is {0}",maxText:"The maximum value for this field is {0}",nanText:"{0} is not a valid number",negativeText:"The value cannot be negative",baseChars:"0123456789",autoStripChars:false,initComponent:function(){var a=this,b;a.callParent();a.setMinValue(a.minValue);a.setMaxValue(a.maxValue);if(a.disableKeyFilter!==true){b=a.baseChars+"";if(a.allowDecimals){b+=a.decimalSeparator}if(a.minValue<0){b+="-"}b=Ext.String.escapeRegex(b);a.maskRe=new RegExp("["+b+"]");if(a.autoStripChars){a.stripCharsRe=new RegExp("[^"+b+"]","gi")}}},getErrors:function(c){var b=this,e=b.callParent(arguments),d=Ext.String.format,a;c=Ext.isDefined(c)?c:this.processRawValue(this.getRawValue());if(c.length<1){return e}c=String(c).replace(b.decimalSeparator,".");if(isNaN(c)){e.push(d(b.nanText,c))}a=b.parseValue(c);if(b.minValue===0&&a<0){e.push(this.negativeText)}else{if(ab.maxValue){e.push(d(b.maxText,b.maxValue))}return e},rawToValue:function(b){var a=this.fixPrecision(this.parseValue(b));if(a===null){a=b||null}return a},valueToRaw:function(c){var b=this,a=b.decimalSeparator;c=b.parseValue(c);c=b.fixPrecision(c);c=Ext.isNumber(c)?c:parseFloat(String(c).replace(a,"."));c=isNaN(c)?"":String(c).replace(".",a);return c},getSubmitValue:function(){var a=this,b=a.callParent();if(!a.submitLocaleSeparator){b=b.replace(a.decimalSeparator,".")}return b},onChange:function(){this.toggleSpinners();this.callParent(arguments)},toggleSpinners:function(){var b=this,c=b.getValue(),a=c===null;b.setSpinUpEnabled(a||cb.minValue)},setMinValue:function(a){this.minValue=Ext.Number.from(a,Number.NEGATIVE_INFINITY);this.toggleSpinners()},setMaxValue:function(a){this.maxValue=Ext.Number.from(a,Number.MAX_VALUE);this.toggleSpinners()},parseValue:function(a){a=parseFloat(String(a).replace(this.decimalSeparator,"."));return isNaN(a)?null:a},fixPrecision:function(d){var c=this,b=isNaN(d),a=c.decimalPrecision;if(b||!d){return b?"":d}else{if(!c.allowDecimals||a<=0){a=0}}return parseFloat(Ext.Number.toFixed(parseFloat(d),a))},beforeBlur:function(){var b=this,a=b.parseValue(b.getRawValue());if(!Ext.isEmpty(a)){b.setValue(a)}},onSpinUp:function(){var a=this;if(!a.readOnly){a.setValue(Ext.Number.constrain(a.getValue()+a.step,a.minValue,a.maxValue))}},onSpinDown:function(){var a=this;if(!a.readOnly){a.setValue(Ext.Number.constrain(a.getValue()-a.step,a.minValue,a.maxValue))}}});Ext.define("Ext.layout.component.field.ComboBox",{extend:"Ext.layout.component.field.Trigger",alias:"layout.combobox",requires:["Ext.util.TextMetrics"],type:"combobox",startingWidth:null,getTextWidth:function(){var h=this,b=h.owner,l=b.store,j=b.displayField,d=l.data.length,k="",e=0,c=0,g,m,a;for(;ec){c=g;k=m}}a=Math.max(h.callParent(arguments),b.inputEl.getTextWidth(k+b.growAppend));if(!h.startingWidth||b.removingRecords){h.startingWidth=a;if(a');c.scrollRangeFlags=e}}},finishRender:function(){var b=this,c,a;b.callParent();b.cacheElements();c=b.getRenderTarget();a=b.getLayoutItems();if(b.targetCls){b.getTarget().addCls(b.targetCls)}b.finishRenderItems(c,a)},notifyOwner:function(){this.owner.afterLayout(this)},getContainerSize:function(c,h){var d=c.targetContext,g=d.getFrameInfo(),k=d.getPaddingInfo(),j=0,l=0,a=c.state.overflowAdjust,e,i,b,m;if(!c.widthModel.shrinkWrap){++l;b=h?d.getDomProp("width"):d.getProp("width");e=(typeof b=="number");if(e){++j;b-=g.width+k.width;if(a){b-=a.width}}}if(!c.heightModel.shrinkWrap){++l;m=h?d.getDomProp("height"):d.getProp("height");i=(typeof m=="number");if(i){++j;m-=g.height+k.height;if(a){m-=a.height}}}return{width:b,height:m,needed:l,got:j,gotAll:j==l,gotWidth:e,gotHeight:i}},getLayoutItems:function(){var a=this.owner,b=a&&a.items;return(b&&b.items)||[]},getRenderData:function(){var a=this.owner;return{$comp:a,$layout:this,ownerId:a.id}},getRenderedItems:function(){var e=this,h=e.getRenderTarget(),a=e.getLayoutItems(),d=a.length,g=[],b,c;for(b=0;b'],calculate:function(b){var a=this,c;if(!b.hasDomProp("containerChildrenDone")){a.done=false}else{c=a.getContainerSize(b);if(!c.gotAll){a.done=false}a.calculateContentSize(b)}}});Ext.define("Ext.container.AbstractContainer",{extend:"Ext.Component",requires:["Ext.util.MixedCollection","Ext.layout.container.Auto","Ext.ZIndexManager"],renderTpl:"{%this.renderContainer(out,values)%}",suspendLayout:false,autoDestroy:true,defaultType:"panel",detachOnRemove:true,isContainer:true,layoutCounter:0,baseCls:Ext.baseCSSPrefix+"container",bubbleEvents:["add","remove"],initComponent:function(){var a=this;a.addEvents("afterlayout","beforeadd","beforeremove","add","remove");a.callParent();a.getLayout();a.initItems()},initItems:function(){var b=this,a=b.items;b.items=new Ext.util.AbstractMixedCollection(false,b.getComponentId);if(a){if(!Ext.isArray(a)){a=[a]}b.add(a)}},getFocusEl:function(){return this.getTargetEl()},finishRenderChildren:function(){this.callParent();var a=this.getLayout();if(a){a.finishRender()}},beforeRender:function(){var b=this,a=b.getLayout();b.callParent();if(!a.initialized){a.initLayout()}},setupRenderTpl:function(b){var a=this.getLayout();this.callParent(arguments);a.setupRenderTpl(b)},setLayout:function(b){var a=this.layout;if(a&&a.isLayout&&a!=b){a.setOwner(null)}this.layout=b;b.setOwner(this)},getLayout:function(){var a=this;if(!a.layout||!a.layout.isLayout){a.setLayout(Ext.layout.Layout.create(a.layout,a.self.prototype.layout||"autocontainer"))}return a.layout},doLayout:function(){this.updateLayout();return this},afterLayout:function(b){var a=this;++a.layoutCounter;if(a.hasListeners.afterlayout){a.fireEvent("afterlayout",a,b)}},prepareItems:function(b,d){if(Ext.isArray(b)){b=b.slice()}else{b=[b]}var c=0,a=b.length,e;for(;c "+a)[0]||null},nextChild:function(e,b){var c=this,a,d=c.items.indexOf(e);if(d!==-1){a=b?Ext.ComponentQuery(b,c.items.items.slice(d+1)):c.items.getAt(d+1);if(!a&&c.ownerCt){a=c.ownerCt.nextChild(c,b)}}return a},prevChild:function(e,b){var c=this,a,d=c.items.indexOf(e);if(d!==-1){a=b?Ext.ComponentQuery(b,c.items.items.slice(d+1)):c.items.getAt(d+1);if(!a&&c.ownerCt){a=c.ownerCt.nextChild(c,b)}}return a},down:function(a){return this.query(a)[0]||null},enable:function(){this.callParent(arguments);var d=this.getChildItemsToDisable(),c=d.length,b,a;for(a=0;a',"{%this.renderContainer(out,values);%}",""],stateEvents:["collapse","expand"],maskOnDisable:false,beforeDestroy:function(){var b=this,a=b.legend;if(a){delete a.ownerCt;a.destroy();b.legend=null}b.callParent()},initComponent:function(){var b=this,a=b.baseCls;b.callParent();b.addEvents("beforeexpand","beforecollapse","expand","collapse");if(b.collapsed){b.addCls(a+"-collapsed");b.collapse()}if(b.title){b.addCls(a+"-with-title")}if(b.title||b.checkboxToggle||b.collapsible){b.addCls(a+"-with-legend")}},initRenderData:function(){var a=this.callParent();a.baseCls=this.baseCls;return a},getState:function(){var a=this.callParent();a=this.addPropertyToState(a,"collapsed");return a},afterCollapse:Ext.emptyFn,afterExpand:Ext.emptyFn,collapsedHorizontal:function(){return true},collapsedVertical:function(){return true},createLegendCt:function(){var c=this,a=[],b={xtype:"container",baseCls:this.baseCls+"-header",id:c.id+"-legend",autoEl:"legend",items:a,ownerCt:c,ownerLayout:c.componentLayout};if(c.checkboxToggle){a.push(c.createCheckboxCmp())}else{if(c.collapsible){a.push(c.createToggleCmp())}}a.push(c.createTitleCmp());return b},createTitleCmp:function(){var b=this,a={xtype:"component",html:b.title,cls:b.baseCls+"-header-text",id:b.id+"-legendTitle"};if(b.collapsible&&b.toggleOnTitleClick){a.listeners={el:{scope:b,click:b.toggle}};a.cls+=" "+b.baseCls+"-header-text-collapsible"}return(b.titleCmp=Ext.widget(a))},createCheckboxCmp:function(){var a=this,b="-checkbox";a.checkboxCmp=Ext.widget({xtype:"checkbox",hideEmptyLabel:true,name:a.checkboxName||a.id+b,cls:a.baseCls+"-header"+b,id:a.id+"-legendChk",checked:!a.collapsed,listeners:{change:a.onCheckChange,scope:a}});return a.checkboxCmp},createToggleCmp:function(){var a=this;a.toggleCmp=Ext.widget({xtype:"tool",type:"toggle",handler:a.toggle,id:a.id+"-legendToggle",scope:a});return a.toggleCmp},doRenderLegend:function(b,e){var d=e.$comp,c,a;if(d.title||d.checkboxToggle||d.collapsible){d.legend=c=Ext.widget(d.createLegendCt());c.ownerLayout.configureItem(c);a=d.legend.getRenderTree();Ext.DomHelper.generateMarkup(a,b)}},finishRender:function(){var a=this.legend;this.callParent();if(a){a.finishRender()}},getCollapsed:function(){return this.collapsed?"top":false},getCollapsedDockedItems:function(){var a=this.legend;return a?[a]:[]},setTitle:function(c){var b=this,a=b.legend;b.title=c;if(b.rendered){if(!b.legend){b.legend=a=Ext.widget(b.createLegendCt());a.ownerLayout.configureItem(a);a.render(b.el,0)}b.titleCmp.update(c)}return b},getTargetEl:function(){return this.body||this.frameBody||this.el},getContentTarget:function(){return this.body},expand:function(){return this.setExpanded(true)},collapse:function(){return this.setExpanded(false)},setExpanded:function(b){var c=this,d=c.checkboxCmp,a=b?"expand":"collapse";if(!c.rendered||c.fireEvent("before"+a,c)!==false){b=!!b;if(d){d.setValue(b)}if(b){c.removeCls(c.baseCls+"-collapsed")}else{c.addCls(c.baseCls+"-collapsed")}c.collapsed=!b;if(c.rendered){c.updateLayout();c.fireEvent(a,c)}}return c},getRefItems:function(a){var c=this.callParent(arguments),b=this.legend;if(b){c.unshift(b);if(a){c.unshift.apply(c,b.getRefItems(true))}}return c},toggle:function(){this.setExpanded(!!this.collapsed)},onCheckChange:function(b,a){this.setExpanded(a)},setupRenderTpl:function(a){this.callParent(arguments);a.renderLegend=this.doRenderLegend}});Ext.define("Ext.layout.container.Anchor",{alias:"layout.anchor",extend:"Ext.layout.container.Container",alternateClassName:"Ext.layout.AnchorLayout",type:"anchor",manageOverflow:2,renderTpl:["{%this.renderBody(out,values);this.renderPadder(out,values)%}"],defaultAnchor:"100%",parseAnchorRE:/^(r|right|b|bottom)$/i,beginLayout:function(c){var j=this,a=0,g,k,e,d,b,h;j.callParent(arguments);e=c.childItems;b=e.length;for(d=0;d','','',"{% this.renderColumn(out,parent,xindex-1) %}","","",""],beginLayout:function(b){var n=this,e,d,l,k,h,a,m,g=0,p=0,o=n.autoFlex,j=n.owner.items.generation,c=n.innerCt.dom.style;n.callParent(arguments);k=b.childItems;if(n.lastChildGeneration!=j){n.lastChildGeneration=j;n.fixColumns()}e=n.columnEls;b.innerCtContext=b.getEl("innerCt",n);if(!b.widthModel.shrinkWrap){d=e.length;if(n.columnsArray){for(h=0;hh)){o=a-h;for(g=0;g',"{%this.renderBody(out,values)%}",'
    ',"","{%this.renderPadder(out,values)%}"],getItemSizePolicy:function(a){if(a.columnWidth){return this.columnWidthSizePolicy}return this.autoSizePolicy},beginLayout:function(){this.callParent(arguments);this.innerCt.dom.style.width=""},calculate:function(c){var a=this,d=a.getContainerSize(c),b=c.state;if(b.calculatedColumns||(b.calculatedColumns=a.calculateColumns(c))){if(a.calculateHeights(c)){a.calculateOverflow(c,d);return}}a.done=false},calculateColumns:function(d){var m=this,a=m.getContainerSize(d),o=d.getEl("innerCt",m),l=d.childItems,j=l.length,b=0,g,n,e,c,h,k;if(!d.heightModel.shrinkWrap&&!d.targetContext.hasProp("height")){return false}if(!a.gotWidth){d.targetContext.block(m,"width");g=true}else{n=a.width;o.setWidth(n)}for(e=0;e1||(g===1&&c[0].nodeType!==3))){b=j.last();i=b.getOffsetsTo(j)[0]+b.getWidth();m=j.getWidth();a=m-i;if(!k.editingPlugin.grid.columnLines){a--}d[0]+=i;k.addCls(Ext.baseCSSPrefix+"grid-editor-on-text-node")}else{a=h.getWidth()-1}if(e===true){k.field.setWidth(a)}k.alignTo(h,k.alignment,d)},onEditorTab:function(b){var a=this.field;if(a.onEditorTab){a.onEditorTab(b)}},alignment:"tl-tl",hideEl:false,cls:Ext.baseCSSPrefix+"small-editor "+Ext.baseCSSPrefix+"grid-editor",shim:false,shadow:false});Ext.define("Ext.layout.container.Fit",{extend:"Ext.layout.container.Container",alternateClassName:"Ext.layout.FitLayout",alias:"layout.fit",itemCls:Ext.baseCSSPrefix+"fit-item",targetCls:Ext.baseCSSPrefix+"layout-fit",type:"fit",defaultMargins:{top:0,right:0,bottom:0,left:0},manageMargins:true,sizePolicies:{0:{setsWidth:0,setsHeight:0},1:{setsWidth:1,setsHeight:0},2:{setsWidth:0,setsHeight:1},3:{setsWidth:1,setsHeight:1}},getItemSizePolicy:function(b){var a=this.owner.getSizeModel(),c=(a.width.shrinkWrap?0:1)|(a.height.shrinkWrap?0:2);return this.sizePolicies[c]},beginLayoutCycle:function(d,p){var l=this,k=d.widthModel,j=d.heightModel,h=d.childItems,n=!k.shrinkWrap,a=!j.shrinkWrap,c=h.length,m=(d.targetContext.el.dom.tagName.toUpperCase()==="TD"),g,e,b,o;l.callParent(arguments);for(g=0;g',renderTpl:['',"{%this.renderBody(out,values)%}","
    ","{%this.renderPadder(out,values)%}"],getRenderData:function(){var a=this.callParent();a.tableCls=this.tableCls;return a},calculate:function(e){var d=this,h=d.getContainerSize(e,true),a,g,b=0,c;if(h.gotWidth){this.callParent(arguments);a=d.formTable.dom.offsetWidth;g=e.childItems;for(c=g.length;b=h||n[d]>0){if(d>=h){d=0;a=0;b++;for(c=0;c0){n[c]--}}}else{d++}}m.push({rowIdx:b,cellIdx:a});for(c=l.colspan||1;c;--c){n[d]=l.rowspan||1;++d}++a}return m},getRenderTree:function(){var k=this,h=k.getLayoutItems(),o,p=[],q=Ext.apply({tag:"table",role:"presentation",cls:k.tableCls,cellspacing:0,cn:{tag:"tbody",cn:p}},k.tableAttrs),c=k.tdAttrs,d=k.needsDivWrap(),e,g=h.length,n,m,j,b,a,l;o=k.calculateCells(h);for(e=0;e=this.getMaxScrollPosition()},scrollTo:function(a,b){var g=this,e=g.layout,h=e.getNames(),d=g.getScrollPosition(),c=Ext.Number.constrain(a,0,g.getMaxScrollPosition());if(c!=d&&!g.scrolling){delete g.scrollPosition;if(b===undefined){b=g.animateScroll}e.innerCt.scrollTo(h.left,c,b?g.getScrollAnim():false);if(b){g.scrolling=true}else{g.updateScrollButtons()}g.fireEvent("scroll",g,c,b?g.getScrollAnim():false)}},scrollToItem:function(h,b){var g=this,e=g.layout,i=e.getNames(),a,d,c;h=g.getItem(h);if(h!==undefined){a=g.getItemVisibility(h);if(!a.fullyVisible){d=h.getBox(true,true);c=d[i.x];if(a.hiddenEnd){c-=(g.layout.innerCt["get"+i.widthCap]()-d[i.width])}g.scrollTo(c,b)}}},getItemVisibility:function(j){var h=this,b=h.getItem(j).getBox(true,true),c=h.layout,g=c.getNames(),e=b[g.x],d=e+b[g.width],a=h.getScrollPosition(),i=a+c.innerCt["get"+g.widthCap]();return{hiddenStart:ei,fullyVisible:e>a&&d',"{text}","",'target="{hrefTarget}" hidefocus="true" unselectable="on">','','style="margin-right: 17px;" >{text}','',"",""],maskOnDisable:false,activate:function(){var a=this;if(!a.activated&&a.canActivate&&a.rendered&&!a.isDisabled()&&a.isVisible()){a.el.addCls(a.activeCls);a.focus();a.activated=true;a.fireEvent("activate",a)}},getFocusEl:function(){return this.itemEl},deactivate:function(){var a=this;if(a.activated){a.el.removeCls(a.activeCls);a.blur();a.hideMenu();a.activated=false;a.fireEvent("deactivate",a)}},deferExpandMenu:function(){var a=this;if(a.activated&&(!a.menu.rendered||!a.menu.isVisible())){a.parentMenu.activeChild=a.menu;a.menu.parentItem=a;a.menu.parentMenu=a.menu.ownerCt=a.parentMenu;a.menu.showBy(a,a.menuAlign)}},deferHideMenu:function(){if(this.menu.isVisible()){this.menu.hide()}},cancelDeferHide:function(){clearTimeout(this.hideMenuTimer)},deferHideParentMenus:function(){var a;Ext.menu.Manager.hideAll();if(!Ext.Element.getActiveElement()){a=this.up(":not([hidden])");if(a){a.focus()}}},expandMenu:function(a){var b=this;if(b.menu){b.cancelDeferHide();if(a===0){b.deferExpandMenu()}else{b.expandMenuTimer=Ext.defer(b.deferExpandMenu,Ext.isNumber(a)?a:b.menuExpandDelay,b)}}},getRefItems:function(a){var c=this.menu,b;if(c){b=c.getRefItems(a);b.unshift(c)}return b||[]},hideMenu:function(a){var b=this;if(b.menu){clearTimeout(b.expandMenuTimer);b.hideMenuTimer=Ext.defer(b.deferHideMenu,Ext.isNumber(a)?a:b.menuHideDelay,b)}},initComponent:function(){var b=this,c=Ext.baseCSSPrefix,a=[c+"menu-item"],d;b.addEvents("activate","click","deactivate");if(b.plain){a.push(c+"menu-item-plain")}if(b.cls){a.push(b.cls)}b.cls=a.join(" ");if(b.menu){d=b.menu;delete b.menu;b.setMenu(d)}b.callParent(arguments)},onClick:function(b){var a=this;if(!a.href){b.stopEvent()}if(a.disabled){return}if(a.hideOnClick){a.deferHideParentMenusTimer=Ext.defer(a.deferHideParentMenus,a.clickHideDelay,a)}Ext.callback(a.handler,a.scope||a,[a,b]);a.fireEvent("click",a,b);if(!a.hideOnClick){a.focus()}},onRemoved:function(){var a=this;if(a.activated&&a.parentMenu.activeItem===a){a.parentMenu.deactivateActiveItem()}a.callParent(arguments);delete a.parentMenu;delete a.ownerButton},beforeDestroy:function(){var a=this;if(a.rendered){a.clearTip()}a.callParent()},onDestroy:function(){var a=this;clearTimeout(a.expandMenuTimer);a.cancelDeferHide();clearTimeout(a.deferHideParentMenusTimer);a.setMenu(null);a.callParent(arguments)},beforeRender:function(){var a=this,b=Ext.BLANK_IMAGE_URL;a.callParent();Ext.applyIf(a.renderData,{href:a.href||"#",hrefTarget:a.hrefTarget,icon:a.icon||b,iconCls:a.iconCls+(a.checkChangeDisabled?" "+a.disabledCls:""),plain:a.plain,text:a.text,arrowCls:a.menu?a.arrowCls:"",blank:b})},onRender:function(){var a=this;a.callParent(arguments);if(a.tooltip){a.setTooltip(a.tooltip,true)}},setMenu:function(d,c){var b=this,a=b.menu;if(a){delete a.parentItem;delete a.parentMenu;delete a.ownerCt;delete a.ownerItem;if(c===true||(c!==false&&b.destroyMenu)){Ext.destroy(a)}}if(d){b.menu=Ext.menu.Manager.get(d);b.menu.ownerItem=b}else{b.menu=null}if(b.rendered&&!b.destroying){b.arrowEl[b.menu?"addCls":"removeCls"](b.arrowCls)}},setHandler:function(b,a){this.handler=b||null;this.scope=a},setIcon:function(b){var a=this.iconEl;if(a){a.src=b||Ext.BLANK_IMAGE_URL}this.icon=b},setIconCls:function(b){var c=this,a=c.iconEl;if(a){if(c.iconCls){a.removeCls(c.iconCls)}if(b){a.addCls(b)}}c.iconCls=b},setText:function(c){var b=this,a=b.textEl||b.el;b.text=c;if(b.rendered){a.update(c||"");b.ownerCt.updateLayout()}},getTipAttr:function(){return this.tooltipType=="qtip"?"data-qtip":"title"},clearTip:function(){if(Ext.isObject(this.tooltip)){Ext.tip.QuickTipManager.unregister(this.itemEl)}},setTooltip:function(c,a){var b=this;if(b.rendered){if(!a){b.clearTip()}if(Ext.isObject(c)){Ext.tip.QuickTipManager.register(Ext.apply({target:b.itemEl.id},c));b.tooltip=c}else{b.itemEl.dom.setAttribute(b.getTipAttr(),c)}}else{b.tooltip=c}return b}});Ext.define("Ext.menu.CheckItem",{extend:"Ext.menu.Item",alias:"widget.menucheckitem",checkedCls:Ext.baseCSSPrefix+"menu-item-checked",uncheckedCls:Ext.baseCSSPrefix+"menu-item-unchecked",groupCls:Ext.baseCSSPrefix+"menu-group-icon",hideOnClick:false,checkChangeDisabled:false,afterRender:function(){var a=this;a.callParent();a.checked=!a.checked;a.setChecked(!a.checked,true);if(a.checkChangeDisabled){a.disableCheckChange()}},initComponent:function(){var a=this;a.addEvents("beforecheckchange","checkchange");a.callParent(arguments);Ext.menu.Manager.registerCheckable(a);if(a.group){if(!a.iconCls){a.iconCls=a.groupCls}if(a.initialConfig.hideOnClick!==false){a.hideOnClick=true}}},disableCheckChange:function(){var b=this,a=b.iconEl;if(a){a.addCls(b.disabledCls)}b.checkChangeDisabled=true},enableCheckChange:function(){var b=this,a=b.iconEl;if(a){a.removeCls(b.disabledCls)}b.checkChangeDisabled=false},onClick:function(b){var a=this;if(!a.disabled&&!a.checkChangeDisabled&&!(a.checked&&a.group)){a.setChecked(!a.checked)}this.callParent([b])},onDestroy:function(){Ext.menu.Manager.unregisterCheckable(this);this.callParent(arguments)},setChecked:function(c,a){var b=this;if(b.checked!==c&&(a||b.fireEvent("beforecheckchange",b,c)!==false)){if(b.el){b.el[c?"addCls":"removeCls"](b.checkedCls)[!c?"addCls":"removeCls"](b.uncheckedCls)}b.checked=c;Ext.menu.Manager.onCheckChange(b,c);if(!a){Ext.callback(b.checkHandler,b.scope,[b,c]);b.fireEvent("checkchange",b,c)}}}});Ext.define("Ext.menu.KeyNav",{extend:"Ext.util.KeyNav",requires:["Ext.FocusManager"],constructor:function(b){var a=this;a.menu=b;a.callParent([b.el,{down:a.down,enter:a.enter,esc:a.escape,left:a.left,right:a.right,space:a.enter,tab:a.tab,up:a.up}])},down:function(b){var a=this,c=a.menu.focusedItem;if(c&&b.getKey()==Ext.EventObject.DOWN&&a.isWhitelisted(c)){return true}a.focusNextItem(1)},enter:function(b){var c=this.menu,a=c.focusedItem;if(c.activeItem){c.onClick(b)}else{if(a&&a.isFormField){return true}}},escape:function(a){Ext.menu.Manager.hideAll()},focusNextItem:function(g){var h=this.menu,b=h.items,d=h.focusedItem,c=d?b.indexOf(d):-1,a=c+g,e;while(a!=c){if(a<0){a=b.length-1}else{if(a>=b.length){a=0}}e=b.getAt(a);if(h.canActivateItem(e)){h.setActiveItem(e);break}a+=g}},isWhitelisted:function(a){return Ext.FocusManager.isWhitelisted(a)},left:function(b){var c=this.menu,d=c.focusedItem,a=c.activeItem;if(d&&this.isWhitelisted(d)){return true}c.hide();if(c.parentMenu){c.parentMenu.focus()}},right:function(c){var d=this.menu,g=d.focusedItem,a=d.activeItem,b;if(g&&this.isWhitelisted(g)){return true}if(a){b=d.activeItem.menu;if(b){a.expandMenu(0);Ext.defer(function(){b.setActiveItem(b.items.getAt(0))},25)}}},tab:function(b){var a=this;if(b.shiftKey){a.up(b)}else{a.down(b)}},up:function(b){var a=this,c=a.menu.focusedItem;if(c&&b.getKey()==Ext.EventObject.UP&&a.isWhitelisted(c)){return true}a.focusNextItem(-1)}});Ext.define("Ext.menu.Manager",{singleton:true,requires:["Ext.util.MixedCollection","Ext.util.KeyMap"],alternateClassName:"Ext.menu.MenuMgr",uses:["Ext.menu.Menu"],menus:{},groups:{},attached:false,lastShow:new Date(),init:function(){var a=this;a.active=new Ext.util.MixedCollection();Ext.getDoc().addKeyListener(27,function(){if(a.active.length>0){a.hideAll()}},a)},hideAll:function(){var c=this.active,e,b,a,d;if(c&&c.length>0){e=c.clone();b=e.items;d=b.length;for(a=0;a50&&c.length>0&&!d.getTarget("."+Ext.baseCSSPrefix+"menu")){b.hideAll()}},register:function(b){var a=this;if(!a.active){a.init()}if(b.floating){a.menus[b.id]=b;b.on({beforehide:a.onBeforeHide,hide:a.onHide,beforeshow:a.onBeforeShow,show:a.onShow,scope:a})}},get:function(b){var a=this.menus;if(typeof b=="string"){if(!a){return null}return a[b]}else{if(b.isMenu){return b}else{if(Ext.isArray(b)){return new Ext.menu.Menu({items:b})}else{return Ext.ComponentManager.create(b,"menu")}}}},unregister:function(d){var a=this,b=a.menus,c=a.active;delete b[d.id];c.remove(d);d.un({beforehide:a.onBeforeHide,hide:a.onHide,beforeshow:a.onBeforeShow,show:a.onShow,scope:a})},registerCheckable:function(c){var a=this.groups,b=c.group;if(b){if(!a[b]){a[b]=[]}a[b].push(c)}},unregisterCheckable:function(c){var a=this.groups,b=c.group;if(b){Ext.Array.remove(a[b],c)}},onCheckChange:function(d,g){var a=this.groups,c=d.group,b=0,j,e,h;if(c&&g){j=a[c];e=j.length;for(;b class="{splitCls}">','',' tabIndex="{tabIndex}"',' disabled="disabled"',' role="link">','',"{text}","",' style="background-image:url({iconUrl})">',"","",'","","",'','',""],scale:"small",allowedScales:["small","medium","large"],iconAlign:"left",arrowAlign:"right",arrowCls:"arrow",maskOnDisable:false,persistentPadding:undefined,shrinkWrap:3,frame:true,initComponent:function(){var a=this;a.callParent(arguments);a.addEvents("click","toggle","mouseover","mouseout","menushow","menuhide","menutriggerover","menutriggerout");if(a.menu){a.split=true;a.menu=Ext.menu.Manager.get(a.menu);a.menu.ownerButton=a}if(a.url){a.href=a.url}if(a.href&&!a.hasOwnProperty("preventDefault")){a.preventDefault=false}if(Ext.isString(a.toggleGroup)){a.enableToggle=true}},getActionEl:function(){return this.btnEl},getFocusEl:function(){return this.inOnFocus?this.el:this.btnEl},onFocus:function(b){var a=this;a.inOnFocus=true;a.callParent(arguments);a.inOnFocus=false},onBlur:function(c){var b=this,a=b.focusCls,d=b.getEl();if(b.destroying){return}b.beforeBlur(c);if(a&&d){d.removeCls(b.removeClsWithUI(a,true))}if(b.validateOnBlur){b.validate()}b.hasFocus=false;b.fireEvent("blur",b,c);b.postBlur(c)},setComponentCls:function(){var b=this,a=b.getComponentCls();if(!Ext.isEmpty(b.oldCls)){b.removeClsWithUI(b.oldCls);b.removeClsWithUI(b.pressedCls)}b.oldCls=a;b.addClsWithUI(a)},getComponentCls:function(){var b=this,a=[];if(b.iconCls||b.icon){if(b.text){a.push("icon-text-"+b.iconAlign)}else{a.push("icon")}}else{if(b.text){a.push("noicon")}}if(b.pressed){a.push(b.pressedCls)}return a},beforeRender:function(){var a=this;a.callParent();a.oldCls=a.getComponentCls();a.addClsWithUI(a.oldCls);Ext.applyIf(a.renderData,a.getTemplateArgs());if(a.scale){a.setScale(a.scale)}},onRender:function(){var c=this,a,b;c.doc=Ext.getDoc();c.callParent(arguments);if(c.split&&c.arrowTooltip){c.arrowEl.dom.setAttribute(c.getTipAttr(),c.arrowTooltip)}a=c.el;if(c.tooltip){c.setTooltip(c.tooltip,true)}if(c.handleMouseEvents){b={scope:c,mouseover:c.onMouseOver,mouseout:c.onMouseOut,mousedown:c.onMouseDown};if(c.split){b.mousemove=c.onMouseMove}}else{b={scope:c}}if(c.menu){c.mon(c.menu,{scope:c,show:c.onMenuShow,hide:c.onMenuHide});c.keyMap=new Ext.util.KeyMap({target:c.el,key:Ext.EventObject.DOWN,handler:c.onDownKey,scope:c})}if(c.repeat){c.mon(new Ext.util.ClickRepeater(a,Ext.isObject(c.repeat)?c.repeat:{}),"click",c.onRepeatClick,c)}else{b[c.clickEvent]=c.onClick}c.mon(a,b);Ext.ButtonToggleManager.register(c)},getTemplateArgs:function(){var c=this,b=c.getPersistentPadding(),a="";if(Math.max.apply(Math,b)>0){a="margin:"+Ext.Array.map(b,function(d){return -d+"px"}).join(" ")}return{href:c.getHref(),disabled:c.disabled,hrefTarget:c.hrefTarget,type:c.type,btnCls:c.getBtnCls(),splitCls:c.getSplitCls(),iconUrl:c.icon,iconCls:c.iconCls,text:c.text||" ",tabIndex:c.tabIndex,innerSpanStyle:a}},getHref:function(){var a=this,b=Ext.apply({},a.baseParams);b=Ext.apply(b,a.params);return a.href?Ext.urlAppend(a.href,Ext.Object.toQueryString(b)):false},setParams:function(a){this.params=a;this.btnEl.dom.href=this.getHref()},getSplitCls:function(){var a=this;return a.split?(a.baseCls+"-"+a.arrowCls)+" "+(a.baseCls+"-"+a.arrowCls+"-"+a.arrowAlign):""},getBtnCls:function(){return this.textAlign?this.baseCls+"-"+this.textAlign:""},setIconCls:function(b){var d=this,a=d.btnIconEl,c=d.iconCls;d.iconCls=b;if(a){a.removeCls(c);a.addCls(b||"");d.setComponentCls();if(d.didIconStateChange(c,b)){d.updateLayout()}}return d},setTooltip:function(c,a){var b=this;if(b.rendered){if(!a){b.clearTip()}if(Ext.isObject(c)){Ext.tip.QuickTipManager.register(Ext.apply({target:b.btnEl.id},c));b.tooltip=c}else{b.btnEl.dom.setAttribute(b.getTipAttr(),c)}}else{b.tooltip=c}return b},setTextAlign:function(c){var b=this,a=b.btnEl;if(a){a.removeCls(b.baseCls+"-"+b.textAlign);a.addCls(b.baseCls+"-"+c)}b.textAlign=c;return b},getTipAttr:function(){return this.tooltipType=="qtip"?"data-qtip":"title"},getRefItems:function(a){var c=this.menu,b;if(c){b=c.getRefItems(a);b.unshift(c)}return b||[]},clearTip:function(){if(Ext.isObject(this.tooltip)){Ext.tip.QuickTipManager.unregister(this.btnEl)}},beforeDestroy:function(){var a=this;if(a.rendered){a.clearTip()}if(a.menu&&a.destroyMenu!==false){Ext.destroy(a.menu)}Ext.destroy(a.btnInnerEl,a.repeater);a.callParent()},onDestroy:function(){var a=this;if(a.rendered){a.doc.un("mouseover",a.monitorMouseOver,a);a.doc.un("mouseup",a.onMouseUp,a);delete a.doc;Ext.ButtonToggleManager.unregister(a);Ext.destroy(a.keyMap);delete a.keyMap}a.callParent()},setHandler:function(b,a){this.handler=b;this.scope=a;return this},setText:function(b){var a=this;a.text=b;if(a.rendered){a.btnInnerEl.update(b||" ");a.setComponentCls();if(Ext.isStrict&&Ext.isIE8){a.el.repaint()}a.updateLayout()}return a},setIcon:function(b){var c=this,a=c.btnIconEl,d=c.icon;c.icon=b;if(a){a.setStyle("background-image",b?"url("+b+")":"");c.setComponentCls();if(c.didIconStateChange(d,b)){c.updateLayout()}}return c},didIconStateChange:function(a,c){var b=Ext.isEmpty(c);return Ext.isEmpty(a)?!b:b},getText:function(){return this.text},toggle:function(c,a){var b=this;c=c===undefined?!b.pressed:!!c;if(c!==b.pressed){if(b.rendered){b[c?"addClsWithUI":"removeClsWithUI"](b.pressedCls)}b.pressed=c;if(!a){b.fireEvent("toggle",b,c);Ext.callback(b.toggleHandler,b.scope||b,[b,c])}}return b},maybeShowMenu:function(){var a=this;if(a.menu&&!a.hasVisibleMenu()&&!a.ignoreNextClick){a.showMenu()}},showMenu:function(){var a=this;if(a.rendered&&a.menu){if(a.tooltip&&a.getTipAttr()!="title"){Ext.tip.QuickTipManager.getQuickTip().cancelShow(a.btnEl)}if(a.menu.isVisible()){a.menu.hide()}a.menu.showBy(a.el,a.menuAlign,((!Ext.isStrict&&Ext.isIE)||Ext.isIE6)?[-2,-2]:undefined)}return a},hideMenu:function(){if(this.hasVisibleMenu()){this.menu.hide()}return this},hasVisibleMenu:function(){var a=this.menu;return a&&a.rendered&&a.isVisible()},onRepeatClick:function(a,b){this.onClick(b)},onClick:function(b){var a=this;if(a.preventDefault||(a.disabled&&a.getHref())&&b){b.preventDefault()}if(b.button!==0){return}if(!a.disabled){a.doToggle();a.maybeShowMenu();a.fireHandler(b)}},fireHandler:function(c){var b=this,a=b.handler;if(b.fireEvent("click",b,c)!==false){if(a){a.call(b.scope||b,b,c)}b.blur()}},doToggle:function(){var a=this;if(a.enableToggle&&(a.allowDepress!==false||!a.pressed)){a.toggle()}},onMouseOver:function(b){var a=this;if(!a.disabled&&!b.within(a.el,true,true)){a.onMouseEnter(b)}},onMouseOut:function(b){var a=this;if(!b.within(a.el,true,true)){if(a.overMenuTrigger){a.onMenuTriggerOut(b)}a.onMouseLeave(b)}},onMouseMove:function(h){var d=this,c=d.el,g=d.overMenuTrigger,b,a;if(d.split){if(d.arrowAlign==="right"){b=h.getX()-c.getX();a=c.getWidth()}else{b=h.getY()-c.getY();a=c.getHeight()}if(b>(a-d.getTriggerSize())){if(!g){d.onMenuTriggerOver(h)}}else{if(g){d.onMenuTriggerOut(h)}}}},getTriggerSize:function(){var e=this,c=e.triggerSize,b,a,d;if(c===d){b=e.arrowAlign;a=b.charAt(0);c=e.triggerSize=e.el.getFrameWidth(a)+e.btnWrap.getFrameWidth(a)+e.frameSize[b]}return c},onMouseEnter:function(b){var a=this;a.addClsWithUI(a.overCls);a.fireEvent("mouseover",a,b)},onMouseLeave:function(b){var a=this;a.removeClsWithUI(a.overCls);a.fireEvent("mouseout",a,b)},onMenuTriggerOver:function(b){var a=this;a.overMenuTrigger=true;a.fireEvent("menutriggerover",a,a.menu,b)},onMenuTriggerOut:function(b){var a=this;delete a.overMenuTrigger;a.fireEvent("menutriggerout",a,a.menu,b)},enable:function(a){var b=this;b.callParent(arguments);if(b.btnEl){b.btnEl.dom.disabled=false}b.removeClsWithUI("disabled");return b},disable:function(a){var b=this;b.callParent(arguments);if(b.btnEl){b.btnEl.dom.disabled=true}b.addClsWithUI("disabled");b.removeClsWithUI(b.overCls);if(b.btnInnerEl&&(Ext.isIE6||Ext.isIE7)){b.btnInnerEl.repaint()}return b},setScale:function(c){var a=this,b=a.ui.replace("-"+a.scale,"");if(!Ext.Array.contains(a.allowedScales,c)){throw ("#setScale: scale must be an allowed scale ("+a.allowedScales.join(", ")+")")}a.scale=c;a.setUI(b)},setUI:function(b){var a=this;if(a.scale&&!b.match(a.scale)){b=b+"-"+a.scale}a.callParent([b])},onMouseDown:function(b){var a=this;if(!a.disabled&&b.button===0){a.addClsWithUI(a.pressedCls);a.doc.on("mouseup",a.onMouseUp,a)}},onMouseUp:function(b){var a=this;if(b.button===0){if(!a.pressed){a.removeClsWithUI(a.pressedCls)}a.doc.un("mouseup",a.onMouseUp,a)}},onMenuShow:function(b){var a=this;a.ignoreNextClick=0;a.addClsWithUI(a.menuActiveCls);a.fireEvent("menushow",a,a.menu)},onMenuHide:function(b){var a=this;a.removeClsWithUI(a.menuActiveCls);a.ignoreNextClick=Ext.defer(a.restoreClick,250,a);a.fireEvent("menuhide",a,a.menu)},restoreClick:function(){this.ignoreNextClick=0},onDownKey:function(){var a=this;if(!a.disabled){if(a.menu){a.showMenu()}}},getPersistentPadding:function(){var d=this,e=d.persistentPadding,b,a,c,g;if(!e){e=d.self.prototype.persistentPadding=[0,0,0,0];if(!Ext.isIE){b=new Ext.button.Button({text:"test",style:"position:absolute;top:-999px;"});b.el=Ext.DomHelper.append(Ext.getBody(),b.getRenderTree(),true);b.applyChildEls(b.el);c=b.btnEl;g=b.btnInnerEl;c.setSize(null,null);a=g.getOffsetsTo(c);e[0]=a[1];e[1]=c.getWidth()-g.getWidth()-a[0];e[2]=c.getHeight()-g.getHeight()-a[1];e[3]=a[0];b.destroy();b.el.remove()}}return e}},function(){var a={},b=function(d,j){if(j){var h=a[d.toggleGroup],e=h.length,c;for(c=0;c {parent.baseCls}-body-{parent.ui}-{.}"',' style="{bodyStyle}">',"{%this.renderContainer(out,values)%}",""],headingTpl:'{title}',shrinkWrap:3,initComponent:function(){var b=this,e,d,a,c,g;b.addEvents("click","dblclick");b.indicateDragCls=b.baseCls+"-draggable";b.title=b.title||" ";b.tools=b.tools||[];b.items=b.items||[];b.orientation=b.orientation||"horizontal";b.dock=(b.dock)?b.dock:(b.orientation=="horizontal")?"top":"left";b.addClsWithUI([b.orientation,b.dock]);if(b.indicateDrag){b.addCls(b.indicateDragCls)}if(!Ext.isEmpty(b.iconCls)||!Ext.isEmpty(b.icon)){b.initIconCmp();b.items.push(b.iconCmp)}if(b.orientation=="vertical"){b.layout={type:"vbox",align:"center"};b.textConfig={width:16,cls:b.baseCls+"-text",type:"text",text:b.title,rotate:{degrees:90}};c=b.ui;if(Ext.isArray(c)){c=c[0]}e="."+b.baseCls+"-text-"+c;if(Ext.scopeResetCSS){e="."+Ext.baseCSSPrefix+"reset "+e}d=Ext.util.CSS.getRule(e);if(d){a=d.style}else{a=(g=Ext.getBody().createChild({style:"position:absolute",cls:b.baseCls+"-text-"+c})).getStyles("fontFamily","fontWeight","fontSize","color");g.remove()}if(a){Ext.apply(b.textConfig,{"font-family":a.fontFamily,"font-weight":a.fontWeight,"font-size":a.fontSize,fill:a.color})}b.titleCmp=new Ext.draw.Component({width:16,ariaRole:"heading",focusable:false,viewBox:false,flex:1,id:b.id+"_hd",autoSize:true,items:b.textConfig,xhooks:{setSize:function(h){this.callParent([h])}},childEls:[{name:"textEl",select:"."+b.baseCls+"-text"}]})}else{b.layout={type:"hbox",align:"middle"};b.titleCmp=new Ext.Component({ariaRole:"heading",focusable:false,noWrap:true,flex:1,id:b.id+"_hd",style:"text-align:"+b.titleAlign,cls:b.baseCls+"-text-container",renderTpl:b.getTpl("headingTpl"),renderData:{title:b.title,cls:b.baseCls,ui:b.ui},childEls:["textEl"]})}b.items.push(b.titleCmp);b.items=b.items.concat(b.tools);b.callParent();b.on({dblclick:b.onDblClick,click:b.onClick,element:"el",scope:b})},initIconCmp:function(){var b=this,a={focusable:false,src:Ext.BLANK_IMAGE_URL,cls:[b.baseCls+"-icon",b.iconCls],id:b.id+"-iconEl",iconCls:b.iconCls};if(!Ext.isEmpty(b.icon)){delete a.iconCls;a.src=b.icon}b.iconCmp=new Ext.Img(a)},afterRender:function(){this.el.unselectable();this.callParent()},addUIClsToElement:function(b){var e=this,a=e.callParent(arguments),d=[e.baseCls+"-body-"+b,e.baseCls+"-body-"+e.ui+"-"+b],g,c;if(e.bodyCls){g=e.bodyCls.split(" ");for(c=0;c','',' ',"",""],initComponent:function(){var a=this;a.callParent(arguments);a.addEvents("select");if(a.handler){a.on("select",a.handler,a.scope,true)}},initRenderData:function(){var a=this;return Ext.apply(a.callParent(),{itemCls:a.itemCls,colors:a.colors})},onRender:function(){var b=this,a=b.clickEvent;b.callParent(arguments);b.mon(b.el,a,b.handleClick,b,{delegate:"a"});if(a!="click"){b.mon(b.el,"click",Ext.emptyFn,b,{delegate:"a",stopEvent:true})}},afterRender:function(){var a=this,b;a.callParent(arguments);if(a.value){b=a.value;a.value=null;a.select(b,true)}},handleClick:function(c,d){var b=this,a;c.stopEvent();if(!b.disabled){a=d.className.match(b.colorRe)[1];b.select(a.toUpperCase())}},select:function(b,a){var d=this,g=d.selectedCls,e=d.value,c;b=b.replace("#","");if(!d.rendered){d.value=b;return}if(b!=e||d.allowReselect){c=d.el;if(d.value){c.down("a.color-"+e).removeCls(g)}c.down("a.color-"+b).addCls(g);d.value=b;if(a!==true){d.fireEvent("select",d,b)}}},getValue:function(){return this.value||null}});Ext.define("Ext.picker.Month",{extend:"Ext.Component",requires:["Ext.XTemplate","Ext.util.ClickRepeater","Ext.Date","Ext.button.Button"],alias:"widget.monthpicker",alternateClassName:"Ext.MonthPicker",childEls:["bodyEl","prevEl","nextEl","buttonsEl","monthEl","yearEl"],renderTpl:['
    ','
    ','','',"","
    ",'
    ','
    ','','',"
    ",'','',"","
    ",'
    ',"
    ",'','
    ',"
    "],okText:"OK",cancelText:"Cancel",baseCls:Ext.baseCSSPrefix+"monthpicker",showButtons:true,width:178,measureWidth:35,measureMaxHeight:20,smallCls:Ext.baseCSSPrefix+"monthpicker-small",totalYears:10,yearOffset:5,monthOffset:6,initComponent:function(){var a=this;a.selectedCls=a.baseCls+"-selected";a.addEvents("cancelclick","monthclick","monthdblclick","okclick","select","yearclick","yeardblclick");if(a.small){a.addCls(a.smallCls)}a.setValue(a.value);a.activeYear=a.getYear(new Date().getFullYear()-4,-4);this.callParent()},beforeRender:function(){var g=this,c=0,b=[],a=Ext.Date.getShortMonthName,e=g.monthOffset,h=g.monthMargin,d="";g.callParent();for(;cd.measureMaxHeight){--c;a.setStyle("margin","0 "+c+"px")}return c},getLargest:function(a){var b=0;this.months.each(function(d){var c=d.getHeight();if(c>b){b=c}});return b},setValue:function(d){var c=this,e=c.activeYear,g=c.monthOffset,b,a;if(!d){c.value=[null,null]}else{if(Ext.isDate(d)){c.value=[d.getMonth(),d.getFullYear()]}else{c.value=[d[0],d[1]]}}if(c.rendered){b=c.value[1];if(b!==null){if((be+c.yearOffset)){c.activeYear=b-c.yearOffset+1}}c.updateBody()}return c},getValue:function(){return this.value},hasSelection:function(){var a=this.value;return a[0]!==null&&a[1]!==null},getYears:function(){var d=this,e=d.yearOffset,g=d.activeYear,a=g+e,c=g,b=[];for(;c','",'','','','',"","",'','',"{#:this.isEndOfWeek}",'","","","",'','',"","",{firstInitial:function(a){return Ext.picker.Date.prototype.getDayInitial(a)},isEndOfWeek:function(b){b--;var a=b%7===0&&b!==0;return a?'':""},renderTodayBtn:function(a,b){Ext.DomHelper.generateMarkup(a.$comp.todayBtn.getRenderTree(),b)},renderMonthBtn:function(a,b){Ext.DomHelper.generateMarkup(a.$comp.monthBtn.getRenderTree(),b)}}],todayText:"Today",ariaTitle:"Date Picker: {0}",ariaTitleDateFormat:"F d, Y",todayTip:"{0} (Spacebar)",minText:"This date is before the minimum date",maxText:"This date is after the maximum date",disabledDaysText:"Disabled",disabledDatesText:"Disabled",nextText:"Next Month (Control+Right)",prevText:"Previous Month (Control+Left)",monthYearText:"Choose a month (Control+Up/Down to move years)",monthYearFormat:"F Y",startDay:0,showToday:true,disableAnim:false,baseCls:Ext.baseCSSPrefix+"datepicker",longDayFormat:"F d, Y",focusOnShow:false,focusOnSelect:true,width:178,initHour:12,numDays:42,initComponent:function(){var b=this,a=Ext.Date.clearTime;b.selectedCls=b.baseCls+"-selected";b.disabledCellCls=b.baseCls+"-disabled";b.prevCls=b.baseCls+"-prevday";b.activeCls=b.baseCls+"-active";b.nextCls=b.baseCls+"-prevday";b.todayCls=b.baseCls+"-today";b.dayNames=b.dayNames.slice(b.startDay).concat(b.dayNames.slice(0,b.startDay));b.listeners=Ext.apply(b.listeners||{},{mousewheel:{element:"eventEl",fn:b.handleMouseWheel,scope:b},click:{element:"eventEl",fn:b.handleDateClick,scope:b,delegate:"a."+b.baseCls+"-date"}});this.callParent();b.value=b.value?a(b.value,true):a(new Date());b.addEvents("select");b.initDisabledDays()},beforeRender:function(){var b=this,c=new Array(b.numDays),a=Ext.Date.format(new Date(),b.format);b.monthBtn=new Ext.button.Split({ownerCt:b,ownerLayout:b.getComponentLayout(),text:"",tooltip:b.monthYearText,listeners:{click:b.showMonthPicker,arrowclick:b.showMonthPicker,scope:b}});if(this.showToday){b.todayBtn=new Ext.button.Button({ownerCt:b,ownerLayout:b.getComponentLayout(),text:Ext.String.format(b.todayText,a),tooltip:Ext.String.format(b.todayTip,a),handler:b.selectToday,scope:b})}b.callParent();Ext.applyIf(b,{renderData:{}});Ext.apply(b.renderData,{dayNames:b.dayNames,showToday:b.showToday,prevText:b.prevText,nextText:b.nextText,days:c})},finishRenderChildren:function(){var a=this;a.callParent();a.monthBtn.finishRender();if(a.showToday){a.todayBtn.finishRender()}},onRender:function(b,a){var c=this;c.callParent(arguments);c.el.unselectable();c.cells=c.eventEl.select("tbody td");c.textNodes=c.eventEl.query("tbody td span")},initEvents:function(){var c=this,a=Ext.Date,b=a.DAY;c.callParent();c.prevRepeater=new Ext.util.ClickRepeater(c.prevEl,{handler:c.showPrevMonth,scope:c,preventDefault:true,stopDefault:true});c.nextRepeater=new Ext.util.ClickRepeater(c.nextEl,{handler:c.showNextMonth,scope:c,preventDefault:true,stopDefault:true});c.keyNav=new Ext.util.KeyNav(c.eventEl,Ext.apply({scope:c,left:function(d){if(d.ctrlKey){c.showPrevMonth()}else{c.update(a.add(c.activeDate,b,-1))}},right:function(d){if(d.ctrlKey){c.showNextMonth()}else{c.update(a.add(c.activeDate,b,1))}},up:function(d){if(d.ctrlKey){c.showNextYear()}else{c.update(a.add(c.activeDate,b,-7))}},down:function(d){if(d.ctrlKey){c.showPrevYear()}else{c.update(a.add(c.activeDate,b,7))}},pageUp:c.showNextMonth,pageDown:c.showPrevMonth,enter:function(d){d.stopPropagation();return true}},c.keyNavConfig));if(c.showToday){c.todayKeyListener=c.eventEl.addKeyListener(Ext.EventObject.SPACE,c.selectToday,c)}c.update(c.value)},initDisabledDays:function(){var h=this,b=h.disabledDates,g="(?:",a,i,c,e;if(!h.disabledDatesRE&&b){a=b.length-1;c=b.length;for(i=0;i0){this.showPrevMonth()}else{if(b<0){this.showNextMonth()}}}},handleDateClick:function(d,a){var c=this,b=c.handler;d.stopEvent();if(!c.disabled&&a.dateValue&&!Ext.fly(a.parentNode).hasCls(c.disabledCellCls)){c.doCancelFocus=c.focusOnSelect===false;c.setValue(new Date(a.dateValue));delete c.doCancelFocus;c.fireEvent("select",c,c.value);if(b){b.call(c.scope||c,c,c.value)}c.onSelect()}},onSelect:function(){if(this.hideOnSelect){this.hide()}},selectToday:function(){var c=this,a=c.todayBtn,b=c.handler;if(a&&!a.disabled){c.setValue(Ext.Date.clearTime(new Date()));c.fireEvent("select",c,c.value);if(b){b.call(c.scope||c,c,c.value)}c.onSelect()}return c},selectedUpdate:function(a){var d=this,i=a.getTime(),j=d.cells,k=d.selectedCls,g=j.elements,b,e=g.length,h;j.removeCls(k);for(b=0;bv||(C&&x&&C.test(n.dateFormat(F,x)))||(H&&H.indexOf(F.getDay())!=-1));if(!E.disabled){E.todayBtn.setDisabled(a);E.todayKeyListener.setDisabled(a)}}m=function(i){r=+n.clearTime(q,true);i.title=n.format(q,b);i.firstChild.dateValue=r;if(r==z){i.className+=" "+E.todayCls;i.title=E.todayText}if(r==u){i.className+=" "+E.selectedCls;E.fireEvent("highlightitem",E,i);if(e&&E.floating){Ext.fly(i.firstChild).focus(50)}}if(rv){i.className=G;i.title=E.maxText;return}if(H){if(H.indexOf(q.getDay())!=-1){i.title=B;i.className=G}}if(C&&x){j=n.dateFormat(q,x);if(C.test(j)){i.title=s.replace("%0",j);i.className=G}}};for(;w=l){o=(++D);c=E.nextCls}else{o=w-h+1;c=E.activeCls}}d[w].innerHTML=o;g[w].className=c;q.setDate(q.getDate()+1);m(g[w])}E.monthBtn.setText(Ext.Date.format(A,E.monthYearFormat))},update:function(a,d){var b=this,c=b.activeDate;if(b.rendered){b.activeDate=a;if(!d&&c&&b.el&&c.getMonth()==a.getMonth()&&c.getFullYear()==a.getFullYear()){b.selectedUpdate(a,c)}else{b.fullUpdate(a,c)}b.innerEl.dom.title=Ext.String.format(b.ariaTitle,Ext.Date.format(b.activeDate,b.ariaTitleDateFormat))}return b},beforeDestroy:function(){var a=this;if(a.rendered){Ext.destroy(a.todayKeyListener,a.keyNav,a.monthPicker,a.monthBtn,a.nextRepeater,a.prevRepeater,a.todayBtn);delete a.textNodes;delete a.cells.elements}a.callParent()},onShow:function(){this.callParent(arguments);if(this.focusOnShow){this.focus()}}},function(){var b=this.prototype,a=Ext.Date;b.monthNames=a.monthNames;b.dayNames=a.dayNames;b.format=a.defaultFormat});Ext.define("Ext.form.field.Date",{extend:"Ext.form.field.Picker",alias:"widget.datefield",requires:["Ext.picker.Date"],alternateClassName:["Ext.form.DateField","Ext.form.Date"],format:"m/d/Y",altFormats:"m/d/Y|n/j/Y|n/j/y|m/j/y|n/d/y|m/j/Y|n/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d|Y-m-d|n-j|n/j",disabledDaysText:"Disabled",disabledDatesText:"Disabled",minText:"The date in this field must be equal to or after {0}",maxText:"The date in this field must be equal to or before {0}",invalidText:"{0} is not a valid date - it must be in the format {1}",triggerCls:Ext.baseCSSPrefix+"form-date-trigger",showToday:true,useStrict:undefined,initTime:"12",initTimeFormat:"H",matchFieldWidth:false,startDay:0,initComponent:function(){var d=this,b=Ext.isString,c,a;c=d.minValue;a=d.maxValue;if(b(c)){d.minValue=d.parseDate(c)}if(b(a)){d.maxValue=d.parseDate(a)}d.disabledDatesRE=null;d.initDisabledDays();d.callParent()},initValue:function(){var a=this,b=a.value;if(Ext.isString(b)){a.value=a.rawToValue(b)}a.callParent()},initDisabledDays:function(){if(this.disabledDates){var b=this.disabledDates,a=b.length-1,g="(?:",h,e=b.length,c;for(h=0;hk(h).getTime()){o.push(p(j.maxText,j.formatDate(h)))}if(n){l=q.getDay();for(;eq){v=q}}if(v-m<2){return null}n=new Ext.util.Region(p,x,k,g);y.constraintAdjusters[a.collapseDirection](n,m,v,a);y.dragInfo={minRange:m,maxRange:v,targetSize:b};return n},constraintAdjusters:{left:function(c,a,b,d){c[0]=c.x=c.left=c.right+a;c.right+=b+d.getWidth()},top:function(c,a,b,d){c[1]=c.y=c.top=c.bottom+a;c.bottom+=b+d.getHeight()},bottom:function(c,a,b,d){c.bottom=c.top-a;c.top-=b+d.getHeight()},right:function(c,a,b,d){c.right=c.left-a;c.left-=b+d.getWidth()}},onBeforeStart:function(h){var k=this,b=k.splitter,a=b.collapseTarget,m=b.neighbors,d=k.getSplitter().collapseEl,j=h.getTarget(),c=m.length,g,l;if(d&&j===b.collapseEl.dom){return false}if(a.collapsed){return false}for(g=0;g','
     
    ',""],baseCls:Ext.baseCSSPrefix+"splitter",collapsedClsInternal:Ext.baseCSSPrefix+"splitter-collapsed",collapsible:false,collapseOnDblClick:true,defaultSplitMin:40,defaultSplitMax:1000,width:5,height:5,collapseTarget:"next",horizontal:false,vertical:false,getTrackerConfig:function(){return{xclass:"Ext.resizer.SplitterTracker",el:this.el,splitter:this}},beforeRender:function(){var a=this,b=a.getCollapseTarget(),c=a.getCollapseDirection();a.callParent();if(b.collapsed){a.addCls(a.collapsedClsInternal)}a.addCls(a.baseCls+"-"+a.orientation);Ext.applyIf(a.renderData,{collapseDir:c,collapsible:a.collapsible||b.collapsible})},onRender:function(){var a=this;a.callParent(arguments);if(a.performCollapse!==false){if(a.renderData.collapsible){a.mon(a.collapseEl,"click",a.toggleTargetCmp,a)}if(a.collapseOnDblClick){a.mon(a.el,"dblclick",a.toggleTargetCmp,a)}}a.mon(a.getCollapseTarget(),{collapse:a.onTargetCollapse,expand:a.onTargetExpand,scope:a});a.el.unselectable();a.tracker=Ext.create(a.getTrackerConfig());a.relayEvents(a.tracker,["beforedragstart","dragstart","dragend"])},getCollapseDirection:function(){var g=this,c=g.collapseDirection,e,a,b,d;if(!c){e=g.collapseTarget;if(e.isComponent){c=e.collapseDirection}if(!c){d=g.ownerCt.layout.type;if(e.isComponent){b=g.ownerCt.items;a=Number(b.indexOf(e)==b.indexOf(g)-1)<<1|Number(d=="hbox")}else{a=Number(g.collapseTarget=="prev")<<1|Number(d=="hbox")}c=["bottom","right","top","left"][a]}g.collapseDirection=c}g.orientation=(c=="top"||c=="bottom")?"horizontal":"vertical";g[g.orientation]=true;return c},getCollapseTarget:function(){var a=this;return a.collapseTarget.isComponent?a.collapseTarget:a.collapseTarget=="prev"?a.previousSibling():a.nextSibling()},onTargetCollapse:function(a){this.el.addCls([this.collapsedClsInternal,this.collapsedCls])},onTargetExpand:function(a){this.el.removeCls([this.collapsedClsInternal,this.collapsedCls])},toggleTargetCmp:function(d,b){var c=this.getCollapseTarget(),g=c.placeholder,a;if(g&&!g.hidden){a=true}else{a=!c.hidden}if(a){if(c.collapsed){c.expand()}else{if(c.collapseDirection){c.collapse()}else{c.collapse(this.renderData.collapseDir)}}}},setSize:function(){var a=this;a.callParent(arguments);if(Ext.isIE&&a.el){a.el.repaint()}}});Ext.define("Ext.resizer.BorderSplitter",{extend:"Ext.resizer.Splitter",uses:["Ext.resizer.BorderSplitterTracker"],alias:"widget.bordersplitter",collapseTarget:null,getTrackerConfig:function(){var a=this.callParent();a.xclass="Ext.resizer.BorderSplitterTracker";return a}});Ext.define("Ext.layout.container.Border",{alias:"layout.border",extend:"Ext.layout.container.Container",requires:["Ext.resizer.BorderSplitter","Ext.Component","Ext.fx.Anim"],alternateClassName:"Ext.layout.BorderLayout",targetCls:Ext.baseCSSPrefix+"border-layout-ct",itemCls:[Ext.baseCSSPrefix+"border-item",Ext.baseCSSPrefix+"box-item"],type:"border",padding:undefined,percentageRe:/(\d+)%/,axisProps:{horz:{borderBegin:"west",borderEnd:"east",horizontal:true,posProp:"x",sizeProp:"width",sizePropCap:"Width"},vert:{borderBegin:"north",borderEnd:"south",horizontal:false,posProp:"y",sizeProp:"height",sizePropCap:"Height"}},centerRegion:null,collapseDirections:{north:"top",south:"bottom",east:"right",west:"left"},manageMargins:true,panelCollapseAnimate:true,panelCollapseMode:"placeholder",regionWeights:{north:20,south:10,center:0,west:-10,east:-20},beginAxis:function(m,b,w){var u=this,c=u.axisProps[w],r=!c.horizontal,l=c.sizeProp,p=0,a=m.childItems,g=a.length,t,q,o,h,s,e,k,n,d,v,j;for(q=0;q=c.store.getCount()){d=c.store.getCount()-1}b=c.store.getAt(d);if(g.shiftKey){c.selectRange(b,g.record,g.ctrlKey,"down");c.setLastFocused(b)}else{if(g.ctrlKey){g.preventDefault();c.setLastFocused(b)}else{c.doSelect(b)}}}},onKeySpace:function(c){var b=this,a=b.lastFocused;if(a){if(b.isSelected(a)){b.doDeselect(a,false)}else{b.doSelect(a,true)}}},onKeyUp:function(d){var c=this,a=c.store.indexOf(c.lastFocused),b;if(a>0){b=c.store.getAt(a-1);if(d.shiftKey&&c.lastFocused){if(c.isSelected(c.lastFocused)&&c.isSelected(b)){c.doDeselect(c.lastFocused,true);c.setLastFocused(b)}else{if(!c.isSelected(c.lastFocused)){c.doSelect(c.lastFocused,true);c.doSelect(b,true)}else{c.doSelect(b,true)}}}else{if(d.ctrlKey){c.setLastFocused(b)}else{c.doSelect(b)}}}},onKeyDown:function(d){var c=this,a=c.store.indexOf(c.lastFocused),b;if(a+1 '},onRowMouseDown:function(b,a,h,d,i){b.el.focus();var g=this,c=i.getTarget("."+Ext.baseCSSPrefix+"grid-row-checker"),j;if(!g.allowRightMouseSelection(i)){return}if(g.checkOnly&&!c){return}if(c){j=g.getSelectionMode();if(j!=="SINGLE"){g.setSelectionMode("SIMPLE")}g.selectWithEvent(a,i);g.setSelectionMode(j)}else{g.selectWithEvent(a,i)}},onSelectChange:function(){this.callParent(arguments);var a=this.selected.getCount()===this.store.getCount();this.toggleUiHeader(a)}});Ext.define("Ext.selection.TreeModel",{extend:"Ext.selection.RowModel",alias:"selection.treemodel",pruneRemoved:false,onKeyRight:function(d,b){var c=this.getLastFocused(),a=this.view;if(c){if(c.isExpanded()){this.onKeyDown(d,b)}else{if(!c.isLeaf()){a.expand(c)}}}},onKeyLeft:function(i,d){var h=this.getLastFocused(),c=this.view,b=c.getSelectionModel(),a,g;if(h){a=h.parentNode;if(h.isExpanded()){c.collapse(h)}else{if(a&&!a.isRoot()){if(i.shiftKey){b.selectRange(a,h,i.ctrlKey,"up");b.setLastFocused(a)}else{if(i.ctrlKey){b.setLastFocused(a)}else{b.select(a)}}}}}},onKeyPress:function(g,b){var a=g.getKey(),c,d;if(a===g.SPACE||a===g.ENTER){g.stopEvent();c=this.getLastSelected();if(c){this.view.onCheckChange(c)}}else{this.callParent(arguments)}}});Ext.define("Ext.tab.Tab",{extend:"Ext.button.Button",alias:"widget.tab",requires:["Ext.layout.component.Tab","Ext.util.KeyNav"],componentLayout:"tab",isTab:true,baseCls:Ext.baseCSSPrefix+"tab",activeCls:"active",closableCls:"closable",closable:true,closeText:"Close Tab",active:false,childEls:["closeEl"],scale:false,position:"top",initComponent:function(){var a=this;a.addEvents("activate","deactivate","beforeclose","close");a.callParent(arguments);if(a.card){a.setCard(a.card)}},getTemplateArgs:function(){var b=this,a=b.callParent();a.closable=b.closable;a.closeText=b.closeText;return a},beforeRender:function(){var b=this,a=b.up("tabbar"),c=b.up("tabpanel");b.callParent();b.addClsWithUI(b.position);b.syncClosableUI();if(!b.minWidth){b.minWidth=(a)?a.minTabWidth:b.minWidth;if(!b.minWidth&&c){b.minWidth=c.minTabWidth}if(b.minWidth&&b.iconCls){b.minWidth+=25}}if(!b.maxWidth){b.maxWidth=(a)?a.maxTabWidth:b.maxWidth;if(!b.maxWidth&&c){b.maxWidth=c.maxTabWidth}}},onRender:function(){var a=this;a.callParent(arguments);a.keyNav=new Ext.util.KeyNav(a.el,{enter:a.onEnterKey,del:a.onDeleteKey,scope:a})},enable:function(a){var b=this;b.callParent(arguments);b.removeClsWithUI(b.position+"-disabled");return b},disable:function(a){var b=this;b.callParent(arguments);b.addClsWithUI(b.position+"-disabled");return b},onDestroy:function(){var a=this;Ext.destroy(a.keyNav);delete a.keyNav;a.callParent(arguments)},setClosable:function(a){var b=this;a=(!arguments.length||!!a);if(b.closable!=a){b.closable=a;if(b.card){b.card.closable=a}b.syncClosableUI();if(b.rendered){b.syncClosableElements();b.updateLayout()}}},syncClosableElements:function(){var a=this,b=a.closeEl;if(a.closable){if(!b){a.closeEl=a.btnWrap.insertSibling({tag:"a",cls:a.baseCls+"-close-btn",href:"#",title:a.closeText},"after")}}else{if(b){b.remove();delete a.closeEl}}},syncClosableUI:function(){var b=this,a=[b.closableCls,b.closableCls+"-"+b.position];if(b.closable){b.addClsWithUI(a)}else{b.removeClsWithUI(a)}},setCard:function(a){var b=this;b.card=a;b.setText(b.title||a.title);b.setIconCls(b.iconCls||a.iconCls);b.setIcon(b.icon||a.icon)},onCloseClick:function(){var a=this;if(a.fireEvent("beforeclose",a)!==false){if(a.tabBar){if(a.tabBar.closeTab(a)===false){return}}else{a.fireClose()}}},fireClose:function(){this.fireEvent("close",this)},onEnterKey:function(b){var a=this;if(a.tabBar){a.tabBar.onClick(b,a.el)}},onDeleteKey:function(a){if(this.closable){this.onCloseClick()}},activate:function(b){var a=this;a.active=true;a.addClsWithUI([a.activeCls,a.position+"-"+a.activeCls]);if(b!==true){a.fireEvent("activate",a)}},deactivate:function(b){var a=this;a.active=false;a.removeClsWithUI([a.activeCls,a.position+"-"+a.activeCls]);if(b!==true){a.fireEvent("deactivate",a)}}});Ext.define("Ext.tab.Bar",{extend:"Ext.panel.Header",alias:"widget.tabbar",baseCls:Ext.baseCSSPrefix+"tab-bar",requires:["Ext.tab.Tab"],isTabBar:true,defaultType:"tab",plain:false,childEls:["body","strip"],renderTpl:['
    {baseCls}-body-{ui} {parent.baseCls}-body-{parent.ui}-{.}" style="{bodyStyle}">',"{%this.renderContainer(out,values)%}","
    ",'
    {baseCls}-strip-{ui} {parent.baseCls}-strip-{parent.ui}-{.}">
    '],initComponent:function(){var a=this;if(a.plain){a.setUI(a.ui+"-plain")}a.addClsWithUI(a.dock);a.addEvents("change");a.callParent(arguments);a.layout.align=(a.orientation=="vertical")?"left":"top";a.layout.overflowHandler=new Ext.layout.container.boxOverflow.Scroller(a.layout);a.remove(a.titleCmp);delete a.titleCmp;Ext.apply(a.renderData,{bodyCls:a.bodyCls})},getLayout:function(){var a=this;a.layout.type=(a.dock==="top"||a.dock==="bottom")?"hbox":"vbox";return a.callParent(arguments)},onAdd:function(a){a.position=this.dock;this.callParent(arguments)},onRemove:function(a){var b=this;if(a===b.previousTab){b.previousTab=null}b.callParent(arguments)},afterComponentLayout:function(a){this.callParent(arguments);this.strip.setWidth(a)},onClick:function(g,d){var c=this,i=g.getTarget("."+Ext.tab.Tab.prototype.baseCls),b=i&&Ext.getCmp(i.id),h=c.tabPanel,a=b&&b.closeEl&&(d===b.closeEl.dom);if(a){g.preventDefault()}if(b&&b.isDisabled&&!b.isDisabled()){if(b.closable&&a){b.onCloseClick()}else{if(h){h.setActiveTab(b.card)}else{c.setActiveTab(b)}b.focus()}}},closeTab:function(c){var d=this,b=c.card,e=d.tabPanel,a;if(b&&b.fireEvent("beforeclose",b)===false){return false}a=d.findNextActivatable(c);Ext.suspendLayouts();if(e&&b){delete c.ownerCt;b.fireEvent("close",b);e.remove(b);if(!e.getComponent(b)){c.fireClose();d.remove(c)}else{c.ownerCt=d;Ext.resumeLayouts(true);return false}}if(a){if(e){e.setActiveTab(a.card)}else{d.setActiveTab(a)}a.focus()}Ext.resumeLayouts(true)},findNextActivatable:function(a){var b=this;if(a.active&&b.items.getCount()>1){return(b.previousTab&&b.previousTab!==a&&!b.previousTab.disabled)?b.previousTab:(a.next("tab[disabled=false]")||a.prev("tab[disabled=false]"))}},setActiveTab:function(a){var b=this;if(!a.disabled&&a!==b.activeTab){if(b.activeTab){if(b.activeTab.isDestroyed){b.previousTab=null}else{b.previousTab=b.activeTab;b.activeTab.deactivate()}}a.activate();b.activeTab=a;b.fireEvent("change",b,a,a.card);b.on({afterlayout:b.afterTabActivate,scope:b,single:true});b.updateLayout()}},afterTabActivate:function(){this.layout.overflowHandler.scrollToItem(this.activeTab)}});Ext.define("Ext.toolbar.Fill",{extend:"Ext.Component",alias:"widget.tbfill",alternateClassName:"Ext.Toolbar.Fill",isFill:true,flex:1});Ext.define("Ext.toolbar.Item",{extend:"Ext.Component",alias:"widget.tbitem",alternateClassName:"Ext.Toolbar.Item",enable:Ext.emptyFn,disable:Ext.emptyFn,focus:Ext.emptyFn});Ext.define("Ext.toolbar.Separator",{extend:"Ext.toolbar.Item",alias:"widget.tbseparator",alternateClassName:"Ext.Toolbar.Separator",baseCls:Ext.baseCSSPrefix+"toolbar-separator",focusable:false});Ext.define("Ext.layout.container.boxOverflow.Menu",{extend:"Ext.layout.container.boxOverflow.None",requires:["Ext.toolbar.Separator","Ext.button.Button"],alternateClassName:"Ext.layout.boxOverflow.Menu",noItemsMenuText:'
    (None)
    ',constructor:function(b){var a=this;a.callParent(arguments);a.triggerButtonCls=a.triggerButtonCls||Ext.baseCSSPrefix+"box-menu-"+b.getNames().right;a.menuItems=[]},beginLayout:function(a){this.callParent(arguments);this.clearOverflow(a)},beginLayoutCycle:function(b,a){this.callParent(arguments);if(!a){this.clearOverflow(b);this.layout.cacheChildItems(b)}},onRemove:function(a){Ext.Array.remove(this.menuItems,a)},getSuffixConfig:function(){var c=this,b=c.layout,a=b.owner.id;c.menu=new Ext.menu.Menu({listeners:{scope:c,beforeshow:c.beforeMenuShow}});c.menuTrigger=new Ext.button.Button({id:a+"-menu-trigger",cls:Ext.layout.container.Box.prototype.innerCls+" "+c.triggerButtonCls,hidden:true,ownerCt:b.owner,ownerLayout:b,iconCls:Ext.baseCSSPrefix+c.getOwnerType(b.owner)+"-more-icon",ui:b.owner instanceof Ext.toolbar.Toolbar?"default-toolbar":"default",menu:c.menu,getSplitCls:function(){return""}});return c.menuTrigger.getRenderTree()},getOverflowCls:function(){return Ext.baseCSSPrefix+this.layout.direction+"-box-overflow-body"},handleOverflow:function(e){var d=this,c=d.layout,h=c.getNames(),a="get"+h.widthCap,g=e.state.boxPlan,b=[null,null];d.showTrigger(e);b[h.heightIndex]=(g.maxSize-d.menuTrigger["get"+h.heightCap]())/2;d.menuTrigger.setPosition.apply(d.menuTrigger,b);return{reservedSpace:d.menuTrigger[a]()}},captureChildElements:function(){var a=this.menuTrigger;if(a.rendering){a.finishRender()}},clearOverflow:function(h){var g=this,b=g.menuItems,e,c=0,d=b.length,a=g.layout.owner;a.suspendLayouts();g.captureChildElements();g.hideTrigger();a.resumeLayouts();for(;cb){j=q.target;o.menuItems.push(j);j.hide()}}a.resumeLayouts()},hideTrigger:function(){var a=this.menuTrigger;if(a){a.hide()}},beforeMenuShow:function(j){var h=this,b=h.menuItems,d=0,a=b.length,g,e,c=function(k,i){return k.isXType("buttongroup")&&!(i instanceof Ext.toolbar.Separator)};j.suspendLayouts();h.clearMenu();j.removeAll();for(;d','
    ',"{%this.renderBody(out, values)%}","
    ","","{%if (oh.getSuffixConfig!==Ext.emptyFn) {","if(oc=oh.getSuffixConfig())dh.generateMarkup(oc, out)","}%}",{disableFormats:true,definitions:"var dh=Ext.DomHelper;"}],constructor:function(a){var c=this,b;c.callParent(arguments);c.flexSortFn=Ext.Function.bind(c.flexSort,c);c.initOverflowHandler();b=typeof c.padding;if(b=="string"||b=="number"){c.padding=Ext.util.Format.parseBox(c.padding);c.padding.height=c.padding.top+c.padding.bottom;c.padding.width=c.padding.left+c.padding.right}},getNames:function(){return this.names},getItemSizePolicy:function(d,e){var c=this,g=c.sizePolicy,h=c.align,b=h,a;if(h==="stretch"){a=(e||c.owner.getSizeModel())[c.names.height];if(a.shrinkWrap){b="stretchmax"}}else{if(h!=="stretchmax"){b=""}}if(d.flex){g=g.flex}return g[b]},flexSort:function(d,c){var e=this.getNames().maxWidth,g=Infinity;d=d.target[e]||g;c=c.target[e]||g;if(!isFinite(d)&&!isFinite(c)){return 0}return d-c},isItemBoxParent:function(a){return true},isItemShrinkWrap:function(a){return true},minSizeSortFn:function(d,c){return c.available-d.available},roundFlex:function(a){return Math.ceil(a)},beginCollapse:function(b){var a=this;if(a.direction==="vertical"&&b.collapsedVertical()){b.collapseMemento.capture(["flex"]);delete b.flex}else{if(a.direction==="horizontal"&&b.collapsedHorizontal()){b.collapseMemento.capture(["flex"]);delete b.flex}}},beginExpand:function(a){a.collapseMemento.restore(["flex"])},beginLayout:function(c){var b=this,e=b.owner.stretchMaxPartner,a=b.innerCt.dom.style,d=b.getNames();b.overflowHandler.beginLayout(c);if(typeof e==="string"){e=Ext.getCmp(e)||b.owner.query(e)[0]}c.stretchMaxPartner=e&&c.context.getCmp(e);b.callParent(arguments);c.innerCtContext=c.getEl("innerCt",b);b.scrollParallel=!!(b.owner.autoScroll||b.owner[d.overflowX]);b.scrollPerpendicular=!!(b.owner.autoScroll||b.owner[d.overflowY]);if(b.scrollParallel){b.scrollPos=b.owner.getTargetEl().dom[d.scrollLeft]}a.width="";a.height="";b.cacheFlexes(c)},beginLayoutCycle:function(b,m){var j=this,e=j.align,h=j.getNames(),l=j.pack,k=h.heightModel,d,n,c,a,g;j.overflowHandler.beginLayoutCycle(b,m);j.callParent(arguments);b.parallelSizeModel=b[h.widthModel];b.perpendicularSizeModel=b[k];b.boxOptions={align:e={stretch:e=="stretch",stretchmax:e=="stretchmax",center:e==h.center},pack:l={center:l=="center",end:l=="end"}};if(e.stretch&&b.perpendicularSizeModel.shrinkWrap){e.stretchmax=true;e.stretch=false}if(b.parallelSizeModel.shrinkWrap){l.center=l.end=false}if(e.stretchmax){d=b.childItems;a=d.length;g=j.sizeModels.shrinkWrap;for(c=0;c1&&d.boxOptions.align.stretchmax&&!c.stretchMaxDone){b.calculateStretchMax(d,h,g);c.stretchMaxDone=true}}else{b.done=false}},calculateParallel:function(g,k,b){var A=this,l=g.parallelSizeModel.shrinkWrap,w=k.width,a=g.childItems,c=k.left,p=k.right,o=k.setWidth,x=a.length,u=g.flexedItems,q=u.length,t=g.boxOptions.pack,j=A.padding,d=j[c],z=d+j[p]+A.scrollOffset+(A.reserveOffset?A.availableSpaceOffset:0),s,h,e,v,m,r,y,n;for(s=0;s0){F=u+Math.round(q/2)}}}v.setProp(C,F)}return true},calculateStretchMax:function(d,k,m){var l=this,h=k.height,n=k.width,g=d.childItems,b=g.length,o=m.maxSize,a=l.onBeforeInvalidateChild,q=l.onAfterInvalidateChild,p,j,e,c;for(e=0;ek.targetSize[i.height]){b.setProp(a,b.state.contentWidth+b.state.additionalScrollbarWidth);if(Ext.isIE6||Ext.isIE7||Ext.isIEQuirks){b[i.setWidth](b.props[a]+b.getPaddingInfo()[i.width]+b.getBorderInfo()[i.width])}}else{b.setProp(a,b.state.contentWidth)}}if(isNaN(c+n)){j.done=false}if(k.calculatedWidth&&(p=="left"||p=="right")){b.setWidth(k.calculatedWidth,true,true)}},onRemove:function(a){var b=this;b.callParent(arguments);if(b.overflowHandler){b.overflowHandler.onRemove(a)}if(a.layoutMarginCap==b.id){delete a.layoutMarginCap}},initOverflowHandler:function(){var d=this,c=d.overflowHandler,b,a;if(typeof c=="string"){c={type:c}}b="None";if(c&&c.type!==undefined){b=c.type}a=Ext.layout.container.boxOverflow[b];if(a[d.type]){a=a[d.type]}d.overflowHandler=Ext.create("Ext.layout.container.boxOverflow."+b,d,c)},getRenderTarget:function(){return this.targetEl},getElementTarget:function(){return this.innerCt},destroy:function(){Ext.destroy(this.innerCt,this.overflowHandler);this.callParent(arguments)}});Ext.define("Ext.layout.container.HBox",{alias:["layout.hbox"],extend:"Ext.layout.container.Box",alternateClassName:"Ext.layout.HBoxLayout",align:"top",type:"hbox",direction:"horizontal",horizontal:true,names:{lr:"lr",left:"left",leftCap:"Left",right:"right",position:"left",width:"width",contentWidth:"contentWidth",minWidth:"minWidth",maxWidth:"maxWidth",widthCap:"Width",widthModel:"widthModel",widthIndex:0,x:"x",scrollLeft:"scrollLeft",overflowX:"overflowX",center:"middle",top:"top",topPosition:"top",bottom:"bottom",height:"height",contentHeight:"contentHeight",minHeight:"minHeight",maxHeight:"maxHeight",heightCap:"Height",heightModel:"heightModel",heightIndex:1,y:"y",scrollTop:"scrollTop",overflowY:"overflowY",getWidth:"getWidth",getHeight:"getHeight",setWidth:"setWidth",setHeight:"setHeight",gotWidth:"gotWidth",gotHeight:"gotHeight",setContentWidth:"setContentWidth",setContentHeight:"setContentHeight"},sizePolicy:{flex:{"":{setsWidth:1,setsHeight:0},stretch:{setsWidth:1,setsHeight:1},stretchmax:{readsHeight:1,setsWidth:1,setsHeight:1}},"":{setsWidth:0,setsHeight:0},stretch:{setsWidth:0,setsHeight:1},stretchmax:{readsHeight:1,setsWidth:0,setsHeight:1}}});Ext.define("Ext.grid.ColumnLayout",{extend:"Ext.layout.container.HBox",alias:"layout.gridcolumn",type:"gridcolumn",reserveOffset:false,firstHeaderCls:Ext.baseCSSPrefix+"column-header-first",lastHeaderCls:Ext.baseCSSPrefix+"column-header-last",beginLayout:function(c){var h=this,b=h.owner,a=b.up("[scrollerOwner]"),j=a.view,d=0,g=h.getVisibleItems(),e=g.length,k;if(a.lockable){if(h.owner.up("tablepanel")===j.normalGrid){j=j.normalGrid.getView()}else{j=null}}h.callParent(arguments);for(;d0){g[0].addCls(h.firstHeaderCls);g[e-1].addCls(h.lastHeaderCls)}if(!h.owner.isHeader&&Ext.getScrollbarSize().width&&!a.collapsed&&j&&j.rendered&&(c.viewTable=j.el.child("table",true))){c.viewContext=c.context.getCmp(j)}},roundFlex:function(a){return Math.floor(a)},getContainerSize:function(e){var d=this,a=d.callParent(arguments),c=e.viewContext,b;if(c&&!c.heightModel.shrinkWrap&&c.target.componentLayout.ownerContext){b=c.getProp("height");if(isNaN(b)){d.done=false}else{if(e.state.tableHeight>b){a.width-=Ext.getScrollbarSize().width;e.state.parallelDone=false;c.invalidate()}}}return a},calculate:function(c){var b=this,a=c.viewContext;if(a&&!c.state.tableHeight){c.state.tableHeight=c.viewTable.offsetHeight}b.callParent(arguments)},completeLayout:function(c){var j=this,b=j.owner,a=c.state,g=false,k=j.sizeModels.calculated,e,h,d,m,l;j.callParent(arguments);if(!a.flexesCalculated&&b.forceFit&&!b.isHeader){e=c.childItems;h=e.length;for(d=0;dgridcolumn[hideable]"),h=a.length,d;for(;b{text}
    {%this.renderContainer(out,values)%}',dataIndex:null,text:" ",menuText:null,emptyCellText:" ",sortable:true,resizable:true,hideable:true,menuDisabled:false,renderer:false,editRenderer:false,align:"left",draggable:true,initDraggable:Ext.emptyFn,isHeader:true,componentLayout:"columncomponent",initResizable:Ext.emptyFn,initComponent:function(){var a=this,b;if(Ext.isDefined(a.header)){a.text=a.header;delete a.header}if(!a.triStateSort){a.possibleSortStates.length=2}if(Ext.isDefined(a.columns)){a.isGroupHeader=true;a.items=a.columns;delete a.columns;delete a.flex;delete a.width;a.cls=(a.cls||"")+" "+Ext.baseCSSPrefix+"group-header";a.sortable=false;a.resizable=false;a.align="center"}else{a.isContainer=false;if(a.flex){a.minWidth=a.minWidth||Ext.grid.plugin.HeaderResizer.prototype.minColWidth}}a.addCls(Ext.baseCSSPrefix+"column-header-align-"+a.align);b=a.renderer;if(b){if(typeof b=="string"){a.renderer=Ext.util.Format[b]}a.hasCustomRenderer=true}else{if(a.defaultRenderer){a.scope=a;a.renderer=a.defaultRenderer}}a.callParent(arguments);a.on({element:"el",click:a.onElClick,dblclick:a.onElDblClick,scope:a});a.on({element:"titleEl",mouseenter:a.onTitleMouseOver,mouseleave:a.onTitleMouseOut,scope:a})},onAdd:function(a){a.isSubHeader=true;a.addCls(Ext.baseCSSPrefix+"group-sub-header");this.callParent(arguments)},onRemove:function(a){a.isSubHeader=false;a.removeCls(Ext.baseCSSPrefix+"group-sub-header");this.callParent(arguments)},initRenderData:function(){var a=this;return Ext.applyIf(a.callParent(arguments),{text:a.text,menuDisabled:a.menuDisabled})},applyColumnState:function(b){var a=this,c=Ext.isDefined;a.applyColumnsState(b.columns);if(c(b.hidden)){a.hidden=b.hidden}if(c(b.locked)){a.locked=b.locked}if(c(b.sortable)){a.sortable=b.sortable}if(c(b.width)){delete a.flex;a.width=b.width}else{if(c(b.flex)){delete a.width;a.flex=b.flex}}},getColumnState:function(){var e=this,b=e.items.items,a=b?b.length:0,d,c=[],g={id:e.getStateId()};e.savePropsToState(["hidden","sortable","locked","flex","width"],g);if(e.isGroupHeader){for(d=0;d:not([hidden])");if(h.length===1&&h[0]==j){j.ownerCt.hide();return}}Ext.suspendLayouts();if(j.isGroupHeader){h=j.items.items;for(d=0,g=h.length;d*");for(e=0,a=c.length;eActions",sortable:false,constructor:function(c){var d=this,a=Ext.apply({},c),b=a.items||[d];d.origRenderer=a.renderer||d.renderer;d.origScope=a.scope||d.scope;delete d.renderer;delete d.scope;delete a.renderer;delete a.scope;delete a.items;d.callParent([a]);d.items=b;if(d.origRenderer){d.hasCustomRenderer=true}},defaultRenderer:function(g,j){var e=this,b=Ext.baseCSSPrefix,k=e.origScope||e,d=e.items,c=d.length,a=0,h;g=Ext.isFunction(e.origRenderer)?e.origRenderer.apply(k,arguments)||"":"";j.tdCls+=" "+Ext.baseCSSPrefix+"action-col-cell";for(;a"}return g},enableAction:function(b,a){var c=this;if(!b){b=0}else{if(!Ext.isNumber(b)){b=Ext.Array.indexOf(c.items,b)}}c.items[b].disabled=false;c.up("tablepanel").el.select("."+Ext.baseCSSPrefix+"action-col-"+b).removeCls(c.disabledCls);if(!a){c.fireEvent("enable",c)}},disableAction:function(b,a){var c=this;if(!b){b=0}else{if(!Ext.isNumber(b)){b=Ext.Array.indexOf(c.items,b)}}c.items[b].disabled=true;c.up("tablepanel").el.select("."+Ext.baseCSSPrefix+"action-col-"+b).addCls(c.disabledCls);if(!a){c.fireEvent("disable",c)}},destroy:function(){delete this.items;delete this.renderer;return this.callParent(arguments)},processEvent:function(i,l,n,a,j,g,c,p){var h=this,d=g.getTarget(),b,o,k,m=i=="keydown"&&g.getKey();if(m&&!Ext.fly(d).findParent(l.cellSelector)){d=Ext.fly(n).down("."+Ext.baseCSSPrefix+"action-col-icon",true)}if(d&&(b=d.className.match(h.actionIdRe))){o=h.items[parseInt(b[1],10)];if(o){if(i=="click"||(m==g.ENTER||m==g.SPACE)){k=o.handler||h.handler;if(k&&!o.disabled){k.call(o.scope||h.scope||h,l,a,j,o,g,c,p)}}else{if(i=="mousedown"&&o.stopSelection!==false){return false}}}}return h.callParent(arguments)},cascade:function(b,a){b.call(a||this,this)},getRefItems:function(){return[]}});Ext.define("Ext.grid.column.Boolean",{extend:"Ext.grid.column.Column",alias:["widget.booleancolumn"],alternateClassName:"Ext.grid.BooleanColumn",trueText:"true",falseText:"false",undefinedText:" ",defaultRenderer:function(a){if(a===undefined){return this.undefinedText}if(!a||a==="false"){return this.falseText}return this.trueText}});Ext.define("Ext.grid.column.Date",{extend:"Ext.grid.column.Column",alias:["widget.datecolumn"],requires:["Ext.Date"],alternateClassName:"Ext.grid.DateColumn",initComponent:function(){if(!this.format){this.format=Ext.Date.defaultFormat}this.callParent(arguments)},defaultRenderer:function(a){return Ext.util.Format.date(a,this.format)}});Ext.define("Ext.grid.column.Number",{extend:"Ext.grid.column.Column",alias:["widget.numbercolumn"],requires:["Ext.util.Format"],alternateClassName:"Ext.grid.NumberColumn",format:"0,000.00",defaultRenderer:function(a){return Ext.util.Format.number(a,this.format)}});Ext.define("Ext.grid.column.Template",{extend:"Ext.grid.column.Column",alias:["widget.templatecolumn"],requires:["Ext.XTemplate"],alternateClassName:"Ext.grid.TemplateColumn",initComponent:function(){var a=this;a.tpl=(!Ext.isPrimitive(a.tpl)&&a.tpl.compile)?a.tpl:new Ext.XTemplate(a.tpl);a.hasCustomRenderer=true;a.callParent(arguments)},defaultRenderer:function(c,d,a){var b=Ext.apply({},a.data,a.getAssociatedData());return this.tpl.apply(b)}});Ext.define("Ext.grid.plugin.Editing",{alias:"editing.editing",requires:["Ext.grid.column.Column","Ext.util.KeyNav"],mixins:{observable:"Ext.util.Observable"},clicksToEdit:2,triggerEvent:undefined,defaultFieldXType:"textfield",editStyle:"",constructor:function(a){var b=this;Ext.apply(b,a);b.addEvents("beforeedit","edit","validateedit","canceledit");b.mixins.observable.constructor.call(b);b.on("edit",function(c,d){b.fireEvent("afteredit",c,d)})},init:function(a){var b=this;if(a.lockable){a=a.view.normalGrid}b.grid=a;b.view=a.view;b.initEvents();b.mon(a,"reconfigure",b.onReconfigure,b);b.onReconfigure();a.relayEvents(b,["beforeedit","edit","validateedit","canceledit"]);a.isEditable=true;a.editingPlugin=a.view.editingPlugin=b},onReconfigure:function(){this.initFieldAccessors(this.view.getGridColumns())},destroy:function(){var b=this,a=b.grid;Ext.destroy(b.keyNav);b.removeFieldAccessors(a.getView().getGridColumns());b.clearListeners();delete b.grid.editingPlugin;delete b.grid.view.editingPlugin;delete b.grid;delete b.view;delete b.editor;delete b.keyNav},getEditStyle:function(){return this.editStyle},initFieldAccessors:function(a){a=[].concat(a);var d=this,g,e=a.length,b;for(g=0;gpanel:not([collapsed])");g=c.length;for(d=0;dpanel:not([collapsed])");if(c.length===1){g.expand()}}else{if(g){g.expand()}}a.deferLayouts=b;e.processing=false}},onComponentShow:function(a){this.onComponentExpand(a)}});Ext.define("Ext.toolbar.Spacer",{extend:"Ext.Component",alias:"widget.tbspacer",alternateClassName:"Ext.Toolbar.Spacer",baseCls:Ext.baseCSSPrefix+"toolbar-spacer",focusable:false});Ext.define("Ext.toolbar.TextItem",{extend:"Ext.toolbar.Item",requires:["Ext.XTemplate"],alias:"widget.tbtext",alternateClassName:"Ext.Toolbar.TextItem",text:"",renderTpl:"{text}",baseCls:Ext.baseCSSPrefix+"toolbar-text",beforeRender:function(){var a=this;a.callParent();Ext.apply(a.renderData,{text:a.text})},setText:function(a){if(this.rendered){this.el.update(a);this.ownerCt.doLayout()}else{this.text=a}}});Ext.define("Ext.toolbar.Toolbar",{extend:"Ext.container.Container",requires:["Ext.toolbar.Fill","Ext.layout.container.HBox","Ext.layout.container.VBox"],uses:["Ext.toolbar.Separator"],alias:"widget.toolbar",alternateClassName:"Ext.Toolbar",isToolbar:true,baseCls:Ext.baseCSSPrefix+"toolbar",ariaRole:"toolbar",defaultType:"button",vertical:false,enableOverflow:false,menuTriggerCls:Ext.baseCSSPrefix+"toolbar-more-icon",trackMenus:true,itemCls:Ext.baseCSSPrefix+"toolbar-item",statics:{shortcuts:{"-":"tbseparator"," ":"tbspacer"},shortcutsHV:{0:{"->":{xtype:"tbfill",height:0}},1:{"->":{xtype:"tbfill",width:0}}}},initComponent:function(){var b=this,a;if(!b.layout&&b.enableOverflow){b.layout={overflowHandler:"Menu"}}if(b.dock==="right"||b.dock==="left"){b.vertical=true}b.layout=Ext.applyIf(Ext.isString(b.layout)?{type:b.layout}:b.layout||{},{type:b.vertical?"vbox":"hbox",align:b.vertical?"stretchmax":"middle"});if(b.vertical){b.addClsWithUI("vertical")}if(b.ui==="footer"){b.ignoreBorderManagement=true}b.callParent();b.addEvents("overflowchange")},getRefItems:function(a){var e=this,b=e.callParent(arguments),d=e.layout,c;if(a&&e.enableOverflow){c=d.overflowHandler;if(c&&c.menu){b=b.concat(c.menu.getRefItems(a))}}return b},lookupComponent:function(d){if(typeof d=="string"){var b=Ext.toolbar.Toolbar,a=b.shortcutsHV[this.vertical?1:0][d]||b.shortcuts[d];if(typeof a=="string"){d={xtype:a}}else{if(a){d=Ext.apply({},a)}else{d={xtype:"tbtext",text:d}}}this.applyDefaults(d)}return this.callParent(arguments)},applyDefaults:function(b){if(!Ext.isString(b)){b=this.callParent(arguments);var a=this.internalDefaults;if(b.events){Ext.applyIf(b.initialConfig,a);Ext.apply(b,a)}else{Ext.applyIf(b,a)}}return b},trackMenu:function(c,a){if(this.trackMenus&&c.menu){var d=a?"mun":"mon",b=this;b[d](c,"mouseover",b.onButtonOver,b);b[d](c,"menushow",b.onButtonMenuShow,b);b[d](c,"menuhide",b.onButtonMenuHide,b)}},constructButton:function(a){return a.events?a:Ext.widget(a.split?"splitbutton":this.defaultType,a)},onBeforeAdd:function(a){if(a.is("field")||(a.is("button")&&this.ui!="footer")){a.ui=a.ui+"-toolbar"}if(a instanceof Ext.toolbar.Separator){a.setUI((this.vertical)?"vertical":"horizontal")}this.callParent(arguments)},onAdd:function(a){this.callParent(arguments);this.trackMenu(a)},onRemove:function(a){this.callParent(arguments);this.trackMenu(a,true)},getChildItemsToDisable:function(){return this.items.getRange()},onButtonOver:function(a){if(this.activeMenuBtn&&this.activeMenuBtn!=a){this.activeMenuBtn.hideMenu();a.showMenu();this.activeMenuBtn=a}},onButtonMenuShow:function(a){this.activeMenuBtn=a},onButtonMenuHide:function(a){delete this.activeMenuBtn}});Ext.define("Ext.panel.AbstractPanel",{extend:"Ext.container.Container",mixins:{docking:"Ext.container.DockingContainer"},requires:["Ext.util.MixedCollection","Ext.Element","Ext.toolbar.Toolbar"],baseCls:Ext.baseCSSPrefix+"panel",isPanel:true,componentLayout:"dock",childEls:["body"],renderTpl:["{% this.renderDockedItems(out,values,0); %}",(Ext.isIE6||Ext.isIE7||Ext.isIEQuirks)?"
    ":"",'
    {bodyCls}',' {baseCls}-body-{ui}',' {parent.baseCls}-body-{parent.ui}-{.}','" style="{bodyStyle}">',"{%this.renderContainer(out,values);%}","
    ","{% this.renderDockedItems(out,values,1); %}"],bodyPosProps:{x:"x",y:"y"},border:true,initComponent:function(){var a=this;a.addEvents("bodyresize");if(a.frame&&a.border&&a.bodyBorder===undefined){a.bodyBorder=false}if(a.frame&&a.border&&(a.bodyBorder===false||a.bodyBorder===0)){a.manageBodyBorders=true}a.callParent()},beforeDestroy:function(){this.destroyDockedItems();this.callParent()},initItems:function(){this.callParent();this.initDockingItems()},initRenderData:function(){var a=this,b=a.callParent();a.initBodyStyles();a.protoBody.writeTo(b);delete a.protoBody;return b},getComponent:function(a){var b=this.callParent(arguments);if(b===undefined&&!Ext.isNumber(a)){b=this.getDockedComponent(a)}return b},getProtoBody:function(){var b=this,a=b.protoBody;if(!a){b.protoBody=a=new Ext.util.ProtoElement({cls:b.bodyCls,style:b.bodyStyle,clsProp:"bodyCls",styleProp:"bodyStyle",styleIsText:true})}return a},initBodyStyles:function(){var c=this,a=c.getProtoBody(),b=Ext.Element;if(c.bodyPadding!==undefined){a.setStyle("padding",b.unitizeBox((c.bodyPadding===true)?5:c.bodyPadding))}if(c.frame&&c.bodyBorder){if(!Ext.isNumber(c.bodyBorder)){c.bodyBorder=1}a.setStyle("border-width",b.unitizeBox(c.bodyBorder))}},getCollapsedDockedItems:function(){return[this.getReExpander()]},setBodyStyle:function(b,d){var c=this,a=c.rendered?c.body:c.getProtoBody();if(Ext.isFunction(b)){b=b()}if(arguments.length==1&&Ext.isString(b)){b=Ext.Element.parseStyles(b)}a.setStyle.apply(c.body,arguments)},addBodyCls:function(b){var c=this,a=c.rendered?c.body:c.getProtoBody();a.addCls(b)},removeBodyCls:function(b){var c=this,a=c.rendered?c.body:c.getProtoBody();a.removeCls(b)},addUIClsToElement:function(b){var c=this,a=c.callParent(arguments);c.addBodyCls([Ext.baseCSSPrefix+b,c.baseCls+"-body-"+b,c.baseCls+"-body-"+c.ui+"-"+b]);return a},removeUIClsFromElement:function(b){var c=this,a=c.callParent(arguments);c.removeBodyCls([Ext.baseCSSPrefix+b,c.baseCls+"-body-"+b,c.baseCls+"-body-"+c.ui+"-"+b]);return a},addUIToElement:function(){var a=this;a.callParent(arguments);a.addBodyCls(a.baseCls+"-body-"+a.ui)},removeUIFromElement:function(){var a=this;a.callParent(arguments);a.removeBodyCls(a.baseCls+"-body-"+a.ui)},getTargetEl:function(){return this.body},getRefItems:function(a){var b=this.callParent(arguments);return this.getDockingRefItems(a,b)},setupRenderTpl:function(a){this.callParent(arguments);this.setupDockingRenderTpl(a)}});Ext.define("Ext.panel.Panel",{extend:"Ext.panel.AbstractPanel",requires:["Ext.panel.Header","Ext.fx.Anim","Ext.util.KeyMap","Ext.panel.DD","Ext.XTemplate","Ext.layout.component.Dock","Ext.util.Memento"],alias:"widget.panel",alternateClassName:"Ext.Panel",collapsedCls:"collapsed",animCollapse:Ext.enableFx,minButtonWidth:75,collapsed:false,collapseFirst:true,hideCollapseTool:false,titleCollapse:false,floatable:true,collapsible:false,closable:false,closeAction:"destroy",placeholderCollapseHideMode:Ext.Element.VISIBILITY,preventHeader:false,header:undefined,headerPosition:"top",frame:false,frameHeader:true,titleAlign:"left",manageHeight:true,initComponent:function(){var a=this;a.addEvents("beforeclose","close","beforeexpand","beforecollapse","expand","collapse","titlechange","iconchange","iconclschange");if(a.collapsible){this.addStateEvents(["expand","collapse"])}if(a.unstyled){a.setUI("plain")}if(a.frame){a.setUI(a.ui+"-framed")}a.bridgeToolbars();a.callParent();a.collapseDirection=a.collapseDirection||a.headerPosition||Ext.Component.DIRECTION_TOP;a.hiddenOnCollapse=new Ext.dom.CompositeElement()},beforeDestroy:function(){var a=this;Ext.destroy(a.placeholder,a.ghostPanel,a.dd);a.callParent()},initAria:function(){this.callParent();this.initHeaderAria()},getFocusEl:function(){return this.el},initHeaderAria:function(){var b=this,a=b.el,c=b.header;if(a&&c){a.dom.setAttribute("aria-labelledby",c.titleCmp.id)}},getHeader:function(){return this.header},setTitle:function(g){var c=this,b=c.title,e=c.header,a=c.reExpander,d=c.placeholder;c.title=g;if(e){if(e.isHeader){e.setTitle(g)}else{e.title=g}}if(a){a.setTitle(g)}if(d&&d.setTitle){d.setTitle(g)}c.fireEvent("titlechange",c,g,b)},setIconCls:function(a){var c=this,b=c.iconCls,e=c.header,d=c.placeholder;c.iconCls=a;if(e){if(e.isHeader){e.setIconCls(a)}else{e.iconCls=a}}if(d&&d.setIconCls){d.setIconCls(a)}c.fireEvent("iconclschange",c,a,b)},setIcon:function(a){var b=this,c=b.icon,e=b.header,d=b.placeholder;b.icon=a;if(e){if(e.isHeader){e.setIcon(a)}else{e.icon=a}}if(d&&d.setIcon){d.setIcon(a)}b.fireEvent("iconchange",b,a,c)},bridgeToolbars:function(){var a=this,g=[],c,b,e=a.minButtonWidth;function d(h,j,i){if(Ext.isArray(h)){h={xtype:"toolbar",items:h}}else{if(!h.xtype){h.xtype="toolbar"}}h.dock=j;if(j=="left"||j=="right"){h.vertical=true}if(i){h.layout=Ext.applyIf(h.layout||{},{pack:{left:"start",center:"center"}[a.buttonAlign]||"end"})}return h}if(a.tbar){g.push(d(a.tbar,"top"));a.tbar=null}if(a.bbar){g.push(d(a.bbar,"bottom"));a.bbar=null}if(a.buttons){a.fbar=a.buttons;a.buttons=null}if(a.fbar){c=d(a.fbar,"bottom",true);c.ui="footer";if(e){b=c.defaults;c.defaults=function(h){var i=b||{};if((!h.xtype||h.xtype==="button"||(h.isComponent&&h.isXType("button")))&&!("minWidth" in i)){i=Ext.apply({minWidth:e},i)}return i}}g.push(c);a.fbar=null}if(a.lbar){g.push(d(a.lbar,"left"));a.lbar=null}if(a.rbar){g.push(d(a.rbar,"right"));a.rbar=null}if(a.dockedItems){if(!Ext.isArray(a.dockedItems)){a.dockedItems=[a.dockedItems]}a.dockedItems=a.dockedItems.concat(g)}else{a.dockedItems=g}},isPlaceHolderCollapse:function(){return this.collapseMode=="placeholder"},onBoxReady:function(){this.callParent();if(this.collapsed){this.setHiddenDocked()}},beforeRender:function(){var b=this,a;b.callParent();b.initTools();if(!(b.preventHeader||(b.header===false))){b.updateHeader()}if(b.collapsed){if(b.isPlaceHolderCollapse()){b.hidden=true;b.placeholderCollapse();a=b.collapsed;b.collapsed=false}else{b.beginCollapse();b.addClsWithUI(b.collapsedCls)}}if(a){b.collapsed=a}},initTools:function(){var a=this;a.tools=a.tools?Ext.Array.clone(a.tools):[];if(a.collapsible&&!(a.hideCollapseTool||a.header===false||a.preventHeader)){a.collapseDirection=a.collapseDirection||a.headerPosition||"top";a.collapseTool=a.expandTool=Ext.widget({xtype:"tool",type:(a.collapsed&&!a.isPlaceHolderCollapse())?("expand-"+a.getOppositeDirection(a.collapseDirection)):("collapse-"+a.collapseDirection),handler:a.toggleCollapse,scope:a});if(a.collapseFirst){a.tools.unshift(a.collapseTool)}}a.addTools();if(a.closable){a.addClsWithUI("closable");a.addTool({type:"close",handler:Ext.Function.bind(a.close,a,[])})}if(a.collapseTool&&!a.collapseFirst){a.addTool(a.collapseTool)}},addTools:Ext.emptyFn,close:function(){if(this.fireEvent("beforeclose",this)!==false){this.doClose()}},doClose:function(){this.fireEvent("close",this);this[this.closeAction]()},updateHeader:function(c){var b=this,g=b.header,e=b.title,d=b.tools,a=b.headerPosition=="left"||b.headerPosition=="right";if((g!==false)&&(c||e||(d&&d.length)||(b.collapsible&&!b.titleCollapse))){if(g&&g.isHeader){g.show()}else{g=b.header=Ext.widget(Ext.apply({xtype:"header",title:e,titleAlign:b.titleAlign,orientation:a?"vertical":"horizontal",dock:b.headerPosition||"top",textCls:b.headerTextCls,iconCls:b.iconCls,icon:b.icon,baseCls:b.baseCls+"-header",tools:d,ui:b.ui,id:b.id+"_header",indicateDrag:b.draggable,frame:b.frame&&b.frameHeader,ignoreParentFrame:b.frame||b.overlapHeader,ignoreBorderManagement:b.frame||b.ignoreHeaderBorderManagement,listeners:b.collapsible&&b.titleCollapse?{click:b.toggleCollapse,scope:b}:null},b.header));b.addDocked(g,0);b.tools=g.tools}b.initHeaderAria()}else{if(g){g.hide()}}},setUI:function(b){var a=this;a.callParent(arguments);if(a.header&&a.header.rendered){a.header.setUI(b)}},getContentTarget:function(){return this.body},getTargetEl:function(){var a=this;return a.body||a.protoBody||a.frameBody||a.el},isVisible:function(a){var b=this;if(b.collapsed&&b.placeholder){return b.placeholder.isVisible(a)}return b.callParent(arguments)},onHide:function(){var a=this;if(a.collapsed&&a.placeholder){a.placeholder.hide()}else{a.callParent(arguments)}},onShow:function(){var a=this;if(a.collapsed&&a.placeholder){a.hidden=true;a.placeholder.show()}else{a.callParent(arguments)}},onRemoved:function(b){var a=this;a.callParent(arguments);if(a.placeholder&&!b){a.ownerCt.remove(a.placeholder,false)}},addTool:function(e){e=[].concat(e);var d=this,g=d.header,c,a=e.length,b;for(c=0;ca){h=e-i}else{if(gb){h=b-j}}}}d.el.setY(h)}});Ext.define("Ext.menu.ColorPicker",{extend:"Ext.menu.Menu",alias:"widget.colormenu",requires:["Ext.picker.Color"],hideOnClick:true,pickerId:null,initComponent:function(){var b=this,a=Ext.apply({},b.initialConfig);delete a.listeners;Ext.apply(b,{plain:true,showSeparator:false,items:Ext.applyIf({cls:Ext.baseCSSPrefix+"menu-color-item",id:b.pickerId,xtype:"colorpicker"},a)});b.callParent(arguments);b.picker=b.down("colorpicker");b.relayEvents(b.picker,["select"]);if(b.hideOnClick){b.on("select",b.hidePickerOnSelect,b)}},hidePickerOnSelect:function(){Ext.menu.Manager.hideAll()}});Ext.define("Ext.menu.DatePicker",{extend:"Ext.menu.Menu",alias:"widget.datemenu",requires:["Ext.picker.Date"],hideOnClick:true,pickerId:null,initComponent:function(){var a=this;Ext.apply(a,{showSeparator:false,plain:true,border:false,bodyPadding:0,items:Ext.applyIf({cls:Ext.baseCSSPrefix+"menu-date-item",id:a.pickerId,xtype:"datepicker"},a.initialConfig)});a.callParent(arguments);a.picker=a.down("datepicker");a.relayEvents(a.picker,["select"]);if(a.hideOnClick){a.on("select",a.hidePickerOnSelect,a)}},hidePickerOnSelect:function(){Ext.menu.Manager.hideAll()}});Ext.define("Ext.panel.Table",{extend:"Ext.panel.Panel",alias:"widget.tablepanel",uses:["Ext.selection.RowModel","Ext.grid.PagingScroller","Ext.grid.header.Container","Ext.grid.Lockable"],extraBaseCls:Ext.baseCSSPrefix+"grid",extraBodyCls:Ext.baseCSSPrefix+"grid-body",layout:"fit",hasView:false,viewType:null,selType:"rowmodel",scroll:true,deferRowRender:true,sortableColumns:true,enableLocking:false,scrollerOwner:true,enableColumnMove:true,restrictColumnReorder:false,enableColumnResize:true,enableColumnHide:true,rowLines:true,initComponent:function(){var h=this,k=h.scroll,b=false,a=false,g=h.columns||h.colModel,j,c=h.border,d,e;if(h.columnLines){h.addCls(Ext.baseCSSPrefix+"grid-with-col-lines")}if(h.rowLines){h.addCls(Ext.baseCSSPrefix+"grid-with-row-lines")}h.store=Ext.data.StoreManager.lookup(h.store||"ext-empty-store");if(g instanceof Ext.grid.header.Container){h.headerCt=g;h.headerCt.border=c;h.columns=h.headerCt.items.items}else{if(Ext.isArray(g)){g={items:g,border:c}}Ext.apply(g,{forceFit:h.forceFit,sortable:h.sortableColumns,enableColumnMove:h.enableColumnMove,enableColumnResize:h.enableColumnResize,enableColumnHide:h.enableColumnHide,border:c,restrictReorder:h.restrictColumnReorder});h.columns=g.items;if(h.enableLocking||Ext.ComponentQuery.query("{locked !== undefined}{processed != true}",h.columns).length){h.self.mixin("lockable",Ext.grid.Lockable);h.injectLockable()}}h.scrollTask=new Ext.util.DelayedTask(h.syncHorizontalScroll,h);h.addEvents("reconfigure","viewready");h.bodyCls=h.bodyCls||"";h.bodyCls+=(" "+h.extraBodyCls);h.cls=h.cls||"";h.cls+=(" "+h.extraBaseCls);delete h.autoScroll;if(!h.hasView){if(!h.headerCt){h.headerCt=new Ext.grid.header.Container(g)}h.columns=h.headerCt.items.items;if(h.store.buffered&&!h.store.remoteSort){for(d=0,e=h.columns.length;d'+a.emptyText+"":""}));a.mon(a.view,{uievent:a.processEvent,scope:a});b.view=a.view;a.headerCt.view=a.view;a.relayEvents(a.view,["cellclick","celldblclick"])}return a.view},setAutoScroll:Ext.emptyFn,processEvent:function(g,b,a,c,d,i){var h=this,j;if(d!==-1){j=h.headerCt.getGridColumns()[d];return j.processEvent.apply(j,arguments)}},determineScrollbars:function(){},invalidateScroller:function(){},scrollByDeltaY:function(b,a){this.getView().scrollBy(0,b,a)},scrollByDeltaX:function(b,a){this.getView().scrollBy(b,0,a)},afterCollapse:function(){var a=this;a.saveScrollPos();a.saveScrollPos();a.callParent(arguments)},afterExpand:function(){var a=this;a.callParent(arguments);a.restoreScrollPos();a.restoreScrollPos()},saveScrollPos:Ext.emptyFn,restoreScrollPos:Ext.emptyFn,onHeaderResize:function(){this.delayScroll()},onHeaderMove:function(e,g,a,b,d){var c=this;if(c.optimizedColumnMove===false){c.view.refresh()}else{c.view.moveColumn(b,d,a)}c.delayScroll()},onHeaderHide:function(a,b){this.delayScroll()},onHeaderShow:function(a,b){this.delayScroll()},delayScroll:function(){var a=this.getScrollTarget().el;if(a){this.scrollTask.delay(10,null,null,[a.dom.scrollLeft])}},onViewReady:function(){this.fireEvent("viewready",this)},onRestoreHorzScroll:function(){var a=this.scrollLeftPos;if(a){this.syncHorizontalScroll(a)}},setScrollTop:function(c){var b=this,a=b.getScrollerOwner();a.virtualScrollTop=c},getScrollerOwner:function(){var a=this;if(!this.scrollerOwner){a=this.up("[scrollerOwner]")}return a},getLhsMarker:function(){var a=this;return a.lhsMarker||(a.lhsMarker=Ext.DomHelper.append(a.el,{cls:Ext.baseCSSPrefix+"grid-resize-marker"},true))},getRhsMarker:function(){var a=this;return a.rhsMarker||(a.rhsMarker=Ext.DomHelper.append(a.el,{cls:Ext.baseCSSPrefix+"grid-resize-marker"},true))},getSelectionModel:function(){if(!this.selModel){this.selModel={}}var b="SINGLE",a;if(this.simpleSelect){b="SIMPLE"}else{if(this.multiSelect){b="MULTI"}}Ext.applyIf(this.selModel,{allowDeselect:this.allowDeselect,mode:b});if(!this.selModel.events){a=this.selModel.selType||this.selType;this.selModel=Ext.create("selection."+a,this.selModel)}if(!this.selModel.hasRelaySetup){this.relayEvents(this.selModel,["selectionchange","beforeselect","beforedeselect","select","deselect"]);this.selModel.hasRelaySetup=true}if(this.disableSelection){this.selModel.locked=true}return this.selModel},getScrollTarget:function(){var a=this.getScrollerOwner(),b=a.query("tableview");return b[1]||b[0]},onHorizontalScroll:function(a,b){this.syncHorizontalScroll(b.scrollLeft)},syncHorizontalScroll:function(c){var b=this,a;if(b.rendered){a=b.getScrollTarget();a.el.dom.scrollLeft=c;b.headerCt.el.dom.scrollLeft=c;b.scrollLeftPos=c}},onStoreLoad:Ext.emptyFn,getEditorParent:function(){return this.body},bindStore:function(a){var b=this;b.store=a;b.getView().bindStore(a)},beforeDestroy:function(){Ext.destroy(this.verticalScroller);this.callParent()},reconfigure:function(a,b){var c=this,d=c.headerCt;if(c.lockable){c.reconfigureLockable(a,b)}else{if(b){delete c.scrollLeftPos;d.suspendLayouts();d.removeAll();d.add(b)}if(a){a=Ext.StoreManager.lookup(a);c.bindStore(a)}else{c.getView().refresh()}if(b){d.resumeLayouts(true)}d.setSortState()}c.fireEvent("reconfigure",c,a,b)}});Ext.define("Ext.tab.Panel",{extend:"Ext.panel.Panel",alias:"widget.tabpanel",alternateClassName:["Ext.TabPanel"],requires:["Ext.layout.container.Card","Ext.tab.Bar"],tabPosition:"top",removePanelHeader:true,plain:false,itemCls:Ext.baseCSSPrefix+"tabpanel-child",minTabWidth:undefined,maxTabWidth:undefined,deferredRender:true,initComponent:function(){var c=this,b=[].concat(c.dockedItems||[]),a=c.activeTab||(c.activeTab=0);c.layout=new Ext.layout.container.Card(Ext.apply({owner:c,deferredRender:c.deferredRender,itemCls:c.itemCls,activeItem:c.activeTab},c.layout));c.tabBar=new Ext.tab.Bar(Ext.apply({dock:c.tabPosition,plain:c.plain,border:c.border,cardLayout:c.layout,tabPanel:c},c.tabBar));b.push(c.tabBar);c.dockedItems=b;c.addEvents("beforetabchange","tabchange");c.callParent(arguments);c.activeTab=c.getComponent(a);if(c.activeTab){c.activeTab.tab.activate(true);c.tabBar.activeTab=c.activeTab.tab}},setActiveTab:function(a){var c=this,b;a=c.getComponent(a);if(a){b=c.getActiveTab();if(b!==a&&c.fireEvent("beforetabchange",c,a,b)===false){return false}if(!a.isComponent){Ext.suspendLayouts();a=c.add(a);Ext.resumeLayouts()}c.activeTab=a;Ext.suspendLayouts();c.layout.setActiveItem(a);a=c.activeTab=c.layout.getActiveItem();if(a&&a!==b){c.tabBar.setActiveTab(a.tab);Ext.resumeLayouts(true);if(b!==a){c.fireEvent("tabchange",c,a,b)}}else{Ext.resumeLayouts(true)}return a}},getActiveTab:function(){var b=this,a=b.getComponent(b.activeTab);if(a&&b.items.indexOf(a)!=-1){b.activeTab=a}else{b.activeTab=null}return b.activeTab},getTabBar:function(){return this.tabBar},onAdd:function(e,c){var d=this,b=e.tabConfig||{},a={xtype:"tab",card:e,disabled:e.disabled,closable:e.closable,hidden:e.hidden&&!e.hiddenByLayout,tooltip:e.tooltip,tabBar:d.tabBar,closeText:e.closeText};b=Ext.applyIf(b,a);e.tab=d.tabBar.insert(c,b);e.on({scope:d,enable:d.onItemEnable,disable:d.onItemDisable,beforeshow:d.onItemBeforeShow,iconchange:d.onItemIconChange,iconclschange:d.onItemIconClsChange,titlechange:d.onItemTitleChange});if(e.isPanel){if(d.removePanelHeader){if(e.rendered){if(e.header){e.header.hide()}}else{e.header=false}}if(e.isPanel&&d.border){e.setBorder(false)}}},onItemEnable:function(a){a.tab.enable()},onItemDisable:function(a){a.tab.disable()},onItemBeforeShow:function(a){if(a!==this.activeTab){this.setActiveTab(a);return false}},onItemIconChange:function(b,a){b.tab.setIcon(a)},onItemIconClsChange:function(b,a){b.tab.setIconCls(a)},onItemTitleChange:function(a,b){a.tab.setText(b)},doRemove:function(d,b){var c=this,a;if(c.destroying||c.items.getCount()==1){c.activeTab=null}else{if((a=c.tabBar.items.indexOf(c.tabBar.findNextActivatable(d.tab)))!==-1){c.setActiveTab(a)}}this.callParent(arguments);delete d.tab.card;delete d.tab},onRemove:function(b,c){var a=this;b.un({scope:a,enable:a.onItemEnable,disable:a.onItemDisable,beforeshow:a.onItemBeforeShow});if(!a.destroying&&b.tab.ownerCt===a.tabBar){a.tabBar.remove(b.tab)}}});Ext.define("Ext.tip.Tip",{extend:"Ext.panel.Panel",alternateClassName:"Ext.Tip",minWidth:40,maxWidth:300,shadow:"sides",defaultAlign:"tl-bl?",constrainPosition:true,autoRender:true,hidden:true,baseCls:Ext.baseCSSPrefix+"tip",floating:{shadow:true,shim:true,constrain:true},focusOnToFront:false,closeAction:"hide",ariaRole:"tooltip",alwaysFramed:true,frameHeader:false,initComponent:function(){var a=this;a.floating=Ext.apply({},{shadow:a.shadow},a.self.prototype.floating);a.callParent(arguments);a.constrain=a.constrain||a.constrainPosition},showAt:function(b){var a=this;this.callParent(arguments);if(a.isVisible()){a.setPagePosition(b[0],b[1]);if(a.constrainPosition||a.constrain){a.doConstrain()}a.toFront(true)}},showBy:function(a,b){this.showAt(this.el.getAlignToXY(a,b||this.defaultAlign))},initDraggable:function(){var a=this;a.draggable={el:a.getDragEl(),delegate:a.header.el,constrain:a,constrainTo:a.el.getScopeParent()};Ext.Component.prototype.initDraggable.call(a)},ghost:undefined,unghost:undefined});Ext.define("Ext.slider.Tip",{extend:"Ext.tip.Tip",minWidth:10,alias:"widget.slidertip",offsets:null,align:null,position:"",defaultVerticalPosition:"left",defaultHorizontalPosition:"top",isSliderTip:true,init:function(c){var b=this,d,a;if(!b.position){b.position=c.vertical?b.defaultVerticalPosition:b.defaultHorizontalPosition}switch(b.position){case"top":a=[0,-10];d="b-t?";break;case"bottom":a=[0,10];d="t-b?";break;case"left":a=[-10,0];d="r-l?";break;case"right":a=[10,0];d="l-r?"}if(!b.align){b.align=d}if(!b.offsets){b.offsets=a}c.on({scope:b,dragstart:b.onSlide,drag:b.onSlide,dragend:b.hide,destroy:b.destroy})},onSlide:function(c,d,a){var b=this;b.show();b.update(b.getText(a));b.el.alignTo(a.el,b.align,b.offsets)},getText:function(a){return String(a.value)}});Ext.define("Ext.slider.Multi",{extend:"Ext.form.field.Base",alias:"widget.multislider",alternateClassName:"Ext.slider.MultiSlider",requires:["Ext.slider.Thumb","Ext.slider.Tip","Ext.Number","Ext.util.Format","Ext.Template","Ext.layout.component.field.Slider"],childEls:["endEl","innerEl"],fieldSubTpl:['
    ','","
    ",{renderThumbs:function(g,e){var j=e.$comp,h=0,c=j.thumbs,b=c.length,d,a;for(;hg?g:c.value}e.syncThumbs()},setValue:function(c,g,b,e){var d=this,a=d.thumbs[c];g=d.normalizeValue(g);if(g!==a.value&&d.fireEvent("beforechange",d,g,a.value,a)!==false){a.value=g;if(d.rendered){d.inputEl.set({"aria-valuenow":g,"aria-valuetext":g});a.move(d.calculateThumbPosition(g),Ext.isDefined(b)?b!==false:d.animate);d.fireEvent("change",d,g,a);d.checkDirty();if(e){d.fireEvent("changecomplete",d,g,a)}}}},calculateThumbPosition:function(a){return(a-this.minValue)/(this.maxValue-this.minValue)*100},getRatio:function(){var b=this,a=this.vertical?this.innerEl.getHeight():this.innerEl.getWidth(),c=this.maxValue-this.minValue;return c===0?a:(a/c)},reversePixelValue:function(a){return this.minValue+(a/this.getRatio())},reversePercentageValue:function(a){return this.minValue+(this.maxValue-this.minValue)*(a/100)},onDisable:function(){var g=this,d=0,b=g.thumbs,a=b.length,c,e,h;g.callParent();for(;da){if(j.anchorToTarget){j.defaultAlign="r-l";if(j.mouseOffset){j.mouseOffset[0]*=-1}}j.anchor="right";return j.getTargetXY()}if(b[1]i){if(j.anchorToTarget){j.defaultAlign="b-t";if(j.mouseOffset){j.mouseOffset[1]*=-1}}j.anchor="bottom";return j.getTargetXY()}}j.anchorCls=Ext.baseCSSPrefix+"tip-anchor-"+j.getAnchorPosition();j.anchorEl.addCls(j.anchorCls);j.targetCounter=0;return b}else{d=j.getMouseOffset();return(j.targetXY)?[j.targetXY[0]+d[0],j.targetXY[1]+d[1]]:d}},getMouseOffset:function(){var a=this,b=a.anchor?[0,0]:[15,18];if(a.mouseOffset){b[0]+=a.mouseOffset[0];b[1]+=a.mouseOffset[1]}return b},getAnchorPosition:function(){var b=this,a;if(b.anchor){b.tipAnchor=b.anchor.charAt(0)}else{a=b.defaultAlign.match(/^([a-z]+)-([a-z]+)(\?)?$/);b.tipAnchor=a[1].charAt(0)}switch(b.tipAnchor){case"t":return"top";case"b":return"bottom";case"r":return"right"}return"left"},getAnchorAlign:function(){switch(this.anchor){case"top":return"tl-bl";case"left":return"tl-tr";case"right":return"tr-tl";default:return"bl-tl"}},getOffsets:function(){var c=this,d,b,a=c.getAnchorPosition().charAt(0);if(c.anchorToTarget&&!c.trackMouse){switch(a){case"t":b=[0,9];break;case"b":b=[0,-13];break;case"r":b=[-13,0];break;default:b=[9,0];break}}else{switch(a){case"t":b=[-15-c.anchorOffset,30];break;case"b":b=[-19-c.anchorOffset,-13-c.el.dom.offsetHeight];break;case"r":b=[-15-c.el.dom.offsetWidth,-13-c.anchorOffset];break;default:b=[25,-13-c.anchorOffset];break}}d=c.getMouseOffset();b[0]+=d[0];b[1]+=d[1];return b},onTargetOver:function(c){var b=this,a;if(b.disabled||c.within(b.target.dom,true)){return}a=c.getTarget(b.delegate);if(a){b.triggerElement=a;b.clearTimer("hide");b.targetXY=c.getXY();b.delayShow()}},delayShow:function(){var a=this;if(a.hidden&&!a.showTimer){if(Ext.Date.getElapsed(a.lastActive)0){c=Infinity;l=-c;for(e=0,h=d.length;el){l=b}if(bl){l=r}if(r0){b=Infinity;l=-b;for(d=0,h=c.length;dl){l=n}if(m-1){b="top"}else{if(Ext.Array.indexOf(d,"bottom")>-1){b="bottom"}else{if(l.get("top")&&l.get("bottom")){for(h=0,k=o.length;h-1){a="left"}else{if(Ext.Array.indexOf(d,"right")>-1){a="right"}else{if(l.get("left")&&l.get("right")){for(h=0,k=e.length;hk.width)&&j.areas){H=j.shrink(z,D,k.width);z=H.x;D=H.y}return{bbox:k,minX:C,minY:B,xValues:z,yValues:D,xScale:h,yScale:E,areasLen:A}},getPaths:function(){var w=this,m=w.chart,c=m.getChartStore(),e=true,g=w.getBounds(),a=g.bbox,n=w.items=[],v=[],b,d=0,p=[],s,j,k,h,q,t,l,z,r,u,o;j=g.xValues.length;for(s=0;sa.x+a.width)?(j-(j+n-a.x-a.width)):j;h=h-ma.y+a.height)?(h-(h+m-a.y-a.height)):h;if(u.chart.animate&&!u.chart.resizing){g.show(true);u.onAnimate(g,{to:{x:j,y:h}})}else{g.setAttributes({x:j,y:h},true);if(r){u.animation.on("afteranimate",function(){g.show(true)})}else{g.show(true)}}},onPlaceCallout:function(m,r,J,G,F,d,k){var M=this,s=M.chart,D=s.surface,H=s.resizing,L=M.callouts,t=M.items,v=(G==0)?false:t[G-1].point,z=(G==t.length-1)?false:t[G+1].point,c=J.point,A,g,N,K,o,q,b=m.label.getBBox(),I=30,C=10,B=3,h,e,j,w,u,E=M.clipRect,n,l;if(!v){v=c}if(!z){z=c}K=(z[1]-v[1])/(z[0]-v[0]);o=(c[1]-v[1])/(c[0]-v[0]);q=(z[1]-c[1])/(z[0]-c[0]);g=Math.sqrt(1+K*K);A=[1/g,K/g];N=[-A[1],A[0]];if(o>0&&q<0&&N[1]<0||o<0&&q>0&&N[1]>0){N[0]*=-1;N[1]*=-1}else{if(Math.abs(o)Math.abs(q)&&N[0]>0){N[0]*=-1;N[1]*=-1}}n=c[0]+N[0]*I;l=c[1]+N[1]*I;h=n+(N[0]>0?0:-(b.width+2*B));e=l-b.height/2-B;j=b.width+2*B;w=b.height+2*B;if(h(E[0]+E[2])){N[0]*=-1}if(e(E[1]+E[3])){N[1]*=-1}n=c[0]+N[0]*I;l=c[1]+N[1]*I;h=n+(N[0]>0?0:-(b.width+2*B));e=l-b.height/2-B;j=b.width+2*B;w=b.height+2*B;m.lines.setAttributes({path:["M",c[0],c[1],"L",n,l,"Z"]},true);m.box.setAttributes({x:h,y:e,width:j,height:w},true);m.label.setAttributes({x:n+(N[0]>0?B:-(b.width+B)),y:l},true);for(u in m){m[u].show(true)}},isItemInPoint:function(j,h,m,c){var g=this,b=m.pointsUp,d=m.pointsDown,q=Math.abs,o=false,l=false,e=Infinity,a,n,k;for(a=0,n=b.length;aq(j-k[0])){e=q(j-k[0]);o=true;if(l){++a}}if(!o||(o&&l)){k=b[a-1];if(h>=k[1]&&(!d.length||h<=(d[a-1][1]))){m.storeIndex=a-1;m.storeField=g.yField[c];m.storeItem=g.chart.store.getAt(a-1);m._points=d.length?[k,d[a-1]]:[k];return true}else{break}}}return false},highlightSeries:function(){var a,c,b;if(this._index!==undefined){a=this.areas[this._index];if(a.__highlightAnim){a.__highlightAnim.paused=true}a.__highlighted=true;a.__prevOpacity=a.__prevOpacity||a.attr.opacity||1;a.__prevFill=a.__prevFill||a.attr.fill;a.__prevLineWidth=a.__prevLineWidth||a.attr.lineWidth;b=Ext.draw.Color.fromString(a.__prevFill);c={lineWidth:(a.__prevLineWidth||0)+2};if(b){c.fill=b.getLighter(0.2).toString()}else{c.opacity=Math.max(a.__prevOpacity-0.3,0)}if(this.chart.animate){a.__highlightAnim=new Ext.fx.Anim(Ext.apply({target:a,to:c},this.chart.animate))}else{a.setAttributes(c,true)}}},unHighlightSeries:function(){var a;if(this._index!==undefined){a=this.areas[this._index];if(a.__highlightAnim){a.__highlightAnim.paused=true}if(a.__highlighted){a.__highlighted=false;a.__highlightAnim=new Ext.fx.Anim({target:a,to:{fill:a.__prevFill,opacity:a.__prevOpacity,lineWidth:a.__prevLineWidth}})}}},highlightItem:function(c){var b=this,a,d;if(!c){this.highlightSeries();return}a=c._points;d=a.length==2?["M",a[0][0],a[0][1],"L",a[1][0],a[1][1]]:["M",a[0][0],a[0][1],"L",a[0][0],b.bbox.y+b.bbox.height];b.highlightSprite.setAttributes({path:d,hidden:false},true)},unHighlightItem:function(a){if(!a){this.unHighlightSeries()}if(this.highlightSprite){this.highlightSprite.hide(true)}},hideAll:function(a){var b=this;a=(isNaN(b._index)?a:b._index)||0;b.__excludes[a]=true;b.areas[a].hide(true);b.redraw()},showAll:function(a){var b=this;a=(isNaN(b._index)?a:b._index)||0;b.__excludes[a]=false;b.areas[a].show(true);b.redraw()},redraw:function(){var a=this,b;b=a.chart.legend.rebuild;a.chart.legend.rebuild=false;a.chart.redraw();a.chart.legend.rebuild=b},hide:function(){if(this.areas){var h=this,b=h.areas,d,c,a,g,e;if(b&&b.length){for(d=0,g=b.length;d0)][M]+=n(I)}}w[+(r>0)].push(n(r));w[+(F>0)].push(n(F));g=k.apply(u,w[0]);d=k.apply(u,w[1]);z=(H?q.height-m*2:q.width-h*2)/(d+g);a=a+g*z*(H?-1:1)}else{if(F/r<0){a=a-F*z*(H?-1:1)}}return{bars:v,bbox:q,shrunkBarWidth:C,barsLen:p,groupBarsLen:l,barWidth:t,groupBarWidth:e,scale:z,zero:a,xPadding:h,yPadding:m,signed:F/r<0,minY:F,maxY:r}},getPaths:function(){var v=this,X=v.chart,b=X.getChartStore(),W=b.data.items,V,E,L,G=v.bounds=v.getBounds(),z=v.items=[],P=v.yField,l=v.gutter/100,c=v.groupGutter/100,T=X.animate,N=v.column,x=v.group,m=X.shadow,R=v.shadowGroups,Q=v.shadowAttributes,q=R.length,y=G.bbox,B=G.barWidth,K=G.shrunkBarWidth,n=v.xPadding,r=v.yPadding,S=v.stacked,w=G.barsLen,O=v.colorArrayStyle,h=O&&O.length||0,C=Math,o=C.max,I=C.min,u=C.abs,U,Y,e,J,D,a,k,t,s,p,g,d,F,A,M,H;for(V=0,E=W.length;V1?U:0)%h]};if(N){Ext.apply(s,{height:e,width:o(G.groupBarWidth,0),x:(y.x+n+(B-K)*0.5+V*B*(1+l)+g*G.groupBarWidth*(1+c)*!S),y:a-e})}else{M=(E-1)-V;Ext.apply(s,{height:o(G.groupBarWidth,0),width:e+(a==G.zero),x:a+(a!=G.zero),y:(y.y+r+(B-K)*0.5+M*B*(1+l)+g*G.groupBarWidth*(1+c)*!S+1)})}if(e<0){if(N){s.y=k;s.height=u(e)}else{s.x=k+e;s.width=u(e)}}if(S){if(e<0){k+=e*(N?-1:1)}else{a+=e*(N?-1:1)}J+=u(e);if(e<0){D+=u(e)}}s.x=Math.floor(s.x)+1;H=Math.floor(s.y);if(!Ext.isIE9&&s.y>H){H--}s.y=H;s.width=Math.floor(s.width);s.height=Math.floor(s.height);z.push({series:v,yField:P[U],storeItem:L,value:[L.get(v.xField),Y],attr:s,point:N?[s.x+s.width/2,Y>=0?s.y:s.y+s.height]:[Y>=0?s.x+s.width:s.x,s.y+s.height/2]});if(T&&X.resizing){p=N?{x:s.x,y:G.zero,width:s.width,height:0}:{x:G.zero,y:s.y,width:0,height:s.height};if(m&&(S&&!t||!S)){t=true;for(d=0;d(O>=0?b-u.y:u.y+u.height-b)){p=M}}else{if(c+C>l.height){p=k;G.isOutside=true}}D=l.x+d/2;B=p==q?(b+((c/2+3)*(O>=0?-1:1))):(O>=0?(l.y+((c/2+3)*(p==k?-1:1))):(l.y+l.height+((c/2+3)*(p===k?1:-1))))}else{if(p==k){if(a+E+l.width>(O>=0?u.x+u.width-b:b-u.x)){p=M}}else{if(a+E>l.width){p=k;G.isOutside=true}}D=p==q?(b+((a/2+5)*(O>=0?1:-1))):(O>=0?(l.x+l.width+((a/2+5)*(p===k?1:-1))):(l.x+((a/2+5)*(p===k?-1:1))));B=l.y+d/2}w={x:D,y:B};if(K){w.rotate={x:D,y:B,degrees:270}}if(H&&A){if(F){D=l.x+l.width/2;B=b}else{D=b;B=l.y+l.height/2}G.setAttributes({x:D,y:B},true);if(K){G.setAttributes({rotate:{x:D,y:B,degrees:270}},true)}}if(H){m.onAnimate(G,{to:w})}else{G.setAttributes(Ext.apply(w,{hidden:false}),true)}},getLabelSize:function(g){var k=this.testerLabel,a=this.label,d=Ext.apply({},a,this.seriesLabelStyle||{}),b=a.orientation==="vertical",j,i,e,c;if(!k){k=this.testerLabel=this.chart.surface.add(Ext.apply({type:"text",opacity:0},d))}k.setAttributes({text:g},true);j=k.getBBox();i=j.width;e=j.height;return{width:b?e:i,height:b?i:e}},onAnimate:function(b,a){b.show();return this.callParent(arguments)},isItemInPoint:function(a,d,b){var c=b.sprite.getBBox();return c.x<=a&&c.y<=d&&(c.x+c.width)>=a&&(c.y+c.height)>=d},hideAll:function(a){var e=this.chart.axes,c=e.items,d=c.length,b=0;a=(isNaN(this._index)?a:this._index)||0;if(!this.__excludes){this.__excludes=[]}this.__excludes[a]=true;this.drawSeries();for(b;b180,D=Math.min(q,p)*B,A=Math.max(q,p)*B,o=false;k+=l*d(j);i+=l*a(j);w=k+b.startRho*d(D);h=i+b.startRho*a(D);v=k+b.endRho*d(D);g=i+b.endRho*a(D);u=k+b.startRho*d(A);e=i+b.startRho*a(A);s=k+b.endRho*d(A);c=i+b.endRho*a(A);if(n(w-u)<=z&&n(h-e)<=z){o=true}if(o){return{path:[["M",w,h],["L",v,g],["A",b.endRho,b.endRho,0,+t,1,s,c],["Z"]]}}else{return{path:[["M",w,h],["L",v,g],["A",b.endRho,b.endRho,0,+t,1,s,c],["L",u,e],["A",b.startRho,b.startRho,0,+t,0,w,h],["Z"]]}}},calcMiddle:function(p){var k=this,l=k.rad,o=p.slice,n=k.centerX,m=k.centerY,j=o.startAngle,e=o.endAngle,i=Math.max(("rho" in o)?o.rho:k.radius,k.label.minMargin),h=+k.donut,b=Math.min(j,e)*l,a=Math.max(j,e)*l,d=-(b+(a-b)/2),g=n+(p.endRho+p.startRho)/2*Math.cos(d),c=m-(p.endRho+p.startRho)/2*Math.sin(d);p.middle={x:g,y:c}},drawSeries:function(){var w=this,W=w.chart,b=W.getChartStore(),A=w.group,S=w.chart.animate,D=w.chart.axes.get(0),E=D&&D.minimum||w.minimum||0,I=D&&D.maximum||w.maximum||0,n=w.angleField||w.field||w.xField,M=W.surface,H=W.chartBBox,h=w.rad,c=+w.donut,X={},B=[],m=w.seriesStyle,a=w.seriesLabelStyle,g=w.colorArrayStyle,z=g&&g.length||0,K=W.maxGutter[0],J=W.maxGutter[1],k=Math.cos,s=Math.sin,t,e,d,v,r,C,O,F,G,L,U,T,l,V,x,o,Q,R,q,y,u,P,N;Ext.apply(m,w.style||{});w.setBBox();y=w.bbox;if(w.colorSet){g=w.colorSet;z=g.length}if(!b||!b.getCount()||w.seriesIsHidden){w.hide();w.items=[];return}e=w.centerX=H.x+(H.width/2);d=w.centerY=H.y+H.height;w.radius=Math.min(e-H.x,d-H.y);w.slices=r=[];w.items=B=[];if(!w.value){L=b.getAt(0);w.value=L.get(n)}O=w.value;if(w.needle){P={series:w,value:O,startAngle:-180,endAngle:0,rho:w.radius};u=-180*(1-(O-E)/(I-E));r.push(P)}else{u=-180*(1-(O-E)/(I-E));P={series:w,value:O,startAngle:-180,endAngle:u,rho:w.radius};N={series:w,value:w.maximum-O,startAngle:u,endAngle:0,rho:w.radius};r.push(P,N)}for(U=0,G=r.length;U=g&&b=n.startRho&&k<=n.endRho)},showAll:function(){if(!isNaN(this._index)){this.__excludes[this._index]=false;this.drawSeries()}},getLegendColor:function(a){var b=this;return b.colorArrayStyle[a%b.colorArrayStyle.length]}});Ext.define("Ext.chart.series.Line",{extend:"Ext.chart.series.Cartesian",alternateClassName:["Ext.chart.LineSeries","Ext.chart.LineChart"],requires:["Ext.chart.axis.Axis","Ext.chart.Shape","Ext.draw.Draw","Ext.fx.Anim"],type:"line",alias:"series.line",selectionTolerance:20,showMarkers:true,markerConfig:{},style:{},smooth:false,defaultSmoothness:3,fill:false,constructor:function(c){this.callParent(arguments);var e=this,a=e.chart.surface,g=e.chart.shadow,d,b;c.highlightCfg=Ext.Object.merge({"stroke-width":3},c.highlightCfg);Ext.apply(e,c,{shadowAttributes:[{"stroke-width":6,"stroke-opacity":0.05,stroke:"rgb(0, 0, 0)",translate:{x:1,y:1}},{"stroke-width":4,"stroke-opacity":0.1,stroke:"rgb(0, 0, 0)",translate:{x:1,y:1}},{"stroke-width":2,"stroke-opacity":0.15,stroke:"rgb(0, 0, 0)",translate:{x:1,y:1}}]});e.group=a.getGroup(e.seriesId);if(e.showMarkers){e.markerGroup=a.getGroup(e.seriesId+"-markers")}if(g){for(d=0,b=e.shadowAttributes.length;dau.width){a=an.shrink(aB,ae,au.width);aB=a.x;ae=a.y}an.items=[];l=0;az=aB.length;for(Q=0;Qa.x+a.width)?(j-(j+n-a.x-a.width)):j;h=(h-ma.x+a.width)?(j-(j+n-a.x-a.width)):j;h=h-ma.y+a.height)?(h-(h+m-a.y-a.height)):h}}if(u.chart.animate&&!u.chart.resizing){g.show(true);u.onAnimate(g,{to:{x:j,y:h}})}else{g.setAttributes({x:j,y:h},true);if(r&&u.animation){u.animation.on("afteranimate",function(){g.show(true)})}else{g.show(true)}}},highlightItem:function(){var a=this;a.callParent(arguments);if(a.line&&!a.highlighted){if(!("__strokeWidth" in a.line)){a.line.__strokeWidth=parseFloat(a.line.attr["stroke-width"])||0}if(a.line.__anim){a.line.__anim.paused=true}a.line.__anim=Ext.create("Ext.fx.Anim",{target:a.line,to:{"stroke-width":a.line.__strokeWidth+3}});a.highlighted=true}},unHighlightItem:function(){var a=this;a.callParent(arguments);if(a.line&&a.highlighted){a.line.__anim=Ext.create("Ext.fx.Anim",{target:a.line,to:{"stroke-width":a.line.__strokeWidth}});a.highlighted=false}},onPlaceCallout:function(m,r,J,G,F,d,k){if(!F){return}var M=this,s=M.chart,D=s.surface,H=s.resizing,L=M.callouts,t=M.items,v=G==0?false:t[G-1].point,z=(G==t.length-1)?false:t[G+1].point,c=[+J.point[0],+J.point[1]],A,g,N,K,o,q,I=L.offsetFromViz||30,C=L.offsetToSide||10,B=L.offsetBox||3,h,e,j,w,u,E=M.clipRect,b={width:L.styles.width||10,height:L.styles.height||10},n,l;if(!v){v=c}if(!z){z=c}K=(z[1]-v[1])/(z[0]-v[0]);o=(c[1]-v[1])/(c[0]-v[0]);q=(z[1]-c[1])/(z[0]-c[0]);g=Math.sqrt(1+K*K);A=[1/g,K/g];N=[-A[1],A[0]];if(o>0&&q<0&&N[1]<0||o<0&&q>0&&N[1]>0){N[0]*=-1;N[1]*=-1}else{if(Math.abs(o)Math.abs(q)&&N[0]>0){N[0]*=-1;N[1]*=-1}}n=c[0]+N[0]*I;l=c[1]+N[1]*I;h=n+(N[0]>0?0:-(b.width+2*B));e=l-b.height/2-B;j=b.width+2*B;w=b.height+2*B;if(h(E[0]+E[2])){N[0]*=-1}if(e(E[1]+E[3])){N[1]*=-1}n=c[0]+N[0]*I;l=c[1]+N[1]*I;h=n+(N[0]>0?0:-(b.width+2*B));e=l-b.height/2-B;j=b.width+2*B;w=b.height+2*B;if(s.animate){M.onAnimate(m.lines,{to:{path:["M",c[0],c[1],"L",n,l,"Z"]}});if(m.panel){m.panel.setPosition(h,e,true)}}else{m.lines.setAttributes({path:["M",c[0],c[1],"L",n,l,"Z"]},true);if(m.panel){m.panel.setPosition(h,e)}}for(u in m){m[u].show(true)}},isItemInPoint:function(j,g,A,q){var C=this,n=C.items,s=C.selectionTolerance,k=null,z,c,p,v,h,w,b,t,a,l,B,e,d,o,u,r,D=Math.sqrt,m=Math.abs;c=n[q];z=q&&n[q-1];if(q>=h){z=n[h-1]}p=z&&z.point;v=c&&c.point;w=z?p[0]:v[0]-s;b=z?p[1]:v[1];t=c?v[0]:p[0]+s;a=c?v[1]:p[1];e=D((j-w)*(j-w)+(g-b)*(g-b));d=D((j-t)*(j-t)+(g-a)*(g-a));o=Math.min(e,d);if(o<=s){return o==e?z:c}return false},toggleAll:function(a){var e=this,b,d,g,c;if(!a){Ext.chart.series.Cartesian.prototype.hideAll.call(e)}else{Ext.chart.series.Cartesian.prototype.showAll.call(e)}if(e.line){e.line.setAttributes({hidden:!a},true);if(e.line.shadows){for(b=0,c=e.line.shadows,d=c.length;b1?T:U)%w]}||{}));D=Ext.apply({},o.segment,{slice:r,series:s,storeItem:r.storeItem,index:U});s.calcMiddle(D);if(g){D.shadows=r.shadowAttrs[T]}y[U]=D;if(!z){m=Ext.apply({type:"path",group:x,middle:D.middle},Ext.apply(h,e&&{fill:e[(K>1?T:U)%w]}||{}));z=J.add(Ext.apply(m,o))}r.sprite=r.sprite||[];D.sprite=z;r.sprite.push(z);r.point=[D.middle.x,D.middle.y];if(S){o=s.renderer(z,a.getAt(U),o,U,a);z._to=o;z._animating=true;s.onAnimate(z,{to:o,listeners:{afteranimate:{fn:function(){this._animating=false},scope:z}}})}else{o=s.renderer(z,a.getAt(U),Ext.apply(o,{hidden:false}),U,a);z.setAttributes(o,true)}B+=q}}F=x.getCount();for(U=0;U>0]&&x.getAt(U)){x.getAt(U).hide(true)}}if(g){aa=Q.length;for(E=0;E>0]){for(T=0;T90&&v<270)?v+180:v;h=k.attr.rotation.degrees;if(h!=null&&Math.abs(h-v)>180*0.5){if(v>h){v-=360}else{v+=360}v=v%360}else{v=a(v)}b.rotate={degrees:v,x:b.x,y:b.y};break;default:break}b.translate={x:0,y:0};if(e&&!w&&(s!="rotate"||h!=null)){B.onAnimate(k,{to:b})}else{k.setAttributes(b,true)}k._from=r},onPlaceCallout:function(l,o,z,v,u,d,e){var A=this,q=A.chart,j=A.centerX,h=A.centerY,B=z.middle,b={x:B.x,y:B.y},m=B.x-j,k=B.y-h,c=1,n,g=Math.atan2(k,m||1),a=l.label.getBBox(),w=20,t=10,s=10,r;c=z.endRho+w;n=(z.endRho+z.startRho)/2+(z.endRho-z.startRho)/3;b.x=c*Math.cos(g)+j;b.y=c*Math.sin(g)+h;m=n*Math.cos(g);k=n*Math.sin(g);if(q.animate){A.onAnimate(l.lines,{to:{path:["M",m+j,k+h,"L",b.x,b.y,"Z","M",b.x,b.y,"l",m>0?t:-t,0,"z"]}});A.onAnimate(l.box,{to:{x:b.x+(m>0?t:-(t+a.width+2*s)),y:b.y+(k>0?(-a.height-s/2):(-a.height-s/2)),width:a.width+2*s,height:a.height+2*s}});A.onAnimate(l.label,{to:{x:b.x+(m>0?(t+s):-(t+a.width+s)),y:b.y+(k>0?-a.height/4:-a.height/4)}})}else{l.lines.setAttributes({path:["M",m+j,k+h,"L",b.x,b.y,"Z","M",b.x,b.y,"l",m>0?t:-t,0,"z"]},true);l.box.setAttributes({x:b.x+(m>0?t:-(t+a.width+2*s)),y:b.y+(k>0?(-a.height-s/2):(-a.height-s/2)),width:a.width+2*s,height:a.height+2*s},true);l.label.setAttributes({x:b.x+(m>0?(t+s):-(t+a.width+s)),y:b.y+(k>0?-a.height/4:-a.height/4)},true)}for(r in l){l[r].show(true)}},onAnimate:function(b,a){b.show();return this.callParent(arguments)},isItemInPoint:function(l,j,n,e){var h=this,d=h.centerX,c=h.centerY,p=Math.abs,o=p(l-d),m=p(j-c),g=n.startAngle,a=n.endAngle,k=Math.sqrt(o*o+m*m),b=Math.atan2(j-c,l-d)/h.rad;if(b>h.firstAngle){b-=h.accuracy}return(b<=g&&b>a&&k>=n.startRho&&k<=n.endRho)},hideAll:function(c){var g,b,j,h,e,a,d;c=(isNaN(this._index)?c:this._index)||0;this.__excludes=this.__excludes||[];this.__excludes[c]=true;d=this.slices[c].sprite;for(e=0,a=d.length;ea.x+a.width)?(j-(j+n-a.x-a.width)):j;h=(h-ma.x+a.width)?(j-(j+n-a.x-a.width)):j;h=h-ma.y+a.height)?(h-(h+m-a.y-a.height)):h}}if(!l.animate){g.setAttributes({x:j,y:h},true);g.show(true)}else{if(s){o=t.sprite.getActiveAnimation();if(o){o.on("afteranimate",function(){g.setAttributes({x:j,y:h},true);g.show(true)})}else{g.show(true)}}else{v.onAnimate(g,{to:{x:j,y:h}})}}},onPlaceCallout:function(k,m,B,z,w,c,h){var E=this,n=E.chart,u=n.surface,A=n.resizing,D=E.callouts,o=E.items,b=B.point,F,a=k.label.getBBox(),C=30,t=10,s=3,e,d,g,r,q,v=E.bbox,l,j;F=[Math.cos(Math.PI/4),-Math.sin(Math.PI/4)];l=b[0]+F[0]*C;j=b[1]+F[1]*C;e=l+(F[0]>0?0:-(a.width+2*s));d=j-a.height/2-s;g=a.width+2*s;r=a.height+2*s;if(e(v[0]+v[2])){F[0]*=-1}if(d(v[1]+v[3])){F[1]*=-1}l=b[0]+F[0]*C;j=b[1]+F[1]*C;e=l+(F[0]>0?0:-(a.width+2*s));d=j-a.height/2-s;g=a.width+2*s;r=a.height+2*s;if(n.animate){E.onAnimate(k.lines,{to:{path:["M",b[0],b[1],"L",l,j,"Z"]}},true);E.onAnimate(k.box,{to:{x:e,y:d,width:g,height:r}},true);E.onAnimate(k.label,{to:{x:l+(F[0]>0?s:-(a.width+s)),y:j}},true)}else{k.lines.setAttributes({path:["M",b[0],b[1],"L",l,j,"Z"]},true);k.box.setAttributes({x:e,y:d,width:g,height:r},true);k.label.setAttributes({x:l+(F[0]>0?s:-(a.width+s)),y:j},true)}for(q in k){k[q].show(true)}},onAnimate:function(b,a){b.show();return this.callParent(arguments)},isItemInPoint:function(c,h,e){var b,d=10,a=Math.abs;function g(i){var k=a(i[0]-c),j=a(i[1]-h);return Math.sqrt(k*k+j*j)}b=e.point;return(b[0]-d<=c&&b[0]+d>=c&&b[1]-d<=h&&b[1]+d>=h)}});Ext.define("Ext.tip.QuickTip",{extend:"Ext.tip.ToolTip",alias:"widget.quicktip",alternateClassName:"Ext.QuickTip",interceptTitles:false,title:" ",tagConfig:{namespace:"data-",attribute:"qtip",width:"qwidth",target:"target",title:"qtitle",hide:"hide",cls:"qclass",align:"qalign",anchor:"anchor"},initComponent:function(){var a=this;a.target=a.target||Ext.getDoc();a.targets=a.targets||{};a.callParent()},register:function(c){var h=Ext.isArray(c)?c:arguments,d=0,a=h.length,g,b,e;for(;d',"{[Ext.util.Format.htmlEncode(values.value)]}","","{afterTextAreaTpl}","{beforeIFrameTpl}",'',"{afterIFrameTpl}",{disableFormats:true}],subTplInsertions:["beforeTextAreaTpl","afterTextAreaTpl","beforeIFrameTpl","afterIFrameTpl","iframeAttrTpl","inputAttrTpl"],enableFormat:true,enableFontSize:true,enableColors:true,enableAlignments:true,enableLists:true,enableSourceEdit:true,enableLinks:true,enableFont:true,createLinkText:"Please enter the URL for the link:",defaultLinkValue:"http://",fontFamilies:["Arial","Courier New","Tahoma","Times New Roman","Verdana"],defaultFont:"tahoma",defaultValue:(Ext.isOpera||Ext.isIE6)?" ":"​",fieldBodyCls:Ext.baseCSSPrefix+"html-editor-wrap",componentLayout:"htmleditor",initialized:false,activated:false,sourceEditMode:false,iframePad:3,hideMode:"offsets",maskOnDisable:true,initComponent:function(){var a=this;a.addEvents("initialize","activate","beforesync","beforepush","sync","push","editmodechange");a.callParent(arguments);a.createToolbar(a);a.initLabelable();a.initField()},getRefItems:function(){return[this.toolbar]},createToolbar:function(g){var j=this,h=[],c,l=Ext.tip.QuickTipManager&&Ext.tip.QuickTipManager.isEnabled(),e=Ext.baseCSSPrefix,d,k,b;function a(n,i,m){return{itemId:n,cls:e+"btn-icon",iconCls:e+"edit-"+n,enableToggle:i!==false,scope:g,handler:m||g.relayBtnCmd,clickEvent:"mousedown",tooltip:l?g.buttonTips[n]||b:b,overflowText:g.buttonTips[n].title||b,tabIndex:-1}}if(j.enableFont&&!Ext.isSafari2){d=Ext.widget("component",{renderTpl:['"],renderData:{cls:e+"font-select",fonts:j.fontFamilies,defaultFont:j.defaultFont},childEls:["selectEl"],afterRender:function(){j.fontSelect=this.selectEl;Ext.Component.prototype.afterRender.apply(this,arguments)},onDisable:function(){var i=this.selectEl;if(i){i.dom.disabled=true}Ext.Component.prototype.onDisable.apply(this,arguments)},onEnable:function(){var i=this.selectEl;if(i){i.dom.disabled=false}Ext.Component.prototype.onEnable.apply(this,arguments)},listeners:{change:function(){j.relayCmd("fontname",j.fontSelect.dom.value);j.deferFocus()},element:"selectEl"}});h.push(d,"-")}if(j.enableFormat){h.push(a("bold"),a("italic"),a("underline"))}if(j.enableFontSize){h.push("-",a("increasefontsize",false,j.adjustFont),a("decreasefontsize",false,j.adjustFont))}if(j.enableColors){h.push("-",{itemId:"forecolor",cls:e+"btn-icon",iconCls:e+"edit-forecolor",overflowText:g.buttonTips.forecolor.title,tooltip:l?g.buttonTips.forecolor||b:b,tabIndex:-1,menu:Ext.widget("menu",{plain:true,items:[{xtype:"colorpicker",allowReselect:true,focus:Ext.emptyFn,value:"000000",plain:true,clickEvent:"mousedown",handler:function(m,i){j.execCmd("forecolor",Ext.isWebKit||Ext.isIE?"#"+i:i);j.deferFocus();this.up("menu").hide()}}]})},{itemId:"backcolor",cls:e+"btn-icon",iconCls:e+"edit-backcolor",overflowText:g.buttonTips.backcolor.title,tooltip:l?g.buttonTips.backcolor||b:b,tabIndex:-1,menu:Ext.widget("menu",{plain:true,items:[{xtype:"colorpicker",focus:Ext.emptyFn,value:"FFFFFF",plain:true,allowReselect:true,clickEvent:"mousedown",handler:function(m,i){if(Ext.isGecko){j.execCmd("useCSS",false);j.execCmd("hilitecolor",i);j.execCmd("useCSS",true);j.deferFocus()}else{j.execCmd(Ext.isOpera?"hilitecolor":"backcolor",Ext.isWebKit||Ext.isIE?"#"+i:i);j.deferFocus()}this.up("menu").hide()}}]})})}if(j.enableAlignments){h.push("-",a("justifyleft"),a("justifycenter"),a("justifyright"))}if(!Ext.isSafari2){if(j.enableLinks){h.push("-",a("createlink",false,j.createLink))}if(j.enableLists){h.push("-",a("insertorderedlist"),a("insertunorderedlist"))}if(j.enableSourceEdit){h.push("-",a("sourceedit",true,function(i){j.toggleSourceEdit(!j.sourceEditMode)}))}}for(c=0;c',b.iframePad,a)},getEditorBody:function(){var a=this.getDoc();return a.body||a.documentElement},getDoc:function(){return(!Ext.isIE&&this.iframeEl.dom.contentDocument)||this.getWin().document},getWin:function(){return Ext.isIE?this.iframeEl.dom.contentWindow:window.frames[this.iframeEl.dom.name]},finishRenderChildren:function(){this.callParent();this.toolbar.finishRender()},onRender:function(){var a=this;a.callParent(arguments);a.inputEl=a.iframeEl;a.monitorTask=Ext.TaskManager.start({run:a.checkDesignMode,scope:a,interval:100})},initRenderTpl:function(){var a=this;if(!a.hasOwnProperty("renderTpl")){a.renderTpl=a.getTpl("labelableRenderTpl")}return a.callParent()},initRenderData:function(){return Ext.applyIf(this.callParent(),this.getLabelableRenderData())},getSubTplData:function(){return{$comp:this,cmpId:this.id,id:this.getInputId(),textareaCls:Ext.baseCSSPrefix+"hidden",value:this.value,iframeName:Ext.id(),iframeSrc:Ext.SSL_SECURE_URL,size:"height:100px;width:100%"}},getSubTplMarkup:function(){return this.getTpl("fieldSubTpl").apply(this.getSubTplData())},initFrameDoc:function(){var b=this,c,a;Ext.TaskManager.stop(b.monitorTask);c=b.getDoc();b.win=b.getWin();c.open();c.write(b.getDocMarkup());c.close();a={run:function(){var d=b.getDoc();if(d.body||d.readyState==="complete"){Ext.TaskManager.stop(a);b.setDesignMode(true);Ext.defer(b.initEditor,10,b)}},interval:10,duration:10000,scope:b};Ext.TaskManager.start(a)},checkDesignMode:function(){var a=this,b=a.getDoc();if(b&&(!b.editorInitialized||a.getDesignMode()!=="on")){a.initFrameDoc()}},setDesignMode:function(c){var a=this,b=a.getDoc();if(b){if(a.readOnly){c=false}b.designMode=(/on|true/i).test(String(c).toLowerCase())?"on":"off"}},getDesignMode:function(){var a=this.getDoc();return !a?"":String(a.designMode).toLowerCase()},disableItems:function(d){var b=this.getToolbar().items.items,c,a=b.length,e;for(c=0;c'+e+""}}e=g.cleanHtml(e);if(g.fireEvent("beforesync",g,e)!==false){if(g.textareaEl.dom.value!=e){g.textareaEl.dom.value=e;h=true}g.fireEvent("sync",g,e);if(h){g.checkChange()}}}},getValue:function(){var a=this,b;if(!a.sourceEditMode){a.syncValue()}b=a.rendered?a.textareaEl.dom.value:a.value;a.value=b;return b},pushValue:function(){var b=this,a;if(b.initialized){a=b.textareaEl.dom.value||"";if(!b.activated&&a.length<1){a=b.defaultValue}if(b.fireEvent("beforepush",b,a)!==false){b.getEditorBody().innerHTML=a;if(Ext.isGecko){b.setDesignMode(false);b.setDesignMode(true)}b.fireEvent("push",b,a)}}},deferFocus:function(){this.focus(false,true)},getFocusEl:function(){var a=this,b=a.win;return b&&!a.sourceEditMode?b:a.textareaEl},initEditor:function(){try{var g=this,d=g.getEditorBody(),b=g.textareaEl.getStyles("font-size","font-family","background-image","background-repeat","background-color","color"),i,c;b["background-attachment"]="fixed";d.bgProperties="fixed";Ext.DomHelper.applyStyles(d,b);i=g.getDoc();if(i){try{Ext.EventManager.removeAll(i)}catch(h){}}c=Ext.Function.bind(g.onEditorEvent,g);Ext.EventManager.on(i,{mousedown:c,dblclick:c,click:c,keyup:c,buffer:100});c=g.onRelayedEvent;Ext.EventManager.on(i,{mousedown:c,mousemove:c,mouseup:c,click:c,dblclick:c,scope:g});if(Ext.isGecko){Ext.EventManager.on(i,"keypress",g.applyCommand,g)}if(g.fixKeys){Ext.EventManager.on(i,"keydown",g.fixKeys,g)}Ext.EventManager.on(window,"unload",g.beforeDestroy,g);i.editorInitialized=true;g.initialized=true;g.pushValue();g.setReadOnly(g.readOnly);g.fireEvent("initialize",g)}catch(a){}},beforeDestroy:function(){var a=this,d=a.monitorTask,c,g;if(d){Ext.TaskManager.stop(d)}if(a.rendered){try{c=a.getDoc();if(c){Ext.EventManager.removeAll(c);for(g in c){if(c.hasOwnProperty&&c.hasOwnProperty(g)){delete c[g]}}}}catch(b){}Ext.destroyMembers(a,"toolbar","iframeEl","textareaEl")}a.callParent()},onRelayedEvent:function(c){var b=this.iframeEl,d=b.getXY(),a=c.getXY();c.xy=[d[0]+a[0],d[1]+a[1]];c.injectEvent(b);c.xy=a},onFirstFocus:function(){var c=this,b,a;c.activated=true;c.disableItems(c.readOnly);if(Ext.isGecko){c.win.focus();b=c.win.getSelection();if(!b.focusNode||b.focusNode.nodeType!==3){a=b.getRangeAt(0);a.selectNodeContents(c.getEditorBody());a.collapse(true);c.deferFocus()}try{c.execCmd("useCSS",true);c.execCmd("styleWithCSS",false)}catch(d){}}c.fireEvent("activate",c)},adjustFont:function(d){var e=d.getItemId()==="increasefontsize"?1:-1,c=this.getDoc().queryCommandValue("FontSize")||"2",a=Ext.isString(c)&&c.indexOf("px")!==-1,b;c=parseInt(c,10);if(a){if(c<=10){c=1+e}else{if(c<=13){c=2+e}else{if(c<=16){c=3+e}else{if(c<=18){c=4+e}else{if(c<=24){c=5+e}else{c=6+e}}}}}c=Ext.Number.constrain(c,1,6)}else{b=Ext.isSafari;if(b){e*=2}c=Math.max(1,c+e)+(b?"px":0)}this.execCmd("FontSize",c)},onEditorEvent:function(a){this.updateToolbar()},updateToolbar:function(){var e=this,d,g,a,c;if(e.readOnly){return}if(!e.activated){e.onFirstFocus();return}d=e.getToolbar().items.map;g=e.getDoc();if(e.enableFont&&!Ext.isSafari2){a=(g.queryCommandValue("FontName")||e.defaultFont).toLowerCase();c=e.fontSelect.dom;if(a!==c.value){c.value=a}}function b(){for(var k=0,h=arguments.length,j;k0){g=String.fromCharCode(g);switch(g){case"b":b="bold";break;case"i":b="italic";break;case"u":b="underline";break}if(b){a.win.focus();a.execCmd(b);a.deferFocus();d.preventDefault()}}}},insertAtCursor:function(c){var b=this,a;if(b.activated){b.win.focus();if(Ext.isIE){a=b.getDoc().selection.createRange();if(a){a.pasteHTML(c);b.syncValue();b.deferFocus()}}else{b.execCmd("InsertHTML",c);b.deferFocus()}}},fixKeys:(function(){if(Ext.isIE){return function(h){var c=this,b=h.getKey(),g=c.getDoc(),i=c.readOnly,a,d;if(b===h.TAB){h.stopEvent();if(!i){a=g.selection.createRange();if(a){a.collapse(true);a.pasteHTML("    ");c.deferFocus()}}}else{if(b===h.ENTER){if(!i){a=g.selection.createRange();if(a){d=a.parentElement();if(!d||d.tagName.toLowerCase()!=="li"){h.stopEvent();a.pasteHTML("
    ");a.collapse(false);a.select()}}}}}}}if(Ext.isOpera){return function(b){var a=this;if(b.getKey()===b.TAB){b.stopEvent();if(!a.readOnly){a.win.focus();a.execCmd("InsertHTML","    ");a.deferFocus()}}}}if(Ext.isWebKit){return function(c){var b=this,a=c.getKey(),d=b.readOnly;if(a===c.TAB){c.stopEvent();if(!d){b.execCmd("InsertText","\t");b.deferFocus()}}else{if(a===c.ENTER){c.stopEvent();if(!d){b.execCmd("InsertHtml","

    ");b.deferFocus()}}}}}return null}()),getToolbar:function(){return this.toolbar},buttonTips:{bold:{title:"Bold (Ctrl+B)",text:"Make the selected text bold.",cls:Ext.baseCSSPrefix+"html-editor-tip"},italic:{title:"Italic (Ctrl+I)",text:"Make the selected text italic.",cls:Ext.baseCSSPrefix+"html-editor-tip"},underline:{title:"Underline (Ctrl+U)",text:"Underline the selected text.",cls:Ext.baseCSSPrefix+"html-editor-tip"},increasefontsize:{title:"Grow Text",text:"Increase the font size.",cls:Ext.baseCSSPrefix+"html-editor-tip"},decreasefontsize:{title:"Shrink Text",text:"Decrease the font size.",cls:Ext.baseCSSPrefix+"html-editor-tip"},backcolor:{title:"Text Highlight Color",text:"Change the background color of the selected text.",cls:Ext.baseCSSPrefix+"html-editor-tip"},forecolor:{title:"Font Color",text:"Change the color of the selected text.",cls:Ext.baseCSSPrefix+"html-editor-tip"},justifyleft:{title:"Align Text Left",text:"Align text to the left.",cls:Ext.baseCSSPrefix+"html-editor-tip"},justifycenter:{title:"Center Text",text:"Center text in the editor.",cls:Ext.baseCSSPrefix+"html-editor-tip"},justifyright:{title:"Align Text Right",text:"Align text to the right.",cls:Ext.baseCSSPrefix+"html-editor-tip"},insertunorderedlist:{title:"Bullet List",text:"Start a bulleted list.",cls:Ext.baseCSSPrefix+"html-editor-tip"},insertorderedlist:{title:"Numbered List",text:"Start a numbered list.",cls:Ext.baseCSSPrefix+"html-editor-tip"},createlink:{title:"Hyperlink",text:"Make the selected text a hyperlink.",cls:Ext.baseCSSPrefix+"html-editor-tip"},sourceedit:{title:"Source Edit",text:"Switch to source editing mode.",cls:Ext.baseCSSPrefix+"html-editor-tip"}}});Ext.define("Ext.panel.Tool",{extend:"Ext.Component",requires:["Ext.tip.QuickTipManager"],alias:"widget.tool",baseCls:Ext.baseCSSPrefix+"tool",disabledCls:Ext.baseCSSPrefix+"tool-disabled",toolPressedCls:Ext.baseCSSPrefix+"tool-pressed",toolOverCls:Ext.baseCSSPrefix+"tool-over",ariaRole:"button",childEls:["toolEl"],renderTpl:[''],tooltipType:"qtip",stopEvent:true,height:15,width:15,initComponent:function(){var a=this;a.addEvents("click");a.type=a.type||a.id;Ext.applyIf(a.renderData,{baseCls:a.baseCls,blank:Ext.BLANK_IMAGE_URL,type:a.type});a.tooltip=a.tooltip||a.qtip;a.callParent();a.on({element:"toolEl",click:a.onClick,mousedown:a.onMouseDown,mouseover:a.onMouseOver,mouseout:a.onMouseOut,scope:a})},afterRender:function(){var b=this,a;b.callParent(arguments);if(b.tooltip){if(Ext.isObject(b.tooltip)){Ext.tip.QuickTipManager.register(Ext.apply({target:b.id},b.tooltip))}else{a=b.tooltipType=="qtip"?"data-qtip":"title";b.toolEl.dom.setAttribute(a,b.tooltip)}}},getFocusEl:function(){return this.el},setType:function(a){var b=this;b.type=a;if(b.rendered){b.toolEl.dom.className=b.baseCls+"-"+a}return b},bindTo:function(a){this.owner=a},onClick:function(d,c){var b=this,a;if(b.disabled){return false}a=b.owner||b.ownerCt;b.el.removeCls(b.toolPressedCls);b.el.removeCls(b.toolOverCls);if(b.stopEvent!==false){d.stopEvent()}Ext.callback(b.handler,b.scope||b,[d,c,a,b]);b.fireEvent("click",b,d);return true},onDestroy:function(){if(Ext.isObject(this.tooltip)){Ext.tip.QuickTipManager.unregister(this.id)}this.callParent()},onMouseDown:function(){if(this.disabled){return false}this.el.addCls(this.toolPressedCls)},onMouseOver:function(){if(this.disabled){return false}this.el.addCls(this.toolOverCls)},onMouseOut:function(){this.el.removeCls(this.toolOverCls)}});Ext.define("Ext.toolbar.Paging",{extend:"Ext.toolbar.Toolbar",alias:"widget.pagingtoolbar",alternateClassName:"Ext.PagingToolbar",requires:["Ext.toolbar.TextItem","Ext.form.field.Number"],mixins:{bindable:"Ext.util.Bindable"},displayInfo:false,prependButtons:false,displayMsg:"Displaying {0} - {1} of {2}",emptyMsg:"No data to display",beforePageText:"Page",afterPageText:"of {0}",firstText:"First Page",prevText:"Previous Page",nextText:"Next Page",lastText:"Last Page",refreshText:"Refresh",inputItemWidth:30,getPagingItems:function(){var a=this;return[{itemId:"first",tooltip:a.firstText,overflowText:a.firstText,iconCls:Ext.baseCSSPrefix+"tbar-page-first",disabled:true,handler:a.moveFirst,scope:a},{itemId:"prev",tooltip:a.prevText,overflowText:a.prevText,iconCls:Ext.baseCSSPrefix+"tbar-page-prev",disabled:true,handler:a.movePrevious,scope:a},"-",a.beforePageText,{xtype:"numberfield",itemId:"inputItem",name:"inputItem",cls:Ext.baseCSSPrefix+"tbar-page-number",allowDecimals:false,minValue:1,hideTrigger:true,enableKeyEvents:true,keyNavEnabled:false,selectOnFocus:true,submitValue:false,isFormField:false,width:a.inputItemWidth,margins:"-1 2 3 2",listeners:{scope:a,keydown:a.onPagingKeyDown,blur:a.onPagingBlur}},{xtype:"tbtext",itemId:"afterTextItem",text:Ext.String.format(a.afterPageText,1)},"-",{itemId:"next",tooltip:a.nextText,overflowText:a.nextText,iconCls:Ext.baseCSSPrefix+"tbar-page-next",disabled:true,handler:a.moveNext,scope:a},{itemId:"last",tooltip:a.lastText,overflowText:a.lastText,iconCls:Ext.baseCSSPrefix+"tbar-page-last",disabled:true,handler:a.moveLast,scope:a},"-",{itemId:"refresh",tooltip:a.refreshText,overflowText:a.refreshText,iconCls:Ext.baseCSSPrefix+"tbar-loading",handler:a.doRefresh,scope:a}]},initComponent:function(){var b=this,c=b.getPagingItems(),a=b.items||b.buttons||[];if(b.prependButtons){b.items=a.concat(c)}else{b.items=c.concat(a)}delete b.buttons;if(b.displayInfo){b.items.push("->");b.items.push({xtype:"tbtext",itemId:"displayItem"})}b.callParent();b.addEvents("change","beforechange");b.on("beforerender",b.onLoad,b,{single:true});b.bindStore(b.store||"ext-empty-store",true)},updateInfo:function(){var e=this,c=e.child("#displayItem"),a=e.store,b=e.getPageData(),d,g;if(c){d=a.getCount();if(d===0){g=e.emptyMsg}else{g=Ext.String.format(e.displayMsg,b.fromRecord,b.toRecord,b.total)}c.setText(g)}},onLoad:function(){var g=this,d,b,c,a,e,h;e=g.store.getCount();h=e===0;if(!h){d=g.getPageData();b=d.currentPage;c=d.pageCount;a=Ext.String.format(g.afterPageText,isNaN(c)?1:c)}else{b=0;c=0;a=Ext.String.format(g.afterPageText,0)}Ext.suspendLayouts();g.child("#afterTextItem").setText(a);g.child("#inputItem").setDisabled(h).setValue(b);g.child("#first").setDisabled(b===1||h);g.child("#prev").setDisabled(b===1||h);g.child("#next").setDisabled(b===c||h);g.child("#last").setDisabled(b===c||h);g.child("#refresh").enable();g.updateInfo();Ext.resumeLayouts(true);if(g.rendered){g.fireEvent("change",g,d)}},getPageData:function(){var b=this.store,a=b.getTotalCount();return{total:a,currentPage:b.currentPage,pageCount:Math.ceil(a/b.pageSize),fromRecord:((b.currentPage-1)*b.pageSize)+1,toRecord:Math.min(b.currentPage*b.pageSize,a)}},onLoadError:function(){if(!this.rendered){return}this.child("#refresh").enable()},readPageFromInput:function(b){var a=this.child("#inputItem").getValue(),c=parseInt(a,10);if(!a||isNaN(c)){this.child("#inputItem").setValue(b.currentPage);return false}return c},onPagingFocus:function(){this.child("#inputItem").select()},onPagingBlur:function(b){var a=this.getPageData().currentPage;this.child("#inputItem").setValue(a)},onPagingKeyDown:function(i,h){var d=this,b=h.getKey(),c=d.getPageData(),a=h.shiftKey?10:1,g;if(b==h.RETURN){h.stopEvent();g=d.readPageFromInput(c);if(g!==false){g=Math.min(Math.max(1,g),c.pageCount);if(d.fireEvent("beforechange",d,g)!==false){d.store.loadPage(g)}}}else{if(b==h.HOME||b==h.END){h.stopEvent();g=b==h.HOME?1:c.pageCount;i.setValue(g)}else{if(b==h.UP||b==h.PAGE_UP||b==h.DOWN||b==h.PAGE_DOWN){h.stopEvent();g=d.readPageFromInput(c);if(g){if(b==h.DOWN||b==h.PAGE_DOWN){a*=-1}g+=a;if(g>=1&&g<=c.pageCount){i.setValue(g)}}}}}},beforeLoad:function(){if(this.rendered&&this.refresh){this.refresh.disable()}},moveFirst:function(){if(this.fireEvent("beforechange",this,1)!==false){this.store.loadPage(1)}},movePrevious:function(){var b=this,a=b.store.currentPage-1;if(a>0){if(b.fireEvent("beforechange",b,a)!==false){b.store.previousPage()}}},moveNext:function(){var c=this,b=c.getPageData().pageCount,a=c.store.currentPage+1;if(a<=b){if(c.fireEvent("beforechange",c,a)!==false){c.store.nextPage()}}},moveLast:function(){var b=this,a=b.getPageData().pageCount;if(b.fireEvent("beforechange",b,a)!==false){b.store.loadPage(a)}},doRefresh:function(){var a=this,b=a.store.currentPage;if(a.fireEvent("beforechange",a,b)!==false){a.store.loadPage(b)}},getStoreListeners:function(){return{beforeload:this.beforeLoad,load:this.onLoad,exception:this.onLoadError}},unbind:function(a){this.bindStore(null)},bind:function(a){this.bindStore(a)},onDestroy:function(){this.unbind();this.callParent()}});Ext.define("Ext.tree.Column",{extend:"Ext.grid.column.Column",alias:"widget.treecolumn",tdCls:Ext.baseCSSPrefix+"grid-cell-treecolumn",initComponent:function(){var a=this.renderer||this.defaultRenderer,b=this.scope||window;this.renderer=function(m,o,e,d,l,h,k){var s=[],q=Ext.String.format,u=e.getDepth(),r=Ext.baseCSSPrefix+"tree-",g=r+"elbow-",n=r+"expander",j='',v='',i=a.apply(b,arguments),p=e.get("href"),t=e.get("hrefTarget"),c=e.get("cls");while(e){if(!e.isRoot()||(e.isRoot()&&k.rootVisible)){if(e.getDepth()===u){s.unshift(q(j,r+"icon "+r+"icon"+(e.get("icon")?"-inline ":(e.isLeaf()?"-leaf ":"-parent "))+(e.get("iconCls")||""),e.get("icon")||Ext.BLANK_IMAGE_URL));if(e.get("checked")!==null){s.unshift(q(v,(r+"checkbox")+(e.get("checked")?" "+r+"checkbox-checked":""),e.get("checked")?'aria-checked="true"':""));if(e.get("checked")){o.tdCls+=(" "+r+"checked")}}if(e.isLast()){if(e.isExpandable()){s.unshift(q(j,(g+"end-plus "+n),Ext.BLANK_IMAGE_URL))}else{s.unshift(q(j,(g+"end"),Ext.BLANK_IMAGE_URL))}}else{if(e.isExpandable()){s.unshift(q(j,(g+"plus "+n),Ext.BLANK_IMAGE_URL))}else{s.unshift(q(j,(r+"elbow"),Ext.BLANK_IMAGE_URL))}}}else{if(e.isLast()||e.getDepth()===0){s.unshift(q(j,(g+"empty"),Ext.BLANK_IMAGE_URL))}else{if(e.getDepth()!==0){s.unshift(q(j,(g+"line"),Ext.BLANK_IMAGE_URL))}}}}e=e.parentNode}if(p){s.push('',i,"")}else{s.push(i)}if(c){o.tdCls+=" "+c}return s.join("")};this.callParent(arguments)},defaultRenderer:function(a){return a}});Ext.define("Ext.view.DragZone",{extend:"Ext.dd.DragZone",containerScroll:false,constructor:function(a){var b=this;Ext.apply(b,a);if(!b.ddGroup){b.ddGroup="view-dd-zone-"+b.view.id}b.callParent([b.view.el.dom.parentNode]);b.ddel=Ext.get(document.createElement("div"));b.ddel.addCls(Ext.baseCSSPrefix+"grid-dd-wrap")},init:function(c,a,b){this.initTarget(c,a,b);this.view.mon(this.view,{itemmousedown:this.onItemMouseDown,scope:this})},onItemMouseDown:function(b,a,d,c,g){if(!this.isPreventDrag(g,a,d,c)){this.handleMouseDown(g);if(b.getSelectionModel().selectionMode=="MULTI"&&!g.ctrlKey&&b.getSelectionModel().isSelected(a)){return false}}},isPreventDrag:function(a){return false},getDragData:function(c){var a=this.view,b=c.getTarget(a.getItemSelector());if(b){return{copy:a.copy||(a.allowCopy&&c.ctrlKey),event:new Ext.EventObjectImpl(c),view:a,ddel:this.ddel,item:b,records:a.getSelectionModel().getSelection(),fromPosition:Ext.fly(b).getXY()}}},onInitDrag:function(b,j){var g=this,h=g.dragData,d=h.view,a=d.getSelectionModel(),c=d.getRecord(h.item),i=h.event;if(!a.isSelected(c)||i.hasModifier()){a.selectWithEvent(c,i,true)}h.records=a.getSelection();g.ddel.update(g.getDragText());g.proxy.update(g.ddel.dom);g.onStartDrag(b,j);return true},getDragText:function(){var a=this.dragData.records.length;return Ext.String.format(this.dragText,a,a==1?"":"s")},getRepairXY:function(b,a){return a?a.fromPosition:false}});Ext.define("Ext.tree.ViewDragZone",{extend:"Ext.view.DragZone",isPreventDrag:function(b,a){return(a.get("allowDrag")===false)||!!b.getTarget(this.view.expanderSelector)},afterRepair:function(){var h=this,a=h.view,i=a.selectedItemCls,b=h.dragData.records,g,e=b.length,c=Ext.fly,d;if(Ext.enableFx&&h.repairHighlight){for(g=0;g
    ',indicatorCls:Ext.baseCSSPrefix+"grid-drop-indicator",constructor:function(a){var b=this;Ext.apply(b,a);if(!b.ddGroup){b.ddGroup="view-dd-zone-"+b.view.id}b.callParent([b.view.el])},fireViewEvent:function(){var b=this,a;b.lock();a=b.view.fireEvent.apply(b.view,arguments);b.unlock();return a},getTargetFromEvent:function(k){var j=k.getTarget(this.view.getItemSelector()),d,c,b,g,a,h;if(!j){d=k.getPageY();for(g=0,c=this.view.getNodes(),a=c.length;g=(b.bottom-b.top)/2){d="before"}else{d="after"}return d},containsRecordAtOffset:function(d,b,g){if(!b){return false}var a=this.view,c=a.indexOf(b),e=a.getNode(c+g),h=e?a.getRecord(e):null;return h&&Ext.Array.contains(d,h)},positionIndicator:function(b,c,d){var g=this,i=g.view,h=g.getPosition(d,b),k=i.getRecord(b),a=c.records,j;if(!Ext.Array.contains(a,k)&&(h=="before"&&!g.containsRecordAtOffset(a,k,-1)||h=="after"&&!g.containsRecordAtOffset(a,k,1))){g.valid=true;if(g.overRecord!=k||g.currentPosition!=h){j=Ext.fly(b).getY()-i.el.getY()-1;if(h=="after"){j+=Ext.fly(b).getHeight()}g.getIndicator().setWidth(Ext.fly(i.el).getWidth()).showAt(0,j);g.overRecord=k;g.currentPosition=h}}else{g.invalidateDrop()}},invalidateDrop:function(){if(this.valid){this.valid=false;this.getIndicator().hide()}},onNodeOver:function(c,a,g,d){var b=this;if(!Ext.Array.contains(d.records,b.view.getRecord(c))){b.positionIndicator(c,d,g)}return b.valid?b.dropAllowed:b.dropNotAllowed},notifyOut:function(c,a,g,d){var b=this;b.callParent(arguments);delete b.overRecord;delete b.currentPosition;if(b.indicator){b.indicator.hide()}},onContainerOver:function(a,h,g){var d=this,b=d.view,c=b.store.getCount();if(c){d.positionIndicator(b.getNode(c-1),g,h)}else{delete d.overRecord;delete d.currentPosition;d.getIndicator().setWidth(Ext.fly(b.el).getWidth()).showAt(0,0);d.valid=true}return d.dropAllowed},onContainerDrop:function(a,c,b){return this.onNodeDrop(a,null,c,b)},onNodeDrop:function(g,a,i,h){var d=this,c=false,b={wait:false,processDrop:function(){d.invalidateDrop();d.handleNodeDrop(h,d.overRecord,d.currentPosition);c=true;d.fireViewEvent("drop",g,h,d.overRecord,d.currentPosition)},cancelDrop:function(){d.invalidateDrop();c=true}},j=false;if(d.valid){j=d.fireViewEvent("beforedrop",g,h,d.overRecord,d.currentPosition,b);if(b.wait){return}if(j!==false){if(!c){b.processDrop()}}}return j},destroy:function(){Ext.destroy(this.indicator);delete this.indicator;this.callParent()}});Ext.define("Ext.grid.ViewDropZone",{extend:"Ext.view.DropZone",indicatorHtml:'
    ',indicatorCls:Ext.baseCSSPrefix+"grid-drop-indicator",handleNodeDrop:function(b,d,e){var j=this.view,k=j.getStore(),h,a,c,g;if(b.copy){a=b.records;b.records=[];for(c=0,g=a.length;c=i.top&&h<(i.top+d)){return"before"}else{if(!a&&(k||(h>=(i.bottom-d)&&h<=i.bottom))){return"after"}else{return"append"}}},isValidDropPoint:function(b,j,n,k,g){if(!b||!g.item){return false}var o=this.view,l=o.getRecord(b),d=g.records,a=d.length,m=d.length,c,h;if(!(l&&j&&a)){return false}for(c=0;c',"",'','','',"","","{[this.openRows()]}","{row}",'',"{[this.embedFeature(values, parent, xindex, xcount)]}","","{[this.closeRows()]}","","","{%if (this.closeTableWrap)out.push(this.closeTableWrap())%}"],constructor:function(){Ext.XTemplate.prototype.recurse=function(b,a){return this.apply(a?b[a]:b)}},embedFeature:function(b,d,a,e){var c="";if(!b.disabled){c=b.getFeatureTpl(b,d,a,e)}return c},embedFullWidth:function(b){var a='style="width:{fullWidth}px;';if(!b.rowCount){a+="height:1px;"}return a+'"'},openRows:function(){return''},closeRows:function(){return""},metaRowTpl:['','','','
    {{id}}
    ',"","
    ",""],firstOrLastCls:function(a,b){if(a===1){return Ext.view.Table.prototype.firstCls}else{if(a===b){return Ext.view.Table.prototype.lastCls}}},embedRowCls:function(){return"{rowCls}"},embedRowAttr:function(){return"{rowAttr}"},openTableWrap:undefined,closeTableWrap:undefined,getTableTpl:function(k,b){var j,h={openRows:this.openRows,closeRows:this.closeRows,embedFeature:this.embedFeature,embedFullWidth:this.embedFullWidth,openTableWrap:this.openTableWrap,closeTableWrap:this.closeTableWrap},g={},c=k.features||[],m=c.length,e=0,l={embedRowCls:this.embedRowCls,embedRowAttr:this.embedRowAttr,firstOrLastCls:this.firstOrLastCls,unselectableAttr:k.enableTextSelection?"":'unselectable="on"',unselectableCls:k.enableTextSelection?"":Ext.baseCSSPrefix+"unselectable"},d=Array.prototype.slice.call(this.metaRowTpl,0),a;for(;e',"{%","var me=values.$comp, pagingToolbar=me.pagingToolbar;","if (pagingToolbar) {","pagingToolbar.ownerLayout = me.componentLayout;","Ext.DomHelper.generateMarkup(pagingToolbar.getRenderTree(), out);","}","%}",{disableFormats:true}],initComponent:function(){var b=this,a=b.baseCls,c=b.itemCls;b.selectedItemCls=a+"-selected";b.overItemCls=a+"-item-over";b.itemSelector="."+c;if(b.floating){b.addCls(a+"-floating")}if(!b.tpl){b.tpl=new Ext.XTemplate('
      ','
    • '+b.getInnerTpl(b.displayField)+"
    • ","
    ")}else{if(Ext.isString(b.tpl)){b.tpl=new Ext.XTemplate(b.tpl)}}if(b.pageSize){b.pagingToolbar=b.createPagingToolbar()}b.callParent()},up:function(b){var a=this.pickerField;if(b){for(;a;a=a.ownerCt){if(Ext.ComponentQuery.is(a,b)){return a}}}return a},createPagingToolbar:function(){return Ext.widget("pagingtoolbar",{id:this.id+"-paging-toolbar",pageSize:this.pageSize,store:this.store,border:false})},finishRenderChildren:function(){var a=this.pagingToolbar;this.callParent(arguments);if(a){a.finishRender()}},refresh:function(){var b=this,a=b.pagingToolbar;b.callParent();if(b.rendered&&a&&!b.preserveScrollOnRefresh){b.el.appendChild(a.el)}},bindStore:function(a,b){var c=this.pagingToolbar;this.callParent(arguments);if(c){c.bindStore(this.store,b)}},getTargetEl:function(){return this.listEl||this.el},getInnerTpl:function(a){return"{"+a+"}"},onDestroy:function(){Ext.destroyMembers(this,"pagingToolbar","listEl");this.callParent()}});Ext.define("Ext.picker.Time",{extend:"Ext.view.BoundList",alias:"widget.timepicker",requires:["Ext.data.Store","Ext.Date"],increment:15,format:"g:i A",displayField:"disp",initDate:[2008,0,1],componentCls:Ext.baseCSSPrefix+"timepicker",loadMask:false,initComponent:function(){var c=this,a=Ext.Date,b=a.clearTime,d=c.initDate;c.absMin=b(new Date(d[0],d[1],d[2]));c.absMax=a.add(b(new Date(d[0],d[1],d[2])),"mi",(24*60)-1);c.store=c.createStore();c.updateList();c.callParent()},setMinValue:function(a){this.minValue=a;this.updateList()},setMaxValue:function(a){this.maxValue=a;this.updateList()},normalizeDate:function(a){var b=this.initDate;a.setFullYear(b[0],b[1],b[2]);return a},updateList:function(){var c=this,b=c.normalizeDate(c.minValue||c.absMin),a=c.normalizeDate(c.maxValue||c.absMax);c.store.filterBy(function(d){var e=d.get("date");return e>=b&&e<=a})},createStore:function(){var d=this,c=Ext.Date,e=[],b=d.absMin,a=d.absMax;while(b<=a){e.push({disp:c.dateFormat(b,d.format),date:b});b=c.add(b,"mi",d.increment)}return new Ext.data.Store({fields:["disp","date"],data:e})}});Ext.define("Ext.view.BoundListKeyNav",{extend:"Ext.util.KeyNav",requires:"Ext.view.BoundList",constructor:function(b,a){var c=this;c.boundList=a.boundList;c.callParent([b,Ext.apply({},a,c.defaultHandlers)])},defaultHandlers:{up:function(){var e=this,b=e.boundList,d=b.all,g=b.highlightedItem,c=g?b.indexOf(g):-1,a=c>0?c-1:d.getCount()-1;e.highlightAt(a)},down:function(){var e=this,b=e.boundList,d=b.all,g=b.highlightedItem,c=g?b.indexOf(g):-1,a=c',' value="{[Ext.util.Format.htmlEncode(values.value)]}"',' name="{name}"',' placeholder="{placeholder}"',' size="{size}"',' maxlength="{maxLength}"',' readonly="readonly"',' disabled="disabled"',' tabIndex="{tabIdx}"',' style="{fieldStyle}"',"/>",{compiled:true,disableFormats:true}],getSubTplData:function(){var a=this;Ext.applyIf(a.subTplData,{hiddenDataCls:a.hiddenDataCls});return a.callParent(arguments)},afterRender:function(){var a=this;a.callParent(arguments);a.setHiddenValue(a.value)},multiSelect:false,delimiter:", ",displayField:"text",triggerAction:"all",allQuery:"",queryParam:"query",queryMode:"remote",queryCaching:true,pageSize:0,autoSelect:true,typeAhead:false,typeAheadDelay:250,selectOnTab:true,forceSelection:false,growToLongestValue:true,defaultListConfig:{loadingHeight:70,minWidth:70,maxHeight:300,shadow:"sides"},ignoreSelection:0,removingRecords:null,resizeComboToGrow:function(){var a=this;return a.grow&&a.growToLongestValue},initComponent:function(){var e=this,c=Ext.isDefined,b=e.store,d=e.transform,a,g;Ext.applyIf(e.renderSelectors,{hiddenDataEl:"."+e.hiddenDataCls.split(" ").join(".")});this.addEvents("beforequery","select","beforeselect","beforedeselect");if(d){a=Ext.getDom(d);if(a){if(!e.store){b=Ext.Array.map(Ext.Array.from(a.options),function(h){return[h.value,h.text]})}if(!e.name){e.name=a.name}if(!("value" in e)){e.value=a.value}}}e.bindStore(b||"ext-empty-store",true);b=e.store;if(b.autoCreated){e.queryMode="local";e.valueField=e.displayField="field1";if(!b.expanded){e.displayField="field2"}}if(!c(e.valueField)){e.valueField=e.displayField}g=e.queryMode==="local";if(!c(e.queryDelay)){e.queryDelay=g?10:500}if(!c(e.minChars)){e.minChars=g?0:4}if(!e.displayTpl){e.displayTpl=new Ext.XTemplate('{[typeof values === "string" ? values : values["'+e.displayField+'"]]}'+e.delimiter+"")}else{if(Ext.isString(e.displayTpl)){e.displayTpl=new Ext.XTemplate(e.displayTpl)}}e.callParent();e.doQueryTask=new Ext.util.DelayedTask(e.doRawQuery,e);if(e.store.getCount()>0){e.setValue(e.value)}if(a){e.render(a.parentNode,a);Ext.removeNode(a);delete e.renderTo}},getStore:function(){return this.store},beforeBlur:function(){this.doQueryTask.cancel();this.assertValue()},assertValue:function(){var a=this,b=a.getRawValue(),c;if(a.forceSelection){if(a.multiSelect){if(b!==a.getDisplayValue()){a.setValue(a.lastSelection)}}else{c=a.findRecordByDisplay(b);if(c){a.select(c)}else{a.setValue(a.lastSelection)}}}a.collapse()},onTypeAhead:function(){var e=this,d=e.displayField,b=e.store.findRecord(d,e.getRawValue()),c=e.getPicker(),g,a,h;if(b){g=b.get(d);a=g.length;h=e.getRawValue().length;c.highlightItem(c.getNode(b));if(h!==0&&h!==a){e.setRawValue(g);e.selectText(h,g.length)}}},resetToDefault:function(){},onUnbindStore:function(a){var b=this.picker;if(!a&&b){b.bindStore(null)}},onBindStore:function(a,c){var b=this.picker;if(!c){this.resetToDefault()}if(b){b.bindStore(a)}},getStoreListeners:function(){var a=this;return{beforeload:a.onBeforeLoad,clear:a.onClear,datachanged:a.onDataChanged,load:a.onLoad,exception:a.onException,remove:a.onRemove}},onBeforeLoad:function(){++this.ignoreSelection},onDataChanged:function(){var a=this;if(a.resizeComboToGrow()){a.updateLayout()}},onClear:function(){var a=this;if(a.resizeComboToGrow()){a.removingRecords=true;a.onDataChanged()}},onRemove:function(){var a=this;if(a.resizeComboToGrow()){a.removingRecords=true}},onException:function(){if(this.ignoreSelection>0){--this.ignoreSelection}this.collapse()},onLoad:function(){var a=this,b=a.value;if(a.ignoreSelection>0){--a.ignoreSelection}if(a.rawQuery){a.rawQuery=false;a.syncSelection();if(a.picker&&!a.picker.getSelectionModel().hasSelection()){a.doAutoSelect()}}else{if(a.value||a.value===0){a.setValue(a.value)}else{if(a.store.getCount()){a.doAutoSelect()}else{a.setValue(a.value)}}}},doRawQuery:function(){this.doQuery(this.getRawValue(),false,true)},doQuery:function(i,d,g){i=i||"";var e=this,b={query:i,forceAll:d,combo:e,cancel:false},a=e.store,h=e.queryMode==="local",c;if(e.fireEvent("beforequery",b)===false||b.cancel){return false}i=b.query;d=b.forceAll;if(d||(i.length>=e.minChars)){e.expand();if(!e.queryCaching||e.lastQuery!==i){e.lastQuery=i;if(h){a.suspendEvents();c=e.clearFilter();if(i||!d){e.activeFilter=new Ext.util.Filter({root:"data",property:e.displayField,value:i});a.filter(e.activeFilter);c=true}else{delete e.activeFilter}a.resumeEvents();if(e.rendered&&c){e.getPicker().refresh()}}else{e.rawQuery=g;if(e.pageSize){e.loadPage(1)}else{a.load({params:e.getParams(i)})}}}if(e.getRawValue()!==e.getDisplayValue()){e.ignoreSelection++;e.picker.getSelectionModel().deselectAll();e.ignoreSelection--}if(h){e.doAutoSelect()}if(e.typeAhead){e.doTypeAhead()}}return true},clearFilter:function(){var a=this.store,d=a.filters,c=this.activeFilter,b;if(c){if(d.getCount()>1){d.remove(c);b=d.getRange()}a.clearFilter(true);if(b){a.filter(b)}}return !!c},loadPage:function(a){this.store.loadPage(a,{params:this.getParams(this.lastQuery)})},onPageChange:function(b,a){this.loadPage(a);return false},getParams:function(c){var b={},a=this.queryParam;if(a){b[a]=c}return b},doAutoSelect:function(){var b=this,a=b.picker,c,d;if(a&&b.autoSelect&&b.store.getCount()>0){c=a.getSelectionModel().lastSelected;d=a.getNode(c||0);if(d){a.highlightItem(d);a.listEl.scrollChildIntoView(d,false)}}},doTypeAhead:function(){if(!this.typeAheadTask){this.typeAheadTask=new Ext.util.DelayedTask(this.onTypeAhead,this)}if(this.lastKey!=Ext.EventObject.BACKSPACE&&this.lastKey!=Ext.EventObject.DELETE){this.typeAheadTask.delay(this.typeAheadDelay)}},onTriggerClick:function(){var a=this;if(!a.readOnly&&!a.disabled){if(a.isExpanded){a.collapse()}else{a.onFocus({});if(a.triggerAction==="all"){a.doQuery(a.allQuery,true)}else{a.doQuery(a.getRawValue(),false,true)}}a.inputEl.focus()}},onKeyUp:function(d,b){var c=this,a=d.getKey();if(!c.readOnly&&!c.disabled&&c.editable){c.lastKey=a;if(!d.isSpecialKey()||a==d.BACKSPACE||a==d.DELETE){c.doQueryTask.delay(c.queryDelay)}}if(c.enableKeyEvents){c.callParent(arguments)}},initEvents:function(){var a=this;a.callParent();if(!a.enableKeyEvents){a.mon(a.inputEl,"keyup",a.onKeyUp,a)}},onDestroy:function(){this.bindStore(null);this.callParent()},onAdded:function(){var a=this;a.callParent(arguments);if(a.picker){a.picker.ownerCt=a.up("[floating]");a.picker.registerWithOwnerCt()}},createPicker:function(){var c=this,b,d=Ext.baseCSSPrefix+"menu",a=Ext.apply({xtype:"boundlist",pickerField:c,selModel:{mode:c.multiSelect?"SIMPLE":"SINGLE"},floating:true,hidden:true,ownerCt:c.up("[floating]"),cls:c.el&&c.el.up("."+d)?d:"",store:c.store,displayField:c.displayField,focusOnToFront:false,pageSize:c.pageSize,tpl:c.tpl},c.listConfig,c.defaultListConfig);b=c.picker=Ext.widget(a);if(c.pageSize){b.pagingToolbar.on("beforechange",c.onPageChange,c)}c.mon(b,{itemclick:c.onItemClick,refresh:c.onListRefresh,scope:c});c.mon(b.getSelectionModel(),{beforeselect:c.onBeforeSelect,beforedeselect:c.onBeforeDeselect,selectionchange:c.onListSelectionChange,scope:c});return b},alignPicker:function(){var b=this,a=b.getPicker(),e=b.getPosition()[1]-Ext.getBody().getScroll().top,d=Ext.Element.getViewHeight()-e-b.getHeight(),c=Math.max(e,d);if(a.height){delete a.height;a.updateLayout()}if(a.getHeight()>c-5){a.setHeight(c-5)}b.callParent()},onListRefresh:function(){this.alignPicker();this.syncSelection()},onItemClick:function(c,a){var e=this,d=e.picker.getSelectionModel().getSelection(),b=e.valueField;if(!e.multiSelect&&d.length){if(a.get(b)===d[0].get(b)){e.displayTplData=[a.data];e.setRawValue(e.getDisplayValue());e.collapse()}}},onBeforeSelect:function(b,a){return this.fireEvent("beforeselect",this,a,a.index)},onBeforeDeselect:function(b,a){return this.fireEvent("beforedeselect",this,a,a.index)},onListSelectionChange:function(b,d){var a=this,e=a.multiSelect,c=d.length>0;if(!a.ignoreSelection&&a.isExpanded){if(!e){Ext.defer(a.collapse,1,a)}if(e||c){a.setValue(d,false)}if(c){a.fireEvent("select",a,d)}a.inputEl.focus()}},onExpand:function(){var d=this,a=d.listKeyNav,c=d.selectOnTab,b=d.getPicker();if(a){a.enable()}else{a=d.listKeyNav=new Ext.view.BoundListKeyNav(this.inputEl,{boundList:b,forceKeyDown:true,tab:function(g){if(c){this.selectHighlighted(g);d.triggerBlur()}return true}})}if(c){d.ignoreMonitorTab=true}Ext.defer(a.enable,1,a);d.inputEl.focus()},onCollapse:function(){var b=this,a=b.listKeyNav;if(a){a.disable();b.ignoreMonitorTab=false}},select:function(a){this.setValue(a,true)},findRecord:function(d,c){var b=this.store,a=b.findExact(d,c);return a!==-1?b.getAt(a):false},findRecordByValue:function(a){return this.findRecord(this.valueField,a)},findRecordByDisplay:function(a){return this.findRecord(this.displayField,a)},setValue:function(m,e){var k=this,c=k.valueNotFoundText,n=k.inputEl,g,j,h,a,l=[],b=[],d=[];if(k.store.loading){k.value=m;k.setHiddenValue(k.value);return k}m=Ext.Array.from(m);for(g=0,j=m.length;g0){e.hiddenDataEl.update(Ext.DomHelper.markup({tag:"input",type:"hidden",name:a}));c=1;h=b.firstChild}while(c>g){b.removeChild(k[0]);--c}while(c=0){g.push(i)}}h.ignoreSelection++;c=d.getSelectionModel();c.deselectAll();if(g.length){c.select(g)}h.ignoreSelection--}},onEditorTab:function(b){var a=this.listKeyNav;if(this.selectOnTab&&a){a.selectHighlighted(b)}}});Ext.define("Ext.form.field.Time",{extend:"Ext.form.field.ComboBox",alias:"widget.timefield",requires:["Ext.form.field.Date","Ext.picker.Time","Ext.view.BoundListKeyNav","Ext.Date"],alternateClassName:["Ext.form.TimeField","Ext.form.Time"],triggerCls:Ext.baseCSSPrefix+"form-time-trigger",minText:"The time in this field must be equal to or after {0}",maxText:"The time in this field must be equal to or before {0}",invalidText:"{0} is not a valid time",format:"g:i A",submitFormat:"g:i A",altFormats:"g:ia|g:iA|g:i a|g:i A|h:i|g:i|H:i|ga|ha|gA|h a|g a|g A|gi|hi|gia|hia|g|H|gi a|hi a|giA|hiA|gi A|hi A",increment:15,pickerMaxHeight:300,selectOnTab:true,snapToIncrement:false,initDate:"1/1/2008",initDateFormat:"j/n/Y",ignoreSelection:0,queryMode:"local",displayField:"disp",valueField:"date",initComponent:function(){var c=this,b=c.minValue,a=c.maxValue;if(b){c.setMinValue(b)}if(a){c.setMaxValue(a)}c.displayTpl=new Ext.XTemplate('{[typeof values === "string" ? values : this.formatDate(values["'+c.displayField+'"])]}'+c.delimiter+"",{formatDate:Ext.Function.bind(c.formatDate,c)});this.callParent()},setMinValue:function(c){var b=this,a=b.picker;b.setLimit(c,true);if(a){a.setMinValue(b.minValue)}},setMaxValue:function(c){var b=this,a=b.picker;b.setLimit(c,false);if(a){a.setMaxValue(b.maxValue)}},setLimit:function(b,g){var a=this,e,c;if(Ext.isString(b)){e=a.parseDate(b)}else{if(Ext.isDate(b)){e=b}}if(e){c=Ext.Date.clearTime(new Date(a.initDate));c.setHours(e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds())}else{c=null}a[g?"minValue":"maxValue"]=c},rawToValue:function(a){return this.parseDate(a)||a||null},valueToRaw:function(a){return this.formatDate(this.parseDate(a))},getErrors:function(d){var b=this,g=Ext.String.format,h=b.callParent(arguments),c=b.minValue,e=b.maxValue,a;d=b.formatDate(d||b.processRawValue(b.getRawValue()));if(d===null||d.length<1){return h}a=b.parseDate(d);if(!a){h.push(g(b.invalidText,d,Ext.Date.unescapeFormat(b.format)));return h}if(c&&ae){h.push(g(b.maxText,b.formatDate(e)))}return h},formatDate:function(){return Ext.form.field.Date.prototype.formatDate.apply(this,arguments)},parseDate:function(e){var d=this,h=e,b=d.altFormats,g=d.altFormatsArray,c=0,a;if(e&&!Ext.isDate(e)){h=d.safeParse(e,d.format);if(!h&&b){g=g||b.split("|");a=g.length;for(;c0){c=c[0];if(c&&Ext.Date.isEqual(a.get("date"),c.get("date"))){d.collapse()}}},onListSelectionChange:function(c,e){var b=this,a=e[0],d=a?a.get("date"):null;if(!b.ignoreSelection){b.skipSync=true;b.setValue(d);b.skipSync=false;b.fireEvent("select",b,d);b.picker.clearHighlight();b.collapse();b.inputEl.focus()}},syncSelection:function(){var j=this,h=j.picker,c,g,k,b,i,e,a;if(h&&!j.skipSync){h.clearHighlight();k=j.getValue();g=h.getSelectionModel();j.ignoreSelection++;if(k===null){g.deselectAll()}else{if(Ext.isDate(k)){b=h.store.data.items;e=b.length;for(i=0;i1)?document.createDocumentFragment():undefined,c=p,q=n.getGridColumns().length,o=q-1,b=(n.firstCls||n.lastCls)&&(p==0||p==q||a==0||a==o),g,e,r,k,m,h;if(n.rendered){h=n.el.query(n.headerRowSelector);r=n.el.query(n.rowSelector);if(p>a&&l){c-=d}for(g=0,k=h.length;ge){i=j.bottom-e}}d=g.getRecord(k);b=g.store.indexOf(d);if(i){a.scrollByDeltaY(i)}g.fireEvent("rowfocus",d,k,b)}},focusCell:function(h){var j=this,k=j.getCellByPosition(h),b=j.el,d=0,e=0,c=b.getRegion(),a=j.ownerCt,i,g;c.bottom=c.top+b.dom.clientHeight;c.right=c.left+b.dom.clientWidth;if(k){i=k.getRegion();if(i.topc.bottom){d=i.bottom-c.bottom}}if(i.leftc.right){e=i.right-c.right}}if(d){a.scrollByDeltaY(d)}if(e){a.scrollByDeltaX(e)}b.focus();j.fireEvent("cellfocus",g,k,h)}},scrollByDelta:function(c,b){b=b||"scrollTop";var a=this.el.dom;a[b]=(a[b]+=c)},onUpdate:function(p,g,d,o){var n=this,j,q,l,a,b,h,e,c,k,m,r;if(n.rendered){j=n.store.indexOf(g);c=n.headerCt.getGridColumns();k=n.overItemCls;if(c.length&&j>-1){q=n.bufferRender([g],j)[0];l=n.all.item(j);m=l.hasCls(k);l.dom.className=q.className;if(m){l.addCls(k)}a=l.query(this.cellSelector);b=Ext.fly(q).query(this.cellSelector);h=b.length;r=a[0].parentNode;for(e=0;ee){e=b}}return e},getPositionByEvent:function(g){var d=this,b=g.getTarget(d.cellSelector),c=g.getTarget(d.itemSelector),a=d.getRecord(c),h=d.getHeaderByCell(b);return d.getPosition(a,h)},getHeaderByCell:function(b){if(b){var a=b.className.match(this.cellRe);if(a&&a[1]){return Ext.getCmp(a[1])}}return false},walkCells:function(l,m,h,n,a,o){if(!l){return}var j=this,p=l.row,d=l.column,k=j.store.getCount(),g=j.getFirstVisibleColumnIndex(),b=j.getLastVisibleColumnIndex(),i={row:p,column:d},c=j.headerCt.getHeaderAtIndex(d);if(!c||c.hidden){return false}h=h||{};m=m.toLowerCase();switch(m){case"right":if(d===b){if(n||p===k-1){return false}if(!h.ctrlKey){i.row=p+1;i.column=g}}else{if(!h.ctrlKey){i.column=d+j.getRightGap(c)}else{i.column=b}}break;case"left":if(d===g){if(n||p===0){return false}if(!h.ctrlKey){i.row=p-1;i.column=b}}else{if(!h.ctrlKey){i.column=d+j.getLeftGap(c)}else{i.column=g}}break;case"up":if(p===0){return false}else{if(!h.ctrlKey){i.row=p-1}else{i.row=0}}break;case"down":if(p===k-1){return false}else{if(!h.ctrlKey){i.row=p+1}else{i.row=k-1}}break}if(a&&a.call(o||window,i)!==true){return false}else{return i}},getFirstVisibleColumnIndex:function(){var a=this.getHeaderCt().getVisibleGridColumns()[0];return a?a.getIndex():-1},getLastVisibleColumnIndex:function(){var b=this.getHeaderCt().getVisibleGridColumns(),a=b[b.length-1];return a.getIndex()},getHeaderCt:function(){return this.headerCt},getPosition:function(a,e){var d=this,b=d.store,c=d.headerCt.getGridColumns();return{row:b.indexOf(a),column:Ext.Array.indexOf(c,e)}},getRightGap:function(a){var g=this.getHeaderCt(),e=g.getGridColumns(),b=Ext.Array.indexOf(e,a),c=b+1,d;for(;c<=e.length;c++){if(!e[c].hidden){d=c;break}}return d-b},beforeDestroy:function(){if(this.rendered){this.el.removeAllListeners()}this.callParent(arguments)},getLeftGap:function(a){var g=this.getHeaderCt(),e=g.getGridColumns(),c=Ext.Array.indexOf(e,a),d=c-1,b;for(;d>=0;d--){if(!e[d].hidden){b=d;break}}return b-c},onAdd:function(c,a,b){this.callParent(arguments);this.doStripeRows(b)},onRemove:function(c,a,b){this.callParent(arguments);this.doStripeRows(b)},doStripeRows:function(b,a){var d=this,e,h,c,g;if(d.rendered&&d.stripeRows){e=d.getNodes(b,a);for(c=0,h=e.length;c>#normalHeaderCt"},normal:{items:c,itemId:"normalHeaderCt",stretchMaxPartner:"^^>>#lockedHeaderCt"}}},onLockedViewMouseWheel:function(i){var d=this,h=-d.scrollDelta,a=h*i.getWheelDeltas().y,b=d.lockedGrid.getView().el.dom,c,g;if(b){c=b.scrollTop!==b.scrollHeight-b.clientHeight;g=b.scrollTop!==0}if((a<0&&g)||(a>0&&c)){i.stopEvent();d.scrolling=true;b.scrollTop+=a;d.normalGrid.getView().el.dom.scrollTop=b.scrollTop;d.scrolling=false;d.onNormalViewScroll()}},onLockedViewScroll:function(){var e=this,d=e.lockedGrid.getView(),c=e.normalGrid.getView(),a,b;if(!e.scrolling){e.scrolling=true;c.el.dom.scrollTop=d.el.dom.scrollTop;if(e.store.buffered){b=d.el.child("table",true);a=c.el.child("table",true);b.style.position="absolute"}e.scrolling=false}},onNormalViewScroll:function(){var e=this,d=e.lockedGrid.getView(),c=e.normalGrid.getView(),a,b;if(!e.scrolling){e.scrolling=true;d.el.dom.scrollTop=c.el.dom.scrollTop;if(e.store.buffered){b=d.el.child("table",true);a=c.el.child("table",true);b.style.position="absolute";b.style.top=a.style.top}e.scrolling=false}},onLockedHeaderMove:function(){if(this.syncRowHeight){this.onNormalViewRefresh()}},onNormalHeaderMove:function(){if(this.syncRowHeight){this.onLockedViewRefresh()}},updateSpacer:function(){var d=this,b=d.lockedGrid.getView().el,c=d.normalGrid.getView().el.dom,a=b.dom.id+"-spacer",e=(c.offsetHeight-c.clientHeight)+"px";d.spacerEl=Ext.getDom(a);if(d.spacerEl){d.spacerEl.style.height=e}else{Ext.core.DomHelper.append(b,{id:a,style:"height: "+e})}},onLockedViewRefresh:function(){if(this.normalGrid.headerCt.getGridColumns().length){var e=this,a=e.lockedGrid.getView(),c=a.el,g=c.query(a.getItemSelector()),d=g.length,b=0;e.lockedHeights=[];for(;bl[g]){Ext.fly(h[g]).setHeight(b[g])}else{if(b[g]0){a.setWidth(b);a.show()}else{a.hide()}Ext.resumeLayouts(true);return b>0},onLockedHeaderResize:function(){this.syncLockedWidth()},onLockedHeaderHide:function(){this.syncLockedWidth()},onLockedHeaderShow:function(){this.syncLockedWidth()},onLockedHeaderSortChange:function(b,c,a){if(a){this.normalGrid.headerCt.clearOtherSortStates(null,true)}},onNormalHeaderSortChange:function(b,c,a){if(a){this.lockedGrid.headerCt.clearOtherSortStates(null,true)}},unlock:function(a,e){var d=this,g=d.normalGrid,i=d.lockedGrid,h=g.headerCt,c=i.headerCt,b=false;if(!Ext.isDefined(e)){e=0}a=a||c.getMenu().activeHeader;Ext.suspendLayouts();c.remove(a,false);if(d.syncLockedWidth()){b=true}a.locked=false;h.insert(e,a);d.normalGrid.getView().refresh();if(b){d.lockedGrid.getView().refresh()}Ext.resumeLayouts(true);d.fireEvent("unlockcolumn",d,a)},applyColumnsState:function(h){var p=this,e=p.lockedGrid,g=e.headerCt,n=p.normalGrid.headerCt,q=Ext.Array.toMap(g.items,"headerId"),j=Ext.Array.toMap(n.items,"headerId"),m=[],o=[],l=1,b=h.length,k,a,d,c;for(k=0;k'}c=Ext.get(d);a=c.insertSibling({tag:"tr",html:['','
    ','',g,"
    ","
    ",""].join("")},"after");return{record:j,node:d,el:a,expanding:false,collapsing:false,animating:false,animateEl:a.down("div"),targetEl:a.down("tbody")}},getAnimWrap:function(d,a){if(!this.animate){return null}var b=this.animWraps,c=b[d.internalId];if(a!==false){while(!c&&d){d=d.parentNode;if(d){c=b[d.internalId]}}}return c},doAdd:function(b,d,i){var j=this,g=d[0],l=g.parentNode,k=j.all.elements,n=0,e=j.getAnimWrap(l),m,c,h;if(!e||!e.expanding){return j.callParent(arguments)}l=e.record;m=e.targetEl;c=m.dom.childNodes;h=c.length-1;n=i-j.indexOf(l)-1;if(!h||n>=h){m.appendChild(b)}else{Ext.fly(c[n+1]).insertSibling(b,"before",true)}Ext.Array.insert(k,i,b);if(e.isAnimating){j.onExpand(l)}},beginBulkUpdate:function(){this.bulkUpdate=true;this.ownerCt.changingScrollbars=true},endBulkUpdate:function(){this.bulkUpdate=false;this.ownerCt.changingScrollbars=true},onRemove:function(e,a,b){var d=this,c=d.bulkUpdate;if(d.rendered){d.doRemove(a,b);if(!c){d.updateIndexes(b)}if(d.store.getCount()===0){d.refresh()}if(!c){d.fireEvent("itemremove",a,b)}}},doRemove:function(a,c){var g=this,d=g.all,b=g.getAnimWrap(a),e=d.item(c).dom;if(!b||!b.collapsing){return g.callParent(arguments)}b.targetEl.appendChild(e);d.removeElement(c)},onBeforeExpand:function(d,b,c){var e=this,a;if(!e.rendered||!e.animate){return}if(e.getNode(d)){a=e.getAnimWrap(d,false);if(!a){a=e.animWraps[d.internalId]=e.createAnimWrap(d);a.animateEl.setHeight(0)}else{if(a.collapsing){a.targetEl.select(e.itemSelector).remove()}}a.expanding=true;a.collapsing=false}},onExpand:function(i){var h=this,e=h.animQueue,a=i.getId(),c=h.getNode(i),g=c?h.indexOf(c):-1,d,b,j;if(h.singleExpand){h.ensureSingleExpand(i)}if(g===-1){return}d=h.getAnimWrap(i,false);if(!d){h.isExpandingOrCollapsing=false;h.fireEvent("afteritemexpand",i,g,c);return}b=d.animateEl;j=d.targetEl;b.stopAnimation();e[a]=true;b.slideIn("t",{duration:h.expandDuration,listeners:{scope:h,lastframe:function(){d.el.insertSibling(j.query(h.itemSelector),"before");d.el.remove();delete h.animWraps[d.record.internalId];delete e[a]}},callback:function(){h.isExpandingOrCollapsing=false;h.fireEvent("afteritemexpand",i,g,c)}});d.isAnimating=true},onBeforeCollapse:function(d,b,c){var e=this,a;if(!e.rendered||!e.animate){return}if(e.getNode(d)){a=e.getAnimWrap(d);if(!a){a=e.animWraps[d.internalId]=e.createAnimWrap(d,c)}else{if(a.expanding){a.targetEl.select(this.itemSelector).remove()}}a.expanding=false;a.collapsing=true}},onCollapse:function(i){var h=this,e=h.animQueue,a=i.getId(),c=h.getNode(i),g=c?h.indexOf(c):-1,d=h.getAnimWrap(i),b,j;if(g===-1){return}if(!d){h.isExpandingOrCollapsing=false;h.fireEvent("afteritemcollapse",i,g,c);return}b=d.animateEl;j=d.targetEl;e[a]=true;b.stopAnimation();b.slideOut("t",{duration:h.collapseDuration,listeners:{scope:h,lastframe:function(){d.el.remove();delete h.animWraps[d.record.internalId];delete e[a]}},callback:function(){h.isExpandingOrCollapsing=false;h.fireEvent("afteritemcollapse",i,g,c)}});d.isAnimating=true},isAnimating:function(a){return !!this.animQueue[a.getId()]},collectData:function(c){var g=this.callParent(arguments),e=g.rows,a=e.length,d=0,h,b;for(;d=0){d.row=c.getNode(a);e.reposition();if(e.tooltip&&e.tooltip.isVisible()){e.tooltip.setTarget(d.row)}}else{e.editingPlugin.cancelEdit()}},onCtScroll:function(d,c){var a=this,b=c.scrollTop,g=c.scrollLeft;if(b!==a.lastScrollTop){a.lastScrollTop=b;if((a.tooltip&&a.tooltip.isVisible())||a.hiddenTip){a.repositionTip()}}if(g!==a.lastScrollLeft){a.lastScrollLeft=g;a.reposition()}},onColumnAdd:function(a){if(!a.isGroupHeader){this.setField(a)}},onColumnRemove:function(a){this.columns.remove(a)},onColumnResize:function(b,a){if(!b.isGroupHeader){b.getEditor().setWidth(a-2);if(this.isVisible()){this.reposition()}}},onColumnHide:function(a){if(!a.isGroupHeader){a.getEditor().hide();if(this.isVisible()){this.reposition()}}},onColumnShow:function(a){var b=a.getEditor();b.setWidth(a.getWidth()-2).show();if(this.isVisible()){this.reposition()}},onColumnMove:function(b,a,c){if(!b.isGroupHeader){var d=b.getEditor();if(this.items.indexOf(d)!=c){this.move(a,c)}}},onFieldAdd:function(e,a,b){var c=this,g,d;if(!b.isGroupHeader){g=c.editingPlugin.grid.headerCt.getHeaderIndex(b);d=b.getEditor({xtype:"displayfield"});c.insert(g,d)}},onFieldRemove:function(g,a,b){var c=this,e,d;if(!b.isGroupHeader){e=b.getEditor();d=e.el;c.remove(e,false);if(d){d.remove()}}},onFieldReplace:function(d,a,c,b){this.onFieldRemove(d,a,b)},clearFields:function(){var b=this.columns,a;for(a in b){if(b.hasOwnProperty(a)){b.removeAtKey(a)}}},getFloatingButtons:function(){var d=this,e=Ext.baseCSSPrefix,c=e+"grid-row-editor-buttons",b=d.editingPlugin,a;if(!d.floatingButtons){a=d.floatingButtons=new Ext.Container({renderTpl:['
    ','
    ','
    ','
    ','
    ',"{%this.renderContainer(out,values)%}"],width:200,renderTo:d.el,baseCls:c,layout:{type:"hbox",align:"middle"},defaults:{flex:1,margins:"0 1 0 1"},items:[{itemId:"update",xtype:"button",handler:b.completeEdit,scope:b,text:d.saveBtnText,disabled:!d.isValid,minWidth:Ext.panel.Panel.prototype.minButtonWidth},{xtype:"button",handler:b.cancelEdit,scope:b,text:d.cancelBtnText,minWidth:Ext.panel.Panel.prototype.minButtonWidth}]});d.mon(a.el,{mousedown:Ext.emptyFn,click:Ext.emptyFn,stopEvent:true})}return d.floatingButtons},reposition:function(r){var s=this,c=s.context,e=c&&Ext.get(c.row),p=s.getFloatingButtons(),q=p.el,a=s.editingPlugin.grid,g=a.view.el,o=a.headerCt.getFullWidth(),t=a.getWidth(),l=Math.min(o,t),n=a.view.el.dom.scrollLeft,i=p.getWidth(),d=(l-i)/2+n,j,h,m,k=function(){q.scrollIntoView(g,false);if(r&&r.callback){r.callback.call(r.scope||s)}},b;if(e&&Ext.isElement(e.dom)){e.scrollIntoView(g,false);j=e.getXY()[1]-5;h=e.getHeight();m=h+(s.editingPlugin.grid.rowLines?9:10);if(s.getHeight()!=m){s.setHeight(m);s.el.setLeft(0)}if(r){b={to:{y:j},duration:r.duration||125,listeners:{afteranimate:function(){k();j=e.getXY()[1]-5}}};s.el.animate(b)}else{s.el.setY(j);k()}}if(s.getWidth()!=o){s.setWidth(o)}q.setLeft(d)},getEditor:function(a){var b=this;if(Ext.isNumber(a)){return b.query(">[isFormField]")[a]}else{if(a.isHeader&&!a.isGroupHeader){return a.getEditor()}}},removeField:function(b){var a=this;b=a.getEditor(b);a.mun(b,"validitychange",a.onValidityChange,a);a.columns.removeAtKey(b.id);Ext.destroy(b)},setField:function(b){var d=this,a,c,e;if(Ext.isArray(b)){c=b.length;for(a=0;adisplayfield");g=d.length;for(e=0;eg&&a":"",h=[],a=d.query(">[isFormField]"),c=a.length,b;function g(i){return"
  • "+i+"
  • "}for(b=0;b"+h.join("")+""},beforeDestroy:function(){Ext.destroy(this.floatingButtons,this.tooltip);this.callParent()}});Ext.define("Ext.grid.plugin.RowEditing",{extend:"Ext.grid.plugin.Editing",alias:"plugin.rowediting",requires:["Ext.grid.RowEditor"],editStyle:"row",autoCancel:true,errorSummary:true,constructor:function(){var a=this;a.callParent(arguments);if(!a.clicksToMoveEditor){a.clicksToMoveEditor=a.clicksToEdit}a.autoCancel=!!a.autoCancel},init:function(a){this.callParent([a])},destroy:function(){var a=this;Ext.destroy(a.editor);a.callParent(arguments)},startEdit:function(a,d){var c=this,b=c.getEditor();if((c.callParent(arguments)!==false)&&(b.beforeEdit()!==false)){b.startEdit(c.context.record,c.context.column);return true}return false},cancelEdit:function(){var a=this;if(a.editing){a.getEditor().cancelEdit();a.callParent(arguments)}},completeEdit:function(){var a=this;if(a.editing&&a.validateEdit()){a.editing=false;a.fireEvent("edit",a,a.context)}},validateEdit:function(){var k=this,h=k.editor,b=k.context,g=b.record,m={},d={},j=h.items.items,i,c=j.length,a,l;for(i=0;i'about:blank', except for IE in secure mode, which is 'javascript:""'). + * @type String + */ + SSL_SECURE_URL : isSecure && isIE ? 'javascript:""' : 'about:blank', + /** + * True if the browser is in strict (standards-compliant) mode, as opposed to quirks mode + * @type Boolean + */ + isStrict : isStrict, + /** + * True if the page is running over SSL + * @type Boolean + */ + isSecure : isSecure, + /** + * True when the document is fully initialized and ready for action + * @type Boolean + */ + isReady : false, + + /** + * True if the {@link Ext.Fx} Class is available + * @type Boolean + * @property enableFx + */ + + /** + * True to automatically uncache orphaned Ext.Elements periodically (defaults to true) + * @type Boolean + */ + enableGarbageCollector : true, + + /** + * True to automatically purge event listeners during garbageCollection (defaults to false). + * @type Boolean + */ + enableListenerCollection : false, + + /** + * EXPERIMENTAL - True to cascade listener removal to child elements when an element is removed. + * Currently not optimized for performance. + * @type Boolean + */ + enableNestedListenerRemoval : false, + + /** + * Indicates whether to use native browser parsing for JSON methods. + * This option is ignored if the browser does not support native JSON methods. + * Note: Native JSON methods will not work with objects that have functions. + * Also, property names must be quoted, otherwise the data will not parse. (Defaults to false) + * @type Boolean + */ + USE_NATIVE_JSON : false, + + /** + * Copies all the properties of config to obj if they don't already exist. + * @param {Object} obj The receiver of the properties + * @param {Object} config The source of the properties + * @return {Object} returns obj + */ + applyIf : function(o, c){ + if(o){ + for(var p in c){ + if(!Ext.isDefined(o[p])){ + o[p] = c[p]; + } + } + } + return o; + }, + + /** + * Generates unique ids. If the element already has an id, it is unchanged + * @param {Mixed} el (optional) The element to generate an id for + * @param {String} prefix (optional) Id prefix (defaults "ext-gen") + * @return {String} The generated Id. + */ + id : function(el, prefix){ + return (el = Ext.getDom(el) || {}).id = el.id || (prefix || "ext-gen") + (++idSeed); + }, + + /** + *

    Extends one class to create a subclass and optionally overrides members with the passed literal. This method + * also adds the function "override()" to the subclass that can be used to override members of the class.

    + * For example, to create a subclass of Ext GridPanel: + *
    
    +MyGridPanel = Ext.extend(Ext.grid.GridPanel, {
    +    constructor: function(config) {
    +
    +//      Create configuration for this Grid.
    +        var store = new Ext.data.Store({...});
    +        var colModel = new Ext.grid.ColumnModel({...});
    +
    +//      Create a new config object containing our computed properties
    +//      *plus* whatever was in the config parameter.
    +        config = Ext.apply({
    +            store: store,
    +            colModel: colModel
    +        }, config);
    +
    +        MyGridPanel.superclass.constructor.call(this, config);
    +
    +//      Your postprocessing here
    +    },
    +
    +    yourMethod: function() {
    +        // etc.
    +    }
    +});
    +
    + * + *

    This function also supports a 3-argument call in which the subclass's constructor is + * passed as an argument. In this form, the parameters are as follows:

    + *
      + *
    • subclass : Function
      The subclass constructor.
    • + *
    • superclass : Function
      The constructor of class being extended
    • + *
    • overrides : Object
      A literal with members which are copied into the subclass's + * prototype, and are therefore shared among all instances of the new class.
    • + *
    + * + * @param {Function} superclass The constructor of class being extended. + * @param {Object} overrides

    A literal with members which are copied into the subclass's + * prototype, and are therefore shared between all instances of the new class.

    + *

    This may contain a special member named constructor. This is used + * to define the constructor of the new class, and is returned. If this property is + * not specified, a constructor is generated and returned which just calls the + * superclass's constructor passing on its parameters.

    + *

    It is essential that you call the superclass constructor in any provided constructor. See example code.

    + * @return {Function} The subclass constructor from the overrides parameter, or a generated one if not provided. + */ + extend : function(){ + // inline overrides + var io = function(o){ + for(var m in o){ + this[m] = o[m]; + } + }; + var oc = Object.prototype.constructor; + + return function(sb, sp, overrides){ + if(Ext.isObject(sp)){ + overrides = sp; + sp = sb; + sb = overrides.constructor != oc ? overrides.constructor : function(){sp.apply(this, arguments);}; + } + var F = function(){}, + sbp, + spp = sp.prototype; + + F.prototype = spp; + sbp = sb.prototype = new F(); + sbp.constructor=sb; + sb.superclass=spp; + if(spp.constructor == oc){ + spp.constructor=sp; + } + sb.override = function(o){ + Ext.override(sb, o); + }; + sbp.superclass = sbp.supr = (function(){ + return spp; + }); + sbp.override = io; + Ext.override(sb, overrides); + sb.extend = function(o){return Ext.extend(sb, o);}; + return sb; + }; + }(), + + /** + * Adds a list of functions to the prototype of an existing class, overwriting any existing methods with the same name. + * Usage:
    
    +Ext.override(MyClass, {
    +    newMethod1: function(){
    +        // etc.
    +    },
    +    newMethod2: function(foo){
    +        // etc.
    +    }
    +});
    +
    + * @param {Object} origclass The class to override + * @param {Object} overrides The list of functions to add to origClass. This should be specified as an object literal + * containing one or more methods. + * @method override + */ + override : function(origclass, overrides){ + if(overrides){ + var p = origclass.prototype; + Ext.apply(p, overrides); + if(Ext.isIE && overrides.hasOwnProperty('toString')){ + p.toString = overrides.toString; + } + } + }, + + /** + * Creates namespaces to be used for scoping variables and classes so that they are not global. + * Specifying the last node of a namespace implicitly creates all other nodes. Usage: + *
    
    +Ext.namespace('Company', 'Company.data');
    +Ext.namespace('Company.data'); // equivalent and preferable to above syntax
    +Company.Widget = function() { ... }
    +Company.data.CustomStore = function(config) { ... }
    +
    + * @param {String} namespace1 + * @param {String} namespace2 + * @param {String} etc + * @return {Object} The namespace object. (If multiple arguments are passed, this will be the last namespace created) + * @method namespace + */ + namespace : function(){ + var o, d; + Ext.each(arguments, function(v) { + d = v.split("."); + o = window[d[0]] = window[d[0]] || {}; + Ext.each(d.slice(1), function(v2){ + o = o[v2] = o[v2] || {}; + }); + }); + return o; + }, + + /** + * Takes an object and converts it to an encoded URL. e.g. Ext.urlEncode({foo: 1, bar: 2}); would return "foo=1&bar=2". Optionally, property values can be arrays, instead of keys and the resulting string that's returned will contain a name/value pair for each array value. + * @param {Object} o + * @param {String} pre (optional) A prefix to add to the url encoded string + * @return {String} + */ + urlEncode : function(o, pre){ + var empty, + buf = [], + e = encodeURIComponent; + + Ext.iterate(o, function(key, item){ + empty = Ext.isEmpty(item); + Ext.each(empty ? key : item, function(val){ + buf.push('&', e(key), '=', (!Ext.isEmpty(val) && (val != key || !empty)) ? (Ext.isDate(val) ? Ext.encode(val).replace(/"/g, '') : e(val)) : ''); + }); + }); + if(!pre){ + buf.shift(); + pre = ''; + } + return pre + buf.join(''); + }, + + /** + * Takes an encoded URL and and converts it to an object. Example:
    
    +Ext.urlDecode("foo=1&bar=2"); // returns {foo: "1", bar: "2"}
    +Ext.urlDecode("foo=1&bar=2&bar=3&bar=4", false); // returns {foo: "1", bar: ["2", "3", "4"]}
    +
    + * @param {String} string + * @param {Boolean} overwrite (optional) Items of the same name will overwrite previous values instead of creating an an array (Defaults to false). + * @return {Object} A literal with members + */ + urlDecode : function(string, overwrite){ + if(Ext.isEmpty(string)){ + return {}; + } + var obj = {}, + pairs = string.split('&'), + d = decodeURIComponent, + name, + value; + Ext.each(pairs, function(pair) { + pair = pair.split('='); + name = d(pair[0]); + value = d(pair[1]); + obj[name] = overwrite || !obj[name] ? value : + [].concat(obj[name]).concat(value); + }); + return obj; + }, + + /** + * Appends content to the query string of a URL, handling logic for whether to place + * a question mark or ampersand. + * @param {String} url The URL to append to. + * @param {String} s The content to append to the URL. + * @return (String) The resulting URL + */ + urlAppend : function(url, s){ + if(!Ext.isEmpty(s)){ + return url + (url.indexOf('?') === -1 ? '?' : '&') + s; + } + return url; + }, + + /** + * Converts any iterable (numeric indices and a length property) into a true array + * Don't use this on strings. IE doesn't support "abc"[0] which this implementation depends on. + * For strings, use this instead: "abc".match(/./g) => [a,b,c]; + * @param {Iterable} the iterable object to be turned into a true Array. + * @return (Array) array + */ + toArray : function(){ + return isIE ? + function(a, i, j, res){ + res = []; + for(var x = 0, len = a.length; x < len; x++) { + res.push(a[x]); + } + return res.slice(i || 0, j || res.length); + } : + function(a, i, j){ + return Array.prototype.slice.call(a, i || 0, j || a.length); + } + }(), + + isIterable : function(v){ + //check for array or arguments + if(Ext.isArray(v) || v.callee){ + return true; + } + //check for node list type + if(/NodeList|HTMLCollection/.test(toString.call(v))){ + return true; + } + //NodeList has an item and length property + //IXMLDOMNodeList has nextNode method, needs to be checked first. + return ((typeof v.nextNode != 'undefined' || v.item) && Ext.isNumber(v.length)); + }, + + /** + * Iterates an array calling the supplied function. + * @param {Array/NodeList/Mixed} array The array to be iterated. If this + * argument is not really an array, the supplied function is called once. + * @param {Function} fn The function to be called with each item. If the + * supplied function returns false, iteration stops and this method returns + * the current index. This function is called with + * the following arguments: + *
      + *
    • item : Mixed + *
      The item at the current index + * in the passed array
    • + *
    • index : Number + *
      The current index within the array
    • + *
    • allItems : Array + *
      The array passed as the first + * argument to Ext.each.
    • + *
    + * @param {Object} scope The scope (this reference) in which the specified function is executed. + * Defaults to the item at the current index + * within the passed array. + * @return See description for the fn parameter. + */ + each : function(array, fn, scope){ + if(Ext.isEmpty(array, true)){ + return; + } + if(!Ext.isIterable(array) || Ext.isPrimitive(array)){ + array = [array]; + } + for(var i = 0, len = array.length; i < len; i++){ + if(fn.call(scope || array[i], array[i], i, array) === false){ + return i; + }; + } + }, + + /** + * Iterates either the elements in an array, or each of the properties in an object. + * Note: If you are only iterating arrays, it is better to call {@link #each}. + * @param {Object/Array} object The object or array to be iterated + * @param {Function} fn The function to be called for each iteration. + * The iteration will stop if the supplied function returns false, or + * all array elements / object properties have been covered. The signature + * varies depending on the type of object being interated: + *
      + *
    • Arrays : (Object item, Number index, Array allItems) + *
      + * When iterating an array, the supplied function is called with each item.
    • + *
    • Objects : (String key, Object value, Object) + *
      + * When iterating an object, the supplied function is called with each key-value pair in + * the object, and the iterated object
    • + *
    + * @param {Object} scope The scope (this reference) in which the specified function is executed. Defaults to + * the object being iterated. + */ + iterate : function(obj, fn, scope){ + if(Ext.isEmpty(obj)){ + return; + } + if(Ext.isIterable(obj)){ + Ext.each(obj, fn, scope); + return; + }else if(Ext.isObject(obj)){ + for(var prop in obj){ + if(obj.hasOwnProperty(prop)){ + if(fn.call(scope || obj, prop, obj[prop], obj) === false){ + return; + }; + } + } + } + }, + + /** + * Return the dom node for the passed String (id), dom node, or Ext.Element. + * Here are some examples: + *
    
    +// gets dom node based on id
    +var elDom = Ext.getDom('elId');
    +// gets dom node based on the dom node
    +var elDom1 = Ext.getDom(elDom);
    +
    +// If we don't know if we are working with an
    +// Ext.Element or a dom node use Ext.getDom
    +function(el){
    +    var dom = Ext.getDom(el);
    +    // do something with the dom node
    +}
    +         * 
    + * Note: the dom node to be found actually needs to exist (be rendered, etc) + * when this method is called to be successful. + * @param {Mixed} el + * @return HTMLElement + */ + getDom : function(el){ + if(!el || !DOC){ + return null; + } + return el.dom ? el.dom : (Ext.isString(el) ? DOC.getElementById(el) : el); + }, + + /** + * Returns the current document body as an {@link Ext.Element}. + * @return Ext.Element The document body + */ + getBody : function(){ + return Ext.get(DOC.body || DOC.documentElement); + }, + + /** + * Removes a DOM node from the document. + */ + /** + *

    Removes this element from the document, removes all DOM event listeners, and deletes the cache reference. + * All DOM event listeners are removed from this element. If {@link Ext#enableNestedListenerRemoval} is + * true, then DOM event listeners are also removed from all child nodes. The body node + * will be ignored if passed in.

    + * @param {HTMLElement} node The node to remove + */ + removeNode : isIE && !isIE8 ? function(){ + var d; + return function(n){ + if(n && n.tagName != 'BODY'){ + (Ext.enableNestedListenerRemoval) ? Ext.EventManager.purgeElement(n, true) : Ext.EventManager.removeAll(n); + d = d || DOC.createElement('div'); + d.appendChild(n); + d.innerHTML = ''; + delete Ext.elCache[n.id]; + } + } + }() : function(n){ + if(n && n.parentNode && n.tagName != 'BODY'){ + (Ext.enableNestedListenerRemoval) ? Ext.EventManager.purgeElement(n, true) : Ext.EventManager.removeAll(n); + n.parentNode.removeChild(n); + delete Ext.elCache[n.id]; + } + }, + + /** + *

    Returns true if the passed value is empty.

    + *

    The value is deemed to be empty if it is

      + *
    • null
    • + *
    • undefined
    • + *
    • an empty array
    • + *
    • a zero length string (Unless the allowBlank parameter is true)
    • + *
    + * @param {Mixed} value The value to test + * @param {Boolean} allowBlank (optional) true to allow empty strings (defaults to false) + * @return {Boolean} + */ + isEmpty : function(v, allowBlank){ + return v === null || v === undefined || ((Ext.isArray(v) && !v.length)) || (!allowBlank ? v === '' : false); + }, + + /** + * Returns true if the passed value is a JavaScript array, otherwise false. + * @param {Mixed} value The value to test + * @return {Boolean} + */ + isArray : function(v){ + return toString.apply(v) === '[object Array]'; + }, + + /** + * Returns true if the passed object is a JavaScript date object, otherwise false. + * @param {Object} object The object to test + * @return {Boolean} + */ + isDate : function(v){ + return toString.apply(v) === '[object Date]'; + }, + + /** + * Returns true if the passed value is a JavaScript Object, otherwise false. + * @param {Mixed} value The value to test + * @return {Boolean} + */ + isObject : function(v){ + return !!v && Object.prototype.toString.call(v) === '[object Object]'; + }, + + /** + * Returns true if the passed value is a JavaScript 'primitive', a string, number or boolean. + * @param {Mixed} value The value to test + * @return {Boolean} + */ + isPrimitive : function(v){ + return Ext.isString(v) || Ext.isNumber(v) || Ext.isBoolean(v); + }, + + /** + * Returns true if the passed value is a JavaScript Function, otherwise false. + * @param {Mixed} value The value to test + * @return {Boolean} + */ + isFunction : function(v){ + return toString.apply(v) === '[object Function]'; + }, + + /** + * Returns true if the passed value is a number. Returns false for non-finite numbers. + * @param {Mixed} value The value to test + * @return {Boolean} + */ + isNumber : function(v){ + return typeof v === 'number' && isFinite(v); + }, + + /** + * Returns true if the passed value is a string. + * @param {Mixed} value The value to test + * @return {Boolean} + */ + isString : function(v){ + return typeof v === 'string'; + }, + + /** + * Returns true if the passed value is a boolean. + * @param {Mixed} value The value to test + * @return {Boolean} + */ + isBoolean : function(v){ + return typeof v === 'boolean'; + }, + + /** + * Returns true if the passed value is an HTMLElement + * @param {Mixed} value The value to test + * @return {Boolean} + */ + isElement : function(v) { + return !!v && v.tagName; + }, + + /** + * Returns true if the passed value is not undefined. + * @param {Mixed} value The value to test + * @return {Boolean} + */ + isDefined : function(v){ + return typeof v !== 'undefined'; + }, + + /** + * True if the detected browser is Opera. + * @type Boolean + */ + isOpera : isOpera, + /** + * True if the detected browser uses WebKit. + * @type Boolean + */ + isWebKit : isWebKit, + /** + * True if the detected browser is Chrome. + * @type Boolean + */ + isChrome : isChrome, + /** + * True if the detected browser is Safari. + * @type Boolean + */ + isSafari : isSafari, + /** + * True if the detected browser is Safari 3.x. + * @type Boolean + */ + isSafari3 : isSafari3, + /** + * True if the detected browser is Safari 4.x. + * @type Boolean + */ + isSafari4 : isSafari4, + /** + * True if the detected browser is Safari 2.x. + * @type Boolean + */ + isSafari2 : isSafari2, + /** + * True if the detected browser is Internet Explorer. + * @type Boolean + */ + isIE : isIE, + /** + * True if the detected browser is Internet Explorer 6.x. + * @type Boolean + */ + isIE6 : isIE6, + /** + * True if the detected browser is Internet Explorer 7.x. + * @type Boolean + */ + isIE7 : isIE7, + /** + * True if the detected browser is Internet Explorer 8.x. + * @type Boolean + */ + isIE8 : isIE8, + /** + * True if the detected browser uses the Gecko layout engine (e.g. Mozilla, Firefox). + * @type Boolean + */ + isGecko : isGecko, + /** + * True if the detected browser uses a pre-Gecko 1.9 layout engine (e.g. Firefox 2.x). + * @type Boolean + */ + isGecko2 : isGecko2, + /** + * True if the detected browser uses a Gecko 1.9+ layout engine (e.g. Firefox 3.x). + * @type Boolean + */ + isGecko3 : isGecko3, + /** + * True if the detected browser is Internet Explorer running in non-strict mode. + * @type Boolean + */ + isBorderBox : isBorderBox, + /** + * True if the detected platform is Linux. + * @type Boolean + */ + isLinux : isLinux, + /** + * True if the detected platform is Windows. + * @type Boolean + */ + isWindows : isWindows, + /** + * True if the detected platform is Mac OS. + * @type Boolean + */ + isMac : isMac, + /** + * True if the detected platform is Adobe Air. + * @type Boolean + */ + isAir : isAir + }); + + /** + * Creates namespaces to be used for scoping variables and classes so that they are not global. + * Specifying the last node of a namespace implicitly creates all other nodes. Usage: + *
    
    +Ext.namespace('Company', 'Company.data');
    +Ext.namespace('Company.data'); // equivalent and preferable to above syntax
    +Company.Widget = function() { ... }
    +Company.data.CustomStore = function(config) { ... }
    +
    + * @param {String} namespace1 + * @param {String} namespace2 + * @param {String} etc + * @return {Object} The namespace object. (If multiple arguments are passed, this will be the last namespace created) + * @method ns + */ + Ext.ns = Ext.namespace; +})(); + +Ext.ns("Ext.util", "Ext.lib", "Ext.data"); + +Ext.elCache = {}; + +/** + * @class Function + * These functions are available on every Function object (any JavaScript function). + */ +Ext.apply(Function.prototype, { + /** + * Creates an interceptor function. The passed function is called before the original one. If it returns false, + * the original one is not called. The resulting function returns the results of the original function. + * The passed function is called with the parameters of the original function. Example usage: + *
    
    +var sayHi = function(name){
    +    alert('Hi, ' + name);
    +}
    +
    +sayHi('Fred'); // alerts "Hi, Fred"
    +
    +// create a new function that validates input without
    +// directly modifying the original function:
    +var sayHiToFriend = sayHi.createInterceptor(function(name){
    +    return name == 'Brian';
    +});
    +
    +sayHiToFriend('Fred');  // no alert
    +sayHiToFriend('Brian'); // alerts "Hi, Brian"
    +
    + * @param {Function} fcn 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 + */ + createInterceptor : function(fcn, scope){ + var method = this; + return !Ext.isFunction(fcn) ? + this : + function() { + var me = this, + args = arguments; + fcn.target = me; + fcn.method = method; + return (fcn.apply(scope || me || window, args) !== false) ? + method.apply(me || window, args) : + null; + }; + }, + + /** + * Creates a callback that passes arguments[0], arguments[1], arguments[2], ... + * Call directly on any function. Example: myFunction.createCallback(arg1, arg2) + * Will create a function that is bound to those 2 args. If a specific scope is required in the + * callback, use {@link #createDelegate} instead. The function returned by createCallback always + * executes in the window scope. + *

    This method is required when you want to pass arguments to a callback function. If no arguments + * are needed, you can simply pass a reference to the function as a callback (e.g., callback: myFn). + * However, if you tried to pass a function with arguments (e.g., callback: myFn(arg1, arg2)) the function + * would simply execute immediately when the code is parsed. Example usage: + *

    
    +var sayHi = function(name){
    +    alert('Hi, ' + name);
    +}
    +
    +// clicking the button alerts "Hi, Fred"
    +new Ext.Button({
    +    text: 'Say Hi',
    +    renderTo: Ext.getBody(),
    +    handler: sayHi.createCallback('Fred')
    +});
    +
    + * @return {Function} The new function + */ + createCallback : function(/*args...*/){ + // make args available, in function below + var args = arguments, + method = this; + return function() { + return method.apply(window, args); + }; + }, + + /** + * Creates a delegate (callback) that sets the scope to obj. + * Call directly on any function. Example: this.myFunction.createDelegate(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.');
    +}
    +
    +var btn = new Ext.Button({
    +    text: 'Say Hi',
    +    renderTo: Ext.getBody()
    +});
    +
    +// This callback will execute in the scope of the
    +// button instance. Clicking the button alerts
    +// "Hi, Fred. You clicked the "Say Hi" button."
    +btn.on('click', sayHi.createDelegate(btn, ['Fred']));
    +
    + * @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(obj, args, appendArgs){ + var method = this; + return function() { + var callArgs = args || arguments; + if (appendArgs === true){ + callArgs = Array.prototype.slice.call(arguments, 0); + callArgs = callArgs.concat(args); + }else if (Ext.isNumber(appendArgs)){ + callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first + var applyArgs = [appendArgs, 0].concat(args); // create method call params + Array.prototype.splice.apply(callArgs, applyArgs); // splice them in + } + return method.apply(obj || window, callArgs); + }; + }, + + /** + * Calls this function after the number of millseconds specified, optionally in a specific scope. Example usage: + *
    
    +var sayHi = function(name){
    +    alert('Hi, ' + name);
    +}
    +
    +// executes immediately:
    +sayHi('Fred');
    +
    +// executes after 2 seconds:
    +sayHi.defer(2000, this, ['Fred']);
    +
    +// this syntax is sometimes useful for deferring
    +// execution of an anonymous function:
    +(function(){
    +    alert('Anonymous');
    +}).defer(100);
    +
    + * @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 + */ + defer : function(millis, obj, args, appendArgs){ + var fn = this.createDelegate(obj, args, appendArgs); + if(millis > 0){ + return setTimeout(fn, millis); + } + fn(); + return 0; + } +}); + +/** + * @class String + * These functions are available on every String object. + */ +Ext.applyIf(String, { + /** + * Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens. Each + * token must be unique, and must increment in the format {0}, {1}, etc. Example usage: + *
    
    +var cls = 'my-class', text = 'Some text';
    +var s = String.format('<div class="{0}">{1}</div>', cls, text);
    +// s now contains the string: '<div class="my-class">Some text</div>'
    +     * 
    + * @param {String} string The tokenized string to be formatted + * @param {String} value1 The value to replace token {0} + * @param {String} value2 Etc... + * @return {String} The formatted string + * @static + */ + format : function(format){ + var args = Ext.toArray(arguments, 1); + return format.replace(/\{(\d+)\}/g, function(m, i){ + return args[i]; + }); + } +}); + +/** + * @class Array + */ +Ext.applyIf(Array.prototype, { + /** + * Checks whether or not the specified object exists in the array. + * @param {Object} o The object to check for + * @param {Number} from (Optional) The index at which to begin the search + * @return {Number} The index of o in the array (or -1 if it is not found) + */ + indexOf : function(o, from){ + var len = this.length; + from = from || 0; + from += (from < 0) ? len : 0; + for (; from < len; ++from){ + if(this[from] === o){ + return from; + } + } + return -1; + }, + + /** + * Removes the specified object from the array. If the object is not found nothing happens. + * @param {Object} o The object to remove + * @return {Array} this array + */ + remove : function(o){ + var index = this.indexOf(o); + if(index != -1){ + this.splice(index, 1); + } + return this; + } +}); +/** + * @class Ext.util.TaskRunner + * Provides the ability to execute one or more arbitrary tasks in a multithreaded + * manner. Generally, you can use the singleton {@link Ext.TaskMgr} instead, but + * if needed, you can create separate instances of TaskRunner. Any number of + * separate tasks can be started at any time and will run independently of each + * other. Example usage: + *
    
    +// Start a simple clock task that updates a div once per second
    +var updateClock = function(){
    +    Ext.fly('clock').update(new Date().format('g:i:s A'));
    +} 
    +var task = {
    +    run: updateClock,
    +    interval: 1000 //1 second
    +}
    +var runner = new Ext.util.TaskRunner();
    +runner.start(task);
    +
    +// equivalent using TaskMgr
    +Ext.TaskMgr.start({
    +    run: updateClock,
    +    interval: 1000
    +});
    +
    + * 
    + * Also see {@link Ext.util.DelayedTask}. + * + * @constructor + * @param {Number} interval (optional) The minimum precision in milliseconds supported by this TaskRunner instance + * (defaults to 10) + */ +Ext.util.TaskRunner = function(interval){ + interval = interval || 10; + var tasks = [], + removeQueue = [], + id = 0, + running = false, + + // private + stopThread = function(){ + running = false; + clearInterval(id); + id = 0; + }, + + // private + startThread = function(){ + if(!running){ + running = true; + id = setInterval(runTasks, interval); + } + }, + + // private + removeTask = function(t){ + removeQueue.push(t); + if(t.onStop){ + t.onStop.apply(t.scope || t); + } + }, + + // private + runTasks = function(){ + var rqLen = removeQueue.length, + now = new Date().getTime(); + + if(rqLen > 0){ + for(var i = 0; i < rqLen; i++){ + tasks.remove(removeQueue[i]); + } + removeQueue = []; + if(tasks.length < 1){ + stopThread(); + return; + } + } + for(var i = 0, t, itime, rt, len = tasks.length; i < len; ++i){ + t = tasks[i]; + itime = now - t.taskRunTime; + if(t.interval <= itime){ + rt = t.run.apply(t.scope || t, t.args || [++t.taskRunCount]); + t.taskRunTime = now; + if(rt === false || t.taskRunCount === t.repeat){ + removeTask(t); + return; + } + } + if(t.duration && t.duration <= (now - t.taskStartTime)){ + removeTask(t); + } + } + }; + + /** + * Starts a new task. + * @method start + * @param {Object} task A config object that supports the following properties:
      + *
    • run : Function
      The function to execute each time the task is run. The + * function will be called at each interval and passed the args argument if specified. If a + * particular scope is required, be sure to specify it using the scope argument.
    • + *
    • interval : Number
      The frequency in milliseconds with which the task + * should be executed.
    • + *
    • args : Array
      (optional) An array of arguments to be passed to the function + * specified by run.
    • + *
    • scope : Object
      (optional) The scope (this reference) in which to execute the + * run function. Defaults to the task config object.
    • + *
    • duration : Number
      (optional) The length of time in milliseconds to execute + * the task before stopping automatically (defaults to indefinite).
    • + *
    • repeat : Number
      (optional) The number of times to execute the task before + * stopping automatically (defaults to indefinite).
    • + *
    + * @return {Object} The task + */ + this.start = function(task){ + tasks.push(task); + task.taskStartTime = new Date().getTime(); + task.taskRunTime = 0; + task.taskRunCount = 0; + startThread(); + return task; + }; + + /** + * Stops an existing running task. + * @method stop + * @param {Object} task The task to stop + * @return {Object} The task + */ + this.stop = function(task){ + removeTask(task); + return task; + }; + + /** + * Stops all tasks that are currently running. + * @method stopAll + */ + this.stopAll = function(){ + stopThread(); + for(var i = 0, len = tasks.length; i < len; i++){ + if(tasks[i].onStop){ + tasks[i].onStop(); + } + } + tasks = []; + removeQueue = []; + }; +}; + +/** + * @class Ext.TaskMgr + * @extends Ext.util.TaskRunner + * A static {@link Ext.util.TaskRunner} instance that can be used to start and stop arbitrary tasks. See + * {@link Ext.util.TaskRunner} for supported methods and task config properties. + *
    
    +// Start a simple clock task that updates a div once per second
    +var task = {
    +    run: function(){
    +        Ext.fly('clock').update(new Date().format('g:i:s A'));
    +    },
    +    interval: 1000 //1 second
    +}
    +Ext.TaskMgr.start(task);
    +
    + * @singleton + */ +Ext.TaskMgr = new Ext.util.TaskRunner();/** + * @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); + }; + + /** + * Cancel the last queued timeout + */ + me.cancel = function(){ + if(id){ + clearInterval(id); + id = null; + } + }; +};(function(){ + var libFlyweight; + + function fly(el) { + if (!libFlyweight) { + libFlyweight = new Ext.Element.Flyweight(); + } + libFlyweight.dom = el; + return libFlyweight; + } + + (function(){ + var doc = document, + isCSS1 = doc.compatMode == "CSS1Compat", + MAX = Math.max, + ROUND = Math.round, + PARSEINT = parseInt; + + Ext.lib.Dom = { + isAncestor : function(p, c) { + var ret = false; + + p = Ext.getDom(p); + c = Ext.getDom(c); + if (p && c) { + if (p.contains) { + return p.contains(c); + } else if (p.compareDocumentPosition) { + return !!(p.compareDocumentPosition(c) & 16); + } else { + while (c = c.parentNode) { + ret = c == p || ret; + } + } + } + return ret; + }, + + getViewWidth : function(full) { + return full ? this.getDocumentWidth() : this.getViewportWidth(); + }, + + getViewHeight : function(full) { + return full ? this.getDocumentHeight() : this.getViewportHeight(); + }, + + getDocumentHeight: function() { + return MAX(!isCSS1 ? doc.body.scrollHeight : doc.documentElement.scrollHeight, this.getViewportHeight()); + }, + + getDocumentWidth: function() { + return MAX(!isCSS1 ? doc.body.scrollWidth : doc.documentElement.scrollWidth, this.getViewportWidth()); + }, + + getViewportHeight: function(){ + return Ext.isIE ? + (Ext.isStrict ? doc.documentElement.clientHeight : doc.body.clientHeight) : + self.innerHeight; + }, + + getViewportWidth : function() { + return !Ext.isStrict && !Ext.isOpera ? doc.body.clientWidth : + Ext.isIE ? doc.documentElement.clientWidth : self.innerWidth; + }, + + getY : function(el) { + return this.getXY(el)[1]; + }, + + getX : function(el) { + return this.getXY(el)[0]; + }, + + getXY : function(el) { + var p, + pe, + b, + bt, + bl, + dbd, + x = 0, + y = 0, + scroll, + hasAbsolute, + bd = (doc.body || doc.documentElement), + ret = [0,0]; + + el = Ext.getDom(el); + + if(el != bd){ + if (el.getBoundingClientRect) { + b = el.getBoundingClientRect(); + scroll = fly(document).getScroll(); + ret = [ROUND(b.left + scroll.left), ROUND(b.top + scroll.top)]; + } else { + p = el; + hasAbsolute = fly(el).isStyle("position", "absolute"); + + while (p) { + pe = fly(p); + x += p.offsetLeft; + y += p.offsetTop; + + hasAbsolute = hasAbsolute || pe.isStyle("position", "absolute"); + + if (Ext.isGecko) { + y += bt = PARSEINT(pe.getStyle("borderTopWidth"), 10) || 0; + x += bl = PARSEINT(pe.getStyle("borderLeftWidth"), 10) || 0; + + if (p != el && !pe.isStyle('overflow','visible')) { + x += bl; + y += bt; + } + } + p = p.offsetParent; + } + + if (Ext.isSafari && hasAbsolute) { + x -= bd.offsetLeft; + y -= bd.offsetTop; + } + + if (Ext.isGecko && !hasAbsolute) { + dbd = fly(bd); + x += PARSEINT(dbd.getStyle("borderLeftWidth"), 10) || 0; + y += PARSEINT(dbd.getStyle("borderTopWidth"), 10) || 0; + } + + p = el.parentNode; + while (p && p != bd) { + if (!Ext.isOpera || (p.tagName != 'TR' && !fly(p).isStyle("display", "inline"))) { + x -= p.scrollLeft; + y -= p.scrollTop; + } + p = p.parentNode; + } + ret = [x,y]; + } + } + return ret + }, + + setXY : function(el, xy) { + (el = Ext.fly(el, '_setXY')).position(); + + var pts = el.translatePoints(xy), + style = el.dom.style, + pos; + + for (pos in pts) { + if(!isNaN(pts[pos])) style[pos] = pts[pos] + "px" + } + }, + + setX : function(el, x) { + this.setXY(el, [x, false]); + }, + + setY : function(el, y) { + this.setXY(el, [false, y]); + } + }; +})();Ext.lib.Event = function() { + var loadComplete = false, + unloadListeners = {}, + retryCount = 0, + onAvailStack = [], + _interval, + locked = false, + win = window, + doc = document, + + // constants + POLL_RETRYS = 200, + POLL_INTERVAL = 20, + EL = 0, + TYPE = 0, + FN = 1, + WFN = 2, + OBJ = 2, + ADJ_SCOPE = 3, + SCROLLLEFT = 'scrollLeft', + SCROLLTOP = 'scrollTop', + UNLOAD = 'unload', + MOUSEOVER = 'mouseover', + MOUSEOUT = 'mouseout', + // private + doAdd = function() { + var ret; + if (win.addEventListener) { + ret = function(el, eventName, fn, capture) { + if (eventName == 'mouseenter') { + fn = fn.createInterceptor(checkRelatedTarget); + el.addEventListener(MOUSEOVER, fn, (capture)); + } else if (eventName == 'mouseleave') { + fn = fn.createInterceptor(checkRelatedTarget); + el.addEventListener(MOUSEOUT, fn, (capture)); + } else { + el.addEventListener(eventName, fn, (capture)); + } + return fn; + }; + } else if (win.attachEvent) { + ret = function(el, eventName, fn, capture) { + el.attachEvent("on" + eventName, fn); + return fn; + }; + } else { + ret = function(){}; + } + return ret; + }(), + // private + doRemove = function(){ + var ret; + if (win.removeEventListener) { + ret = function (el, eventName, fn, capture) { + if (eventName == 'mouseenter') { + eventName = MOUSEOVER; + } else if (eventName == 'mouseleave') { + eventName = MOUSEOUT; + } + el.removeEventListener(eventName, fn, (capture)); + }; + } else if (win.detachEvent) { + ret = function (el, eventName, fn) { + el.detachEvent("on" + eventName, fn); + }; + } else { + ret = function(){}; + } + return ret; + }(); + + function checkRelatedTarget(e) { + return !elContains(e.currentTarget, pub.getRelatedTarget(e)); + } + + function elContains(parent, child) { + if(parent && parent.firstChild){ + while(child) { + if(child === parent) { + return true; + } + child = child.parentNode; + if(child && (child.nodeType != 1)) { + child = null; + } + } + } + return false; + } + + // private + function _tryPreloadAttach() { + var ret = false, + notAvail = [], + element, i, len, v, + tryAgain = !loadComplete || (retryCount > 0); + + if (!locked) { + locked = true; + + for (i = 0, len = onAvailStack.length; i < len; i++) { + v = onAvailStack[i]; + if(v && (element = doc.getElementById(v.id))){ + if(!v.checkReady || loadComplete || element.nextSibling || (doc && doc.body)) { + element = v.override ? (v.override === true ? v.obj : v.override) : element; + v.fn.call(element, v.obj); + onAvailStack.remove(v); + } else { + notAvail.push(v); + } + } + } + + retryCount = (notAvail.length === 0) ? 0 : retryCount - 1; + + if (tryAgain) { + startInterval(); + } else { + clearInterval(_interval); + _interval = null; + } + + ret = !(locked = false); + } + return ret; + } + + // private + function startInterval() { + if(!_interval){ + var callback = function() { + _tryPreloadAttach(); + }; + _interval = setInterval(callback, POLL_INTERVAL); + } + } + + // private + function getScroll() { + var dd = doc.documentElement, + db = doc.body; + if(dd && (dd[SCROLLTOP] || dd[SCROLLLEFT])){ + return [dd[SCROLLLEFT], dd[SCROLLTOP]]; + }else if(db){ + return [db[SCROLLLEFT], db[SCROLLTOP]]; + }else{ + return [0, 0]; + } + } + + // private + function getPageCoord (ev, xy) { + ev = ev.browserEvent || ev; + var coord = ev['page' + xy]; + if (!coord && coord !== 0) { + coord = ev['client' + xy] || 0; + + if (Ext.isIE) { + coord += getScroll()[xy == "X" ? 0 : 1]; + } + } + + return coord; + } + + var pub = { + extAdapter: true, + onAvailable : function(p_id, p_fn, p_obj, p_override) { + onAvailStack.push({ + id: p_id, + fn: p_fn, + obj: p_obj, + override: p_override, + checkReady: false }); + + retryCount = POLL_RETRYS; + startInterval(); + }, + + // This function should ALWAYS be called from Ext.EventManager + addListener: function(el, eventName, fn) { + el = Ext.getDom(el); + if (el && fn) { + if (eventName == UNLOAD) { + if (unloadListeners[el.id] === undefined) { + unloadListeners[el.id] = []; + } + unloadListeners[el.id].push([eventName, fn]); + return fn; + } + return doAdd(el, eventName, fn, false); + } + return false; + }, + + // This function should ALWAYS be called from Ext.EventManager + removeListener: function(el, eventName, fn) { + el = Ext.getDom(el); + var i, len, li, lis; + if (el && fn) { + if(eventName == UNLOAD){ + if((lis = unloadListeners[el.id]) !== undefined){ + for(i = 0, len = lis.length; i < len; i++){ + if((li = lis[i]) && li[TYPE] == eventName && li[FN] == fn){ + unloadListeners[id].splice(i, 1); + } + } + } + return; + } + doRemove(el, eventName, fn, false); + } + }, + + getTarget : function(ev) { + ev = ev.browserEvent || ev; + return this.resolveTextNode(ev.target || ev.srcElement); + }, + + resolveTextNode : Ext.isGecko ? function(node){ + if(!node){ + return; + } + // work around firefox bug, https://bugzilla.mozilla.org/show_bug.cgi?id=101197 + var s = HTMLElement.prototype.toString.call(node); + if(s == '[xpconnect wrapped native prototype]' || s == '[object XULElement]'){ + return; + } + return node.nodeType == 3 ? node.parentNode : node; + } : function(node){ + return node && node.nodeType == 3 ? node.parentNode : node; + }, + + getRelatedTarget : function(ev) { + ev = ev.browserEvent || ev; + return this.resolveTextNode(ev.relatedTarget || + (ev.type == MOUSEOUT ? ev.toElement : + ev.type == MOUSEOVER ? ev.fromElement : null)); + }, + + getPageX : function(ev) { + return getPageCoord(ev, "X"); + }, + + getPageY : function(ev) { + return getPageCoord(ev, "Y"); + }, + + + getXY : function(ev) { + return [this.getPageX(ev), this.getPageY(ev)]; + }, + + stopEvent : function(ev) { + this.stopPropagation(ev); + this.preventDefault(ev); + }, + + stopPropagation : function(ev) { + ev = ev.browserEvent || ev; + if (ev.stopPropagation) { + ev.stopPropagation(); + } else { + ev.cancelBubble = true; + } + }, + + preventDefault : function(ev) { + ev = ev.browserEvent || ev; + if (ev.preventDefault) { + ev.preventDefault(); + } else { + ev.returnValue = false; + } + }, + + getEvent : function(e) { + e = e || win.event; + if (!e) { + var c = this.getEvent.caller; + while (c) { + e = c.arguments[0]; + if (e && Event == e.constructor) { + break; + } + c = c.caller; + } + } + return e; + }, + + getCharCode : function(ev) { + ev = ev.browserEvent || ev; + return ev.charCode || ev.keyCode || 0; + }, + + //clearCache: function() {}, + // deprecated, call from EventManager + getListeners : function(el, eventName) { + Ext.EventManager.getListeners(el, eventName); + }, + + // deprecated, call from EventManager + purgeElement : function(el, recurse, eventName) { + Ext.EventManager.purgeElement(el, recurse, eventName); + }, + + _load : function(e) { + loadComplete = true; + var EU = Ext.lib.Event; + if (Ext.isIE && e !== true) { + // IE8 complains that _load is null or not an object + // so lets remove self via arguments.callee + doRemove(win, "load", arguments.callee); + } + }, + + _unload : function(e) { + var EU = Ext.lib.Event, + i, j, l, v, ul, id, len, index, scope; + + + for (id in unloadListeners) { + ul = unloadListeners[id]; + for (i = 0, len = ul.length; i < len; i++) { + v = ul[i]; + if (v) { + try{ + scope = v[ADJ_SCOPE] ? (v[ADJ_SCOPE] === true ? v[OBJ] : v[ADJ_SCOPE]) : win; + v[FN].call(scope, EU.getEvent(e), v[OBJ]); + }catch(ex){} + } + } + }; + + unloadListeners = null; + Ext.EventManager._unload(); + + doRemove(win, UNLOAD, EU._unload); + } + }; + + // Initialize stuff. + pub.on = pub.addListener; + pub.un = pub.removeListener; + if (doc && doc.body) { + pub._load(true); + } else { + doAdd(win, "load", pub._load); + } + doAdd(win, UNLOAD, pub._unload); + _tryPreloadAttach(); + + return pub; +}(); +/* +* Portions of this file are based on pieces of Yahoo User Interface Library +* Copyright (c) 2007, Yahoo! Inc. All rights reserved. +* YUI licensed under the BSD License: +* http://developer.yahoo.net/yui/license.txt +*/ +Ext.lib.Ajax = function() { + var activeX = ['MSXML2.XMLHTTP.3.0', + 'MSXML2.XMLHTTP', + 'Microsoft.XMLHTTP'], + CONTENTTYPE = 'Content-Type'; + + // private + function setHeader(o) { + var conn = o.conn, + prop; + + function setTheHeaders(conn, headers){ + for (prop in headers) { + if (headers.hasOwnProperty(prop)) { + conn.setRequestHeader(prop, headers[prop]); + } + } + } + + if (pub.defaultHeaders) { + setTheHeaders(conn, pub.defaultHeaders); + } + + if (pub.headers) { + setTheHeaders(conn, pub.headers); + delete pub.headers; + } + } + + // private + function createExceptionObject(tId, callbackArg, isAbort, isTimeout) { + return { + tId : tId, + status : isAbort ? -1 : 0, + statusText : isAbort ? 'transaction aborted' : 'communication failure', + isAbort: isAbort, + isTimeout: isTimeout, + argument : callbackArg + }; + } + + // private + function initHeader(label, value) { + (pub.headers = pub.headers || {})[label] = value; + } + + // private + function createResponseObject(o, callbackArg) { + var headerObj = {}, + headerStr, + conn = o.conn, + t, + s; + + try { + headerStr = o.conn.getAllResponseHeaders(); + Ext.each(headerStr.replace(/\r\n/g, '\n').split('\n'), function(v){ + t = v.indexOf(':'); + if(t >= 0){ + s = v.substr(0, t).toLowerCase(); + if(v.charAt(t + 1) == ' '){ + ++t; + } + headerObj[s] = v.substr(t + 1); + } + }); + } catch(e) {} + + return { + tId : o.tId, + status : conn.status, + statusText : conn.statusText, + getResponseHeader : function(header){return headerObj[header.toLowerCase()];}, + getAllResponseHeaders : function(){return headerStr}, + responseText : conn.responseText, + responseXML : conn.responseXML, + argument : callbackArg + }; + } + + // private + function releaseObject(o) { + o.conn = null; + o = null; + } + + // private + function handleTransactionResponse(o, callback, isAbort, isTimeout) { + if (!callback) { + releaseObject(o); + return; + } + + var httpStatus, responseObject; + + try { + if (o.conn.status !== undefined && o.conn.status != 0) { + httpStatus = o.conn.status; + } + else { + httpStatus = 13030; + } + } + catch(e) { + httpStatus = 13030; + } + + if ((httpStatus >= 200 && httpStatus < 300) || (Ext.isIE && httpStatus == 1223)) { + responseObject = createResponseObject(o, callback.argument); + if (callback.success) { + if (!callback.scope) { + callback.success(responseObject); + } + else { + callback.success.apply(callback.scope, [responseObject]); + } + } + } + else { + switch (httpStatus) { + case 12002: + case 12029: + case 12030: + case 12031: + case 12152: + case 13030: + responseObject = createExceptionObject(o.tId, callback.argument, (isAbort ? isAbort : false), isTimeout); + if (callback.failure) { + if (!callback.scope) { + callback.failure(responseObject); + } + else { + callback.failure.apply(callback.scope, [responseObject]); + } + } + break; + default: + responseObject = createResponseObject(o, callback.argument); + if (callback.failure) { + if (!callback.scope) { + callback.failure(responseObject); + } + else { + callback.failure.apply(callback.scope, [responseObject]); + } + } + } + } + + releaseObject(o); + responseObject = null; + } + + // private + function handleReadyState(o, callback){ + callback = callback || {}; + var conn = o.conn, + tId = o.tId, + poll = pub.poll, + cbTimeout = callback.timeout || null; + + if (cbTimeout) { + pub.timeout[tId] = setTimeout(function() { + pub.abort(o, callback, true); + }, cbTimeout); + } + + poll[tId] = setInterval( + function() { + if (conn && conn.readyState == 4) { + clearInterval(poll[tId]); + poll[tId] = null; + + if (cbTimeout) { + clearTimeout(pub.timeout[tId]); + pub.timeout[tId] = null; + } + + handleTransactionResponse(o, callback); + } + }, + pub.pollInterval); + } + + // private + function asyncRequest(method, uri, callback, postData) { + var o = getConnectionObject() || null; + + if (o) { + o.conn.open(method, uri, true); + + if (pub.useDefaultXhrHeader) { + initHeader('X-Requested-With', pub.defaultXhrHeader); + } + + if(postData && pub.useDefaultHeader && (!pub.headers || !pub.headers[CONTENTTYPE])){ + initHeader(CONTENTTYPE, pub.defaultPostHeader); + } + + if (pub.defaultHeaders || pub.headers) { + setHeader(o); + } + + handleReadyState(o, callback); + o.conn.send(postData || null); + } + return o; + } + + // private + function getConnectionObject() { + var o; + + try { + if (o = createXhrObject(pub.transactionId)) { + pub.transactionId++; + } + } catch(e) { + } finally { + return o; + } + } + + // private + function createXhrObject(transactionId) { + var http; + + try { + http = new XMLHttpRequest(); + } catch(e) { + for (var i = 0; i < activeX.length; ++i) { + try { + http = new ActiveXObject(activeX[i]); + break; + } catch(e) {} + } + } finally { + return {conn : http, tId : transactionId}; + } + } + + var pub = { + request : function(method, uri, cb, data, options) { + if(options){ + var me = this, + xmlData = options.xmlData, + jsonData = options.jsonData, + hs; + + Ext.applyIf(me, options); + + if(xmlData || jsonData){ + hs = me.headers; + if(!hs || !hs[CONTENTTYPE]){ + initHeader(CONTENTTYPE, xmlData ? 'text/xml' : 'application/json'); + } + data = xmlData || (!Ext.isPrimitive(jsonData) ? Ext.encode(jsonData) : jsonData); + } + } + return asyncRequest(method || options.method || "POST", uri, cb, data); + }, + + serializeForm : function(form) { + var fElements = form.elements || (document.forms[form] || Ext.getDom(form)).elements, + hasSubmit = false, + encoder = encodeURIComponent, + element, + options, + name, + val, + data = '', + type; + + Ext.each(fElements, function(element) { + name = element.name; + type = element.type; + + if (!element.disabled && name){ + if(/select-(one|multiple)/i.test(type)) { + Ext.each(element.options, function(opt) { + if (opt.selected) { + data += String.format("{0}={1}&", encoder(name), encoder((opt.hasAttribute ? opt.hasAttribute('value') : opt.getAttribute('value') !== null) ? opt.value : opt.text)); + } + }); + } else if(!/file|undefined|reset|button/i.test(type)) { + if(!(/radio|checkbox/i.test(type) && !element.checked) && !(type == 'submit' && hasSubmit)){ + + data += encoder(name) + '=' + encoder(element.value) + '&'; + hasSubmit = /submit/i.test(type); + } + } + } + }); + return data.substr(0, data.length - 1); + }, + + useDefaultHeader : true, + defaultPostHeader : 'application/x-www-form-urlencoded; charset=UTF-8', + useDefaultXhrHeader : true, + defaultXhrHeader : 'XMLHttpRequest', + poll : {}, + timeout : {}, + pollInterval : 50, + transactionId : 0, + +// This is never called - Is it worth exposing this? +// setProgId : function(id) { +// activeX.unshift(id); +// }, + +// This is never called - Is it worth exposing this? +// setDefaultPostHeader : function(b) { +// this.useDefaultHeader = b; +// }, + +// This is never called - Is it worth exposing this? +// setDefaultXhrHeader : function(b) { +// this.useDefaultXhrHeader = b; +// }, + +// This is never called - Is it worth exposing this? +// setPollingInterval : function(i) { +// if (typeof i == 'number' && isFinite(i)) { +// this.pollInterval = i; +// } +// }, + +// This is never called - Is it worth exposing this? +// resetDefaultHeaders : function() { +// this.defaultHeaders = null; +// }, + + abort : function(o, callback, isTimeout) { + var me = this, + tId = o.tId, + isAbort = false; + + if (me.isCallInProgress(o)) { + o.conn.abort(); + clearInterval(me.poll[tId]); + me.poll[tId] = null; + clearTimeout(pub.timeout[tId]); + me.timeout[tId] = null; + + handleTransactionResponse(o, callback, (isAbort = true), isTimeout); + } + return isAbort; + }, + + isCallInProgress : function(o) { + // if there is a connection and readyState is not 0 or 4 + return o.conn && !{0:true,4:true}[o.conn.readyState]; + } + }; + return pub; + }();(function(){ + var EXTLIB = Ext.lib, + noNegatives = /width|height|opacity|padding/i, + offsetAttribute = /^((width|height)|(top|left))$/, + defaultUnit = /width|height|top$|bottom$|left$|right$/i, + offsetUnit = /\d+(em|%|en|ex|pt|in|cm|mm|pc)$/i, + isset = function(v){ + return typeof v !== 'undefined'; + }, + now = function(){ + return new Date(); + }; + + EXTLIB.Anim = { + motion : function(el, args, duration, easing, cb, scope) { + return this.run(el, args, duration, easing, cb, scope, Ext.lib.Motion); + }, + + run : function(el, args, duration, easing, cb, scope, type) { + type = type || Ext.lib.AnimBase; + if (typeof easing == "string") { + easing = Ext.lib.Easing[easing]; + } + var anim = new type(el, args, duration, easing); + anim.animateX(function() { + if(Ext.isFunction(cb)){ + cb.call(scope); + } + }); + return anim; + } + }; + + EXTLIB.AnimBase = function(el, attributes, duration, method) { + if (el) { + this.init(el, attributes, duration, method); + } + }; + + EXTLIB.AnimBase.prototype = { + doMethod: function(attr, start, end) { + var me = this; + return me.method(me.curFrame, start, end - start, me.totalFrames); + }, + + + setAttr: function(attr, val, unit) { + if (noNegatives.test(attr) && val < 0) { + val = 0; + } + Ext.fly(this.el, '_anim').setStyle(attr, val + unit); + }, + + + getAttr: function(attr) { + var el = Ext.fly(this.el), + val = el.getStyle(attr), + a = offsetAttribute.exec(attr) || [] + + if (val !== 'auto' && !offsetUnit.test(val)) { + return parseFloat(val); + } + + return (!!(a[2]) || (el.getStyle('position') == 'absolute' && !!(a[3]))) ? el.dom['offset' + a[0].charAt(0).toUpperCase() + a[0].substr(1)] : 0; + }, + + + getDefaultUnit: function(attr) { + return defaultUnit.test(attr) ? 'px' : ''; + }, + + animateX : function(callback, scope) { + var me = this, + f = function() { + me.onComplete.removeListener(f); + if (Ext.isFunction(callback)) { + callback.call(scope || me, me); + } + }; + me.onComplete.addListener(f, me); + me.animate(); + }, + + + setRunAttr: function(attr) { + var me = this, + a = this.attributes[attr], + to = a.to, + by = a.by, + from = a.from, + unit = a.unit, + ra = (this.runAttrs[attr] = {}), + end; + + if (!isset(to) && !isset(by)){ + return false; + } + + var start = isset(from) ? from : me.getAttr(attr); + if (isset(to)) { + end = to; + }else if(isset(by)) { + if (Ext.isArray(start)){ + end = []; + for(var i=0,len=start.length; i 0 && isFinite(tweak)){ + if(tween.curFrame + tweak >= frames){ + tweak = frames - (frame + 1); + } + tween.curFrame += tweak; + } + }; + }; + + EXTLIB.Bezier = new function() { + + this.getPosition = function(points, t) { + var n = points.length, + tmp = [], + c = 1 - t, + i, + j; + + for (i = 0; i < n; ++i) { + tmp[i] = [points[i][0], points[i][1]]; + } + + for (j = 1; j < n; ++j) { + for (i = 0; i < n - j; ++i) { + tmp[i][0] = c * tmp[i][0] + t * tmp[parseInt(i + 1, 10)][0]; + tmp[i][1] = c * tmp[i][1] + t * tmp[parseInt(i + 1, 10)][1]; + } + } + + return [ tmp[0][0], tmp[0][1] ]; + + }; + }; + + + EXTLIB.Easing = { + easeNone: function (t, b, c, d) { + return c * t / d + b; + }, + + + easeIn: function (t, b, c, d) { + return c * (t /= d) * t + b; + }, + + + easeOut: function (t, b, c, d) { + return -c * (t /= d) * (t - 2) + b; + } + }; + + (function() { + EXTLIB.Motion = function(el, attributes, duration, method) { + if (el) { + EXTLIB.Motion.superclass.constructor.call(this, el, attributes, duration, method); + } + }; + + Ext.extend(EXTLIB.Motion, Ext.lib.AnimBase); + + var superclass = EXTLIB.Motion.superclass, + proto = EXTLIB.Motion.prototype, + pointsRe = /^points$/i; + + Ext.apply(EXTLIB.Motion.prototype, { + setAttr: function(attr, val, unit){ + var me = this, + setAttr = superclass.setAttr; + + if (pointsRe.test(attr)) { + unit = unit || 'px'; + setAttr.call(me, 'left', val[0], unit); + setAttr.call(me, 'top', val[1], unit); + } else { + setAttr.call(me, attr, val, unit); + } + }, + + getAttr: function(attr){ + var me = this, + getAttr = superclass.getAttr; + + return pointsRe.test(attr) ? [getAttr.call(me, 'left'), getAttr.call(me, 'top')] : getAttr.call(me, attr); + }, + + doMethod: function(attr, start, end){ + var me = this; + + return pointsRe.test(attr) + ? EXTLIB.Bezier.getPosition(me.runAttrs[attr], me.method(me.curFrame, 0, 100, me.totalFrames) / 100) + : superclass.doMethod.call(me, attr, start, end); + }, + + setRunAttr: function(attr){ + if(pointsRe.test(attr)){ + + var me = this, + el = this.el, + points = this.attributes.points, + control = points.control || [], + from = points.from, + to = points.to, + by = points.by, + DOM = EXTLIB.Dom, + start, + i, + end, + len, + ra; + + + if(control.length > 0 && !Ext.isArray(control[0])){ + control = [control]; + }else{ + /* + var tmp = []; + for (i = 0,len = control.length; i < len; ++i) { + tmp[i] = control[i]; + } + control = tmp; + */ + } + + Ext.fly(el, '_anim').position(); + DOM.setXY(el, isset(from) ? from : DOM.getXY(el)); + start = me.getAttr('points'); + + + if(isset(to)){ + end = translateValues.call(me, to, start); + for (i = 0,len = control.length; i < len; ++i) { + control[i] = translateValues.call(me, control[i], start); + } + } else if (isset(by)) { + end = [start[0] + by[0], start[1] + by[1]]; + + for (i = 0,len = control.length; i < len; ++i) { + control[i] = [ start[0] + control[i][0], start[1] + control[i][1] ]; + } + } + + ra = this.runAttrs[attr] = [start]; + if (control.length > 0) { + ra = ra.concat(control); + } + + ra[ra.length] = end; + }else{ + superclass.setRunAttr.call(this, attr); + } + } + }); + + var translateValues = function(val, start) { + var pageXY = EXTLIB.Dom.getXY(this.el); + return [val[0] - pageXY[0] + start[0], val[1] - pageXY[1] + start[1]]; + }; + })(); +})();// Easing functions +(function(){ + // shortcuts to aid compression + var abs = Math.abs, + pi = Math.PI, + asin = Math.asin, + pow = Math.pow, + sin = Math.sin, + EXTLIB = Ext.lib; + + Ext.apply(EXTLIB.Easing, { + + easeBoth: function (t, b, c, d) { + return ((t /= d / 2) < 1) ? c / 2 * t * t + b : -c / 2 * ((--t) * (t - 2) - 1) + b; + }, + + easeInStrong: function (t, b, c, d) { + return c * (t /= d) * t * t * t + b; + }, + + easeOutStrong: function (t, b, c, d) { + return -c * ((t = t / d - 1) * t * t * t - 1) + b; + }, + + easeBothStrong: function (t, b, c, d) { + return ((t /= d / 2) < 1) ? c / 2 * t * t * t * t + b : -c / 2 * ((t -= 2) * t * t * t - 2) + b; + }, + + elasticIn: function (t, b, c, d, a, p) { + if (t == 0 || (t /= d) == 1) { + return t == 0 ? b : b + c; + } + p = p || (d * .3); + + var s; + if (a >= abs(c)) { + s = p / (2 * pi) * asin(c / a); + } else { + a = c; + s = p / 4; + } + + return -(a * pow(2, 10 * (t -= 1)) * sin((t * d - s) * (2 * pi) / p)) + b; + + }, + + elasticOut: function (t, b, c, d, a, p) { + if (t == 0 || (t /= d) == 1) { + return t == 0 ? b : b + c; + } + p = p || (d * .3); + + var s; + if (a >= abs(c)) { + s = p / (2 * pi) * asin(c / a); + } else { + a = c; + s = p / 4; + } + + return a * pow(2, -10 * t) * sin((t * d - s) * (2 * pi) / p) + c + b; + }, + + elasticBoth: function (t, b, c, d, a, p) { + if (t == 0 || (t /= d / 2) == 2) { + return t == 0 ? b : b + c; + } + + p = p || (d * (.3 * 1.5)); + + var s; + if (a >= abs(c)) { + s = p / (2 * pi) * asin(c / a); + } else { + a = c; + s = p / 4; + } + + return t < 1 ? + -.5 * (a * pow(2, 10 * (t -= 1)) * sin((t * d - s) * (2 * pi) / p)) + b : + a * pow(2, -10 * (t -= 1)) * sin((t * d - s) * (2 * pi) / p) * .5 + c + b; + }, + + backIn: function (t, b, c, d, s) { + s = s || 1.70158; + return c * (t /= d) * t * ((s + 1) * t - s) + b; + }, + + + backOut: function (t, b, c, d, s) { + if (!s) { + s = 1.70158; + } + return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b; + }, + + + backBoth: function (t, b, c, d, s) { + s = s || 1.70158; + + return ((t /= d / 2 ) < 1) ? + c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b : + c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b; + }, + + + bounceIn: function (t, b, c, d) { + return c - EXTLIB.Easing.bounceOut(d - t, 0, c, d) + b; + }, + + + bounceOut: function (t, b, c, d) { + if ((t /= d) < (1 / 2.75)) { + return c * (7.5625 * t * t) + b; + } else if (t < (2 / 2.75)) { + return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b; + } else if (t < (2.5 / 2.75)) { + return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b; + } + return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b; + }, + + + bounceBoth: function (t, b, c, d) { + return (t < d / 2) ? + EXTLIB.Easing.bounceIn(t * 2, 0, c, d) * .5 + b : + EXTLIB.Easing.bounceOut(t * 2 - d, 0, c, d) * .5 + c * .5 + b; + } + }); +})(); + +(function() { + var EXTLIB = Ext.lib; + // Color Animation + EXTLIB.Anim.color = function(el, args, duration, easing, cb, scope) { + return EXTLIB.Anim.run(el, args, duration, easing, cb, scope, EXTLIB.ColorAnim); + } + + EXTLIB.ColorAnim = function(el, attributes, duration, method) { + EXTLIB.ColorAnim.superclass.constructor.call(this, el, attributes, duration, method); + }; + + Ext.extend(EXTLIB.ColorAnim, EXTLIB.AnimBase); + + var superclass = EXTLIB.ColorAnim.superclass, + colorRE = /color$/i, + transparentRE = /^transparent|rgba\(0, 0, 0, 0\)$/, + rgbRE = /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i, + hexRE= /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i, + hex3RE = /^#?([0-9A-F]{1})([0-9A-F]{1})([0-9A-F]{1})$/i, + isset = function(v){ + return typeof v !== 'undefined'; + } + + // private + function parseColor(s) { + var pi = parseInt, + base, + out = null, + c; + + if (s.length == 3) { + return s; + } + + Ext.each([hexRE, rgbRE, hex3RE], function(re, idx){ + base = (idx % 2 == 0) ? 16 : 10; + c = re.exec(s); + if(c && c.length == 4){ + out = [pi(c[1], base), pi(c[2], base), pi(c[3], base)]; + return false; + } + }); + return out; + } + + Ext.apply(EXTLIB.ColorAnim.prototype, { + getAttr : function(attr) { + var me = this, + el = me.el, + val; + if(colorRE.test(attr)){ + while(el && transparentRE.test(val = Ext.fly(el).getStyle(attr))){ + el = el.parentNode; + val = "fff"; + } + }else{ + val = superclass.getAttr.call(me, attr); + } + return val; + }, + + doMethod : function(attr, start, end) { + var me = this, + val, + floor = Math.floor, + i, + len, + v; + + if(colorRE.test(attr)){ + val = []; + + for(i = 0, len = start.length; i < len; i++) { + v = start[i]; + val[i] = superclass.doMethod.call(me, attr, v, end[i]); + } + val = 'rgb(' + floor(val[0]) + ',' + floor(val[1]) + ',' + floor(val[2]) + ')'; + }else{ + val = superclass.doMethod.call(me, attr, start, end); + } + return val; + }, + + setRunAttr : function(attr) { + var me = this, + a = me.attributes[attr], + to = a.to, + by = a.by, + ra; + + superclass.setRunAttr.call(me, attr); + ra = me.runAttrs[attr]; + if(colorRE.test(attr)){ + var start = parseColor(ra.start), + end = parseColor(ra.end); + + if(!isset(to) && isset(by)){ + end = parseColor(by); + for(var i=0,len=start.length; i + * 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); + delete me.listeners; + } + me.events = e || {}; +}; + +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), + ename = a[0].toLowerCase(), + me = this, + ret = TRUE, + ce = me.events[ename], + q, + c; + if (me.eventsSuspended === TRUE) { + if (q = me.eventQueue) { + 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); + } + return c.fireEvent.apply(c, a); + } + } + else { + if (ISOBJECT(ce)) { + a.shift(); + ret = ce.fire.apply(ce, a); + } + } + return ret; + }, + + /** + * Appends an event handler to this object. + * @param {String} eventName The name of the event to listen for. + * @param {Function} handler The method the event invokes. + * @param {Object} scope (optional) The scope (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:
      + *
    • scope : Object
      The scope (this reference) in which the handler function is executed. + * If omitted, defaults to the object which fired the event.
    • + *
    • delay : Number
      The number of milliseconds to delay the invocation of the handler after the event fires.
    • + *
    • single : Boolean
      True to add a handler to handle just the next firing of the event, and then remove itself.
    • + *
    • buffer : Number
      Causes the handler to be scheduled to run in an {@link Ext.util.DelayedTask} delayed + * by the specified number of milliseconds. If the event fires again within that time, the original + * handler is not invoked, but the new handler is scheduled in its place.
    • + *
    • target : Observable
      Only call the handler if the event was fired on the target Observable, not + * if the event was bubbled up from a child Observable.
    • + *

    + *

    + * 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)) { + o = eventName; + for (e in o){ + oe = o[e]; + if (!me.filterOptRe.test(e)) { + me.addListener(e, oe.fn || oe, oe.scope || o.scope, oe.fn ? oe : o); + } + } + } else { + eventName = eventName.toLowerCase(); + ce = me.events[eventName] || TRUE; + if (Ext.isBoolean(ce)) { + me.events[eventName] = ce = new EXTUTIL.Event(me, eventName); + } + ce.addListener(fn, scope, ISOBJECT(o) ? 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)) { + 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)){ + 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)) { + 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; + }, + + /** + * Suspend the firing of all events. (see {@link #resumeEvents}) + * @param {Boolean} queueSuspended Pass as true to queue up suspended events to be fired + * after the {@link #resumeEvents} call instead of discarding all suspended events; + */ + suspendEvents : function(queueSuspended){ + this.eventsSuspended = TRUE; + if(queueSuspended && !this.eventQueue){ + this.eventQueue = []; + } + }, + + /** + * Resume firing events. (see {@link #suspendEvents}) + * If events were suspended using the queueSuspended parameter, then all + * events fired during event suspension will be sent to any listeners now. + */ + resumeEvents : function(){ + var me = this, + queued = me.eventQueue || []; + me.eventsSuspended = FALSE; + delete me.eventQueue; + EACH(queued, function(e) { + me.fireEvent.apply(me, e); + }); + } +}; + +var OBSERVABLE = EXTUTIL.Observable.prototype; +/** + * Appends an event handler to this object (shorthand for {@link #addListener}.) + * @param {String} eventName The type of event to listen for + * @param {Function} handler The method the event invokes + * @param {Object} scope (optional) The scope (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; +}; + +function createTargeted(h, o, scope){ + return function(){ + if(o.target == arguments[0]){ + h.apply(scope, TOARRAY(arguments)); + } + }; +}; + +function createBuffered(h, o, l, scope){ + l.task = new EXTUTIL.DelayedTask(); + return function(){ + l.task.delay(o.buffer, h, scope, TOARRAY(arguments)); + }; +}; + +function createSingle(h, e, fn, scope){ + return function(){ + e.removeListener(fn, scope); + return h.apply(scope, arguments); + }; +}; + +function createDelayed(h, o, l, scope){ + return function(){ + var task = new EXTUTIL.DelayedTask(); + if(!l.tasks) { + l.tasks = []; + } + l.tasks.push(task); + task.delay(o.delay || 10, h, scope, TOARRAY(arguments)); + }; +}; + +EXTUTIL.Event = function(obj, name){ + this.name = name; + this.obj = obj; + this.listeners = []; +}; + +EXTUTIL.Event.prototype = { + addListener : function(fn, scope, options){ + var me = this, + l; + scope = scope || me.obj; + if(!me.isListening(fn, scope)){ + l = me.createListener(fn, scope, options); + if(me.firing){ // if we are currently firing this event, don't disturb the listener loop + me.listeners = me.listeners.slice(0); + } + me.listeners.push(l); + } + }, + + createListener: function(fn, scope, o){ + o = o || {}, scope = scope || this.obj; + var l = { + fn: fn, + scope: scope, + options: o + }, h = fn; + if(o.target){ + h = createTargeted(h, o, scope); + } + if(o.delay){ + h = createDelayed(h, o, l, scope); + } + if(o.single){ + h = createSingle(h, this, fn, scope); + } + if(o.buffer){ + h = createBuffered(h, o, l, scope); + } + l.fireFn = h; + return l; + }, + + findListener : function(fn, scope){ + var list = this.listeners, + i = list.length, + l, + s; + while(i--) { + l = list[i]; + if(l) { + s = l.scope; + if(l.fn == fn && (s == scope || s == this.obj)){ + return i; + } + } + } + return -1; + }, + + isListening : function(fn, scope){ + return this.findListener(fn, scope) != -1; + }, + + removeListener : function(fn, scope){ + var index, + l, + k, + me = this, + ret = FALSE; + if((index = me.findListener(fn, scope)) != -1){ + if (me.firing) { + me.listeners = me.listeners.slice(0); + } + l = me.listeners[index]; + if(l.task) { + l.task.cancel(); + delete l.task; + } + k = l.tasks && l.tasks.length; + if(k) { + while(k--) { + l.tasks[k].cancel(); + } + delete l.tasks; + } + me.listeners.splice(index, 1); + ret = TRUE; + } + return ret; + }, + + // Iterate to stop any buffered/delayed events + clearListeners : function(){ + var me = this, + l = me.listeners, + i = l.length; + while(i--) { + me.removeListener(l[i].fn, l[i].scope); + } + }, + + fire : function(){ + var me = this, + args = TOARRAY(arguments), + listeners = me.listeners, + len = listeners.length, + i = 0, + l; + + if(len > 0){ + me.firing = TRUE; + for (; i < len; i++) { + l = listeners[i]; + if(l && l.fireFn.apply(l.scope || me.obj || window, args) === FALSE) { + return (me.firing = FALSE); + } + } + } + me.firing = FALSE; + return TRUE; + } +}; +})();/** + * @class Ext.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: + *

      + *
    • tag :
      The tag name of the element
    • + *
    • children : or cn
      An array of the + * same kind of element definition objects to be created and appended. These can be nested + * as deep as you want.
    • + *
    • cls :
      The class attribute of the element. + * This will end up being either the "class" attribute on a HTML fragment or className + * for a DOM node, depending on whether DomHelper is using fragments or DOM.
    • + *
    • html :
      The innerHTML for the element
    • + *

    + * + *

    Insertion methods

    + *

    Commonly used insertion methods: + *

      + *
    • {@link #append} :
    • + *
    • {@link #insertBefore} :
    • + *
    • {@link #insertAfter} :
    • + *
    • {@link #overwrite} :
    • + *
    • {@link #createTemplate} :
    • + *
    • {@link #insertHtml} :
    • + *

    + * + *

    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)) { + for (var i=0; i < o.length; i++) { + if(o[i]) { + b += createHtml(o[i]); + } + }; + } 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.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: + *
      + *
    • single argument : String/Array + *
      + * The single argument may be either a String or an Array:
        + *
      • String :
      • 
        +var t = new Ext.Template("<div>Hello {0}.</div>");
        +t.{@link #append}('some-element', ['foo']);
        + * 
        + *
      • Array :
      • + * An Array will be combined with join(''). +
        
        +var t = new Ext.Template([
        +    '<div name="{id}">',
        +        '<span class="{cls}">{name:trim} {value:ellipsis(10)}</span>',
        +    '</div>',
        +]);
        +t.{@link #compile}();
        +t.{@link #append}('some-element', {id: 'myid', cls: 'myclass', name: 'foo', value: 'bar'});
        +
        + *
    • + *
    • multiple arguments : String, Object, Array, ... + *
      + * Multiple arguments will be combined with join(''). + *
      
      +var t = new Ext.Template(
      +    '<div name="{id}">',
      +        '<span class="{cls}">{name} {value}</span>',
      +    '</div>',
      +    // a configuration object:
      +    {
      +        compiled: true,      // {@link #compile} immediately
      +        disableFormats: true // See Notes below.
      +    } 
      +);
      + * 
      + *

      Notes:

      + *
        + *
      • Formatting and disableFormats are not applicable for Ext Core.
      • + *
      • For a list of available format functions, see {@link Ext.util.Format}.
      • + *
      • disableFormats reduces {@link #apply} time + * when no formatting is required.
      • + *
      + *
    • + *
    + * @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 || ''); +};/* + * 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:

    +
      +
    • * any element
    • +
    • E an element with the tag E
    • +
    • E F All descendent elements of E that have the tag F
    • +
    • E > F or E/F all direct children elements of E that have the tag F
    • +
    • E + F all elements with the tag F that are immediately preceded by an element with the tag E
    • +
    • E ~ F all elements with the tag F that are preceded by a sibling element with the tag E
    • +
    +

    Attribute Selectors:

    +

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

    +
      +
    • E[foo] has an attribute "foo"
    • +
    • E[foo=bar] has an attribute "foo" that equals "bar"
    • +
    • E[foo^=bar] has an attribute "foo" that starts with "bar"
    • +
    • E[foo$=bar] has an attribute "foo" that ends with "bar"
    • +
    • E[foo*=bar] has an attribute "foo" that contains the substring "bar"
    • +
    • E[foo%=2] has an attribute "foo" that is evenly divisible by 2
    • +
    • E[foo!=bar] has an attribute "foo" that does not equal "bar"
    • +
    +

    Pseudo Classes:

    +
      +
    • E:first-child E is the first child of its parent
    • +
    • E:last-child E is the last child of its parent
    • +
    • E:nth-child(n) E is the nth child of its parent (1 based as per the spec)
    • +
    • E:nth-child(odd) E is an odd child of its parent
    • +
    • E:nth-child(even) E is an even child of its parent
    • +
    • E:only-child E is the only child of its parent
    • +
    • E:checked E is an element that is has a checked attribute that is true (e.g. a radio or checkbox)
    • +
    • E:first the first E in the resultset
    • +
    • E:last the last E in the resultset
    • +
    • E:nth(n) the nth E in the resultset (1 based)
    • +
    • E:odd shortcut for :nth-child(odd)
    • +
    • E:even shortcut for :nth-child(even)
    • +
    • E:contains(foo) E's innerHTML contains the substring "foo"
    • +
    • E:nodeValue(foo) E contains a textNode with a nodeValue that equals "foo"
    • +
    • E:not(S) an E element that does not match simple selector S
    • +
    • E:has(S) an E element that has a descendent that matches simple selector S
    • +
    • E:next(S) an E element whose next sibling matches simple selector S
    • +
    • E:prev(S) an E element whose previous sibling matches simple selector S
    • +
    +

    CSS Value Selectors:

    +
      +
    • E{display=none} css value "display" that equals "none"
    • +
    • E{display^=none} css value "display" that starts with "none"
    • +
    • E{display$=none} css value "display" that ends with "none"
    • +
    • E{display*=none} css value "display" that contains the substring "none"
    • +
    • E{display%=2} css value "display" that is evenly divisible by 2
    • +
    • E{display!=none} css value "display" that does not equal "none"
    • +
    + * @singleton + */ +Ext.DomQuery = function(){ + var cache = {}, + simpleCache = {}, + valueCache = {}, + nonSpace = /\S/, + trimRe = /^\s+|\s+$/g, + tplRe = /\{(\d+)\}/g, + modeRe = /^(\s?[\/>+~]\s?|\s|$)/, + tagTokenRe = /^(#)?([\w-\*]+)/, + nthRe = /(\d*)n\+?(\d*)/, + nthRe2 = /\D/, + // This is for IE MSXML which does not support expandos. + // IE runs the same speed using setAttribute, however FF slows way down + // and Safari completely fails so they need to continue to use expandos. + isIE = window.ActiveXObject ? true : false, + key = 30803; + + // this eval is stop the compressor from + // renaming the variable to something shorter + eval("var batch = 30803;"); + + 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 = 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], + a, + ih; + for(var i = 0, ci; ci = cs[i]; i++){ + if(ci.nodeType != 1){ + continue; + } + ih = ci.innerHTML; + // we only need to change the property names if we're dealing with html nodes, not XML + if(ih !== null && ih !== undefined){ + 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); + } + }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 && 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, 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; + + if (typeof n.normalize == 'function') n.normalize(); + + v = (n && n.firstChild ? n.firstChild.nodeValue : null); + return ((v === null||v === undefined||v==='') ? defaultValue : v); + }, + + /** + * Selects the value of a node, parsing integers and floats. Returns the defaultValue, or 0 if none is specified. + * @param {String} selector The selector/xpath query + * @param {Node} root (optional) The start of the query (defaults to document). + * @param {Number} defaultValue + * @return {Number} + */ + selectNumber : function(path, root, defaultValue){ + var v = Ext.DomQuery.selectValue(path, root, defaultValue || 0); + return parseFloat(v); + }, + + /** + * Returns true if the passed element(s) match the passed simple selector (e.g. div.some-class or span:first-child) + * @param {String/HTMLElement/Array} el An element id, element or array of elements + * @param {String} selector The simple selector to test + * @return {Boolean} + */ + is : function(el, ss){ + if(typeof el == "string"){ + el = document.getElementById(el); + } + var isArray = Ext.isArray(el), + result = Ext.DomQuery.filter(isArray ? el : [el], ss); + return isArray ? (result.length == el.length) : (result.length > 0); + }, + + /** + * Filters an array of elements to only include matches of a simple selector (e.g. div.some-class or span:first-child) + * @param {Array} el An array of elements to filter + * @param {String} selector The simple selector to test + * @param {Boolean} nonMatches If true, it returns the elements that DON'T match + * the selector instead of the ones that match + * @return {Array} An Array of DOM elements which match the selector. If there are + * no matches, and empty Array is returned. + */ + filter : function(els, ss, nonMatches){ + ss = ss.replace(trimRe, ""); + if(!simpleCache[ss]){ + simpleCache[ss] = Ext.DomQuery.compile(ss, "simple"); + } + var result = simpleCache[ss](els); + return nonMatches ? quickDiff(result, els) : result; + }, + + /** + * Collection of matching regular expressions and code snippets. + */ + 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:

      + *
    • c : Array
      An Array of DOM elements to filter.
    • + *
    • v : String
      The argument (if any) supplied in the selector.
    • + *
    + *

    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; +/** + * @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", + propRe = /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/, + /* + * This cache is used to hold special js objects, the document and window, that don't have an id. We need to keep + * a reference to them so we can look them up at a later point. + */ + specialElCache = []; + + function getId(el){ + var id = false, + i = 0, + len = specialElCache.length, + id = false, + skip = false, + o; + if(el){ + if(el.getElementById || el.navigator){ + // look up the id + for(; i < len; ++i){ + o = specialElCache[i]; + if(o.el === el){ + id = o.id; + break; + } + } + if(!id){ + // for browsers that support it, ensure that give the el the same id + id = Ext.id(el); + specialElCache.push({ + id: id, + el: el + }); + skip = true; + } + }else{ + id = Ext.id(el); + } + if(!Ext.elCache[id]){ + Ext.Element.addToCache(new Ext.Element(el), id); + if(skip){ + Ext.elCache[id].skipGC = true; + } + } + } + return id; + }; + + /// There is some jquery work around stuff here that isn't needed in Ext Core. + function addListener(el, ename, fn, task, wrap, scope){ + el = Ext.getDom(el); + var id = getId(el), + es = Ext.elCache[id].events, + wfn; + + wfn = E.on(el, ename, wrap); + es[ename] = es[ename] || []; + + /* 0 = Original Function, + 1 = Event Manager Wrapped Function, + 2 = Scope, + 3 = Adapter Wrapped Function, + 4 = Buffered Task + */ + es[ename].push([fn, wrap, scope, wfn, task]); + + + // this is a workaround for jQuery and should somehow be removed from Ext Core in the future + // without breaking ExtJS. + if(ename == "mousewheel" && el.addEventListener){ // workaround for jQuery + var args = ["DOMMouseScroll", wrap, false]; + el.addEventListener.apply(el, args); + Ext.EventManager.addListener(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); + } + } + if(docReadyEvent){ + docReadyEvent.fire(); + docReadyEvent.listeners = []; // clearListeners no longer compatible. Force single: true? + } + } + }; + + 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); + } + // no matter what, make sure it fires on load + E.on(WINDOW, "load", fireDocReady); + }; + + function createTargeted(h, o){ + return function(){ + var args = Ext.toArray(arguments); + if(o.target == Ext.EventObject.setEvent(args[0]).target){ + h.apply(this, args); + } + }; + }; + + function createBuffered(h, o, task){ + return function(e){ + // create new event object impl so new events don't wipe out properties + task.delay(o.buffer, h, null, [new Ext.EventObjectImpl(e)]); + }; + }; + + function createSingle(h, el, ename, fn, scope){ + return function(e){ + Ext.EventManager.removeListener(el, ename, fn, scope); + h(e); + }; + }; + + function createDelayed(h, o, fn){ + return function(e){ + var task = new Ext.util.DelayedTask(h); + if(!fn.tasks) { + fn.tasks = []; + } + fn.tasks.push(task); + task.delay(o.delay || 10, h, null, [new Ext.EventObjectImpl(e)]); + }; + }; + + function listen(element, ename, opt, fn, scope){ + var o = !Ext.isObject(opt) ? {} : opt, + el = Ext.getDom(element), task; + + fn = fn || o.fn; + scope = scope || o.scope; + + if(!el){ + throw "Error listening for \"" + ename + '\". Element "' + element + '" doesn\'t exist.'; + } + function h(e){ + // prevent errors while unload occurring + if(!Ext){// !window[xname]){ ==> can't we do this? + return; + } + e = Ext.EventObject.setEvent(e); + var t; + if (o.delegate) { + if(!(t = e.getTarget(o.delegate, el))){ + return; + } + } else { + t = e.target; + } + if (o.stopEvent) { + e.stopEvent(); + } + if (o.preventDefault) { + e.preventDefault(); + } + if (o.stopPropagation) { + e.stopPropagation(); + } + if (o.normalized) { + e = e.browserEvent; + } + + fn.call(scope || el, e, t, o); + }; + if(o.target){ + h = createTargeted(h, o); + } + if(o.delay){ + h = createDelayed(h, o, fn); + } + if(o.single){ + h = createSingle(h, el, ename, fn, scope); + } + if(o.buffer){ + task = new Ext.util.DelayedTask(h); + h = createBuffered(h, o, task); + } + + addListener(el, ename, fn, task, h, scope); + return h; + }; + + var pub = { + /** + * Appends an event handler to an element. The shorthand version {@link #on} is equivalent. Typically you will + * use {@link Ext.Element#addListener} directly on an Element in favor of calling this version. + * @param {String/HTMLElement} el The html element or id to assign the event handler to. + * @param {String} eventName The name of the event to listen for. + * @param {Function} handler The handler function the event invokes. This function is passed + * the following parameters:
      + *
    • evt : EventObject
      The {@link Ext.EventObject EventObject} describing the event.
    • + *
    • t : Element
      The {@link Ext.Element Element} which was the target of the event. + * Note that this may be filtered by using the delegate option.
    • + *
    • o : Object
      The options object from the addListener call.
    • + *
    + * @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:
      + *
    • scope : Object
      The scope (this reference) in which the handler function is executed. Defaults to the Element.
    • + *
    • delegate : String
      A simple selector to filter the target or look for a descendant of the target
    • + *
    • stopEvent : Boolean
      True to stop the event. That is stop propagation, and prevent the default action.
    • + *
    • preventDefault : Boolean
      True to prevent the default action
    • + *
    • stopPropagation : Boolean
      True to prevent event propagation
    • + *
    • normalized : Boolean
      False to pass a browser event to the handler function instead of an Ext.EventObject
    • + *
    • delay : Number
      The number of milliseconds to delay the invocation of the handler after te event fires.
    • + *
    • single : Boolean
      True to add a handler to handle just the next firing of the event, and then remove itself.
    • + *
    • buffer : Number
      Causes the handler to be scheduled to run in an {@link Ext.util.DelayedTask} delayed + * by the specified number of milliseconds. If the event fires again within that time, the original + * handler is not invoked, but the new handler is scheduled in its place.
    • + *
    • target : Element
      Only call the handler if the event was fired on the target Element, not if the event was bubbled up from a child node.
    • + *

    + *

    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); + }else{ + // individual options + listen(element, e, val); + } + } + } + } else { + listen(element, eventName, options, fn, scope); + } + }, + + /** + * Removes an event handler from an element. The shorthand version {@link #un} is equivalent. Typically + * you will use {@link Ext.Element#removeListener} directly on an Element in favor of calling this version. + * @param {String/HTMLElement} el The id or html element from which to remove the listener. + * @param {String} eventName The name of the event. + * @param {Function} fn The handler function to remove. 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(el, eventName, fn, scope){ + el = Ext.getDom(el); + var id = getId(el), + f = el && (Ext.elCache[id].events)[eventName] || [], + wrap, i, l, k, wf, len, fnc; + + for (i = 0, len = f.length; i < len; i++) { + + /* 0 = Original Function, + 1 = Event Manager Wrapped Function, + 2 = Scope, + 3 = Adapter Wrapped Function, + 4 = Buffered Task + */ + if (Ext.isArray(fnc = f[i]) && fnc[0] == fn && (!scope || fnc[2] == scope)) { + if(fnc[4]) { + fnc[4].cancel(); + } + k = fn.tasks && fn.tasks.length; + if(k) { + while(k--) { + fn.tasks[k].cancel(); + } + delete fn.tasks; + } + wf = wrap = fnc[1]; + if (E.extAdapter) { + wf = fnc[3]; + } + E.un(el, eventName, wf); + 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; + } + } + + // 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); + } + }, + + /** + * Removes all event handers from an element. Typically you will use {@link Ext.Element#removeAllListeners} + * directly on an Element in favor of calling this version. + * @param {String/HTMLElement} el The id or html element from which to remove all event handlers. + */ + removeAll : function(el){ + el = Ext.getDom(el); + var id = getId(el), + ec = Ext.elCache[id] || {}, + es = ec.events || {}, + f, i, len, ename, fn, k; + + for(ename in es){ + if(es.hasOwnProperty(ename)){ + f = es[ename]; + /* 0 = Original Function, + 1 = Event Manager Wrapped Function, + 2 = Scope, + 3 = Adapter Wrapped Function, + 4 = Buffered Task + */ + for (i = 0, len = f.length; i < len; i++) { + fn = f[i]; + if(fn[4]) { + fn[4].cancel(); + } + if(fn[0].tasks && (k = fn[0].tasks.length)) { + while(k--) { + fn[0].tasks[k].cancel(); + } + delete fn.tasks; + } + E.un(el, ename, E.extAdapter ? fn[3] : fn[1]); + } + } + } + if (Ext.elCache[id]) { + Ext.elCache[id].events = {}; + } + }, + + getListeners : function(el, eventName) { + el = Ext.getDom(el); + var id = getId(el), + ec = Ext.elCache[id] || {}, + es = ec.events || {}, + results = []; + if (es && es[eventName]) { + return es[eventName]; + } else { + return null; + } + }, + + purgeElement : function(el, recurse, eventName) { + el = Ext.getDom(el); + var id = getId(el), + ec = Ext.elCache[id] || {}, + es = ec.events || {}, + i, f, len; + if (eventName) { + if (es && es.hasOwnProperty(eventName)) { + f = es[eventName]; + for (i = 0, len = f.length; i < len; i++) { + Ext.EventManager.removeListener(el, eventName, f[i][0]); + } + } + } else { + Ext.EventManager.removeAll(el); + } + if (recurse && el && el.childNodes) { + for (i = 0, len = el.childNodes.length; i < len; i++) { + Ext.EventManager.purgeElement(el.childNodes[i], recurse, eventName); + } + } + }, + + _unload : function() { + var el; + for (el in Ext.elCache) { + Ext.EventManager.removeAll(el); + } + }, + /** + * 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.listeners = []; // clearListeners no longer compatible. Force single: true? + } else { + if(!docReadyEvent) initDocReady(); + options = options || {}; + options.delay = options.delay || 1; + docReadyEvent.addListener(fn, scope, options); + } + } + }; + /** + * 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; + + pub.stoppedMouseDownEvent = new Ext.util.Event(); + return pub; +}(); +/** + * Adds a listener to be notified when the document is ready (before onload and before images are loaded). Shorthand of {@link Ext.EventManager#onDocumentReady}. + * @param {Function} fn The method the event invokes. + * @param {Object} scope (optional) The scope (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; + + +//Initialize doc classes +(function(){ + + var initExtCss = function(){ + // find the body element + var bd = document.body || document.getElementsByTagName('body')[0]; + if(!bd){ return false; } + var cls = [' ', + Ext.isIE ? "ext-ie " + (Ext.isIE6 ? 'ext-ie6' : (Ext.isIE7 ? 'ext-ie7' : 'ext-ie8')) + : Ext.isGecko ? "ext-gecko " + (Ext.isGecko2 ? 'ext-gecko2' : 'ext-gecko3') + : Ext.isOpera ? "ext-opera" + : Ext.isWebKit ? "ext-webkit" : ""]; + + if(Ext.isSafari){ + cls.push("ext-safari " + (Ext.isSafari2 ? 'ext-safari2' : (Ext.isSafari3 ? 'ext-safari3' : 'ext-safari4'))); + }else if(Ext.isChrome){ + cls.push("ext-chrome"); + } + + if(Ext.isMac){ + cls.push("ext-mac"); + } + if(Ext.isLinux){ + cls.push("ext-linux"); + } + + if(Ext.isStrict || Ext.isBorderBox){ // add to the parent to allow for selectors like ".ext-strict .ext-ie" + var p = bd.parentNode; + if(p){ + p.className += Ext.isStrict ? ' ext-strict' : ' ext-border-box'; + } + } + bd.className += cls.join(' '); + return true; + } + + if(!initExtCss()){ + Ext.onReady(initExtCss); + } +})(); + + +/** + * @class Ext.EventObject + * Just as {@link Ext.Element} wraps around a native DOM node, Ext.EventObject + * wraps the browser's native event-object normalizing cross-browser differences, + * such as which mouse button is clicked, keys pressed, mechanisms to stop + * event-propagation along with a method to prevent default actions from taking place. + *

    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}); + + Ext.EventObjectImpl = function(e){ + if(e){ + this.setEvent(e.browserEvent || e); + } + }; + + Ext.EventObjectImpl.prototype = { + /** @private */ + setEvent : function(e){ + var me = this; + if(e == me || (e && e.browserEvent)){ // already wrapped + return e; + } + me.browserEvent = e; + if(e){ + // normalize buttons + me.button = e.button ? btnMap[e.button] : (e.which ? e.which - 1 : -1); + if(e.type == 'click' && me.button == -1){ + me.button = 0; + } + me.type = e.type; + me.shiftKey = e.shiftKey; + // mac metaKey behaves like ctrlKey + me.ctrlKey = e.ctrlKey || e.metaKey || false; + me.altKey = e.altKey; + // in getKey these will be normalized for the mac + me.keyCode = e.keyCode; + me.charCode = e.charCode; + // cache the target for the delayed and or buffered events + me.target = E.getTarget(e); + // same for XY + me.xy = E.getXY(e); + }else{ + me.button = -1; + me.shiftKey = false; + me.ctrlKey = false; + me.altKey = false; + me.keyCode = 0; + me.charCode = 0; + me.target = null; + me.xy = [0, 0]; + } + return me; + }, + + /** + * Stop the event (preventDefault and stopPropagation) + */ + stopEvent : function(){ + var me = this; + if(me.browserEvent){ + if(me.browserEvent.type == 'mousedown'){ + Ext.EventManager.stoppedMouseDownEvent.fire(me); + } + E.stopEvent(me.browserEvent); + } + }, + + /** + * Prevents the browsers default handling of the event. + */ + preventDefault : function(){ + if(this.browserEvent){ + E.preventDefault(this.browserEvent); + } + }, + + /** + * Cancels bubbling of the event. + */ + stopPropagation : function(){ + var me = this; + if(me.browserEvent){ + if(me.browserEvent.type == 'mousedown'){ + Ext.EventManager.stoppedMouseDownEvent.fire(me); + } + E.stopPropagation(me.browserEvent); + } + }, + + /** + * Gets the character code for the event. + * @return {Number} + */ + getCharCode : function(){ + return this.charCode || this.keyCode; + }, + + /** + * Returns a normalized keyCode for the event. + * @return {Number} The key code + */ + getKey : function(){ + return this.normalizeKey(this.keyCode || this.charCode) + }, + + // private + normalizeKey: function(k){ + return Ext.isSafari ? (safariKeys[k] || k) : k; + }, + + /** + * Gets the x coordinate of the event. + * @return {Number} + */ + getPageX : function(){ + return this.xy[0]; + }, + + /** + * Gets the y coordinate of the event. + * @return {Number} + */ + getPageY : function(){ + return this.xy[1]; + }, + + /** + * Gets the page coordinates of the event. + * @return {Array} The xy values like [x, y] + */ + getXY : function(){ + return this.xy; + }, + + /** + * Gets the target for the event. + * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target + * @param {Number/Mixed} maxDepth (optional) The max depth to + search as a number or element (defaults to 10 || document.body) + * @param {Boolean} returnEl (optional) True to return a Ext.Element object instead of DOM node + * @return {HTMLelement} + */ + getTarget : function(selector, maxDepth, returnEl){ + return selector ? Ext.fly(this.target).findParent(selector, maxDepth, returnEl) : (returnEl ? Ext.get(this.target) : this.target); + }, + + /** + * Gets the related target. + * @return {HTMLElement} + */ + getRelatedTarget : function(){ + return this.browserEvent ? E.getRelatedTarget(this.browserEvent) : null; + }, + + /** + * Normalizes mouse wheel delta across browsers + * @return {Number} The delta + */ + getWheelDelta : function(){ + var e = this.browserEvent; + var delta = 0; + if(e.wheelDelta){ /* IE/Opera. */ + delta = e.wheelDelta/120; + }else if(e.detail){ /* Mozilla case. */ + delta = -e.detail/3; + } + return delta; + }, + + /** + * Returns true if the target of this event is a child of el. Unless the allowEl parameter is set, it will return false if if the target is el. + * Example usage:
    
    +        // Handle click on any child of an element
    +        Ext.getBody().on('click', function(e){
    +            if(e.within('some-el')){
    +                alert('Clicked on a child of some-el!');
    +            }
    +        });
    +
    +        // Handle click directly on an element, ignoring clicks on child nodes
    +        Ext.getBody().on('click', function(e,t){
    +            if((t.id == 'some-el') && !e.within(t, true)){
    +                alert('Clicked directly on some-el!');
    +            }
    +        });
    +        
    + * @param {Mixed} el The id, DOM element or Ext.Element to check + * @param {Boolean} related (optional) true to test if the related target is within el instead of the target + * @param {Boolean} allowEl {optional} true to also check if the passed element is the target or related target + * @return {Boolean} + */ + within : function(el, related, allowEl){ + if(el){ + var t = this[related ? "getRelatedTarget" : "getTarget"](); + return t && ((allowEl ? (t == Ext.getDom(el)) : false) || Ext.fly(el).contains(t)); + } + return false; + } + }; + + return new Ext.EventObjectImpl(); +}(); +/** + * @class Ext.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.elCache[id]){ // element object already exists + return Ext.elCache[id].el; + } + + /** + * The DOM element + * @type HTMLElement + */ + this.dom = dom; + + /** + * The DOM element ID + * @type String + */ + this.id = id || Ext.id(dom); +}; + +var D = Ext.lib.Dom, + DH = Ext.DomHelper, + E = Ext.lib.Event, + A = Ext.lib.Anim, + El = Ext.Element, + EC = Ext.elCache; + +El.prototype = { + /** + * Sets the passed attributes as attributes of this element (a style attribute can be a string, object or function) + * @param {Object} o The object with the attributes + * @param {Boolean} useSet (optional) false to override the default setAttribute to use expandos. + * @return {Ext.Element} this + */ + set : function(o, useSet){ + var el = this.dom, + attr, + val, + useSet = (useSet !== false) && !!el.setAttribute; + + for(attr in o){ + if (o.hasOwnProperty(attr)) { + val = o[attr]; + if (attr == 'style') { + DH.applyStyles(el, val); + } else if (attr == 'cls') { + el.className = val; + } else if (useSet) { + el.setAttribute(attr, val); + } else { + el[attr] = val; + } + } + } + return this; + }, + +// Mouse events + /** + * @event click + * Fires when a mouse click is detected within the element. + * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event. + * @param {HtmlElement} t The target of the event. + * @param {Object} o The options configuration passed to the {@link #addListener} call. + */ + /** + * @event contextmenu + * Fires when a right click is detected within the element. + * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event. + * @param {HtmlElement} t The target of the event. + * @param {Object} o The options configuration passed to the {@link #addListener} call. + */ + /** + * @event dblclick + * Fires when a mouse double click is detected within the element. + * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event. + * @param {HtmlElement} t The target of the event. + * @param {Object} o The options configuration passed to the {@link #addListener} call. + */ + /** + * @event mousedown + * Fires when a mousedown is detected within the element. + * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event. + * @param {HtmlElement} t The target of the event. + * @param {Object} o The options configuration passed to the {@link #addListener} call. + */ + /** + * @event mouseup + * Fires when a mouseup is detected within the element. + * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event. + * @param {HtmlElement} t The target of the event. + * @param {Object} o The options configuration passed to the {@link #addListener} call. + */ + /** + * @event mouseover + * Fires when a mouseover is detected within the element. + * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event. + * @param {HtmlElement} t The target of the event. + * @param {Object} o The options configuration passed to the {@link #addListener} call. + */ + /** + * @event mousemove + * Fires when a mousemove is detected with the element. + * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event. + * @param {HtmlElement} t The target of the event. + * @param {Object} o The options configuration passed to the {@link #addListener} call. + */ + /** + * @event mouseout + * Fires when a mouseout is detected with the element. + * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event. + * @param {HtmlElement} t The target of the event. + * @param {Object} o The options configuration passed to the {@link #addListener} call. + */ + /** + * @event mouseenter + * Fires when the mouse enters the element. + * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event. + * @param {HtmlElement} t The target of the event. + * @param {Object} o The options configuration passed to the {@link #addListener} call. + */ + /** + * @event mouseleave + * Fires when the mouse leaves the element. + * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event. + * @param {HtmlElement} t The target of the event. + * @param {Object} o The options configuration passed to the {@link #addListener} call. + */ + +// Keyboard events + /** + * @event keypress + * Fires when a keypress is detected within the element. + * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event. + * @param {HtmlElement} t The target of the event. + * @param {Object} o The options configuration passed to the {@link #addListener} call. + */ + /** + * @event keydown + * Fires when a keydown is detected within the element. + * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event. + * @param {HtmlElement} t The target of the event. + * @param {Object} o The options configuration passed to the {@link #addListener} call. + */ + /** + * @event keyup + * Fires when a keyup is detected within the element. + * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event. + * @param {HtmlElement} t The target of the event. + * @param {Object} o The options configuration passed to the {@link #addListener} call. + */ + + +// HTML frame/object events + /** + * @event load + * Fires when the user agent finishes loading all content within the element. Only supported by window, frames, objects and images. + * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event. + * @param {HtmlElement} t The target of the event. + * @param {Object} o The options configuration passed to the {@link #addListener} call. + */ + /** + * @event unload + * Fires when the user agent removes all content from a window or frame. For elements, it fires when the target element or any of its content has been removed. + * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event. + * @param {HtmlElement} t The target of the event. + * @param {Object} o The options configuration passed to the {@link #addListener} call. + */ + /** + * @event abort + * Fires when an object/image is stopped from loading before completely loaded. + * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event. + * @param {HtmlElement} t The target of the event. + * @param {Object} o The options configuration passed to the {@link #addListener} call. + */ + /** + * @event error + * Fires when an object/image/frame cannot be loaded properly. + * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event. + * @param {HtmlElement} t The target of the event. + * @param {Object} o The options configuration passed to the {@link #addListener} call. + */ + /** + * @event resize + * Fires when a document view is resized. + * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event. + * @param {HtmlElement} t The target of the event. + * @param {Object} o The options configuration passed to the {@link #addListener} call. + */ + /** + * @event scroll + * Fires when a document view is scrolled. + * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event. + * @param {HtmlElement} t The target of the event. + * @param {Object} o The options configuration passed to the {@link #addListener} call. + */ + +// Form events + /** + * @event select + * Fires when a user selects some text in a text field, including input and textarea. + * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event. + * @param {HtmlElement} t The target of the event. + * @param {Object} o The options configuration passed to the {@link #addListener} call. + */ + /** + * @event change + * Fires when a control loses the input focus and its value has been modified since gaining focus. + * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event. + * @param {HtmlElement} t The target of the event. + * @param {Object} o The options configuration passed to the {@link #addListener} call. + */ + /** + * @event submit + * Fires when a form is submitted. + * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event. + * @param {HtmlElement} t The target of the event. + * @param {Object} o The options configuration passed to the {@link #addListener} call. + */ + /** + * @event reset + * Fires when a form is reset. + * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event. + * @param {HtmlElement} t The target of the event. + * @param {Object} o The options configuration passed to the {@link #addListener} call. + */ + /** + * @event focus + * Fires when an element receives focus either via the pointing device or by tab navigation. + * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event. + * @param {HtmlElement} t The target of the event. + * @param {Object} o The options configuration passed to the {@link #addListener} call. + */ + /** + * @event blur + * Fires when an element loses focus either via the pointing device or by tabbing navigation. + * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event. + * @param {HtmlElement} t The target of the event. + * @param {Object} o The options configuration passed to the {@link #addListener} call. + */ + +// User Interface events + /** + * @event DOMFocusIn + * Where supported. Similar to HTML focus event, but can be applied to any focusable element. + * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event. + * @param {HtmlElement} t The target of the event. + * @param {Object} o The options configuration passed to the {@link #addListener} call. + */ + /** + * @event DOMFocusOut + * Where supported. Similar to HTML blur event, but can be applied to any focusable element. + * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event. + * @param {HtmlElement} t The target of the event. + * @param {Object} o The options configuration passed to the {@link #addListener} call. + */ + /** + * @event DOMActivate + * Where supported. Fires when an element is activated, for instance, through a mouse click or a keypress. + * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event. + * @param {HtmlElement} t The target of the event. + * @param {Object} o The options configuration passed to the {@link #addListener} call. + */ + +// DOM Mutation events + /** + * @event DOMSubtreeModified + * Where supported. Fires when the subtree is modified. + * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event. + * @param {HtmlElement} t The target of the event. + * @param {Object} o The options configuration passed to the {@link #addListener} call. + */ + /** + * @event DOMNodeInserted + * Where supported. Fires when a node has been added as a child of another node. + * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event. + * @param {HtmlElement} t The target of the event. + * @param {Object} o The options configuration passed to the {@link #addListener} call. + */ + /** + * @event DOMNodeRemoved + * Where supported. Fires when a descendant node of the element is removed. + * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event. + * @param {HtmlElement} t The target of the event. + * @param {Object} o The options configuration passed to the {@link #addListener} call. + */ + /** + * @event DOMNodeRemovedFromDocument + * Where supported. Fires when a node is being removed from a document. + * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event. + * @param {HtmlElement} t The target of the event. + * @param {Object} o The options configuration passed to the {@link #addListener} call. + */ + /** + * @event DOMNodeInsertedIntoDocument + * Where supported. Fires when a node is being inserted into a document. + * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event. + * @param {HtmlElement} t The target of the event. + * @param {Object} o The options configuration passed to the {@link #addListener} call. + */ + /** + * @event DOMAttrModified + * Where supported. Fires when an attribute has been modified. + * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event. + * @param {HtmlElement} t The target of the event. + * @param {Object} o The options configuration passed to the {@link #addListener} call. + */ + /** + * @event DOMCharacterDataModified + * Where supported. Fires when the character data has been modified. + * @param {Ext.EventObject} e The {@link Ext.EventObject} encapsulating the DOM event. + * @param {HtmlElement} t The target of the event. + * @param {Object} o The options configuration passed to the {@link #addListener} call. + */ + + /** + * The default unit to append to CSS values where a unit isn't provided (defaults to px). + * @type String + */ + defaultUnit : "px", + + /** + * Returns true if this element matches the passed simple selector (e.g. div.some-class or span:first-child) + * @param {String} selector The simple selector to test + * @return {Boolean} True if this element matches the selector, else false + */ + is : function(simpleSelector){ + return Ext.DomQuery.is(this.dom, simpleSelector); + }, + + /** + * Tries to focus the element. Any exceptions are caught and ignored. + * @param {Number} defer (optional) Milliseconds to defer the focus + * @return {Ext.Element} this + */ + focus : function(defer, /* private */ dom) { + var me = this, + dom = dom || me.dom; + try{ + if(Number(defer)){ + me.focus.defer(defer, null, [null, dom]); + }else{ + dom.focus(); + } + }catch(e){} + return me; + }, + + /** + * Tries to blur the element. Any exceptions are caught and ignored. + * @return {Ext.Element} this + */ + blur : function() { + try{ + this.dom.blur(); + }catch(e){} + return this; + }, + + /** + * Returns the value of the "value" attribute + * @param {Boolean} asNumber true to parse the value as a number + * @return {String/Number} + */ + getValue : function(asNumber){ + var val = this.dom.value; + return asNumber ? parseInt(val, 10) : val; + }, + + /** + * Appends an event handler to this element. The shorthand version {@link #on} is equivalent. + * @param {String} eventName The name of event to handle. + * @param {Function} fn The handler function the event invokes. This function is passed + * the following parameters:
      + *
    • evt : EventObject
      The {@link Ext.EventObject EventObject} describing the event.
    • + *
    • el : HtmlElement
      The DOM element which was the target of the event. + * Note that this may be filtered by using the delegate option.
    • + *
    • o : Object
      The options object from the addListener call.
    • + *
    + * @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:
      + *
    • scope Object :
      The scope (this reference) in which the handler function is executed. + * If omitted, defaults to this Element.
    • + *
    • delegate String:
      A simple selector to filter the target or look for a descendant of the target. See below for additional details.
    • + *
    • stopEvent Boolean:
      True to stop the event. That is stop propagation, and prevent the default action.
    • + *
    • preventDefault Boolean:
      True to prevent the default action
    • + *
    • stopPropagation Boolean:
      True to prevent event propagation
    • + *
    • normalized Boolean:
      False to pass a browser event to the handler function instead of an Ext.EventObject
    • + *
    • target Ext.Element:
      Only call the handler if the event was fired on the target Element, not if the event was bubbled up from a child node.
    • + *
    • delay Number:
      The number of milliseconds to delay the invocation of the handler after the event fires.
    • + *
    • single Boolean:
      True to add a handler to handle just the next firing of the event, and then remove itself.
    • + *
    • buffer Number:
      Causes the handler to be scheduled to run in an {@link Ext.util.DelayedTask} delayed + * by the specified number of milliseconds. If the event fires again within that time, the original + * handler is not invoked, but the new handler is scheduled in its place.
    • + *

    + *

    + * 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; + }, + + /** + * Recursively removes all previous added listeners from this element and its children + * @return {Ext.Element} this + */ + purgeAllListeners : function() { + Ext.EventManager.purgeElement(this, true); + return this; + }, + /** + * @private Test if size has a unit, otherwise appends the default + */ + addUnits : function(size){ + if(size === "" || size == "auto" || size === undefined){ + size = size || ''; + } else if(!isNaN(size) || !unitPattern.test(size)){ + size = size + (this.defaultUnit || 'px'); + } + return size; + }, + + /** + *

    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's dom reference. Note that event and cache removal is handled at {@link Ext#removeNode}

    + */ + remove : function(){ + var me = this, + dom = me.dom; + + if (dom) { + delete me.dom; + Ext.removeNode(dom); + } + }, + + /** + * Sets up event handlers to call the passed functions when the mouse is moved into and out of the Element. + * @param {Function} overFn The function to call when the mouse enters the Element. + * @param {Function} outFn The function to call when the mouse leaves the Element. + * @param {Object} scope (optional) The scope (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 + */ + +/** + * 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 (EC[el] && EC[el].el) { + ex = EC[el].el; + ex.dom = elm; + } else { + ex = El.addToCache(new El(elm)); + } + return ex; + } else if (el.tagName) { // dom element + if(!(id = el.id)){ + id = Ext.id(el); + } + if (EC[id] && EC[id].el) { + ex = EC[id].el; + ex.dom = el; + } else { + ex = El.addToCache(new El(el)); + } + return ex; + } else if (el instanceof El) { + if(el != docEl){ + el.dom = DOC.getElementById(el.id) || el.dom; // refresh dom element in case no longer valid, + // catch case where it hasn't been appended + } + return el; + } else if(el.isComposite) { + return el; + } else if(Ext.isArray(el)) { + return El.select(el); + } else if(el == DOC) { + // create a bogus element object representing the document object + if(!docEl){ + var f = function(){}; + f.prototype = El.prototype; + docEl = new f(); + docEl.dom = DOC; + } + return docEl; + } + return null; +}; + +El.addToCache = function(el, id){ + id = id || el.id; + EC[id] = { + el: el, + data: {}, + events: {} + }; + return el; +}; + +// private method for getting and setting element data +El.data = function(el, key, value){ + el = El.get(el); + if (!el) { + return null; + } + var c = EC[el.id].data; + if(arguments.length == 2){ + return c[key]; + }else{ + return (c[key] = value); + } +}; + +// private +// Garbage collection - uncache elements/purge listeners on orphaned elements +// so we don't hold a reference and cause the browser to retain them +function garbageCollect(){ + if(!Ext.enableGarbageCollector){ + clearInterval(El.collectorThreadId); + } else { + var eid, + el, + d, + o; + + for(eid in EC){ + o = EC[eid]; + if(o.skipGC){ + continue; + } + el = o.el; + d = el.dom; + // ------------------------------------------------------- + // Determining what is garbage: + // ------------------------------------------------------- + // !d + // dom node is null, definitely garbage + // ------------------------------------------------------- + // !d.parentNode + // no parentNode == direct orphan, definitely garbage + // ------------------------------------------------------- + // !d.offsetParent && !document.getElementById(eid) + // display none elements have no offsetParent so we will + // also try to look it up by it's id. However, check + // offsetParent first so we don't do unneeded lookups. + // This enables collection of elements that are not orphans + // directly, but somewhere up the line they have an orphan + // parent. + // ------------------------------------------------------- + if(!d || !d.parentNode || (!d.offsetParent && !DOC.getElementById(eid))){ + if(Ext.enableListenerCollection){ + Ext.EventManager.removeAll(d); + } + delete EC[eid]; + } + } + // Cleanup IE Object leaks + if (Ext.isIE) { + var t = {}; + for (eid in EC) { + t[eid] = EC[eid]; + } + EC = Ext.elCache = t; + } + } +} +El.collectorThreadId = setInterval(garbageCollect, 30000); + +var flyFn = function(){}; +flyFn.prototype = El.prototype; + +// dom is optional +El.Flyweight = function(dom){ + this.dom = dom; +}; + +El.Flyweight.prototype = new flyFn(); +El.Flyweight.prototype.isFlyweight = true; +El._flyweights = {}; + +/** + *

    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 EC; + delete El._flyweights; +}); +})(); +/** + * @class Ext.Element + */ +Ext.Element.addMethods(function(){ + var PARENTNODE = 'parentNode', + NEXTSIBLING = 'nextSibling', + PREVIOUSSIBLING = 'previousSibling', + DQ = Ext.DomQuery, + GET = Ext.get; + + return { + /** + * Looks at this node and then at parent nodes for a match of the passed simple selector (e.g. div.some-class or span:first-child) + * @param {String} selector The simple selector to test + * @param {Number/Mixed} maxDepth (optional) The max depth to search as a number or element (defaults to 50 || document.body) + * @param {Boolean} returnEl (optional) True to return a Ext.Element object instead of DOM node + * @return {HTMLElement} The matching DOM node (or null if no match was found) + */ + findParent : function(simpleSelector, maxDepth, returnEl){ + var p = this.dom, + b = document.body, + depth = 0, + stopEl; + if(Ext.isGecko && Object.prototype.toString.call(p) == '[object XULElement]') { + return null; + } + maxDepth = maxDepth || 50; + if (isNaN(maxDepth)) { + stopEl = Ext.getDom(maxDepth); + maxDepth = Number.MAX_VALUE; + } + while(p && p.nodeType == 1 && depth < maxDepth && p != b && p != stopEl){ + if(DQ.is(p, simpleSelector)){ + return returnEl ? GET(p) : p; + } + depth++; + p = p.parentNode; + } + return null; + }, + + /** + * Looks at parent nodes for a match of the passed simple selector (e.g. div.some-class or span:first-child) + * @param {String} selector The simple selector to test + * @param {Number/Mixed} maxDepth (optional) The max depth to + search as a number or element (defaults to 10 || document.body) + * @param {Boolean} returnEl (optional) True to return a Ext.Element object instead of DOM node + * @return {HTMLElement} The matching DOM node (or null if no match was found) + */ + findParentNode : function(simpleSelector, maxDepth, returnEl){ + var p = Ext.fly(this.dom.parentNode, '_internal'); + return p ? p.findParent(simpleSelector, maxDepth, returnEl) : null; + }, + + /** + * Walks up the dom looking for a parent node that matches the passed simple selector (e.g. div.some-class or span:first-child). + * This is a shortcut for findParentNode() that always returns an Ext.Element. + * @param {String} selector The simple selector to test + * @param {Number/Mixed} maxDepth (optional) The max depth to + search as a number or element (defaults to 10 || document.body) + * @return {Ext.Element} The matching DOM node (or null if no match was found) + */ + up : function(simpleSelector, maxDepth){ + return this.findParentNode(simpleSelector, maxDepth, true); + }, + + /** + * Creates a {@link Ext.CompositeElement} for child nodes based on the passed CSS selector (the selector should not contain an id). + * @param {String} selector The CSS selector + * @return {CompositeElement/CompositeElementLite} The composite element + */ + select : function(selector){ + return Ext.Element.select(selector, this.dom); + }, + + /** + * Selects child nodes based on the passed CSS selector (the selector should not contain an id). + * @param {String} selector The CSS selector + * @return {Array} An array of the matched nodes + */ + query : function(selector){ + return DQ.select(selector, this.dom); + }, + + /** + * Selects a single child at any depth below this element based on the passed CSS selector (the selector should not contain an id). + * @param {String} selector The CSS selector + * @param {Boolean} returnDom (optional) True to return the DOM node instead of Ext.Element (defaults to false) + * @return {HTMLElement/Ext.Element} The child Ext.Element (or DOM node if returnDom = true) + */ + child : function(selector, returnDom){ + var n = DQ.selectNode(selector, this.dom); + return returnDom ? n : GET(n); + }, + + /** + * Selects a single *direct* child based on the passed CSS selector (the selector should not contain an id). + * @param {String} selector The CSS selector + * @param {Boolean} returnDom (optional) True to return the DOM node instead of Ext.Element (defaults to false) + * @return {HTMLElement/Ext.Element} The child Ext.Element (or DOM node if returnDom = true) + */ + down : function(selector, returnDom){ + var n = DQ.selectNode(" > " + selector, this.dom); + return returnDom ? n : GET(n); + }, + + /** + * Gets the parent node for this element, optionally chaining up trying to match a selector + * @param {String} selector (optional) Find a parent node that matches the passed simple selector + * @param {Boolean} returnDom (optional) True to return a raw dom node instead of an Ext.Element + * @return {Ext.Element/HTMLElement} The parent node or null + */ + parent : function(selector, returnDom){ + return this.matchNode(PARENTNODE, PARENTNODE, selector, returnDom); + }, + + /** + * Gets the next sibling, skipping text nodes + * @param {String} selector (optional) Find the next sibling that matches the passed simple selector + * @param {Boolean} returnDom (optional) True to return a raw dom node instead of an Ext.Element + * @return {Ext.Element/HTMLElement} The next sibling or null + */ + next : function(selector, returnDom){ + return this.matchNode(NEXTSIBLING, NEXTSIBLING, selector, returnDom); + }, + + /** + * Gets the previous sibling, skipping text nodes + * @param {String} selector (optional) Find the previous sibling that matches the passed simple selector + * @param {Boolean} returnDom (optional) True to return a raw dom node instead of an Ext.Element + * @return {Ext.Element/HTMLElement} The previous sibling or null + */ + prev : function(selector, returnDom){ + return this.matchNode(PREVIOUSSIBLING, PREVIOUSSIBLING, selector, returnDom); + }, + + + /** + * Gets the first child, skipping text nodes + * @param {String} selector (optional) Find the next sibling that matches the passed simple selector + * @param {Boolean} returnDom (optional) True to return a raw dom node instead of an Ext.Element + * @return {Ext.Element/HTMLElement} The first child or null + */ + first : function(selector, returnDom){ + return this.matchNode(NEXTSIBLING, 'firstChild', selector, returnDom); + }, + + /** + * Gets the last child, skipping text nodes + * @param {String} selector (optional) Find the previous sibling that matches the passed simple selector + * @param {Boolean} returnDom (optional) True to return a raw dom node instead of an Ext.Element + * @return {Ext.Element/HTMLElement} The last child or null + */ + last : function(selector, returnDom){ + return this.matchNode(PREVIOUSSIBLING, 'lastChild', selector, returnDom); + }, + + matchNode : function(dir, start, selector, returnDom){ + var n = this.dom[start]; + while(n){ + if(n.nodeType == 1 && (!selector || DQ.is(n, selector))){ + return !returnDom ? GET(n) : n; + } + n = n[dir]; + } + return null; + } + } +}());/** + * @class Ext.Element + */ +Ext.Element.addMethods( +function() { + var GETDOM = Ext.getDom, + GET = Ext.get, + DH = Ext.DomHelper; + + return { + /** + * Appends the passed element(s) to this element + * @param {String/HTMLElement/Array/Element/CompositeElement} el + * @return {Ext.Element} this + */ + appendChild: function(el){ + return GET(el).appendTo(this); + }, + + /** + * Appends this element to the passed element + * @param {Mixed} el The new parent element + * @return {Ext.Element} this + */ + appendTo: function(el){ + GETDOM(el).appendChild(this.dom); + return this; + }, + + /** + * Inserts this element before the passed element in the DOM + * @param {Mixed} el The element before which this element will be inserted + * @return {Ext.Element} this + */ + insertBefore: function(el){ + (el = GETDOM(el)).parentNode.insertBefore(this.dom, el); + return this; + }, + + /** + * Inserts this element after the passed element in the DOM + * @param {Mixed} el The element to insert after + * @return {Ext.Element} this + */ + insertAfter: function(el){ + (el = GETDOM(el)).parentNode.insertBefore(this.dom, el.nextSibling); + return this; + }, + + /** + * Inserts (or creates) an element (or DomHelper config) as the first child of this element + * @param {Mixed/Object} el The id or element to insert or a DomHelper config to create and insert + * @return {Ext.Element} The new child + */ + insertFirst: function(el, returnDom){ + el = el || {}; + if(el.nodeType || el.dom || typeof el == 'string'){ // element + el = GETDOM(el); + this.dom.insertBefore(el, this.dom.firstChild); + return !returnDom ? GET(el) : el; + }else{ // dh config + return this.createChild(el, this.dom.firstChild, returnDom); + } + }, + + /** + * Replaces the passed element with this element + * @param {Mixed} el The element to replace + * @return {Ext.Element} this + */ + replace: function(el){ + el = GET(el); + this.insertBefore(el); + el.remove(); + return this; + }, + + /** + * Replaces this element with the passed element + * @param {Mixed/Object} el The new element or a DomHelper config of an element to create + * @return {Ext.Element} this + */ + replaceWith: function(el){ + var me = this; + + if(el.nodeType || el.dom || typeof el == 'string'){ + el = GETDOM(el); + me.dom.parentNode.insertBefore(el, me.dom); + }else{ + el = DH.insertBefore(me.dom, el); + } + + delete Ext.elCache[me.id]; + Ext.removeNode(me.dom); + me.id = Ext.id(me.dom = el); + Ext.Element.addToCache(me.isFlyweight ? new Ext.Element(me.dom) : me); + return me; + }, + + /** + * Creates the passed DomHelper config and appends it to this element or optionally inserts it before the passed child element. + * @param {Object} config DomHelper element config object. If no tag is specified (e.g., {tag:'input'}) then a div will be + * automatically generated with the specified attributes. + * @param {HTMLElement} insertBefore (optional) a child element of this element + * @param {Boolean} returnDom (optional) true to return the dom node instead of creating an Element + * @return {Ext.Element} The new child element + */ + createChild: function(config, insertBefore, returnDom){ + config = config || {tag:'div'}; + return insertBefore ? + DH.insertBefore(insertBefore, config, returnDom !== true) : + DH[!this.dom.firstChild ? 'overwrite' : 'append'](this.dom, config, returnDom !== true); + }, + + /** + * Creates and wraps this element with another element + * @param {Object} config (optional) DomHelper element config object for the wrapper element or null for an empty div + * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Ext.Element + * @return {HTMLElement/Element} The newly created wrapper element + */ + wrap: function(config, returnDom){ + var newEl = DH.insertBefore(this.dom, config || {tag: "div"}, !returnDom); + newEl.dom ? newEl.dom.appendChild(this.dom) : newEl.appendChild(this.dom); + return newEl; + }, + + /** + * Inserts an html fragment into this element + * @param {String} where Where to insert the html in relation to this element - beforeBegin, afterBegin, beforeEnd, afterEnd. + * @param {String} html The HTML fragment + * @param {Boolean} returnEl (optional) True to return an Ext.Element (defaults to false) + * @return {HTMLElement/Ext.Element} The inserted node (or nearest related if more than 1 inserted) + */ + insertHtml : function(where, html, returnEl){ + var el = DH.insertHtml(where, this.dom, html); + return returnEl ? Ext.get(el) : el; + } + } +}());/** + * @class Ext.Element + */ +Ext.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; + + + // private + function camelFn(m, a) { + return a.charAt(1).toUpperCase(); + } + + function chkCache(prop) { + return propCache[prop] || (propCache[prop] = prop == 'float' ? propFloat : prop.replace(camelRe, camelFn)); + } + + return { + // private ==> used by Fx + adjustWidth : function(width) { + var me = this; + var isNum = 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; + }, + + + /** + * Adds one or more CSS classes to the element. Duplicate classes are automatically filtered out. + * @param {String/Array} className The CSS class to add, or an array of classes + * @return {Ext.Element} this + */ + addClass : function(className){ + var me = this, i, len, v; + className = Ext.isArray(className) ? className : [className]; + for (i=0, len = className.length; i < len; i++) { + v = className[i]; + if (v) { + me.dom.className += (!me.hasClass(v) && v ? " " + v : ""); + }; + }; + return me; + }, + + /** + * Adds one or more CSS classes to this element and removes the same class(es) from all siblings. + * @param {String/Array} className The CSS class to add, or an array of classes + * @return {Ext.Element} this + */ + radioClass : function(className){ + var cn = this.dom.parentNode.childNodes, v; + className = Ext.isArray(className) ? className : [className]; + for (var 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); + }, + + /** + * 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, v; + className = Ext.isArray(className) ? className : [className]; + if (me.dom && me.dom.className) { + for (var i=0, len=className.length; i < len; i++) { + v = className[i]; + if(v) { + me.dom.className = me.dom.className.replace( + classReCache[v] = classReCache[v] || new RegExp('(?:^|\\s+)' + v + '(?:\\s+|$)', "g"), " " + ); + } + }; + } + return me; + }, + + /** + * Toggles the specified CSS class on this element (removes it if it already exists, otherwise adds it). + * @param {String} className The CSS class to toggle + * @return {Ext.Element} this + */ + toggleClass : function(className){ + return this.hasClass(className) ? this.removeClass(className) : this.addClass(className); + }, + + /** + * Checks if the specified CSS class exists on this element's DOM node. + * @param {String} className The CSS class to check for + * @return {Boolean} True if the class exists, else false + */ + hasClass : function(className){ + return className && (' '+this.dom.className+' ').indexOf(' '+className+' ') != -1; + }, + + /** + * Replaces a CSS class on the element with another. If the old name does not exist, the new name will simply be added. + * @param {String} oldClassName The CSS class to replace + * @param {String} newClassName The replacement CSS class + * @return {Ext.Element} this + */ + replaceClass : function(oldClassName, newClassName){ + return this.removeClass(oldClassName).addClass(newClassName); + }, + + isStyle : function(style, val) { + return this.getStyle(style) == val; + }, + + /** + * Normalizes currentStyle and computedStyle. + * @param {String} property The style property whose value is returned. + * @return {String} The current value of the style property for this element. + */ + getStyle : function(){ + return view && view.getComputedStyle ? + function(prop){ + var el = this.dom, + v, + cs, + out, + display, + wk = Ext.isWebKit, + display; + + if(el == document){ + return null; + } + prop = chkCache(prop); + // Fix bug caused by this: https://bugs.webkit.org/show_bug.cgi?id=13343 + if(wk && /marginRight/.test(prop)){ + display = this.getStyle('display'); + el.style.display = 'inline-block'; + } + out = (v = el.style[prop]) ? v : + (cs = view.getComputedStyle(el, "")) ? cs[prop] : null; + + // Webkit returns rgb values for transparent. + if(wk){ + if(out == 'rgba(0, 0, 0, 0)'){ + out = 'transparent'; + }else if(display){ + el.style.display = display; + } + } + return out; + } : + function(prop){ + var el = this.dom, + m, + cs; + + if(el == document) return null; + if (prop == 'opacity') { + if (el.style.filter.match) { + if(m = el.style.filter.match(opacityRe)){ + var fv = parseFloat(m[1]); + if(!isNaN(fv)){ + return fv ? fv / 100 : 0; + } + } + } + return 1; + } + prop = chkCache(prop); + return el.style[prop] || ((cs = el.currentStyle) ? cs[prop] : null); + }; + }(), + + /** + * Return the CSS color for the specified CSS attribute. rgb, 3 digit (like #fff) and valid values + * are convert to standard 6 digit hex color. + * @param {String} attr The css attribute + * @param {String} defaultValue The default value to use when a valid color isn't found + * @param {String} prefix (optional) defaults to #. Use an empty string when working with + * color anims. + */ + getColor : function(attr, defaultValue, prefix){ + var v = this.getStyle(attr), + color = 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, ''); + } + }else{ + style.opacity = style['-moz-opacity'] = style['-khtml-opacity'] = ''; + } + return this; + }, + + /** + * Returns the offset height of the element + * @param {Boolean} contentHeight (optional) true to get the height minus borders and padding + * @return {Number} The element's height + */ + getHeight : function(contentHeight){ + var me = this, + dom = me.dom, + hidden = Ext.isIE && me.isStyle('display', 'none'), + h = MATH.max(dom.offsetHeight, hidden ? 0 : dom.clientHeight) || 0; + + h = !contentHeight ? h : h - me.getBorderWidth("tb") - me.getPadding("tb"); + return h < 0 ? 0 : h; + }, + + /** + * Returns the offset width of the element + * @param {Boolean} contentWidth (optional) true to get the width minus borders and padding + * @return {Number} The element's width + */ + getWidth : function(contentWidth){ + var me = this, + dom = me.dom, + hidden = Ext.isIE && me.isStyle('display', 'none'), + w = MATH.max(dom.offsetWidth, hidden ? 0 : dom.clientWidth) || 0; + w = !contentWidth ? w : w - me.getBorderWidth("lr") - me.getPadding("lr"); + return w < 0 ? 0 : w; + }, + + /** + * Set the width of this Element. + * @param {Mixed} width The new width. This may be one of:
      + *
    • 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; + }, + + /** + * 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); + }, + + /** + * 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); + }, + + /** + * 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; + }, + + /** + * 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; + }, + + // private + addStyles : function(sides, styles){ + var val = 0, + m = sides.match(/\w/g), + s; + for (var i=0, len=m.length; i 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 + */ +/** + * 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; + } + } +}());(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, + + // private + getElement : function(el){ + // Set the shared flyweight dom property to the current element + var e = this.el; + e.dom = el; + e.id = el.id; + return e; + }, + + // private + transformElement : function(el){ + return Ext.getDom(el); + }, + + /** + * Returns the number of elements in this Composite. + * @return Number + */ + getCount : function(){ + return this.elements.length; + }, + /** + * Adds elements to this Composite object. + * @param {Mixed} els Either an Array of DOM elements to add, or another Composite object who's elements should be added. + * @return {CompositeElement} This Composite object. + */ + add : function(els, root){ + var me = this, + elements = me.elements; + if(!els){ + return this; + } + if(Ext.isString(els)){ + els = Ext.Element.selectorFunction(els, root); + }else if(els.isComposite){ + els = els.elements; + }else if(!Ext.isIterable(els)){ + els = [els]; + } + + for(var i = 0, len = els.length; i < len; ++i){ + elements.push(me.transformElement(els[i])); + } + return me; + }, + + invoke : function(fn, args){ + var me = this, + els = me.elements, + len = els.length, + e, + i; + + for(i = 0; i < len; i++) { + e = els[i]; + if(e){ + Ext.Element.prototype[fn].apply(me.getElement(e), args); + } + } + return me; + }, + /** + * Returns a flyweight Element of the dom element object at the specified index + * @param {Number} index + * @return {Ext.Element} + */ + item : function(index){ + var me = this, + el = me.elements[index], + out = null; + + if(el){ + out = me.getElement(el); + } + return out; + }, + + // fixes scope with flyweight + addListener : function(eventName, handler, scope, opt){ + var els = this.elements, + len = els.length, + i, e; + + for(i = 0; iCalls 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, + els = me.elements, + len = els.length, + i, e; + + for(i = 0; i + *
  • 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, + elements = me.elements, + fn = Ext.isFunction(selector) ? selector + : function(el){ + return el.is(selector); + }; + + + me.each(function(el, self, i){ + if(fn(el, i) !== false){ + els[els.length] = me.transformElement(el); + } + }); + me.elements = els; + return me; + }, + + /** + * Find the index of the passed element within the composite collection. + * @param el {Mixed} The id of an element, or an Ext.Element, or an HtmlElement to find within the composite collection. + * @return Number The index of the passed Ext.Element in the composite collection, or -1 if not found. + */ + indexOf : function(el){ + return this.elements.indexOf(this.transformElement(el)); + }, + + /** + * Replaces the specified element with the passed element. + * @param {Mixed} el The id of an element, the Element itself, the index of the element in this composite + * to replace. + * @param {Mixed} replacement The id of an element or the Element itself. + * @param {Boolean} domReplace (Optional) True to remove and replace the element in the document too. + * @return {CompositeElement} this + */ + replaceElement : function(el, replacement, domReplace){ + var index = !isNaN(el) ? el : this.indexOf(el), + d; + if(index > -1){ + replacement = Ext.getDom(replacement); + if(domReplace){ + d = this.elements[index]; + d.parentNode.insertBefore(replacement, d); + Ext.removeNode(d); + } + this.elements.splice(index, 1, replacement); + } + return this; + }, + + /** + * Removes all elements. + */ + clear : function(){ + this.elements = []; + } +}; + +Ext.CompositeElementLite.prototype.on = Ext.CompositeElementLite.prototype.addListener; + +(function(){ +var fnName, + ElProto = Ext.Element.prototype, + CelProto = Ext.CompositeElementLite.prototype; + +for(fnName in ElProto){ + if(Ext.isFunction(ElProto[fnName])){ + (function(fnName){ + CelProto[fnName] = CelProto[fnName] || function(){ + return this.invoke(fnName, arguments); + }; + }).call(CelProto, fnName); + + } +} +})(); + +if(Ext.DomQuery){ + Ext.Element.selectorFunction = Ext.DomQuery.select; +} + +/** + * Selects elements based on the passed CSS selector to enable {@link Ext.Element Element} methods + * to be applied to many related elements in one statement through the returned {@link Ext.CompositeElement CompositeElement} or + * {@link Ext.CompositeElementLite CompositeElementLite} object. + * @param {String/Array} selector The CSS selector or an array of elements + * @param {HTMLElement/String} root (optional) The root element of the query or id of the root + * @return {CompositeElementLite/CompositeElement} + * @member Ext.Element + * @method select + */ +Ext.Element.select = function(selector, root){ + var els; + if(typeof selector == "string"){ + els = Ext.Element.selectorFunction(selector, root); + }else if(selector.length !== undefined){ + els = selector; + }else{ + throw "Invalid selector"; + } + return new Ext.CompositeElementLite(els); +}; +/** + * Selects elements based on the passed CSS selector to enable {@link Ext.Element Element} methods + * to be applied to many related elements in one statement through the returned {@link Ext.CompositeElement CompositeElement} or + * {@link Ext.CompositeElementLite CompositeElementLite} object. + * @param {String/Array} selector The CSS selector or an array of elements + * @param {HTMLElement/String} root (optional) The root element of the query or id of the root + * @return {CompositeElementLite/CompositeElement} + * @member Ext + * @method select + */ +Ext.select = Ext.Element.select;(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' + + }); + + doc.body.appendChild(frame); + + //Reset the Frame to neutral domain + Ext.fly(frame).set({ + src : Ext.SSL_SECURE_URL + }); + + // 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.util.JSON + * Modified version of Douglas Crockford"s json.js that doesn"t + * mess with the Object prototype + * http://www.json.org/js.html + * @singleton + */ +Ext.util.JSON = new (function(){ + var useHasOwn = !!{}.hasOwnProperty, + isNative = function() { + var useNative = null; + + return function() { + if (useNative === null) { + useNative = Ext.USE_NATIVE_JSON && window.JSON && JSON.toString() == '[object JSON]'; + } + + return useNative; + }; + }(), + pad = function(n) { + return n < 10 ? "0" + n : n; + }, + doDecode = function(json){ + return eval("(" + json + ')'); + }, + doEncode = function(o){ + if(!Ext.isDefined(o) || o === null){ + return "null"; + }else if(Ext.isArray(o)){ + return encodeArray(o); + }else if(Ext.isDate(o)){ + return Ext.util.JSON.encodeDate(o); + }else if(Ext.isString(o)){ + return encodeString(o); + }else if(typeof o == "number"){ + //don't use isNumber here, since finite checks happen inside isNumber + return isFinite(o) ? String(o) : "null"; + }else if(Ext.isBoolean(o)){ + return String(o); + }else { + var a = ["{"], b, i, v; + for (i in o) { + // don't encode DOM objects + if(!o.getElementsByTagName){ + if(!useHasOwn || o.hasOwnProperty(i)) { + v = o[i]; + switch (typeof v) { + case "undefined": + case "function": + case "unknown": + break; + default: + if(b){ + a.push(','); + } + a.push(doEncode(i), ":", + v === null ? "null" : doEncode(v)); + b = true; + } + } + } + } + a.push("}"); + return a.join(""); + } + }, + m = { + "\b": '\\b', + "\t": '\\t', + "\n": '\\n', + "\f": '\\f', + "\r": '\\r', + '"' : '\\"', + "\\": '\\\\' + }, + encodeString = function(s){ + if (/["\\\x00-\x1f]/.test(s)) { + return '"' + s.replace(/([\x00-\x1f\\"])/g, function(a, b) { + var c = m[b]; + if(c){ + return c; + } + c = b.charCodeAt(); + return "\\u00" + + Math.floor(c / 16).toString(16) + + (c % 16).toString(16); + }) + '"'; + } + return '"' + s + '"'; + }, + encodeArray = function(o){ + var a = ["["], b, i, l = o.length, v; + for (i = 0; i < l; i += 1) { + v = o[i]; + switch (typeof v) { + case "undefined": + case "function": + case "unknown": + break; + default: + if (b) { + a.push(','); + } + a.push(v === null ? "null" : Ext.util.JSON.encode(v)); + b = true; + } + } + a.push("]"); + return a.join(""); + }; + + /** + *

    Encodes a Date. This returns the actual string which is inserted into the JSON string as the literal expression. + * The returned value includes enclosing double quotation marks.

    + *

    The default return format is "yyyy-mm-ddThh:mm:ss".

    + *

    To override this:

    
    +Ext.util.JSON.encodeDate = function(d) {
    +    return d.format('"Y-m-d"');
    +};
    +
    + * @param {Date} d The Date to encode + * @return {String} The string literal to use in a JSON string. + */ + this.encodeDate = function(o){ + return '"' + o.getFullYear() + "-" + + pad(o.getMonth() + 1) + "-" + + pad(o.getDate()) + "T" + + pad(o.getHours()) + ":" + + pad(o.getMinutes()) + ":" + + pad(o.getSeconds()) + '"'; + }; + + /** + * Encodes an Object, Array or other value + * @param {Mixed} o The variable to encode + * @return {String} The JSON string + */ + this.encode = function() { + var ec; + return function(o) { + if (!ec) { + // setup encoding function on first access + ec = isNative() ? JSON.stringify : doEncode; + } + return ec(o); + }; + }(); + + + /** + * Decodes (parses) a JSON string to an object. If the JSON is invalid, this function throws a SyntaxError unless the safe option is set. + * @param {String} json The JSON string + * @return {Object} The resulting object + */ + this.decode = function() { + var dc; + return function(json) { + if (!dc) { + // setup decoding function on first access + dc = isNative() ? JSON.parse : doDecode; + } + return dc(json); + }; + }(); + +})(); +/** + * Shorthand for {@link Ext.util.JSON#encode} + * @param {Mixed} o The variable to encode + * @return {String} The JSON string + * @member Ext + * @method encode + */ +Ext.encode = Ext.util.JSON.encode; +/** + * Shorthand for {@link Ext.util.JSON#decode} + * @param {String} json The JSON string + * @param {Boolean} safe (optional) Whether to return null or throw an exception if the JSON is invalid. + * @return {Object} The resulting object + * @member Ext + * @method decode + */ +Ext.decode = Ext.util.JSON.decode; diff --git a/test/testcase/ext-debug.js b/test/testcase/ext-debug.js new file mode 100644 index 0000000..0b2e105 --- /dev/null +++ b/test/testcase/ext-debug.js @@ -0,0 +1,18151 @@ +/* +This file is part of Ext JS 4.1 + +Copyright (c) 2011-2012 Sencha Inc + +Contact: http://www.sencha.com/contact + +GNU General Public License Usage +This file may be used under the terms of the GNU General Public License version 3.0 as +published by the Free Software Foundation and appearing in the file LICENSE included in the +packaging of this file. + +Please review the following information to ensure the GNU General Public License version 3.0 +requirements will be met: http://www.gnu.org/copyleft/gpl.html. + +If you are unsure which license is appropriate for your use, please contact the sales department +at http://www.sencha.com/contact. + +Build date: 2012-04-20 14:10:47 (19f55ab932145a3443b228045fa80950dfeaf9cc) +*/ + + +var Ext = Ext || {}; +Ext._startTime = new Date().getTime(); +(function() { + var global = this, + objectPrototype = Object.prototype, + toString = objectPrototype.toString, + enumerables = true, + enumerablesTest = { toString: 1 }, + emptyFn = function () {}, + + + callOverrideParent = function () { + var method = callOverrideParent.caller.caller; + return method.$owner.prototype[method.$name].apply(this, arguments); + }, + i; + + Ext.global = global; + + for (i in enumerablesTest) { + enumerables = null; + } + + if (enumerables) { + enumerables = ['hasOwnProperty', 'valueOf', 'isPrototypeOf', 'propertyIsEnumerable', + 'toLocaleString', 'toString', 'constructor']; + } + + + Ext.enumerables = enumerables; + + + Ext.apply = function(object, config, defaults) { + if (defaults) { + Ext.apply(object, defaults); + } + + if (object && config && typeof config === 'object') { + var i, j, k; + + for (i in config) { + object[i] = config[i]; + } + + if (enumerables) { + for (j = enumerables.length; j--;) { + k = enumerables[j]; + if (config.hasOwnProperty(k)) { + object[k] = config[k]; + } + } + } + } + + return object; + }; + + Ext.buildSettings = Ext.apply({ + baseCSSPrefix: 'x-', + scopeResetCSS: false + }, Ext.buildSettings || {}); + + Ext.apply(Ext, { + + + name: Ext.sandboxName || 'Ext', + + + emptyFn: emptyFn, + + + emptyString: new String(), + + baseCSSPrefix: Ext.buildSettings.baseCSSPrefix, + + + applyIf: function(object, config) { + var property; + + if (object) { + for (property in config) { + if (object[property] === undefined) { + object[property] = config[property]; + } + } + } + + return object; + }, + + + iterate: function(object, fn, scope) { + if (Ext.isEmpty(object)) { + return; + } + + if (scope === undefined) { + scope = object; + } + + if (Ext.isIterable(object)) { + Ext.Array.each.call(Ext.Array, object, fn, scope); + } + else { + Ext.Object.each.call(Ext.Object, object, fn, scope); + } + } + }); + + Ext.apply(Ext, { + + + extend: (function() { + + var objectConstructor = objectPrototype.constructor, + inlineOverrides = function(o) { + for (var m in o) { + if (!o.hasOwnProperty(m)) { + continue; + } + this[m] = o[m]; + } + }; + + return function(subclass, superclass, overrides) { + + if (Ext.isObject(superclass)) { + overrides = superclass; + superclass = subclass; + subclass = overrides.constructor !== objectConstructor ? overrides.constructor : function() { + superclass.apply(this, arguments); + }; + } + + + + var F = function() {}, + subclassProto, superclassProto = superclass.prototype; + + F.prototype = superclassProto; + subclassProto = subclass.prototype = new F(); + subclassProto.constructor = subclass; + subclass.superclass = superclassProto; + + if (superclassProto.constructor === objectConstructor) { + superclassProto.constructor = superclass; + } + + subclass.override = function(overrides) { + Ext.override(subclass, overrides); + }; + + subclassProto.override = inlineOverrides; + subclassProto.proto = subclassProto; + + subclass.override(overrides); + subclass.extend = function(o) { + return Ext.extend(subclass, o); + }; + + return subclass; + }; + }()), + + + override: function (target, overrides) { + if (target.$isClass) { + target.override(overrides); + } else if (typeof target == 'function') { + Ext.apply(target.prototype, overrides); + } else { + var owner = target.self, + name, value; + + if (owner && owner.$isClass) { + for (name in overrides) { + if (overrides.hasOwnProperty(name)) { + value = overrides[name]; + + if (typeof value == 'function') { + + value.$name = name; + value.$owner = owner; + value.$previous = target.hasOwnProperty(name) + ? target[name] + : callOverrideParent; + } + + target[name] = value; + } + } + } else { + Ext.apply(target, overrides); + } + } + + return target; + } + }); + + + Ext.apply(Ext, { + + + valueFrom: function(value, defaultValue, allowBlank){ + return Ext.isEmpty(value, allowBlank) ? defaultValue : value; + }, + + + typeOf: function(value) { + var type, + typeToString; + + if (value === null) { + return 'null'; + } + + type = typeof value; + + if (type === 'undefined' || type === 'string' || type === 'number' || type === 'boolean') { + return type; + } + + typeToString = toString.call(value); + + switch(typeToString) { + case '[object Array]': + return 'array'; + case '[object Date]': + return 'date'; + case '[object Boolean]': + return 'boolean'; + case '[object Number]': + return 'number'; + case '[object RegExp]': + return 'regexp'; + } + + if (type === 'function') { + return 'function'; + } + + if (type === 'object') { + if (value.nodeType !== undefined) { + if (value.nodeType === 3) { + return (/\S/).test(value.nodeValue) ? 'textnode' : 'whitespace'; + } + else { + return 'element'; + } + } + + return 'object'; + } + + }, + + + isEmpty: function(value, allowEmptyString) { + return (value === null) || (value === undefined) || (!allowEmptyString ? value === '' : false) || (Ext.isArray(value) && value.length === 0); + }, + + + isArray: ('isArray' in Array) ? Array.isArray : function(value) { + return toString.call(value) === '[object Array]'; + }, + + + isDate: function(value) { + return toString.call(value) === '[object Date]'; + }, + + + isObject: (toString.call(null) === '[object Object]') ? + function(value) { + + return value !== null && value !== undefined && toString.call(value) === '[object Object]' && value.ownerDocument === undefined; + } : + function(value) { + return toString.call(value) === '[object Object]'; + }, + + + isSimpleObject: function(value) { + return value instanceof Object && value.constructor === Object; + }, + + isPrimitive: function(value) { + var type = typeof value; + + return type === 'string' || type === 'number' || type === 'boolean'; + }, + + + isFunction: + + + (typeof document !== 'undefined' && typeof document.getElementsByTagName('body') === 'function') ? function(value) { + return toString.call(value) === '[object Function]'; + } : function(value) { + return typeof value === 'function'; + }, + + + isNumber: function(value) { + return typeof value === 'number' && isFinite(value); + }, + + + isNumeric: function(value) { + return !isNaN(parseFloat(value)) && isFinite(value); + }, + + + isString: function(value) { + return typeof value === 'string'; + }, + + + isBoolean: function(value) { + return typeof value === 'boolean'; + }, + + + isElement: function(value) { + return value ? value.nodeType === 1 : false; + }, + + + isTextNode: function(value) { + return value ? value.nodeName === "#text" : false; + }, + + + isDefined: function(value) { + return typeof value !== 'undefined'; + }, + + + isIterable: function(value) { + var type = typeof value, + checkLength = false; + if (value && type != 'string') { + + if (type == 'function') { + + + if (Ext.isSafari) { + checkLength = value instanceof NodeList || value instanceof HTMLCollection; + } + } else { + checkLength = true; + } + } + return checkLength ? value.length !== undefined : false; + } + }); + + Ext.apply(Ext, { + + + clone: function(item) { + var type, + i, + j, + k, + clone, + key; + + if (item === null || item === undefined) { + return item; + } + + + + + if (item.nodeType && item.cloneNode) { + return item.cloneNode(true); + } + + type = toString.call(item); + + + if (type === '[object Date]') { + return new Date(item.getTime()); + } + + + + if (type === '[object Array]') { + i = item.length; + + clone = []; + + while (i--) { + clone[i] = Ext.clone(item[i]); + } + } + + else if (type === '[object Object]' && item.constructor === Object) { + clone = {}; + + for (key in item) { + clone[key] = Ext.clone(item[key]); + } + + if (enumerables) { + for (j = enumerables.length; j--;) { + k = enumerables[j]; + clone[k] = item[k]; + } + } + } + + return clone || item; + }, + + + getUniqueGlobalNamespace: function() { + var uniqueGlobalNamespace = this.uniqueGlobalNamespace, + i; + + if (uniqueGlobalNamespace === undefined) { + i = 0; + + do { + uniqueGlobalNamespace = 'ExtBox' + (++i); + } while (Ext.global[uniqueGlobalNamespace] !== undefined); + + Ext.global[uniqueGlobalNamespace] = Ext; + this.uniqueGlobalNamespace = uniqueGlobalNamespace; + } + + return uniqueGlobalNamespace; + }, + + + functionFactoryCache: {}, + + cacheableFunctionFactory: function() { + var me = this, + args = Array.prototype.slice.call(arguments), + cache = me.functionFactoryCache, + idx, fn, ln; + + if (Ext.isSandboxed) { + ln = args.length; + if (ln > 0) { + ln--; + args[ln] = 'var Ext=window.' + Ext.name + ';' + args[ln]; + } + } + idx = args.join(''); + fn = cache[idx]; + if (!fn) { + fn = Function.prototype.constructor.apply(Function.prototype, args); + + cache[idx] = fn; + } + return fn; + }, + + functionFactory: function() { + var me = this, + args = Array.prototype.slice.call(arguments), + ln; + + if (Ext.isSandboxed) { + ln = args.length; + if (ln > 0) { + ln--; + args[ln] = 'var Ext=window.' + Ext.name + ';' + args[ln]; + } + } + + return Function.prototype.constructor.apply(Function.prototype, args); + }, + + + Logger: { + verbose: emptyFn, + log: emptyFn, + info: emptyFn, + warn: emptyFn, + error: function(message) { + throw new Error(message); + }, + deprecate: emptyFn + } + }); + + + Ext.type = Ext.typeOf; + +}()); + + +Ext.globalEval = Ext.global.execScript + ? function(code) { + execScript(code); + } + : function($$code) { + + + (function(){ + eval($$code); + }()); + }; + + +(function() { + + +var version = '4.1.0', Version; + Ext.Version = Version = Ext.extend(Object, { + + + constructor: function(version) { + var parts, releaseStartIndex; + + if (version instanceof Version) { + return version; + } + + this.version = this.shortVersion = String(version).toLowerCase().replace(/_/g, '.').replace(/[\-+]/g, ''); + + releaseStartIndex = this.version.search(/([^\d\.])/); + + if (releaseStartIndex !== -1) { + this.release = this.version.substr(releaseStartIndex, version.length); + this.shortVersion = this.version.substr(0, releaseStartIndex); + } + + this.shortVersion = this.shortVersion.replace(/[^\d]/g, ''); + + parts = this.version.split('.'); + + this.major = parseInt(parts.shift() || 0, 10); + this.minor = parseInt(parts.shift() || 0, 10); + this.patch = parseInt(parts.shift() || 0, 10); + this.build = parseInt(parts.shift() || 0, 10); + + return this; + }, + + + toString: function() { + return this.version; + }, + + + valueOf: function() { + return this.version; + }, + + + getMajor: function() { + return this.major || 0; + }, + + + getMinor: function() { + return this.minor || 0; + }, + + + getPatch: function() { + return this.patch || 0; + }, + + + getBuild: function() { + return this.build || 0; + }, + + + getRelease: function() { + return this.release || ''; + }, + + + isGreaterThan: function(target) { + return Version.compare(this.version, target) === 1; + }, + + + isGreaterThanOrEqual: function(target) { + return Version.compare(this.version, target) >= 0; + }, + + + isLessThan: function(target) { + return Version.compare(this.version, target) === -1; + }, + + + isLessThanOrEqual: function(target) { + return Version.compare(this.version, target) <= 0; + }, + + + equals: function(target) { + return Version.compare(this.version, target) === 0; + }, + + + match: function(target) { + target = String(target); + return this.version.substr(0, target.length) === target; + }, + + + toArray: function() { + return [this.getMajor(), this.getMinor(), this.getPatch(), this.getBuild(), this.getRelease()]; + }, + + + getShortVersion: function() { + return this.shortVersion; + }, + + + gt: function() { + return this.isGreaterThan.apply(this, arguments); + }, + + + lt: function() { + return this.isLessThan.apply(this, arguments); + }, + + + gtEq: function() { + return this.isGreaterThanOrEqual.apply(this, arguments); + }, + + + ltEq: function() { + return this.isLessThanOrEqual.apply(this, arguments); + } + }); + + Ext.apply(Version, { + + releaseValueMap: { + 'dev': -6, + 'alpha': -5, + 'a': -5, + 'beta': -4, + 'b': -4, + 'rc': -3, + '#': -2, + 'p': -1, + 'pl': -1 + }, + + + getComponentValue: function(value) { + return !value ? 0 : (isNaN(value) ? this.releaseValueMap[value] || value : parseInt(value, 10)); + }, + + + compare: function(current, target) { + var currentValue, targetValue, i; + + current = new Version(current).toArray(); + target = new Version(target).toArray(); + + for (i = 0; i < Math.max(current.length, target.length); i++) { + currentValue = this.getComponentValue(current[i]); + targetValue = this.getComponentValue(target[i]); + + if (currentValue < targetValue) { + return -1; + } else if (currentValue > targetValue) { + return 1; + } + } + + return 0; + } + }); + + Ext.apply(Ext, { + + versions: {}, + + + lastRegisteredVersion: null, + + + setVersion: function(packageName, version) { + Ext.versions[packageName] = new Version(version); + Ext.lastRegisteredVersion = Ext.versions[packageName]; + + return this; + }, + + + getVersion: function(packageName) { + if (packageName === undefined) { + return Ext.lastRegisteredVersion; + } + + return Ext.versions[packageName]; + }, + + + deprecate: function(packageName, since, closure, scope) { + if (Version.compare(Ext.getVersion(packageName), since) < 1) { + closure.call(scope); + } + } + }); + + Ext.setVersion('core', version); + +}()); + + + +Ext.String = (function() { + var trimRegex = /^[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+|[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+$/g, + escapeRe = /('|\\)/g, + formatRe = /\{(\d+)\}/g, + escapeRegexRe = /([-.*+?\^${}()|\[\]\/\\])/g, + basicTrimRe = /^\s+|\s+$/g, + whitespaceRe = /\s+/, + varReplace = /(^[^a-z]*|[^\w])/gi, + charToEntity, + entityToChar, + charToEntityRegex, + entityToCharRegex, + htmlEncodeReplaceFn = function(match, capture) { + return charToEntity[capture]; + }, + htmlDecodeReplaceFn = function(match, capture) { + return (capture in entityToChar) ? entityToChar[capture] : String.fromCharCode(parseInt(capture.substr(2), 10)); + }; + + return { + + + createVarName: function(s) { + return s.replace(varReplace, ''); + }, + + + htmlEncode: function(value) { + return (!value) ? value : String(value).replace(charToEntityRegex, htmlEncodeReplaceFn); + }, + + + htmlDecode: function(value) { + return (!value) ? value : String(value).replace(entityToCharRegex, htmlDecodeReplaceFn); + }, + + + addCharacterEntities: function(newEntities) { + var charKeys = [], + entityKeys = [], + key, echar; + for (key in newEntities) { + echar = newEntities[key]; + entityToChar[key] = echar; + charToEntity[echar] = key; + charKeys.push(echar); + entityKeys.push(key); + } + charToEntityRegex = new RegExp('(' + charKeys.join('|') + ')', 'g'); + entityToCharRegex = new RegExp('(' + entityKeys.join('|') + '|&#[0-9]{1,5};' + ')', 'g'); + }, + + + resetCharacterEntities: function() { + charToEntity = {}; + entityToChar = {}; + + this.addCharacterEntities({ + '&' : '&', + '>' : '>', + '<' : '<', + '"' : '"', + ''' : "'" + }); + }, + + + urlAppend : function(url, string) { + if (!Ext.isEmpty(string)) { + return url + (url.indexOf('?') === -1 ? '?' : '&') + string; + } + + return url; + }, + + + trim: function(string) { + return string.replace(trimRegex, ""); + }, + + + capitalize: function(string) { + return string.charAt(0).toUpperCase() + string.substr(1); + }, + + + uncapitalize: function(string) { + return string.charAt(0).toLowerCase() + string.substr(1); + }, + + + 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 vs.substr(0, index) + "..."; + } + } + return value.substr(0, len - 3) + "..."; + } + return value; + }, + + + escapeRegex: function(string) { + return string.replace(escapeRegexRe, "\\$1"); + }, + + + escape: function(string) { + return string.replace(escapeRe, "\\$1"); + }, + + + toggle: function(string, value, other) { + return string === value ? other : value; + }, + + + leftPad: function(string, size, character) { + var result = String(string); + character = character || " "; + while (result.length < size) { + result = character + result; + } + return result; + }, + + + format: function(format) { + var args = Ext.Array.toArray(arguments, 1); + return format.replace(formatRe, function(m, i) { + return args[i]; + }); + }, + + + repeat: function(pattern, count, sep) { + for (var buf = [], i = count; i--; ) { + buf.push(pattern); + } + return buf.join(sep || ''); + }, + + + splitWords: function (words) { + if (words && typeof words == 'string') { + return words.replace(basicTrimRe, '').split(whitespaceRe); + } + return words || []; + } + }; +}()); + + +Ext.String.resetCharacterEntities(); + + +Ext.htmlEncode = Ext.String.htmlEncode; + + + +Ext.htmlDecode = Ext.String.htmlDecode; + + +Ext.urlAppend = Ext.String.urlAppend; + + +Ext.Number = new function() { + + var me = this, + isToFixedBroken = (0.9).toFixed() !== '1', + math = Math; + + Ext.apply(this, { + + constrain: function(number, min, max) { + var x = parseFloat(number); + + + + + + + + + + return (x < min) ? min : ((x > max) ? max : x); + }, + + + snap : function(value, increment, minValue, maxValue) { + var m; + + + + if (value === undefined || value < minValue) { + return minValue || 0; + } + + if (increment) { + m = value % increment; + if (m !== 0) { + value -= m; + if (m * 2 >= increment) { + value += increment; + } else if (m * 2 < -increment) { + value -= increment; + } + } + } + return me.constrain(value, minValue, maxValue); + }, + + + snapInRange : function(value, increment, minValue, maxValue) { + var tween; + + + minValue = (minValue || 0); + + + if (value === undefined || value < minValue) { + return minValue; + } + + + if (increment && (tween = ((value - minValue) % increment))) { + value -= tween; + tween *= 2; + if (tween >= increment) { + value += increment; + } + } + + + if (maxValue !== undefined) { + if (value > (maxValue = me.snapInRange(maxValue, increment, minValue))) { + value = maxValue; + } + } + + return value; + }, + + + toFixed: isToFixedBroken ? function(value, precision) { + precision = precision || 0; + var pow = math.pow(10, precision); + return (math.round(value * pow) / pow).toFixed(precision); + } : function(value, precision) { + return value.toFixed(precision); + }, + + + from: function(value, defaultValue) { + if (isFinite(value)) { + value = parseFloat(value); + } + + return !isNaN(value) ? value : defaultValue; + }, + + + randomInt: function (from, to) { + return math.floor(math.random() * (to - from + 1) + from); + } + }); + + + Ext.num = function() { + return me.from.apply(this, arguments); + }; +}; + +(function() { + + var arrayPrototype = Array.prototype, + slice = arrayPrototype.slice, + supportsSplice = (function () { + var array = [], + lengthBefore, + j = 20; + + if (!array.splice) { + return false; + } + + + + + while (j--) { + array.push("A"); + } + + array.splice(15, 0, "F", "F", "F", "F", "F","F","F","F","F","F","F","F","F","F","F","F","F","F","F","F","F"); + + lengthBefore = array.length; + array.splice(13, 0, "XXX"); + + if (lengthBefore+1 != array.length) { + return false; + } + + + return true; + }()), + supportsForEach = 'forEach' in arrayPrototype, + supportsMap = 'map' in arrayPrototype, + supportsIndexOf = 'indexOf' in arrayPrototype, + supportsEvery = 'every' in arrayPrototype, + supportsSome = 'some' in arrayPrototype, + supportsFilter = 'filter' in arrayPrototype, + supportsSort = (function() { + var a = [1,2,3,4,5].sort(function(){ return 0; }); + return a[0] === 1 && a[1] === 2 && a[2] === 3 && a[3] === 4 && a[4] === 5; + }()), + supportsSliceOnNodeList = true, + ExtArray, + erase, + replace, + splice; + + try { + + if (typeof document !== 'undefined') { + slice.call(document.getElementsByTagName('body')); + } + } catch (e) { + supportsSliceOnNodeList = false; + } + + function fixArrayIndex (array, index) { + return (index < 0) ? Math.max(0, array.length + index) + : Math.min(array.length, index); + } + + + function replaceSim (array, index, removeCount, insert) { + var add = insert ? insert.length : 0, + length = array.length, + pos = fixArrayIndex(array, index), + remove, + tailOldPos, + tailNewPos, + tailCount, + lengthAfterRemove, + i; + + + if (pos === length) { + if (add) { + array.push.apply(array, insert); + } + } else { + remove = Math.min(removeCount, length - pos); + tailOldPos = pos + remove; + tailNewPos = tailOldPos + add - remove; + tailCount = length - tailOldPos; + lengthAfterRemove = length - remove; + + if (tailNewPos < tailOldPos) { + for (i = 0; i < tailCount; ++i) { + array[tailNewPos+i] = array[tailOldPos+i]; + } + } else if (tailNewPos > tailOldPos) { + for (i = tailCount; i--; ) { + array[tailNewPos+i] = array[tailOldPos+i]; + } + } + + if (add && pos === lengthAfterRemove) { + array.length = lengthAfterRemove; + array.push.apply(array, insert); + } else { + array.length = lengthAfterRemove + add; + for (i = 0; i < add; ++i) { + array[pos+i] = insert[i]; + } + } + } + + return array; + } + + function replaceNative (array, index, removeCount, insert) { + if (insert && insert.length) { + if (index < array.length) { + array.splice.apply(array, [index, removeCount].concat(insert)); + } else { + array.push.apply(array, insert); + } + } else { + array.splice(index, removeCount); + } + return array; + } + + function eraseSim (array, index, removeCount) { + return replaceSim(array, index, removeCount); + } + + function eraseNative (array, index, removeCount) { + array.splice(index, removeCount); + return array; + } + + function spliceSim (array, index, removeCount) { + var pos = fixArrayIndex(array, index), + removed = array.slice(index, fixArrayIndex(array, pos+removeCount)); + + if (arguments.length < 4) { + replaceSim(array, pos, removeCount); + } else { + replaceSim(array, pos, removeCount, slice.call(arguments, 3)); + } + + return removed; + } + + function spliceNative (array) { + return array.splice.apply(array, slice.call(arguments, 1)); + } + + erase = supportsSplice ? eraseNative : eraseSim; + replace = supportsSplice ? replaceNative : replaceSim; + splice = supportsSplice ? spliceNative : spliceSim; + + + + ExtArray = Ext.Array = { + + each: function(array, fn, scope, reverse) { + array = ExtArray.from(array); + + var i, + ln = array.length; + + if (reverse !== true) { + for (i = 0; i < ln; i++) { + if (fn.call(scope || array[i], array[i], i, array) === false) { + return i; + } + } + } + else { + for (i = ln - 1; i > -1; i--) { + if (fn.call(scope || array[i], array[i], i, array) === false) { + return i; + } + } + } + + return true; + }, + + + forEach: supportsForEach ? function(array, fn, scope) { + return array.forEach(fn, scope); + } : function(array, fn, scope) { + var i = 0, + ln = array.length; + + for (; i < ln; i++) { + fn.call(scope, array[i], i, array); + } + }, + + + indexOf: supportsIndexOf ? function(array, item, from) { + return array.indexOf(item, from); + } : function(array, item, from) { + var i, length = array.length; + + for (i = (from < 0) ? Math.max(0, length + from) : from || 0; i < length; i++) { + if (array[i] === item) { + return i; + } + } + + return -1; + }, + + + contains: supportsIndexOf ? function(array, item) { + return array.indexOf(item) !== -1; + } : function(array, item) { + var i, ln; + + for (i = 0, ln = array.length; i < ln; i++) { + if (array[i] === item) { + return true; + } + } + + return false; + }, + + + toArray: function(iterable, start, end){ + if (!iterable || !iterable.length) { + return []; + } + + if (typeof iterable === 'string') { + iterable = iterable.split(''); + } + + if (supportsSliceOnNodeList) { + return slice.call(iterable, start || 0, end || iterable.length); + } + + var array = [], + i; + + start = start || 0; + end = end ? ((end < 0) ? iterable.length + end : end) : iterable.length; + + for (i = start; i < end; i++) { + array.push(iterable[i]); + } + + return array; + }, + + + pluck: function(array, propertyName) { + var ret = [], + i, ln, item; + + for (i = 0, ln = array.length; i < ln; i++) { + item = array[i]; + + ret.push(item[propertyName]); + } + + return ret; + }, + + + map: supportsMap ? function(array, fn, scope) { + return array.map(fn, scope); + } : function(array, fn, scope) { + var results = [], + i = 0, + len = array.length; + + for (; i < len; i++) { + results[i] = fn.call(scope, array[i], i, array); + } + + return results; + }, + + + every: supportsEvery ? function(array, fn, scope) { + return array.every(fn, scope); + } : function(array, fn, scope) { + var i = 0, + ln = array.length; + + for (; i < ln; ++i) { + if (!fn.call(scope, array[i], i, array)) { + return false; + } + } + + return true; + }, + + + some: supportsSome ? function(array, fn, scope) { + return array.some(fn, scope); + } : function(array, fn, scope) { + var i = 0, + ln = array.length; + + for (; i < ln; ++i) { + if (fn.call(scope, array[i], i, array)) { + return true; + } + } + + return false; + }, + + + clean: function(array) { + var results = [], + i = 0, + ln = array.length, + item; + + for (; i < ln; i++) { + item = array[i]; + + if (!Ext.isEmpty(item)) { + results.push(item); + } + } + + return results; + }, + + + unique: function(array) { + var clone = [], + i = 0, + ln = array.length, + item; + + for (; i < ln; i++) { + item = array[i]; + + if (ExtArray.indexOf(clone, item) === -1) { + clone.push(item); + } + } + + return clone; + }, + + + filter: supportsFilter ? function(array, fn, scope) { + return array.filter(fn, scope); + } : function(array, fn, scope) { + var results = [], + i = 0, + ln = array.length; + + for (; i < ln; i++) { + if (fn.call(scope, array[i], i, array)) { + results.push(array[i]); + } + } + + return results; + }, + + + from: function(value, newReference) { + if (value === undefined || value === null) { + return []; + } + + if (Ext.isArray(value)) { + return (newReference) ? slice.call(value) : value; + } + + var type = typeof value; + + + if (value && value.length !== undefined && type !== 'string' && (type !== 'function' || !value.apply)) { + return ExtArray.toArray(value); + } + + return [value]; + }, + + + remove: function(array, item) { + var index = ExtArray.indexOf(array, item); + + if (index !== -1) { + erase(array, index, 1); + } + + return array; + }, + + + include: function(array, item) { + if (!ExtArray.contains(array, item)) { + array.push(item); + } + }, + + + clone: function(array) { + return slice.call(array); + }, + + + merge: function() { + var args = slice.call(arguments), + array = [], + i, ln; + + for (i = 0, ln = args.length; i < ln; i++) { + array = array.concat(args[i]); + } + + return ExtArray.unique(array); + }, + + + intersect: function() { + var intersection = [], + arrays = slice.call(arguments), + arraysLength, + array, + arrayLength, + minArray, + minArrayIndex, + minArrayCandidate, + minArrayLength, + element, + elementCandidate, + elementCount, + i, j, k; + + if (!arrays.length) { + return intersection; + } + + + arraysLength = arrays.length; + for (i = minArrayIndex = 0; i < arraysLength; i++) { + minArrayCandidate = arrays[i]; + if (!minArray || minArrayCandidate.length < minArray.length) { + minArray = minArrayCandidate; + minArrayIndex = i; + } + } + + minArray = ExtArray.unique(minArray); + erase(arrays, minArrayIndex, 1); + + + + + minArrayLength = minArray.length; + arraysLength = arrays.length; + for (i = 0; i < minArrayLength; i++) { + element = minArray[i]; + elementCount = 0; + + for (j = 0; j < arraysLength; j++) { + array = arrays[j]; + arrayLength = array.length; + for (k = 0; k < arrayLength; k++) { + elementCandidate = array[k]; + if (element === elementCandidate) { + elementCount++; + break; + } + } + } + + if (elementCount === arraysLength) { + intersection.push(element); + } + } + + return intersection; + }, + + + difference: function(arrayA, arrayB) { + var clone = slice.call(arrayA), + ln = clone.length, + i, j, lnB; + + for (i = 0,lnB = arrayB.length; i < lnB; i++) { + for (j = 0; j < ln; j++) { + if (clone[j] === arrayB[i]) { + erase(clone, j, 1); + j--; + ln--; + } + } + } + + return clone; + }, + + + + slice: ([1,2].slice(1, undefined).length ? + function (array, begin, end) { + return slice.call(array, begin, end); + } : + + function (array, begin, end) { + + + if (typeof begin === 'undefined') { + return slice.call(array); + } + if (typeof end === 'undefined') { + return slice.call(array, begin); + } + return slice.call(array, begin, end); + } + ), + + + sort: supportsSort ? function(array, sortFn) { + if (sortFn) { + return array.sort(sortFn); + } else { + return array.sort(); + } + } : function(array, sortFn) { + var length = array.length, + i = 0, + comparison, + j, min, tmp; + + for (; i < length; i++) { + min = i; + for (j = i + 1; j < length; j++) { + if (sortFn) { + comparison = sortFn(array[j], array[min]); + if (comparison < 0) { + min = j; + } + } else if (array[j] < array[min]) { + min = j; + } + } + if (min !== i) { + tmp = array[i]; + array[i] = array[min]; + array[min] = tmp; + } + } + + return array; + }, + + + flatten: function(array) { + var worker = []; + + function rFlatten(a) { + var i, ln, v; + + for (i = 0, ln = a.length; i < ln; i++) { + v = a[i]; + + if (Ext.isArray(v)) { + rFlatten(v); + } else { + worker.push(v); + } + } + + return worker; + } + + return rFlatten(array); + }, + + + min: function(array, comparisonFn) { + var min = array[0], + i, ln, item; + + for (i = 0, ln = array.length; i < ln; i++) { + item = array[i]; + + if (comparisonFn) { + if (comparisonFn(min, item) === 1) { + min = item; + } + } + else { + if (item < min) { + min = item; + } + } + } + + return min; + }, + + + max: function(array, comparisonFn) { + var max = array[0], + i, ln, item; + + for (i = 0, ln = array.length; i < ln; i++) { + item = array[i]; + + if (comparisonFn) { + if (comparisonFn(max, item) === -1) { + max = item; + } + } + else { + if (item > max) { + max = item; + } + } + } + + return max; + }, + + + mean: function(array) { + return array.length > 0 ? ExtArray.sum(array) / array.length : undefined; + }, + + + sum: function(array) { + var sum = 0, + i, ln, item; + + for (i = 0,ln = array.length; i < ln; i++) { + item = array[i]; + + sum += item; + } + + return sum; + }, + + + toMap: function(array, getKey, scope) { + var map = {}, + i = array.length; + + if (!getKey) { + while (i--) { + map[array[i]] = i+1; + } + } else if (typeof getKey == 'string') { + while (i--) { + map[array[i][getKey]] = i+1; + } + } else { + while (i--) { + map[getKey.call(scope, array[i])] = i+1; + } + } + + return map; + }, + + + + erase: erase, + + + insert: function (array, index, items) { + return replace(array, index, 0, items); + }, + + + replace: replace, + + + splice: splice, + + + push: function(array) { + var len = arguments.length, + i = 1, + newItem; + + if (array === undefined) { + array = []; + } else if (!Ext.isArray(array)) { + array = [array]; + } + for (; i < len; i++) { + newItem = arguments[i]; + Array.prototype.push[Ext.isArray(newItem) ? 'apply' : 'call'](array, newItem); + } + return array; + } + }; + + + Ext.each = ExtArray.each; + + + ExtArray.union = ExtArray.merge; + + + Ext.min = ExtArray.min; + + + Ext.max = ExtArray.max; + + + Ext.sum = ExtArray.sum; + + + Ext.mean = ExtArray.mean; + + + Ext.flatten = ExtArray.flatten; + + + Ext.clean = ExtArray.clean; + + + Ext.unique = ExtArray.unique; + + + Ext.pluck = ExtArray.pluck; + + + Ext.toArray = function() { + return ExtArray.toArray.apply(ExtArray, arguments); + }; +}()); + + +Ext.Function = { + + + flexSetter: function(fn) { + return function(a, b) { + var k, i; + + if (a === null) { + return this; + } + + if (typeof a !== 'string') { + for (k in a) { + if (a.hasOwnProperty(k)) { + fn.call(this, k, a[k]); + } + } + + if (Ext.enumerables) { + for (i = Ext.enumerables.length; i--;) { + k = Ext.enumerables[i]; + if (a.hasOwnProperty(k)) { + fn.call(this, k, a[k]); + } + } + } + } else { + fn.call(this, a, b); + } + + return this; + }; + }, + + + bind: function(fn, scope, args, appendArgs) { + if (arguments.length === 2) { + return function() { + return fn.apply(scope, arguments); + }; + } + + var method = fn, + slice = Array.prototype.slice; + + return function() { + var callArgs = args || arguments; + + if (appendArgs === true) { + callArgs = slice.call(arguments, 0); + callArgs = callArgs.concat(args); + } + else if (typeof appendArgs == 'number') { + callArgs = slice.call(arguments, 0); + Ext.Array.insert(callArgs, appendArgs, args); + } + + return method.apply(scope || Ext.global, callArgs); + }; + }, + + + pass: function(fn, args, scope) { + if (!Ext.isArray(args)) { + if (Ext.isIterable(args)) { + args = Ext.Array.clone(args); + } else { + args = args !== undefined ? [args] : []; + } + } + + return function() { + var fnArgs = [].concat(args); + fnArgs.push.apply(fnArgs, arguments); + return fn.apply(scope || this, fnArgs); + }; + }, + + + alias: function(object, methodName) { + return function() { + return object[methodName].apply(object, arguments); + }; + }, + + + clone: function(method) { + return function() { + return method.apply(this, arguments); + }; + }, + + + createInterceptor: function(origFn, newFn, scope, returnValue) { + 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 || Ext.global, args) !== false) ? origFn.apply(me || Ext.global, args) : returnValue || null; + }; + } + }, + + + createDelayed: function(fn, delay, scope, args, appendArgs) { + if (scope || args) { + fn = Ext.Function.bind(fn, scope, args, appendArgs); + } + + return function() { + var me = this, + args = Array.prototype.slice.call(arguments); + + setTimeout(function() { + fn.apply(me, args); + }, delay); + }; + }, + + + defer: function(fn, millis, scope, args, appendArgs) { + fn = Ext.Function.bind(fn, scope, args, appendArgs); + if (millis > 0) { + return setTimeout(Ext.supports.TimeoutActualLateness ? function () { + fn(); + } : fn, millis); + } + fn(); + return 0; + }, + + + createSequence: function(originalFn, newFn, scope) { + if (!newFn) { + return originalFn; + } + else { + return function() { + var result = originalFn.apply(this, arguments); + newFn.apply(scope || this, arguments); + return result; + }; + } + }, + + + createBuffered: function(fn, buffer, scope, args) { + var timerId; + + return function() { + var callArgs = args || Array.prototype.slice.call(arguments, 0), + me = scope || this; + + if (timerId) { + clearTimeout(timerId); + } + + timerId = setTimeout(function(){ + fn.apply(me, callArgs); + }, buffer); + }; + }, + + + createThrottled: function(fn, interval, scope) { + var lastCallTime, elapsed, lastArgs, timer, execute = function() { + fn.apply(scope || this, lastArgs); + lastCallTime = new Date().getTime(); + }; + + return function() { + elapsed = new Date().getTime() - lastCallTime; + lastArgs = arguments; + + clearTimeout(timer); + if (!lastCallTime || (elapsed >= interval)) { + execute(); + } else { + timer = setTimeout(execute, interval - elapsed); + } + }; + }, + + + + interceptBefore: function(object, methodName, fn, scope) { + var method = object[methodName] || Ext.emptyFn; + + return (object[methodName] = function() { + var ret = fn.apply(scope || this, arguments); + method.apply(this, arguments); + + return ret; + }); + }, + + + interceptAfter: function(object, methodName, fn, scope) { + var method = object[methodName] || Ext.emptyFn; + + return (object[methodName] = function() { + method.apply(this, arguments); + return fn.apply(scope || this, arguments); + }); + } +}; + + +Ext.defer = Ext.Function.alias(Ext.Function, 'defer'); + + +Ext.pass = Ext.Function.alias(Ext.Function, 'pass'); + + +Ext.bind = Ext.Function.alias(Ext.Function, 'bind'); + + + +(function() { + + +var TemplateClass = function(){}, + ExtObject = Ext.Object = { + + + chain: function (object) { + TemplateClass.prototype = object; + var result = new TemplateClass(); + TemplateClass.prototype = null; + return result; + }, + + + toQueryObjects: function(name, value, recursive) { + var self = ExtObject.toQueryObjects, + objects = [], + i, ln; + + if (Ext.isArray(value)) { + for (i = 0, ln = value.length; i < ln; i++) { + if (recursive) { + objects = objects.concat(self(name + '[' + i + ']', value[i], true)); + } + else { + objects.push({ + name: name, + value: value[i] + }); + } + } + } + else if (Ext.isObject(value)) { + for (i in value) { + if (value.hasOwnProperty(i)) { + if (recursive) { + objects = objects.concat(self(name + '[' + i + ']', value[i], true)); + } + else { + objects.push({ + name: name, + value: value[i] + }); + } + } + } + } + else { + objects.push({ + name: name, + value: value + }); + } + + return objects; + }, + + + toQueryString: function(object, recursive) { + var paramObjects = [], + params = [], + i, j, ln, paramObject, value; + + for (i in object) { + if (object.hasOwnProperty(i)) { + paramObjects = paramObjects.concat(ExtObject.toQueryObjects(i, object[i], recursive)); + } + } + + for (j = 0, ln = paramObjects.length; j < ln; j++) { + paramObject = paramObjects[j]; + value = paramObject.value; + + if (Ext.isEmpty(value)) { + value = ''; + } + else if (Ext.isDate(value)) { + value = Ext.Date.toString(value); + } + + params.push(encodeURIComponent(paramObject.name) + '=' + encodeURIComponent(String(value))); + } + + return params.join('&'); + }, + + + fromQueryString: function(queryString, recursive) { + var parts = queryString.replace(/^\?/, '').split('&'), + object = {}, + temp, components, name, value, i, ln, + part, j, subLn, matchedKeys, matchedName, + keys, key, nextKey; + + for (i = 0, ln = parts.length; i < ln; i++) { + part = parts[i]; + + if (part.length > 0) { + components = part.split('='); + name = decodeURIComponent(components[0]); + value = (components[1] !== undefined) ? decodeURIComponent(components[1]) : ''; + + if (!recursive) { + if (object.hasOwnProperty(name)) { + if (!Ext.isArray(object[name])) { + object[name] = [object[name]]; + } + + object[name].push(value); + } + else { + object[name] = value; + } + } + else { + matchedKeys = name.match(/(\[):?([^\]]*)\]/g); + matchedName = name.match(/^([^\[]+)/); + + + name = matchedName[0]; + keys = []; + + if (matchedKeys === null) { + object[name] = value; + continue; + } + + for (j = 0, subLn = matchedKeys.length; j < subLn; j++) { + key = matchedKeys[j]; + key = (key.length === 2) ? '' : key.substring(1, key.length - 1); + keys.push(key); + } + + keys.unshift(name); + + temp = object; + + for (j = 0, subLn = keys.length; j < subLn; j++) { + key = keys[j]; + + if (j === subLn - 1) { + if (Ext.isArray(temp) && key === '') { + temp.push(value); + } + else { + temp[key] = value; + } + } + else { + if (temp[key] === undefined || typeof temp[key] === 'string') { + nextKey = keys[j+1]; + + temp[key] = (Ext.isNumeric(nextKey) || nextKey === '') ? [] : {}; + } + + temp = temp[key]; + } + } + } + } + } + + return object; + }, + + + each: function(object, fn, scope) { + for (var property in object) { + if (object.hasOwnProperty(property)) { + if (fn.call(scope || object, property, object[property], object) === false) { + return; + } + } + } + }, + + + merge: function(destination) { + var i = 1, + ln = arguments.length, + mergeFn = ExtObject.merge, + cloneFn = Ext.clone, + object, key, value, sourceKey; + + for (; i < ln; i++) { + object = arguments[i]; + + for (key in object) { + value = object[key]; + if (value && value.constructor === Object) { + sourceKey = destination[key]; + if (sourceKey && sourceKey.constructor === Object) { + mergeFn(sourceKey, value); + } + else { + destination[key] = cloneFn(value); + } + } + else { + destination[key] = value; + } + } + } + + return destination; + }, + + + mergeIf: function(destination) { + var i = 1, + ln = arguments.length, + cloneFn = Ext.clone, + object, key, value; + + for (; i < ln; i++) { + object = arguments[i]; + + for (key in object) { + if (!(key in destination)) { + value = object[key]; + + if (value && value.constructor === Object) { + destination[key] = cloneFn(value); + } + else { + destination[key] = value; + } + } + } + } + + return destination; + }, + + + getKey: function(object, value) { + for (var property in object) { + if (object.hasOwnProperty(property) && object[property] === value) { + return property; + } + } + + return null; + }, + + + getValues: function(object) { + var values = [], + property; + + for (property in object) { + if (object.hasOwnProperty(property)) { + values.push(object[property]); + } + } + + return values; + }, + + + getKeys: (typeof Object.keys == 'function') + ? function(object){ + if (!object) { + return []; + } + return Object.keys(object); + } + : function(object) { + var keys = [], + property; + + for (property in object) { + if (object.hasOwnProperty(property)) { + keys.push(property); + } + } + + return keys; + }, + + + getSize: function(object) { + var size = 0, + property; + + for (property in object) { + if (object.hasOwnProperty(property)) { + size++; + } + } + + return size; + }, + + + classify: function(object) { + var prototype = object, + objectProperties = [], + propertyClassesMap = {}, + objectClass = function() { + var i = 0, + ln = objectProperties.length, + property; + + for (; i < ln; i++) { + property = objectProperties[i]; + this[property] = new propertyClassesMap[property](); + } + }, + key, value; + + for (key in object) { + if (object.hasOwnProperty(key)) { + value = object[key]; + + if (value && value.constructor === Object) { + objectProperties.push(key); + propertyClassesMap[key] = ExtObject.classify(value); + } + } + } + + objectClass.prototype = prototype; + + return objectClass; + } +}; + + +Ext.merge = Ext.Object.merge; + + +Ext.mergeIf = Ext.Object.mergeIf; + + +Ext.urlEncode = function() { + var args = Ext.Array.from(arguments), + prefix = ''; + + + if ((typeof args[1] === 'string')) { + prefix = args[1] + '&'; + args[1] = false; + } + + return prefix + ExtObject.toQueryString.apply(ExtObject, args); +}; + + +Ext.urlDecode = function() { + return ExtObject.fromQueryString.apply(ExtObject, arguments); +}; + +}()); + + + + + +(function() { + + + + +function xf(format) { + var args = Array.prototype.slice.call(arguments, 1); + return format.replace(/\{(\d+)\}/g, function(m, i) { + return args[i]; + }); +} + +Ext.Date = { + + now: Date.now || function() { + return +new Date(); + }, + + + toString: function(date) { + var pad = Ext.String.leftPad; + + return date.getFullYear() + "-" + + pad(date.getMonth() + 1, 2, '0') + "-" + + pad(date.getDate(), 2, '0') + "T" + + pad(date.getHours(), 2, '0') + ":" + + pad(date.getMinutes(), 2, '0') + ":" + + pad(date.getSeconds(), 2, '0'); + }, + + + getElapsed: function(dateA, dateB) { + return Math.abs(dateA - (dateB || new Date())); + }, + + + useStrict: false, + + + formatCodeToRegex: function(character, currentGroup) { + + var p = utilDate.parseCodes[character]; + + if (p) { + p = typeof p == 'function'? p() : p; + utilDate.parseCodes[character] = p; + } + + return p ? Ext.applyIf({ + c: p.c ? xf(p.c, currentGroup || "{0}") : p.c + }, p) : { + g: 0, + c: null, + s: Ext.String.escapeRegex(character) + }; + }, + + + parseFunctions: { + "MS": function(input, strict) { + + + var re = new RegExp('\\/Date\\(([-+])?(\\d+)(?:[+-]\\d{4})?\\)\\/'), + r = (input || '').match(re); + return r? new Date(((r[1] || '') + r[2]) * 1) : null; + } + }, + parseRegexes: [], + + + formatFunctions: { + "MS": function() { + + return '\\/Date(' + this.getTime() + ')\\/'; + } + }, + + y2kYear : 50, + + + 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 : { + January: 0, + Jan: 0, + February: 1, + Feb: 1, + March: 2, + Mar: 2, + April: 3, + Apr: 3, + May: 4, + June: 5, + Jun: 5, + July: 6, + Jul: 6, + August: 7, + Aug: 7, + September: 8, + Sep: 8, + October: 9, + Oct: 9, + November: 10, + Nov: 10, + December: 11, + Dec: 11 + }, + + + + + defaultFormat : "m/d/Y", + + + + getShortMonthName : function(month) { + return Ext.Date.monthNames[month].substring(0, 3); + }, + + + + + getShortDayName : function(day) { + return Ext.Date.dayNames[day].substring(0, 3); + }, + + + + + getMonthNumber : function(name) { + + return Ext.Date.monthNumbers[name.substring(0, 1).toUpperCase() + name.substring(1, 3).toLowerCase()]; + }, + + + + formatContainsHourInfo : (function(){ + var stripEscapeRe = /(\\.)/g, + hourInfoRe = /([gGhHisucUOPZ]|MS)/; + return function(format){ + return hourInfoRe.test(format.replace(stripEscapeRe, '')); + }; + }()), + + + formatContainsDateInfo : (function(){ + var stripEscapeRe = /(\\.)/g, + dateInfoRe = /([djzmnYycU]|MS)/; + + return function(format){ + return dateInfoRe.test(format.replace(stripEscapeRe, '')); + }; + }()), + + + unescapeFormat: (function() { + var slashRe = /\\/gi; + return function(format) { + + + + return format.replace(slashRe, ''); + } + }()), + + + formatCodes : { + d: "Ext.String.leftPad(this.getDate(), 2, '0')", + D: "Ext.Date.getShortDayName(this.getDay())", + j: "this.getDate()", + l: "Ext.Date.dayNames[this.getDay()]", + N: "(this.getDay() ? this.getDay() : 7)", + S: "Ext.Date.getSuffix(this)", + w: "this.getDay()", + z: "Ext.Date.getDayOfYear(this)", + W: "Ext.String.leftPad(Ext.Date.getWeekOfYear(this), 2, '0')", + F: "Ext.Date.monthNames[this.getMonth()]", + m: "Ext.String.leftPad(this.getMonth() + 1, 2, '0')", + M: "Ext.Date.getShortMonthName(this.getMonth())", + n: "(this.getMonth() + 1)", + t: "Ext.Date.getDaysInMonth(this)", + L: "(Ext.Date.isLeapYear(this) ? 1 : 0)", + o: "(this.getFullYear() + (Ext.Date.getWeekOfYear(this) == 1 && this.getMonth() > 0 ? +1 : (Ext.Date.getWeekOfYear(this) >= 52 && this.getMonth() < 11 ? -1 : 0)))", + Y: "Ext.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: "Ext.String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0')", + H: "Ext.String.leftPad(this.getHours(), 2, '0')", + i: "Ext.String.leftPad(this.getMinutes(), 2, '0')", + s: "Ext.String.leftPad(this.getSeconds(), 2, '0')", + u: "Ext.String.leftPad(this.getMilliseconds(), 3, '0')", + O: "Ext.Date.getGMTOffset(this)", + P: "Ext.Date.getGMTOffset(this, true)", + T: "Ext.Date.getTimezone(this)", + Z: "(this.getTimezoneOffset() * -60)", + + c: function() { + var c, code, i, l, e; + for (c = "Y-m-dTH:i:sP", code = [], i = 0, l = c.length; i < l; ++i) { + e = c.charAt(i); + code.push(e == "T" ? "'T'" : utilDate.getFormatCode(e)); + } + return code.join(" + "); + }, + + + U: "Math.round(this.getTime() / 1000)" + }, + + + isValid : function(y, m, d, h, i, s, ms) { + + h = h || 0; + i = i || 0; + s = s || 0; + ms = ms || 0; + + + var dt = utilDate.add(new Date(y < 100 ? 100 : y, m - 1, d, h, i, s, ms), utilDate.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(); + }, + + + parse : function(input, format, strict) { + var p = utilDate.parseFunctions; + if (p[format] == null) { + utilDate.createParser(format); + } + return p[format](input, Ext.isDefined(strict) ? strict : utilDate.useStrict); + }, + + + parseDate: function(input, format, strict){ + return utilDate.parse(input, format, strict); + }, + + + + getFormatCode : function(character) { + var f = utilDate.formatCodes[character]; + + if (f) { + f = typeof f == 'function'? f() : f; + utilDate.formatCodes[character] = f; + } + + + return f || ("'" + Ext.String.escape(character) + "'"); + }, + + + createFormat : function(format) { + var code = [], + special = false, + ch = '', + i; + + for (i = 0; i < format.length; ++i) { + ch = format.charAt(i); + if (!special && ch == "\\") { + special = true; + } else if (special) { + special = false; + code.push("'" + Ext.String.escape(ch) + "'"); + } else { + code.push(utilDate.getFormatCode(ch)); + } + } + utilDate.formatFunctions[format] = Ext.functionFactory("return " + code.join('+')); + }, + + + createParser : (function() { + var code = [ + "var dt, y, m, d, h, i, s, ms, o, z, zz, u, v,", + "def = Ext.Date.defaults,", + "results = String(input).match(Ext.Date.parseRegexes[{0}]);", + + "if(results){", + "{1}", + + "if(u != null){", + "v = new Date(u * 1000);", + "}else{", + + + + "dt = Ext.Date.clearTime(new Date);", + + + "y = Ext.Number.from(y, Ext.Number.from(def.y, dt.getFullYear()));", + "m = Ext.Number.from(m, Ext.Number.from(def.m - 1, dt.getMonth()));", + "d = Ext.Number.from(d, Ext.Number.from(def.d, dt.getDate()));", + + + "h = Ext.Number.from(h, Ext.Number.from(def.h, dt.getHours()));", + "i = Ext.Number.from(i, Ext.Number.from(def.i, dt.getMinutes()));", + "s = Ext.Number.from(s, Ext.Number.from(def.s, dt.getSeconds()));", + "ms = Ext.Number.from(ms, Ext.Number.from(def.ms, dt.getMilliseconds()));", + + "if(z >= 0 && y >= 0){", + + + + + + "v = Ext.Date.add(new Date(y < 100 ? 100 : y, 0, 1, h, i, s, ms), Ext.Date.YEAR, y < 100 ? y - 100 : 0);", + + + "v = !strict? v : (strict === true && (z <= 364 || (Ext.Date.isLeapYear(v) && z <= 365))? Ext.Date.add(v, Ext.Date.DAY, z) : null);", + "}else if(strict === true && !Ext.Date.isValid(y, m + 1, d, h, i, s, ms)){", + "v = null;", + "}else{", + + + "v = Ext.Date.add(new Date(y < 100 ? 100 : y, m, d, h, i, s, ms), Ext.Date.YEAR, y < 100 ? y - 100 : 0);", + "}", + "}", + "}", + + "if(v){", + + "if(zz != null){", + + "v = Ext.Date.add(v, Ext.Date.SECOND, -v.getTimezoneOffset() * 60 - zz);", + "}else if(o){", + + "v = Ext.Date.add(v, Ext.Date.MINUTE, -v.getTimezoneOffset() + (sn == '+'? -1 : 1) * (hr * 60 + mn));", + "}", + "}", + + "return v;" + ].join('\n'); + + return function(format) { + var regexNum = utilDate.parseRegexes.length, + currentGroup = 1, + calc = [], + regex = [], + special = false, + ch = "", + i = 0, + len = format.length, + atEnd = [], + obj; + + for (; i < len; ++i) { + ch = format.charAt(i); + if (!special && ch == "\\") { + special = true; + } else if (special) { + special = false; + regex.push(Ext.String.escape(ch)); + } else { + obj = utilDate.formatCodeToRegex(ch, currentGroup); + currentGroup += obj.g; + regex.push(obj.s); + if (obj.g && obj.c) { + if (obj.calcAtEnd) { + atEnd.push(obj.c); + } else { + calc.push(obj.c); + } + } + } + } + + calc = calc.concat(atEnd); + + utilDate.parseRegexes[regexNum] = new RegExp("^" + regex.join('') + "$", 'i'); + utilDate.parseFunctions[format] = Ext.functionFactory("input", "strict", xf(code, regexNum, calc.join(''))); + }; + }()), + + + parseCodes : { + + d: { + g:1, + c:"d = parseInt(results[{0}], 10);\n", + s:"(3[0-1]|[1-2][0-9]|0[1-9])" + }, + j: { + g:1, + c:"d = parseInt(results[{0}], 10);\n", + s:"(3[0-1]|[1-2][0-9]|[1-9])" + }, + D: function() { + for (var a = [], i = 0; i < 7; a.push(utilDate.getShortDayName(i)), ++i); + return { + g:0, + c:null, + s:"(?:" + a.join("|") +")" + }; + }, + l: function() { + return { + g:0, + c:null, + s:"(?:" + utilDate.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(Ext.Date.getMonthNumber(results[{0}]), 10);\n", + s:"(" + utilDate.monthNames.join("|") + ")" + }; + }, + M: function() { + for (var a = [], i = 0; i < 12; a.push(utilDate.getShortMonthName(i)), ++i); + return Ext.applyIf({ + s:"(" + a.join("|") + ")" + }, utilDate.formatCodeToRegex("F")); + }, + m: { + g:1, + c:"m = parseInt(results[{0}], 10) - 1;\n", + s:"(1[0-2]|0[1-9])" + }, + n: { + g:1, + c:"m = parseInt(results[{0}], 10) - 1;\n", + s:"(1[0-2]|[1-9])" + }, + t: { + g:0, + c:null, + s:"(?:\\d{2})" + }, + L: { + g:0, + c:null, + s:"(?:1|0)" + }, + o: function() { + return utilDate.formatCodeToRegex("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 > Ext.Date.y2kYear ? 1900 + ty : 2000 + ty;\n", + s:"(\\d{1,2})" + }, + + + a: { + 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)", + calcAtEnd: true + }, + + + A: { + 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)", + calcAtEnd: true + }, + + g: { + g:1, + c:"h = parseInt(results[{0}], 10);\n", + s:"(1[0-2]|[0-9])" + }, + G: { + g:1, + c:"h = parseInt(results[{0}], 10);\n", + s:"(2[0-3]|1[0-9]|[0-9])" + }, + h: { + g:1, + c:"h = parseInt(results[{0}], 10);\n", + s:"(1[0-2]|0[1-9])" + }, + H: { + g:1, + c:"h = parseInt(results[{0}], 10);\n", + s:"(2[0-3]|[0-1][0-9])" + }, + i: { + g:1, + c:"i = parseInt(results[{0}], 10);\n", + s:"([0-5][0-9])" + }, + s: { + g:1, + c:"s = parseInt(results[{0}], 10);\n", + s:"([0-5][0-9])" + }, + 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 + Ext.String.leftPad(hr, 2, '0') + Ext.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 + Ext.String.leftPad(hr, 2, '0') + Ext.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 = [ + utilDate.formatCodeToRegex("Y", 1), + utilDate.formatCodeToRegex("m", 2), + utilDate.formatCodeToRegex("d", 3), + utilDate.formatCodeToRegex("H", 4), + utilDate.formatCodeToRegex("i", 5), + utilDate.formatCodeToRegex("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){", + utilDate.formatCodeToRegex("P", 8).c, + "}else{", + utilDate.formatCodeToRegex("O", 8).c, + "}", + "}" + ].join('\n')} + ], + i, + l; + + for (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+)" + } + }, + + + + dateFormat: function(date, format) { + return utilDate.format(date, format); + }, + + + isEqual: function(date1, date2) { + + if (date1 && date2) { + return (date1.getTime() === date2.getTime()); + } + + return !(date1 || date2); + }, + + + format: function(date, format) { + var formatFunctions = utilDate.formatFunctions; + + if (!Ext.isDate(date)) { + return ''; + } + + if (formatFunctions[format] == null) { + utilDate.createFormat(format); + } + + return formatFunctions[format].call(date) + ''; + }, + + + getTimezone : function(date) { + + + + + + + + + + + + + return date.toString().replace(/^.* (?:\((.*)\)|([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?)$/, "$1$2").replace(/[^A-Z]/g, ""); + }, + + + getGMTOffset : function(date, colon) { + var offset = date.getTimezoneOffset(); + return (offset > 0 ? "-" : "+") + + Ext.String.leftPad(Math.floor(Math.abs(offset) / 60), 2, "0") + + (colon ? ":" : "") + + Ext.String.leftPad(Math.abs(offset % 60), 2, "0"); + }, + + + getDayOfYear: function(date) { + var num = 0, + d = Ext.Date.clone(date), + m = date.getMonth(), + i; + + for (i = 0, d.setDate(1), d.setMonth(0); i < m; d.setMonth(++i)) { + num += utilDate.getDaysInMonth(d); + } + return num + date.getDate() - 1; + }, + + + getWeekOfYear : (function() { + + var ms1d = 864e5, + ms7d = 7 * ms1d; + + return function(date) { + var DC3 = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate() + 3) / ms1d, + AWN = Math.floor(DC3 / 7), + Wyr = new Date(AWN * ms7d).getUTCFullYear(); + + return AWN - Math.floor(Date.UTC(Wyr, 0, 7) / ms7d) + 1; + }; + }()), + + + isLeapYear : function(date) { + var year = date.getFullYear(); + return !!((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year))); + }, + + + getFirstDayOfMonth : function(date) { + var day = (date.getDay() - (date.getDate() - 1)) % 7; + return (day < 0) ? (day + 7) : day; + }, + + + getLastDayOfMonth : function(date) { + return utilDate.getLastDateOfMonth(date).getDay(); + }, + + + + getFirstDateOfMonth : function(date) { + return new Date(date.getFullYear(), date.getMonth(), 1); + }, + + + getLastDateOfMonth : function(date) { + return new Date(date.getFullYear(), date.getMonth(), utilDate.getDaysInMonth(date)); + }, + + + getDaysInMonth: (function() { + var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + + return function(date) { + var m = date.getMonth(); + + return m == 1 && utilDate.isLeapYear(date) ? 29 : daysInMonth[m]; + }; + }()), + + + + getSuffix : function(date) { + switch (date.getDate()) { + case 1: + case 21: + case 31: + return "st"; + case 2: + case 22: + return "nd"; + case 3: + case 23: + return "rd"; + default: + return "th"; + } + }, + + + + clone : function(date) { + return new Date(date.getTime()); + }, + + + isDST : function(date) { + + + return new Date(date.getFullYear(), 0, 1).getTimezoneOffset() != date.getTimezoneOffset(); + }, + + + clearTime : function(date, clone) { + if (clone) { + return Ext.Date.clearTime(Ext.Date.clone(date)); + } + + + var d = date.getDate(), + hr, + c; + + + date.setHours(0); + date.setMinutes(0); + date.setSeconds(0); + date.setMilliseconds(0); + + if (date.getDate() != d) { + + + + + for (hr = 1, c = utilDate.add(date, Ext.Date.HOUR, hr); c.getDate() != d; hr++, c = utilDate.add(date, Ext.Date.HOUR, hr)); + + date.setDate(d); + date.setHours(c.getHours()); + } + + return date; + }, + + + add : function(date, interval, value) { + var d = Ext.Date.clone(date), + Date = Ext.Date, + day; + if (!interval || value === 0) { + return d; + } + + switch(interval.toLowerCase()) { + case Ext.Date.MILLI: + d.setMilliseconds(d.getMilliseconds() + value); + break; + case Ext.Date.SECOND: + d.setSeconds(d.getSeconds() + value); + break; + case Ext.Date.MINUTE: + d.setMinutes(d.getMinutes() + value); + break; + case Ext.Date.HOUR: + d.setHours(d.getHours() + value); + break; + case Ext.Date.DAY: + d.setDate(d.getDate() + value); + break; + case Ext.Date.MONTH: + day = date.getDate(); + if (day > 28) { + day = Math.min(day, Ext.Date.getLastDateOfMonth(Ext.Date.add(Ext.Date.getFirstDateOfMonth(date), Ext.Date.MONTH, value)).getDate()); + } + d.setDate(day); + d.setMonth(date.getMonth() + value); + break; + case Ext.Date.YEAR: + day = date.getDate(); + if (day > 28) { + day = Math.min(day, Ext.Date.getLastDateOfMonth(Ext.Date.add(Ext.Date.getFirstDateOfMonth(date), Ext.Date.YEAR, value)).getDate()); + } + d.setDate(day); + d.setFullYear(date.getFullYear() + value); + break; + } + return d; + }, + + + between : function(date, start, end) { + var t = date.getTime(); + return start.getTime() <= t && t <= end.getTime(); + }, + + + compat: function() { + var nativeDate = window.Date, + p, u, + statics = ['useStrict', 'formatCodeToRegex', 'parseFunctions', 'parseRegexes', 'formatFunctions', 'y2kYear', 'MILLI', 'SECOND', 'MINUTE', 'HOUR', 'DAY', 'MONTH', 'YEAR', 'defaults', 'dayNames', 'monthNames', 'monthNumbers', 'getShortMonthName', 'getShortDayName', 'getMonthNumber', 'formatCodes', 'isValid', 'parseDate', 'getFormatCode', 'createFormat', 'createParser', 'parseCodes'], + proto = ['dateFormat', 'format', 'getTimezone', 'getGMTOffset', 'getDayOfYear', 'getWeekOfYear', 'isLeapYear', 'getFirstDayOfMonth', 'getLastDayOfMonth', 'getDaysInMonth', 'getSuffix', 'clone', 'isDST', 'clearTime', 'add', 'between'], + sLen = statics.length, + pLen = proto.length, + stat, prot, s; + + + for (s = 0; s < sLen; s++) { + stat = statics[s]; + nativeDate[stat] = utilDate[stat]; + } + + + for (p = 0; p < pLen; p++) { + prot = proto[p]; + nativeDate.prototype[prot] = function() { + var args = Array.prototype.slice.call(arguments); + args.unshift(this); + return utilDate[prot].apply(utilDate, args); + }; + } + } +}; + +var utilDate = Ext.Date; + +}()); + + +(function(flexSetter) { + +var noArgs = [], + Base = function(){}; + + + Ext.apply(Base, { + $className: 'Ext.Base', + + $isClass: true, + + + create: function() { + return Ext.create.apply(Ext, [this].concat(Array.prototype.slice.call(arguments, 0))); + }, + + + extend: function(parent) { + var parentPrototype = parent.prototype, + basePrototype, prototype, i, ln, name, statics; + + prototype = this.prototype = Ext.Object.chain(parentPrototype); + prototype.self = this; + + this.superclass = prototype.superclass = parentPrototype; + + if (!parent.$isClass) { + basePrototype = Ext.Base.prototype; + + for (i in basePrototype) { + if (i in prototype) { + prototype[i] = basePrototype[i]; + } + } + } + + + statics = parentPrototype.$inheritableStatics; + + if (statics) { + for (i = 0,ln = statics.length; i < ln; i++) { + name = statics[i]; + + if (!this.hasOwnProperty(name)) { + this[name] = parent[name]; + } + } + } + + if (parent.$onExtended) { + this.$onExtended = parent.$onExtended.slice(); + } + + prototype.config = new prototype.configClass(); + prototype.initConfigList = prototype.initConfigList.slice(); + prototype.initConfigMap = Ext.clone(prototype.initConfigMap); + prototype.configMap = Ext.Object.chain(prototype.configMap); + }, + + + $onExtended: [], + + + triggerExtended: function() { + var callbacks = this.$onExtended, + ln = callbacks.length, + i, callback; + + if (ln > 0) { + for (i = 0; i < ln; i++) { + callback = callbacks[i]; + callback.fn.apply(callback.scope || this, arguments); + } + } + }, + + + onExtended: function(fn, scope) { + this.$onExtended.push({ + fn: fn, + scope: scope + }); + + return this; + }, + + + addConfig: function(config, fullMerge) { + var prototype = this.prototype, + configNameCache = Ext.Class.configNameCache, + hasConfig = prototype.configMap, + initConfigList = prototype.initConfigList, + initConfigMap = prototype.initConfigMap, + defaultConfig = prototype.config, + initializedName, name, value; + + for (name in config) { + if (config.hasOwnProperty(name)) { + if (!hasConfig[name]) { + hasConfig[name] = true; + } + + value = config[name]; + + initializedName = configNameCache[name].initialized; + + if (!initConfigMap[name] && value !== null && !prototype[initializedName]) { + initConfigMap[name] = true; + initConfigList.push(name); + } + } + } + + if (fullMerge) { + Ext.merge(defaultConfig, config); + } + else { + Ext.mergeIf(defaultConfig, config); + } + + prototype.configClass = Ext.Object.classify(defaultConfig); + }, + + + addStatics: function(members) { + var member, name; + + for (name in members) { + if (members.hasOwnProperty(name)) { + member = members[name]; + this[name] = member; + } + } + + return this; + }, + + + addInheritableStatics: function(members) { + var inheritableStatics, + hasInheritableStatics, + prototype = this.prototype, + name, member; + + inheritableStatics = prototype.$inheritableStatics; + hasInheritableStatics = prototype.$hasInheritableStatics; + + if (!inheritableStatics) { + inheritableStatics = prototype.$inheritableStatics = []; + hasInheritableStatics = prototype.$hasInheritableStatics = {}; + } + + for (name in members) { + if (members.hasOwnProperty(name)) { + member = members[name]; + this[name] = member; + + if (!hasInheritableStatics[name]) { + hasInheritableStatics[name] = true; + inheritableStatics.push(name); + } + } + } + + return this; + }, + + + addMembers: function(members) { + var prototype = this.prototype, + enumerables = Ext.enumerables, + names = [], + i, ln, name, member; + + for (name in members) { + names.push(name); + } + + if (enumerables) { + names.push.apply(names, enumerables); + } + + for (i = 0,ln = names.length; i < ln; i++) { + name = names[i]; + + if (members.hasOwnProperty(name)) { + member = members[name]; + + if (typeof member == 'function' && !member.$isClass && member !== Ext.emptyFn) { + member.$owner = this; + member.$name = name; + } + + prototype[name] = member; + } + } + + return this; + }, + + + addMember: function(name, member) { + if (typeof member == 'function' && !member.$isClass && member !== Ext.emptyFn) { + member.$owner = this; + member.$name = name; + } + + this.prototype[name] = member; + + return this; + }, + + + implement: function() { + this.addMembers.apply(this, arguments); + }, + + + borrow: function(fromClass, members) { + var prototype = this.prototype, + fromPrototype = fromClass.prototype, + i, ln, name, fn, toBorrow; + + members = Ext.Array.from(members); + + for (i = 0,ln = members.length; i < ln; i++) { + name = members[i]; + + toBorrow = fromPrototype[name]; + + if (typeof toBorrow == 'function') { + fn = Ext.Function.clone(toBorrow); + + + fn.$owner = this; + fn.$name = name; + + prototype[name] = fn; + } + else { + prototype[name] = toBorrow; + } + } + + return this; + }, + + + override: function(members) { + var me = this, + enumerables = Ext.enumerables, + target = me.prototype, + cloneFunction = Ext.Function.clone, + name, index, member, statics, names, previous; + + if (arguments.length === 2) { + name = members; + members = {}; + members[name] = arguments[1]; + enumerables = null; + } + + do { + names = []; + statics = null; + + for (name in members) { + if (name == 'statics') { + statics = members[name]; + } else if (name == 'config') { + me.addConfig(members[name], true); + } else { + names.push(name); + } + } + + if (enumerables) { + names.push.apply(names, enumerables); + } + + for (index = names.length; index--; ) { + name = names[index]; + + if (members.hasOwnProperty(name)) { + member = members[name]; + + if (typeof member == 'function' && !member.$className && member !== Ext.emptyFn) { + if (typeof member.$owner != 'undefined') { + member = cloneFunction(member); + } + + + member.$owner = me; + member.$name = name; + + previous = target[name]; + if (previous) { + member.$previous = previous; + } + } + + target[name] = member; + } + } + + target = me; + members = statics; + } while (members); + + return this; + }, + + + callParent: function(args) { + var method; + + + return (method = this.callParent.caller) && (method.$previous || + ((method = method.$owner ? method : method.caller) && + method.$owner.superclass.$class[method.$name])).apply(this, args || noArgs); + }, + + + mixin: function(name, mixinClass) { + var mixin = mixinClass.prototype, + prototype = this.prototype, + key; + + if (typeof mixin.onClassMixedIn != 'undefined') { + mixin.onClassMixedIn.call(mixinClass, this); + } + + if (!prototype.hasOwnProperty('mixins')) { + if ('mixins' in prototype) { + prototype.mixins = Ext.Object.chain(prototype.mixins); + } + else { + prototype.mixins = {}; + } + } + + for (key in mixin) { + if (key === 'mixins') { + Ext.merge(prototype.mixins, mixin[key]); + } + else if (typeof prototype[key] == 'undefined' && key != 'mixinId' && key != 'config') { + prototype[key] = mixin[key]; + } + } + + if ('config' in mixin) { + this.addConfig(mixin.config, false); + } + + prototype.mixins[name] = mixin; + }, + + + getName: function() { + return Ext.getClassName(this); + }, + + + createAlias: flexSetter(function(alias, origin) { + this.override(alias, function() { + return this[origin].apply(this, arguments); + }); + }), + + + addXtype: function(xtype) { + var prototype = this.prototype, + xtypesMap = prototype.xtypesMap, + xtypes = prototype.xtypes, + xtypesChain = prototype.xtypesChain; + + if (!prototype.hasOwnProperty('xtypesMap')) { + xtypesMap = prototype.xtypesMap = Ext.merge({}, prototype.xtypesMap || {}); + xtypes = prototype.xtypes = prototype.xtypes ? [].concat(prototype.xtypes) : []; + xtypesChain = prototype.xtypesChain = prototype.xtypesChain ? [].concat(prototype.xtypesChain) : []; + prototype.xtype = xtype; + } + + if (!xtypesMap[xtype]) { + xtypesMap[xtype] = true; + xtypes.push(xtype); + xtypesChain.push(xtype); + Ext.ClassManager.setAlias(this, 'widget.' + xtype); + } + + return this; + } + }); + + Base.implement({ + isInstance: true, + + $className: 'Ext.Base', + + configClass: Ext.emptyFn, + + initConfigList: [], + + configMap: {}, + + initConfigMap: {}, + + + statics: function() { + var method = this.statics.caller, + self = this.self; + + if (!method) { + return self; + } + + return method.$owner; + }, + + + callParent: function(args) { + + + + + var method, + superMethod = (method = this.callParent.caller) && (method.$previous || + ((method = method.$owner ? method : method.caller) && + method.$owner.superclass[method.$name])); + + + return superMethod.apply(this, args || noArgs); + }, + + + self: Base, + + + constructor: function() { + return this; + }, + + + initConfig: function(config) { + var instanceConfig = config, + configNameCache = Ext.Class.configNameCache, + defaultConfig = new this.configClass(), + defaultConfigList = this.initConfigList, + hasConfig = this.configMap, + nameMap, i, ln, name, initializedName; + + this.initConfig = Ext.emptyFn; + + this.initialConfig = instanceConfig || {}; + + this.config = config = (instanceConfig) ? Ext.merge(defaultConfig, config) : defaultConfig; + + if (instanceConfig) { + defaultConfigList = defaultConfigList.slice(); + + for (name in instanceConfig) { + if (hasConfig[name]) { + if (instanceConfig[name] !== null) { + defaultConfigList.push(name); + this[configNameCache[name].initialized] = false; + } + } + } + } + + for (i = 0,ln = defaultConfigList.length; i < ln; i++) { + name = defaultConfigList[i]; + nameMap = configNameCache[name]; + initializedName = nameMap.initialized; + + if (!this[initializedName]) { + this[initializedName] = true; + this[nameMap.set].call(this, config[name]); + } + } + + return this; + }, + + + hasConfig: function(name) { + return Boolean(this.configMap[name]); + }, + + + setConfig: function(config, applyIfNotSet) { + if (!config) { + return this; + } + + var configNameCache = Ext.Class.configNameCache, + currentConfig = this.config, + hasConfig = this.configMap, + initialConfig = this.initialConfig, + name, value; + + applyIfNotSet = Boolean(applyIfNotSet); + + for (name in config) { + if (applyIfNotSet && initialConfig.hasOwnProperty(name)) { + continue; + } + + value = config[name]; + currentConfig[name] = value; + + if (hasConfig[name]) { + this[configNameCache[name].set](value); + } + } + + return this; + }, + + + getConfig: function(name) { + var configNameCache = Ext.Class.configNameCache; + + return this[configNameCache[name].get](); + }, + + + getInitialConfig: function(name) { + var config = this.config; + + if (!name) { + return config; + } + else { + return config[name]; + } + }, + + + onConfigUpdate: function(names, callback, scope) { + var self = this.self, + i, ln, name, + updaterName, updater, newUpdater; + + names = Ext.Array.from(names); + + scope = scope || this; + + for (i = 0,ln = names.length; i < ln; i++) { + name = names[i]; + updaterName = 'update' + Ext.String.capitalize(name); + updater = this[updaterName] || Ext.emptyFn; + newUpdater = function() { + updater.apply(this, arguments); + scope[callback].apply(scope, arguments); + }; + newUpdater.$name = updaterName; + newUpdater.$owner = self; + + this[updaterName] = newUpdater; + } + }, + + destroy: function() { + this.destroy = Ext.emptyFn; + } + }); + + + Base.prototype.callOverridden = Base.prototype.callParent; + + Ext.Base = Base; + +}(Ext.Function.flexSetter)); + + +(function() { + var ExtClass, + Base = Ext.Base, + baseStaticMembers = [], + baseStaticMember, baseStaticMemberLength; + + for (baseStaticMember in Base) { + if (Base.hasOwnProperty(baseStaticMember)) { + baseStaticMembers.push(baseStaticMember); + } + } + + baseStaticMemberLength = baseStaticMembers.length; + + + function makeCtor (className) { + function constructor () { + + + return this.constructor.apply(this, arguments) || null; + } + return constructor; + } + + + Ext.Class = ExtClass = function(Class, data, onCreated) { + if (typeof Class != 'function') { + onCreated = data; + data = Class; + Class = null; + } + + if (!data) { + data = {}; + } + + Class = ExtClass.create(Class, data); + + ExtClass.process(Class, data, onCreated); + + return Class; + }; + + Ext.apply(ExtClass, { + + onBeforeCreated: function(Class, data, hooks) { + Class.addMembers(data); + + hooks.onCreated.call(Class, Class); + }, + + + create: function(Class, data) { + var name, i; + + if (!Class) { + + + + + + + + + + + + Class = makeCtor( + ); + + } + + for (i = 0; i < baseStaticMemberLength; i++) { + name = baseStaticMembers[i]; + Class[name] = Base[name]; + } + + return Class; + }, + + + process: function(Class, data, onCreated) { + var preprocessorStack = data.preprocessors || ExtClass.defaultPreprocessors, + registeredPreprocessors = this.preprocessors, + hooks = { + onBeforeCreated: this.onBeforeCreated + }, + preprocessors = [], + preprocessor, preprocessorsProperties, + i, ln, j, subLn, preprocessorProperty, process; + + delete data.preprocessors; + + for (i = 0,ln = preprocessorStack.length; i < ln; i++) { + preprocessor = preprocessorStack[i]; + + if (typeof preprocessor == 'string') { + preprocessor = registeredPreprocessors[preprocessor]; + preprocessorsProperties = preprocessor.properties; + + if (preprocessorsProperties === true) { + preprocessors.push(preprocessor.fn); + } + else if (preprocessorsProperties) { + for (j = 0,subLn = preprocessorsProperties.length; j < subLn; j++) { + preprocessorProperty = preprocessorsProperties[j]; + + if (data.hasOwnProperty(preprocessorProperty)) { + preprocessors.push(preprocessor.fn); + break; + } + } + } + } + else { + preprocessors.push(preprocessor); + } + } + + hooks.onCreated = onCreated ? onCreated : Ext.emptyFn; + hooks.preprocessors = preprocessors; + + this.doProcess(Class, data, hooks); + }, + + doProcess: function(Class, data, hooks){ + var me = this, + preprocessor = hooks.preprocessors.shift(); + + if (!preprocessor) { + hooks.onBeforeCreated.apply(me, arguments); + return; + } + + if (preprocessor.call(me, Class, data, hooks, me.doProcess) !== false) { + me.doProcess(Class, data, hooks); + } + }, + + + preprocessors: {}, + + + registerPreprocessor: function(name, fn, properties, position, relativeTo) { + if (!position) { + position = 'last'; + } + + if (!properties) { + properties = [name]; + } + + this.preprocessors[name] = { + name: name, + properties: properties || false, + fn: fn + }; + + this.setDefaultPreprocessorPosition(name, position, relativeTo); + + return this; + }, + + + getPreprocessor: function(name) { + return this.preprocessors[name]; + }, + + + getPreprocessors: function() { + return this.preprocessors; + }, + + + defaultPreprocessors: [], + + + getDefaultPreprocessors: function() { + return this.defaultPreprocessors; + }, + + + setDefaultPreprocessors: function(preprocessors) { + this.defaultPreprocessors = Ext.Array.from(preprocessors); + + return this; + }, + + + setDefaultPreprocessorPosition: function(name, offset, relativeName) { + var defaultPreprocessors = this.defaultPreprocessors, + index; + + if (typeof offset == 'string') { + if (offset === 'first') { + defaultPreprocessors.unshift(name); + + return this; + } + else if (offset === 'last') { + defaultPreprocessors.push(name); + + return this; + } + + offset = (offset === 'after') ? 1 : -1; + } + + index = Ext.Array.indexOf(defaultPreprocessors, relativeName); + + if (index !== -1) { + Ext.Array.splice(defaultPreprocessors, Math.max(0, index + offset), 0, name); + } + + return this; + }, + + configNameCache: {}, + + getConfigNameMap: function(name) { + var cache = this.configNameCache, + map = cache[name], + capitalizedName; + + if (!map) { + capitalizedName = name.charAt(0).toUpperCase() + name.substr(1); + + map = cache[name] = { + internal: name, + initialized: '_is' + capitalizedName + 'Initialized', + apply: 'apply' + capitalizedName, + update: 'update' + capitalizedName, + 'set': 'set' + capitalizedName, + 'get': 'get' + capitalizedName, + doSet : 'doSet' + capitalizedName, + changeEvent: name.toLowerCase() + 'change' + }; + } + + return map; + } + }); + + + ExtClass.registerPreprocessor('extend', function(Class, data) { + var Base = Ext.Base, + basePrototype = Base.prototype, + extend = data.extend, + Parent, parentPrototype, i; + + delete data.extend; + + if (extend && extend !== Object) { + Parent = extend; + } + else { + Parent = Base; + } + + parentPrototype = Parent.prototype; + + if (!Parent.$isClass) { + for (i in basePrototype) { + if (!parentPrototype[i]) { + parentPrototype[i] = basePrototype[i]; + } + } + } + + Class.extend(Parent); + + Class.triggerExtended.apply(Class, arguments); + + if (data.onClassExtended) { + Class.onExtended(data.onClassExtended, Class); + delete data.onClassExtended; + } + + }, true); + + + ExtClass.registerPreprocessor('statics', function(Class, data) { + Class.addStatics(data.statics); + + delete data.statics; + }); + + + ExtClass.registerPreprocessor('inheritableStatics', function(Class, data) { + Class.addInheritableStatics(data.inheritableStatics); + + delete data.inheritableStatics; + }); + + + ExtClass.registerPreprocessor('config', function(Class, data) { + var config = data.config, + prototype = Class.prototype; + + delete data.config; + + Ext.Object.each(config, function(name, value) { + var nameMap = ExtClass.getConfigNameMap(name), + internalName = nameMap.internal, + initializedName = nameMap.initialized, + applyName = nameMap.apply, + updateName = nameMap.update, + setName = nameMap.set, + getName = nameMap.get, + hasOwnSetter = (setName in prototype) || data.hasOwnProperty(setName), + hasOwnApplier = (applyName in prototype) || data.hasOwnProperty(applyName), + hasOwnUpdater = (updateName in prototype) || data.hasOwnProperty(updateName), + optimizedGetter, customGetter; + + if (value === null || (!hasOwnSetter && !hasOwnApplier && !hasOwnUpdater)) { + prototype[internalName] = value; + prototype[initializedName] = true; + } + else { + prototype[initializedName] = false; + } + + if (!hasOwnSetter) { + data[setName] = function(value) { + var oldValue = this[internalName], + applier = this[applyName], + updater = this[updateName]; + + if (!this[initializedName]) { + this[initializedName] = true; + } + + if (applier) { + value = applier.call(this, value, oldValue); + } + + if (typeof value != 'undefined') { + this[internalName] = value; + + if (updater && value !== oldValue) { + updater.call(this, value, oldValue); + } + } + + return this; + }; + } + + if (!(getName in prototype) || data.hasOwnProperty(getName)) { + customGetter = data[getName] || false; + + if (customGetter) { + optimizedGetter = function() { + return customGetter.apply(this, arguments); + }; + } + else { + optimizedGetter = function() { + return this[internalName]; + }; + } + + data[getName] = function() { + var currentGetter; + + if (!this[initializedName]) { + this[initializedName] = true; + this[setName](this.config[name]); + } + + currentGetter = this[getName]; + + if ('$previous' in currentGetter) { + currentGetter.$previous = optimizedGetter; + } + else { + this[getName] = optimizedGetter; + } + + return optimizedGetter.apply(this, arguments); + }; + } + }); + + Class.addConfig(config, true); + }); + + + ExtClass.registerPreprocessor('mixins', function(Class, data, hooks) { + var mixins = data.mixins, + name, mixin, i, ln; + + delete data.mixins; + + Ext.Function.interceptBefore(hooks, 'onCreated', function() { + if (mixins instanceof Array) { + for (i = 0,ln = mixins.length; i < ln; i++) { + mixin = mixins[i]; + name = mixin.prototype.mixinId || mixin.$className; + + Class.mixin(name, mixin); + } + } + else { + for (var mixinName in mixins) { + if (mixins.hasOwnProperty(mixinName)) { + Class.mixin(mixinName, mixins[mixinName]); + } + } + } + }); + }); + + + Ext.extend = function(Class, Parent, members) { + if (arguments.length === 2 && Ext.isObject(Parent)) { + members = Parent; + Parent = Class; + Class = null; + } + + var cls; + + if (!Parent) { + throw new Error("[Ext.extend] Attempting to extend from a class which has not been loaded on the page."); + } + + members.extend = Parent; + members.preprocessors = [ + 'extend' + ,'statics' + ,'inheritableStatics' + ,'mixins' + ,'config' + ]; + + if (Class) { + cls = new ExtClass(Class, members); + } + else { + cls = new ExtClass(members); + } + + cls.prototype.override = function(o) { + for (var m in o) { + if (o.hasOwnProperty(m)) { + this[m] = o[m]; + } + } + }; + + return cls; + }; + +}()); + + +(function(Class, alias, arraySlice, arrayFrom, global) { + + var Manager = Ext.ClassManager = { + + + classes: {}, + + + existCache: {}, + + + namespaceRewrites: [{ + from: 'Ext.', + to: Ext + }], + + + maps: { + alternateToName: {}, + aliasToName: {}, + nameToAliases: {}, + nameToAlternates: {} + }, + + + enableNamespaceParseCache: true, + + + namespaceParseCache: {}, + + + instantiators: [], + + + isCreated: function(className) { + var existCache = this.existCache, + i, ln, part, root, parts; + + + if (this.classes[className] || existCache[className]) { + return true; + } + + root = global; + parts = this.parseNamespace(className); + + for (i = 0, ln = parts.length; i < ln; i++) { + part = parts[i]; + + if (typeof part != 'string') { + root = part; + } else { + if (!root || !root[part]) { + return false; + } + + root = root[part]; + } + } + + existCache[className] = true; + + this.triggerCreated(className); + + return true; + }, + + + createdListeners: [], + + + nameCreatedListeners: {}, + + + triggerCreated: function(className) { + var listeners = this.createdListeners, + nameListeners = this.nameCreatedListeners, + alternateNames = this.maps.nameToAlternates[className], + names = [className], + i, ln, j, subLn, listener, name; + + for (i = 0,ln = listeners.length; i < ln; i++) { + listener = listeners[i]; + listener.fn.call(listener.scope, className); + } + + if (alternateNames) { + names.push.apply(names, alternateNames); + } + + for (i = 0,ln = names.length; i < ln; i++) { + name = names[i]; + listeners = nameListeners[name]; + + if (listeners) { + for (j = 0,subLn = listeners.length; j < subLn; j++) { + listener = listeners[j]; + listener.fn.call(listener.scope, name); + } + delete nameListeners[name]; + } + } + }, + + + onCreated: function(fn, scope, className) { + var listeners = this.createdListeners, + nameListeners = this.nameCreatedListeners, + listener = { + fn: fn, + scope: scope + }; + + if (className) { + if (this.isCreated(className)) { + fn.call(scope, className); + return; + } + + if (!nameListeners[className]) { + nameListeners[className] = []; + } + + nameListeners[className].push(listener); + } + else { + listeners.push(listener); + } + }, + + + parseNamespace: function(namespace) { + + var cache = this.namespaceParseCache, + parts, + rewrites, + root, + name, + rewrite, from, to, i, ln; + + if (this.enableNamespaceParseCache) { + if (cache.hasOwnProperty(namespace)) { + return cache[namespace]; + } + } + + parts = []; + rewrites = this.namespaceRewrites; + root = global; + name = namespace; + + for (i = 0, ln = rewrites.length; i < ln; i++) { + rewrite = rewrites[i]; + from = rewrite.from; + to = rewrite.to; + + if (name === from || name.substring(0, from.length) === from) { + name = name.substring(from.length); + + if (typeof to != 'string') { + root = to; + } else { + parts = parts.concat(to.split('.')); + } + + break; + } + } + + parts.push(root); + + parts = parts.concat(name.split('.')); + + if (this.enableNamespaceParseCache) { + cache[namespace] = parts; + } + + return parts; + }, + + + setNamespace: function(name, value) { + var root = global, + parts = this.parseNamespace(name), + ln = parts.length - 1, + leaf = parts[ln], + i, part; + + for (i = 0; i < ln; i++) { + part = parts[i]; + + if (typeof part != 'string') { + root = part; + } else { + if (!root[part]) { + root[part] = {}; + } + + root = root[part]; + } + } + + root[leaf] = value; + + return root[leaf]; + }, + + + createNamespaces: function() { + var root = global, + parts, part, i, j, ln, subLn; + + for (i = 0, ln = arguments.length; i < ln; i++) { + parts = this.parseNamespace(arguments[i]); + + for (j = 0, subLn = parts.length; j < subLn; j++) { + part = parts[j]; + + if (typeof part != 'string') { + root = part; + } else { + if (!root[part]) { + root[part] = {}; + } + + root = root[part]; + } + } + } + + return root; + }, + + + set: function(name, value) { + var me = this, + maps = me.maps, + nameToAlternates = maps.nameToAlternates, + targetName = me.getName(value), + alternates; + + me.classes[name] = me.setNamespace(name, value); + + if (targetName && targetName !== name) { + maps.alternateToName[name] = targetName; + alternates = nameToAlternates[targetName] || (nameToAlternates[targetName] = []); + alternates.push(name); + } + + return this; + }, + + + get: function(name) { + var classes = this.classes, + root, + parts, + part, i, ln; + + if (classes[name]) { + return classes[name]; + } + + root = global; + parts = this.parseNamespace(name); + + for (i = 0, ln = parts.length; i < ln; i++) { + part = parts[i]; + + if (typeof part != 'string') { + root = part; + } else { + if (!root || !root[part]) { + return null; + } + + root = root[part]; + } + } + + return root; + }, + + + setAlias: function(cls, alias) { + var aliasToNameMap = this.maps.aliasToName, + nameToAliasesMap = this.maps.nameToAliases, + className; + + if (typeof cls == 'string') { + className = cls; + } else { + className = this.getName(cls); + } + + if (alias && aliasToNameMap[alias] !== className) { + + aliasToNameMap[alias] = className; + } + + if (!nameToAliasesMap[className]) { + nameToAliasesMap[className] = []; + } + + if (alias) { + Ext.Array.include(nameToAliasesMap[className], alias); + } + + return this; + }, + + + getByAlias: function(alias) { + return this.get(this.getNameByAlias(alias)); + }, + + + getNameByAlias: function(alias) { + return this.maps.aliasToName[alias] || ''; + }, + + + getNameByAlternate: function(alternate) { + return this.maps.alternateToName[alternate] || ''; + }, + + + getAliasesByName: function(name) { + return this.maps.nameToAliases[name] || []; + }, + + + getName: function(object) { + return object && object.$className || ''; + }, + + + getClass: function(object) { + return object && object.self || null; + }, + + + create: function(className, data, createdFn) { + + data.$className = className; + + return new Class(data, function() { + var postprocessorStack = data.postprocessors || Manager.defaultPostprocessors, + registeredPostprocessors = Manager.postprocessors, + postprocessors = [], + postprocessor, i, ln, j, subLn, postprocessorProperties, postprocessorProperty; + + delete data.postprocessors; + + for (i = 0,ln = postprocessorStack.length; i < ln; i++) { + postprocessor = postprocessorStack[i]; + + if (typeof postprocessor == 'string') { + postprocessor = registeredPostprocessors[postprocessor]; + postprocessorProperties = postprocessor.properties; + + if (postprocessorProperties === true) { + postprocessors.push(postprocessor.fn); + } + else if (postprocessorProperties) { + for (j = 0,subLn = postprocessorProperties.length; j < subLn; j++) { + postprocessorProperty = postprocessorProperties[j]; + + if (data.hasOwnProperty(postprocessorProperty)) { + postprocessors.push(postprocessor.fn); + break; + } + } + } + } + else { + postprocessors.push(postprocessor); + } + } + + data.postprocessors = postprocessors; + data.createdFn = createdFn; + Manager.processCreate(className, this, data); + }); + }, + + processCreate: function(className, cls, clsData){ + var me = this, + postprocessor = clsData.postprocessors.shift(), + createdFn = clsData.createdFn; + + if (!postprocessor) { + me.set(className, cls); + + if (createdFn) { + createdFn.call(cls, cls); + } + + me.triggerCreated(className); + return; + } + + if (postprocessor.call(me, className, cls, clsData, me.processCreate) !== false) { + me.processCreate(className, cls, clsData); + } + }, + + createOverride: function (className, data, createdFn) { + var me = this, + overriddenClassName = data.override, + requires = data.requires, + uses = data.uses, + classReady = function () { + var cls, temp; + + if (requires) { + temp = requires; + requires = null; + + + + + Ext.Loader.require(temp, classReady); + } else { + + + cls = me.get(overriddenClassName); + + + delete data.override; + delete data.requires; + delete data.uses; + + Ext.override(cls, data); + + + + + me.triggerCreated(className); + + if (uses) { + Ext.Loader.addUsedClasses(uses); + } + + if (createdFn) { + createdFn.call(cls); + } + } + }; + + me.existCache[className] = true; + + + me.onCreated(classReady, me, overriddenClassName); + + return me; + }, + + + instantiateByAlias: function() { + var alias = arguments[0], + args = arraySlice.call(arguments), + className = this.getNameByAlias(alias); + + if (!className) { + className = this.maps.aliasToName[alias]; + + + + Ext.syncRequire(className); + } + + args[0] = className; + + return this.instantiate.apply(this, args); + }, + + + instantiate: function() { + var name = arguments[0], + nameType = typeof name, + args = arraySlice.call(arguments, 1), + alias = name, + possibleName, cls; + + if (nameType != 'function') { + if (nameType != 'string' && args.length === 0) { + args = [name]; + name = name.xclass; + } + + + cls = this.get(name); + } + else { + cls = name; + } + + + if (!cls) { + possibleName = this.getNameByAlias(name); + + if (possibleName) { + name = possibleName; + + cls = this.get(name); + } + } + + + if (!cls) { + possibleName = this.getNameByAlternate(name); + + if (possibleName) { + name = possibleName; + + cls = this.get(name); + } + } + + + if (!cls) { + + Ext.syncRequire(name); + + cls = this.get(name); + } + + + return this.getInstantiator(args.length)(cls, args); + }, + + + dynInstantiate: function(name, args) { + args = arrayFrom(args, true); + args.unshift(name); + + return this.instantiate.apply(this, args); + }, + + + getInstantiator: function(length) { + var instantiators = this.instantiators, + instantiator, + i, + args; + + instantiator = instantiators[length]; + + if (!instantiator) { + i = length; + args = []; + + for (i = 0; i < length; i++) { + args.push('a[' + i + ']'); + } + + instantiator = instantiators[length] = new Function('c', 'a', 'return new c(' + args.join(',') + ')'); + } + + return instantiator; + }, + + + postprocessors: {}, + + + defaultPostprocessors: [], + + + registerPostprocessor: function(name, fn, properties, position, relativeTo) { + if (!position) { + position = 'last'; + } + + if (!properties) { + properties = [name]; + } + + this.postprocessors[name] = { + name: name, + properties: properties || false, + fn: fn + }; + + this.setDefaultPostprocessorPosition(name, position, relativeTo); + + return this; + }, + + + setDefaultPostprocessors: function(postprocessors) { + this.defaultPostprocessors = arrayFrom(postprocessors); + + return this; + }, + + + setDefaultPostprocessorPosition: function(name, offset, relativeName) { + var defaultPostprocessors = this.defaultPostprocessors, + index; + + if (typeof offset == 'string') { + if (offset === 'first') { + defaultPostprocessors.unshift(name); + + return this; + } + else if (offset === 'last') { + defaultPostprocessors.push(name); + + return this; + } + + offset = (offset === 'after') ? 1 : -1; + } + + index = Ext.Array.indexOf(defaultPostprocessors, relativeName); + + if (index !== -1) { + Ext.Array.splice(defaultPostprocessors, Math.max(0, index + offset), 0, name); + } + + return this; + }, + + + getNamesByExpression: function(expression) { + var nameToAliasesMap = this.maps.nameToAliases, + names = [], + name, alias, aliases, possibleName, regex, i, ln; + + + if (expression.indexOf('*') !== -1) { + expression = expression.replace(/\*/g, '(.*?)'); + regex = new RegExp('^' + expression + '$'); + + for (name in nameToAliasesMap) { + if (nameToAliasesMap.hasOwnProperty(name)) { + aliases = nameToAliasesMap[name]; + + if (name.search(regex) !== -1) { + names.push(name); + } + else { + for (i = 0, ln = aliases.length; i < ln; i++) { + alias = aliases[i]; + + if (alias.search(regex) !== -1) { + names.push(name); + break; + } + } + } + } + } + + } else { + possibleName = this.getNameByAlias(expression); + + if (possibleName) { + names.push(possibleName); + } else { + possibleName = this.getNameByAlternate(expression); + + if (possibleName) { + names.push(possibleName); + } else { + names.push(expression); + } + } + } + + return names; + } + }; + + + Manager.registerPostprocessor('alias', function(name, cls, data) { + var aliases = data.alias, + i, ln; + + for (i = 0,ln = aliases.length; i < ln; i++) { + alias = aliases[i]; + + this.setAlias(cls, alias); + } + + }, ['xtype', 'alias']); + + + Manager.registerPostprocessor('singleton', function(name, cls, data, fn) { + fn.call(this, name, new cls(), data); + return false; + }); + + + Manager.registerPostprocessor('alternateClassName', function(name, cls, data) { + var alternates = data.alternateClassName, + i, ln, alternate; + + if (!(alternates instanceof Array)) { + alternates = [alternates]; + } + + for (i = 0, ln = alternates.length; i < ln; i++) { + alternate = alternates[i]; + + + this.set(alternate, cls); + } + }); + + Ext.apply(Ext, { + + create: alias(Manager, 'instantiate'), + + + widget: function(name, config) { + + + + + + + + var xtype = name, + alias, className, T, load; + + if (typeof xtype != 'string') { + + config = name; + xtype = config.xtype; + } else { + config = config || {}; + } + + if (config.isComponent) { + return config; + } + + alias = 'widget.' + xtype; + className = Manager.getNameByAlias(alias); + + + if (!className) { + load = true; + } + + T = Manager.get(className); + if (load || !T) { + return Manager.instantiateByAlias(alias, config); + } + return new T(config); + }, + + + createByAlias: alias(Manager, 'instantiateByAlias'), + + + define: function (className, data, createdFn) { + if (data.override) { + return Manager.createOverride.apply(Manager, arguments); + } + + return Manager.create.apply(Manager, arguments); + }, + + + getClassName: alias(Manager, 'getName'), + + + getDisplayName: function(object) { + if (object) { + if (object.displayName) { + return object.displayName; + } + + if (object.$name && object.$class) { + return Ext.getClassName(object.$class) + '#' + object.$name; + } + + if (object.$className) { + return object.$className; + } + } + + return 'Anonymous'; + }, + + + getClass: alias(Manager, 'getClass'), + + + namespace: alias(Manager, 'createNamespaces') + }); + + + Ext.createWidget = Ext.widget; + + + Ext.ns = Ext.namespace; + + Class.registerPreprocessor('className', function(cls, data) { + if (data.$className) { + cls.$className = data.$className; + } + }, true, 'first'); + + Class.registerPreprocessor('alias', function(cls, data) { + var prototype = cls.prototype, + xtypes = arrayFrom(data.xtype), + aliases = arrayFrom(data.alias), + widgetPrefix = 'widget.', + widgetPrefixLength = widgetPrefix.length, + xtypesChain = Array.prototype.slice.call(prototype.xtypesChain || []), + xtypesMap = Ext.merge({}, prototype.xtypesMap || {}), + i, ln, alias, xtype; + + for (i = 0,ln = aliases.length; i < ln; i++) { + alias = aliases[i]; + + + if (alias.substring(0, widgetPrefixLength) === widgetPrefix) { + xtype = alias.substring(widgetPrefixLength); + Ext.Array.include(xtypes, xtype); + } + } + + cls.xtype = data.xtype = xtypes[0]; + data.xtypes = xtypes; + + for (i = 0,ln = xtypes.length; i < ln; i++) { + xtype = xtypes[i]; + + if (!xtypesMap[xtype]) { + xtypesMap[xtype] = true; + xtypesChain.push(xtype); + } + } + + data.xtypesChain = xtypesChain; + data.xtypesMap = xtypesMap; + + Ext.Function.interceptAfter(data, 'onClassCreated', function() { + var mixins = prototype.mixins, + key, mixin; + + for (key in mixins) { + if (mixins.hasOwnProperty(key)) { + mixin = mixins[key]; + + xtypes = mixin.xtypes; + + if (xtypes) { + for (i = 0,ln = xtypes.length; i < ln; i++) { + xtype = xtypes[i]; + + if (!xtypesMap[xtype]) { + xtypesMap[xtype] = true; + xtypesChain.push(xtype); + } + } + } + } + } + }); + + for (i = 0,ln = xtypes.length; i < ln; i++) { + xtype = xtypes[i]; + + + Ext.Array.include(aliases, widgetPrefix + xtype); + } + + data.alias = aliases; + + }, ['xtype', 'alias']); + +}(Ext.Class, Ext.Function.alias, Array.prototype.slice, Ext.Array.from, Ext.global)); + + + +Ext.Loader = new function() { + var Loader = this, + Manager = Ext.ClassManager, + Class = Ext.Class, + flexSetter = Ext.Function.flexSetter, + alias = Ext.Function.alias, + pass = Ext.Function.pass, + defer = Ext.Function.defer, + arrayErase = Ext.Array.erase, + dependencyProperties = ['extend', 'mixins', 'requires'], + isInHistory = {}, + history = [], + slashDotSlashRe = /\/\.\//g, + dotRe = /\./g; + + Ext.apply(Loader, { + + + isInHistory: isInHistory, + + + history: history, + + + config: { + + enabled: false, + + + scriptChainDelay : false, + + + disableCaching: true, + + + disableCachingParam: '_dc', + + + garbageCollect : false, + + + paths: { + 'Ext': '.' + }, + + + preserveScripts : true, + + + scriptCharset : undefined + }, + + + setConfig: function(name, value) { + if (Ext.isObject(name) && arguments.length === 1) { + Ext.merge(Loader.config, name); + } + else { + Loader.config[name] = (Ext.isObject(value)) ? Ext.merge(Loader.config[name], value) : value; + } + + return Loader; + }, + + + getConfig: function(name) { + if (name) { + return Loader.config[name]; + } + + return Loader.config; + }, + + + setPath: flexSetter(function(name, path) { + Loader.config.paths[name] = path; + + return Loader; + }), + + + getPath: function(className) { + var path = '', + paths = Loader.config.paths, + prefix = Loader.getPrefix(className); + + if (prefix.length > 0) { + if (prefix === className) { + return paths[prefix]; + } + + path = paths[prefix]; + className = className.substring(prefix.length + 1); + } + + if (path.length > 0) { + path += '/'; + } + + return path.replace(slashDotSlashRe, '/') + className.replace(dotRe, "/") + '.js'; + }, + + + getPrefix: function(className) { + var paths = Loader.config.paths, + prefix, deepestPrefix = ''; + + if (paths.hasOwnProperty(className)) { + return className; + } + + for (prefix in paths) { + if (paths.hasOwnProperty(prefix) && prefix + '.' === className.substring(0, prefix.length + 1)) { + if (prefix.length > deepestPrefix.length) { + deepestPrefix = prefix; + } + } + } + + return deepestPrefix; + }, + + + isAClassNameWithAKnownPrefix: function(className) { + var prefix = Loader.getPrefix(className); + + + return prefix !== '' && prefix !== className; + }, + + + require: function(expressions, fn, scope, excludes) { + if (fn) { + fn.call(scope); + } + }, + + + syncRequire: function() {}, + + + exclude: function(excludes) { + return { + require: function(expressions, fn, scope) { + return Loader.require(expressions, fn, scope, excludes); + }, + + syncRequire: function(expressions, fn, scope) { + return Loader.syncRequire(expressions, fn, scope, excludes); + } + }; + }, + + + onReady: function(fn, scope, withDomReady, options) { + var oldFn; + + if (withDomReady !== false && Ext.onDocumentReady) { + oldFn = fn; + + fn = function() { + Ext.onDocumentReady(oldFn, scope, options); + }; + } + + fn.call(scope); + } + }); + + var queue = [], + isClassFileLoaded = {}, + isFileLoaded = {}, + classNameToFilePathMap = {}, + scriptElements = {}, + readyListeners = [], + usedClasses = [], + requiresMap = {}; + + Ext.apply(Loader, { + + documentHead: typeof document != 'undefined' && (document.head || document.getElementsByTagName('head')[0]), + + + isLoading: false, + + + queue: queue, + + + isClassFileLoaded: isClassFileLoaded, + + + isFileLoaded: isFileLoaded, + + + readyListeners: readyListeners, + + + optionalRequires: usedClasses, + + + requiresMap: requiresMap, + + + numPendingFiles: 0, + + + numLoadedFiles: 0, + + + hasFileLoadError: false, + + + classNameToFilePathMap: classNameToFilePathMap, + + + scriptsLoading: 0, + + + syncModeEnabled: false, + + scriptElements: scriptElements, + + + refreshQueue: function() { + var ln = queue.length, + i, item, j, requires; + + + + if (!ln && !Loader.scriptsLoading) { + return Loader.triggerReady(); + } + + for (i = 0; i < ln; i++) { + item = queue[i]; + + if (item) { + requires = item.requires; + + + + if (requires.length > Loader.numLoadedFiles) { + continue; + } + + + for (j = 0; j < requires.length; ) { + if (Manager.isCreated(requires[j])) { + + arrayErase(requires, j, 1); + } + else { + j++; + } + } + + + if (item.requires.length === 0) { + arrayErase(queue, i, 1); + item.callback.call(item.scope); + Loader.refreshQueue(); + break; + } + } + } + + return Loader; + }, + + + injectScriptElement: function(url, onLoad, onError, scope, charset) { + var script = document.createElement('script'), + dispatched = false, + config = Loader.config, + onLoadFn = function() { + + if(!dispatched) { + dispatched = true; + script.onload = script.onreadystatechange = script.onerror = null; + if (typeof config.scriptChainDelay == 'number') { + + defer(onLoad, config.scriptChainDelay, scope); + } else { + onLoad.call(scope); + } + Loader.cleanupScriptElement(script, config.preserveScripts === false, config.garbageCollect); + } + + }, + onErrorFn = function(arg) { + defer(onError, 1, scope); + Loader.cleanupScriptElement(script, config.preserveScripts === false, config.garbageCollect); + }; + + script.type = 'text/javascript'; + script.onerror = onErrorFn; + charset = charset || config.scriptCharset; + if (charset) { + script.charset = charset; + } + + + if ('addEventListener' in script ) { + script.onload = onLoadFn; + } else if ('readyState' in script) { + script.onreadystatechange = function() { + if ( this.readyState == 'loaded' || this.readyState == 'complete' ) { + onLoadFn(); + } + }; + } else { + script.onload = onLoadFn; + } + + script.src = url; + (Loader.documentHead || document.getElementsByTagName('head')[0]).appendChild(script); + + return script; + }, + + + removeScriptElement: function(url) { + if (scriptElements[url]) { + Loader.cleanupScriptElement(scriptElements[url], true, !!Loader.getConfig('garbageCollect')); + delete scriptElements[url]; + } + + return Loader; + }, + + + cleanupScriptElement: function(script, remove, collect) { + var prop; + script.onload = script.onreadystatechange = script.onerror = null; + if (remove) { + Ext.removeNode(script); + if (collect) { + for (prop in script) { + try { + script[prop] = null; + delete script[prop]; + } catch (cleanEx) { + + } + } + } + } + + return Loader; + }, + + + loadScript: function (options) { + var config = Loader.getConfig(), + isString = typeof options == 'string', + url = isString ? options : options.url, + onError = !isString && options.onError, + onLoad = !isString && options.onLoad, + scope = !isString && options.scope, + onScriptError = function() { + Loader.numPendingFiles--; + Loader.scriptsLoading--; + + if (onError) { + onError.call(scope, "Failed loading '" + url + "', please verify that the file exists"); + } + + if (Loader.numPendingFiles + Loader.scriptsLoading === 0) { + Loader.refreshQueue(); + } + }, + onScriptLoad = function () { + Loader.numPendingFiles--; + Loader.scriptsLoading--; + + if (onLoad) { + onLoad.call(scope); + } + + if (Loader.numPendingFiles + Loader.scriptsLoading === 0) { + Loader.refreshQueue(); + } + }, + src; + + Loader.isLoading = true; + Loader.numPendingFiles++; + Loader.scriptsLoading++; + + src = config.disableCaching ? + (url + '?' + config.disableCachingParam + '=' + Ext.Date.now()) : url; + + scriptElements[url] = Loader.injectScriptElement(src, onScriptLoad, onScriptError); + }, + + + loadScriptFile: function(url, onLoad, onError, scope, synchronous) { + if (isFileLoaded[url]) { + return Loader; + } + + var config = Loader.getConfig(), + noCacheUrl = url + (config.disableCaching ? ('?' + config.disableCachingParam + '=' + Ext.Date.now()) : ''), + isCrossOriginRestricted = false, + xhr, status, onScriptError; + + scope = scope || Loader; + + Loader.isLoading = true; + + if (!synchronous) { + onScriptError = function() { + }; + + scriptElements[url] = Loader.injectScriptElement(noCacheUrl, onLoad, onScriptError, scope); + } else { + if (typeof XMLHttpRequest != 'undefined') { + xhr = new XMLHttpRequest(); + } else { + xhr = new ActiveXObject('Microsoft.XMLHTTP'); + } + + try { + xhr.open('GET', noCacheUrl, false); + xhr.send(null); + } catch (e) { + isCrossOriginRestricted = true; + } + + status = (xhr.status === 1223) ? 204 : + (xhr.status === 0 && (self.location || {}).protocol == 'file:') ? 200 : xhr.status; + + isCrossOriginRestricted = isCrossOriginRestricted || (status === 0); + + if (isCrossOriginRestricted + ) { + } + else if ((status >= 200 && status < 300) || (status === 304) + ) { + + + Ext.globalEval(xhr.responseText + "\n//@ sourceURL=" + url); + + onLoad.call(scope); + } + else { + } + + + xhr = null; + } + }, + + + syncRequire: function() { + var syncModeEnabled = Loader.syncModeEnabled; + + if (!syncModeEnabled) { + Loader.syncModeEnabled = true; + } + + Loader.require.apply(Loader, arguments); + + if (!syncModeEnabled) { + Loader.syncModeEnabled = false; + } + + Loader.refreshQueue(); + }, + + + require: function(expressions, fn, scope, excludes) { + var excluded = {}, + included = {}, + excludedClassNames = [], + possibleClassNames = [], + classNames = [], + references = [], + callback, + syncModeEnabled, + filePath, expression, exclude, className, + possibleClassName, i, j, ln, subLn; + + if (excludes) { + + excludes = (typeof excludes === 'string') ? [ excludes ] : excludes; + + for (i = 0,ln = excludes.length; i < ln; i++) { + exclude = excludes[i]; + + if (typeof exclude == 'string' && exclude.length > 0) { + excludedClassNames = Manager.getNamesByExpression(exclude); + + for (j = 0,subLn = excludedClassNames.length; j < subLn; j++) { + excluded[excludedClassNames[j]] = true; + } + } + } + } + + + expressions = (typeof expressions === 'string') ? [ expressions ] : (expressions ? expressions : []); + + if (fn) { + if (fn.length > 0) { + callback = function() { + var classes = [], + i, ln; + + for (i = 0,ln = references.length; i < ln; i++) { + classes.push(Manager.get(references[i])); + } + + return fn.apply(this, classes); + }; + } + else { + callback = fn; + } + } + else { + callback = Ext.emptyFn; + } + + scope = scope || Ext.global; + + for (i = 0,ln = expressions.length; i < ln; i++) { + expression = expressions[i]; + + if (typeof expression == 'string' && expression.length > 0) { + possibleClassNames = Manager.getNamesByExpression(expression); + subLn = possibleClassNames.length; + + for (j = 0; j < subLn; j++) { + possibleClassName = possibleClassNames[j]; + + if (excluded[possibleClassName] !== true) { + references.push(possibleClassName); + + if (!Manager.isCreated(possibleClassName) && !included[possibleClassName]) { + included[possibleClassName] = true; + classNames.push(possibleClassName); + } + } + } + } + } + + + + if (classNames.length > 0) { + if (!Loader.config.enabled) { + throw new Error("Ext.Loader is not enabled, so dependencies cannot be resolved dynamically. " + + "Missing required class" + ((classNames.length > 1) ? "es" : "") + ": " + classNames.join(', ')); + } + } + else { + callback.call(scope); + return Loader; + } + + syncModeEnabled = Loader.syncModeEnabled; + + if (!syncModeEnabled) { + queue.push({ + requires: classNames.slice(), + + callback: callback, + scope: scope + }); + } + + ln = classNames.length; + + for (i = 0; i < ln; i++) { + className = classNames[i]; + + filePath = Loader.getPath(className); + + + + + if (syncModeEnabled && isClassFileLoaded.hasOwnProperty(className)) { + Loader.numPendingFiles--; + Loader.removeScriptElement(filePath); + delete isClassFileLoaded[className]; + } + + if (!isClassFileLoaded.hasOwnProperty(className)) { + isClassFileLoaded[className] = false; + + classNameToFilePathMap[className] = filePath; + + Loader.numPendingFiles++; + Loader.loadScriptFile( + filePath, + pass(Loader.onFileLoaded, [className, filePath], Loader), + pass(Loader.onFileLoadError, [className, filePath], Loader), + Loader, + syncModeEnabled + ); + } + } + + if (syncModeEnabled) { + callback.call(scope); + + if (ln === 1) { + return Manager.get(className); + } + } + + return Loader; + }, + + + onFileLoaded: function(className, filePath) { + Loader.numLoadedFiles++; + + isClassFileLoaded[className] = true; + isFileLoaded[filePath] = true; + + Loader.numPendingFiles--; + + if (Loader.numPendingFiles === 0) { + Loader.refreshQueue(); + } + + }, + + + onFileLoadError: function(className, filePath, errorMessage, isSynchronous) { + Loader.numPendingFiles--; + Loader.hasFileLoadError = true; + + }, + + + addUsedClasses: function (classes) { + var cls, i, ln; + + if (classes) { + classes = (typeof classes == 'string') ? [classes] : classes; + for (i = 0, ln = classes.length; i < ln; i++) { + cls = classes[i]; + if (typeof cls == 'string' && !Ext.Array.contains(usedClasses, cls)) { + usedClasses.push(cls); + } + } + } + + return Loader; + }, + + + triggerReady: function() { + var listener, + i, refClasses = usedClasses; + + if (Loader.isLoading) { + Loader.isLoading = false; + + if (refClasses.length !== 0) { + + refClasses = refClasses.slice(); + usedClasses.length = 0; + + + Loader.require(refClasses, Loader.triggerReady, Loader); + return Loader; + } + } + + + + + while (readyListeners.length && !Loader.isLoading) { + + + listener = readyListeners.shift(); + listener.fn.call(listener.scope); + } + + return Loader; + }, + + + onReady: function(fn, scope, withDomReady, options) { + var oldFn; + + if (withDomReady !== false && Ext.onDocumentReady) { + oldFn = fn; + + fn = function() { + Ext.onDocumentReady(oldFn, scope, options); + }; + } + + if (!Loader.isLoading) { + fn.call(scope); + } + else { + readyListeners.push({ + fn: fn, + scope: scope + }); + } + }, + + + historyPush: function(className) { + if (className && isClassFileLoaded.hasOwnProperty(className) && !isInHistory[className]) { + isInHistory[className] = true; + history.push(className); + } + return Loader; + } + }); + + + Ext.disableCacheBuster = function (disable, path) { + var date = new Date(); + date.setTime(date.getTime() + (disable ? 10*365 : -1) * 24*60*60*1000); + date = date.toGMTString(); + document.cookie = 'ext-cache=1; expires=' + date + '; path='+(path || '/'); + }; + + + + Ext.require = alias(Loader, 'require'); + + + Ext.syncRequire = alias(Loader, 'syncRequire'); + + + Ext.exclude = alias(Loader, 'exclude'); + + + Ext.onReady = function(fn, scope, options) { + Loader.onReady(fn, scope, true, options); + }; + + + Class.registerPreprocessor('loader', function(cls, data, hooks, continueFn) { + var me = this, + dependencies = [], + dependency, + className = Manager.getName(cls), + i, j, ln, subLn, value, propertyName, propertyValue, + requiredMap, requiredDep; + + + + for (i = 0,ln = dependencyProperties.length; i < ln; i++) { + propertyName = dependencyProperties[i]; + + if (data.hasOwnProperty(propertyName)) { + propertyValue = data[propertyName]; + + if (typeof propertyValue == 'string') { + dependencies.push(propertyValue); + } + else if (propertyValue instanceof Array) { + for (j = 0, subLn = propertyValue.length; j < subLn; j++) { + value = propertyValue[j]; + + if (typeof value == 'string') { + dependencies.push(value); + } + } + } + else if (typeof propertyValue != 'function') { + for (j in propertyValue) { + if (propertyValue.hasOwnProperty(j)) { + value = propertyValue[j]; + + if (typeof value == 'string') { + dependencies.push(value); + } + } + } + } + } + } + + if (dependencies.length === 0) { + return; + } + + + Loader.require(dependencies, function() { + for (i = 0,ln = dependencyProperties.length; i < ln; i++) { + propertyName = dependencyProperties[i]; + + if (data.hasOwnProperty(propertyName)) { + propertyValue = data[propertyName]; + + if (typeof propertyValue == 'string') { + data[propertyName] = Manager.get(propertyValue); + } + else if (propertyValue instanceof Array) { + for (j = 0, subLn = propertyValue.length; j < subLn; j++) { + value = propertyValue[j]; + + if (typeof value == 'string') { + data[propertyName][j] = Manager.get(value); + } + } + } + else if (typeof propertyValue != 'function') { + for (var k in propertyValue) { + if (propertyValue.hasOwnProperty(k)) { + value = propertyValue[k]; + + if (typeof value == 'string') { + data[propertyName][k] = Manager.get(value); + } + } + } + } + } + } + + continueFn.call(me, cls, data, hooks); + }); + + return false; + }, true, 'after', 'className'); + + + Manager.registerPostprocessor('uses', function(name, cls, data) { + var uses = data.uses; + if (uses) { + Loader.addUsedClasses(uses); + } + }); + + Manager.onCreated(Loader.historyPush); +}; + + +Ext.Error = Ext.extend(Error, { + statics: { + + ignore: false, + + + + + + raise: function(err){ + err = err || {}; + if (Ext.isString(err)) { + err = { msg: err }; + } + + var method = this.raise.caller, + msg; + + if (method) { + if (method.$name) { + err.sourceMethod = method.$name; + } + if (method.$owner) { + err.sourceClass = method.$owner.$className; + } + } + + if (Ext.Error.handle(err) !== true) { + msg = Ext.Error.prototype.toString.call(err); + + Ext.log({ + msg: msg, + level: 'error', + dump: err, + stack: true + }); + + throw new Ext.Error(err); + } + }, + + + handle: function(){ + return Ext.Error.ignore; + } + }, + + + name: 'Ext.Error', + + + constructor: function(config){ + if (Ext.isString(config)) { + config = { msg: config }; + } + + var me = this; + + Ext.apply(me, config); + + me.message = me.message || me.msg; + + }, + + + toString: function(){ + var me = this, + className = me.sourceClass ? me.sourceClass : '', + methodName = me.sourceMethod ? '.' + me.sourceMethod + '(): ' : '', + msg = me.msg || '(No description provided)'; + + return className + methodName + msg; + } +}); + + +Ext.deprecated = function (suggestion) { + return Ext.emptyFn; +}; + + + + + +Ext.JSON = (new(function() { + var me = this, + encodingFunction, + decodingFunction, + useNative = null, + useHasOwn = !! {}.hasOwnProperty, + isNative = function() { + if (useNative === null) { + useNative = Ext.USE_NATIVE_JSON && window.JSON && JSON.toString() == '[object JSON]'; + } + return useNative; + }, + pad = function(n) { + return n < 10 ? "0" + n : n; + }, + doDecode = function(json) { + return eval("(" + json + ')'); + }, + doEncode = function(o, newline) { + + if (o === null || o === undefined) { + return "null"; + } else if (Ext.isDate(o)) { + return Ext.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 if (o.toJSON) { + return o.toJSON(); + } else if (Ext.isArray(o)) { + return encodeArray(o, newline); + } else if (Ext.isObject(o)) { + return encodeObject(o, newline); + } else if (typeof o === "function") { + return "null"; + } + return 'undefined'; + }, + m = { + "\b": '\\b', + "\t": '\\t', + "\n": '\\n', + "\f": '\\f', + "\r": '\\r', + '"': '\\"', + "\\": '\\\\', + '\x0b': '\\u000b' + }, + charToReplace = /[\\\"\x00-\x1f\x7f-\uffff]/g, + encodeString = function(s) { + return '"' + s.replace(charToReplace, function(a) { + var c = m[a]; + return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); + }) + '"'; + }, + + + encodeArray = function(o, newline) { + + var a = ["[", ""], + len = o.length, + i; + for (i = 0; i < len; i += 1) { + a.push(doEncode(o[i]), ','); + } + + a[a.length - 1] = ']'; + return a.join(""); + }, + + encodeObject = function(o, newline) { + + var a = ["{", ""], + i; + for (i in o) { + if (!useHasOwn || o.hasOwnProperty(i)) { + a.push(doEncode(i), ":", doEncode(o[i]), ','); + } + } + + a[a.length - 1] = '}'; + return a.join(""); + }; + + + me.encodeValue = doEncode; + + + me.encodeDate = function(o) { + return '"' + o.getFullYear() + "-" + + pad(o.getMonth() + 1) + "-" + + pad(o.getDate()) + "T" + + pad(o.getHours()) + ":" + + pad(o.getMinutes()) + ":" + + pad(o.getSeconds()) + '"'; + }; + + + me.encode = function(o) { + if (!encodingFunction) { + + encodingFunction = isNative() ? JSON.stringify : me.encodeValue; + } + return encodingFunction(o); + }; + + + me.decode = function(json, safe) { + if (!decodingFunction) { + + decodingFunction = isNative() ? JSON.parse : doDecode; + } + try { + return decodingFunction(json); + } catch (e) { + if (safe === true) { + return null; + } + Ext.Error.raise({ + sourceClass: "Ext.JSON", + sourceMethod: "decode", + msg: "You're trying to decode an invalid JSON String: " + json + }); + } + }; +})()); + +Ext.encode = Ext.JSON.encode; + +Ext.decode = Ext.JSON.decode; + +Ext.apply(Ext, { + userAgent: navigator.userAgent.toLowerCase(), + cache: {}, + idSeed: 1000, + windowId: 'ext-window', + documentId: 'ext-document', + + + isReady: false, + + + enableGarbageCollector: true, + + + enableListenerCollection: true, + + addCacheEntry: function(id, el, dom) { + dom = dom || el.dom; + + + var key = id || (el && el.id) || dom.id, + entry = Ext.cache[key] || (Ext.cache[key] = { + data: {}, + events: {}, + + dom: dom, + + + skipGarbageCollection: !!(dom.getElementById || dom.navigator) + }); + + if (el) { + el.$cache = entry; + + + entry.el = el; + } + + return entry; + }, + + + id: function(el, prefix) { + var me = this, + sandboxPrefix = ''; + el = Ext.getDom(el, true) || {}; + if (el === document) { + el.id = me.documentId; + } + else if (el === window) { + el.id = me.windowId; + } + if (!el.id) { + if (me.isSandboxed) { + sandboxPrefix = Ext.sandboxName.toLowerCase() + '-'; + } + el.id = sandboxPrefix + (prefix || "ext-gen") + (++Ext.idSeed); + } + return el.id; + }, + + escapeId: (function(){ + var validIdRe = /^[a-zA-Z_][a-zA-Z0-9_\-]*$/i, + escapeRx = /([\W]{1})/g, + leadingNumRx = /^(\d)/g, + escapeFn = function(match, capture){ + return "\\" + capture; + }, + numEscapeFn = function(match, capture){ + return '\\00' + capture.charCodeAt(0).toString(16) + ' '; + }; + + return function(id) { + return validIdRe.test(id) + ? id + + + : id.replace(escapeRx, escapeFn) + .replace(leadingNumRx, numEscapeFn); + }; + }()), + + + getBody: (function() { + var body; + return function() { + return body || (body = Ext.get(document.body)); + }; + }()), + + + getHead: (function() { + var head; + return function() { + return head || (head = Ext.get(document.getElementsByTagName("head")[0])); + }; + }()), + + + getDoc: (function() { + var doc; + return function() { + return doc || (doc = Ext.get(document)); + }; + }()), + + + getCmp: function(id) { + return Ext.ComponentManager.get(id); + }, + + + getOrientation: function() { + return window.innerHeight > window.innerWidth ? 'portrait' : 'landscape'; + }, + + + destroy: function() { + var ln = arguments.length, + i, arg; + + for (i = 0; i < ln; i++) { + arg = arguments[i]; + if (arg) { + if (Ext.isArray(arg)) { + this.destroy.apply(this, arg); + } + else if (Ext.isFunction(arg.destroy)) { + arg.destroy(); + } + else if (arg.dom) { + arg.remove(); + } + } + } + }, + + + callback: function(callback, scope, args, delay){ + if(Ext.isFunction(callback)){ + args = args || []; + scope = scope || window; + if (delay) { + Ext.defer(callback, delay, scope, args); + } else { + callback.apply(scope, args); + } + } + }, + + + htmlEncode : function(value) { + return Ext.String.htmlEncode(value); + }, + + + htmlDecode : function(value) { + return Ext.String.htmlDecode(value); + }, + + + urlAppend : function(url, s) { + return Ext.String.urlAppend(url, s); + } +}); + + +Ext.ns = Ext.namespace; + + +window.undefined = window.undefined; + + +(function(){ + + var check = function(regex){ + return regex.test(Ext.userAgent); + }, + isStrict = document.compatMode == "CSS1Compat", + version = function (is, regex) { + var m; + return (is && (m = regex.exec(Ext.userAgent))) ? parseFloat(m[1]) : 0; + }, + docMode = document.documentMode, + isOpera = check(/opera/), + isOpera10_5 = isOpera && check(/version\/10\.5/), + isChrome = check(/\bchrome\b/), + isWebKit = check(/webkit/), + isSafari = !isChrome && check(/safari/), + isSafari2 = isSafari && check(/applewebkit\/4/), + isSafari3 = isSafari && check(/version\/3/), + isSafari4 = isSafari && check(/version\/4/), + isSafari5_0 = isSafari && check(/version\/5\.0/), + isSafari5 = isSafari && check(/version\/5/), + isIE = !isOpera && check(/msie/), + isIE7 = isIE && ((check(/msie 7/) && docMode != 8 && docMode != 9) || docMode == 7), + isIE8 = isIE && ((check(/msie 8/) && docMode != 7 && docMode != 9) || docMode == 8), + isIE9 = isIE && ((check(/msie 9/) && docMode != 7 && docMode != 8) || docMode == 9), + isIE6 = isIE && check(/msie 6/), + isGecko = !isWebKit && check(/gecko/), + isGecko3 = isGecko && check(/rv:1\.9/), + isGecko4 = isGecko && check(/rv:2\.0/), + isGecko5 = isGecko && check(/rv:5\./), + isGecko10 = isGecko && check(/rv:10\./), + isFF3_0 = isGecko3 && check(/rv:1\.9\.0/), + isFF3_5 = isGecko3 && check(/rv:1\.9\.1/), + isFF3_6 = isGecko3 && check(/rv:1\.9\.2/), + isWindows = check(/windows|win32/), + isMac = check(/macintosh|mac os x/), + isLinux = check(/linux/), + scrollbarSize = null, + chromeVersion = version(true, /\bchrome\/(\d+\.\d+)/), + firefoxVersion = version(true, /\bfirefox\/(\d+\.\d+)/), + ieVersion = version(isIE, /msie (\d+\.\d+)/), + operaVersion = version(isOpera, /version\/(\d+\.\d+)/), + safariVersion = version(isSafari, /version\/(\d+\.\d+)/), + webKitVersion = version(isWebKit, /webkit\/(\d+\.\d+)/), + isSecure = /^https/i.test(window.location.protocol), + nullLog; + + + try { + document.execCommand("BackgroundImageCache", false, true); + } catch(e) {} + + + + nullLog = function () {}; + nullLog.info = nullLog.warn = nullLog.error = Ext.emptyFn; + + Ext.setVersion('extjs', '4.1.0'); + Ext.apply(Ext, { + + SSL_SECURE_URL : isSecure && isIE ? 'javascript:\'\'' : 'about:blank', + + + + + scopeResetCSS : Ext.buildSettings.scopeResetCSS, + + + resetCls: Ext.buildSettings.baseCSSPrefix + 'reset', + + + enableNestedListenerRemoval : false, + + + USE_NATIVE_JSON : false, + + + getDom : function(el, strict) { + if (!el || !document) { + return null; + } + if (el.dom) { + return el.dom; + } else { + if (typeof el == 'string') { + var e = Ext.getElementById(el); + + + if (e && isIE && strict) { + if (el == e.getAttribute('id')) { + return e; + } else { + return null; + } + } + return e; + } else { + return el; + } + } + }, + + + removeNode : isIE6 || isIE7 || isIE8 + ? (function() { + var d; + return function(n){ + if(n && n.tagName.toUpperCase() != 'BODY'){ + (Ext.enableNestedListenerRemoval) ? Ext.EventManager.purgeElement(n) : Ext.EventManager.removeAll(n); + + var cache = Ext.cache, + id = n.id; + + if (cache[id]) { + delete cache[id].dom; + delete cache[id]; + } + + + + if (n.tagName.toUpperCase() != 'IFRAME') { + if (isIE8 && n.parentNode) { + n.parentNode.removeChild(n); + } + d = d || document.createElement('div'); + d.appendChild(n); + d.innerHTML = ''; + } + } + }; + }()) + : function(n) { + if (n && n.parentNode && n.tagName.toUpperCase() != 'BODY') { + (Ext.enableNestedListenerRemoval) ? Ext.EventManager.purgeElement(n) : Ext.EventManager.removeAll(n); + + var cache = Ext.cache, + id = n.id; + + if (cache[id]) { + delete cache[id].dom; + delete cache[id]; + } + + n.parentNode.removeChild(n); + } + }, + + isStrict: isStrict, + + isIEQuirks: isIE && !isStrict, + + + isOpera : isOpera, + + + isOpera10_5 : isOpera10_5, + + + isWebKit : isWebKit, + + + isChrome : isChrome, + + + isSafari : isSafari, + + + isSafari3 : isSafari3, + + + isSafari4 : isSafari4, + + + isSafari5 : isSafari5, + + + isSafari5_0 : isSafari5_0, + + + + isSafari2 : isSafari2, + + + isIE : isIE, + + + isIE6 : isIE6, + + + isIE7 : isIE7, + + + isIE8 : isIE8, + + + isIE9 : isIE9, + + + isGecko : isGecko, + + + isGecko3 : isGecko3, + + + isGecko4 : isGecko4, + + + isGecko5 : isGecko5, + + + isGecko10 : isGecko10, + + + isFF3_0 : isFF3_0, + + + isFF3_5 : isFF3_5, + + + isFF3_6 : isFF3_6, + + + isFF4 : 4 <= firefoxVersion && firefoxVersion < 5, + + + isFF5 : 5 <= firefoxVersion && firefoxVersion < 6, + + + isFF10 : 10 <= firefoxVersion && firefoxVersion < 11, + + + isLinux : isLinux, + + + isWindows : isWindows, + + + isMac : isMac, + + + chromeVersion: chromeVersion, + + + firefoxVersion: firefoxVersion, + + + ieVersion: ieVersion, + + + operaVersion: operaVersion, + + + safariVersion: safariVersion, + + + webKitVersion: webKitVersion, + + + isSecure: isSecure, + + + BLANK_IMAGE_URL : (isIE6 || isIE7) ? '/' + '/www.sencha.com/s.gif' : 'data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==', + + + value : function(v, defaultValue, allowBlank){ + return Ext.isEmpty(v, allowBlank) ? defaultValue : v; + }, + + + escapeRe : function(s) { + return s.replace(/([-.*+?\^${}()|\[\]\/\\])/g, "\\$1"); + }, + + + 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; + } + }, + + + getScrollbarSize: function (force) { + if (!Ext.isReady) { + return {}; + } + + if (force || !scrollbarSize) { + var db = document.body, + div = document.createElement('div'); + + div.style.width = div.style.height = '100px'; + div.style.overflow = 'scroll'; + div.style.position = 'absolute'; + + db.appendChild(div); + + + scrollbarSize = { + width: div.offsetWidth - div.clientWidth, + height: div.offsetHeight - div.clientHeight + }; + + db.removeChild(div); + } + + return scrollbarSize; + }, + + + getScrollBarWidth: function(force){ + var size = Ext.getScrollbarSize(force); + return size.width + 2; + }, + + + copyTo : function(dest, source, names, usePrototypeKeys){ + if(typeof names == 'string'){ + names = names.split(/[,;\s]/); + } + + var n, + nLen = names.length, + name; + + for(n = 0; n < nLen; n++) { + name = names[n]; + + if(usePrototypeKeys || source.hasOwnProperty(name)){ + dest[name] = source[name]; + } + } + + return dest; + }, + + + destroyMembers : function(o){ + for (var i = 1, a = arguments, len = a.length; i < len; i++) { + Ext.destroy(o[a[i]]); + delete o[a[i]]; + } + }, + + + log : + nullLog, + + + partition : function(arr, truth){ + var ret = [[],[]], + a, v, + aLen = arr.length; + + for (a = 0; a < aLen; a++) { + v = arr[a]; + ret[ (truth && truth(v, a, arr)) || (!truth && v) ? 0 : 1].push(v); + } + + return ret; + }, + + + invoke : function(arr, methodName){ + var ret = [], + args = Array.prototype.slice.call(arguments, 2), + a, v, + aLen = arr.length; + + for (a = 0; a < aLen; a++) { + v = arr[a]; + + if (v && typeof v[methodName] == 'function') { + ret.push(v[methodName].apply(v, args)); + } else { + ret.push(undefined); + } + } + + 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 = [], + i, + j, + aLen; + + for (i = 0; i < len; i++) { + ret[i] = []; + if(fn){ + ret[i] = fn.apply(fn, Ext.pluck(arrs, i)); + }else{ + for (j = 0, aLen = arrs.length; j < aLen; j++){ + ret[i].push( arrs[j][i] ); + } + } + } + return ret; + }, + + + toSentence: function(items, connector) { + var length = items.length, + head, + tail; + + if (length <= 1) { + return items[0]; + } else { + head = items.slice(0, length - 1); + tail = items[length - 1]; + + return Ext.util.Format.format("{0} {1} {2}", head.join(", "), connector || 'and', tail); + } + }, + + + useShims: isIE6 + }); +}()); + + +Ext.application = function(config) { + Ext.require('Ext.app.Application'); + + Ext.onReady(function() { + new Ext.app.Application(config); + }); +}; + + +(function() { + Ext.ns('Ext.util'); + + Ext.util.Format = {}; + var UtilFormat = Ext.util.Format, + stripTagsRE = /<\/?[^>]+>/gi, + stripScriptsRe = /(?:)((\n|\r|.)*?)(?:<\/script>)/ig, + nl2brRe = /\r?\n/g, + + + formatCleanRe = /[^\d\.]/g, + + + + I18NFormatCleanRe; + + Ext.apply(UtilFormat, { + + + thousandSeparator: ',', + + + + + decimalSeparator: '.', + + + + + currencyPrecision: 2, + + + + + currencySign: '$', + + + + + currencyAtEnd: false, + + + + undef : function(value) { + return value !== undefined ? value : ""; + }, + + + defaultValue : function(value, defaultValue) { + return value !== undefined && value !== '' ? value : defaultValue; + }, + + + substr : 'ab'.substr(-1) != 'b' + ? function (value, start, length) { + var str = String(value); + return (start < 0) + ? str.substr(Math.max(str.length + start, 0), length) + : str.substr(start, length); + } + : function(value, start, length) { + return String(value).substr(start, length); + }, + + + lowercase : function(value) { + return String(value).toLowerCase(); + }, + + + uppercase : function(value) { + return String(value).toUpperCase(); + }, + + + usMoney : function(v) { + return UtilFormat.currency(v, '$', 2); + }, + + + currency: function(v, currencySign, decimals, end) { + var negativeSign = '', + format = ",0", + i = 0; + v = v - 0; + if (v < 0) { + v = -v; + negativeSign = '-'; + } + decimals = Ext.isDefined(decimals) ? decimals : UtilFormat.currencyPrecision; + format += format + (decimals > 0 ? '.' : ''); + for (; i < decimals; i++) { + format += '0'; + } + v = UtilFormat.number(v, format); + if ((end || UtilFormat.currencyAtEnd) === true) { + return Ext.String.format("{0}{1}{2}", negativeSign, v, currencySign || UtilFormat.currencySign); + } else { + return Ext.String.format("{0}{1}{2}", negativeSign, currencySign || UtilFormat.currencySign, v); + } + }, + + + date: function(v, format) { + if (!v) { + return ""; + } + if (!Ext.isDate(v)) { + v = new Date(Date.parse(v)); + } + return Ext.Date.dateFormat(v, format || Ext.Date.defaultFormat); + }, + + + dateRenderer : function(format) { + return function(v) { + return UtilFormat.date(v, format); + }; + }, + + + stripTags : function(v) { + return !v ? v : String(v).replace(stripTagsRE, ""); + }, + + + stripScripts : function(v) { + return !v ? v : String(v).replace(stripScriptsRe, ""); + }, + + + 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"; + } + }, + + + math : (function(){ + var fns = {}; + + return function(v, a){ + if (!fns[a]) { + fns[a] = Ext.functionFactory('v', 'return v ' + a + ';'); + } + return fns[a](v); + }; + }()), + + + 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; + }, + + + number : function(v, formatString) { + if (!formatString) { + return v; + } + v = Ext.Number.from(v, NaN); + if (isNaN(v)) { + return ''; + } + var comma = UtilFormat.thousandSeparator, + dec = UtilFormat.decimalSeparator, + i18n = false, + neg = v < 0, + hasComma, + psplit, + fnum, + cnum, + parr, + j, + m, + n, + i; + + v = Math.abs(v); + + + + + + if (formatString.substr(formatString.length - 2) == '/i') { + if (!I18NFormatCleanRe) { + I18NFormatCleanRe = new RegExp('[^\\d\\' + UtilFormat.decimalSeparator + ']','g'); + } + formatString = formatString.substr(0, formatString.length - 2); + i18n = true; + hasComma = formatString.indexOf(comma) != -1; + psplit = formatString.replace(I18NFormatCleanRe, '').split(dec); + } else { + hasComma = formatString.indexOf(',') != -1; + psplit = formatString.replace(formatCleanRe, '').split('.'); + } + + if (psplit.length > 2) { + } else if (psplit.length > 1) { + v = Ext.Number.toFixed(v, psplit[1].length); + } else { + v = Ext.Number.toFixed(v, 0); + } + + fnum = v.toString(); + + psplit = fnum.split('.'); + + if (hasComma) { + cnum = psplit[0]; + parr = []; + j = cnum.length; + m = Math.floor(j / 3); + n = cnum.length % 3 || 3; + + 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]; + } + } + + if (neg) { + + neg = fnum.replace(/[^1-9]/g, '') !== ''; + } + + return (neg ? '-' : '') + formatString.replace(/[\d,?\.?]+/, fnum); + }, + + + numberRenderer : function(format) { + return function(v) { + return UtilFormat.number(v, format); + }; + }, + + + plural : function(v, s, p) { + return v +' ' + (v == 1 ? s : (p ? p : s+'s')); + }, + + + nl2br : function(v) { + return Ext.isEmpty(v) ? '' : v.replace(nl2brRe, '
    '); + }, + + + capitalize: Ext.String.capitalize, + + + ellipsis: Ext.String.ellipsis, + + + format: Ext.String.format, + + + htmlDecode: Ext.String.htmlDecode, + + + htmlEncode: Ext.String.htmlEncode, + + + leftPad: Ext.String.leftPad, + + + trim : Ext.String.trim, + + + parseBox : function(box) { + box = Ext.isEmpty(box) ? '' : box; + if (Ext.isNumber(box)) { + box = box.toString(); + } + var parts = box.split(' '), + ln = parts.length; + + if (ln == 1) { + parts[1] = parts[2] = parts[3] = parts[0]; + } + else if (ln == 2) { + parts[2] = parts[0]; + parts[3] = parts[1]; + } + else if (ln == 3) { + parts[3] = parts[1]; + } + + return { + top :parseInt(parts[0], 10) || 0, + right :parseInt(parts[1], 10) || 0, + bottom:parseInt(parts[2], 10) || 0, + left :parseInt(parts[3], 10) || 0 + }; + }, + + + escapeRegex : function(s) { + return s.replace(/([\-.*+?\^${}()|\[\]\/\\])/g, "\\$1"); + } + }); +}()); + + +Ext.define('Ext.util.TaskRunner', { + + interval: 10, + + + timerId: null, + + constructor: function (interval) { + var me = this; + + if (typeof interval == 'number') { + me.interval = interval; + } else if (interval) { + Ext.apply(me, interval); + } + + me.tasks = []; + me.timerFn = Ext.Function.bind(me.onTick, me); + }, + + + newTask: function (config) { + var task = new Ext.util.TaskRunner.Task(config); + task.manager = this; + return task; + }, + + + start: function(task) { + var me = this, + now = new Date().getTime(); + + if (!task.pending) { + me.tasks.push(task); + task.pending = true; + } + + task.stopped = false; + task.taskStartTime = now; + task.taskRunTime = task.fireOnStart !== false ? 0 : task.taskStartTime; + task.taskRunCount = 0; + + if (!me.firing) { + if (task.fireOnStart !== false) { + me.startTimer(0, now); + } else { + me.startTimer(task.interval, now); + } + } + + return task; + }, + + + stop: function(task) { + + + + if (!task.stopped) { + task.stopped = true; + + if (task.onStop) { + task.onStop.call(task.scope || task, task); + } + } + + return task; + }, + + + stopAll: function() { + + Ext.each(this.tasks, this.stop, this); + }, + + + + firing: false, + + nextExpires: 1e99, + + + onTick: function () { + var me = this, + tasks = me.tasks, + now = new Date().getTime(), + nextExpires = 1e99, + len = tasks.length, + expires, newTasks, i, task, rt, remove; + + me.timerId = null; + me.firing = true; + + + + + + for (i = 0; i < len || i < (len = tasks.length); ++i) { + task = tasks[i]; + + if (!(remove = task.stopped)) { + expires = task.taskRunTime + task.interval; + + if (expires <= now) { + rt = 1; + try { + rt = task.run.apply(task.scope || task, task.args || [++task.taskRunCount]); + } catch (taskError) { + try { + if (task.onError) { + rt = task.onError.call(task.scope || task, task, taskError); + } + } catch (ignore) { } + } + task.taskRunTime = now; + if (rt === false || task.taskRunCount === task.repeat) { + me.stop(task); + remove = true; + } else { + remove = task.stopped; + expires = now + task.interval; + } + } + + if (!remove && task.duration && task.duration <= (now - task.taskStartTime)) { + me.stop(task); + remove = true; + } + } + + if (remove) { + task.pending = false; + + + + + + + if (!newTasks) { + newTasks = tasks.slice(0, i); + + + + } + } else { + if (newTasks) { + newTasks.push(task); + } + + if (nextExpires > expires) { + nextExpires = expires; + } + } + } + + if (newTasks) { + + + me.tasks = newTasks; + } + + me.firing = false; + + if (me.tasks.length) { + + + + me.startTimer(nextExpires - now, new Date().getTime()); + } + }, + + + startTimer: function (timeout, now) { + var me = this, + expires = now + timeout, + timerId = me.timerId; + + + + if (timerId && me.nextExpires - expires > me.interval) { + clearTimeout(timerId); + timerId = null; + } + + if (!timerId) { + if (timeout < me.interval) { + timeout = me.interval; + } + + me.timerId = setTimeout(me.timerFn, timeout); + me.nextExpires = expires; + } + } +}, +function () { + var me = this, + proto = me.prototype; + + + proto.destroy = proto.stopAll; + + + Ext.util.TaskManager = Ext.TaskManager = new me(); + + + me.Task = new Ext.Class({ + isTask: true, + + + stopped: true, + + + fireOnStart: false, + + constructor: function (config) { + Ext.apply(this, config); + }, + + + restart: function (interval) { + if (interval !== undefined) { + this.interval = interval; + } + + this.manager.start(this); + }, + + + start: function (interval) { + if (this.stopped) { + this.restart(interval); + } + }, + + + stop: function () { + this.manager.stop(this); + } + }); + + proto = me.Task.prototype; + + + proto.destroy = proto.stop; +}); + + +Ext.define('Ext.perf.Accumulator', (function () { + var currentFrame = null, + khrome = Ext.global['chrome'], + formatTpl, + + + getTimestamp = function () { + + getTimestamp = function () { + return new Date().getTime(); + }; + + var interval, toolbox; + + + if (Ext.isChrome && khrome && khrome.Interval) { + interval = new khrome.Interval(); + interval.start(); + getTimestamp = function () { + return interval.microseconds() / 1000; + }; + } else if (window.ActiveXObject) { + try { + + toolbox = new ActiveXObject('SenchaToolbox.Toolbox'); + Ext.senchaToolbox = toolbox; + getTimestamp = function () { + return toolbox.milliseconds; + }; + } catch (e) { + + } + } else if (Date.now) { + getTimestamp = Date.now; + } + + Ext.perf.getTimestamp = Ext.perf.Accumulator.getTimestamp = getTimestamp; + return getTimestamp(); + }; + + function adjustSet (set, time) { + set.sum += time; + set.min = Math.min(set.min, time); + set.max = Math.max(set.max, time); + } + + function leaveFrame (time) { + var totalTime = time ? time : (getTimestamp() - this.time), + me = this, + accum = me.accum; + + ++accum.count; + if (! --accum.depth) { + adjustSet(accum.total, totalTime); + } + adjustSet(accum.pure, totalTime - me.childTime); + + currentFrame = me.parent; + if (currentFrame) { + ++currentFrame.accum.childCount; + currentFrame.childTime += totalTime; + } + } + + function makeSet () { + return { + min: Number.MAX_VALUE, + max: 0, + sum: 0 + }; + } + + function makeTap (me, fn) { + return function () { + var frame = me.enter(), + ret = fn.apply(this, arguments); + + frame.leave(); + return ret; + }; + } + + function round (x) { + return Math.round(x * 100) / 100; + } + + function setToJSON (count, childCount, calibration, set) { + var data = { + avg: 0, + min: set.min, + max: set.max, + sum: 0 + }; + + if (count) { + calibration = calibration || 0; + data.sum = set.sum - childCount * calibration; + data.avg = data.sum / count; + + + } + + return data; + } + + return { + constructor: function (name) { + var me = this; + + me.count = me.childCount = me.depth = me.maxDepth = 0; + me.pure = makeSet(); + me.total = makeSet(); + me.name = name; + }, + + statics: { + getTimestamp: getTimestamp + }, + + format: function (calibration) { + if (!formatTpl) { + formatTpl = new Ext.XTemplate([ + '{name} - {count} call(s)', + '', + '', + ' ({childCount} children)', + '', + '', + ' ({depth} deep)', + '', + '', + ', {type}: {[this.time(values.sum)]} msec (', + + 'avg={[this.time(values.sum / parent.count)]}', + + ')', + '', + '' + ].join(''), { + time: function (t) { + return Math.round(t * 100) / 100; + } + }); + } + + var data = this.getData(calibration); + data.name = this.name; + data.pure.type = 'Pure'; + data.total.type = 'Total'; + data.times = [data.pure, data.total]; + return formatTpl.apply(data); + }, + + getData: function (calibration) { + var me = this; + + return { + count: me.count, + childCount: me.childCount, + depth: me.maxDepth, + pure: setToJSON(me.count, me.childCount, calibration, me.pure), + total: setToJSON(me.count, me.childCount, calibration, me.total) + }; + }, + + enter: function () { + var me = this, + frame = { + accum: me, + leave: leaveFrame, + childTime: 0, + parent: currentFrame + }; + + ++me.depth; + if (me.maxDepth < me.depth) { + me.maxDepth = me.depth; + } + + currentFrame = frame; + frame.time = getTimestamp(); + return frame; + }, + + monitor: function (fn, scope, args) { + var frame = this.enter(); + if (args) { + fn.apply(scope, args); + } else { + fn.call(scope); + } + frame.leave(); + }, + + report: function () { + Ext.log(this.format()); + }, + + tap: function (className, methodName) { + var me = this, + methods = typeof methodName == 'string' ? [methodName] : methodName, + klass, statik, i, parts, length, name, src, + tapFunc; + + tapFunc = function(){ + if (typeof className == 'string') { + klass = Ext.global; + parts = className.split('.'); + for (i = 0, length = parts.length; i < length; ++i) { + klass = klass[parts[i]]; + } + } else { + klass = className; + } + + for (i = 0, length = methods.length; i < length; ++i) { + name = methods[i]; + statik = name.charAt(0) == '!'; + + if (statik) { + name = name.substring(1); + } else { + statik = !(name in klass.prototype); + } + + src = statik ? klass : klass.prototype; + src[name] = makeTap(me, src[name]); + } + }; + + Ext.ClassManager.onCreated(tapFunc, me, className); + + return me; + } + }; +}()), + +function () { + Ext.perf.getTimestamp = this.getTimestamp; +}); + + +Ext.define('Ext.perf.Monitor', { + singleton: true, + alternateClassName: 'Ext.Perf', + + requires: [ + 'Ext.perf.Accumulator' + ], + + constructor: function () { + this.accumulators = []; + this.accumulatorsByName = {}; + }, + + calibrate: function () { + var accum = new Ext.perf.Accumulator('$'), + total = accum.total, + getTimestamp = Ext.perf.Accumulator.getTimestamp, + count = 0, + frame, + endTime, + startTime; + + startTime = getTimestamp(); + + do { + frame = accum.enter(); + frame.leave(); + ++count; + } while (total.sum < 100); + + endTime = getTimestamp(); + + return (endTime - startTime) / count; + }, + + get: function (name) { + var me = this, + accum = me.accumulatorsByName[name]; + + if (!accum) { + me.accumulatorsByName[name] = accum = new Ext.perf.Accumulator(name); + me.accumulators.push(accum); + } + + return accum; + }, + + enter: function (name) { + return this.get(name).enter(); + }, + + monitor: function (name, fn, scope) { + this.get(name).monitor(fn, scope); + }, + + report: function () { + var me = this, + accumulators = me.accumulators, + calibration = me.calibrate(); + + accumulators.sort(function (a, b) { + return (a.name < b.name) ? -1 : ((b.name < a.name) ? 1 : 0); + }); + + me.updateGC(); + + Ext.log('Calibration: ' + Math.round(calibration * 100) / 100 + ' msec/sample'); + Ext.each(accumulators, function (accum) { + Ext.log(accum.format(calibration)); + }); + }, + + getData: function (all) { + var ret = {}, + accumulators = this.accumulators; + + Ext.each(accumulators, function (accum) { + if (all || accum.count) { + ret[accum.name] = accum.getData(); + } + }); + + return ret; + }, + + updateGC: function () { + var accumGC = this.accumulatorsByName.GC, + toolbox = Ext.senchaToolbox, + bucket; + + if (accumGC) { + accumGC.count = toolbox.garbageCollectionCounter || 0; + + if (accumGC.count) { + bucket = accumGC.pure; + accumGC.total.sum = bucket.sum = toolbox.garbageCollectionMilliseconds; + bucket.min = bucket.max = bucket.sum / accumGC.count; + bucket = accumGC.total; + bucket.min = bucket.max = bucket.sum / accumGC.count; + } + } + }, + + watchGC: function () { + Ext.perf.getTimestamp(); + + var toolbox = Ext.senchaToolbox; + + if (toolbox) { + this.get("GC"); + toolbox.watchGarbageCollector(false); + } + }, + + setup: function (config) { + if (!config) { + config = { + + + + + + + + + render: { + 'Ext.AbstractComponent': 'render' + }, + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + layout: { + 'Ext.layout.Context': 'run' + } + }; + } + + this.currentConfig = config; + + var key, prop, + accum, className, methods; + for (key in config) { + if (config.hasOwnProperty(key)) { + prop = config[key]; + accum = Ext.Perf.get(key); + + for (className in prop) { + if (prop.hasOwnProperty(className)) { + methods = prop[className]; + accum.tap(className, methods); + } + } + } + } + + this.watchGC(); + } +}); + + +Ext.is = { + init : function(navigator) { + var platforms = this.platforms, + ln = platforms.length, + i, platform; + + navigator = navigator || window.navigator; + + for (i = 0; i < ln; i++) { + platform = platforms[i]; + this[platform.identity] = platform.regex.test(navigator[platform.property]); + } + + + this.Desktop = this.Mac || this.Windows || (this.Linux && !this.Android); + + this.Tablet = this.iPad; + + this.Phone = !this.Desktop && !this.Tablet; + + this.iOS = this.iPhone || this.iPad || this.iPod; + + + this.Standalone = !!window.navigator.standalone; + }, + + + platforms: [{ + property: 'platform', + regex: /iPhone/i, + identity: 'iPhone' + }, + + + { + property: 'platform', + regex: /iPod/i, + identity: 'iPod' + }, + + + { + property: 'userAgent', + regex: /iPad/i, + identity: 'iPad' + }, + + + { + property: 'userAgent', + regex: /Blackberry/i, + identity: 'Blackberry' + }, + + + { + property: 'userAgent', + regex: /Android/i, + identity: 'Android' + }, + + + { + property: 'platform', + regex: /Mac/i, + identity: 'Mac' + }, + + + { + property: 'platform', + regex: /Win/i, + identity: 'Windows' + }, + + + { + property: 'platform', + regex: /Linux/i, + identity: 'Linux' + }] +}; + +Ext.is.init(); + + +(function(){ + + + + + var getStyle = function(element, styleName){ + var view = element.ownerDocument.defaultView, + style = (view ? view.getComputedStyle(element, null) : element.currentStyle) || element.style; + return style[styleName]; + }; + +Ext.supports = { + + init : function() { + var me = this, + doc = document, + tests = me.tests, + n = tests.length, + div = n && Ext.isReady && doc.createElement('div'), + test, notRun = []; + + if (div) { + div.innerHTML = [ + '
    ', + '
    ', + '
    ', + '
    ', + '
    ', + '
    ', + '
    ', + '
    ' + ].join(''); + + doc.body.appendChild(div); + } + + while (n--) { + test = tests[n]; + if (div || test.early) { + me[test.identity] = test.fn.call(me, doc, div); + } else { + notRun.push(test); + } + } + + if (div) { + doc.body.removeChild(div); + } + + me.tests = notRun; + }, + + + PointerEvents: 'pointerEvents' in document.documentElement.style, + + + CSS3BoxShadow: 'boxShadow' in document.documentElement.style || 'WebkitBoxShadow' in document.documentElement.style || 'MozBoxShadow' in document.documentElement.style, + + + ClassList: !!document.documentElement.classList, + + + OrientationChange: ((typeof window.orientation != 'undefined') && ('onorientationchange' in window)), + + + DeviceMotion: ('ondevicemotion' in window), + + + + + Touch: ('ontouchstart' in window) && (!Ext.is.Desktop), + + + TimeoutActualLateness: (function(){ + setTimeout(function(){ + Ext.supports.TimeoutActualLateness = arguments.length !== 0; + }, 0); + }()), + + tests: [ + + { + identity: 'Transitions', + fn: function(doc, div) { + var prefix = [ + 'webkit', + 'Moz', + 'o', + 'ms', + 'khtml' + ], + TE = 'TransitionEnd', + transitionEndName = [ + prefix[0] + TE, + 'transitionend', + prefix[2] + TE, + prefix[3] + TE, + prefix[4] + TE + ], + ln = prefix.length, + i = 0, + out = false; + + for (; i < ln; i++) { + if (getStyle(div, prefix[i] + "TransitionProperty")) { + Ext.supports.CSS3Prefix = prefix[i]; + Ext.supports.CSS3TransitionEnd = transitionEndName[i]; + out = true; + break; + } + } + return out; + } + }, + + + { + identity: 'RightMargin', + fn: function(doc, div) { + var view = doc.defaultView; + return !(view && view.getComputedStyle(div.firstChild.firstChild, null).marginRight != '0px'); + } + }, + + + { + identity: 'DisplayChangeInputSelectionBug', + early: true, + fn: function() { + var webKitVersion = Ext.webKitVersion; + + return 0 < webKitVersion && webKitVersion < 533; + } + }, + + + { + identity: 'DisplayChangeTextAreaSelectionBug', + early: true, + fn: function() { + var webKitVersion = Ext.webKitVersion; + + + return 0 < webKitVersion && webKitVersion < 534.24; + } + }, + + + { + identity: 'TransparentColor', + fn: function(doc, div, view) { + view = doc.defaultView; + return !(view && view.getComputedStyle(div.lastChild, null).backgroundColor != 'transparent'); + } + }, + + + { + identity: 'ComputedStyle', + fn: function(doc, div, view) { + view = doc.defaultView; + return view && view.getComputedStyle; + } + }, + + + { + identity: 'Svg', + fn: function(doc) { + return !!doc.createElementNS && !!doc.createElementNS( "http:/" + "/www.w3.org/2000/svg", "svg").createSVGRect; + } + }, + + + { + identity: 'Canvas', + fn: function(doc) { + return !!doc.createElement('canvas').getContext; + } + }, + + + { + identity: 'Vml', + fn: function(doc) { + var d = doc.createElement("div"); + d.innerHTML = ""; + return (d.childNodes.length == 2); + } + }, + + + { + identity: 'Float', + fn: function(doc, div) { + return !!div.lastChild.style.cssFloat; + } + }, + + + { + identity: 'AudioTag', + fn: function(doc) { + return !!doc.createElement('audio').canPlayType; + } + }, + + + { + identity: 'History', + fn: function() { + var history = window.history; + return !!(history && history.pushState); + } + }, + + + { + identity: 'CSS3DTransform', + fn: function() { + return (typeof WebKitCSSMatrix != 'undefined' && new WebKitCSSMatrix().hasOwnProperty('m41')); + } + }, + + + { + identity: 'CSS3LinearGradient', + fn: function(doc, div) { + var property = 'background-image:', + webkit = '-webkit-gradient(linear, left top, right bottom, from(black), to(white))', + w3c = 'linear-gradient(left top, black, white)', + moz = '-moz-' + w3c, + opera = '-o-' + w3c, + options = [property + webkit, property + w3c, property + moz, property + opera]; + + div.style.cssText = options.join(';'); + + return ("" + div.style.backgroundImage).indexOf('gradient') !== -1; + } + }, + + + { + identity: 'CSS3BorderRadius', + fn: function(doc, div) { + var domPrefixes = ['borderRadius', 'BorderRadius', 'MozBorderRadius', 'WebkitBorderRadius', 'OBorderRadius', 'KhtmlBorderRadius'], + pass = false, + i; + for (i = 0; i < domPrefixes.length; i++) { + if (document.body.style[domPrefixes[i]] !== undefined) { + return true; + } + } + return pass; + } + }, + + + { + identity: 'GeoLocation', + fn: function() { + return (typeof navigator != 'undefined' && typeof navigator.geolocation != 'undefined') || (typeof google != 'undefined' && typeof google.gears != 'undefined'); + } + }, + + { + identity: 'MouseEnterLeave', + fn: function(doc, div){ + return ('onmouseenter' in div && 'onmouseleave' in div); + } + }, + + { + identity: 'MouseWheel', + fn: function(doc, div) { + return ('onmousewheel' in div); + } + }, + + { + identity: 'Opacity', + fn: function(doc, div){ + + if (Ext.isIE6 || Ext.isIE7 || Ext.isIE8) { + return false; + } + div.firstChild.style.cssText = 'opacity:0.73'; + return div.firstChild.style.opacity == '0.73'; + } + }, + + { + identity: 'Placeholder', + fn: function(doc) { + return 'placeholder' in doc.createElement('input'); + } + }, + + + { + identity: 'Direct2DBug', + fn: function() { + return Ext.isString(document.body.style.msTransformOrigin); + } + }, + + { + identity: 'BoundingClientRect', + fn: function(doc, div) { + return Ext.isFunction(div.getBoundingClientRect); + } + }, + { + identity: 'IncludePaddingInWidthCalculation', + fn: function(doc, div){ + return div.childNodes[1].firstChild.offsetWidth == 210; + } + }, + { + identity: 'IncludePaddingInHeightCalculation', + fn: function(doc, div){ + return div.childNodes[1].firstChild.offsetHeight == 210; + } + }, + + + { + identity: 'ArraySort', + fn: function() { + var a = [1,2,3,4,5].sort(function(){ return 0; }); + return a[0] === 1 && a[1] === 2 && a[2] === 3 && a[3] === 4 && a[4] === 5; + } + }, + + { + identity: 'Range', + fn: function() { + return !!document.createRange; + } + }, + + { + identity: 'CreateContextualFragment', + fn: function() { + var range = Ext.supports.Range ? document.createRange() : false; + + return range && !!range.createContextualFragment; + } + }, + + + { + identity: 'WindowOnError', + fn: function () { + + return Ext.isIE || Ext.isGecko || Ext.webKitVersion >= 534.16; + } + }, + + + { + identity: 'TextAreaMaxLength', + fn: function(){ + var el = document.createElement('textarea'); + return ('maxlength' in el); + } + }, + + + { + identity: 'GetPositionPercentage', + fn: function(doc, div){ + return getStyle(div.childNodes[2], 'left') == '10%'; + } + } + ] +}; +}()); + +Ext.supports.init(); + + + +Ext.util.DelayedTask = function(fn, scope, args) { + var me = this, + id, + call = function() { + clearInterval(id); + id = null; + fn.apply(scope, args || []); + }; + + + this.delay = function(delay, newFn, newScope, newArgs) { + me.cancel(); + fn = newFn || fn; + scope = newScope || scope; + args = newArgs || args; + id = setInterval(call, delay); + }; + + + this.cancel = function(){ + if (id) { + clearInterval(id); + id = null; + } + }; +}; +Ext.require('Ext.util.DelayedTask', function() { + + + Ext.util.Event = Ext.extend(Object, (function() { + function createTargeted(handler, listener, o, scope){ + return function(){ + if (o.target === arguments[0]){ + handler.apply(scope, arguments); + } + }; + } + + function createBuffered(handler, listener, o, scope) { + listener.task = new Ext.util.DelayedTask(); + return function() { + listener.task.delay(o.buffer, handler, scope, Ext.Array.toArray(arguments)); + }; + } + + function createDelayed(handler, listener, o, scope) { + return function() { + var task = new Ext.util.DelayedTask(); + if (!listener.tasks) { + listener.tasks = []; + } + listener.tasks.push(task); + task.delay(o.delay || 10, handler, scope, Ext.Array.toArray(arguments)); + }; + } + + function createSingle(handler, listener, o, scope) { + return function() { + var event = listener.ev; + + if (event.removeListener(listener.fn, scope) && event.observable) { + + + event.observable.hasListeners[event.name]--; + } + + return handler.apply(scope, arguments); + }; + } + + return { + + isEvent: true, + + constructor: function(observable, name) { + this.name = name; + this.observable = observable; + this.listeners = []; + }, + + addListener: function(fn, scope, options) { + var me = this, + listener; + scope = scope || me.observable; + + + if (!me.isListening(fn, scope)) { + listener = me.createListener(fn, scope, options); + if (me.firing) { + + me.listeners = me.listeners.slice(0); + } + me.listeners.push(listener); + } + }, + + createListener: function(fn, scope, o) { + o = o || {}; + scope = scope || this.observable; + + var listener = { + fn: fn, + scope: scope, + o: o, + ev: this + }, + handler = fn; + + + + if (o.single) { + handler = createSingle(handler, listener, o, scope); + } + if (o.target) { + handler = createTargeted(handler, listener, o, scope); + } + if (o.delay) { + handler = createDelayed(handler, listener, o, scope); + } + if (o.buffer) { + handler = createBuffered(handler, listener, o, scope); + } + + listener.fireFn = handler; + return listener; + }, + + findListener: function(fn, scope) { + var listeners = this.listeners, + i = listeners.length, + listener, + s; + + while (i--) { + listener = listeners[i]; + if (listener) { + s = listener.scope; + if (listener.fn == fn && (s == scope || s == this.observable)) { + return i; + } + } + } + + return - 1; + }, + + isListening: function(fn, scope) { + return this.findListener(fn, scope) !== -1; + }, + + removeListener: function(fn, scope) { + var me = this, + index, + listener, + k; + index = me.findListener(fn, scope); + if (index != -1) { + listener = me.listeners[index]; + + if (me.firing) { + me.listeners = me.listeners.slice(0); + } + + + if (listener.task) { + listener.task.cancel(); + delete listener.task; + } + + + k = listener.tasks && listener.tasks.length; + if (k) { + while (k--) { + listener.tasks[k].cancel(); + } + delete listener.tasks; + } + + + Ext.Array.erase(me.listeners, index, 1); + return true; + } + + return false; + }, + + + clearListeners: function() { + var listeners = this.listeners, + i = listeners.length; + + while (i--) { + this.removeListener(listeners[i].fn, listeners[i].scope); + } + }, + + fire: function() { + var me = this, + listeners = me.listeners, + count = listeners.length, + i, + args, + listener; + + if (count > 0) { + me.firing = true; + for (i = 0; i < count; i++) { + listener = listeners[i]; + args = arguments.length ? Array.prototype.slice.call(arguments, 0) : []; + if (listener.o) { + args.push(listener.o); + } + if (listener && listener.fireFn.apply(listener.scope || me.observable, args) === false) { + return (me.firing = false); + } + } + } + me.firing = false; + return true; + } + }; + }())); +}); + + +Ext.EventManager = new function() { + var EventManager = this, + doc = document, + win = window, + initExtCss = function() { + + var bd = doc.body || doc.getElementsByTagName('body')[0], + baseCSSPrefix = Ext.baseCSSPrefix, + cls = [baseCSSPrefix + 'body'], + htmlCls = [], + html; + + if (!bd) { + return false; + } + + html = bd.parentNode; + + function add (c) { + cls.push(baseCSSPrefix + c); + } + + + if (Ext.isIE) { + add('ie'); + + + + + + + + + + + + + if (Ext.isIE6) { + add('ie6'); + } else { + add('ie7p'); + + if (Ext.isIE7) { + add('ie7'); + } else { + add('ie8p'); + + if (Ext.isIE8) { + add('ie8'); + } else { + add('ie9p'); + + if (Ext.isIE9) { + add('ie9'); + } + } + } + } + + if (Ext.isIE6 || Ext.isIE7) { + add('ie7m'); + } + if (Ext.isIE6 || Ext.isIE7 || Ext.isIE8) { + add('ie8m'); + } + if (Ext.isIE7 || Ext.isIE8) { + add('ie78'); + } + } + if (Ext.isGecko) { + add('gecko'); + if (Ext.isGecko3) { + add('gecko3'); + } + if (Ext.isGecko4) { + add('gecko4'); + } + if (Ext.isGecko5) { + add('gecko5'); + } + } + if (Ext.isOpera) { + add('opera'); + } + if (Ext.isWebKit) { + add('webkit'); + } + if (Ext.isSafari) { + add('safari'); + if (Ext.isSafari2) { + add('safari2'); + } + if (Ext.isSafari3) { + add('safari3'); + } + if (Ext.isSafari4) { + add('safari4'); + } + if (Ext.isSafari5) { + add('safari5'); + } + if (Ext.isSafari5_0) { + add('safari5_0') + } + } + if (Ext.isChrome) { + add('chrome'); + } + if (Ext.isMac) { + add('mac'); + } + if (Ext.isLinux) { + add('linux'); + } + if (!Ext.supports.CSS3BorderRadius) { + add('nbr'); + } + if (!Ext.supports.CSS3LinearGradient) { + add('nlg'); + } + if (!Ext.scopeResetCSS) { + add('reset'); + } + + + if (html) { + if (Ext.isStrict && (Ext.isIE6 || Ext.isIE7)) { + Ext.isBorderBox = false; + } + else { + Ext.isBorderBox = true; + } + + if(Ext.isBorderBox) { + htmlCls.push(baseCSSPrefix + 'border-box'); + } + if (Ext.isStrict) { + htmlCls.push(baseCSSPrefix + 'strict'); + } else { + htmlCls.push(baseCSSPrefix + 'quirks'); + } + Ext.fly(html, '_internal').addCls(htmlCls); + } + + Ext.fly(bd, '_internal').addCls(cls); + return true; + }; + + Ext.apply(EventManager, { + + hasBoundOnReady: false, + + + hasFiredReady: false, + + + deferReadyEvent : 1, + + + onReadyChain : [], + + + readyEvent: + (function () { + var event = new Ext.util.Event(); + event.fire = function () { + Ext._beforeReadyTime = Ext._beforeReadyTime || new Date().getTime(); + event.self.prototype.fire.apply(event, arguments); + Ext._afterReadytime = new Date().getTime(); + }; + return event; + }()), + + + idleEvent: new Ext.util.Event(), + + + isReadyPaused: function(){ + return (/[?&]ext-pauseReadyFire\b/i.test(location.search) && !Ext._continueFireReady); + }, + + + bindReadyEvent: function() { + if (EventManager.hasBoundOnReady) { + return; + } + + + if ( doc.readyState == 'complete' ) { + EventManager.onReadyEvent({ + type: doc.readyState || 'body' + }); + } else { + document.addEventListener('DOMContentLoaded', EventManager.onReadyEvent, false); + window.addEventListener('load', EventManager.onReadyEvent, false); + EventManager.hasBoundOnReady = true; + } + }, + + onReadyEvent : function(e) { + if (e && e.type) { + EventManager.onReadyChain.push(e.type); + } + + if (EventManager.hasBoundOnReady) { + document.removeEventListener('DOMContentLoaded', EventManager.onReadyEvent, false); + window.removeEventListener('load', EventManager.onReadyEvent, false); + } + + if (!Ext.isReady) { + EventManager.fireDocReady(); + } + }, + + + fireDocReady: function() { + if (!Ext.isReady) { + Ext._readyTime = new Date().getTime(); + Ext.isReady = true; + + Ext.supports.init(); + EventManager.onWindowUnload(); + EventManager.readyEvent.onReadyChain = EventManager.onReadyChain; + + if (Ext.isNumber(EventManager.deferReadyEvent)) { + Ext.Function.defer(EventManager.fireReadyEvent, EventManager.deferReadyEvent); + EventManager.hasDocReadyTimer = true; + } else { + EventManager.fireReadyEvent(); + } + } + }, + + + fireReadyEvent: function(){ + var readyEvent = EventManager.readyEvent; + + + + EventManager.hasDocReadyTimer = false; + EventManager.isFiring = true; + + + + + while (readyEvent.listeners.length && !EventManager.isReadyPaused()) { + readyEvent.fire(); + } + EventManager.isFiring = false; + EventManager.hasFiredReady = true; + }, + + + onDocumentReady: function(fn, scope, options) { + options = options || {}; + + options.single = true; + EventManager.readyEvent.addListener(fn, scope, options); + + + + if (!(EventManager.isFiring || EventManager.hasDocReadyTimer)) { + if (Ext.isReady) { + EventManager.fireReadyEvent(); + } else { + EventManager.bindReadyEvent(); + } + } + }, + + + + + stoppedMouseDownEvent: new Ext.util.Event(), + + + propRe: /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate|freezeEvent)$/, + + + getId : function(element) { + var id; + + element = Ext.getDom(element); + + if (element === doc || element === win) { + id = element === doc ? Ext.documentId : Ext.windowId; + } + else { + id = Ext.id(element); + } + + if (!Ext.cache[id]) { + Ext.addCacheEntry(id, null, element); + } + + return id; + }, + + + prepareListenerConfig: function(element, config, isRemove) { + var propRe = EventManager.propRe, + key, value, args; + + + for (key in config) { + if (config.hasOwnProperty(key)) { + + if (!propRe.test(key)) { + value = config[key]; + + + if (typeof value == 'function') { + + args = [element, key, value, config.scope, config]; + } else { + + args = [element, key, value.fn, value.scope, value]; + } + + if (isRemove) { + EventManager.removeListener.apply(EventManager, args); + } else { + EventManager.addListener.apply(EventManager, args); + } + } + } + } + }, + + mouseEnterLeaveRe: /mouseenter|mouseleave/, + + + normalizeEvent: function(eventName, fn) { + if (EventManager.mouseEnterLeaveRe.test(eventName) && !Ext.supports.MouseEnterLeave) { + if (fn) { + fn = Ext.Function.createInterceptor(fn, EventManager.contains); + } + eventName = eventName == 'mouseenter' ? 'mouseover' : 'mouseout'; + } else if (eventName == 'mousewheel' && !Ext.supports.MouseWheel && !Ext.isOpera) { + eventName = 'DOMMouseScroll'; + } + return { + eventName: eventName, + fn: fn + }; + }, + + + contains: function(event) { + var parent = event.browserEvent.currentTarget, + child = EventManager.getRelatedTarget(event); + + if (parent && parent.firstChild) { + while (child) { + if (child === parent) { + return false; + } + child = child.parentNode; + if (child && (child.nodeType != 1)) { + child = null; + } + } + } + return true; + }, + + + addListener: function(element, eventName, fn, scope, options) { + + if (typeof eventName !== 'string') { + EventManager.prepareListenerConfig(element, eventName); + return; + } + + var dom = element.dom || Ext.getDom(element), + bind, wrap; + + + + options = options || {}; + + bind = EventManager.normalizeEvent(eventName, fn); + wrap = EventManager.createListenerWrap(dom, eventName, bind.fn, scope, options); + + if (dom.attachEvent) { + dom.attachEvent('on' + bind.eventName, wrap); + } else { + dom.addEventListener(bind.eventName, wrap, options.capture || false); + } + + if (dom == doc && eventName == 'mousedown') { + EventManager.stoppedMouseDownEvent.addListener(wrap); + } + + + EventManager.getEventListenerCache(element.dom ? element : dom, eventName).push({ + fn: fn, + wrap: wrap, + scope: scope + }); + }, + + + removeListener : function(element, eventName, fn, scope) { + + if (typeof eventName !== 'string') { + EventManager.prepareListenerConfig(element, eventName, true); + return; + } + + var dom = Ext.getDom(element), + el = element.dom ? element : Ext.get(dom), + cache = EventManager.getEventListenerCache(el, eventName), + bindName = EventManager.normalizeEvent(eventName).eventName, + i = cache.length, j, + listener, wrap, tasks; + + + while (i--) { + listener = cache[i]; + + if (listener && (!fn || listener.fn == fn) && (!scope || listener.scope === scope)) { + wrap = listener.wrap; + + + if (wrap.task) { + clearTimeout(wrap.task); + delete wrap.task; + } + + + j = wrap.tasks && wrap.tasks.length; + if (j) { + while (j--) { + clearTimeout(wrap.tasks[j]); + } + delete wrap.tasks; + } + + if (dom.detachEvent) { + dom.detachEvent('on' + bindName, wrap); + } else { + dom.removeEventListener(bindName, wrap, false); + } + + if (wrap && dom == doc && eventName == 'mousedown') { + EventManager.stoppedMouseDownEvent.removeListener(wrap); + } + + + Ext.Array.erase(cache, i, 1); + } + } + }, + + + removeAll : function(element) { + var el = element.dom ? element : Ext.get(element), + cache, events, eventName; + + if (!el) { + return; + } + cache = (el.$cache || el.getCache()); + events = cache.events; + + for (eventName in events) { + if (events.hasOwnProperty(eventName)) { + EventManager.removeListener(el, eventName); + } + } + cache.events = {}; + }, + + + purgeElement : function(element, eventName) { + var dom = Ext.getDom(element), + i = 0, len; + + if (eventName) { + EventManager.removeListener(element, eventName); + } + else { + EventManager.removeAll(element); + } + + if (dom && dom.childNodes) { + for (len = element.childNodes.length; i < len; i++) { + EventManager.purgeElement(element.childNodes[i], eventName); + } + } + }, + + + createListenerWrap : function(dom, ename, fn, scope, options) { + options = options || {}; + + var f, gen, escapeRx = /\\/g, wrap = function(e, args) { + + if (!gen) { + f = ['if(!' + Ext.name + ') {return;}']; + + if(options.buffer || options.delay || options.freezeEvent) { + f.push('e = new X.EventObjectImpl(e, ' + (options.freezeEvent ? 'true' : 'false' ) + ');'); + } else { + f.push('e = X.EventObject.setEvent(e);'); + } + + if (options.delegate) { + + + f.push('var t = e.getTarget("' + (options.delegate + '').replace(escapeRx, '\\\\') + '", this);'); + f.push('if(!t) {return;}'); + } else { + f.push('var t = e.target;'); + } + + if (options.target) { + f.push('if(e.target !== options.target) {return;}'); + } + + if(options.stopEvent) { + f.push('e.stopEvent();'); + } else { + if(options.preventDefault) { + f.push('e.preventDefault();'); + } + if(options.stopPropagation) { + f.push('e.stopPropagation();'); + } + } + + if(options.normalized === false) { + f.push('e = e.browserEvent;'); + } + + if(options.buffer) { + f.push('(wrap.task && clearTimeout(wrap.task));'); + f.push('wrap.task = setTimeout(function() {'); + } + + if(options.delay) { + f.push('wrap.tasks = wrap.tasks || [];'); + f.push('wrap.tasks.push(setTimeout(function() {'); + } + + + f.push('fn.call(scope || dom, e, t, options);'); + + if(options.single) { + f.push('evtMgr.removeListener(dom, ename, fn, scope);'); + } + + + + if (ename !== 'mousemove') { + f.push('if (evtMgr.idleEvent.listeners.length) {'); + f.push('evtMgr.idleEvent.fire();'); + f.push('}'); + } + + if(options.delay) { + f.push('}, ' + options.delay + '));'); + } + + if(options.buffer) { + f.push('}, ' + options.buffer + ');'); + } + + gen = Ext.cacheableFunctionFactory('e', 'options', 'fn', 'scope', 'ename', 'dom', 'wrap', 'args', 'X', 'evtMgr', f.join('\n')); + } + + gen.call(dom, e, options, fn, scope, ename, dom, wrap, args, Ext, EventManager); + }; + return wrap; + }, + + + getEventListenerCache : function(element, eventName) { + var elementCache, eventCache; + if (!element) { + return []; + } + + if (element.$cache) { + elementCache = element.$cache; + } else { + + elementCache = Ext.cache[EventManager.getId(element)]; + } + eventCache = elementCache.events || (elementCache.events = {}); + + return eventCache[eventName] || (eventCache[eventName] = []); + }, + + + mouseLeaveRe: /(mouseout|mouseleave)/, + mouseEnterRe: /(mouseover|mouseenter)/, + + + stopEvent: function(event) { + EventManager.stopPropagation(event); + EventManager.preventDefault(event); + }, + + + stopPropagation: function(event) { + event = event.browserEvent || event; + if (event.stopPropagation) { + event.stopPropagation(); + } else { + event.cancelBubble = true; + } + }, + + + preventDefault: function(event) { + event = event.browserEvent || event; + if (event.preventDefault) { + event.preventDefault(); + } else { + event.returnValue = false; + + try { + + if (event.ctrlKey || event.keyCode > 111 && event.keyCode < 124) { + event.keyCode = -1; + } + } catch (e) { + + } + } + }, + + + getRelatedTarget: function(event) { + event = event.browserEvent || event; + var target = event.relatedTarget; + if (!target) { + if (EventManager.mouseLeaveRe.test(event.type)) { + target = event.toElement; + } else if (EventManager.mouseEnterRe.test(event.type)) { + target = event.fromElement; + } + } + return EventManager.resolveTextNode(target); + }, + + + getPageX: function(event) { + return EventManager.getPageXY(event)[0]; + }, + + + getPageY: function(event) { + return EventManager.getPageXY(event)[1]; + }, + + + getPageXY: function(event) { + event = event.browserEvent || event; + var x = event.pageX, + y = event.pageY, + docEl = doc.documentElement, + body = doc.body; + + + if (!x && x !== 0) { + x = event.clientX + (docEl && docEl.scrollLeft || body && body.scrollLeft || 0) - (docEl && docEl.clientLeft || body && body.clientLeft || 0); + y = event.clientY + (docEl && docEl.scrollTop || body && body.scrollTop || 0) - (docEl && docEl.clientTop || body && body.clientTop || 0); + } + return [x, y]; + }, + + + getTarget: function(event) { + event = event.browserEvent || event; + return EventManager.resolveTextNode(event.target || event.srcElement); + }, + + + + + + resolveTextNode: Ext.isGecko ? + function(node) { + if (!node) { + return; + } + + var s = HTMLElement.prototype.toString.call(node); + if (s == '[xpconnect wrapped native prototype]' || s == '[object XULElement]') { + return; + } + return node.nodeType == 3 ? node.parentNode: node; + }: function(node) { + return node && node.nodeType == 3 ? node.parentNode: node; + }, + + + + + curWidth: 0, + curHeight: 0, + + + onWindowResize: function(fn, scope, options) { + var resize = EventManager.resizeEvent; + + if (!resize) { + EventManager.resizeEvent = resize = new Ext.util.Event(); + EventManager.on(win, 'resize', EventManager.fireResize, null, {buffer: 100}); + } + resize.addListener(fn, scope, options); + }, + + + fireResize: function() { + var w = Ext.Element.getViewWidth(), + h = Ext.Element.getViewHeight(); + + + if (EventManager.curHeight != h || EventManager.curWidth != w) { + EventManager.curHeight = h; + EventManager.curWidth = w; + EventManager.resizeEvent.fire(w, h); + } + }, + + + removeResizeListener: function(fn, scope) { + var resize = EventManager.resizeEvent; + if (resize) { + resize.removeListener(fn, scope); + } + }, + + + onWindowUnload: function(fn, scope, options) { + var unload = EventManager.unloadEvent; + + if (!unload) { + EventManager.unloadEvent = unload = new Ext.util.Event(); + EventManager.addListener(win, 'unload', EventManager.fireUnload); + } + if (fn) { + unload.addListener(fn, scope, options); + } + }, + + + fireUnload: function() { + + try { + + doc = win = undefined; + + var gridviews, i, ln, + el, cache; + + EventManager.unloadEvent.fire(); + + if (Ext.isGecko3) { + gridviews = Ext.ComponentQuery.query('gridview'); + i = 0; + ln = gridviews.length; + for (; i < ln; i++) { + gridviews[i].scrollToTop(); + } + } + + cache = Ext.cache; + + for (el in cache) { + if (cache.hasOwnProperty(el)) { + EventManager.removeAll(el); + } + } + } catch(e) { + } + }, + + + removeUnloadListener: function(fn, scope) { + var unload = EventManager.unloadEvent; + if (unload) { + unload.removeListener(fn, scope); + } + }, + + + useKeyDown: Ext.isWebKit ? + parseInt(navigator.userAgent.match(/AppleWebKit\/(\d+)/)[1], 10) >= 525 : + !((Ext.isGecko && !Ext.isWindows) || Ext.isOpera), + + + getKeyEvent: function() { + return EventManager.useKeyDown ? 'keydown' : 'keypress'; + } + }); + + + if(!('addEventListener' in document) && document.attachEvent) { + Ext.apply( EventManager, { + + + + pollScroll : function() { + var scrollable = true; + + try { + document.documentElement.doScroll('left'); + } catch(e) { + scrollable = false; + } + + if (scrollable) { + EventManager.onReadyEvent({ + type:'doScroll' + }); + } else { + + EventManager.scrollTimeout = setTimeout(EventManager.pollScroll, 20); + } + + return scrollable; + }, + + + scrollTimeout: null, + + + readyStatesRe : /complete/i, + + + checkReadyState: function() { + var state = document.readyState; + + if (EventManager.readyStatesRe.test(state)) { + EventManager.onReadyEvent({ + type: state + }); + } + }, + + bindReadyEvent: function() { + var topContext = true; + + if (EventManager.hasBoundOnReady) { + return; + } + + + try { + topContext = !window.frameElement; + } catch(e) { + } + + if (!topContext || !doc.documentElement.doScroll) { + EventManager.pollScroll = Ext.emptyFn; + } + + + if (EventManager.pollScroll() === true) { + return; + } + + + if (doc.readyState == 'complete' ) { + EventManager.onReadyEvent({type: 'already ' + (doc.readyState || 'body') }); + } else { + doc.attachEvent('onreadystatechange', EventManager.checkReadyState); + window.attachEvent('onload', EventManager.onReadyEvent); + EventManager.hasBoundOnReady = true; + } + }, + + onReadyEvent : function(e) { + if (e && e.type) { + EventManager.onReadyChain.push(e.type); + } + + if (EventManager.hasBoundOnReady) { + document.detachEvent('onreadystatechange', EventManager.checkReadyState); + window.detachEvent('onload', EventManager.onReadyEvent); + } + + if (Ext.isNumber(EventManager.scrollTimeout)) { + clearTimeout(EventManager.scrollTimeout); + delete EventManager.scrollTimeout; + } + + if (!Ext.isReady) { + EventManager.fireDocReady(); + } + }, + + + onReadyChain : [] + }); + } + + + + Ext.onReady = function(fn, scope, options) { + Ext.Loader.onReady(fn, scope, true, options); + }; + + + Ext.onDocumentReady = EventManager.onDocumentReady; + + + EventManager.on = EventManager.addListener; + + + EventManager.un = EventManager.removeListener; + + Ext.onReady(initExtCss); +}; + + +Ext.define('Ext.EventObjectImpl', { + uses: ['Ext.util.Point'], + + + BACKSPACE: 8, + + TAB: 9, + + NUM_CENTER: 12, + + ENTER: 13, + + RETURN: 13, + + SHIFT: 16, + + CTRL: 17, + + ALT: 18, + + PAUSE: 19, + + CAPS_LOCK: 20, + + ESC: 27, + + SPACE: 32, + + PAGE_UP: 33, + + PAGE_DOWN: 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, + + WHEEL_SCALE: (function () { + var scale; + + if (Ext.isGecko) { + + scale = 3; + } else if (Ext.isMac) { + + + + + if (Ext.isSafari && Ext.webKitVersion >= 532.0) { + + + + + + + scale = 120; + } else { + + + scale = 12; + } + + + + + + scale *= 3; + } else { + + scale = 120; + } + + return scale; + }()), + + + 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 + }, + + + + + + constructor: function(event, freezeEvent){ + if (event) { + this.setEvent(event.browserEvent || event, freezeEvent); + } + }, + + setEvent: function(event, freezeEvent){ + var me = this, button, options; + + if (event == me || (event && event.browserEvent)) { + return event; + } + me.browserEvent = event; + if (event) { + + button = event.button ? me.btnMap[event.button] : (event.which ? event.which - 1 : -1); + if (me.clickRe.test(event.type) && button == -1) { + button = 0; + } + options = { + type: event.type, + button: button, + shiftKey: event.shiftKey, + + ctrlKey: event.ctrlKey || event.metaKey || false, + altKey: event.altKey, + + keyCode: event.keyCode, + charCode: event.charCode, + + target: Ext.EventManager.getTarget(event), + relatedTarget: Ext.EventManager.getRelatedTarget(event), + currentTarget: event.currentTarget, + xy: (freezeEvent ? me.getXY() : null) + }; + } else { + options = { + button: -1, + shiftKey: false, + ctrlKey: false, + altKey: false, + keyCode: 0, + charCode: 0, + target: null, + xy: [0, 0] + }; + } + Ext.apply(me, options); + return me; + }, + + + stopEvent: function(){ + this.stopPropagation(); + this.preventDefault(); + }, + + + preventDefault: function(){ + if (this.browserEvent) { + Ext.EventManager.preventDefault(this.browserEvent); + } + }, + + + stopPropagation: function(){ + var browserEvent = this.browserEvent; + + if (browserEvent) { + if (browserEvent.type == 'mousedown') { + Ext.EventManager.stoppedMouseDownEvent.fire(this); + } + Ext.EventManager.stopPropagation(browserEvent); + } + }, + + + getCharCode: function(){ + return this.charCode || this.keyCode; + }, + + + getKey: function(){ + return this.normalizeKey(this.keyCode || this.charCode); + }, + + + normalizeKey: function(key){ + + return Ext.isWebKit ? (this.safariKeys[key] || key) : key; + }, + + + getPageX: function(){ + return this.getX(); + }, + + + getPageY: function(){ + return this.getY(); + }, + + + getX: function() { + return this.getXY()[0]; + }, + + + getY: function() { + return this.getXY()[1]; + }, + + + getXY: function() { + if (!this.xy) { + + this.xy = Ext.EventManager.getPageXY(this.browserEvent); + } + return this.xy; + }, + + + getTarget : function(selector, maxDepth, returnEl){ + if (selector) { + return Ext.fly(this.target).findParent(selector, maxDepth, returnEl); + } + return returnEl ? Ext.get(this.target) : this.target; + }, + + + getRelatedTarget : function(selector, maxDepth, returnEl){ + if (selector) { + return Ext.fly(this.relatedTarget).findParent(selector, maxDepth, returnEl); + } + return returnEl ? Ext.get(this.relatedTarget) : this.relatedTarget; + }, + + + correctWheelDelta : function (delta) { + var scale = this.WHEEL_SCALE, + ret = Math.round(delta / scale); + + if (!ret && delta) { + ret = (delta < 0) ? -1 : 1; + } + + return ret; + }, + + + getWheelDeltas : function () { + var me = this, + event = me.browserEvent, + dx = 0, dy = 0; + + if (Ext.isDefined(event.wheelDeltaX)) { + dx = event.wheelDeltaX; + dy = event.wheelDeltaY; + } else if (event.wheelDelta) { + dy = event.wheelDelta; + } else if (event.detail) { + dy = -event.detail; + + + + if (dy > 100) { + dy = 3; + } else if (dy < -100) { + dy = -3; + } + + + + if (Ext.isDefined(event.axis) && event.axis === event.HORIZONTAL_AXIS) { + dx = dy; + dy = 0; + } + } + + return { + x: me.correctWheelDelta(dx), + y: me.correctWheelDelta(dy) + }; + }, + + + getWheelDelta : function(){ + var deltas = this.getWheelDeltas(); + + return deltas.y; + }, + + + within : function(el, related, allowEl){ + if(el){ + var t = related ? this.getRelatedTarget() : this.getTarget(), + result; + + if (t) { + result = Ext.fly(el).contains(t); + if (!result && allowEl) { + result = t == Ext.getDom(el); + } + return result; + } + } + return false; + }, + + + 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(){ + var xy = this.getXY(); + return new Ext.util.Point(xy[0], xy[1]); + }, + + + hasModifier : function(){ + return this.ctrlKey || this.altKey || this.shiftKey || this.metaKey; + }, + + + injectEvent: (function () { + var API, + dispatchers = {}, + crazyIEButtons; + + + + + + + if (!Ext.isIE && document.createEvent) { + API = { + createHtmlEvent: function (doc, type, bubbles, cancelable) { + var event = doc.createEvent('HTMLEvents'); + + event.initEvent(type, bubbles, cancelable); + return event; + }, + + createMouseEvent: function (doc, type, bubbles, cancelable, detail, + clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, + button, relatedTarget) { + var event = doc.createEvent('MouseEvents'), + view = doc.defaultView || window; + + if (event.initMouseEvent) { + event.initMouseEvent(type, bubbles, cancelable, view, detail, + clientX, clientY, clientX, clientY, ctrlKey, altKey, + shiftKey, metaKey, button, relatedTarget); + } else { + event = doc.createEvent('UIEvents'); + event.initEvent(type, bubbles, cancelable); + event.view = view; + event.detail = detail; + event.screenX = clientX; + event.screenY = clientY; + event.clientX = clientX; + event.clientY = clientY; + event.ctrlKey = ctrlKey; + event.altKey = altKey; + event.metaKey = metaKey; + event.shiftKey = shiftKey; + event.button = button; + event.relatedTarget = relatedTarget; + } + + return event; + }, + + createUIEvent: function (doc, type, bubbles, cancelable, detail) { + var event = doc.createEvent('UIEvents'), + view = doc.defaultView || window; + + event.initUIEvent(type, bubbles, cancelable, view, detail); + return event; + }, + + fireEvent: function (target, type, event) { + target.dispatchEvent(event); + }, + + fixTarget: function (target) { + + if (target == window && !target.dispatchEvent) { + return document; + } + + return target; + } + }; + } else if (document.createEventObject) { + crazyIEButtons = { 0: 1, 1: 4, 2: 2 }; + + API = { + createHtmlEvent: function (doc, type, bubbles, cancelable) { + var event = doc.createEventObject(); + event.bubbles = bubbles; + event.cancelable = cancelable; + return event; + }, + + createMouseEvent: function (doc, type, bubbles, cancelable, detail, + clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, + button, relatedTarget) { + var event = doc.createEventObject(); + event.bubbles = bubbles; + event.cancelable = cancelable; + event.detail = detail; + event.screenX = clientX; + event.screenY = clientY; + event.clientX = clientX; + event.clientY = clientY; + event.ctrlKey = ctrlKey; + event.altKey = altKey; + event.shiftKey = shiftKey; + event.metaKey = metaKey; + event.button = crazyIEButtons[button] || button; + event.relatedTarget = relatedTarget; + return event; + }, + + createUIEvent: function (doc, type, bubbles, cancelable, detail) { + var event = doc.createEventObject(); + event.bubbles = bubbles; + event.cancelable = cancelable; + return event; + }, + + fireEvent: function (target, type, event) { + target.fireEvent('on' + type, event); + }, + + fixTarget: function (target) { + if (target == document) { + + + return document.documentElement; + } + + return target; + } + }; + } + + + + + Ext.Object.each({ + load: [false, false], + unload: [false, false], + select: [true, false], + change: [true, false], + submit: [true, true], + reset: [true, false], + resize: [true, false], + scroll: [true, false] + }, + function (name, value) { + var bubbles = value[0], cancelable = value[1]; + dispatchers[name] = function (targetEl, srcEvent) { + var e = API.createHtmlEvent(name, bubbles, cancelable); + API.fireEvent(targetEl, name, e); + }; + }); + + + + + function createMouseEventDispatcher (type, detail) { + var cancelable = (type != 'mousemove'); + return function (targetEl, srcEvent) { + var xy = srcEvent.getXY(), + e = API.createMouseEvent(targetEl.ownerDocument, type, true, cancelable, + detail, xy[0], xy[1], srcEvent.ctrlKey, srcEvent.altKey, + srcEvent.shiftKey, srcEvent.metaKey, srcEvent.button, + srcEvent.relatedTarget); + API.fireEvent(targetEl, type, e); + }; + } + + Ext.each(['click', 'dblclick', 'mousedown', 'mouseup', 'mouseover', 'mousemove', 'mouseout'], + function (eventName) { + dispatchers[eventName] = createMouseEventDispatcher(eventName, 1); + }); + + + + + Ext.Object.each({ + focusin: [true, false], + focusout: [true, false], + activate: [true, true], + focus: [false, false], + blur: [false, false] + }, + function (name, value) { + var bubbles = value[0], cancelable = value[1]; + dispatchers[name] = function (targetEl, srcEvent) { + var e = API.createUIEvent(targetEl.ownerDocument, name, bubbles, cancelable, 1); + API.fireEvent(targetEl, name, e); + }; + }); + + + if (!API) { + + + dispatchers = {}; + + API = { + fixTarget: function (t) { + return t; + } + }; + } + + function cannotInject (target, srcEvent) { + } + + return function (target) { + var me = this, + dispatcher = dispatchers[me.type] || cannotInject, + t = target ? (target.dom || target) : me.getTarget(); + + t = API.fixTarget(t); + dispatcher(t, me); + }; + }()) + +}, function() { + +Ext.EventObject = new Ext.EventObjectImpl(); + +}); + + + +Ext.define('Ext.dom.AbstractQuery', { + + select: function(q, root) { + var results = [], + nodes, + i, + j, + qlen, + nlen; + + root = root || document; + + if (typeof root == 'string') { + root = document.getElementById(root); + } + + q = q.split(","); + + for (i = 0,qlen = q.length; i < qlen; i++) { + if (typeof q[i] == 'string') { + + + if (typeof q[i][0] == '@') { + nodes = root.getAttributeNode(q[i].substring(1)); + results.push(nodes); + } else { + nodes = root.querySelectorAll(q[i]); + + for (j = 0,nlen = nodes.length; j < nlen; j++) { + results.push(nodes[j]); + } + } + } + } + + return results; + }, + + + selectNode: function(q, root) { + return this.select(q, root)[0]; + }, + + + is: function(el, q) { + if (typeof el == "string") { + el = document.getElementById(el); + } + return this.select(q).indexOf(el) !== -1; + } + +}); + + +Ext.define('Ext.dom.AbstractHelper', { + emptyTags : /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i, + confRe : /tag|children|cn|html|tpl|tplData$/i, + endRe : /end/i, + + attribXlat: { cls : 'class', htmlFor : 'for' }, + + closeTags: {}, + + decamelizeName : (function () { + var camelCaseRe = /([a-z])([A-Z])/g, + cache = {}; + + function decamel (match, p1, p2) { + return p1 + '-' + p2.toLowerCase(); + } + + return function (s) { + return cache[s] || (cache[s] = s.replace(camelCaseRe, decamel)); + }; + }()), + + generateMarkup: function(spec, buffer) { + var me = this, + attr, val, tag, i, closeTags; + + if (typeof spec == "string") { + buffer.push(spec); + } else if (Ext.isArray(spec)) { + for (i = 0; i < spec.length; i++) { + if (spec[i]) { + me.generateMarkup(spec[i], buffer); + } + } + } else { + tag = spec.tag || 'div'; + buffer.push('<', tag); + + for (attr in spec) { + if (spec.hasOwnProperty(attr)) { + val = spec[attr]; + if (!me.confRe.test(attr)) { + if (typeof val == "object") { + buffer.push(' ', attr, '="'); + me.generateStyles(val, buffer).push('"'); + } else { + buffer.push(' ', me.attribXlat[attr] || attr, '="', val, '"'); + } + } + } + } + + + if (me.emptyTags.test(tag)) { + buffer.push('/>'); + } else { + buffer.push('>'); + + + if ((val = spec.tpl)) { + val.applyOut(spec.tplData, buffer); + } + if ((val = spec.html)) { + buffer.push(val); + } + if ((val = spec.cn || spec.children)) { + me.generateMarkup(val, buffer); + } + + + closeTags = me.closeTags; + buffer.push(closeTags[tag] || (closeTags[tag] = '')); + } + } + + return buffer; + }, + + + generateStyles: function (styles, buffer) { + var a = buffer || [], + name; + + for (name in styles) { + if (styles.hasOwnProperty(name)) { + a.push(this.decamelizeName(name), ':', styles[name], ';'); + } + } + + return buffer || a.join(''); + }, + + + markup: function(spec) { + if (typeof spec == "string") { + return spec; + } + + var buf = this.generateMarkup(spec, []); + return buf.join(''); + }, + + + applyStyles: function(el, styles) { + if (styles) { + var i = 0, + len, + style; + + el = Ext.fly(el); + if (typeof styles == 'function') { + styles = styles.call(); + } + if (typeof styles == 'string'){ + styles = Ext.util.Format.trim(styles).split(/\s*(?::|;)\s*/); + for(len = styles.length; i < len;){ + el.setStyle(styles[i++], styles[i++]); + } + } else if (Ext.isObject(styles)) { + el.setStyle(styles); + } + } + }, + + + insertHtml: function(where, el, html) { + var hash = {}, + hashVal, + setStart, + range, + frag, + rangeEl, + rs; + + where = where.toLowerCase(); + + + hash['beforebegin'] = ['BeforeBegin', 'previousSibling']; + hash['afterend'] = ['AfterEnd', 'nextSibling']; + + range = el.ownerDocument.createRange(); + setStart = 'setStart' + (this.endRe.test(where) ? 'After' : 'Before'); + if (hash[where]) { + range[setStart](el); + frag = range.createContextualFragment(html); + el.parentNode.insertBefore(frag, where == 'beforebegin' ? el : el.nextSibling); + return el[(where == 'beforebegin' ? 'previous' : 'next') + 'Sibling']; + } + else { + rangeEl = (where == 'afterbegin' ? 'first' : 'last') + 'Child'; + if (el.firstChild) { + range[setStart](el[rangeEl]); + frag = range.createContextualFragment(html); + if (where == 'afterbegin') { + el.insertBefore(frag, el.firstChild); + } + else { + el.appendChild(frag); + } + } + else { + el.innerHTML = html; + } + return el[rangeEl]; + } + + throw 'Illegal insertion point -> "' + where + '"'; + }, + + + insertBefore: function(el, o, returnElement) { + return this.doInsert(el, o, returnElement, 'beforebegin'); + }, + + + insertAfter: function(el, o, returnElement) { + return this.doInsert(el, o, returnElement, 'afterend', 'nextSibling'); + }, + + + insertFirst: function(el, o, returnElement) { + return this.doInsert(el, o, returnElement, 'afterbegin', 'firstChild'); + }, + + + append: function(el, o, returnElement) { + return this.doInsert(el, o, returnElement, 'beforeend', '', true); + }, + + + overwrite: function(el, o, returnElement) { + el = Ext.getDom(el); + el.innerHTML = this.markup(o); + return returnElement ? Ext.get(el.firstChild) : el.firstChild; + }, + + doInsert: function(el, o, returnElement, pos, sibling, append) { + var newNode = this.insertHtml(pos, Ext.getDom(el), this.markup(o)); + return returnElement ? Ext.get(newNode, true) : newNode; + } + +}); + + +(function() { + +var document = window.document, + trimRe = /^\s+|\s+$/g, + whitespaceRe = /\s/; + +if (!Ext.cache){ + Ext.cache = {}; +} + +Ext.define('Ext.dom.AbstractElement', { + + inheritableStatics: { + + + get: function(el) { + var me = this, + El = Ext.dom.Element, + cache, + extEl, + dom, + id; + + if (!el) { + return null; + } + + if (typeof el == "string") { + if (el == Ext.windowId) { + return El.get(window); + } else if (el == Ext.documentId) { + return El.get(document); + } + + cache = Ext.cache[el]; + + + + + if (cache && cache.skipGarbageCollection) { + extEl = cache.el; + return extEl; + } + + if (!(dom = document.getElementById(el))) { + return null; + } + + if (cache && cache.el) { + extEl = cache.el; + extEl.dom = dom; + } else { + + extEl = new El(dom, !!cache); + } + return extEl; + } else if (el.tagName) { + if (!(id = el.id)) { + id = Ext.id(el); + } + cache = Ext.cache[id]; + if (cache && cache.el) { + extEl = Ext.cache[id].el; + extEl.dom = el; + } else { + + extEl = new El(el, !!cache); + } + return extEl; + } else if (el instanceof me) { + if (el != me.docEl && el != me.winEl) { + + + el.dom = document.getElementById(el.id) || el.dom; + } + return el; + } else if (el.isComposite) { + return el; + } else if (Ext.isArray(el)) { + return me.select(el); + } else if (el === document) { + + if (!me.docEl) { + me.docEl = Ext.Object.chain(El.prototype); + me.docEl.dom = document; + me.docEl.id = Ext.id(document); + me.addToCache(me.docEl); + } + return me.docEl; + } else if (el === window) { + if (!me.winEl) { + me.winEl = Ext.Object.chain(El.prototype); + me.winEl.dom = window; + me.winEl.id = Ext.id(window); + me.addToCache(me.winEl); + } + return me.winEl; + } + return null; + }, + + addToCache: function(el, id) { + if (el) { + Ext.addCacheEntry(id, el); + } + return el; + }, + + addMethods: function() { + this.override.apply(this, arguments); + }, + + + mergeClsList: function() { + var clsList, clsHash = {}, + i, length, j, listLength, clsName, result = [], + changed = false; + + for (i = 0, length = arguments.length; i < length; i++) { + clsList = arguments[i]; + if (Ext.isString(clsList)) { + clsList = clsList.replace(trimRe, '').split(whitespaceRe); + } + if (clsList) { + for (j = 0, listLength = clsList.length; j < listLength; j++) { + clsName = clsList[j]; + if (!clsHash[clsName]) { + if (i) { + changed = true; + } + clsHash[clsName] = true; + } + } + } + } + + for (clsName in clsHash) { + result.push(clsName); + } + result.changed = changed; + return result; + }, + + + removeCls: function(existingClsList, removeClsList) { + var clsHash = {}, + i, length, clsName, result = [], + changed = false; + + if (existingClsList) { + if (Ext.isString(existingClsList)) { + existingClsList = existingClsList.replace(trimRe, '').split(whitespaceRe); + } + for (i = 0, length = existingClsList.length; i < length; i++) { + clsHash[existingClsList[i]] = true; + } + } + if (removeClsList) { + if (Ext.isString(removeClsList)) { + removeClsList = removeClsList.split(whitespaceRe); + } + for (i = 0, length = removeClsList.length; i < length; i++) { + clsName = removeClsList[i]; + if (clsHash[clsName]) { + changed = true; + delete clsHash[clsName]; + } + } + } + for (clsName in clsHash) { + result.push(clsName); + } + result.changed = changed; + return result; + }, + + + VISIBILITY: 1, + + + DISPLAY: 2, + + + OFFSETS: 3, + + + ASCLASS: 4 + }, + + constructor: function(element, forceNew) { + var me = this, + dom = typeof element == 'string' + ? document.getElementById(element) + : element, + id; + + if (!dom) { + return null; + } + + id = dom.id; + if (!forceNew && id && Ext.cache[id]) { + + return Ext.cache[id].el; + } + + + me.dom = dom; + + + me.id = id || Ext.id(dom); + + me.self.addToCache(me); + }, + + + set: function(o, useSet) { + var el = this.dom, + attr, + value; + + for (attr in o) { + if (o.hasOwnProperty(attr)) { + value = o[attr]; + if (attr == 'style') { + this.applyStyles(value); + } + else if (attr == 'cls') { + el.className = value; + } + else if (useSet !== false) { + if (value === undefined) { + el.removeAttribute(attr); + } else { + el.setAttribute(attr, value); + } + } + else { + el[attr] = value; + } + } + } + return this; + }, + + + defaultUnit: "px", + + + is: function(simpleSelector) { + return Ext.DomQuery.is(this.dom, simpleSelector); + }, + + + getValue: function(asNumber) { + var val = this.dom.value; + return asNumber ? parseInt(val, 10) : val; + }, + + + remove: function() { + var me = this, + dom = me.dom; + + if (dom) { + Ext.removeNode(dom); + delete me.dom; + } + }, + + + contains: function(el) { + if (!el) { + return false; + } + + var me = this, + dom = el.dom || el; + + + return (dom === me.dom) || Ext.dom.AbstractElement.isAncestor(me.dom, dom); + }, + + + getAttribute: function(name, ns) { + var dom = this.dom; + return dom.getAttributeNS(ns, name) || dom.getAttribute(ns + ":" + name) || dom.getAttribute(name) || dom[name]; + }, + + + update: function(html) { + if (this.dom) { + this.dom.innerHTML = html; + } + return this; + }, + + + + setHTML: function(html) { + if(this.dom) { + this.dom.innerHTML = html; + } + return this; + }, + + + getHTML: function() { + return this.dom ? this.dom.innerHTML : ''; + }, + + + hide: function() { + this.setVisible(false); + return this; + }, + + + show: function() { + this.setVisible(true); + return this; + }, + + + setVisible: function(visible, animate) { + var me = this, + statics = me.self, + mode = me.getVisibilityMode(), + prefix = Ext.baseCSSPrefix; + + switch (mode) { + case statics.VISIBILITY: + me.removeCls([prefix + 'hidden-display', prefix + 'hidden-offsets']); + me[visible ? 'removeCls' : 'addCls'](prefix + 'hidden-visibility'); + break; + + case statics.DISPLAY: + me.removeCls([prefix + 'hidden-visibility', prefix + 'hidden-offsets']); + me[visible ? 'removeCls' : 'addCls'](prefix + 'hidden-display'); + break; + + case statics.OFFSETS: + me.removeCls([prefix + 'hidden-visibility', prefix + 'hidden-display']); + me[visible ? 'removeCls' : 'addCls'](prefix + 'hidden-offsets'); + break; + } + + return me; + }, + + getVisibilityMode: function() { + + + + var data = (this.$cache || this.getCache()).data, + visMode = data.visibilityMode; + + if (visMode === undefined) { + data.visibilityMode = visMode = this.self.DISPLAY; + } + + return visMode; + }, + + + setVisibilityMode: function(mode) { + (this.$cache || this.getCache()).data.visibilityMode = mode; + return this; + }, + + getCache: function() { + var me = this, + id = me.dom.id || Ext.id(me.dom); + + + + + me.$cache = Ext.cache[id] || Ext.addCacheEntry(id, null, me.dom); + + return me.$cache; + } + +}, function() { + var AbstractElement = this; + + Ext.getDetachedBody = function () { + var detachedEl = AbstractElement.detachedBodyEl; + + if (!detachedEl) { + detachedEl = document.createElement('div'); + AbstractElement.detachedBodyEl = detachedEl = new AbstractElement.Fly(detachedEl); + detachedEl.isDetachedBody = true; + } + + return detachedEl; + }; + + Ext.getElementById = function (id) { + var el = document.getElementById(id), + detachedBodyEl; + + if (!el && (detachedBodyEl = AbstractElement.detachedBodyEl)) { + el = detachedBodyEl.dom.querySelector('#' + Ext.escapeId(id)); + } + + return el; + }; + + + Ext.get = function(el) { + return Ext.dom.Element.get(el); + }; + + this.addStatics({ + + Fly: new Ext.Class({ + extend: AbstractElement, + + + isFly: true, + + constructor: function(dom) { + this.dom = dom; + }, + + + attach: function (dom) { + + + this.dom = dom; + + + this.$cache = dom.id ? Ext.cache[dom.id] : null; + return this; + } + }), + + _flyweights: {}, + + + fly: function(dom, named) { + var fly = null, + _flyweights = AbstractElement._flyweights; + + named = named || '_global'; + + dom = Ext.getDom(dom); + + if (dom) { + fly = _flyweights[named] || (_flyweights[named] = new AbstractElement.Fly()); + + + + fly.dom = dom; + + + fly.$cache = dom.id ? Ext.cache[dom.id] : null; + } + return fly; + } + }); + + + Ext.fly = function() { + return AbstractElement.fly.apply(AbstractElement, arguments); + }; + + (function (proto) { + + proto.destroy = proto.remove; + + + if (document.querySelector) { + proto.getById = function (id, asDom) { + + + var dom = document.getElementById(id) || + this.dom.querySelector('#'+Ext.escapeId(id)); + return asDom ? dom : (dom ? Ext.get(dom) : null); + }; + } else { + proto.getById = function (id, asDom) { + var dom = document.getElementById(id); + return asDom ? dom : (dom ? Ext.get(dom) : null); + }; + } + }(this.prototype)); +}); + +}()); + + +Ext.dom.AbstractElement.addInheritableStatics({ + unitRe: /\d+(px|em|%|en|ex|pt|in|cm|mm|pc)$/i, + camelRe: /(-[a-z])/gi, + cssRe: /([a-z0-9\-]+)\s*:\s*([^;\s]+(?:\s*[^;\s]+)*);?/gi, + opacityRe: /alpha\(opacity=(.*)\)/i, + propertyCache: {}, + defaultUnit : "px", + 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'}, + + addUnits: function(size, units) { + + if (typeof size == 'number') { + return size + (units || this.defaultUnit || 'px'); + } + + + if (size === "" || size == "auto" || size === undefined || size === null) { + return size || ''; + } + + + if (!this.unitRe.test(size)) { + return size || ''; + } + + return size; + }, + + + isAncestor: function(p, c) { + var ret = false; + + p = Ext.getDom(p); + c = Ext.getDom(c); + if (p && c) { + if (p.contains) { + return p.contains(c); + } else if (p.compareDocumentPosition) { + return !!(p.compareDocumentPosition(c) & 16); + } else { + while ((c = c.parentNode)) { + ret = c == p || ret; + } + } + } + return ret; + }, + + + parseBox: function(box) { + if (typeof box != 'string') { + box = box.toString(); + } + var parts = box.split(' '), + ln = parts.length; + + if (ln == 1) { + parts[1] = parts[2] = parts[3] = parts[0]; + } + else if (ln == 2) { + parts[2] = parts[0]; + parts[3] = parts[1]; + } + else if (ln == 3) { + parts[3] = parts[1]; + } + + return { + top :parseFloat(parts[0]) || 0, + right :parseFloat(parts[1]) || 0, + bottom:parseFloat(parts[2]) || 0, + left :parseFloat(parts[3]) || 0 + }; + }, + + + unitizeBox: function(box, units) { + var a = this.addUnits, + b = this.parseBox(box); + + return a(b.top, units) + ' ' + + a(b.right, units) + ' ' + + a(b.bottom, units) + ' ' + + a(b.left, units); + + }, + + + camelReplaceFn: function(m, a) { + return a.charAt(1).toUpperCase(); + }, + + + normalize: function(prop) { + + if (prop == 'float') { + prop = Ext.supports.Float ? 'cssFloat' : 'styleFloat'; + } + return this.propertyCache[prop] || (this.propertyCache[prop] = prop.replace(this.camelRe, this.camelReplaceFn)); + }, + + + getDocumentHeight: function() { + return Math.max(!Ext.isStrict ? document.body.scrollHeight : document.documentElement.scrollHeight, this.getViewportHeight()); + }, + + + getDocumentWidth: function() { + return Math.max(!Ext.isStrict ? document.body.scrollWidth : document.documentElement.scrollWidth, this.getViewportWidth()); + }, + + + getViewportHeight: function(){ + return window.innerHeight; + }, + + + getViewportWidth: function() { + return window.innerWidth; + }, + + + getViewSize: function() { + return { + width: window.innerWidth, + height: window.innerHeight + }; + }, + + + getOrientation: function() { + if (Ext.supports.OrientationChange) { + return (window.orientation == 0) ? 'portrait' : 'landscape'; + } + + return (window.innerHeight > window.innerWidth) ? 'portrait' : 'landscape'; + }, + + + fromPoint: function(x, y) { + return Ext.get(document.elementFromPoint(x, y)); + }, + + + parseStyles: function(styles){ + var out = {}, + cssRe = this.cssRe, + matches; + + if (styles) { + + + + + cssRe.lastIndex = 0; + while ((matches = cssRe.exec(styles))) { + out[matches[1]] = matches[2]; + } + } + return out; + } +}); + + +(function(){ + var doc = document, + AbstractElement = Ext.dom.AbstractElement, + activeElement = null, + isCSS1 = doc.compatMode == "CSS1Compat", + flyInstance, + fly = function (el) { + if (!flyInstance) { + flyInstance = new AbstractElement.Fly(); + } + flyInstance.attach(el); + return flyInstance; + }; + + + + + if (!('activeElement' in doc) && doc.addEventListener) { + doc.addEventListener('focus', + function (ev) { + if (ev && ev.target) { + activeElement = (ev.target == doc) ? null : ev.target; + } + }, true); + } + + + function makeSelectionRestoreFn (activeEl, start, end) { + return function () { + activeEl.selectionStart = start; + activeEl.selectionEnd = end; + }; + } + + AbstractElement.addInheritableStatics({ + + getActiveElement: function () { + return doc.activeElement || activeElement; + }, + + + getRightMarginFixCleaner: function (target) { + var supports = Ext.supports, + hasInputBug = supports.DisplayChangeInputSelectionBug, + hasTextAreaBug = supports.DisplayChangeTextAreaSelectionBug, + activeEl, + tag, + start, + end; + + if (hasInputBug || hasTextAreaBug) { + activeEl = doc.activeElement || activeElement; + tag = activeEl && activeEl.tagName; + + if ((hasTextAreaBug && tag == 'TEXTAREA') || + (hasInputBug && tag == 'INPUT' && activeEl.type == 'text')) { + if (Ext.dom.Element.isAncestor(target, activeEl)) { + start = activeEl.selectionStart; + end = activeEl.selectionEnd; + + if (Ext.isNumber(start) && Ext.isNumber(end)) { + + + + + return makeSelectionRestoreFn(activeEl, start, end); + } + } + } + } + + return Ext.emptyFn; + }, + + getViewWidth: function(full) { + return full ? Ext.dom.Element.getDocumentWidth() : Ext.dom.Element.getViewportWidth(); + }, + + getViewHeight: function(full) { + return full ? Ext.dom.Element.getDocumentHeight() : Ext.dom.Element.getViewportHeight(); + }, + + getDocumentHeight: function() { + return Math.max(!isCSS1 ? doc.body.scrollHeight : doc.documentElement.scrollHeight, Ext.dom.Element.getViewportHeight()); + }, + + getDocumentWidth: function() { + return Math.max(!isCSS1 ? doc.body.scrollWidth : doc.documentElement.scrollWidth, Ext.dom.Element.getViewportWidth()); + }, + + getViewportHeight: function(){ + return Ext.isIE ? + (Ext.isStrict ? doc.documentElement.clientHeight : doc.body.clientHeight) : + self.innerHeight; + }, + + getViewportWidth: function() { + return (!Ext.isStrict && !Ext.isOpera) ? doc.body.clientWidth : + Ext.isIE ? doc.documentElement.clientWidth : self.innerWidth; + }, + + getY: function(el) { + return Ext.dom.Element.getXY(el)[1]; + }, + + getX: function(el) { + return Ext.dom.Element.getXY(el)[0]; + }, + + getXY: function(el) { + var bd = doc.body, + docEl = doc.documentElement, + leftBorder = 0, + topBorder = 0, + ret = [0,0], + round = Math.round, + box, + scroll; + + el = Ext.getDom(el); + + if(el != doc && el != bd){ + + + if (Ext.isIE) { + try { + box = el.getBoundingClientRect(); + + topBorder = docEl.clientTop || bd.clientTop; + leftBorder = docEl.clientLeft || bd.clientLeft; + } catch (ex) { + box = { left: 0, top: 0 }; + } + } else { + box = el.getBoundingClientRect(); + } + + scroll = fly(document).getScroll(); + ret = [round(box.left + scroll.left - leftBorder), round(box.top + scroll.top - topBorder)]; + } + return ret; + }, + + setXY: function(el, xy) { + (el = Ext.fly(el, '_setXY')).position(); + + var pts = el.translatePoints(xy), + style = el.dom.style, + pos; + + for (pos in pts) { + if (!isNaN(pts[pos])) { + style[pos] = pts[pos] + "px"; + } + } + }, + + setX: function(el, x) { + Ext.dom.Element.setXY(el, [x, false]); + }, + + setY: function(el, y) { + Ext.dom.Element.setXY(el, [false, y]); + }, + + + serializeForm: function(form) { + var fElements = form.elements || (document.forms[form] || Ext.getDom(form)).elements, + hasSubmit = false, + encoder = encodeURIComponent, + data = '', + eLen = fElements.length, + element, name, type, options, hasValue, e, + o, oLen, opt; + + for (e = 0; e < eLen; e++) { + element = fElements[e]; + name = element.name; + type = element.type; + options = element.options; + + if (!element.disabled && name) { + if (/select-(one|multiple)/i.test(type)) { + oLen = options.length; + for (o = 0; o < oLen; o++) { + opt = options[o]; + if (opt.selected) { + hasValue = opt.hasAttribute ? opt.hasAttribute('value') : opt.getAttributeNode('value').specified; + data += Ext.String.format("{0}={1}&", encoder(name), encoder(hasValue ? opt.value : opt.text)); + } + } + } else if (!(/file|undefined|reset|button/i.test(type))) { + if (!(/radio|checkbox/i.test(type) && !element.checked) && !(type == 'submit' && hasSubmit)) { + data += encoder(name) + '=' + encoder(element.value) + '&'; + hasSubmit = /submit/i.test(type); + } + } + } + } + return data.substr(0, data.length - 1); + } + }); +}()); + + +Ext.dom.AbstractElement.override({ + + + getAnchorXY: function(anchor, local, size) { + + + anchor = (anchor || "tl").toLowerCase(); + size = size || {}; + + var me = this, + vp = me.dom == document.body || me.dom == document, + width = size.width || vp ? window.innerWidth: me.getWidth(), + height = size.height || vp ? window.innerHeight: me.getHeight(), + xy, + rnd = Math.round, + myXY = me.getXY(), + extraX = vp ? 0: !local ? myXY[0] : 0, + extraY = vp ? 0: !local ? myXY[1] : 0, + hash = { + c: [rnd(width * 0.5), rnd(height * 0.5)], + t: [rnd(width * 0.5), 0], + l: [0, rnd(height * 0.5)], + r: [width, rnd(height * 0.5)], + b: [rnd(width * 0.5), height], + tl: [0, 0], + bl: [0, height], + br: [width, height], + tr: [width, 0] + }; + + xy = hash[anchor]; + return [xy[0] + extraX, xy[1] + extraY]; + }, + + alignToRe: /^([a-z]+)-([a-z]+)(\?)?$/, + + + getAlignToXY: function(el, position, offsets, local) { + local = !!local; + el = Ext.get(el); + + offsets = offsets || [0, 0]; + + if (!position || position == '?') { + position = 'tl-bl?'; + } + else if (! (/-/).test(position) && position !== "") { + position = 'tl-' + position; + } + position = position.toLowerCase(); + + var me = this, + matches = position.match(this.alignToRe), + dw = window.innerWidth, + dh = window.innerHeight, + p1 = "", + p2 = "", + a1, + a2, + x, + y, + swapX, + swapY, + p1x, + p1y, + p2x, + p2y, + width, + height, + region, + constrain; + + if (!matches) { + throw "Element.alignTo with an invalid alignment " + position; + } + + p1 = matches[1]; + p2 = matches[2]; + constrain = !!matches[3]; + + + + a1 = me.getAnchorXY(p1, true); + a2 = el.getAnchorXY(p2, local); + + x = a2[0] - a1[0] + offsets[0]; + y = a2[1] - a1[1] + offsets[1]; + + if (constrain) { + width = me.getWidth(); + height = me.getHeight(); + + region = el.getPageBox(); + + + + + 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 + width > dw) { + x = swapX ? region.left - width: dw - width; + } + if (x < 0) { + x = swapX ? region.right: 0; + } + if (y + height > dh) { + y = swapY ? region.top - height: dh - height; + } + if (y < 0) { + y = swapY ? region.bottom: 0; + } + } + + return [x, y]; + }, + + + getAnchor: function(){ + var data = (this.$cache || this.getCache()).data, + anchor; + + if (!this.dom) { + return; + } + anchor = data._anchor; + + if(!anchor){ + anchor = data._anchor = {}; + } + return anchor; + }, + + + adjustForConstraints: function(xy, parent) { + var vector = this.getConstrainVector(parent, xy); + if (vector) { + xy[0] += vector[0]; + xy[1] += vector[1]; + } + return xy; + } + +}); + + +Ext.dom.AbstractElement.addMethods({ + + appendChild: function(el) { + return Ext.get(el).appendTo(this); + }, + + + appendTo: function(el) { + Ext.getDom(el).appendChild(this.dom); + return this; + }, + + + insertBefore: function(el) { + el = Ext.getDom(el); + el.parentNode.insertBefore(this.dom, el); + return this; + }, + + + insertAfter: function(el) { + el = Ext.getDom(el); + el.parentNode.insertBefore(this.dom, el.nextSibling); + return this; + }, + + + insertFirst: function(el, returnDom) { + el = el || {}; + if (el.nodeType || el.dom || typeof el == 'string') { + el = Ext.getDom(el); + this.dom.insertBefore(el, this.dom.firstChild); + return !returnDom ? Ext.get(el) : el; + } + else { + return this.createChild(el, this.dom.firstChild, returnDom); + } + }, + + + insertSibling: function(el, where, returnDom){ + var me = this, + isAfter = (where || 'before').toLowerCase() == 'after', + rt, insertEl, eLen, e; + + if (Ext.isArray(el)) { + insertEl = me; + eLen = el.length; + + for (e = 0; e < eLen; e++) { + rt = Ext.fly(insertEl, '_internal').insertSibling(el[e], where, returnDom); + + if (isAfter) { + insertEl = rt; + } + } + + return rt; + } + + el = el || {}; + + if(el.nodeType || el.dom){ + rt = me.dom.parentNode.insertBefore(Ext.getDom(el), isAfter ? me.dom.nextSibling : me.dom); + if (!returnDom) { + rt = Ext.get(rt); + } + }else{ + if (isAfter && !me.dom.nextSibling) { + rt = Ext.core.DomHelper.append(me.dom.parentNode, el, !returnDom); + } else { + rt = Ext.core.DomHelper[isAfter ? 'insertAfter' : 'insertBefore'](me.dom, el, !returnDom); + } + } + return rt; + }, + + + replace: function(el) { + el = Ext.get(el); + this.insertBefore(el); + el.remove(); + return this; + }, + + + replaceWith: function(el){ + var me = this; + + if(el.nodeType || el.dom || typeof el == 'string'){ + el = Ext.get(el); + me.dom.parentNode.insertBefore(el, me.dom); + }else{ + el = Ext.core.DomHelper.insertBefore(me.dom, el); + } + + delete Ext.cache[me.id]; + Ext.removeNode(me.dom); + me.id = Ext.id(me.dom = el); + Ext.dom.AbstractElement.addToCache(me.isFlyweight ? new Ext.dom.AbstractElement(me.dom) : me); + return me; + }, + + + createChild: function(config, insertBefore, returnDom) { + config = config || {tag:'div'}; + if (insertBefore) { + return Ext.core.DomHelper.insertBefore(insertBefore, config, returnDom !== true); + } + else { + return Ext.core.DomHelper[!this.dom.firstChild ? 'insertFirst' : 'append'](this.dom, config, returnDom !== true); + } + }, + + + wrap: function(config, returnDom) { + var newEl = Ext.core.DomHelper.insertBefore(this.dom, config || {tag: "div"}, !returnDom), + d = newEl.dom || newEl; + + d.appendChild(this.dom); + return newEl; + }, + + + insertHtml: function(where, html, returnEl) { + var el = Ext.core.DomHelper.insertHtml(where, this.dom, html); + return returnEl ? Ext.get(el) : el; + } +}); + + +(function(){ + +var Element = Ext.dom.AbstractElement; + +Element.override({ + + + getX: function(el) { + return this.getXY(el)[0]; + }, + + + getY: function(el) { + return this.getXY(el)[1]; + }, + + + getXY: function() { + + var point = window.webkitConvertPointFromNodeToPage(this.dom, new WebKitPoint(0, 0)); + return [point.x, point.y]; + }, + + + getOffsetsTo: function(el){ + var o = this.getXY(), + e = Ext.fly(el, '_internal').getXY(); + return [o[0]-e[0],o[1]-e[1]]; + }, + + + setX: function(x){ + return this.setXY([x, this.getY()]); + }, + + + setY: function(y) { + return this.setXY([this.getX(), y]); + }, + + + setLeft: function(left) { + this.setStyle('left', Element.addUnits(left)); + return this; + }, + + + setTop: function(top) { + this.setStyle('top', Element.addUnits(top)); + return this; + }, + + + setRight: function(right) { + this.setStyle('right', Element.addUnits(right)); + return this; + }, + + + setBottom: function(bottom) { + this.setStyle('bottom', Element.addUnits(bottom)); + return this; + }, + + + setXY: function(pos) { + var me = this, + pts, + style, + pt; + + if (arguments.length > 1) { + pos = [pos, arguments[1]]; + } + + + pts = me.translatePoints(pos); + style = me.dom.style; + + for (pt in pts) { + if (!pts.hasOwnProperty(pt)) { + continue; + } + if (!isNaN(pts[pt])) { + style[pt] = pts[pt] + "px"; + } + } + return me; + }, + + + getLeft: function(local) { + return parseInt(this.getStyle('left'), 10) || 0; + }, + + + getRight: function(local) { + return parseInt(this.getStyle('right'), 10) || 0; + }, + + + getTop: function(local) { + return parseInt(this.getStyle('top'), 10) || 0; + }, + + + getBottom: function(local) { + return parseInt(this.getStyle('bottom'), 10) || 0; + }, + + + 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)}; + }, + + + setBox: function(box) { + var me = this, + width = box.width, + height = box.height, + top = box.top, + left = box.left; + + if (left !== undefined) { + me.setLeft(left); + } + if (top !== undefined) { + me.setTop(top); + } + if (width !== undefined) { + me.setWidth(width); + } + if (height !== undefined) { + me.setHeight(height); + } + + return this; + }, + + + getBox: function(contentBox, local) { + var me = this, + dom = me.dom, + width = dom.offsetWidth, + height = dom.offsetHeight, + xy, box, l, r, t, b; + + if (!local) { + xy = me.getXY(); + } + else if (contentBox) { + xy = [0,0]; + } + else { + xy = [parseInt(me.getStyle("left"), 10) || 0, parseInt(me.getStyle("top"), 10) || 0]; + } + + if (!contentBox) { + box = { + x: xy[0], + y: xy[1], + 0: xy[0], + 1: xy[1], + width: width, + height: height + }; + } + else { + l = me.getBorderWidth.call(me, "l") + me.getPadding.call(me, "l"); + r = me.getBorderWidth.call(me, "r") + me.getPadding.call(me, "r"); + t = me.getBorderWidth.call(me, "t") + me.getPadding.call(me, "t"); + b = me.getBorderWidth.call(me, "b") + me.getPadding.call(me, "b"); + box = { + x: xy[0] + l, + y: xy[1] + t, + 0: xy[0] + l, + 1: xy[1] + t, + width: width - (l + r), + height: height - (t + b) + }; + } + + box.left = box.x; + box.top = box.y; + box.right = box.x + box.width; + box.bottom = box.y + box.height; + + return box; + }, + + + getPageBox: function(getRegion) { + var me = this, + el = me.dom, + w = el.offsetWidth, + h = el.offsetHeight, + xy = me.getXY(), + t = xy[1], + r = xy[0] + w, + b = xy[1] + h, + l = xy[0]; + + if (!el) { + return new Ext.util.Region(); + } + + if (getRegion) { + return new Ext.util.Region(t, r, b, l); + } + else { + return { + left: l, + top: t, + width: w, + height: h, + right: r, + bottom: b + }; + } + } +}); + +}()); + + +(function(){ + + var Element = Ext.dom.AbstractElement, + view = document.defaultView, + array = Ext.Array, + trimRe = /^\s+|\s+$/g, + wordsRe = /\w/g, + spacesRe = /\s+/, + transparentRe = /^(?:transparent|(?:rgba[(](?:\s*\d+\s*[,]){3}\s*0\s*[)]))$/i, + hasClassList = Ext.supports.ClassList, + PADDING = 'padding', + MARGIN = 'margin', + BORDER = 'border', + LEFT_SUFFIX = '-left', + RIGHT_SUFFIX = '-right', + TOP_SUFFIX = '-top', + BOTTOM_SUFFIX = '-bottom', + WIDTH = '-width', + + borders = {l: BORDER + LEFT_SUFFIX + WIDTH, r: BORDER + RIGHT_SUFFIX + WIDTH, t: BORDER + TOP_SUFFIX + WIDTH, b: BORDER + BOTTOM_SUFFIX + WIDTH}, + paddings = {l: PADDING + LEFT_SUFFIX, r: PADDING + RIGHT_SUFFIX, t: PADDING + TOP_SUFFIX, b: PADDING + BOTTOM_SUFFIX}, + margins = {l: MARGIN + LEFT_SUFFIX, r: MARGIN + RIGHT_SUFFIX, t: MARGIN + TOP_SUFFIX, b: MARGIN + BOTTOM_SUFFIX}; + + + Element.override({ + + + styleHooks: {}, + + + addStyles : function(sides, styles){ + var totalSize = 0, + sidesArr = (sides || '').match(wordsRe), + i, + len = sidesArr.length, + side, + styleSides = []; + + if (len == 1) { + totalSize = Math.abs(parseFloat(this.getStyle(styles[sidesArr[0]])) || 0); + } else if (len) { + for (i = 0; i < len; i++) { + side = sidesArr[i]; + styleSides.push(styles[side]); + } + + styleSides = this.getStyle(styleSides); + + for (i=0; i < len; i++) { + side = sidesArr[i]; + totalSize += Math.abs(parseFloat(styleSides[styles[side]]) || 0); + } + } + + return totalSize; + }, + + + addCls: hasClassList ? + function (className) { + var me = this, + dom = me.dom, + classList, + newCls, + i, + len, + cls; + + if (typeof(className) == 'string') { + + className = className.replace(trimRe, '').split(spacesRe); + } + + + + if (dom && className && !!(len = className.length)) { + if (!dom.className) { + dom.className = className.join(' '); + } else { + classList = dom.classList; + for (i = 0; i < len; ++i) { + cls = className[i]; + if (cls) { + if (!classList.contains(cls)) { + if (newCls) { + newCls.push(cls); + } else { + newCls = dom.className.replace(trimRe, ''); + newCls = newCls ? [newCls, cls] : [cls]; + } + } + } + } + + if (newCls) { + dom.className = newCls.join(' '); + } + } + } + return me; + } : + function(className) { + var me = this, + dom = me.dom, + changed, + elClasses; + + if (dom && className && className.length) { + elClasses = Ext.Element.mergeClsList(dom.className, className); + if (elClasses.changed) { + dom.className = elClasses.join(' '); + } + } + return me; + }, + + + + removeCls: function(className) { + var me = this, + dom = me.dom, + len, + elClasses; + + if (typeof(className) == 'string') { + + className = className.replace(trimRe, '').split(spacesRe); + } + + if (dom && dom.className && className && !!(len = className.length)) { + if (len == 1 && hasClassList) { + if (className[0]) { + dom.classList.remove(className[0]); + } + } else { + elClasses = Ext.Element.removeCls(dom.className, className); + if (elClasses.changed) { + dom.className = elClasses.join(' '); + } + } + } + return me; + }, + + + radioCls: 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').removeCls(className); + } + } + return this.addCls(className); + }, + + + toggleCls: hasClassList ? + function (className) { + var me = this, + dom = me.dom; + + if (dom) { + className = className.replace(trimRe, ''); + if (className) { + dom.classList.toggle(className); + } + } + + return me; + } : + function(className) { + var me = this; + return me.hasCls(className) ? me.removeCls(className) : me.addCls(className); + }, + + + hasCls: hasClassList ? + function (className) { + var dom = this.dom; + return (dom && className) ? dom.classList.contains(className) : false; + } : + function(className) { + var dom = this.dom; + return dom ? className && (' '+dom.className+' ').indexOf(' '+className+' ') != -1 : false; + }, + + + replaceCls: function(oldClassName, newClassName){ + return this.removeCls(oldClassName).addCls(newClassName); + }, + + + isStyle: function(style, val) { + return this.getStyle(style) == val; + }, + + + getStyle: function (property, inline) { + var me = this, + dom = me.dom, + multiple = typeof property != 'string', + hooks = me.styleHooks, + prop = property, + props = prop, + len = 1, + domStyle, camel, values, hook, out, style, i; + + if (multiple) { + values = {}; + prop = props[0]; + i = 0; + if (!(len = props.length)) { + return values; + } + } + + if (!dom || dom.documentElement) { + return values || ''; + } + + domStyle = dom.style; + + if (inline) { + style = domStyle; + } else { + + + + + style = dom.ownerDocument.defaultView.getComputedStyle(dom, null); + + + if (!style) { + inline = true; + style = domStyle; + } + } + + do { + hook = hooks[prop]; + + if (!hook) { + hooks[prop] = hook = { name: Element.normalize(prop) }; + } + + if (hook.get) { + out = hook.get(dom, me, inline, style); + } else { + camel = hook.name; + out = style[camel]; + } + + if (!multiple) { + return out; + } + + values[prop] = out; + prop = props[++i]; + } while (i < len); + + return values; + }, + + getStyles: function () { + var props = Ext.Array.slice(arguments), + len = props.length, + inline; + + if (len && typeof props[len-1] == 'boolean') { + inline = props.pop(); + } + + return this.getStyle(props, inline); + }, + + + isTransparent: function (prop) { + var value = this.getStyle(prop); + return value ? transparentRe.test(value) : false; + }, + + + setStyle: function(prop, value) { + var me = this, + dom = me.dom, + hooks = me.styleHooks, + style = dom.style, + name = prop, + hook; + + + if (typeof name == 'string') { + hook = hooks[name]; + if (!hook) { + hooks[name] = hook = { name: Element.normalize(name) }; + } + value = (value == null) ? '' : value; + if (hook.set) { + hook.set(dom, value, me); + } else { + style[hook.name] = value; + } + if (hook.afterSet) { + hook.afterSet(dom, value, me); + } + } else { + for (name in prop) { + if (prop.hasOwnProperty(name)) { + hook = hooks[name]; + if (!hook) { + hooks[name] = hook = { name: Element.normalize(name) }; + } + value = prop[name]; + value = (value == null) ? '' : value; + if (hook.set) { + hook.set(dom, value, me); + } else { + style[hook.name] = value; + } + if (hook.afterSet) { + hook.afterSet(dom, value, me); + } + } + } + } + + return me; + }, + + + getHeight: function(contentHeight) { + var dom = this.dom, + height = contentHeight ? (dom.clientHeight - this.getPadding("tb")) : dom.offsetHeight; + return height > 0 ? height: 0; + }, + + + getWidth: function(contentWidth) { + var dom = this.dom, + width = contentWidth ? (dom.clientWidth - this.getPadding("lr")) : dom.offsetWidth; + return width > 0 ? width: 0; + }, + + + setWidth: function(width) { + var me = this; + me.dom.style.width = Element.addUnits(width); + return me; + }, + + + setHeight: function(height) { + var me = this; + me.dom.style.height = Element.addUnits(height); + return me; + }, + + + getBorderWidth: function(side){ + return this.addStyles(side, borders); + }, + + + getPadding: function(side){ + return this.addStyles(side, paddings); + }, + + margins : margins, + + + applyStyles: function(styles) { + if (styles) { + var i, + len, + dom = this.dom; + + if (typeof styles == 'function') { + styles = styles.call(); + } + if (typeof styles == 'string') { + styles = Ext.util.Format.trim(styles).split(/\s*(?::|;)\s*/); + for (i = 0, len = styles.length; i < len;) { + dom.style[Element.normalize(styles[i++])] = styles[i++]; + } + } + else if (typeof styles == 'object') { + this.setStyle(styles); + } + } + }, + + + setSize: function(width, height) { + var me = this, + style = me.dom.style; + + if (Ext.isObject(width)) { + + height = width.height; + width = width.width; + } + + style.width = Element.addUnits(width); + style.height = Element.addUnits(height); + return me; + }, + + + getViewSize: function() { + var doc = document, + dom = this.dom; + + if (dom == doc || dom == doc.body) { + return { + width: Element.getViewportWidth(), + height: Element.getViewportHeight() + }; + } + else { + return { + width: dom.clientWidth, + height: dom.clientHeight + }; + } + }, + + + getSize: function(contentSize) { + var dom = this.dom; + return { + width: Math.max(0, contentSize ? (dom.clientWidth - this.getPadding("lr")) : dom.offsetWidth), + height: Math.max(0, contentSize ? (dom.clientHeight - this.getPadding("tb")) : dom.offsetHeight) + }; + }, + + + repaint: function(){ + var dom = this.dom; + this.addCls(Ext.baseCSSPrefix + 'repaint'); + setTimeout(function(){ + Ext.fly(dom).removeCls(Ext.baseCSSPrefix + 'repaint'); + }, 1); + return this; + }, + + + getMargin: function(side){ + var me = this, + hash = {t:"top", l:"left", r:"right", b: "bottom"}, + key, + o, + margins; + + if (!side) { + margins = []; + for (key in me.margins) { + if(me.margins.hasOwnProperty(key)) { + margins.push(me.margins[key]); + } + } + o = me.getStyle(margins); + if(o && typeof o == 'object') { + + for (key in me.margins) { + if(me.margins.hasOwnProperty(key)) { + o[hash[key]] = parseFloat(o[me.margins[key]]) || 0; + } + } + } + + return o; + } else { + return me.addStyles.call(me, side, me.margins); + } + }, + + + mask: function(msg, msgCls, transparent) { + var me = this, + dom = me.dom, + data = (me.$cache || me.getCache()).data, + el = data.mask, + mask, + size, + cls = '', + prefix = Ext.baseCSSPrefix; + + me.addCls(prefix + 'masked'); + if (me.getStyle("position") == "static") { + me.addCls(prefix + 'masked-relative'); + } + if (el) { + el.remove(); + } + if (msgCls && typeof msgCls == 'string' ) { + cls = ' ' + msgCls; + } + else { + cls = ' ' + prefix + 'mask-gray'; + } + + mask = me.createChild({ + cls: prefix + 'mask' + ((transparent !== false) ? '' : (' ' + prefix + 'mask-gray')), + html: msg ? ('
    ' + msg + '
    ') : '' + }); + + size = me.getSize(); + + data.mask = mask; + + if (dom === document.body) { + size.height = window.innerHeight; + if (me.orientationHandler) { + Ext.EventManager.unOrientationChange(me.orientationHandler, me); + } + + me.orientationHandler = function() { + size = me.getSize(); + size.height = window.innerHeight; + mask.setSize(size); + }; + + Ext.EventManager.onOrientationChange(me.orientationHandler, me); + } + mask.setSize(size); + if (Ext.is.iPad) { + Ext.repaint(); + } + }, + + + unmask: function() { + var me = this, + data = (me.$cache || me.getCache()).data, + mask = data.mask, + prefix = Ext.baseCSSPrefix; + + if (mask) { + mask.remove(); + delete data.mask; + } + me.removeCls([prefix + 'masked', prefix + 'masked-relative']); + + if (me.dom === document.body) { + Ext.EventManager.unOrientationChange(me.orientationHandler, me); + delete me.orientationHandler; + } + } + }); + + + Element.populateStyleMap = function (map, order) { + var baseStyles = ['margin-', 'padding-', 'border-width-'], + beforeAfter = ['before', 'after'], + index, style, name, i; + + for (index = baseStyles.length; index--; ) { + for (i = 2; i--; ) { + style = baseStyles[index] + beforeAfter[i]; + + map[Element.normalize(style)] = map[style] = { + name: Element.normalize(baseStyles[index] + order[i]) + }; + } + } + }; + + Ext.onReady(function () { + var supports = Ext.supports, + styleHooks, + colorStyles, i, name, camel; + + function fixTransparent (dom, el, inline, style) { + var value = style[this.name] || ''; + return transparentRe.test(value) ? 'transparent' : value; + } + + function fixRightMargin (dom, el, inline, style) { + var result = style.marginRight, + domStyle, display; + + + + if (result != '0px') { + domStyle = dom.style; + display = domStyle.display; + domStyle.display = 'inline-block'; + result = (inline ? style : dom.ownerDocument.defaultView.getComputedStyle(dom, null)).marginRight; + domStyle.display = display; + } + + return result; + } + + function fixRightMarginAndInputFocus (dom, el, inline, style) { + var result = style.marginRight, + domStyle, cleaner, display; + + if (result != '0px') { + domStyle = dom.style; + cleaner = Element.getRightMarginFixCleaner(dom); + display = domStyle.display; + domStyle.display = 'inline-block'; + result = (inline ? style : dom.ownerDocument.defaultView.getComputedStyle(dom, '')).marginRight; + domStyle.display = display; + cleaner(); + } + + return result; + } + + styleHooks = Element.prototype.styleHooks; + + + Element.populateStyleMap(styleHooks, ['left', 'right']); + + + + if (supports.init) { + supports.init(); + } + + + if (!supports.RightMargin) { + styleHooks.marginRight = styleHooks['margin-right'] = { + name: 'marginRight', + + + get: (supports.DisplayChangeInputSelectionBug || supports.DisplayChangeTextAreaSelectionBug) ? + fixRightMarginAndInputFocus : fixRightMargin + }; + } + + if (!supports.TransparentColor) { + colorStyles = ['background-color', 'border-color', 'color', 'outline-color']; + for (i = colorStyles.length; i--; ) { + name = colorStyles[i]; + camel = Element.normalize(name); + + styleHooks[name] = styleHooks[camel] = { + name: camel, + get: fixTransparent + }; + } + } + }); +}()); + + +Ext.dom.AbstractElement.override({ + + findParent: function(simpleSelector, limit, returnEl) { + var target = this.dom, + topmost = document.documentElement, + depth = 0, + stopEl; + + limit = limit || 50; + if (isNaN(limit)) { + stopEl = Ext.getDom(limit); + limit = Number.MAX_VALUE; + } + while (target && target.nodeType == 1 && depth < limit && target != topmost && target != stopEl) { + if (Ext.DomQuery.is(target, simpleSelector)) { + return returnEl ? Ext.get(target) : target; + } + depth++; + target = target.parentNode; + } + return null; + }, + + + findParentNode: function(simpleSelector, limit, returnEl) { + var p = Ext.fly(this.dom.parentNode, '_internal'); + return p ? p.findParent(simpleSelector, limit, returnEl) : null; + }, + + + up: function(simpleSelector, limit) { + return this.findParentNode(simpleSelector, limit, true); + }, + + + select: function(selector, composite) { + return Ext.dom.Element.select(selector, this.dom, composite); + }, + + + query: function(selector) { + return Ext.DomQuery.select(selector, this.dom); + }, + + + down: function(selector, returnDom) { + var n = Ext.DomQuery.selectNode(selector, this.dom); + return returnDom ? n : Ext.get(n); + }, + + + child: function(selector, returnDom) { + var node, + me = this, + id; + + + + id = Ext.id(me.dom); + + id = id.replace(/[\.:]/g, "\\$0"); + node = Ext.DomQuery.selectNode('#' + id + " > " + selector, me.dom); + return returnDom ? node : Ext.get(node); + }, + + + 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) { + if (!this.dom) { + return null; + } + + var n = this.dom[start]; + while (n) { + if (n.nodeType == 1 && (!selector || Ext.DomQuery.is(n, selector))) { + return !returnDom ? Ext.get(n) : n; + } + n = n[dir]; + } + return null; + }, + + isAncestor: function(element) { + return this.self.isAncestor.call(this.self, this.dom, element); + } +}); + + +(function() { + + +var afterbegin = 'afterbegin', + afterend = 'afterend', + beforebegin = 'beforebegin', + beforeend = 'beforeend', + ts = '', + te = '
    ', + tbs = ts+'', + tbe = ''+te, + trs = tbs + '', + tre = ''+tbe, + detachedDiv = document.createElement('div'), + bbValues = ['BeforeBegin', 'previousSibling'], + aeValues = ['AfterEnd', 'nextSibling'], + bb_ae_PositionHash = { + beforebegin: bbValues, + afterend: aeValues + }, + fullPositionHash = { + beforebegin: bbValues, + afterend: aeValues, + afterbegin: ['AfterBegin', 'firstChild'], + beforeend: ['BeforeEnd', 'lastChild'] + }; + +Ext.define('Ext.dom.Helper', { + extend: 'Ext.dom.AbstractHelper', + + tableRe: /^table|tbody|tr|td$/i, + + tableElRe: /td|tr|tbody/i, + + + useDom : false, + + + createDom: function(o, parentNode){ + var el, + doc = document, + useSet, + attr, + val, + cn, + i, l; + + if (Ext.isArray(o)) { + el = doc.createDocumentFragment(); + for (i = 0, l = o.length; i < l; i++) { + this.createDom(o[i], el); + } + } else if (typeof o == 'string') { + el = doc.createTextNode(o); + } else { + el = doc.createElement(o.tag || 'div'); + useSet = !!el.setAttribute; + for (attr in o) { + if (!this.confRe.test(attr)) { + val = o[attr]; + if (attr == 'cls') { + el.className = val; + } else { + if (useSet) { + el.setAttribute(attr, val); + } else { + el[attr] = val; + } + } + } + } + Ext.DomHelper.applyStyles(el, o.style); + + if ((cn = o.children || o.cn)) { + this.createDom(cn, el); + } else if (o.html) { + el.innerHTML = o.html; + } + } + if (parentNode) { + parentNode.appendChild(el); + } + return el; + }, + + ieTable: function(depth, openingTags, htmlContent, closingTags){ + detachedDiv.innerHTML = [openingTags, htmlContent, closingTags].join(''); + + var i = -1, + el = detachedDiv, + ns; + + while (++i < depth) { + el = el.firstChild; + } + + ns = el.nextSibling; + + if (ns) { + el = document.createDocumentFragment(); + while (ns) { + el.appendChild(ns); + ns = ns.nextSibling; + } + } + return el; + }, + + + insertIntoTable: function(tag, where, destinationEl, html) { + var node, + before, + bb = where == beforebegin, + ab = where == afterbegin, + be = where == beforeend, + ae = where == afterend; + + if (tag == 'td' && (ab || be) || !this.tableElRe.test(tag) && (bb || ae)) { + return null; + } + before = bb ? destinationEl : + ae ? destinationEl.nextSibling : + ab ? destinationEl.firstChild : null; + + if (bb || ae) { + destinationEl = destinationEl.parentNode; + } + + if (tag == 'td' || (tag == 'tr' && (be || ab))) { + node = this.ieTable(4, trs, html, tre); + } else if ((tag == 'tbody' && (be || ab)) || + (tag == 'tr' && (bb || ae))) { + node = this.ieTable(3, tbs, html, tbe); + } else { + node = this.ieTable(2, ts, html, te); + } + destinationEl.insertBefore(node, before); + return node; + }, + + + createContextualFragment: function(html) { + var fragment = document.createDocumentFragment(), + length, childNodes; + + detachedDiv.innerHTML = html; + childNodes = detachedDiv.childNodes; + length = childNodes.length; + + + while (length--) { + fragment.appendChild(childNodes[0]); + } + return fragment; + }, + + applyStyles: function(el, styles) { + if (styles) { + el = Ext.fly(el); + if (typeof styles == "function") { + styles = styles.call(); + } + if (typeof styles == "string") { + styles = Ext.dom.Element.parseStyles(styles); + } + if (typeof styles == "object") { + el.setStyle(styles); + } + } + }, + + + createHtml: function(spec) { + return this.markup(spec); + }, + + doInsert: function(el, o, returnElement, pos, sibling, append) { + + el = el.dom || Ext.getDom(el); + + var newNode; + + if (this.useDom) { + newNode = this.createDom(o, null); + + if (append) { + el.appendChild(newNode); + } + else { + (sibling == 'firstChild' ? el : el.parentNode).insertBefore(newNode, el[sibling] || el); + } + + } else { + newNode = this.insertHtml(pos, el, this.markup(o)); + } + return returnElement ? Ext.get(newNode, true) : newNode; + }, + + + overwrite: function(el, html, returnElement) { + var newNode; + + el = Ext.getDom(el); + html = this.markup(html); + + + if (Ext.isIE && this.tableRe.test(el.tagName)) { + + while (el.firstChild) { + el.removeChild(el.firstChild); + } + if (html) { + newNode = this.insertHtml('afterbegin', el, html); + return returnElement ? Ext.get(newNode) : newNode; + } + return null; + } + el.innerHTML = html; + return returnElement ? Ext.get(el.firstChild) : el.firstChild; + }, + + insertHtml: function(where, el, html) { + var hashVal, + range, + rangeEl, + setStart, + frag; + + where = where.toLowerCase(); + + + if (el.insertAdjacentHTML) { + + + if (Ext.isIE && this.tableRe.test(el.tagName) && (frag = this.insertIntoTable(el.tagName.toLowerCase(), where, el, html))) { + return frag; + } + + if ((hashVal = fullPositionHash[where])) { + el.insertAdjacentHTML(hashVal[0], html); + return el[hashVal[1]]; + } + + } else { + + if (el.nodeType === 3) { + where = where === 'afterbegin' ? 'beforebegin' : where; + where = where === 'beforeend' ? 'afterend' : where; + } + range = Ext.supports.CreateContextualFragment ? el.ownerDocument.createRange() : undefined; + setStart = 'setStart' + (this.endRe.test(where) ? 'After' : 'Before'); + if (bb_ae_PositionHash[where]) { + if (range) { + range[setStart](el); + frag = range.createContextualFragment(html); + } else { + frag = this.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) { + if (range) { + range[setStart](el[rangeEl]); + frag = range.createContextualFragment(html); + } else { + frag = this.createContextualFragment(html); + } + + if (where == afterbegin) { + el.insertBefore(frag, el.firstChild); + } else { + el.appendChild(frag); + } + } else { + el.innerHTML = html; + } + return el[rangeEl]; + } + } + }, + + + createTemplate: function(o) { + var html = this.markup(o); + return new Ext.Template(html); + } + +}, function() { + Ext.ns('Ext.core'); + Ext.DomHelper = Ext.core.DomHelper = new this; +}); + + +}()); + + + +Ext.ns('Ext.core'); + +Ext.dom.Query = Ext.core.DomQuery = 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/, + startIdRe = /^\s*\#/, + + + + isIE = window.ActiveXObject ? true : false, + key = 30803, + longHex = /\\([0-9a-fA-F]{6})/g, + shortHex = /\\([0-9a-fA-F]{1,6})\s{0,1}/g, + nonHex = /\\([^0-9a-fA-F]{1})/g, + escapes = /\\/g, + num, hasEscapes, + + + + longHexToChar = function($0, $1) { + return String.fromCharCode(parseInt($1, 16)); + }, + + + shortToLongHex = function($0, $1) { + while ($1.length < 6) { + $1 = '0' + $1; + } + return '\\' + $1; + }, + + + charToLongHex = function($0, $1) { + num = $1.charCodeAt(0).toString(16); + if (num.length === 1) { + num = '0' + num; + } + return '\\0000' + num; + }, + + + + + unescapeCssSelector = function (selector) { + return (hasEscapes) + ? selector.replace(longHex, longHexToChar) + : selector; + }; + + + + 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; + } + 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(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; + } + + + + function byClassName(nodeSet, cls){ + cls = unescapeCssSelector(cls); + if(!cls){ + return nodeSet; + } + var result = [], ri = -1, + i, ci; + for(i = 0, ci; ci = nodeSet[i]; i++){ + if((' '+ci.className+' ').indexOf(cls) != -1){ + result[++ri] = ci; + } + } + return result; + } + + 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, + i, ni, j, ci, cn, utag, n, cj; + if(!ns){ + return result; + } + tagName = tagName || "*"; + + if(typeof ns.getElementsByTagName != "undefined"){ + ns = [ns]; + } + + + + if(!mode){ + for(i = 0, ni; ni = ns[i]; i++){ + cs = ni.getElementsByTagName(tagName); + for(j = 0, ci; ci = cs[j]; j++){ + result[++ri] = ci; + } + } + + + } else if(mode == "/" || mode == ">"){ + utag = tagName.toUpperCase(); + for(i = 0, ni, cn; ni = ns[i]; i++){ + cn = ni.childNodes; + for(j = 0, cj; cj = cn[j]; j++){ + if(cj.nodeName == utag || cj.nodeName == tagName || tagName == '*'){ + result[++ri] = cj; + } + } + } + + + }else if(mode == "+"){ + utag = tagName.toUpperCase(); + for(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 == "~"){ + utag = tagName.toUpperCase(); + for(i = 0, n; n = ns[i]; i++){ + while((n = n.nextSibling)){ + if (n.nodeName == utag || n.nodeName == tagName || tagName == '*'){ + result[++ri] = n; + } + } + } + } + return result; + } + + function concat(a, b){ + if(b.slice){ + return a.concat(b); + } + for(var i = 0, l = b.length; i < l; i++){ + a[a.length] = b[i]; + } + return a; + } + + function byTag(cs, tagName){ + if(cs.tagName || cs == document){ + cs = [cs]; + } + if(!tagName){ + return cs; + } + var result = [], ri = -1, + i, ci; + tagName = tagName.toLowerCase(); + for(i = 0, ci; ci = cs[i]; i++){ + if(ci.nodeType == 1 && ci.tagName.toLowerCase() == tagName){ + result[++ri] = ci; + } + } + return result; + } + + function byId(cs, id){ + id = unescapeCssSelector(id); + if(cs.tagName || cs == document){ + cs = [cs]; + } + if(!id){ + return cs; + } + var result = [], ri = -1, + i, ci; + for(i = 0, ci; ci = cs[i]; i++){ + if(ci && ci.id == id){ + result[++ri] = ci; + return result; + } + } + return result; + } + + + + function byAttribute(cs, attr, value, op, custom){ + var result = [], + ri = -1, + useGetStyle = custom == "{", + fn = Ext.DomQuery.operators[op], + a, + xml, + hasXml, + i, ci; + + value = unescapeCssSelector(value); + + for(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){ + value = unescapeCssSelector(value); + return Ext.DomQuery.pseudos[name](cs, value); + } + + function nodupIEXml(cs){ + var d = ++key, + r, + i, len, c; + cs[0].setAttribute("_nodup", d); + r = [cs[0]]; + for(i = 1, len = cs.length; i < len; i++){ + c = cs[i]; + if(!c.getAttribute("_nodup") != d){ + c.setAttribute("_nodup", d); + r[r.length] = c; + } + } + for(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, d, j; + if(!len || typeof cs.nodeType != "undefined" || len == 1){ + return cs; + } + if(isIE && typeof cs[0].selectSingleNode != "undefined"){ + return nodupIEXml(cs); + } + d = ++key; + cs[0]._nodup = d; + for(i = 1; c = cs[i]; i++){ + if(c._nodup != d){ + c._nodup = d; + }else{ + r = []; + for(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 = [], + i, len; + for(i = 0, len = c1.length; i < len; i++){ + c1[i].setAttribute("_qdiff", d); + } + for(i = 0, len = c2.length; i < len; i++){ + if(c2[i].getAttribute("_qdiff") != d){ + r[r.length] = c2[i]; + } + } + for(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 = [], + i, len; + if(!len1){ + return c2; + } + if(isIE && typeof c1[0].selectSingleNode != "undefined"){ + return quickDiffIEXml(c1, c2); + } + for(i = 0; i < len1; i++){ + c1[i]._qdiff = d; + } + for(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){ + id = unescapeCssSelector(id); + 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), + tokenMatch, matched, j, t, m; + + hasEscapes = (path.indexOf('\\') > -1); + if (hasEscapes) { + path = path + .replace(shortHex, shortToLongHex) + .replace(nonHex, charToLongHex) + .replace(escapes, '\\\\'); + } + + 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; + 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))){ + matched = false; + for(j = 0; j < matchersLn; j++){ + t = matchers[j]; + 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){ + Ext.Error.raise({ + sourceClass: 'Ext.DomQuery', + sourceMethod: 'compile', + msg: '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; + }, + + + jsSelect: function(path, root, type){ + + root = root || document; + + if(typeof root == "string"){ + root = document.getElementById(root); + } + var paths = path.split(","), + results = [], + i, len, subPath, result; + + + for(i = 0, len = paths.length; i < len; i++){ + subPath = paths[i].replace(trimRe, ""); + + if(!cache[subPath]){ + cache[subPath] = Ext.DomQuery.compile(subPath, type); + if(!cache[subPath]){ + Ext.Error.raise({ + sourceClass: 'Ext.DomQuery', + sourceMethod: 'jsSelect', + msg: subPath + ' is not a valid selector' + }); + } + } + 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 { + + if (root.parentNode && (root.nodeType !== 9) && path.indexOf(',') === -1 && !startIdRe.test(path)) { + path = '#' + Ext.escapeId(Ext.id(root)) + ' ' + path; + root = root.parentNode; + } + return Ext.Array.toArray(root.querySelectorAll(path)); + } + catch (e) { + } + } + return Ext.DomQuery.jsSelect.call(this, path, root, type); + } : function(path, root, type) { + return Ext.DomQuery.jsSelect.call(this, path, root, type); + }, + + + selectNode : function(path, root){ + return Ext.DomQuery.select(path, root)[0]; + }, + + + 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); + }, + + + 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); + } + var isArray = Ext.isArray(el), + result = Ext.DomQuery.filter(isArray ? el : [el], ss); + return isArray ? (result.length == el.length) : (result.length > 0); + }, + + + 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; + }, + + + 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}")}};' + } + ], + + + 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, + i, ci; + for(i = 0; (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, + i, ci; + for(i = 0; (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, + i, n, j, cn, pn; + for(i = 0; n = c[i]; i++){ + pn = n.parentNode; + if (batch != pn._batch) { + j = 0; + for(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, + i, ci; + for(i = 0; ci = c[i]; i++){ + if(!prev(ci) && !next(ci)){ + r[++ri] = ci; + } + } + return r; + }, + + "empty" : function(c){ + var r = [], ri = -1, + i, ci, cns, j, cn, empty; + for(i = 0, ci; ci = c[i]; i++){ + cns = ci.childNodes; + j = 0; + 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, + i, ci; + for(i = 0; ci = c[i]; i++){ + if((ci.textContent||ci.innerText||ci.text||'').indexOf(v) != -1){ + r[++ri] = ci; + } + } + return r; + }, + + "nodeValue" : function(c, v){ + var r = [], ri = -1, + i, ci; + for(i = 0; ci = c[i]; i++){ + if(ci.firstChild && ci.firstChild.nodeValue == v){ + r[++ri] = ci; + } + } + return r; + }, + + "checked" : function(c){ + var r = [], ri = -1, + i, ci; + for(i = 0; 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, + i, ci, j; + for(i = 0; ci = c[i]; i++){ + for(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, + i, ci; + for(i = 0; 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, + i, ci, n; + for(i = 0; ci = c[i]; i++){ + 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, + i, ci, n; + for(i = 0; ci = c[i]; i++){ + n = prev(ci); + if(n && is(n, ss)){ + r[++ri] = ci; + } + } + return r; + } + } + }; +}()); + + +Ext.query = Ext.DomQuery.select; + + + +(function() { + +var HIDDEN = 'hidden', + DOC = document, + VISIBILITY = "visibility", + DISPLAY = "display", + NONE = "none", + XMASKED = Ext.baseCSSPrefix + "masked", + XMASKEDRELATIVE = Ext.baseCSSPrefix + "masked-relative", + EXTELMASKMSG = Ext.baseCSSPrefix + "mask-msg", + bodyRe = /^body/i, + visFly, + + + noBoxAdjust = Ext.isStrict ? { + select: 1 + }: { + input: 1, + select: 1, + textarea: 1 + }, + + + isScrolled = function(c) { + var r = [], ri = -1, + i, ci; + for (i = 0; ci = c[i]; i++) { + if (ci.scrollTop > 0 || ci.scrollLeft > 0) { + r[++ri] = ci; + } + } + return r; + }, + + Element = Ext.define('Ext.dom.Element', { + + extend: 'Ext.dom.AbstractElement', + + alternateClassName: ['Ext.Element', 'Ext.core.Element'], + + addUnits: function() { + return this.self.addUnits.apply(this.self, arguments); + }, + + + focus: function(defer, dom) { + var me = this, + scrollTop, + body; + + dom = dom || me.dom; + body = (dom.ownerDocument || DOC).body || DOC.body; + try { + if (Number(defer)) { + Ext.defer(me.focus, defer, me, [null, dom]); + } else { + + + if (dom.offsetHeight > Element.getViewHeight()) { + scrollTop = body.scrollTop; + } + dom.focus(); + if (scrollTop !== undefined) { + body.scrollTop = scrollTop; + } + } + } catch(e) { + } + return me; + }, + + + blur: function() { + try { + this.dom.blur(); + } catch(e) { + } + return this; + }, + + + isBorderBox: function() { + var box = Ext.isBorderBox; + if (box) { + box = !((this.dom.tagName || "").toLowerCase() in noBoxAdjust); + } + return box; + }, + + + 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; + }, + + + getAttributeNS: function(ns, name) { + return this.getAttribute(name, ns); + }, + + getAttribute: (Ext.isIE && !(Ext.isIE9 && DOC.documentMode === 9)) ? + function(name, ns) { + var d = this.dom, + type; + if (ns) { + type = typeof d[ns + ":" + name]; + if (type != 'undefined' && type != 'unknown') { + return d[ns + ":" + name] || null; + } + return null; + } + if (name === "for") { + name = "htmlFor"; + } + return d[name] || null; + } : function(name, ns) { + var d = this.dom; + if (ns) { + return d.getAttributeNS(ns, name) || d.getAttribute(ns + ":" + name); + } + return d.getAttribute(name) || d[name] || null; + }, + + + cacheScrollValues: function() { + var me = this, + scrolledDescendants, + el, i, + scrollValues = [], + result = function() { + for (i = 0; i < scrolledDescendants.length; i++) { + el = scrolledDescendants[i]; + el.scrollLeft = scrollValues[i][0]; + el.scrollTop = scrollValues[i][1]; + } + }; + + if (!Ext.DomQuery.pseudos.isScrolled) { + Ext.DomQuery.pseudos.isScrolled = isScrolled; + } + scrolledDescendants = me.query(':isScrolled'); + for (i = 0; i < scrolledDescendants.length; i++) { + el = scrolledDescendants[i]; + scrollValues[i] = [el.scrollLeft, el.scrollTop]; + } + return result; + }, + + + autoBoxAdjust: true, + + + isVisible : function(deep) { + var me = this, + dom = me.dom, + stopNode = dom.ownerDocument.documentElement; + + if (!visFly) { + visFly = new Element.Fly(); + } + + while (dom !== stopNode) { + + + if (!dom || dom.nodeType === 11 || (visFly.attach(dom)).isStyle(VISIBILITY, HIDDEN) || visFly.isStyle(DISPLAY, NONE)) { + return false; + } + + if (!deep) { + break; + } + dom = dom.parentNode; + } + return true; + }, + + + isDisplayed : function() { + return !this.isStyle(DISPLAY, NONE); + }, + + + enableDisplayMode : function(display) { + var me = this; + + me.setVisibilityMode(Element.DISPLAY); + + if (!Ext.isEmpty(display)) { + (me.$cache || me.getCache()).data.originalDisplay = display; + } + + return me; + }, + + + mask : function(msg, msgCls , elHeight) { + var me = this, + dom = me.dom, + setExpression = dom.style.setExpression, + data = (me.$cache || me.getCache()).data, + maskEl = data.maskEl, + maskMsg = data.maskMsg; + + if (!(bodyRe.test(dom.tagName) && me.getStyle('position') == 'static')) { + me.addCls(XMASKEDRELATIVE); + } + + + if (maskEl) { + maskEl.remove(); + } + + if (maskMsg) { + maskMsg.remove(); + } + + Ext.DomHelper.append(dom, [{ + cls : Ext.baseCSSPrefix + "mask" + }, { + cls : msgCls ? EXTELMASKMSG + " " + msgCls : EXTELMASKMSG, + cn : { + tag: 'div', + html: msg || '' + } + }]); + + maskMsg = Ext.get(dom.lastChild); + maskEl = Ext.get(maskMsg.dom.previousSibling); + data.maskMsg = maskMsg; + data.maskEl = maskEl; + + me.addCls(XMASKED); + maskEl.setDisplayed(true); + + if (typeof msg == 'string') { + maskMsg.setDisplayed(true); + maskMsg.center(me); + } else { + maskMsg.setDisplayed(false); + } + + + + + + if (!Ext.supports.IncludePaddingInWidthCalculation && setExpression) { + maskEl.dom.style.setExpression('width', 'this.parentNode.clientWidth + "px"'); + } + + + + if (!Ext.supports.IncludePaddingInHeightCalculation && setExpression) { + maskEl.dom.style.setExpression('height', 'this.parentNode.' + (dom == DOC.body ? 'scrollHeight' : 'offsetHeight') + ' + "px"'); + } + + else if (Ext.isIE && !(Ext.isIE7 && Ext.isStrict) && me.getStyle('height') == 'auto') { + maskEl.setSize(undefined, elHeight || me.getHeight()); + } + return maskEl; + }, + + + unmask : function() { + var me = this, + data = (me.$cache || me.getCache()).data, + maskEl = data.maskEl, + maskMsg = data.maskMsg, + style; + + if (maskEl) { + style = maskEl.dom.style; + + if (style.clearExpression) { + style.clearExpression('width'); + style.clearExpression('height'); + } + + if (maskEl) { + maskEl.remove(); + delete data.maskEl; + } + + if (maskMsg) { + maskMsg.remove(); + delete data.maskMsg; + } + + me.removeCls([XMASKED, XMASKEDRELATIVE]); + } + }, + + + isMasked : function() { + var me = this, + data = (me.$cache || me.getCache()).data, + maskEl = data.maskEl, + maskMsg = data.maskMsg, + hasMask = false; + + if (maskEl && maskEl.isVisible()) { + if (maskMsg) { + maskMsg.center(me); + } + hasMask = true; + } + return hasMask; + }, + + + createShim : function() { + var el = DOC.createElement('iframe'), + shim; + + el.frameBorder = '0'; + el.className = Ext.baseCSSPrefix + 'shim'; + el.src = Ext.SSL_SECURE_URL; + shim = Ext.get(this.dom.parentNode.insertBefore(el, this.dom)); + shim.autoBoxAdjust = false; + return shim; + }, + + + addKeyListener : function(key, fn, scope){ + var config; + if(typeof key != 'object' || Ext.isArray(key)){ + config = { + target: this, + key: key, + fn: fn, + scope: scope + }; + }else{ + config = { + target: this, + key : key.key, + shift : key.shift, + ctrl : key.ctrl, + alt : key.alt, + fn: fn, + scope: scope + }; + } + return new Ext.util.KeyMap(config); + }, + + + addKeyMap : function(config) { + return new Ext.util.KeyMap(Ext.apply({ + target: this + }, config)); + }, + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + on: function(eventName, fn, scope, options) { + Ext.EventManager.on(this, eventName, fn, scope || this, options); + return this; + }, + + + un: function(eventName, fn, scope) { + Ext.EventManager.un(this, eventName, fn, scope || this); + return this; + }, + + + removeAllListeners: function() { + Ext.EventManager.removeAll(this); + return this; + }, + + + purgeAllListeners: function() { + Ext.EventManager.purgeElement(this); + return this; + } + +}, function() { + + var EC = Ext.cache, + El = this, + AbstractElement = Ext.dom.AbstractElement, + focusRe = /a|button|embed|iframe|img|input|object|select|textarea/i, + nonSpaceRe = /\S/, + scriptTagRe = /(?:]*)?>)((\n|\r|.)*?)(?:<\/script>)/ig, + replaceScriptTagRe = /(?:)((\n|\r|.)*?)(?:<\/script>)/ig, + srcRe = /\ssrc=([\'\"])(.*?)\1/i, + typeRe = /\stype=([\'\"])(.*?)\1/i, + useDocForId = !(Ext.isIE6 || Ext.isIE7 || Ext.isIE8); + + El.boxMarkup = '
    '; + + + + + + function garbageCollect() { + if (!Ext.enableGarbageCollector) { + clearInterval(El.collectorThreadId); + } else { + var eid, + d, + o, + t; + + for (eid in EC) { + if (!EC.hasOwnProperty(eid)) { + continue; + } + + o = EC[eid]; + + + if (o.skipGarbageCollection) { + continue; + } + + d = o.dom; + + + + + + + + + + + + + + + + + if (!d.parentNode || (!d.offsetParent && !Ext.getElementById(eid))) { + if (d && Ext.enableListenerCollection) { + Ext.EventManager.removeAll(d); + } + delete EC[eid]; + } + } + + if (Ext.isIE) { + t = {}; + for (eid in EC) { + if (!EC.hasOwnProperty(eid)) { + continue; + } + t[eid] = EC[eid]; + } + EC = Ext.cache = t; + } + } + } + + El.collectorThreadId = setInterval(garbageCollect, 30000); + + + El.addMethods({ + + + monitorMouseLeave: function(delay, handler, scope) { + var me = this, + timer, + listeners = { + mouseleave: function(e) { + timer = setTimeout(Ext.Function.bind(handler, scope||me, [e]), delay); + }, + mouseenter: function() { + clearTimeout(timer); + }, + freezeEvent: true + }; + + me.on(listeners); + return listeners; + }, + + + swallowEvent : function(eventName, preventDefault) { + var me = this, + e, eLen; + function fn(e) { + e.stopPropagation(); + if (preventDefault) { + e.preventDefault(); + } + } + + if (Ext.isArray(eventName)) { + eLen = eventName.length; + + for (e = 0; e < eLen; e++) { + me.on(eventName[e], fn); + } + + return me; + } + 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, + data = (me.$cache || me.getCache()).data, + n = dom.firstChild, + ni = -1, + nx; + + if (data.isCleaned && forceReclean !== true) { + return me; + } + + while (n) { + nx = n.nextSibling; + if (n.nodeType == 3) { + + if (!(nonSpaceRe.test(n.nodeValue))) { + dom.removeChild(n); + + } else if (nx && nx.nodeType == 3) { + n.appendData(Ext.String.trim(nx.data)); + dom.removeChild(nx); + nx = n.nextSibling; + n.nodeIndex = ++ni; + } + } else { + + Ext.fly(n).clean(); + n.nodeIndex = ++ni; + } + n = nx; + } + + data.isCleaned = true; + return me; + }, + + + load : function(options) { + this.getLoader().load(options); + return this; + }, + + + getLoader : function() { + var me = this, + data = (me.$cache || me.getCache()).data, + loader = data.loader; + + if (!loader) { + data.loader = loader = new Ext.ElementLoader({ + target: me + }); + } + return loader; + }, + + + update : function(html, loadScripts, callback) { + var me = this, + id, + dom, + interval; + + if (!me.dom) { + return me; + } + html = html || ''; + dom = me.dom; + + if (loadScripts !== true) { + dom.innerHTML = html; + Ext.callback(callback, me); + return me; + } + + id = Ext.id(); + html += ''; + + interval = setInterval(function() { + var hd, + match, + attrs, + srcMatch, + typeMatch, + el, + s; + if (!(el = DOC.getElementById(id))) { + return false; + } + clearInterval(interval); + Ext.removeNode(el); + hd = Ext.getHead().dom; + + while ((match = scriptTagRe.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.callback(callback, me); + }, 20); + dom.innerHTML = html.replace(replaceScriptTagRe, ''); + return me; + }, + + + removeAllListeners : function() { + this.removeAnchor(); + Ext.EventManager.removeAll(this.dom); + return this; + }, + + + 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); + + proxy.setVisibilityMode(Element.DISPLAY); + proxy.hide(); + if (matchBox && me.setBox && me.getBox) { + proxy.setBox(me.getBox()); + } + return proxy; + }, + + + getScopeParent: function() { + var parent = this.dom.parentNode; + return Ext.scopeResetCSS ? parent.parentNode : parent; + }, + + + needsTabIndex: function() { + if (this.dom) { + if ((this.dom.nodeName === 'a') && (!this.dom.href)) { + return true; + } + return !focusRe.test(this.dom.nodeName); + } + }, + + + focusable: function () { + var dom = this.dom, + nodeName = dom.nodeName, + canFocus = false; + + if (!dom.disabled) { + if (focusRe.test(nodeName)) { + if ((nodeName !== 'a') || dom.href) { + canFocus = true; + } + } else { + canFocus = !isNaN(dom.tabIndex); + } + } + return canFocus && this.isVisible(true); + } + }); + + if (Ext.isIE) { + El.prototype.getById = function (id, asDom) { + var dom = this.dom, + cached, el, ret; + + if (dom) { + + + el = (useDocForId && DOC.getElementById(id)) || dom.all[id]; + if (el) { + if (asDom) { + ret = el; + } else { + + + cached = EC[id]; + if (cached && cached.el) { + ret = cached.el; + ret.dom = el; + } else { + ret = new Element(el); + } + } + return ret; + } + } + + return asDom ? Ext.getDom(id) : El.get(id); + }; + } + + El.createAlias({ + + addListener: 'on', + + removeListener: 'un', + + clearListeners: 'removeAllListeners' + }); + + El.Fly = AbstractElement.Fly = new Ext.Class({ + extend: El, + + constructor: function(dom) { + this.dom = dom; + }, + + attach: AbstractElement.Fly.prototype.attach + }); + + if (Ext.isIE) { + Ext.getElementById = function (id) { + var el = DOC.getElementById(id), + detachedBodyEl; + + if (!el && (detachedBodyEl = AbstractElement.detachedBodyEl)) { + el = detachedBodyEl.dom.all[id]; + } + + return el; + }; + } else if (!DOC.querySelector) { + Ext.getDetachedBody = Ext.getBody; + + Ext.getElementById = function (id) { + return DOC.getElementById(id); + }; + } +}); + +}()); + + +Ext.dom.Element.override((function() { + + var doc = document, + win = window, + alignRe = /^([a-z]+)-([a-z]+)(\?)?$/, + round = Math.round; + + return { + + + getAnchorXY: function(anchor, local, mySize) { + + + anchor = (anchor || "tl").toLowerCase(); + mySize = mySize || {}; + + var me = this, + isViewport = me.dom == doc.body || me.dom == doc, + myWidth = mySize.width || isViewport ? Ext.dom.Element.getViewWidth() : me.getWidth(), + myHeight = mySize.height || isViewport ? Ext.dom.Element.getViewHeight() : me.getHeight(), + xy, + myPos = me.getXY(), + scroll = me.getScroll(), + extraX = isViewport ? scroll.left : !local ? myPos[0] : 0, + extraY = isViewport ? scroll.top : !local ? myPos[1] : 0; + + + + switch (anchor) { + case 'tl' : xy = [ 0, 0]; + break; + case 'bl' : xy = [ 0, myHeight]; + break; + case 'tr' : xy = [ myWidth, 0]; + break; + case 'c' : xy = [ round(myWidth * 0.5), round(myHeight * 0.5)]; + break; + case 't' : xy = [ round(myWidth * 0.5), 0]; + break; + case 'l' : xy = [ 0, round(myHeight * 0.5)]; + break; + case 'r' : xy = [ myWidth, round(myHeight * 0.5)]; + break; + case 'b' : xy = [ round(myWidth * 0.5), myHeight]; + break; + case 'br' : xy = [ myWidth, myHeight]; + } + return [xy[0] + extraX, xy[1] + extraY]; + }, + + + getAlignToXY : function(alignToEl, posSpec, offset) { + alignToEl = Ext.get(alignToEl); + + if (!alignToEl || !alignToEl.dom) { + } + + offset = offset || [0,0]; + posSpec = (!posSpec || posSpec == "?" ? "tl-bl?" : (!(/-/).test(posSpec) && posSpec !== "" ? "tl-" + posSpec : posSpec || "tl-bl")).toLowerCase(); + + var me = this, + myPosition, + alignToElPosition, + x, + y, + myWidth, + myHeight, + alignToElRegion, + viewportWidth = Ext.dom.Element.getViewWidth() - 10, + viewportHeight = Ext.dom.Element.getViewHeight() - 10, + p1y, + p1x, + p2y, + p2x, + swapY, + swapX, + docElement = doc.documentElement, + docBody = doc.body, + scrollX = (docElement.scrollLeft || docBody.scrollLeft || 0), + scrollY = (docElement.scrollTop || docBody.scrollTop || 0), + constrain, + align1, + align2, + alignMatch = posSpec.match(alignRe); + + + align1 = alignMatch[1]; + align2 = alignMatch[2]; + constrain = !!alignMatch[3]; + + + + myPosition = me.getAnchorXY(align1, true); + alignToElPosition = alignToEl.getAnchorXY(align2, false); + + x = alignToElPosition[0] - myPosition[0] + offset[0]; + y = alignToElPosition[1] - myPosition[1] + offset[1]; + + + if (constrain) { + myWidth = me.getWidth(); + myHeight = me.getHeight(); + alignToElRegion = alignToEl.getRegion(); + + + + p1y = align1.charAt(0); + p1x = align1.charAt(align1.length - 1); + p2y = align2.charAt(0); + p2x = align2.charAt(align2.length - 1); + swapY = ((p1y == "t" && p2y == "b") || (p1y == "b" && p2y == "t")); + swapX = ((p1x == "r" && p2x == "l") || (p1x == "l" && p2x == "r")); + + if (x + myWidth > viewportWidth + scrollX) { + x = swapX ? alignToElRegion.left - myWidth : viewportWidth + scrollX - myWidth; + } + if (x < scrollX) { + x = swapX ? alignToElRegion.right : scrollX; + } + if (y + myHeight > viewportHeight + scrollY) { + y = swapY ? alignToElRegion.top - myHeight : viewportHeight + scrollY - myHeight; + } + if (y < scrollY) { + y = swapY ? alignToElRegion.bottom : scrollY; + } + } + return [x,y]; + }, + + + + 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 + }); + + Ext.EventManager.onWindowResize(action, null); + + if (scroll) { + Ext.EventManager.on(win, 'scroll', action, null, + {buffer: !isNaN(monitorScroll) ? monitorScroll : 50}); + } + action.call(me); + return me; + }, + + + removeAnchor : function() { + var me = this, + anchor = this.getAnchor(); + + if (anchor && anchor.fn) { + Ext.EventManager.removeResizeListener(anchor.fn); + if (anchor.scroll) { + Ext.EventManager.un(win, 'scroll', anchor.fn); + } + delete anchor.fn; + } + return me; + }, + + getAlignVector: function(el, spec, offset) { + var me = this, + myPos = me.getXY(), + alignedPos = me.getAlignToXY(el, spec, offset); + + el = Ext.get(el); + + alignedPos[0] -= myPos[0]; + alignedPos[1] -= myPos[1]; + return alignedPos; + }, + + + alignTo: function(element, position, offsets, animate) { + var me = this; + return me.setXY(me.getAlignToXY(element, position, offsets), + me.anim && !!animate ? me.anim(animate) : false); + }, + + + getConstrainVector: function(constrainTo, proposedPosition) { + if (!(constrainTo instanceof Ext.util.Region)) { + constrainTo = Ext.get(constrainTo).getViewRegion(); + } + var thisRegion = this.getRegion(), + vector = [0, 0], + shadowSize = this.shadow && this.shadow.offset, + overflowed = false; + + + if (proposedPosition) { + thisRegion.translateBy(proposedPosition[0] - thisRegion.x, proposedPosition[1] - thisRegion.y); + } + + + + if (shadowSize) { + constrainTo.adjust(0, -shadowSize, -shadowSize, shadowSize); + } + + + if (thisRegion.right > constrainTo.right) { + overflowed = true; + vector[0] = (constrainTo.right - thisRegion.right); + } + if (thisRegion.left + vector[0] < constrainTo.left) { + overflowed = true; + vector[0] = (constrainTo.left - thisRegion.left); + } + + + if (thisRegion.bottom > constrainTo.bottom) { + overflowed = true; + vector[1] = (constrainTo.bottom - thisRegion.bottom); + } + if (thisRegion.top + vector[1] < constrainTo.top) { + overflowed = true; + vector[1] = (constrainTo.top - thisRegion.top); + } + return overflowed ? vector : false; + }, + + + getCenterXY : function(){ + return this.getAlignToXY(doc, 'c-c'); + }, + + + center : function(centerIn){ + return this.alignTo(centerIn || doc, 'c-c'); + } + }; +}())); + + + +Ext.dom.Element.override({ + + animate: function(config) { + var me = this, + listeners, + anim, + animId = me.dom.id || Ext.id(me.dom); + + if (!Ext.fx.Manager.hasFxBlock(animId)) { + + if (config.listeners) { + listeners = config.listeners; + delete config.listeners; + } + if (config.internalListeners) { + config.listeners = config.internalListeners; + delete config.internalListeners; + } + anim = new Ext.fx.Anim(me.anim(config)); + if (listeners) { + anim.on(listeners); + } + Ext.fx.Manager.queueFx(anim); + } + return me; + }, + + + anim: function(config) { + if (!Ext.isObject(config)) { + return (config) ? {} : false; + } + + var me = this, + duration = config.duration || Ext.fx.Anim.prototype.duration, + easing = config.easing || 'ease', + animConfig; + + if (config.stopAnimation) { + me.stopAnimation(); + } + + Ext.applyIf(config, Ext.fx.Manager.getFxDefaults(me.id)); + + + Ext.fx.Manager.setFxDefaults(me.id, { + delay: 0 + }); + + animConfig = { + + target: me.dom, + remove: config.remove, + alternate: config.alternate || false, + duration: duration, + easing: easing, + callback: config.callback, + listeners: config.listeners, + iterations: config.iterations || 1, + scope: config.scope, + block: config.block, + concurrent: config.concurrent, + delay: config.delay || 0, + paused: true, + keyframes: config.keyframes, + from: config.from || {}, + to: Ext.apply({}, config) + }; + Ext.apply(animConfig.to, config.to); + + + delete animConfig.to.to; + delete animConfig.to.from; + delete animConfig.to.remove; + delete animConfig.to.alternate; + delete animConfig.to.keyframes; + delete animConfig.to.iterations; + delete animConfig.to.listeners; + delete animConfig.to.target; + delete animConfig.to.paused; + delete animConfig.to.callback; + delete animConfig.to.scope; + delete animConfig.to.duration; + delete animConfig.to.easing; + delete animConfig.to.concurrent; + delete animConfig.to.block; + delete animConfig.to.stopAnimation; + delete animConfig.to.delay; + return animConfig; + }, + + + slideIn: function(anchor, obj, slideOut) { + var me = this, + elStyle = me.dom.style, + beforeAnim, + wrapAnim, + restoreScroll, + wrapDomParentNode; + + anchor = anchor || "t"; + obj = obj || {}; + + beforeAnim = function() { + var animScope = this, + listeners = obj.listeners, + box, originalStyles, anim, wrap; + + if (!slideOut) { + me.fixDisplay(); + } + + box = me.getBox(); + if ((anchor == 't' || anchor == 'b') && box.height === 0) { + box.height = me.dom.scrollHeight; + } + else if ((anchor == 'l' || anchor == 'r') && box.width === 0) { + box.width = me.dom.scrollWidth; + } + + originalStyles = me.getStyles('width', 'height', 'left', 'right', 'top', 'bottom', 'position', 'z-index', true); + me.setSize(box.width, box.height); + + + if (obj.preserveScroll) { + restoreScroll = me.cacheScrollValues(); + } + + wrap = me.wrap({ + id: Ext.id() + '-anim-wrap-for-' + me.id, + style: { + visibility: slideOut ? 'visible' : 'hidden' + } + }); + wrapDomParentNode = wrap.dom.parentNode; + wrap.setPositioning(me.getPositioning()); + if (wrap.isStyle('position', 'static')) { + wrap.position('relative'); + } + me.clearPositioning('auto'); + wrap.clip(); + + + if (restoreScroll) { + restoreScroll(); + } + + + + + me.setStyle({ + visibility: '', + position: 'absolute' + }); + if (slideOut) { + wrap.setSize(box.width, box.height); + } + + switch (anchor) { + case 't': + anim = { + from: { + width: box.width + 'px', + height: '0px' + }, + to: { + width: box.width + 'px', + height: box.height + 'px' + } + }; + elStyle.bottom = '0px'; + break; + case 'l': + anim = { + from: { + width: '0px', + height: box.height + 'px' + }, + to: { + width: box.width + 'px', + height: box.height + 'px' + } + }; + elStyle.right = '0px'; + break; + case 'r': + anim = { + from: { + x: box.x + box.width, + width: '0px', + height: box.height + 'px' + }, + to: { + x: box.x, + width: box.width + 'px', + height: box.height + 'px' + } + }; + break; + case 'b': + anim = { + from: { + y: box.y + box.height, + width: box.width + 'px', + height: '0px' + }, + to: { + y: box.y, + width: box.width + 'px', + height: box.height + 'px' + } + }; + break; + case 'tl': + anim = { + from: { + x: box.x, + y: box.y, + width: '0px', + height: '0px' + }, + to: { + width: box.width + 'px', + height: box.height + 'px' + } + }; + elStyle.bottom = '0px'; + elStyle.right = '0px'; + break; + case 'bl': + anim = { + from: { + x: box.x + box.width, + width: '0px', + height: '0px' + }, + to: { + x: box.x, + width: box.width + 'px', + height: box.height + 'px' + } + }; + elStyle.right = '0px'; + break; + case 'br': + anim = { + from: { + x: box.x + box.width, + y: box.y + box.height, + width: '0px', + height: '0px' + }, + to: { + x: box.x, + y: box.y, + width: box.width + 'px', + height: box.height + 'px' + } + }; + break; + case 'tr': + anim = { + from: { + y: box.y + box.height, + width: '0px', + height: '0px' + }, + to: { + y: box.y, + width: box.width + 'px', + height: box.height + 'px' + } + }; + elStyle.bottom = '0px'; + break; + } + + wrap.show(); + wrapAnim = Ext.apply({}, obj); + delete wrapAnim.listeners; + wrapAnim = new Ext.fx.Anim(Ext.applyIf(wrapAnim, { + target: wrap, + duration: 500, + easing: 'ease-out', + from: slideOut ? anim.to : anim.from, + to: slideOut ? anim.from : anim.to + })); + + + wrapAnim.on('afteranimate', function() { + me.setStyle(originalStyles); + if (slideOut) { + if (obj.useDisplay) { + me.setDisplayed(false); + } else { + me.hide(); + } + } + if (wrap.dom) { + if (wrap.dom.parentNode) { + wrap.dom.parentNode.insertBefore(me.dom, wrap.dom); + } else { + wrapDomParentNode.appendChild(me.dom); + } + wrap.remove(); + } + + if (restoreScroll) { + restoreScroll(); + } + + animScope.end(); + }); + + if (listeners) { + wrapAnim.on(listeners); + } + }; + + me.animate({ + + duration: obj.duration ? Math.max(obj.duration, 500) * 2 : 1000, + listeners: { + beforeanimate: beforeAnim + } + }); + return me; + }, + + + + slideOut: function(anchor, o) { + return this.slideIn(anchor, o, true); + }, + + + puff: function(obj) { + var me = this, + beforeAnim, + box = me.getBox(), + originalStyles = me.getStyles('width', 'height', 'left', 'right', 'top', 'bottom', 'position', 'z-index', 'font-size', 'opacity', true); + + obj = Ext.applyIf(obj || {}, { + easing: 'ease-out', + duration: 500, + useDisplay: false + }); + + beforeAnim = function() { + me.clearOpacity(); + me.show(); + this.to = { + width: box.width * 2, + height: box.height * 2, + x: box.x - (box.width / 2), + y: box.y - (box.height /2), + opacity: 0, + fontSize: '200%' + }; + this.on('afteranimate',function() { + if (me.dom) { + if (obj.useDisplay) { + me.setDisplayed(false); + } else { + me.hide(); + } + me.setStyle(originalStyles); + obj.callback.call(obj.scope); + } + }); + }; + + me.animate({ + duration: obj.duration, + easing: obj.easing, + listeners: { + beforeanimate: { + fn: beforeAnim + } + } + }); + return me; + }, + + + switchOff: function(obj) { + var me = this, + beforeAnim; + + obj = Ext.applyIf(obj || {}, { + easing: 'ease-in', + duration: 500, + remove: false, + useDisplay: false + }); + + beforeAnim = function() { + var animScope = this, + size = me.getSize(), + xy = me.getXY(), + keyframe, position; + me.clearOpacity(); + me.clip(); + position = me.getPositioning(); + + keyframe = new Ext.fx.Animator({ + target: me, + duration: obj.duration, + easing: obj.easing, + keyframes: { + 33: { + opacity: 0.3 + }, + 66: { + height: 1, + y: xy[1] + size.height / 2 + }, + 100: { + width: 1, + x: xy[0] + size.width / 2 + } + } + }); + keyframe.on('afteranimate', function() { + if (obj.useDisplay) { + me.setDisplayed(false); + } else { + me.hide(); + } + me.clearOpacity(); + me.setPositioning(position); + me.setSize(size); + + animScope.end(); + }); + }; + + me.animate({ + + duration: (Math.max(obj.duration, 500) * 2), + listeners: { + beforeanimate: { + fn: beforeAnim + } + } + }); + return me; + }, + + + frame : function(color, count, obj){ + var me = this, + beforeAnim; + + color = color || '#C3DAF9'; + count = count || 1; + obj = obj || {}; + + beforeAnim = function() { + me.show(); + var animScope = this, + box = me.getBox(), + proxy = Ext.getBody().createChild({ + id: me.id + '-anim-proxy', + style: { + position : 'absolute', + 'pointer-events': 'none', + 'z-index': 35000, + border : '0px solid ' + color + } + }), + proxyAnim; + proxyAnim = new Ext.fx.Anim({ + target: proxy, + duration: obj.duration || 1000, + iterations: count, + from: { + top: box.y, + left: box.x, + borderWidth: 0, + opacity: 1, + height: box.height, + width: box.width + }, + to: { + top: box.y - 20, + left: box.x - 20, + borderWidth: 10, + opacity: 0, + height: box.height + 40, + width: box.width + 40 + } + }); + proxyAnim.on('afteranimate', function() { + proxy.remove(); + + animScope.end(); + }); + }; + + me.animate({ + + duration: (Math.max(obj.duration, 500) * 2) || 2000, + listeners: { + beforeanimate: { + fn: beforeAnim + } + } + }); + return me; + }, + + + ghost: function(anchor, obj) { + var me = this, + beforeAnim; + + anchor = anchor || "b"; + beforeAnim = function() { + var width = me.getWidth(), + height = me.getHeight(), + xy = me.getXY(), + position = me.getPositioning(), + to = { + opacity: 0 + }; + switch (anchor) { + case 't': + to.y = xy[1] - height; + break; + case 'l': + to.x = xy[0] - width; + break; + case 'r': + to.x = xy[0] + width; + break; + case 'b': + to.y = xy[1] + height; + break; + case 'tl': + to.x = xy[0] - width; + to.y = xy[1] - height; + break; + case 'bl': + to.x = xy[0] - width; + to.y = xy[1] + height; + break; + case 'br': + to.x = xy[0] + width; + to.y = xy[1] + height; + break; + case 'tr': + to.x = xy[0] + width; + to.y = xy[1] - height; + break; + } + this.to = to; + this.on('afteranimate', function () { + if (me.dom) { + me.hide(); + me.clearOpacity(); + me.setPositioning(position); + } + }); + }; + + me.animate(Ext.applyIf(obj || {}, { + duration: 500, + easing: 'ease-out', + listeners: { + beforeanimate: { + fn: beforeAnim + } + } + })); + return me; + }, + + + highlight: function(color, o) { + var me = this, + dom = me.dom, + from = {}, + restore, to, attr, lns, event, fn; + + o = o || {}; + lns = o.listeners || {}; + attr = o.attr || 'backgroundColor'; + from[attr] = color || 'ffff9c'; + + if (!o.to) { + to = {}; + to[attr] = o.endColor || me.getColor(attr, 'ffffff', ''); + } + else { + to = o.to; + } + + + o.listeners = Ext.apply(Ext.apply({}, lns), { + beforeanimate: function() { + restore = dom.style[attr]; + me.clearOpacity(); + me.show(); + + event = lns.beforeanimate; + if (event) { + fn = event.fn || event; + return fn.apply(event.scope || lns.scope || window, arguments); + } + }, + afteranimate: function() { + if (dom) { + dom.style[attr] = restore; + } + + event = lns.afteranimate; + if (event) { + fn = event.fn || event; + fn.apply(event.scope || lns.scope || window, arguments); + } + } + }); + + me.animate(Ext.apply({}, o, { + duration: 1000, + easing: 'ease-in', + from: from, + to: to + })); + return me; + }, + + + pause: function(ms) { + var me = this; + Ext.fx.Manager.setFxDefaults(me.id, { + delay: ms + }); + return me; + }, + + + fadeIn: function(o) { + var me = this; + me.animate(Ext.apply({}, o, { + opacity: 1, + internalListeners: { + beforeanimate: function(anim){ + + + if (me.isStyle('display', 'none')) { + me.setDisplayed(''); + } else { + me.show(); + } + } + } + })); + return this; + }, + + + fadeOut: function(o) { + var me = this; + o = Ext.apply({ + opacity: 0, + internalListeners: { + afteranimate: function(anim){ + var dom = me.dom; + if (dom && anim.to.opacity === 0) { + if (o.useDisplay) { + me.setDisplayed(false); + } else { + me.hide(); + } + } + } + } + }, o); + me.animate(o); + return me; + }, + + + scale: function(w, h, o) { + this.animate(Ext.apply({}, o, { + width: w, + height: h + })); + return this; + }, + + + shift: function(config) { + this.animate(config); + return this; + } +}); + + +Ext.dom.Element.override({ + + initDD : function(group, config, overrides){ + var dd = new Ext.dd.DD(Ext.id(this.dom), group, config); + return Ext.apply(dd, overrides); + }, + + + initDDProxy : function(group, config, overrides){ + var dd = new Ext.dd.DDProxy(Ext.id(this.dom), group, config); + return Ext.apply(dd, overrides); + }, + + + initDDTarget : function(group, config, overrides){ + var dd = new Ext.dd.DDTarget(Ext.id(this.dom), group, config); + return Ext.apply(dd, overrides); + } +}); + + +(function() { + +var Element = Ext.dom.Element, + VISIBILITY = "visibility", + DISPLAY = "display", + NONE = "none", + HIDDEN = 'hidden', + VISIBLE = 'visible', + OFFSETS = "offsets", + ASCLASS = "asclass", + NOSIZE = 'nosize', + ORIGINALDISPLAY = 'originalDisplay', + VISMODE = 'visibilityMode', + ISVISIBLE = 'isVisible', + OFFSETCLASS = Ext.baseCSSPrefix + 'hide-offsets', + getDisplay = function(el) { + var data = (el.$cache || el.getCache()).data, + display = data[ORIGINALDISPLAY]; + + if (display === undefined) { + data[ORIGINALDISPLAY] = display = ''; + } + return display; + }, + getVisMode = function(el){ + var data = (el.$cache || el.getCache()).data, + visMode = data[VISMODE]; + + if (visMode === undefined) { + data[VISMODE] = visMode = Element.VISIBILITY; + } + return visMode; + }; + +Element.override({ + + originalDisplay : "", + visibilityMode : 1, + + + setVisible : function(visible, animate) { + var me = this, + dom = me.dom, + visMode = getVisMode(me); + + + if (typeof animate == 'string') { + switch (animate) { + case DISPLAY: + visMode = Element.DISPLAY; + break; + case VISIBILITY: + visMode = Element.VISIBILITY; + break; + case OFFSETS: + visMode = Element.OFFSETS; + break; + case NOSIZE: + case ASCLASS: + visMode = Element.ASCLASS; + break; + } + me.setVisibilityMode(visMode); + animate = false; + } + + if (!animate || !me.anim) { + if (visMode == Element.DISPLAY) { + return me.setDisplayed(visible); + } else if (visMode == Element.OFFSETS) { + me[visible?'removeCls':'addCls'](OFFSETCLASS); + } else if (visMode == Element.VISIBILITY) { + me.fixDisplay(); + + dom.style.visibility = visible ? '' : HIDDEN; + } else if (visMode == Element.ASCLASS) { + me[visible?'removeCls':'addCls'](me.visibilityCls || Element.visibilityCls); + } + } else { + + if (visible) { + me.setOpacity(0.01); + me.setVisible(true); + } + if (!Ext.isObject(animate)) { + animate = { + duration: 350, + easing: 'ease-in' + }; + } + me.animate(Ext.applyIf({ + callback: function() { + if (!visible) { + me.setVisible(false).setOpacity(1); + } + }, + to: { + opacity: (visible) ? 1 : 0 + } + }, animate)); + } + (me.$cache || me.getCache()).data[ISVISIBLE] = visible; + return me; + }, + + + hasMetrics : function(){ + var visMode = getVisMode(this); + return this.isVisible() || (visMode == Element.OFFSETS) || (visMode == Element.VISIBILITY); + }, + + + toggle : function(animate){ + var me = this; + me.setVisible(!me.isVisible(), me.anim(animate)); + return me; + }, + + + setDisplayed : function(value) { + if(typeof value == "boolean"){ + value = value ? getDisplay(this) : NONE; + } + this.setStyle(DISPLAY, value); + return this; + }, + + + fixDisplay : function(){ + var me = this; + if (me.isStyle(DISPLAY, NONE)) { + me.setStyle(VISIBILITY, HIDDEN); + me.setStyle(DISPLAY, getDisplay(me)); + if (me.isStyle(DISPLAY, NONE)) { + me.setStyle(DISPLAY, "block"); + } + } + }, + + + hide : function(animate){ + + if (typeof animate == 'string'){ + this.setVisible(false, animate); + return this; + } + this.setVisible(false, this.anim(animate)); + return this; + }, + + + show : function(animate){ + + if (typeof animate == 'string'){ + this.setVisible(true, animate); + return this; + } + this.setVisible(true, this.anim(animate)); + return this; + } +}); + +}()); + + +(function() { + +var Element = Ext.dom.Element, + LEFT = "left", + RIGHT = "right", + TOP = "top", + BOTTOM = "bottom", + POSITION = "position", + STATIC = "static", + RELATIVE = "relative", + AUTO = "auto", + ZINDEX = "z-index", + BODY = 'BODY', + + PADDING = 'padding', + BORDER = 'border', + SLEFT = '-left', + SRIGHT = '-right', + STOP = '-top', + SBOTTOM = '-bottom', + SWIDTH = '-width', + + borders = {l: BORDER + SLEFT + SWIDTH, r: BORDER + SRIGHT + SWIDTH, t: BORDER + STOP + SWIDTH, b: BORDER + SBOTTOM + SWIDTH}, + paddings = {l: PADDING + SLEFT, r: PADDING + SRIGHT, t: PADDING + STOP, b: PADDING + SBOTTOM}, + paddingsTLRB = [paddings.l, paddings.r, paddings.t, paddings.b], + bordersTLRB = [borders.l, borders.r, borders.t, borders.b], + positionTopLeft = ['position', 'top', 'left']; + +Element.override({ + + getX: function() { + return Element.getX(this.dom); + }, + + getY: function() { + return Element.getY(this.dom); + }, + + + getXY: function() { + return Element.getXY(this.dom); + }, + + + getOffsetsTo : function(el){ + var o = this.getXY(), + e = Ext.fly(el, '_internal').getXY(); + return [o[0] - e[0],o[1] - e[1]]; + }, + + setX: function(x, animate) { + return this.setXY([x, this.getY()], animate); + }, + + setY: function(y, animate) { + return this.setXY([this.getX(), y], animate); + }, + + setLeft: function(left) { + this.setStyle(LEFT, this.addUnits(left)); + return this; + }, + + setTop: function(top) { + this.setStyle(TOP, this.addUnits(top)); + return this; + }, + + setRight: function(right) { + this.setStyle(RIGHT, this.addUnits(right)); + return this; + }, + + setBottom: function(bottom) { + this.setStyle(BOTTOM, this.addUnits(bottom)); + return this; + }, + + + setXY: function(pos, animate) { + var me = this; + if (!animate || !me.anim) { + Element.setXY(me.dom, pos); + } + else { + if (!Ext.isObject(animate)) { + animate = {}; + } + me.animate(Ext.applyIf({ to: { x: pos[0], y: pos[1] } }, animate)); + } + return me; + }, + + getLeft: function(local) { + return !local ? this.getX() : parseFloat(this.getStyle(LEFT)) || 0; + }, + + getRight: function(local) { + var me = this; + return !local ? me.getX() + me.getWidth() : (me.getLeft(true) + me.getWidth()) || 0; + }, + + getTop: function(local) { + return !local ? this.getY() : parseFloat(this.getStyle(TOP)) || 0; + }, + + getBottom: function(local) { + var me = this; + return !local ? me.getY() + me.getHeight() : (me.getTop(true) + me.getHeight()) || 0; + }, + + translatePoints: function(x, y) { + var me = this, + styles = me.getStyle(positionTopLeft), + relative = styles.position == 'relative', + left = parseFloat(styles.left), + top = parseFloat(styles.top), + xy = me.getXY(); + + if (Ext.isArray(x)) { + y = x[1]; + x = x[0]; + } + if (isNaN(left)) { + left = relative ? 0 : me.dom.offsetLeft; + } + if (isNaN(top)) { + top = relative ? 0 : me.dom.offsetTop; + } + left = (typeof x == 'number') ? x - xy[0] + left : undefined; + top = (typeof y == 'number') ? y - xy[1] + top : undefined; + return { + left: left, + top: top + }; + + }, + + 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, animate); + return me; + }, + + getBox: function(contentBox, local) { + var me = this, + xy, + left, + top, + paddingWidth, + bordersWidth, + l, r, t, b, w, h, bx; + + if (!local) { + xy = me.getXY(); + } else { + xy = me.getStyle([LEFT, TOP]); + xy = [ parseFloat(xy.left) || 0, parseFloat(xy.top) || 0]; + } + w = me.getWidth(); + h = me.getHeight(); + if (!contentBox) { + bx = { + x: xy[0], + y: xy[1], + 0: xy[0], + 1: xy[1], + width: w, + height: h + }; + } else { + paddingWidth = me.getStyle(paddingsTLRB); + bordersWidth = me.getStyle(bordersTLRB); + + l = (parseFloat(bordersWidth[borders.l]) || 0) + (parseFloat(paddingWidth[paddings.l]) || 0); + r = (parseFloat(bordersWidth[borders.r]) || 0) + (parseFloat(paddingWidth[paddings.r]) || 0); + t = (parseFloat(bordersWidth[borders.t]) || 0) + (parseFloat(paddingWidth[paddings.t]) || 0); + b = (parseFloat(bordersWidth[borders.b]) || 0) + (parseFloat(paddingWidth[paddings.b]) || 0); + + 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; + }, + + getPageBox: function(getRegion) { + var me = this, + el = me.dom, + isDoc = el.nodeName == BODY, + w = isDoc ? Ext.dom.AbstractElement.getViewWidth() : el.offsetWidth, + h = isDoc ? Ext.dom.AbstractElement.getViewHeight() : el.offsetHeight, + xy = me.getXY(), + t = xy[1], + r = xy[0] + w, + b = xy[1] + h, + l = xy[0]; + + if (getRegion) { + return new Ext.util.Region(t, r, b, l); + } + else { + return { + left: l, + top: t, + width: w, + height: h, + right: r, + bottom: b + }; + } + }, + + + setLocation : function(x, y, animate) { + return this.setXY([x, y], animate); + }, + + + moveTo : function(x, y, animate) { + return this.setXY([x, y], animate); + }, + + + 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]); + } + }, + + + clearPositioning : function(value) { + value = value || ''; + this.setStyle({ + left : value, + right : value, + top : value, + bottom : value, + "z-index" : "", + position : STATIC + }); + return this; + }, + + + getPositioning : function(){ + var styles = this.getStyle([LEFT, TOP, POSITION, RIGHT, BOTTOM, ZINDEX]); + styles[RIGHT] = styles[LEFT] ? '' : styles[RIGHT]; + styles[BOTTOM] = styles[TOP] ? '' : styles[BOTTOM]; + return styles; + }, + + + 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; + }, + + + 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], animate); + }, + + + setLeftTop: function(left, top) { + var style = this.dom.style; + + style.left = Element.addUnits(left); + style.top = Element.addUnits(top); + + return this; + }, + + + getRegion: function() { + return this.getPageBox(true); + }, + + + getViewRegion: function() { + var me = this, + isBody = me.dom.nodeName == BODY, + scroll, pos, top, left, width, height; + + + if (isBody) { + scroll = me.getScroll(); + left = scroll.left; + top = scroll.top; + width = Ext.dom.AbstractElement.getViewportWidth(); + height = Ext.dom.AbstractElement.getViewportHeight(); + } + else { + pos = me.getXY(); + left = pos[0] + me.getBorderWidth('l') + me.getPadding('l'); + top = pos[1] + me.getBorderWidth('t') + me.getPadding('t'); + width = me.getWidth(true); + height = me.getHeight(true); + } + + return new Ext.util.Region(top, left + width, top + height, left); + }, + + + setBounds: function(x, y, width, height, animate) { + var me = this; + if (!animate || !me.anim) { + me.setSize(width, height); + me.setLocation(x, y); + } else { + if (!Ext.isObject(animate)) { + animate = {}; + } + me.animate(Ext.applyIf({ + to: { + x: x, + y: y, + width: me.adjustWidth(width), + height: me.adjustHeight(height) + } + }, animate)); + } + return me; + }, + + + setRegion: function(region, animate) { + return this.setBounds(region.left, region.top, region.right - region.left, region.bottom - region.top, animate); + } +}); + +}()); + + + +Ext.dom.Element.override({ + + isScrollable: function() { + var dom = this.dom; + return dom.scrollHeight > dom.clientHeight || dom.scrollWidth > dom.clientWidth; + }, + + + 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; + }, + + + scrollBy: function(deltaX, deltaY, animate) { + var me = this, + dom = me.dom; + + + if (deltaX.length) { + animate = deltaY; + deltaY = deltaX[1]; + deltaX = deltaX[0]; + } else if (typeof deltaX != 'number') { + animate = deltaY; + deltaY = deltaX.y; + deltaX = deltaX.x; + } + + if (deltaX) { + me.scrollTo('left', Math.max(Math.min(dom.scrollLeft + deltaX, dom.scrollWidth - dom.clientWidth), 0), animate); + } + if (deltaY) { + me.scrollTo('top', Math.max(Math.min(dom.scrollTop + deltaY, dom.scrollHeight - dom.clientHeight), 0), animate); + } + + return me; + }, + + + scrollTo: function(side, value, animate) { + + var top = /top/i.test(side), + me = this, + dom = me.dom, + obj = {}, + prop; + + if (!animate || !me.anim) { + + prop = 'scroll' + (top ? 'Top' : 'Left'); + dom[prop] = value; + } + else { + if (!Ext.isObject(animate)) { + animate = {}; + } + obj['scroll' + (top ? 'Top' : 'Left')] = value; + me.animate(Ext.applyIf({ + to: obj + }, animate)); + } + return me; + }, + + + scrollIntoView: function(container, hscroll) { + container = Ext.getDom(container) || Ext.getBody().dom; + var el = this.dom, + offsets = this.getOffsetsTo(container), + + left = offsets[0] + container.scrollLeft, + top = offsets[1] + container.scrollTop, + bottom = top + el.offsetHeight, + right = left + el.offsetWidth, + + ctClientHeight = container.clientHeight, + ctScrollTop = parseInt(container.scrollTop, 10), + ctScrollLeft = parseInt(container.scrollLeft, 10), + ctBottom = ctScrollTop + ctClientHeight, + ctRight = ctScrollLeft + container.clientWidth; + + if (el.offsetHeight > ctClientHeight || top < ctScrollTop) { + container.scrollTop = top; + } else if (bottom > ctBottom) { + container.scrollTop = bottom - ctClientHeight; + } + + container.scrollTop = container.scrollTop; + + if (hscroll !== false) { + if (el.offsetWidth > container.clientWidth || left < ctScrollLeft) { + container.scrollLeft = left; + } + else if (right > ctRight) { + container.scrollLeft = right - container.clientWidth; + } + container.scrollLeft = container.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.anim(animate)); + } + return scrolled; + } +}); + + +(function() { + +var Element = Ext.dom.Element, + view = document.defaultView, + adjustDirect2DTableRe = /table-row|table-.*-group/, + INTERNAL = '_internal', + HIDDEN = 'hidden', + HEIGHT = 'height', + WIDTH = 'width', + ISCLIPPED = 'isClipped', + OVERFLOW = 'overflow', + OVERFLOWX = 'overflow-x', + OVERFLOWY = 'overflow-y', + ORIGINALCLIP = 'originalClip', + DOCORBODYRE = /#document|body/i, + + + styleHooks, + edges, k, edge, borderWidth; + +if (!view || !view.getComputedStyle) { + Element.prototype.getStyle = function (property, inline) { + var me = this, + dom = me.dom, + multiple = typeof property != 'string', + hooks = me.styleHooks, + prop = property, + props = prop, + len = 1, + isInline = inline, + camel, domStyle, values, hook, out, style, i; + + if (multiple) { + values = {}; + prop = props[0]; + i = 0; + if (!(len = props.length)) { + return values; + } + } + + if (!dom || dom.documentElement) { + return values || ''; + } + + domStyle = dom.style; + + if (inline) { + style = domStyle; + } else { + style = dom.currentStyle; + + + if (!style) { + isInline = true; + style = domStyle; + } + } + + do { + hook = hooks[prop]; + + if (!hook) { + hooks[prop] = hook = { name: Element.normalize(prop) }; + } + + if (hook.get) { + out = hook.get(dom, me, isInline, style); + } else { + camel = hook.name; + + + + + + if (hook.canThrow) { + try { + out = style[camel]; + } catch (e) { + out = ''; + } + } else { + + + out = style ? style[camel] : ''; + } + } + + if (!multiple) { + return out; + } + + values[prop] = out; + prop = props[++i]; + } while (i < len); + + return values; + }; +} + +Element.override({ + getHeight: function(contentHeight, preciseHeight) { + var me = this, + dom = me.dom, + hidden = me.isStyle('display', 'none'), + height, + floating; + + if (hidden) { + return 0; + } + + height = Math.max(dom.offsetHeight, dom.clientHeight) || 0; + + + if (Ext.supports.Direct2DBug) { + floating = me.adjustDirect2DDimension(HEIGHT); + if (preciseHeight) { + height += floating; + } + else if (floating > 0 && floating < 0.5) { + height++; + } + } + + if (contentHeight) { + height -= me.getBorderWidth("tb") + me.getPadding("tb"); + } + + return (height < 0) ? 0 : height; + }, + + getWidth: function(contentWidth, preciseWidth) { + var me = this, + dom = me.dom, + hidden = me.isStyle('display', 'none'), + rect, width, floating; + + if (hidden) { + return 0; + } + + + + + + + + if (Ext.supports.BoundingClientRect) { + rect = dom.getBoundingClientRect(); + width = rect.right - rect.left; + width = preciseWidth ? width : Math.ceil(width); + } else { + width = dom.offsetWidth; + } + + width = Math.max(width, dom.clientWidth) || 0; + + + if (Ext.supports.Direct2DBug) { + + floating = me.adjustDirect2DDimension(WIDTH); + if (preciseWidth) { + width += floating; + } + + + + else if (floating > 0 && floating < 0.5) { + width++; + } + } + + if (contentWidth) { + width -= me.getBorderWidth("lr") + me.getPadding("lr"); + } + + return (width < 0) ? 0 : width; + }, + + setWidth: function(width, animate) { + var me = this; + width = me.adjustWidth(width); + if (!animate || !me.anim) { + me.dom.style.width = me.addUnits(width); + } + else { + if (!Ext.isObject(animate)) { + animate = {}; + } + me.animate(Ext.applyIf({ + to: { + width: width + } + }, animate)); + } + return me; + }, + + setHeight : function(height, animate) { + var me = this; + + height = me.adjustHeight(height); + if (!animate || !me.anim) { + me.dom.style.height = me.addUnits(height); + } + else { + if (!Ext.isObject(animate)) { + animate = {}; + } + me.animate(Ext.applyIf({ + to: { + height: height + } + }, animate)); + } + + return me; + }, + + applyStyles: function(style) { + Ext.DomHelper.applyStyles(this.dom, style); + return this; + }, + + setSize: function(width, height, animate) { + var me = this; + + if (Ext.isObject(width)) { + animate = height; + 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 { + if (animate === true) { + animate = {}; + } + me.animate(Ext.applyIf({ + to: { + width: width, + height: height + } + }, animate)); + } + + return me; + }, + + getViewSize : function() { + var me = this, + dom = me.dom, + isDoc = DOCORBODYRE.test(dom.nodeName), + ret; + + + if (isDoc) { + ret = { + width : Element.getViewWidth(), + height : Element.getViewHeight() + }; + } else { + ret = { + width : dom.clientWidth, + height : dom.clientHeight + }; + } + + return ret; + }, + + getSize: function(contentSize) { + return {width: this.getWidth(contentSize), height: this.getHeight(contentSize)}; + }, + + + + + adjustWidth : function(width) { + var me = this, + isNum = (typeof width == 'number'); + + if (isNum && me.autoBoxAdjust && !me.isBorderBox()) { + width -= (me.getBorderWidth("lr") + me.getPadding("lr")); + } + return (isNum && width < 0) ? 0 : width; + }, + + + adjustHeight : function(height) { + var me = this, + isNum = (typeof height == "number"); + + if (isNum && me.autoBoxAdjust && !me.isBorderBox()) { + height -= (me.getBorderWidth("tb") + me.getPadding("tb")); + } + return (isNum && height < 0) ? 0 : height; + }, + + + getColor : function(attr, defaultValue, prefix) { + var v = this.getStyle(attr), + color = prefix || prefix === '' ? prefix : '#', + h, len, i=0; + + if (!v || (/transparent|inherit/.test(v))) { + return defaultValue; + } + if (/^r/.test(v)) { + v = v.slice(4, v.length - 1).split(','); + len = v.length; + for (; i 5 ? color.toLowerCase() : defaultValue); + }, + + + setOpacity: function(opacity, animate) { + var me = this; + + if (!me.dom) { + return me; + } + + if (!animate || !me.anim) { + me.setStyle('opacity', opacity); + } + else { + if (typeof animate != 'object') { + animate = { + duration: 350, + easing: 'ease-in' + }; + } + + me.animate(Ext.applyIf({ + to: { + opacity: opacity + } + }, animate)); + } + return me; + }, + + + clearOpacity : function() { + return this.setOpacity(''); + }, + + + adjustDirect2DDimension: function(dimension) { + var me = this, + dom = me.dom, + display = me.getStyle('display'), + inlineDisplay = dom.style.display, + inlinePosition = dom.style.position, + originIndex = dimension === WIDTH ? 0 : 1, + currentStyle = dom.currentStyle, + floating; + + if (display === 'inline') { + dom.style.display = 'inline-block'; + } + + dom.style.position = display.match(adjustDirect2DTableRe) ? 'absolute' : 'static'; + + + + + + + floating = (parseFloat(currentStyle[dimension]) || parseFloat(currentStyle.msTransformOrigin.split(' ')[originIndex]) * 2) % 1; + + dom.style.position = inlinePosition; + + if (display === 'inline') { + dom.style.display = inlineDisplay; + } + + return floating; + }, + + + clip : function() { + var me = this, + data = (me.$cache || me.getCache()).data, + style; + + if (!data[ISCLIPPED]) { + data[ISCLIPPED] = true; + style = me.getStyle([OVERFLOW, OVERFLOWX, OVERFLOWY]); + data[ORIGINALCLIP] = { + o: style[OVERFLOW], + x: style[OVERFLOWX], + y: style[OVERFLOWY] + }; + me.setStyle(OVERFLOW, HIDDEN); + me.setStyle(OVERFLOWX, HIDDEN); + me.setStyle(OVERFLOWY, HIDDEN); + } + return me; + }, + + + unclip : function() { + var me = this, + data = (me.$cache || me.getCache()).data, + clip; + + if (data[ISCLIPPED]) { + data[ISCLIPPED] = false; + clip = data[ORIGINALCLIP]; + if (clip.o) { + me.setStyle(OVERFLOW, clip.o); + } + if (clip.x) { + me.setStyle(OVERFLOWX, clip.x); + } + if (clip.y) { + me.setStyle(OVERFLOWY, clip.y); + } + } + return me; + }, + + + boxWrap : function(cls) { + cls = cls || Ext.baseCSSPrefix + 'box'; + var el = Ext.get(this.insertHtml("beforeBegin", "
    " + Ext.String.format(Element.boxMarkup, cls) + "
    ")); + Ext.DomQuery.selectNode('.' + cls + '-mc', el.dom).appendChild(this.dom); + return el; + }, + + + getComputedHeight : function() { + var me = this, + h = Math.max(me.dom.offsetHeight, me.dom.clientHeight); + if (!h) { + h = parseFloat(me.getStyle(HEIGHT)) || 0; + if (!me.isBorderBox()) { + h += me.getFrameWidth('tb'); + } + } + return h; + }, + + + getComputedWidth : function() { + var me = this, + w = Math.max(me.dom.offsetWidth, me.dom.clientWidth); + + if (!w) { + w = parseFloat(me.getStyle(WIDTH)) || 0; + if (!me.isBorderBox()) { + w += me.getFrameWidth('lr'); + } + } + return w; + }, + + + getFrameWidth : function(sides, onlyContentBox) { + return (onlyContentBox && this.isBorderBox()) ? 0 : (this.getPadding(sides) + this.getBorderWidth(sides)); + }, + + + addClsOnOver : function(className, testFn, scope) { + var me = this, + dom = me.dom, + hasTest = Ext.isFunction(testFn); + + me.hover( + function() { + if (hasTest && testFn.call(scope || me, me) === false) { + return; + } + Ext.fly(dom, INTERNAL).addCls(className); + }, + function() { + Ext.fly(dom, INTERNAL).removeCls(className); + } + ); + return me; + }, + + + addClsOnFocus : function(className, testFn, scope) { + var me = this, + dom = me.dom, + hasTest = Ext.isFunction(testFn); + + me.on("focus", function() { + if (hasTest && testFn.call(scope || me, me) === false) { + return false; + } + Ext.fly(dom, INTERNAL).addCls(className); + }); + me.on("blur", function() { + Ext.fly(dom, INTERNAL).removeCls(className); + }); + return me; + }, + + + addClsOnClick : function(className, testFn, scope) { + var me = this, + dom = me.dom, + hasTest = Ext.isFunction(testFn); + + me.on("mousedown", function() { + if (hasTest && testFn.call(scope || me, me) === false) { + return false; + } + Ext.fly(dom, INTERNAL).addCls(className); + var d = Ext.getDoc(), + fn = function() { + Ext.fly(dom, INTERNAL).removeCls(className); + d.removeListener("mouseup", fn); + }; + d.on("mouseup", fn); + }); + return me; + }, + + + getStyleSize : function() { + var me = this, + d = this.dom, + isDoc = DOCORBODYRE.test(d.nodeName), + s , + w, h; + + + if (isDoc) { + return { + width : Element.getViewWidth(), + height : Element.getViewHeight() + }; + } + + s = me.getStyle([HEIGHT, WIDTH], true); + + 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)}; + }, + + + selectable : function() { + var me = this; + me.dom.unselectable = "off"; + + me.on('selectstart', function (e) { + e.stopPropagation(); + return true; + }); + me.applyStyles("-moz-user-select: text; -khtml-user-select: text;"); + me.removeCls(Ext.baseCSSPrefix + 'unselectable'); + return me; + }, + + + unselectable : function() { + var me = this; + me.dom.unselectable = "on"; + + me.swallowEvent("selectstart", true); + me.applyStyles("-moz-user-select:-moz-none;-khtml-user-select:none;"); + me.addCls(Ext.baseCSSPrefix + 'unselectable'); + + return me; + } +}); + +Element.prototype.styleHooks = styleHooks = Ext.dom.AbstractElement.prototype.styleHooks; + +if (Ext.isIE6) { + styleHooks.fontSize = styleHooks['font-size'] = { + name: 'fontSize', + canThrow: true + }; +} + + +if (Ext.isIEQuirks || Ext.isIE && Ext.ieVersion <= 8) { + function getBorderWidth (dom, el, inline, style) { + if (style[this.styleName] == 'none') { + return '0px'; + } + return style[this.name]; + } + + edges = ['Top','Right','Bottom','Left']; + k = edges.length; + + while (k--) { + edge = edges[k]; + borderWidth = 'border' + edge + 'Width'; + + styleHooks['border-'+edge.toLowerCase()+'-width'] = styleHooks[borderWidth] = { + name: borderWidth, + styleName: 'border' + edge + 'Style', + get: getBorderWidth + }; + } +} + +}()); + +Ext.onReady(function () { + var opacityRe = /alpha\(opacity=(.*)\)/i, + trimRe = /^\s+|\s+$/g, + hooks = Ext.dom.Element.prototype.styleHooks; + + + hooks.opacity = { + name: 'opacity', + afterSet: function(dom, value, el) { + if (el.isLayer) { + el.onOpacitySet(value); + } + } + }; + if (!Ext.supports.Opacity && Ext.isIE) { + Ext.apply(hooks.opacity, { + get: function (dom) { + var filter = dom.style.filter, + match, opacity; + if (filter.match) { + match = filter.match(opacityRe); + if (match) { + opacity = parseFloat(match[1]); + if (!isNaN(opacity)) { + return opacity ? opacity / 100 : 0; + } + } + } + return 1; + }, + set: function (dom, value) { + var style = dom.style, + val = style.filter.replace(opacityRe, '').replace(trimRe, ''); + + style.zoom = 1; + + + if (typeof(value) == 'number' && value >= 0 && value < 1) { + value *= 100; + style.filter = val + (val.length ? ' ' : '') + 'alpha(opacity='+value+')'; + } else { + style.filter = val; + } + } + }); + } + + +}); + + +Ext.dom.Element.override({ + select: function(selector) { + return Ext.dom.Element.select(selector, false, this.dom); + } +}); + + +Ext.define('Ext.dom.CompositeElementLite', { + alternateClassName: 'Ext.CompositeElementLite', + + requires: ['Ext.dom.Element'], + + statics: { + + importElementMethods: function() { + var name, + elementPrototype = Ext.dom.Element.prototype, + prototype = this.prototype; + + for (name in elementPrototype) { + if (typeof elementPrototype[name] == 'function'){ + (function(key) { + prototype[key] = prototype[key] || function() { + return this.invoke(key, arguments); + }; + }).call(prototype, name); + + } + } + } + }, + + constructor: function(elements, root) { + + this.elements = []; + this.add(elements, root); + this.el = new Ext.dom.AbstractElement.Fly(); + }, + + + isComposite: true, + + + getElement: function(el) { + + return this.el.attach(el); + }, + + + transformElement: function(el) { + return Ext.getDom(el); + }, + + + getCount: function() { + return this.elements.length; + }, + + + add: function(els, root) { + var elements = this.elements, + i, ln; + + if (!els) { + return this; + } + + if (typeof els == "string") { + els = Ext.dom.Element.selectorFunction(els, root); + } + else if (els.isComposite) { + els = els.elements; + } + else if (!Ext.isIterable(els)) { + els = [els]; + } + + for (i = 0, ln = els.length; i < ln; ++i) { + elements.push(this.transformElement(els[i])); + } + + return this; + }, + + invoke: function(fn, args) { + var elements = this.elements, + ln = elements.length, + element, + i; + + fn = Ext.dom.Element.prototype[fn]; + for (i = 0; i < ln; i++) { + element = elements[i]; + + if (element) { + fn.apply(this.getElement(element), args); + } + } + return this; + }, + + + item: function(index) { + var el = this.elements[index], + out = null; + + if (el) { + out = this.getElement(el); + } + + return out; + }, + + + addListener: function(eventName, handler, scope, opt) { + var els = this.elements, + len = els.length, + i, e; + + for (i = 0; i < len; i++) { + e = els[i]; + if (e) { + Ext.EventManager.on(e, eventName, handler, scope || e, opt); + } + } + return this; + }, + + each: function(fn, scope) { + var me = this, + els = me.elements, + len = els.length, + i, e; + + for (i = 0; i < len; i++) { + e = els[i]; + if (e) { + e = this.getElement(e); + if (fn.call(scope || e, e, me, i) === false) { + break; + } + } + } + return me; + }, + + + fill: function(els) { + var me = this; + me.elements = []; + me.add(els); + return me; + }, + + + filter: function(selector) { + var me = this, + els = me.elements, + len = els.length, + out = [], + i = 0, + isFunc = typeof selector == 'function', + add, + el; + + for (; i < len; i++) { + el = els[i]; + add = false; + if (el) { + el = me.getElement(el); + + if (isFunc) { + add = selector.call(el, el, me, i) !== false; + } else { + add = el.is(selector); + } + + if (add) { + out.push(me.transformElement(el)); + } + } + } + + me.elements = out; + return me; + }, + + + indexOf: function(el) { + return Ext.Array.indexOf(this.elements, this.transformElement(el)); + }, + + + 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); + } + Ext.Array.splice(this.elements, index, 1, replacement); + } + return this; + }, + + + clear: function() { + this.elements = []; + }, + + addElements: function(els, root) { + if (!els) { + return this; + } + + if (typeof els == "string") { + els = Ext.dom.Element.selectorFunction(els, root); + } + + var yels = this.elements, + eLen = els.length, + e; + + for (e = 0; e < eLen; e++) { + yels.push(Ext.get(els[e])); + } + + return this; + }, + + + first: function() { + return this.item(0); + }, + + + last: function() { + return this.item(this.getCount() - 1); + }, + + + contains: function(el) { + return this.indexOf(el) != -1; + }, + + + removeElement: function(keys, removeDom) { + keys = [].concat(keys); + + var me = this, + elements = me.elements, + kLen = keys.length, + val, el, k; + + for (k = 0; k < kLen; k++) { + val = keys[k]; + + if ((el = (elements[val] || elements[val = me.indexOf(val)]))) { + if (removeDom) { + if (el.dom) { + el.remove(); + } else { + Ext.removeNode(el); + } + } + Ext.Array.erase(elements, val, 1); + } + } + + return me; + } + +}, function() { + this.importElementMethods(); + + this.prototype.on = this.prototype.addListener; + + if (Ext.DomQuery){ + Ext.dom.Element.selectorFunction = Ext.DomQuery.select; + } + + + Ext.dom.Element.select = function(selector, root) { + var elements; + + if (typeof selector == "string") { + elements = Ext.dom.Element.selectorFunction(selector, root); + } + else if (selector.length !== undefined) { + elements = selector; + } + else { + } + + return new Ext.CompositeElementLite(elements); + }; + + + Ext.select = function() { + return Ext.dom.Element.select.apply(Ext.dom.Element, arguments); + }; +}); + + +Ext.define('Ext.dom.CompositeElement', { + alternateClassName: 'Ext.CompositeElement', + + extend: 'Ext.dom.CompositeElementLite', + + + getElement: function(el) { + + return el; + }, + + + transformElement: function(el) { + return Ext.get(el); + } + +}, function() { + + + Ext.dom.Element.select = function(selector, unique, root) { + var elements; + + if (typeof selector == "string") { + elements = Ext.dom.Element.selectorFunction(selector, root); + } + else if (selector.length !== undefined) { + elements = selector; + } + else { + } + return (unique === true) ? new Ext.CompositeElement(elements) : new Ext.CompositeElementLite(elements); + }; +}); + + +Ext.select = Ext.Element.select; + + +this.ExtBootstrapData = { + "nameToAliasesMap":{ + "Ext.AbstractComponent":[], + "Ext.AbstractManager":[], + "Ext.AbstractPlugin":[], + "Ext.Ajax":[], + "Ext.ComponentLoader":[], + "Ext.ComponentManager":[], + "Ext.ComponentQuery":[], + "Ext.ElementLoader":[], + "Ext.ModelManager":[], + "Ext.PluginManager":[], + "Ext.Template":[], + "Ext.XTemplate":[], + "Ext.XTemplateCompiler":[], + "Ext.XTemplateParser":[], + "Ext.app.Application":[], + "Ext.app.Controller":[], + "Ext.app.EventBus":[], + "Ext.chart.Callout":[], + "Ext.chart.Chart":["widget.chart" + ], + "Ext.chart.Highlight":[], + "Ext.chart.Label":[], + "Ext.chart.Legend":[], + "Ext.chart.LegendItem":[], + "Ext.chart.Mask":[], + "Ext.chart.MaskLayer":[], + "Ext.chart.Navigation":[], + "Ext.chart.Shape":[], + "Ext.chart.Tip":[], + "Ext.chart.TipSurface":[], + "Ext.chart.axis.Abstract":[], + "Ext.chart.axis.Axis":[], + "Ext.chart.axis.Category":["axis.category" + ], + "Ext.chart.axis.Gauge":["axis.gauge" + ], + "Ext.chart.axis.Numeric":["axis.numeric" + ], + "Ext.chart.axis.Radial":["axis.radial" + ], + "Ext.chart.axis.Time":["axis.time" + ], + "Ext.chart.series.Area":["series.area" + ], + "Ext.chart.series.Bar":["series.bar" + ], + "Ext.chart.series.Cartesian":[], + "Ext.chart.series.Column":["series.column" + ], + "Ext.chart.series.Gauge":["series.gauge" + ], + "Ext.chart.series.Line":["series.line" + ], + "Ext.chart.series.Pie":["series.pie" + ], + "Ext.chart.series.Radar":["series.radar" + ], + "Ext.chart.series.Scatter":["series.scatter" + ], + "Ext.chart.series.Series":[], + "Ext.chart.theme.Base":[], + "Ext.chart.theme.Theme":[], + "Ext.container.AbstractContainer":[], + "Ext.container.DockingContainer":[], + "Ext.data.AbstractStore":[], + "Ext.data.ArrayStore":["store.array" + ], + "Ext.data.Batch":[], + "Ext.data.BufferStore":["store.buffer" + ], + "Ext.data.Connection":[], + "Ext.data.DirectStore":["store.direct" + ], + "Ext.data.Errors":[], + "Ext.data.Field":["data.field" + ], + "Ext.data.IdGenerator":[], + "Ext.data.JsonP":[], + "Ext.data.JsonPStore":["store.jsonp" + ], + "Ext.data.JsonStore":["store.json" + ], + "Ext.data.Model":[], + "Ext.data.NodeInterface":[], + "Ext.data.NodeStore":["store.node" + ], + "Ext.data.Operation":[], + "Ext.data.Request":[], + "Ext.data.ResultSet":[], + "Ext.data.SequentialIdGenerator":["idgen.sequential" + ], + "Ext.data.SortTypes":[], + "Ext.data.Store":["store.store" + ], + "Ext.data.StoreManager":[], + "Ext.data.Tree":["data.tree" + ], + "Ext.data.TreeStore":["store.tree" + ], + "Ext.data.Types":[], + "Ext.data.UuidGenerator":[], + "Ext.data.validations":[], + "Ext.data.XmlStore":["store.xml" + ], + "Ext.data.association.Association":[], + "Ext.data.association.BelongsTo":["association.belongsto" + ], + "Ext.data.association.HasMany":["association.hasmany" + ], + "Ext.data.association.HasOne":["association.hasone" + ], + "Ext.data.proxy.Ajax":["proxy.ajax" + ], + "Ext.data.proxy.Client":[], + "Ext.data.proxy.Direct":["proxy.direct" + ], + "Ext.data.proxy.JsonP":["proxy.jsonp", + "proxy.scripttag" + ], + "Ext.data.proxy.LocalStorage":["proxy.localstorage" + ], + "Ext.data.proxy.Memory":["proxy.memory" + ], + "Ext.data.proxy.Proxy":["proxy.proxy" + ], + "Ext.data.proxy.Rest":["proxy.rest" + ], + "Ext.data.proxy.Server":["proxy.server" + ], + "Ext.data.proxy.SessionStorage":["proxy.sessionstorage" + ], + "Ext.data.proxy.WebStorage":[], + "Ext.data.reader.Array":["reader.array" + ], + "Ext.data.reader.Json":["reader.json" + ], + "Ext.data.reader.Reader":[], + "Ext.data.reader.Xml":["reader.xml" + ], + "Ext.data.writer.Json":["writer.json" + ], + "Ext.data.writer.Writer":["writer.base" + ], + "Ext.data.writer.Xml":["writer.xml" + ], + "Ext.direct.Event":["direct.event" + ], + "Ext.direct.ExceptionEvent":["direct.exception" + ], + "Ext.direct.JsonProvider":["direct.jsonprovider" + ], + "Ext.direct.Manager":[], + "Ext.direct.PollingProvider":["direct.pollingprovider" + ], + "Ext.direct.Provider":["direct.provider" + ], + "Ext.direct.RemotingEvent":["direct.rpc" + ], + "Ext.direct.RemotingMethod":[], + "Ext.direct.RemotingProvider":["direct.remotingprovider" + ], + "Ext.direct.Transaction":["direct.transaction" + ], + "Ext.draw.Color":[], + "Ext.draw.Component":["widget.draw" + ], + "Ext.draw.CompositeSprite":[], + "Ext.draw.Draw":[], + "Ext.draw.Matrix":[], + "Ext.draw.Sprite":[], + "Ext.draw.SpriteDD":[], + "Ext.draw.Surface":[], + "Ext.draw.Text":["widget.text" + ], + "Ext.draw.engine.ImageExporter":[], + "Ext.draw.engine.Svg":[], + "Ext.draw.engine.SvgExporter":[], + "Ext.draw.engine.Vml":[], + "Ext.fx.Anim":[], + "Ext.fx.Animator":[], + "Ext.fx.CubicBezier":[], + "Ext.fx.Manager":[], + "Ext.fx.PropertyHandler":[], + "Ext.fx.Queue":[], + "Ext.fx.target.Component":[], + "Ext.fx.target.CompositeElement":[], + "Ext.fx.target.CompositeElementCSS":[], + "Ext.fx.target.CompositeSprite":[], + "Ext.fx.target.Element":[], + "Ext.fx.target.ElementCSS":[], + "Ext.fx.target.Sprite":[], + "Ext.fx.target.Target":[], + "Ext.layout.ClassList":[], + "Ext.layout.Context":[], + "Ext.layout.ContextItem":[], + "Ext.layout.Layout":[], + "Ext.layout.component.Auto":["layout.autocomponent" + ], + "Ext.layout.component.Component":[], + "Ext.layout.component.Draw":["layout.draw" + ], + "Ext.layout.container.Auto":["layout.auto", + "layout.autocontainer" + ], + "Ext.panel.AbstractPanel":[], + "Ext.selection.DataViewModel":[], + "Ext.selection.Model":[], + "Ext.state.CookieProvider":[], + "Ext.state.LocalStorageProvider":["state.localstorage" + ], + "Ext.state.Manager":[], + "Ext.state.Provider":[], + "Ext.state.Stateful":[], + "Ext.util.AbstractMixedCollection":[], + "Ext.util.Bindable":[], + "Ext.util.ElementContainer":[], + "Ext.util.Filter":[], + "Ext.util.Grouper":[], + "Ext.util.HashMap":[], + "Ext.util.Inflector":[], + "Ext.util.LruCache":[], + "Ext.util.Memento":[], + "Ext.util.MixedCollection":[], + "Ext.util.Observable":[], + "Ext.util.Offset":[], + "Ext.util.Point":[], + "Ext.util.ProtoElement":[], + "Ext.util.Queue":[], + "Ext.util.Region":[], + "Ext.util.Renderable":[], + "Ext.util.Sortable":[], + "Ext.util.Sorter":[], + "Ext.view.AbstractView":[], + "Ext.Action":[], + "Ext.Component":["widget.component", + "widget.box" + ], + "Ext.Editor":["widget.editor" + ], + "Ext.FocusManager":[], + "Ext.Img":["widget.image", + "widget.imagecomponent" + ], + "Ext.Layer":[], + "Ext.LoadMask":["widget.loadmask" + ], + "Ext.ProgressBar":["widget.progressbar" + ], + "Ext.Shadow":[], + "Ext.ShadowPool":[], + "Ext.ZIndexManager":[], + "Ext.button.Button":["widget.button" + ], + "Ext.button.Cycle":["widget.cycle" + ], + "Ext.button.Split":["widget.splitbutton" + ], + "Ext.container.ButtonGroup":["widget.buttongroup" + ], + "Ext.container.Container":["widget.container" + ], + "Ext.container.Viewport":["widget.viewport" + ], + "Ext.dd.DD":[], + "Ext.dd.DDProxy":[], + "Ext.dd.DDTarget":[], + "Ext.dd.DragDrop":[], + "Ext.dd.DragDropManager":[], + "Ext.dd.DragSource":[], + "Ext.dd.DragTracker":[], + "Ext.dd.DragZone":[], + "Ext.dd.DropTarget":[], + "Ext.dd.DropZone":[], + "Ext.dd.Registry":[], + "Ext.dd.ScrollManager":[], + "Ext.dd.StatusProxy":[], + "Ext.dom.Element":[], + "Ext.dom.Helper":[], + "Ext.flash.Component":["widget.flash" + ], + "Ext.form.Basic":[], + "Ext.form.CheckboxGroup":["widget.checkboxgroup" + ], + "Ext.form.CheckboxManager":[], + "Ext.form.FieldAncestor":[], + "Ext.form.FieldContainer":["widget.fieldcontainer" + ], + "Ext.form.FieldSet":["widget.fieldset" + ], + "Ext.form.Label":["widget.label" + ], + "Ext.form.Labelable":[], + "Ext.form.Panel":["widget.form" + ], + "Ext.form.RadioGroup":["widget.radiogroup" + ], + "Ext.form.RadioManager":[], + "Ext.form.action.Action":[], + "Ext.form.action.DirectLoad":["formaction.directload" + ], + "Ext.form.action.DirectSubmit":["formaction.directsubmit" + ], + "Ext.form.action.Load":["formaction.load" + ], + "Ext.form.action.StandardSubmit":["formaction.standardsubmit" + ], + "Ext.form.action.Submit":["formaction.submit" + ], + "Ext.form.field.Base":["widget.field" + ], + "Ext.form.field.Checkbox":["widget.checkboxfield", + "widget.checkbox" + ], + "Ext.form.field.ComboBox":["widget.combobox", + "widget.combo" + ], + "Ext.form.field.Date":["widget.datefield" + ], + "Ext.form.field.Display":["widget.displayfield" + ], + "Ext.form.field.Field":[], + "Ext.form.field.File":["widget.filefield", + "widget.fileuploadfield" + ], + "Ext.form.field.Hidden":["widget.hiddenfield", + "widget.hidden" + ], + "Ext.form.field.HtmlEditor":["widget.htmleditor" + ], + "Ext.form.field.Number":["widget.numberfield" + ], + "Ext.form.field.Picker":["widget.pickerfield" + ], + "Ext.form.field.Radio":["widget.radiofield", + "widget.radio" + ], + "Ext.form.field.Spinner":["widget.spinnerfield" + ], + "Ext.form.field.Text":["widget.textfield" + ], + "Ext.form.field.TextArea":["widget.textareafield", + "widget.textarea" + ], + "Ext.form.field.Time":["widget.timefield" + ], + "Ext.form.field.Trigger":["widget.triggerfield", + "widget.trigger" + ], + "Ext.form.field.VTypes":[], + "Ext.grid.CellEditor":[], + "Ext.grid.ColumnComponentLayout":["layout.columncomponent" + ], + "Ext.grid.ColumnLayout":["layout.gridcolumn" + ], + "Ext.grid.Lockable":[], + "Ext.grid.LockingView":[], + "Ext.grid.PagingScroller":[], + "Ext.grid.Panel":["widget.gridpanel", + "widget.grid" + ], + "Ext.grid.RowEditor":[], + "Ext.grid.RowNumberer":["widget.rownumberer" + ], + "Ext.grid.Scroller":[], + "Ext.grid.View":["widget.gridview" + ], + "Ext.grid.ViewDropZone":[], + "Ext.grid.column.Action":["widget.actioncolumn" + ], + "Ext.grid.column.Boolean":["widget.booleancolumn" + ], + "Ext.grid.column.Column":["widget.gridcolumn" + ], + "Ext.grid.column.Date":["widget.datecolumn" + ], + "Ext.grid.column.Number":["widget.numbercolumn" + ], + "Ext.grid.column.Template":["widget.templatecolumn" + ], + "Ext.grid.feature.AbstractSummary":["feature.abstractsummary" + ], + "Ext.grid.feature.Chunking":["feature.chunking" + ], + "Ext.grid.feature.Feature":["feature.feature" + ], + "Ext.grid.feature.Grouping":["feature.grouping" + ], + "Ext.grid.feature.GroupingSummary":["feature.groupingsummary" + ], + "Ext.grid.feature.RowBody":["feature.rowbody" + ], + "Ext.grid.feature.RowWrap":["feature.rowwrap" + ], + "Ext.grid.feature.Summary":["feature.summary" + ], + "Ext.grid.header.Container":["widget.headercontainer" + ], + "Ext.grid.header.DragZone":[], + "Ext.grid.header.DropZone":[], + "Ext.grid.plugin.CellEditing":["plugin.cellediting" + ], + "Ext.grid.plugin.DragDrop":["plugin.gridviewdragdrop" + ], + "Ext.grid.plugin.Editing":["editing.editing" + ], + "Ext.grid.plugin.HeaderReorderer":["plugin.gridheaderreorderer" + ], + "Ext.grid.plugin.HeaderResizer":["plugin.gridheaderresizer" + ], + "Ext.grid.plugin.RowEditing":["plugin.rowediting" + ], + "Ext.grid.property.Grid":["widget.propertygrid" + ], + "Ext.grid.property.HeaderContainer":[], + "Ext.grid.property.Property":[], + "Ext.grid.property.Store":[], + "Ext.layout.component.Body":["layout.body" + ], + "Ext.layout.component.BoundList":["layout.boundlist" + ], + "Ext.layout.component.Button":["layout.button" + ], + "Ext.layout.component.Dock":["layout.dock" + ], + "Ext.layout.component.FieldSet":["layout.fieldset" + ], + "Ext.layout.component.ProgressBar":["layout.progressbar" + ], + "Ext.layout.component.Tab":["layout.tab" + ], + "Ext.layout.component.field.ComboBox":["layout.combobox" + ], + "Ext.layout.component.field.Field":["layout.field" + ], + "Ext.layout.component.field.FieldContainer":["layout.fieldcontainer" + ], + "Ext.layout.component.field.HtmlEditor":["layout.htmleditor" + ], + "Ext.layout.component.field.Slider":["layout.sliderfield" + ], + "Ext.layout.component.field.Text":["layout.textfield" + ], + "Ext.layout.component.field.TextArea":["layout.textareafield" + ], + "Ext.layout.component.field.Trigger":["layout.triggerfield" + ], + "Ext.layout.container.Absolute":["layout.absolute" + ], + "Ext.layout.container.Accordion":["layout.accordion" + ], + "Ext.layout.container.Anchor":["layout.anchor" + ], + "Ext.layout.container.Border":["layout.border" + ], + "Ext.layout.container.Box":["layout.box" + ], + "Ext.layout.container.Card":["layout.card" + ], + "Ext.layout.container.CheckboxGroup":["layout.checkboxgroup" + ], + "Ext.layout.container.Column":["layout.column" + ], + "Ext.layout.container.Container":[], + "Ext.layout.container.Editor":["layout.editor" + ], + "Ext.layout.container.Fit":["layout.fit" + ], + "Ext.layout.container.Form":["layout.form" + ], + "Ext.layout.container.HBox":["layout.hbox" + ], + "Ext.layout.container.Table":["layout.table" + ], + "Ext.layout.container.VBox":["layout.vbox" + ], + "Ext.layout.container.boxOverflow.Menu":[], + "Ext.layout.container.boxOverflow.None":[], + "Ext.layout.container.boxOverflow.Scroller":[], + "Ext.menu.CheckItem":["widget.menucheckitem" + ], + "Ext.menu.ColorPicker":["widget.colormenu" + ], + "Ext.menu.DatePicker":["widget.datemenu" + ], + "Ext.menu.Item":["widget.menuitem" + ], + "Ext.menu.KeyNav":[], + "Ext.menu.Manager":[], + "Ext.menu.Menu":["widget.menu" + ], + "Ext.menu.Separator":["widget.menuseparator" + ], + "Ext.panel.DD":[], + "Ext.panel.Header":["widget.header" + ], + "Ext.panel.Panel":["widget.panel" + ], + "Ext.panel.Proxy":[], + "Ext.panel.Table":["widget.tablepanel" + ], + "Ext.panel.Tool":["widget.tool" + ], + "Ext.picker.Color":["widget.colorpicker" + ], + "Ext.picker.Date":["widget.datepicker" + ], + "Ext.picker.Month":["widget.monthpicker" + ], + "Ext.picker.Time":["widget.timepicker" + ], + "Ext.resizer.BorderSplitter":["widget.bordersplitter" + ], + "Ext.resizer.BorderSplitterTracker":[], + "Ext.resizer.Handle":[], + "Ext.resizer.Resizer":[], + "Ext.resizer.ResizeTracker":[], + "Ext.resizer.Splitter":["widget.splitter" + ], + "Ext.resizer.SplitterTracker":[], + "Ext.selection.CellModel":["selection.cellmodel" + ], + "Ext.selection.CheckboxModel":["selection.checkboxmodel" + ], + "Ext.selection.RowModel":["selection.rowmodel" + ], + "Ext.selection.TreeModel":["selection.treemodel" + ], + "Ext.slider.Multi":["widget.multislider" + ], + "Ext.slider.Single":["widget.slider", + "widget.sliderfield" + ], + "Ext.slider.Thumb":[], + "Ext.slider.Tip":["widget.slidertip" + ], + "Ext.tab.Bar":["widget.tabbar" + ], + "Ext.tab.Panel":["widget.tabpanel" + ], + "Ext.tab.Tab":["widget.tab" + ], + "Ext.tip.QuickTip":["widget.quicktip" + ], + "Ext.tip.QuickTipManager":[], + "Ext.tip.Tip":[], + "Ext.tip.ToolTip":["widget.tooltip" + ], + "Ext.toolbar.Fill":["widget.tbfill" + ], + "Ext.toolbar.Item":["widget.tbitem" + ], + "Ext.toolbar.Paging":["widget.pagingtoolbar" + ], + "Ext.toolbar.Separator":["widget.tbseparator" + ], + "Ext.toolbar.Spacer":["widget.tbspacer" + ], + "Ext.toolbar.TextItem":["widget.tbtext" + ], + "Ext.toolbar.Toolbar":["widget.toolbar" + ], + "Ext.tree.Column":["widget.treecolumn" + ], + "Ext.tree.Panel":["widget.treepanel" + ], + "Ext.tree.View":["widget.treeview" + ], + "Ext.tree.ViewDragZone":[], + "Ext.tree.ViewDropZone":[], + "Ext.tree.plugin.TreeViewDragDrop":["plugin.treeviewdragdrop" + ], + "Ext.util.Animate":[], + "Ext.util.ClickRepeater":[], + "Ext.util.ComponentDragger":[], + "Ext.util.Cookies":[], + "Ext.util.CSS":[], + "Ext.util.Floating":[], + "Ext.util.History":[], + "Ext.util.KeyMap":[], + "Ext.util.KeyNav":[], + "Ext.util.TextMetrics":[], + "Ext.view.BoundList":["widget.boundlist" + ], + "Ext.view.BoundListKeyNav":[], + "Ext.view.DragZone":[], + "Ext.view.DropZone":[], + "Ext.view.Table":["widget.tableview" + ], + "Ext.view.TableChunker":[], + "Ext.view.View":["widget.dataview" + ], + "Ext.window.MessageBox":["widget.messagebox" + ], + "Ext.window.Window":["widget.window" + ] + }, + "alternateToNameMap":{ + "Ext.ComponentMgr":"Ext.ComponentManager", + "Ext.ModelMgr":"Ext.ModelManager", + "Ext.PluginMgr":"Ext.PluginManager", + "Ext.chart.Axis":"Ext.chart.axis.Axis", + "Ext.chart.CategoryAxis":"Ext.chart.axis.Category", + "Ext.chart.NumericAxis":"Ext.chart.axis.Numeric", + "Ext.chart.TimeAxis":"Ext.chart.axis.Time", + "Ext.chart.BarSeries":"Ext.chart.series.Bar", + "Ext.chart.BarChart":"Ext.chart.series.Bar", + "Ext.chart.StackedBarChart":"Ext.chart.series.Bar", + "Ext.chart.CartesianSeries":"Ext.chart.series.Cartesian", + "Ext.chart.CartesianChart":"Ext.chart.series.Cartesian", + "Ext.chart.ColumnSeries":"Ext.chart.series.Column", + "Ext.chart.ColumnChart":"Ext.chart.series.Column", + "Ext.chart.StackedColumnChart":"Ext.chart.series.Column", + "Ext.chart.LineSeries":"Ext.chart.series.Line", + "Ext.chart.LineChart":"Ext.chart.series.Line", + "Ext.chart.PieSeries":"Ext.chart.series.Pie", + "Ext.chart.PieChart":"Ext.chart.series.Pie", + "Ext.data.Record":"Ext.data.Model", + "Ext.StoreMgr":"Ext.data.StoreManager", + "Ext.data.StoreMgr":"Ext.data.StoreManager", + "Ext.StoreManager":"Ext.data.StoreManager", + "Ext.data.Association":"Ext.data.association.Association", + "Ext.data.BelongsToAssociation":"Ext.data.association.BelongsTo", + "Ext.data.HasManyAssociation":"Ext.data.association.HasMany", + "Ext.data.HasOneAssociation":"Ext.data.association.HasOne", + "Ext.data.HttpProxy":"Ext.data.proxy.Ajax", + "Ext.data.AjaxProxy":"Ext.data.proxy.Ajax", + "Ext.data.ClientProxy":"Ext.data.proxy.Client", + "Ext.data.DirectProxy":"Ext.data.proxy.Direct", + "Ext.data.ScriptTagProxy":"Ext.data.proxy.JsonP", + "Ext.data.LocalStorageProxy":"Ext.data.proxy.LocalStorage", + "Ext.data.MemoryProxy":"Ext.data.proxy.Memory", + "Ext.data.DataProxy":"Ext.data.proxy.Proxy", + "Ext.data.Proxy":"Ext.data.proxy.Proxy", + "Ext.data.RestProxy":"Ext.data.proxy.Rest", + "Ext.data.ServerProxy":"Ext.data.proxy.Server", + "Ext.data.SessionStorageProxy":"Ext.data.proxy.SessionStorage", + "Ext.data.WebStorageProxy":"Ext.data.proxy.WebStorage", + "Ext.data.ArrayReader":"Ext.data.reader.Array", + "Ext.data.JsonReader":"Ext.data.reader.Json", + "Ext.data.Reader":"Ext.data.reader.Reader", + "Ext.data.DataReader":"Ext.data.reader.Reader", + "Ext.data.XmlReader":"Ext.data.reader.Xml", + "Ext.data.JsonWriter":"Ext.data.writer.Json", + "Ext.data.DataWriter":"Ext.data.writer.Writer", + "Ext.data.Writer":"Ext.data.writer.Writer", + "Ext.data.XmlWriter":"Ext.data.writer.Xml", + "Ext.Direct.Transaction":"Ext.direct.Transaction", + "Ext.AbstractSelectionModel":"Ext.selection.Model", + "Ext.FocusMgr":"Ext.FocusManager", + "Ext.WindowGroup":"Ext.ZIndexManager", + "Ext.Button":"Ext.button.Button", + "Ext.CycleButton":"Ext.button.Cycle", + "Ext.SplitButton":"Ext.button.Split", + "Ext.ButtonGroup":"Ext.container.ButtonGroup", + "Ext.Container":"Ext.container.Container", + "Ext.Viewport":"Ext.container.Viewport", + "Ext.dd.DragDropMgr":"Ext.dd.DragDropManager", + "Ext.dd.DDM":"Ext.dd.DragDropManager", + "Ext.Element":"Ext.dom.Element", + "Ext.core.Element":"Ext.dom.Element", + "Ext.FlashComponent":"Ext.flash.Component", + "Ext.form.BasicForm":"Ext.form.Basic", + "Ext.FormPanel":"Ext.form.Panel", + "Ext.form.FormPanel":"Ext.form.Panel", + "Ext.form.Action":"Ext.form.action.Action", + "Ext.form.Action.DirectLoad":"Ext.form.action.DirectLoad", + "Ext.form.Action.DirectSubmit":"Ext.form.action.DirectSubmit", + "Ext.form.Action.Load":"Ext.form.action.Load", + "Ext.form.Action.Submit":"Ext.form.action.Submit", + "Ext.form.Field":"Ext.form.field.Base", + "Ext.form.BaseField":"Ext.form.field.Base", + "Ext.form.Checkbox":"Ext.form.field.Checkbox", + "Ext.form.ComboBox":"Ext.form.field.ComboBox", + "Ext.form.DateField":"Ext.form.field.Date", + "Ext.form.Date":"Ext.form.field.Date", + "Ext.form.DisplayField":"Ext.form.field.Display", + "Ext.form.Display":"Ext.form.field.Display", + "Ext.form.FileUploadField":"Ext.form.field.File", + "Ext.ux.form.FileUploadField":"Ext.form.field.File", + "Ext.form.File":"Ext.form.field.File", + "Ext.form.Hidden":"Ext.form.field.Hidden", + "Ext.form.HtmlEditor":"Ext.form.field.HtmlEditor", + "Ext.form.NumberField":"Ext.form.field.Number", + "Ext.form.Number":"Ext.form.field.Number", + "Ext.form.Picker":"Ext.form.field.Picker", + "Ext.form.Radio":"Ext.form.field.Radio", + "Ext.form.Spinner":"Ext.form.field.Spinner", + "Ext.form.TextField":"Ext.form.field.Text", + "Ext.form.Text":"Ext.form.field.Text", + "Ext.form.TextArea":"Ext.form.field.TextArea", + "Ext.form.TimeField":"Ext.form.field.Time", + "Ext.form.Time":"Ext.form.field.Time", + "Ext.form.TriggerField":"Ext.form.field.Trigger", + "Ext.form.TwinTriggerField":"Ext.form.field.Trigger", + "Ext.form.Trigger":"Ext.form.field.Trigger", + "Ext.list.ListView":"Ext.grid.Panel", + "Ext.ListView":"Ext.grid.Panel", + "Ext.grid.GridPanel":"Ext.grid.Panel", + "Ext.grid.ActionColumn":"Ext.grid.column.Action", + "Ext.grid.BooleanColumn":"Ext.grid.column.Boolean", + "Ext.grid.Column":"Ext.grid.column.Column", + "Ext.grid.DateColumn":"Ext.grid.column.Date", + "Ext.grid.NumberColumn":"Ext.grid.column.Number", + "Ext.grid.TemplateColumn":"Ext.grid.column.Template", + "Ext.grid.PropertyGrid":"Ext.grid.property.Grid", + "Ext.grid.PropertyColumnModel":"Ext.grid.property.HeaderContainer", + "Ext.PropGridProperty":"Ext.grid.property.Property", + "Ext.grid.PropertyStore":"Ext.grid.property.Store", + "Ext.layout.component.AbstractDock":"Ext.layout.component.Dock", + "Ext.layout.AbsoluteLayout":"Ext.layout.container.Absolute", + "Ext.layout.AccordionLayout":"Ext.layout.container.Accordion", + "Ext.layout.AnchorLayout":"Ext.layout.container.Anchor", + "Ext.layout.BorderLayout":"Ext.layout.container.Border", + "Ext.layout.BoxLayout":"Ext.layout.container.Box", + "Ext.layout.CardLayout":"Ext.layout.container.Card", + "Ext.layout.ColumnLayout":"Ext.layout.container.Column", + "Ext.layout.ContainerLayout":"Ext.layout.container.Container", + "Ext.layout.FitLayout":"Ext.layout.container.Fit", + "Ext.layout.FormLayout":"Ext.layout.container.Form", + "Ext.layout.HBoxLayout":"Ext.layout.container.HBox", + "Ext.layout.TableLayout":"Ext.layout.container.Table", + "Ext.layout.VBoxLayout":"Ext.layout.container.VBox", + "Ext.layout.boxOverflow.Menu":"Ext.layout.container.boxOverflow.Menu", + "Ext.layout.boxOverflow.None":"Ext.layout.container.boxOverflow.None", + "Ext.layout.boxOverflow.Scroller":"Ext.layout.container.boxOverflow.Scroller", + "Ext.menu.TextItem":"Ext.menu.Item", + "Ext.menu.MenuMgr":"Ext.menu.Manager", + "Ext.Panel":"Ext.panel.Panel", + "Ext.dd.PanelProxy":"Ext.panel.Proxy", + "Ext.ColorPalette":"Ext.picker.Color", + "Ext.DatePicker":"Ext.picker.Date", + "Ext.MonthPicker":"Ext.picker.Month", + "Ext.Resizable":"Ext.resizer.Resizer", + "Ext.slider.MultiSlider":"Ext.slider.Multi", + "Ext.Slider":"Ext.slider.Single", + "Ext.form.SliderField":"Ext.slider.Single", + "Ext.slider.SingleSlider":"Ext.slider.Single", + "Ext.slider.Slider":"Ext.slider.Single", + "Ext.TabPanel":"Ext.tab.Panel", + "Ext.QuickTip":"Ext.tip.QuickTip", + "Ext.Tip":"Ext.tip.Tip", + "Ext.ToolTip":"Ext.tip.ToolTip", + "Ext.Toolbar.Fill":"Ext.toolbar.Fill", + "Ext.Toolbar.Item":"Ext.toolbar.Item", + "Ext.PagingToolbar":"Ext.toolbar.Paging", + "Ext.Toolbar.Separator":"Ext.toolbar.Separator", + "Ext.Toolbar.Spacer":"Ext.toolbar.Spacer", + "Ext.Toolbar.TextItem":"Ext.toolbar.TextItem", + "Ext.Toolbar":"Ext.toolbar.Toolbar", + "Ext.tree.TreePanel":"Ext.tree.Panel", + "Ext.TreePanel":"Ext.tree.Panel", + "Ext.History":"Ext.util.History", + "Ext.KeyMap":"Ext.util.KeyMap", + "Ext.KeyNav":"Ext.util.KeyNav", + "Ext.BoundList":"Ext.view.BoundList", + "Ext.DataView":"Ext.view.View", + "Ext.Window":"Ext.window.Window" + } +}; + +(function() { + var scripts = document.getElementsByTagName('script'), + currentScript = scripts[scripts.length - 1], + src = currentScript.src, + path = src.substring(0, src.lastIndexOf('/') + 1), + Loader = Ext.Loader, + ClassManager = Ext.ClassManager, + data = this.ExtBootstrapData, + nameToAliasesMap = data.nameToAliasesMap, + alternateToNameMap = data.alternateToNameMap, + i, ln, name, aliases; + + if (nameToAliasesMap) { + for (name in nameToAliasesMap) { + if (nameToAliasesMap.hasOwnProperty(name)) { + aliases = nameToAliasesMap[name]; + + if (aliases.length > 0) { + for (i = 0,ln = aliases.length; i < ln; i++) { + ClassManager.setAlias(name, aliases[i]); + } + } + else { + ClassManager.setAlias(name, null); + } + } + } + } + + if (alternateToNameMap) { + Ext.merge(ClassManager.maps.alternateToName, alternateToNameMap); + } + + Loader.setConfig({ + enabled: true, + disableCaching: true, + paths: { + 'Ext': path + 'src' + } + }); + + try { + delete this.ExtBootstrapData; + } catch (e) { + this.ExtBootstrapData = null; + } +})(); + + + + +Ext._endTime = new Date().getTime(); +if (Ext._beforereadyhandler){ + Ext._beforereadyhandler(); +} diff --git a/test/testcase/ext-dev.js b/test/testcase/ext-dev.js new file mode 100644 index 0000000..53fd5bd --- /dev/null +++ b/test/testcase/ext-dev.js @@ -0,0 +1,26871 @@ +/* +This file is part of Ext JS 4.1 + +Copyright (c) 2011-2012 Sencha Inc + +Contact: http://www.sencha.com/contact + +GNU General Public License Usage +This file may be used under the terms of the GNU General Public License version 3.0 as +published by the Free Software Foundation and appearing in the file LICENSE included in the +packaging of this file. + +Please review the following information to ensure the GNU General Public License version 3.0 +requirements will be met: http://www.gnu.org/copyleft/gpl.html. + +If you are unsure which license is appropriate for your use, please contact the sales department +at http://www.sencha.com/contact. + +Build date: 2012-04-20 14:10:47 (19f55ab932145a3443b228045fa80950dfeaf9cc) +*/ +/** + * @class Ext + * @singleton + */ +var Ext = Ext || {}; +Ext._startTime = new Date().getTime(); +(function() { + var global = this, + objectPrototype = Object.prototype, + toString = objectPrototype.toString, + enumerables = true, + enumerablesTest = { toString: 1 }, + emptyFn = function () {}, + // This is the "$previous" method of a hook function on an instance. When called, it + // calls through the class prototype by the name of the called method. + callOverrideParent = function () { + var method = callOverrideParent.caller.caller; // skip callParent (our caller) + return method.$owner.prototype[method.$name].apply(this, arguments); + }, + i; + + Ext.global = global; + + for (i in enumerablesTest) { + enumerables = null; + } + + if (enumerables) { + enumerables = ['hasOwnProperty', 'valueOf', 'isPrototypeOf', 'propertyIsEnumerable', + 'toLocaleString', 'toString', 'constructor']; + } + + /** + * An array containing extra enumerables for old browsers + * @property {String[]} + */ + Ext.enumerables = enumerables; + + /** + * Copies all the properties of config to the specified object. + * Note that if recursive merging and cloning without referencing the original objects / arrays is needed, use + * {@link Ext.Object#merge} instead. + * @param {Object} object The receiver of the properties + * @param {Object} config The source of the properties + * @param {Object} [defaults] A different object that will also be applied for default values + * @return {Object} returns obj + */ + Ext.apply = function(object, config, defaults) { + if (defaults) { + Ext.apply(object, defaults); + } + + if (object && config && typeof config === 'object') { + var i, j, k; + + for (i in config) { + object[i] = config[i]; + } + + if (enumerables) { + for (j = enumerables.length; j--;) { + k = enumerables[j]; + if (config.hasOwnProperty(k)) { + object[k] = config[k]; + } + } + } + } + + return object; + }; + + Ext.buildSettings = Ext.apply({ + baseCSSPrefix: 'x-', + scopeResetCSS: false + }, Ext.buildSettings || {}); + + Ext.apply(Ext, { + + /** + * @property {String} [name='Ext'] + *

    The name of the property in the global namespace (The window in browser environments) which refers to the current instance of Ext.

    + *

    This is usually "Ext", but if a sandboxed build of ExtJS is being used, this will be an alternative name.

    + *

    If code is being generated for use by eval or to create a new Function, and the global instance + * of Ext must be referenced, this is the name that should be built into the code.

    + */ + name: Ext.sandboxName || 'Ext', + + /** + * A reusable empty function + */ + emptyFn: emptyFn, + + /** + * A zero length string which will pass a truth test. Useful for passing to methods + * which use a truth test to reject falsy values where a string value must be cleared. + */ + emptyString: new String(), + + baseCSSPrefix: Ext.buildSettings.baseCSSPrefix, + + /** + * Copies all the properties of config to object if they don't already exist. + * @param {Object} object The receiver of the properties + * @param {Object} config The source of the properties + * @return {Object} returns obj + */ + applyIf: function(object, config) { + var property; + + if (object) { + for (property in config) { + if (object[property] === undefined) { + object[property] = config[property]; + } + } + } + + return object; + }, + + /** + * Iterates either an array or an object. This method delegates to + * {@link Ext.Array#each Ext.Array.each} if the given value is iterable, and {@link Ext.Object#each Ext.Object.each} otherwise. + * + * @param {Object/Array} object The object or array to be iterated. + * @param {Function} fn The function to be called for each iteration. See and {@link Ext.Array#each Ext.Array.each} and + * {@link Ext.Object#each Ext.Object.each} for detailed lists of arguments passed to this function depending on the given object + * type that is being iterated. + * @param {Object} scope (Optional) The scope (`this` reference) in which the specified function is executed. + * Defaults to the object being iterated itself. + * @markdown + */ + iterate: function(object, fn, scope) { + if (Ext.isEmpty(object)) { + return; + } + + if (scope === undefined) { + scope = object; + } + + if (Ext.isIterable(object)) { + Ext.Array.each.call(Ext.Array, object, fn, scope); + } + else { + Ext.Object.each.call(Ext.Object, object, fn, scope); + } + } + }); + + Ext.apply(Ext, { + + /** + * This method deprecated. Use {@link Ext#define Ext.define} instead. + * @method + * @param {Function} superclass + * @param {Object} overrides + * @return {Function} The subclass constructor from the overrides parameter, or a generated one if not provided. + * @deprecated 4.0.0 Use {@link Ext#define Ext.define} instead + */ + extend: (function() { + // inline overrides + var objectConstructor = objectPrototype.constructor, + inlineOverrides = function(o) { + for (var m in o) { + if (!o.hasOwnProperty(m)) { + continue; + } + this[m] = o[m]; + } + }; + + return function(subclass, superclass, overrides) { + // First we check if the user passed in just the superClass with overrides + if (Ext.isObject(superclass)) { + overrides = superclass; + superclass = subclass; + subclass = overrides.constructor !== objectConstructor ? overrides.constructor : function() { + superclass.apply(this, arguments); + }; + } + + if (!superclass) { + Ext.Error.raise({ + sourceClass: 'Ext', + sourceMethod: 'extend', + msg: 'Attempting to extend from a class which has not been loaded on the page.' + }); + } + + // We create a new temporary class + var F = function() {}, + subclassProto, superclassProto = superclass.prototype; + + F.prototype = superclassProto; + subclassProto = subclass.prototype = new F(); + subclassProto.constructor = subclass; + subclass.superclass = superclassProto; + + if (superclassProto.constructor === objectConstructor) { + superclassProto.constructor = superclass; + } + + subclass.override = function(overrides) { + Ext.override(subclass, overrides); + }; + + subclassProto.override = inlineOverrides; + subclassProto.proto = subclassProto; + + subclass.override(overrides); + subclass.extend = function(o) { + return Ext.extend(subclass, o); + }; + + return subclass; + }; + }()), + + /** + * Overrides members of the specified `target` with the given values. + * + * If the `target` is a class declared using {@link Ext#define Ext.define}, the + * `override` method of that class is called (see {@link Ext.Base#override}) given + * the `overrides`. + * + * If the `target` is a function, it is assumed to be a constructor and the contents + * of `overrides` are applied to its `prototype` using {@link Ext#apply Ext.apply}. + * + * If the `target` is an instance of a class declared using {@link Ext#define Ext.define}, + * the `overrides` are applied to only that instance. In this case, methods are + * specially processed to allow them to use {@link Ext.Base#callParent}. + * + * var panel = new Ext.Panel({ ... }); + * + * Ext.override(panel, { + * initComponent: function () { + * // extra processing... + * + * this.callParent(); + * } + * }); + * + * If the `target` is none of these, the `overrides` are applied to the `target` + * using {@link Ext#apply Ext.apply}. + * + * Please refer to {@link Ext#define Ext.define} and {@link Ext.Base#override} for + * further details. + * + * @param {Object} target The target to override. + * @param {Object} overrides The properties to add or replace on `target`. + * @method override + */ + override: function (target, overrides) { + if (target.$isClass) { + target.override(overrides); + } else if (typeof target == 'function') { + Ext.apply(target.prototype, overrides); + } else { + var owner = target.self, + name, value; + + if (owner && owner.$isClass) { // if (instance of Ext.define'd class) + for (name in overrides) { + if (overrides.hasOwnProperty(name)) { + value = overrides[name]; + + if (typeof value == 'function') { + if (owner.$className) { + value.displayName = owner.$className + '#' + name; + } + + value.$name = name; + value.$owner = owner; + value.$previous = target.hasOwnProperty(name) + ? target[name] // already hooked, so call previous hook + : callOverrideParent; // calls by name on prototype + } + + target[name] = value; + } + } + } else { + Ext.apply(target, overrides); + } + } + + return target; + } + }); + + // A full set of static methods to do type checking + Ext.apply(Ext, { + + /** + * Returns the given value itself if it's not empty, as described in {@link Ext#isEmpty}; returns the default + * value (second argument) otherwise. + * + * @param {Object} value The value to test + * @param {Object} defaultValue The value to return if the original value is empty + * @param {Boolean} allowBlank (optional) true to allow zero length strings to qualify as non-empty (defaults to false) + * @return {Object} value, if non-empty, else defaultValue + */ + valueFrom: function(value, defaultValue, allowBlank){ + return Ext.isEmpty(value, allowBlank) ? defaultValue : value; + }, + + /** + * Returns the type of the given variable in string format. List of possible values are: + * + * - `undefined`: If the given value is `undefined` + * - `null`: If the given value is `null` + * - `string`: If the given value is a string + * - `number`: If the given value is a number + * - `boolean`: If the given value is a boolean value + * - `date`: If the given value is a `Date` object + * - `function`: If the given value is a function reference + * - `object`: If the given value is an object + * - `array`: If the given value is an array + * - `regexp`: If the given value is a regular expression + * - `element`: If the given value is a DOM Element + * - `textnode`: If the given value is a DOM text node and contains something other than whitespace + * - `whitespace`: If the given value is a DOM text node and contains only whitespace + * + * @param {Object} value + * @return {String} + * @markdown + */ + typeOf: function(value) { + var type, + typeToString; + + if (value === null) { + return 'null'; + } + + type = typeof value; + + if (type === 'undefined' || type === 'string' || type === 'number' || type === 'boolean') { + return type; + } + + typeToString = toString.call(value); + + switch(typeToString) { + case '[object Array]': + return 'array'; + case '[object Date]': + return 'date'; + case '[object Boolean]': + return 'boolean'; + case '[object Number]': + return 'number'; + case '[object RegExp]': + return 'regexp'; + } + + if (type === 'function') { + return 'function'; + } + + if (type === 'object') { + if (value.nodeType !== undefined) { + if (value.nodeType === 3) { + return (/\S/).test(value.nodeValue) ? 'textnode' : 'whitespace'; + } + else { + return 'element'; + } + } + + return 'object'; + } + + Ext.Error.raise({ + sourceClass: 'Ext', + sourceMethod: 'typeOf', + msg: 'Failed to determine the type of the specified value "' + value + '". This is most likely a bug.' + }); + }, + + /** + * Returns true if the passed value is empty, false otherwise. The value is deemed to be empty if it is either: + * + * - `null` + * - `undefined` + * - a zero-length array + * - a zero-length string (Unless the `allowEmptyString` parameter is set to `true`) + * + * @param {Object} value The value to test + * @param {Boolean} allowEmptyString (optional) true to allow empty strings (defaults to false) + * @return {Boolean} + * @markdown + */ + isEmpty: function(value, allowEmptyString) { + return (value === null) || (value === undefined) || (!allowEmptyString ? value === '' : false) || (Ext.isArray(value) && value.length === 0); + }, + + /** + * Returns true if the passed value is a JavaScript Array, false otherwise. + * + * @param {Object} target The target to test + * @return {Boolean} + * @method + */ + isArray: ('isArray' in Array) ? Array.isArray : function(value) { + return toString.call(value) === '[object Array]'; + }, + + /** + * Returns true if the passed value is a JavaScript Date object, false otherwise. + * @param {Object} object The object to test + * @return {Boolean} + */ + isDate: function(value) { + return toString.call(value) === '[object Date]'; + }, + + /** + * Returns true if the passed value is a JavaScript Object, false otherwise. + * @param {Object} value The value to test + * @return {Boolean} + * @method + */ + isObject: (toString.call(null) === '[object Object]') ? + function(value) { + // check ownerDocument here as well to exclude DOM nodes + return value !== null && value !== undefined && toString.call(value) === '[object Object]' && value.ownerDocument === undefined; + } : + function(value) { + return toString.call(value) === '[object Object]'; + }, + + /** + * @private + */ + isSimpleObject: function(value) { + return value instanceof Object && value.constructor === Object; + }, + /** + * Returns true if the passed value is a JavaScript 'primitive', a string, number or boolean. + * @param {Object} value The value to test + * @return {Boolean} + */ + isPrimitive: function(value) { + var type = typeof value; + + return type === 'string' || type === 'number' || type === 'boolean'; + }, + + /** + * Returns true if the passed value is a JavaScript Function, false otherwise. + * @param {Object} value The value to test + * @return {Boolean} + * @method + */ + isFunction: + // Safari 3.x and 4.x returns 'function' for typeof , hence we need to fall back to using + // Object.prototype.toString (slower) + (typeof document !== 'undefined' && typeof document.getElementsByTagName('body') === 'function') ? function(value) { + return toString.call(value) === '[object Function]'; + } : function(value) { + return typeof value === 'function'; + }, + + /** + * Returns true if the passed value is a number. Returns false for non-finite numbers. + * @param {Object} value The value to test + * @return {Boolean} + */ + isNumber: function(value) { + return typeof value === 'number' && isFinite(value); + }, + + /** + * Validates that a value is numeric. + * @param {Object} value Examples: 1, '1', '2.34' + * @return {Boolean} True if numeric, false otherwise + */ + isNumeric: function(value) { + return !isNaN(parseFloat(value)) && isFinite(value); + }, + + /** + * Returns true if the passed value is a string. + * @param {Object} value The value to test + * @return {Boolean} + */ + isString: function(value) { + return typeof value === 'string'; + }, + + /** + * Returns true if the passed value is a boolean. + * + * @param {Object} value The value to test + * @return {Boolean} + */ + isBoolean: function(value) { + return typeof value === 'boolean'; + }, + + /** + * Returns true if the passed value is an HTMLElement + * @param {Object} value The value to test + * @return {Boolean} + */ + isElement: function(value) { + return value ? value.nodeType === 1 : false; + }, + + /** + * Returns true if the passed value is a TextNode + * @param {Object} value The value to test + * @return {Boolean} + */ + isTextNode: function(value) { + return value ? value.nodeName === "#text" : false; + }, + + /** + * Returns true if the passed value is defined. + * @param {Object} value The value to test + * @return {Boolean} + */ + isDefined: function(value) { + return typeof value !== 'undefined'; + }, + + /** + * Returns true if the passed value is iterable, false otherwise + * @param {Object} value The value to test + * @return {Boolean} + */ + isIterable: function(value) { + var type = typeof value, + checkLength = false; + if (value && type != 'string') { + // Functions have a length property, so we need to filter them out + if (type == 'function') { + // In Safari, NodeList/HTMLCollection both return "function" when using typeof, so we need + // to explicitly check them here. + if (Ext.isSafari) { + checkLength = value instanceof NodeList || value instanceof HTMLCollection; + } + } else { + checkLength = true; + } + } + return checkLength ? value.length !== undefined : false; + } + }); + + Ext.apply(Ext, { + + /** + * Clone simple variables including array, {}-like objects, DOM nodes and Date without keeping the old reference. + * A reference for the object itself is returned if it's not a direct decendant of Object. For model cloning, + * see {@link Model#copy Model.copy}. + * + * @param {Object} item The variable to clone + * @return {Object} clone + */ + clone: function(item) { + var type, + i, + j, + k, + clone, + key; + + if (item === null || item === undefined) { + return item; + } + + // DOM nodes + // TODO proxy this to Ext.Element.clone to handle automatic id attribute changing + // recursively + if (item.nodeType && item.cloneNode) { + return item.cloneNode(true); + } + + type = toString.call(item); + + // Date + if (type === '[object Date]') { + return new Date(item.getTime()); + } + + + // Array + if (type === '[object Array]') { + i = item.length; + + clone = []; + + while (i--) { + clone[i] = Ext.clone(item[i]); + } + } + // Object + else if (type === '[object Object]' && item.constructor === Object) { + clone = {}; + + for (key in item) { + clone[key] = Ext.clone(item[key]); + } + + if (enumerables) { + for (j = enumerables.length; j--;) { + k = enumerables[j]; + clone[k] = item[k]; + } + } + } + + return clone || item; + }, + + /** + * @private + * Generate a unique reference of Ext in the global scope, useful for sandboxing + */ + getUniqueGlobalNamespace: function() { + var uniqueGlobalNamespace = this.uniqueGlobalNamespace, + i; + + if (uniqueGlobalNamespace === undefined) { + i = 0; + + do { + uniqueGlobalNamespace = 'ExtBox' + (++i); + } while (Ext.global[uniqueGlobalNamespace] !== undefined); + + Ext.global[uniqueGlobalNamespace] = Ext; + this.uniqueGlobalNamespace = uniqueGlobalNamespace; + } + + return uniqueGlobalNamespace; + }, + + /** + * @private + */ + functionFactoryCache: {}, + + cacheableFunctionFactory: function() { + var me = this, + args = Array.prototype.slice.call(arguments), + cache = me.functionFactoryCache, + idx, fn, ln; + + if (Ext.isSandboxed) { + ln = args.length; + if (ln > 0) { + ln--; + args[ln] = 'var Ext=window.' + Ext.name + ';' + args[ln]; + } + } + idx = args.join(''); + fn = cache[idx]; + if (!fn) { + fn = Function.prototype.constructor.apply(Function.prototype, args); + + cache[idx] = fn; + } + return fn; + }, + + functionFactory: function() { + var me = this, + args = Array.prototype.slice.call(arguments), + ln; + + if (Ext.isSandboxed) { + ln = args.length; + if (ln > 0) { + ln--; + args[ln] = 'var Ext=window.' + Ext.name + ';' + args[ln]; + } + } + + return Function.prototype.constructor.apply(Function.prototype, args); + }, + + /** + * @private + * @property + */ + Logger: { + verbose: emptyFn, + log: emptyFn, + info: emptyFn, + warn: emptyFn, + error: function(message) { + throw new Error(message); + }, + deprecate: emptyFn + } + }); + + /** + * Old alias to {@link Ext#typeOf} + * @deprecated 4.0.0 Use {@link Ext#typeOf} instead + * @method + * @inheritdoc Ext#typeOf + */ + Ext.type = Ext.typeOf; + +}()); + +/* + * This method evaluates the given code free of any local variable. In some browsers this + * will be at global scope, in others it will be in a function. + * @parma {String} code The code to evaluate. + * @private + * @method + */ +Ext.globalEval = Ext.global.execScript + ? function(code) { + execScript(code); + } + : function($$code) { + // IMPORTANT: because we use eval we cannot place this in the above function or it + // will break the compressor's ability to rename local variables... + (function(){ + eval($$code); + }()); + }; + +/** + * @author Jacky Nguyen + * @docauthor Jacky Nguyen + * @class Ext.Version + * + * A utility class that wrap around a string version number and provide convenient + * method to perform comparison. See also: {@link Ext.Version#compare compare}. Example: + + var version = new Ext.Version('1.0.2beta'); + console.log("Version is " + version); // Version is 1.0.2beta + + console.log(version.getMajor()); // 1 + console.log(version.getMinor()); // 0 + console.log(version.getPatch()); // 2 + console.log(version.getBuild()); // 0 + console.log(version.getRelease()); // beta + + console.log(version.isGreaterThan('1.0.1')); // True + console.log(version.isGreaterThan('1.0.2alpha')); // True + console.log(version.isGreaterThan('1.0.2RC')); // False + console.log(version.isGreaterThan('1.0.2')); // False + console.log(version.isLessThan('1.0.2')); // True + + console.log(version.match(1.0)); // True + console.log(version.match('1.0.2')); // True + + * @markdown + */ +(function() { + +// Current core version +var version = '4.1.0', Version; + Ext.Version = Version = Ext.extend(Object, { + + /** + * @param {String/Number} version The version number in the follow standard format: major[.minor[.patch[.build[release]]]] + * Examples: 1.0 or 1.2.3beta or 1.2.3.4RC + * @return {Ext.Version} this + */ + constructor: function(version) { + var parts, releaseStartIndex; + + if (version instanceof Version) { + return version; + } + + this.version = this.shortVersion = String(version).toLowerCase().replace(/_/g, '.').replace(/[\-+]/g, ''); + + releaseStartIndex = this.version.search(/([^\d\.])/); + + if (releaseStartIndex !== -1) { + this.release = this.version.substr(releaseStartIndex, version.length); + this.shortVersion = this.version.substr(0, releaseStartIndex); + } + + this.shortVersion = this.shortVersion.replace(/[^\d]/g, ''); + + parts = this.version.split('.'); + + this.major = parseInt(parts.shift() || 0, 10); + this.minor = parseInt(parts.shift() || 0, 10); + this.patch = parseInt(parts.shift() || 0, 10); + this.build = parseInt(parts.shift() || 0, 10); + + return this; + }, + + /** + * Override the native toString method + * @private + * @return {String} version + */ + toString: function() { + return this.version; + }, + + /** + * Override the native valueOf method + * @private + * @return {String} version + */ + valueOf: function() { + return this.version; + }, + + /** + * Returns the major component value + * @return {Number} major + */ + getMajor: function() { + return this.major || 0; + }, + + /** + * Returns the minor component value + * @return {Number} minor + */ + getMinor: function() { + return this.minor || 0; + }, + + /** + * Returns the patch component value + * @return {Number} patch + */ + getPatch: function() { + return this.patch || 0; + }, + + /** + * Returns the build component value + * @return {Number} build + */ + getBuild: function() { + return this.build || 0; + }, + + /** + * Returns the release component value + * @return {Number} release + */ + getRelease: function() { + return this.release || ''; + }, + + /** + * Returns whether this version if greater than the supplied argument + * @param {String/Number} target The version to compare with + * @return {Boolean} True if this version if greater than the target, false otherwise + */ + isGreaterThan: function(target) { + return Version.compare(this.version, target) === 1; + }, + + /** + * Returns whether this version if greater than or equal to the supplied argument + * @param {String/Number} target The version to compare with + * @return {Boolean} True if this version if greater than or equal to the target, false otherwise + */ + isGreaterThanOrEqual: function(target) { + return Version.compare(this.version, target) >= 0; + }, + + /** + * Returns whether this version if smaller than the supplied argument + * @param {String/Number} target The version to compare with + * @return {Boolean} True if this version if smaller than the target, false otherwise + */ + isLessThan: function(target) { + return Version.compare(this.version, target) === -1; + }, + + /** + * Returns whether this version if less than or equal to the supplied argument + * @param {String/Number} target The version to compare with + * @return {Boolean} True if this version if less than or equal to the target, false otherwise + */ + isLessThanOrEqual: function(target) { + return Version.compare(this.version, target) <= 0; + }, + + /** + * Returns whether this version equals to the supplied argument + * @param {String/Number} target The version to compare with + * @return {Boolean} True if this version equals to the target, false otherwise + */ + equals: function(target) { + return Version.compare(this.version, target) === 0; + }, + + /** + * Returns whether this version matches the supplied argument. Example: + *
    
    +         * var version = new Ext.Version('1.0.2beta');
    +         * console.log(version.match(1)); // True
    +         * console.log(version.match(1.0)); // True
    +         * console.log(version.match('1.0.2')); // True
    +         * console.log(version.match('1.0.2RC')); // False
    +         * 
    + * @param {String/Number} target The version to compare with + * @return {Boolean} True if this version matches the target, false otherwise + */ + match: function(target) { + target = String(target); + return this.version.substr(0, target.length) === target; + }, + + /** + * Returns this format: [major, minor, patch, build, release]. Useful for comparison + * @return {Number[]} + */ + toArray: function() { + return [this.getMajor(), this.getMinor(), this.getPatch(), this.getBuild(), this.getRelease()]; + }, + + /** + * Returns shortVersion version without dots and release + * @return {String} + */ + getShortVersion: function() { + return this.shortVersion; + }, + + /** + * Convenient alias to {@link Ext.Version#isGreaterThan isGreaterThan} + * @param {String/Number} target + * @return {Boolean} + */ + gt: function() { + return this.isGreaterThan.apply(this, arguments); + }, + + /** + * Convenient alias to {@link Ext.Version#isLessThan isLessThan} + * @param {String/Number} target + * @return {Boolean} + */ + lt: function() { + return this.isLessThan.apply(this, arguments); + }, + + /** + * Convenient alias to {@link Ext.Version#isGreaterThanOrEqual isGreaterThanOrEqual} + * @param {String/Number} target + * @return {Boolean} + */ + gtEq: function() { + return this.isGreaterThanOrEqual.apply(this, arguments); + }, + + /** + * Convenient alias to {@link Ext.Version#isLessThanOrEqual isLessThanOrEqual} + * @param {String/Number} target + * @return {Boolean} + */ + ltEq: function() { + return this.isLessThanOrEqual.apply(this, arguments); + } + }); + + Ext.apply(Version, { + // @private + releaseValueMap: { + 'dev': -6, + 'alpha': -5, + 'a': -5, + 'beta': -4, + 'b': -4, + 'rc': -3, + '#': -2, + 'p': -1, + 'pl': -1 + }, + + /** + * Converts a version component to a comparable value + * + * @static + * @param {Object} value The value to convert + * @return {Object} + */ + getComponentValue: function(value) { + return !value ? 0 : (isNaN(value) ? this.releaseValueMap[value] || value : parseInt(value, 10)); + }, + + /** + * Compare 2 specified versions, starting from left to right. If a part contains special version strings, + * they are handled in the following order: + * 'dev' < 'alpha' = 'a' < 'beta' = 'b' < 'RC' = 'rc' < '#' < 'pl' = 'p' < 'anything else' + * + * @static + * @param {String} current The current version to compare to + * @param {String} target The target version to compare to + * @return {Number} Returns -1 if the current version is smaller than the target version, 1 if greater, and 0 if they're equivalent + */ + compare: function(current, target) { + var currentValue, targetValue, i; + + current = new Version(current).toArray(); + target = new Version(target).toArray(); + + for (i = 0; i < Math.max(current.length, target.length); i++) { + currentValue = this.getComponentValue(current[i]); + targetValue = this.getComponentValue(target[i]); + + if (currentValue < targetValue) { + return -1; + } else if (currentValue > targetValue) { + return 1; + } + } + + return 0; + } + }); + + Ext.apply(Ext, { + /** + * @private + */ + versions: {}, + + /** + * @private + */ + lastRegisteredVersion: null, + + /** + * Set version number for the given package name. + * + * @param {String} packageName The package name, for example: 'core', 'touch', 'extjs' + * @param {String/Ext.Version} version The version, for example: '1.2.3alpha', '2.4.0-dev' + * @return {Ext} + */ + setVersion: function(packageName, version) { + Ext.versions[packageName] = new Version(version); + Ext.lastRegisteredVersion = Ext.versions[packageName]; + + return this; + }, + + /** + * Get the version number of the supplied package name; will return the last registered version + * (last Ext.setVersion call) if there's no package name given. + * + * @param {String} packageName (Optional) The package name, for example: 'core', 'touch', 'extjs' + * @return {Ext.Version} The version + */ + getVersion: function(packageName) { + if (packageName === undefined) { + return Ext.lastRegisteredVersion; + } + + return Ext.versions[packageName]; + }, + + /** + * Create a closure for deprecated code. + * + // This means Ext.oldMethod is only supported in 4.0.0beta and older. + // If Ext.getVersion('extjs') returns a version that is later than '4.0.0beta', for example '4.0.0RC', + // the closure will not be invoked + Ext.deprecate('extjs', '4.0.0beta', function() { + Ext.oldMethod = Ext.newMethod; + + ... + }); + + * @param {String} packageName The package name + * @param {String} since The last version before it's deprecated + * @param {Function} closure The callback function to be executed with the specified version is less than the current version + * @param {Object} scope The execution scope (this) if the closure + * @markdown + */ + deprecate: function(packageName, since, closure, scope) { + if (Version.compare(Ext.getVersion(packageName), since) < 1) { + closure.call(scope); + } + } + }); // End Versioning + + Ext.setVersion('core', version); + +}()); + +/** + * @class Ext.String + * + * A collection of useful static methods to deal with strings + * @singleton + */ + +Ext.String = (function() { + var trimRegex = /^[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+|[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+$/g, + escapeRe = /('|\\)/g, + formatRe = /\{(\d+)\}/g, + escapeRegexRe = /([-.*+?\^${}()|\[\]\/\\])/g, + basicTrimRe = /^\s+|\s+$/g, + whitespaceRe = /\s+/, + varReplace = /(^[^a-z]*|[^\w])/gi, + charToEntity, + entityToChar, + charToEntityRegex, + entityToCharRegex, + htmlEncodeReplaceFn = function(match, capture) { + return charToEntity[capture]; + }, + htmlDecodeReplaceFn = function(match, capture) { + return (capture in entityToChar) ? entityToChar[capture] : String.fromCharCode(parseInt(capture.substr(2), 10)); + }; + + return { + + /** + * Converts a string of characters into a legal, parseable Javascript `var` name as long as the passed + * string contains at least one alphabetic character. Non alphanumeric characters, and *leading* non alphabetic + * characters will be removed. + * @param {String} s A string to be converted into a `var` name. + * @return {String} A legal Javascript `var` name. + */ + createVarName: function(s) { + return s.replace(varReplace, ''); + }, + + /** + * 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 + * @method + */ + htmlEncode: function(value) { + return (!value) ? value : String(value).replace(charToEntityRegex, htmlEncodeReplaceFn); + }, + + /** + * Convert certain characters (&, <, >, ', and ") from their HTML character equivalents. + * @param {String} value The string to decode + * @return {String} The decoded text + * @method + */ + htmlDecode: function(value) { + return (!value) ? value : String(value).replace(entityToCharRegex, htmlDecodeReplaceFn); + }, + + /** + * Adds a set of character entity definitions to the set used by + * {@link Ext.String#htmlEncode} and {@link Ext.String#htmlDecode}. + * + * This object should be keyed by the entity name sequence, + * with the value being the textual representation of the entity. + * + * Ext.String.addCharacterEntities({ + * '&Uuml;':'Ü', + * '&ccedil;':'ç', + * '&ntilde;':'ñ', + * '&egrave;':'è' + * }); + * var s = Ext.String.htmlEncode("A string with entities: èÜçñ"); + * + * Note: the values of the character entites defined on this object are expected + * to be single character values. As such, the actual values represented by the + * characters are sensitive to the character encoding of the javascript source + * file when defined in string literal form. Script tasgs referencing server + * resources with character entities must ensure that the 'charset' attribute + * of the script node is consistent with the actual character encoding of the + * server resource. + * + * The set of character entities may be reset back to the default state by using + * the {@link Ext.String#resetCharacterEntities} method + * + * @param {Object} entities The set of character entities to add to the current + * definitions. + */ + addCharacterEntities: function(newEntities) { + var charKeys = [], + entityKeys = [], + key, echar; + for (key in newEntities) { + echar = newEntities[key]; + entityToChar[key] = echar; + charToEntity[echar] = key; + charKeys.push(echar); + entityKeys.push(key); + } + charToEntityRegex = new RegExp('(' + charKeys.join('|') + ')', 'g'); + entityToCharRegex = new RegExp('(' + entityKeys.join('|') + '|&#[0-9]{1,5};' + ')', 'g'); + }, + + /** + * Resets the set of character entity definitions used by + * {@link Ext.String#htmlEncode} and {@link Ext.String#htmlDecode} back to the + * default state. + */ + resetCharacterEntities: function() { + charToEntity = {}; + entityToChar = {}; + // add the default set + this.addCharacterEntities({ + '&' : '&', + '>' : '>', + '<' : '<', + '"' : '"', + ''' : "'" + }); + }, + + /** + * Appends content to the query string of a URL, handling logic for whether to place + * a question mark or ampersand. + * @param {String} url The URL to append to. + * @param {String} string The content to append to the URL. + * @return {String} The resulting URL + */ + urlAppend : function(url, string) { + if (!Ext.isEmpty(string)) { + return url + (url.indexOf('?') === -1 ? '?' : '&') + string; + } + + return url; + }, + + /** + * Trims whitespace from either end of a string, leaving spaces within the string intact. Example: + * @example + var s = ' foo bar '; + alert('-' + s + '-'); //alerts "- foo bar -" + alert('-' + Ext.String.trim(s) + '-'); //alerts "-foo bar-" + + * @param {String} string The string to escape + * @return {String} The trimmed string + */ + trim: function(string) { + return string.replace(trimRegex, ""); + }, + + /** + * Capitalize the given string + * @param {String} string + * @return {String} + */ + capitalize: function(string) { + return string.charAt(0).toUpperCase() + string.substr(1); + }, + + /** + * Uncapitalize the given string + * @param {String} string + * @return {String} + */ + uncapitalize: function(string) { + return string.charAt(0).toLowerCase() + string.substr(1); + }, + + /** + * 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 word break + * @return {String} The converted text + */ + ellipsis: function(value, len, word) { + if (value && value.length > len) { + if (word) { + var vs = value.substr(0, len - 2), + index = Math.max(vs.lastIndexOf(' '), vs.lastIndexOf('.'), vs.lastIndexOf('!'), vs.lastIndexOf('?')); + if (index !== -1 && index >= (len - 15)) { + return vs.substr(0, index) + "..."; + } + } + return value.substr(0, len - 3) + "..."; + } + return value; + }, + + /** + * Escapes the passed string for use in a regular expression + * @param {String} string + * @return {String} + */ + escapeRegex: function(string) { + return string.replace(escapeRegexRe, "\\$1"); + }, + + /** + * Escapes the passed string for ' and \ + * @param {String} string The string to escape + * @return {String} The escaped string + */ + escape: function(string) { + return string.replace(escapeRe, "\\$1"); + }, + + /** + * Utility function that allows you to easily switch a string between two alternating values. The passed value + * is compared to the current string, and if they are equal, the other value that was passed in is returned. If + * they are already different, the first value passed in is returned. Note that this method returns the new value + * but does not change the current string. + *
    
    +        // alternate sort directions
    +        sort = Ext.String.toggle(sort, 'ASC', 'DESC');
    +
    +        // instead of conditional logic:
    +        sort = (sort == 'ASC' ? 'DESC' : 'ASC');
    +           
    + * @param {String} string The current string + * @param {String} value The value to compare to the current string + * @param {String} other The new value to use if the string already equals the first value passed in + * @return {String} The new value + */ + toggle: function(string, value, other) { + return string === value ? other : value; + }, + + /** + * Pads the left side of a string with a specified character. This is especially useful + * for normalizing number and date strings. Example usage: + * + *
    
    +    var s = Ext.String.leftPad('123', 5, '0');
    +    // s now contains the string: '00123'
    +           
    + * @param {String} string The original string + * @param {Number} size The total length of the output string + * @param {String} character (optional) The character with which to pad the original string (defaults to empty string " ") + * @return {String} The padded string + */ + leftPad: function(string, size, character) { + var result = String(string); + character = character || " "; + while (result.length < size) { + result = character + result; + } + return result; + }, + + /** + * Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens. Each + * token must be unique, and must increment in the format {0}, {1}, etc. Example usage: + *
    
    +    var cls = 'my-class', text = 'Some text';
    +    var s = Ext.String.format('<div class="{0}">{1}</div>', cls, text);
    +    // s now contains the string: '<div class="my-class">Some text</div>'
    +           
    + * @param {String} string The tokenized string to be formatted + * @param {String} value1 The value to replace token {0} + * @param {String} value2 Etc... + * @return {String} The formatted string + */ + format: function(format) { + var args = Ext.Array.toArray(arguments, 1); + return format.replace(formatRe, function(m, i) { + return args[i]; + }); + }, + + /** + * Returns a string with a specified number of repititions a given string pattern. + * The pattern be separated by a different string. + * + * var s = Ext.String.repeat('---', 4); // = '------------' + * var t = Ext.String.repeat('--', 3, '/'); // = '--/--/--' + * + * @param {String} pattern The pattern to repeat. + * @param {Number} count The number of times to repeat the pattern (may be 0). + * @param {String} sep An option string to separate each pattern. + */ + repeat: function(pattern, count, sep) { + for (var buf = [], i = count; i--; ) { + buf.push(pattern); + } + return buf.join(sep || ''); + }, + + /** + * Splits a string of space separated words into an array, trimming as needed. If the + * words are already an array, it is returned. + * + * @param {String/Array} words + */ + splitWords: function (words) { + if (words && typeof words == 'string') { + return words.replace(basicTrimRe, '').split(whitespaceRe); + } + return words || []; + } + }; +}()); + +// initialize the default encode / decode entities +Ext.String.resetCharacterEntities(); + +/** + * Old alias to {@link Ext.String#htmlEncode} + * @deprecated Use {@link Ext.String#htmlEncode} instead + * @method + * @member Ext + * @inheritdoc Ext.String#htmlEncode + */ +Ext.htmlEncode = Ext.String.htmlEncode; + + +/** + * Old alias to {@link Ext.String#htmlDecode} + * @deprecated Use {@link Ext.String#htmlDecode} instead + * @method + * @member Ext + * @inheritdoc Ext.String#htmlDecode + */ +Ext.htmlDecode = Ext.String.htmlDecode; + +/** + * Old alias to {@link Ext.String#urlAppend} + * @deprecated Use {@link Ext.String#urlAppend} instead + * @method + * @member Ext + * @inheritdoc Ext.String#urlAppend + */ +Ext.urlAppend = Ext.String.urlAppend; +/** + * @class Ext.Number + * + * A collection of useful static methods to deal with numbers + * @singleton + */ + +Ext.Number = new function() { + + var me = this, + isToFixedBroken = (0.9).toFixed() !== '1', + math = Math; + + Ext.apply(this, { + /** + * Checks whether or not the passed number is within a desired range. If the number is already within the + * range it is returned, otherwise the min or max value is returned depending on which side of the range is + * exceeded. Note that this method returns the constrained value but does not change the current number. + * @param {Number} number The number to check + * @param {Number} min The minimum number in the range + * @param {Number} max The maximum number in the range + * @return {Number} The constrained value if outside the range, otherwise the current value + */ + constrain: function(number, min, max) { + var x = parseFloat(number); + + // Watch out for NaN in Chrome 18 + // V8bug: http://code.google.com/p/v8/issues/detail?id=2056 + + // Operators are faster than Math.min/max. See http://jsperf.com/number-constrain + // ... and (x < Nan) || (x < undefined) == false + // ... same for (x > NaN) || (x > undefined) + // so if min or max are undefined or NaN, we never return them... sadly, this + // is not true of null (but even Math.max(-1,null)==0 and isNaN(null)==false) + return (x < min) ? min : ((x > max) ? max : x); + }, + + /** + * Snaps the passed number between stopping points based upon a passed increment value. + * + * The difference between this and {@link #snapInRange} is that {@link #snapInRange} uses the minValue + * when calculating snap points: + * + * r = Ext.Number.snap(56, 2, 55, 65); // Returns 56 - snap points are zero based + * + * r = Ext.Number.snapInRange(56, 2, 55, 65); // Returns 57 - snap points are based from minValue + * + * @param {Number} value The unsnapped value. + * @param {Number} increment The increment by which the value must move. + * @param {Number} minValue The minimum value to which the returned value must be constrained. Overrides the increment. + * @param {Number} maxValue The maximum value to which the returned value must be constrained. Overrides the increment. + * @return {Number} The value of the nearest snap target. + */ + snap : function(value, increment, minValue, maxValue) { + var m; + + // If no value passed, or minValue was passed and value is less than minValue (anything < undefined is false) + // Then use the minValue (or zero if the value was undefined) + if (value === undefined || value < minValue) { + return minValue || 0; + } + + if (increment) { + m = value % increment; + if (m !== 0) { + value -= m; + if (m * 2 >= increment) { + value += increment; + } else if (m * 2 < -increment) { + value -= increment; + } + } + } + return me.constrain(value, minValue, maxValue); + }, + + /** + * Snaps the passed number between stopping points based upon a passed increment value. + * + * The difference between this and {@link #snap} is that {@link #snap} does not use the minValue + * when calculating snap points: + * + * r = Ext.Number.snap(56, 2, 55, 65); // Returns 56 - snap points are zero based + * + * r = Ext.Number.snapInRange(56, 2, 55, 65); // Returns 57 - snap points are based from minValue + * + * @param {Number} value The unsnapped value. + * @param {Number} increment The increment by which the value must move. + * @param {Number} [minValue=0] The minimum value to which the returned value must be constrained. + * @param {Number} [maxValue=Infinity] The maximum value to which the returned value must be constrained. + * @return {Number} The value of the nearest snap target. + */ + snapInRange : function(value, increment, minValue, maxValue) { + var tween; + + // default minValue to zero + minValue = (minValue || 0); + + // If value is undefined, or less than minValue, use minValue + if (value === undefined || value < minValue) { + return minValue; + } + + // Calculate how many snap points from the minValue the passed value is. + if (increment && (tween = ((value - minValue) % increment))) { + value -= tween; + tween *= 2; + if (tween >= increment) { + value += increment; + } + } + + // If constraining within a maximum, ensure the maximum is on a snap point + if (maxValue !== undefined) { + if (value > (maxValue = me.snapInRange(maxValue, increment, minValue))) { + value = maxValue; + } + } + + return value; + }, + + /** + * Formats a number using fixed-point notation + * @param {Number} value The number to format + * @param {Number} precision The number of digits to show after the decimal point + */ + toFixed: isToFixedBroken ? function(value, precision) { + precision = precision || 0; + var pow = math.pow(10, precision); + return (math.round(value * pow) / pow).toFixed(precision); + } : function(value, precision) { + return value.toFixed(precision); + }, + + /** + * Validate that a value is numeric and convert it to a number if necessary. Returns the specified default value if + * it is not. + + Ext.Number.from('1.23', 1); // returns 1.23 + Ext.Number.from('abc', 1); // returns 1 + + * @param {Object} value + * @param {Number} defaultValue The value to return if the original value is non-numeric + * @return {Number} value, if numeric, defaultValue otherwise + */ + from: function(value, defaultValue) { + if (isFinite(value)) { + value = parseFloat(value); + } + + return !isNaN(value) ? value : defaultValue; + }, + + /** + * Returns a random integer between the specified range (inclusive) + * @param {Number} from Lowest value to return. + * @param {Number} to Highst value to return. + * @return {Number} A random integer within the specified range. + */ + randomInt: function (from, to) { + return math.floor(math.random() * (to - from + 1) + from); + } + }); + + /** + * @deprecated 4.0.0 Please use {@link Ext.Number#from} instead. + * @member Ext + * @method num + * @inheritdoc Ext.Number#from + */ + Ext.num = function() { + return me.from.apply(this, arguments); + }; +}; +/** + * @class Ext.Array + * @singleton + * @author Jacky Nguyen + * @docauthor Jacky Nguyen + * + * A set of useful static methods to deal with arrays; provide missing methods for older browsers. + */ +(function() { + + var arrayPrototype = Array.prototype, + slice = arrayPrototype.slice, + supportsSplice = (function () { + var array = [], + lengthBefore, + j = 20; + + if (!array.splice) { + return false; + } + + // This detects a bug in IE8 splice method: + // see http://social.msdn.microsoft.com/Forums/en-US/iewebdevelopment/thread/6e946d03-e09f-4b22-a4dd-cd5e276bf05a/ + + while (j--) { + array.push("A"); + } + + array.splice(15, 0, "F", "F", "F", "F", "F","F","F","F","F","F","F","F","F","F","F","F","F","F","F","F","F"); + + lengthBefore = array.length; //41 + array.splice(13, 0, "XXX"); // add one element + + if (lengthBefore+1 != array.length) { + return false; + } + // end IE8 bug + + return true; + }()), + supportsForEach = 'forEach' in arrayPrototype, + supportsMap = 'map' in arrayPrototype, + supportsIndexOf = 'indexOf' in arrayPrototype, + supportsEvery = 'every' in arrayPrototype, + supportsSome = 'some' in arrayPrototype, + supportsFilter = 'filter' in arrayPrototype, + supportsSort = (function() { + var a = [1,2,3,4,5].sort(function(){ return 0; }); + return a[0] === 1 && a[1] === 2 && a[2] === 3 && a[3] === 4 && a[4] === 5; + }()), + supportsSliceOnNodeList = true, + ExtArray, + erase, + replace, + splice; + + try { + // IE 6 - 8 will throw an error when using Array.prototype.slice on NodeList + if (typeof document !== 'undefined') { + slice.call(document.getElementsByTagName('body')); + } + } catch (e) { + supportsSliceOnNodeList = false; + } + + function fixArrayIndex (array, index) { + return (index < 0) ? Math.max(0, array.length + index) + : Math.min(array.length, index); + } + + /* + Does the same work as splice, but with a slightly more convenient signature. The splice + method has bugs in IE8, so this is the implementation we use on that platform. + + The rippling of items in the array can be tricky. Consider two use cases: + + index=2 + removeCount=2 + /=====\ + +---+---+---+---+---+---+---+---+ + | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | + +---+---+---+---+---+---+---+---+ + / \/ \/ \/ \ + / /\ /\ /\ \ + / / \/ \/ \ +--------------------------+ + / / /\ /\ +--------------------------+ \ + / / / \/ +--------------------------+ \ \ + / / / /+--------------------------+ \ \ \ + / / / / \ \ \ \ + v v v v v v v v + +---+---+---+---+---+---+ +---+---+---+---+---+---+---+---+---+ + | 0 | 1 | 4 | 5 | 6 | 7 | | 0 | 1 | a | b | c | 4 | 5 | 6 | 7 | + +---+---+---+---+---+---+ +---+---+---+---+---+---+---+---+---+ + A B \=========/ + insert=[a,b,c] + + In case A, it is obvious that copying of [4,5,6,7] must be left-to-right so + that we don't end up with [0,1,6,7,6,7]. In case B, we have the opposite; we + must go right-to-left or else we would end up with [0,1,a,b,c,4,4,4,4]. + */ + function replaceSim (array, index, removeCount, insert) { + var add = insert ? insert.length : 0, + length = array.length, + pos = fixArrayIndex(array, index), + remove, + tailOldPos, + tailNewPos, + tailCount, + lengthAfterRemove, + i; + + // we try to use Array.push when we can for efficiency... + if (pos === length) { + if (add) { + array.push.apply(array, insert); + } + } else { + remove = Math.min(removeCount, length - pos); + tailOldPos = pos + remove; + tailNewPos = tailOldPos + add - remove; + tailCount = length - tailOldPos; + lengthAfterRemove = length - remove; + + if (tailNewPos < tailOldPos) { // case A + for (i = 0; i < tailCount; ++i) { + array[tailNewPos+i] = array[tailOldPos+i]; + } + } else if (tailNewPos > tailOldPos) { // case B + for (i = tailCount; i--; ) { + array[tailNewPos+i] = array[tailOldPos+i]; + } + } // else, add == remove (nothing to do) + + if (add && pos === lengthAfterRemove) { + array.length = lengthAfterRemove; // truncate array + array.push.apply(array, insert); + } else { + array.length = lengthAfterRemove + add; // reserves space + for (i = 0; i < add; ++i) { + array[pos+i] = insert[i]; + } + } + } + + return array; + } + + function replaceNative (array, index, removeCount, insert) { + if (insert && insert.length) { + if (index < array.length) { + array.splice.apply(array, [index, removeCount].concat(insert)); + } else { + array.push.apply(array, insert); + } + } else { + array.splice(index, removeCount); + } + return array; + } + + function eraseSim (array, index, removeCount) { + return replaceSim(array, index, removeCount); + } + + function eraseNative (array, index, removeCount) { + array.splice(index, removeCount); + return array; + } + + function spliceSim (array, index, removeCount) { + var pos = fixArrayIndex(array, index), + removed = array.slice(index, fixArrayIndex(array, pos+removeCount)); + + if (arguments.length < 4) { + replaceSim(array, pos, removeCount); + } else { + replaceSim(array, pos, removeCount, slice.call(arguments, 3)); + } + + return removed; + } + + function spliceNative (array) { + return array.splice.apply(array, slice.call(arguments, 1)); + } + + erase = supportsSplice ? eraseNative : eraseSim; + replace = supportsSplice ? replaceNative : replaceSim; + splice = supportsSplice ? spliceNative : spliceSim; + + // NOTE: from here on, use erase, replace or splice (not native methods)... + + ExtArray = Ext.Array = { + /** + * Iterates an array or an iterable value and invoke the given callback function for each item. + * + * var countries = ['Vietnam', 'Singapore', 'United States', 'Russia']; + * + * Ext.Array.each(countries, function(name, index, countriesItSelf) { + * console.log(name); + * }); + * + * var sum = function() { + * var sum = 0; + * + * Ext.Array.each(arguments, function(value) { + * sum += value; + * }); + * + * return sum; + * }; + * + * sum(1, 2, 3); // returns 6 + * + * The iteration can be stopped by returning false in the function callback. + * + * Ext.Array.each(countries, function(name, index, countriesItSelf) { + * if (name === 'Singapore') { + * return false; // break here + * } + * }); + * + * {@link Ext#each Ext.each} is alias for {@link Ext.Array#each Ext.Array.each} + * + * @param {Array/NodeList/Object} iterable The value to be iterated. If this + * argument is not iterable, the callback function is called once. + * @param {Function} fn The callback function. If it returns false, the iteration stops and this method returns + * the current `index`. + * @param {Object} fn.item The item at the current `index` in the passed `array` + * @param {Number} fn.index The current `index` within the `array` + * @param {Array} fn.allItems The `array` itself which was passed as the first argument + * @param {Boolean} fn.return Return false to stop iteration. + * @param {Object} scope (Optional) The scope (`this` reference) in which the specified function is executed. + * @param {Boolean} reverse (Optional) Reverse the iteration order (loop from the end to the beginning) + * Defaults false + * @return {Boolean} See description for the `fn` parameter. + */ + each: function(array, fn, scope, reverse) { + array = ExtArray.from(array); + + var i, + ln = array.length; + + if (reverse !== true) { + for (i = 0; i < ln; i++) { + if (fn.call(scope || array[i], array[i], i, array) === false) { + return i; + } + } + } + else { + for (i = ln - 1; i > -1; i--) { + if (fn.call(scope || array[i], array[i], i, array) === false) { + return i; + } + } + } + + return true; + }, + + /** + * Iterates an array and invoke the given callback function for each item. Note that this will simply + * delegate to the native Array.prototype.forEach method if supported. It doesn't support stopping the + * iteration by returning false in the callback function like {@link Ext.Array#each}. However, performance + * could be much better in modern browsers comparing with {@link Ext.Array#each} + * + * @param {Array} array The array to iterate + * @param {Function} fn The callback function. + * @param {Object} fn.item The item at the current `index` in the passed `array` + * @param {Number} fn.index The current `index` within the `array` + * @param {Array} fn.allItems The `array` itself which was passed as the first argument + * @param {Object} scope (Optional) The execution scope (`this`) in which the specified function is executed. + */ + forEach: supportsForEach ? function(array, fn, scope) { + return array.forEach(fn, scope); + } : function(array, fn, scope) { + var i = 0, + ln = array.length; + + for (; i < ln; i++) { + fn.call(scope, array[i], i, array); + } + }, + + /** + * Get the index of the provided `item` in the given `array`, a supplement for the + * missing arrayPrototype.indexOf in Internet Explorer. + * + * @param {Array} array The array to check + * @param {Object} item The item to look for + * @param {Number} from (Optional) The index at which to begin the search + * @return {Number} The index of item in the array (or -1 if it is not found) + */ + indexOf: supportsIndexOf ? function(array, item, from) { + return array.indexOf(item, from); + } : function(array, item, from) { + var i, length = array.length; + + for (i = (from < 0) ? Math.max(0, length + from) : from || 0; i < length; i++) { + if (array[i] === item) { + return i; + } + } + + return -1; + }, + + /** + * Checks whether or not the given `array` contains the specified `item` + * + * @param {Array} array The array to check + * @param {Object} item The item to look for + * @return {Boolean} True if the array contains the item, false otherwise + */ + contains: supportsIndexOf ? function(array, item) { + return array.indexOf(item) !== -1; + } : function(array, item) { + var i, ln; + + for (i = 0, ln = array.length; i < ln; i++) { + if (array[i] === item) { + return true; + } + } + + return false; + }, + + /** + * Converts any iterable (numeric indices and a length property) into a true array. + * + * function test() { + * var args = Ext.Array.toArray(arguments), + * fromSecondToLastArgs = Ext.Array.toArray(arguments, 1); + * + * alert(args.join(' ')); + * alert(fromSecondToLastArgs.join(' ')); + * } + * + * test('just', 'testing', 'here'); // alerts 'just testing here'; + * // alerts 'testing here'; + * + * Ext.Array.toArray(document.getElementsByTagName('div')); // will convert the NodeList into an array + * Ext.Array.toArray('splitted'); // returns ['s', 'p', 'l', 'i', 't', 't', 'e', 'd'] + * Ext.Array.toArray('splitted', 0, 3); // returns ['s', 'p', 'l'] + * + * {@link Ext#toArray Ext.toArray} is alias for {@link Ext.Array#toArray Ext.Array.toArray} + * + * @param {Object} iterable the iterable object to be turned into a true Array. + * @param {Number} start (Optional) a zero-based index that specifies the start of extraction. Defaults to 0 + * @param {Number} end (Optional) a 1-based index that specifies the end of extraction. Defaults to the last + * index of the iterable value + * @return {Array} array + */ + toArray: function(iterable, start, end){ + if (!iterable || !iterable.length) { + return []; + } + + if (typeof iterable === 'string') { + iterable = iterable.split(''); + } + + if (supportsSliceOnNodeList) { + return slice.call(iterable, start || 0, end || iterable.length); + } + + var array = [], + i; + + start = start || 0; + end = end ? ((end < 0) ? iterable.length + end : end) : iterable.length; + + for (i = start; i < end; i++) { + array.push(iterable[i]); + } + + return array; + }, + + /** + * Plucks the value of a property from each item in the Array. Example: + * + * Ext.Array.pluck(Ext.query("p"), "className"); // [el1.className, el2.className, ..., elN.className] + * + * @param {Array/NodeList} array The Array of items to pluck the value from. + * @param {String} propertyName The property name to pluck from each element. + * @return {Array} The value from each item in the Array. + */ + pluck: function(array, propertyName) { + var ret = [], + i, ln, item; + + for (i = 0, ln = array.length; i < ln; i++) { + item = array[i]; + + ret.push(item[propertyName]); + } + + return ret; + }, + + /** + * Creates a new array with the results of calling a provided function on every element in this array. + * + * @param {Array} array + * @param {Function} fn Callback function for each item + * @param {Object} scope Callback function scope + * @return {Array} results + */ + map: supportsMap ? function(array, fn, scope) { + if (!fn) { + Ext.Error.raise('Ext.Array.map must have a callback function passed as second argument.'); + } + return array.map(fn, scope); + } : function(array, fn, scope) { + if (!fn) { + Ext.Error.raise('Ext.Array.map must have a callback function passed as second argument.'); + } + var results = [], + i = 0, + len = array.length; + + for (; i < len; i++) { + results[i] = fn.call(scope, array[i], i, array); + } + + return results; + }, + + /** + * Executes the specified function for each array element until the function returns a falsy value. + * If such an item is found, the function will return false immediately. + * Otherwise, it will return true. + * + * @param {Array} array + * @param {Function} fn Callback function for each item + * @param {Object} scope Callback function scope + * @return {Boolean} True if no false value is returned by the callback function. + */ + every: supportsEvery ? function(array, fn, scope) { + if (!fn) { + Ext.Error.raise('Ext.Array.every must have a callback function passed as second argument.'); + } + return array.every(fn, scope); + } : function(array, fn, scope) { + if (!fn) { + Ext.Error.raise('Ext.Array.every must have a callback function passed as second argument.'); + } + var i = 0, + ln = array.length; + + for (; i < ln; ++i) { + if (!fn.call(scope, array[i], i, array)) { + return false; + } + } + + return true; + }, + + /** + * Executes the specified function for each array element until the function returns a truthy value. + * If such an item is found, the function will return true immediately. Otherwise, it will return false. + * + * @param {Array} array + * @param {Function} fn Callback function for each item + * @param {Object} scope Callback function scope + * @return {Boolean} True if the callback function returns a truthy value. + */ + some: supportsSome ? function(array, fn, scope) { + if (!fn) { + Ext.Error.raise('Ext.Array.some must have a callback function passed as second argument.'); + } + return array.some(fn, scope); + } : function(array, fn, scope) { + if (!fn) { + Ext.Error.raise('Ext.Array.some must have a callback function passed as second argument.'); + } + var i = 0, + ln = array.length; + + for (; i < ln; ++i) { + if (fn.call(scope, array[i], i, array)) { + return true; + } + } + + return false; + }, + + /** + * Filter through an array and remove empty item as defined in {@link Ext#isEmpty Ext.isEmpty} + * + * See {@link Ext.Array#filter} + * + * @param {Array} array + * @return {Array} results + */ + clean: function(array) { + var results = [], + i = 0, + ln = array.length, + item; + + for (; i < ln; i++) { + item = array[i]; + + if (!Ext.isEmpty(item)) { + results.push(item); + } + } + + return results; + }, + + /** + * Returns a new array with unique items + * + * @param {Array} array + * @return {Array} results + */ + unique: function(array) { + var clone = [], + i = 0, + ln = array.length, + item; + + for (; i < ln; i++) { + item = array[i]; + + if (ExtArray.indexOf(clone, item) === -1) { + clone.push(item); + } + } + + return clone; + }, + + /** + * Creates a new array with all of the elements of this array for which + * the provided filtering function returns true. + * + * @param {Array} array + * @param {Function} fn Callback function for each item + * @param {Object} scope Callback function scope + * @return {Array} results + */ + filter: supportsFilter ? function(array, fn, scope) { + if (!fn) { + Ext.Error.raise('Ext.Array.filter must have a callback function passed as second argument.'); + } + return array.filter(fn, scope); + } : function(array, fn, scope) { + if (!fn) { + Ext.Error.raise('Ext.Array.filter must have a callback function passed as second argument.'); + } + var results = [], + i = 0, + ln = array.length; + + for (; i < ln; i++) { + if (fn.call(scope, array[i], i, array)) { + results.push(array[i]); + } + } + + return results; + }, + + /** + * Converts a value to an array if it's not already an array; returns: + * + * - An empty array if given value is `undefined` or `null` + * - Itself if given value is already an array + * - An array copy if given value is {@link Ext#isIterable iterable} (arguments, NodeList and alike) + * - An array with one item which is the given value, otherwise + * + * @param {Object} value The value to convert to an array if it's not already is an array + * @param {Boolean} newReference (Optional) True to clone the given array and return a new reference if necessary, + * defaults to false + * @return {Array} array + */ + from: function(value, newReference) { + if (value === undefined || value === null) { + return []; + } + + if (Ext.isArray(value)) { + return (newReference) ? slice.call(value) : value; + } + + var type = typeof value; + // Both strings and functions will have a length property. In phantomJS, NodeList + // instances report typeof=='function' but don't have an apply method... + if (value && value.length !== undefined && type !== 'string' && (type !== 'function' || !value.apply)) { + return ExtArray.toArray(value); + } + + return [value]; + }, + + /** + * Removes the specified item from the array if it exists + * + * @param {Array} array The array + * @param {Object} item The item to remove + * @return {Array} The passed array itself + */ + remove: function(array, item) { + var index = ExtArray.indexOf(array, item); + + if (index !== -1) { + erase(array, index, 1); + } + + return array; + }, + + /** + * Push an item into the array only if the array doesn't contain it yet + * + * @param {Array} array The array + * @param {Object} item The item to include + */ + include: function(array, item) { + if (!ExtArray.contains(array, item)) { + array.push(item); + } + }, + + /** + * Clone a flat array without referencing the previous one. Note that this is different + * from Ext.clone since it doesn't handle recursive cloning. It's simply a convenient, easy-to-remember method + * for Array.prototype.slice.call(array) + * + * @param {Array} array The array + * @return {Array} The clone array + */ + clone: function(array) { + return slice.call(array); + }, + + /** + * Merge multiple arrays into one with unique items. + * + * {@link Ext.Array#union} is alias for {@link Ext.Array#merge} + * + * @param {Array} array1 + * @param {Array} array2 + * @param {Array} etc + * @return {Array} merged + */ + merge: function() { + var args = slice.call(arguments), + array = [], + i, ln; + + for (i = 0, ln = args.length; i < ln; i++) { + array = array.concat(args[i]); + } + + return ExtArray.unique(array); + }, + + /** + * Merge multiple arrays into one with unique items that exist in all of the arrays. + * + * @param {Array} array1 + * @param {Array} array2 + * @param {Array} etc + * @return {Array} intersect + */ + intersect: function() { + var intersection = [], + arrays = slice.call(arguments), + arraysLength, + array, + arrayLength, + minArray, + minArrayIndex, + minArrayCandidate, + minArrayLength, + element, + elementCandidate, + elementCount, + i, j, k; + + if (!arrays.length) { + return intersection; + } + + // Find the smallest array + arraysLength = arrays.length; + for (i = minArrayIndex = 0; i < arraysLength; i++) { + minArrayCandidate = arrays[i]; + if (!minArray || minArrayCandidate.length < minArray.length) { + minArray = minArrayCandidate; + minArrayIndex = i; + } + } + + minArray = ExtArray.unique(minArray); + erase(arrays, minArrayIndex, 1); + + // Use the smallest unique'd array as the anchor loop. If the other array(s) do contain + // an item in the small array, we're likely to find it before reaching the end + // of the inner loop and can terminate the search early. + minArrayLength = minArray.length; + arraysLength = arrays.length; + for (i = 0; i < minArrayLength; i++) { + element = minArray[i]; + elementCount = 0; + + for (j = 0; j < arraysLength; j++) { + array = arrays[j]; + arrayLength = array.length; + for (k = 0; k < arrayLength; k++) { + elementCandidate = array[k]; + if (element === elementCandidate) { + elementCount++; + break; + } + } + } + + if (elementCount === arraysLength) { + intersection.push(element); + } + } + + return intersection; + }, + + /** + * Perform a set difference A-B by subtracting all items in array B from array A. + * + * @param {Array} arrayA + * @param {Array} arrayB + * @return {Array} difference + */ + difference: function(arrayA, arrayB) { + var clone = slice.call(arrayA), + ln = clone.length, + i, j, lnB; + + for (i = 0,lnB = arrayB.length; i < lnB; i++) { + for (j = 0; j < ln; j++) { + if (clone[j] === arrayB[i]) { + erase(clone, j, 1); + j--; + ln--; + } + } + } + + return clone; + }, + + /** + * Returns a shallow copy of a part of an array. This is equivalent to the native + * call "Array.prototype.slice.call(array, begin, end)". This is often used when "array" + * is "arguments" since the arguments object does not supply a slice method but can + * be the context object to Array.prototype.slice. + * + * @param {Array} array The array (or arguments object). + * @param {Number} begin The index at which to begin. Negative values are offsets from + * the end of the array. + * @param {Number} end The index at which to end. The copied items do not include + * end. Negative values are offsets from the end of the array. If end is omitted, + * all items up to the end of the array are copied. + * @return {Array} The copied piece of the array. + * @method slice + */ + // Note: IE6 will return [] on slice.call(x, undefined). + slice: ([1,2].slice(1, undefined).length ? + function (array, begin, end) { + return slice.call(array, begin, end); + } : + // at least IE6 uses arguments.length for variadic signature + function (array, begin, end) { + // After tested for IE 6, the one below is of the best performance + // see http://jsperf.com/slice-fix + if (typeof begin === 'undefined') { + return slice.call(array); + } + if (typeof end === 'undefined') { + return slice.call(array, begin); + } + return slice.call(array, begin, end); + } + ), + + /** + * Sorts the elements of an Array. + * By default, this method sorts the elements alphabetically and ascending. + * + * @param {Array} array The array to sort. + * @param {Function} sortFn (optional) The comparison function. + * @return {Array} The sorted array. + */ + sort: supportsSort ? function(array, sortFn) { + if (sortFn) { + return array.sort(sortFn); + } else { + return array.sort(); + } + } : function(array, sortFn) { + var length = array.length, + i = 0, + comparison, + j, min, tmp; + + for (; i < length; i++) { + min = i; + for (j = i + 1; j < length; j++) { + if (sortFn) { + comparison = sortFn(array[j], array[min]); + if (comparison < 0) { + min = j; + } + } else if (array[j] < array[min]) { + min = j; + } + } + if (min !== i) { + tmp = array[i]; + array[i] = array[min]; + array[min] = tmp; + } + } + + return array; + }, + + /** + * Recursively flattens into 1-d Array. Injects Arrays inline. + * + * @param {Array} array The array to flatten + * @return {Array} The 1-d array. + */ + flatten: function(array) { + var worker = []; + + function rFlatten(a) { + var i, ln, v; + + for (i = 0, ln = a.length; i < ln; i++) { + v = a[i]; + + if (Ext.isArray(v)) { + rFlatten(v); + } else { + worker.push(v); + } + } + + return worker; + } + + return rFlatten(array); + }, + + /** + * Returns the minimum value in the Array. + * + * @param {Array/NodeList} array The Array from which to select the minimum value. + * @param {Function} comparisonFn (optional) a function to perform the comparision which determines minimization. + * If omitted the "<" operator will be used. Note: gt = 1; eq = 0; lt = -1 + * @return {Object} minValue The minimum value + */ + min: function(array, comparisonFn) { + var min = array[0], + i, ln, item; + + for (i = 0, ln = array.length; i < ln; i++) { + item = array[i]; + + if (comparisonFn) { + if (comparisonFn(min, item) === 1) { + min = item; + } + } + else { + if (item < min) { + min = item; + } + } + } + + return min; + }, + + /** + * Returns the maximum value in the Array. + * + * @param {Array/NodeList} array The Array from which to select the maximum value. + * @param {Function} comparisonFn (optional) a function to perform the comparision which determines maximization. + * If omitted the ">" operator will be used. Note: gt = 1; eq = 0; lt = -1 + * @return {Object} maxValue The maximum value + */ + max: function(array, comparisonFn) { + var max = array[0], + i, ln, item; + + for (i = 0, ln = array.length; i < ln; i++) { + item = array[i]; + + if (comparisonFn) { + if (comparisonFn(max, item) === -1) { + max = item; + } + } + else { + if (item > max) { + max = item; + } + } + } + + return max; + }, + + /** + * Calculates the mean of all items in the array. + * + * @param {Array} array The Array to calculate the mean value of. + * @return {Number} The mean. + */ + mean: function(array) { + return array.length > 0 ? ExtArray.sum(array) / array.length : undefined; + }, + + /** + * Calculates the sum of all items in the given array. + * + * @param {Array} array The Array to calculate the sum value of. + * @return {Number} The sum. + */ + sum: function(array) { + var sum = 0, + i, ln, item; + + for (i = 0,ln = array.length; i < ln; i++) { + item = array[i]; + + sum += item; + } + + return sum; + }, + + /** + * Creates a map (object) keyed by the elements of the given array. The values in + * the map are the index+1 of the array element. For example: + * + * var map = Ext.Array.toMap(['a','b','c']); + * + * // map = { a: 1, b: 2, c: 3 }; + * + * Or a key property can be specified: + * + * var map = Ext.Array.toMap([ + * { name: 'a' }, + * { name: 'b' }, + * { name: 'c' } + * ], 'name'); + * + * // map = { a: 1, b: 2, c: 3 }; + * + * Lastly, a key extractor can be provided: + * + * var map = Ext.Array.toMap([ + * { name: 'a' }, + * { name: 'b' }, + * { name: 'c' } + * ], function (obj) { return obj.name.toUpperCase(); }); + * + * // map = { A: 1, B: 2, C: 3 }; + */ + toMap: function(array, getKey, scope) { + var map = {}, + i = array.length; + + if (!getKey) { + while (i--) { + map[array[i]] = i+1; + } + } else if (typeof getKey == 'string') { + while (i--) { + map[array[i][getKey]] = i+1; + } + } else { + while (i--) { + map[getKey.call(scope, array[i])] = i+1; + } + } + + return map; + }, + + _replaceSim: replaceSim, // for unit testing + _spliceSim: spliceSim, + + /** + * Removes items from an array. This is functionally equivalent to the splice method + * of Array, but works around bugs in IE8's splice method and does not copy the + * removed elements in order to return them (because very often they are ignored). + * + * @param {Array} array The Array on which to replace. + * @param {Number} index The index in the array at which to operate. + * @param {Number} removeCount The number of items to remove at index. + * @return {Array} The array passed. + * @method + */ + erase: erase, + + /** + * Inserts items in to an array. + * + * @param {Array} array The Array in which to insert. + * @param {Number} index The index in the array at which to operate. + * @param {Array} items The array of items to insert at index. + * @return {Array} The array passed. + */ + insert: function (array, index, items) { + return replace(array, index, 0, items); + }, + + /** + * Replaces items in an array. This is functionally equivalent to the splice method + * of Array, but works around bugs in IE8's splice method and is often more convenient + * to call because it accepts an array of items to insert rather than use a variadic + * argument list. + * + * @param {Array} array The Array on which to replace. + * @param {Number} index The index in the array at which to operate. + * @param {Number} removeCount The number of items to remove at index (can be 0). + * @param {Array} insert (optional) An array of items to insert at index. + * @return {Array} The array passed. + * @method + */ + replace: replace, + + /** + * Replaces items in an array. This is equivalent to the splice method of Array, but + * works around bugs in IE8's splice method. The signature is exactly the same as the + * splice method except that the array is the first argument. All arguments following + * removeCount are inserted in the array at index. + * + * @param {Array} array The Array on which to replace. + * @param {Number} index The index in the array at which to operate. + * @param {Number} removeCount The number of items to remove at index (can be 0). + * @param {Object...} elements The elements to add to the array. If you don't specify + * any elements, splice simply removes elements from the array. + * @return {Array} An array containing the removed items. + * @method + */ + splice: splice, + + /** + * Pushes new items onto the end of an Array. + * + * Passed parameters may be single items, or arrays of items. If an Array is found in the argument list, all its + * elements are pushed into the end of the target Array. + * + * @param {Array} target The Array onto which to push new items + * @param {Object...} elements The elements to add to the array. Each parameter may + * be an Array, in which case all the elements of that Array will be pushed into the end of the + * destination Array. + * @return {Array} An array containing all the new items push onto the end. + * + */ + push: function(array) { + var len = arguments.length, + i = 1, + newItem; + + if (array === undefined) { + array = []; + } else if (!Ext.isArray(array)) { + array = [array]; + } + for (; i < len; i++) { + newItem = arguments[i]; + Array.prototype.push[Ext.isArray(newItem) ? 'apply' : 'call'](array, newItem); + } + return array; + } + }; + + /** + * @method + * @member Ext + * @inheritdoc Ext.Array#each + */ + Ext.each = ExtArray.each; + + /** + * @method + * @member Ext.Array + * @inheritdoc Ext.Array#merge + */ + ExtArray.union = ExtArray.merge; + + /** + * Old alias to {@link Ext.Array#min} + * @deprecated 4.0.0 Use {@link Ext.Array#min} instead + * @method + * @member Ext + * @inheritdoc Ext.Array#min + */ + Ext.min = ExtArray.min; + + /** + * Old alias to {@link Ext.Array#max} + * @deprecated 4.0.0 Use {@link Ext.Array#max} instead + * @method + * @member Ext + * @inheritdoc Ext.Array#max + */ + Ext.max = ExtArray.max; + + /** + * Old alias to {@link Ext.Array#sum} + * @deprecated 4.0.0 Use {@link Ext.Array#sum} instead + * @method + * @member Ext + * @inheritdoc Ext.Array#sum + */ + Ext.sum = ExtArray.sum; + + /** + * Old alias to {@link Ext.Array#mean} + * @deprecated 4.0.0 Use {@link Ext.Array#mean} instead + * @method + * @member Ext + * @inheritdoc Ext.Array#mean + */ + Ext.mean = ExtArray.mean; + + /** + * Old alias to {@link Ext.Array#flatten} + * @deprecated 4.0.0 Use {@link Ext.Array#flatten} instead + * @method + * @member Ext + * @inheritdoc Ext.Array#flatten + */ + Ext.flatten = ExtArray.flatten; + + /** + * Old alias to {@link Ext.Array#clean} + * @deprecated 4.0.0 Use {@link Ext.Array#clean} instead + * @method + * @member Ext + * @inheritdoc Ext.Array#clean + */ + Ext.clean = ExtArray.clean; + + /** + * Old alias to {@link Ext.Array#unique} + * @deprecated 4.0.0 Use {@link Ext.Array#unique} instead + * @method + * @member Ext + * @inheritdoc Ext.Array#unique + */ + Ext.unique = ExtArray.unique; + + /** + * Old alias to {@link Ext.Array#pluck Ext.Array.pluck} + * @deprecated 4.0.0 Use {@link Ext.Array#pluck Ext.Array.pluck} instead + * @method + * @member Ext + * @inheritdoc Ext.Array#pluck + */ + Ext.pluck = ExtArray.pluck; + + /** + * @method + * @member Ext + * @inheritdoc Ext.Array#toArray + */ + Ext.toArray = function() { + return ExtArray.toArray.apply(ExtArray, arguments); + }; +}()); + +/** + * @class Ext.Function + * + * A collection of useful static methods to deal with function callbacks + * @singleton + * @alternateClassName Ext.util.Functions + */ +Ext.Function = { + + /** + * A very commonly used method throughout the framework. It acts as a wrapper around another method + * which originally accepts 2 arguments for `name` and `value`. + * The wrapped function then allows "flexible" value setting of either: + * + * - `name` and `value` as 2 arguments + * - one single object argument with multiple key - value pairs + * + * For example: + * + * var setValue = Ext.Function.flexSetter(function(name, value) { + * this[name] = value; + * }); + * + * // Afterwards + * // Setting a single name - value + * setValue('name1', 'value1'); + * + * // Settings multiple name - value pairs + * setValue({ + * name1: 'value1', + * name2: 'value2', + * name3: 'value3' + * }); + * + * @param {Function} setter + * @returns {Function} flexSetter + */ + flexSetter: function(fn) { + return function(a, b) { + var k, i; + + if (a === null) { + return this; + } + + if (typeof a !== 'string') { + for (k in a) { + if (a.hasOwnProperty(k)) { + fn.call(this, k, a[k]); + } + } + + if (Ext.enumerables) { + for (i = Ext.enumerables.length; i--;) { + k = Ext.enumerables[i]; + if (a.hasOwnProperty(k)) { + fn.call(this, k, a[k]); + } + } + } + } else { + fn.call(this, a, b); + } + + return this; + }; + }, + + /** + * Create a new function from the provided `fn`, change `this` to the provided scope, optionally + * overrides arguments for the call. (Defaults to the arguments passed by the caller) + * + * {@link Ext#bind Ext.bind} is alias for {@link Ext.Function#bind Ext.Function.bind} + * + * @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 default global environment object (usually 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 + */ + bind: function(fn, scope, args, appendArgs) { + if (arguments.length === 2) { + return function() { + return fn.apply(scope, arguments); + }; + } + + var method = fn, + slice = Array.prototype.slice; + + return function() { + var callArgs = args || arguments; + + if (appendArgs === true) { + callArgs = slice.call(arguments, 0); + callArgs = callArgs.concat(args); + } + else if (typeof appendArgs == 'number') { + callArgs = slice.call(arguments, 0); // copy arguments first + Ext.Array.insert(callArgs, appendArgs, args); + } + + return method.apply(scope || Ext.global, callArgs); + }; + }, + + /** + * Create a new function from the provided `fn`, the arguments of which are pre-set to `args`. + * New arguments passed to the newly created callback when it's invoked are appended after the pre-set ones. + * This is especially useful when creating callbacks. + * + * For example: + * + * var originalFunction = function(){ + * alert(Ext.Array.from(arguments).join(' ')); + * }; + * + * var callback = Ext.Function.pass(originalFunction, ['Hello', 'World']); + * + * callback(); // alerts 'Hello World' + * callback('by Me'); // alerts 'Hello World by Me' + * + * {@link Ext#pass Ext.pass} is alias for {@link Ext.Function#pass Ext.Function.pass} + * + * @param {Function} fn The original function + * @param {Array} args The arguments to pass to new callback + * @param {Object} scope (optional) The scope (`this` reference) in which the function is executed. + * @return {Function} The new callback function + */ + pass: function(fn, args, scope) { + if (!Ext.isArray(args)) { + if (Ext.isIterable(args)) { + args = Ext.Array.clone(args); + } else { + args = args !== undefined ? [args] : []; + } + } + + return function() { + var fnArgs = [].concat(args); + fnArgs.push.apply(fnArgs, arguments); + return fn.apply(scope || this, fnArgs); + }; + }, + + /** + * Create an alias to the provided method property with name `methodName` of `object`. + * Note that the execution scope will still be bound to the provided `object` itself. + * + * @param {Object/Function} object + * @param {String} methodName + * @return {Function} aliasFn + */ + alias: function(object, methodName) { + return function() { + return object[methodName].apply(object, arguments); + }; + }, + + /** + * Create a "clone" of the provided method. The returned method will call the given + * method passing along all arguments and the "this" pointer and return its result. + * + * @param {Function} method + * @return {Function} cloneFn + */ + clone: function(method) { + return function() { + return method.apply(this, arguments); + }; + }, + + /** + * 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); + * } + * + * sayHi('Fred'); // alerts "Hi, Fred" + * + * // create a new function that validates input without + * // directly modifying the original function: + * var sayHiToFriend = Ext.Function.createInterceptor(sayHi, function(name){ + * return name == 'Brian'; + * }); + * + * 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.** + * @param {Object} returnValue (optional) The value to return if the passed function return false (defaults to null). + * @return {Function} The new function + */ + createInterceptor: function(origFn, newFn, scope, returnValue) { + 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 || Ext.global, args) !== false) ? origFn.apply(me || Ext.global, args) : returnValue || null; + }; + } + }, + + /** + * Creates a delegate (callback) which, when called, executes after a specific delay. + * + * @param {Function} fn The function which will be called on a delay when the returned function is called. + * Optionally, a replacement (or additional) argument list may be specified. + * @param {Number} delay The number of milliseconds to defer execution by whenever called. + * @param {Object} scope (optional) The scope (`this` reference) used by the function at execution time. + * @param {Array} args (optional) Override 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} A function which, when called, executes the original function after the specified delay. + */ + createDelayed: function(fn, delay, scope, args, appendArgs) { + if (scope || args) { + fn = Ext.Function.bind(fn, scope, args, appendArgs); + } + + return function() { + var me = this, + args = Array.prototype.slice.call(arguments); + + setTimeout(function() { + fn.apply(me, args); + }, delay); + }; + }, + + /** + * Calls this function after the number of millseconds specified, optionally in a specific scope. Example usage: + * + * var sayHi = function(name){ + * alert('Hi, ' + name); + * } + * + * // executes immediately: + * sayHi('Fred'); + * + * // executes after 2 seconds: + * Ext.Function.defer(sayHi, 2000, this, ['Fred']); + * + * // this syntax is sometimes useful for deferring + * // execution of an anonymous function: + * Ext.Function.defer(function(){ + * alert('Anonymous'); + * }, 100); + * + * {@link Ext#defer Ext.defer} is alias for {@link Ext.Function#defer Ext.Function.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 + */ + defer: function(fn, millis, scope, args, appendArgs) { + fn = Ext.Function.bind(fn, scope, args, appendArgs); + if (millis > 0) { + return setTimeout(Ext.supports.TimeoutActualLateness ? function () { + fn(); + } : fn, millis); + } + fn(); + return 0; + }, + + /** + * 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 function is called with the parameters of the original function. Example usage: + * + * var sayHi = function(name){ + * alert('Hi, ' + name); + * } + * + * sayHi('Fred'); // alerts "Hi, Fred" + * + * var sayGoodbye = Ext.Function.createSequence(sayHi, function(name){ + * alert('Bye, ' + name); + * }); + * + * sayGoodbye('Fred'); // both alerts show + * + * @param {Function} originalFn 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 default global environment object (usually the browser window). + * @return {Function} The new function + */ + createSequence: function(originalFn, newFn, scope) { + if (!newFn) { + return originalFn; + } + else { + return function() { + var result = originalFn.apply(this, arguments); + newFn.apply(scope || this, arguments); + return result; + }; + } + }, + + /** + * Creates a delegate function, optionally with a bound scope which, when called, buffers + * the execution of the passed function for the configured number of milliseconds. + * If called again within that period, the impending invocation will be canceled, and the + * timeout period will begin again. + * + * @param {Function} fn The function to invoke on a buffered timer. + * @param {Number} buffer The number of milliseconds by which to buffer the invocation of the + * function. + * @param {Object} scope (optional) The scope (`this` reference) in which + * the passed function is executed. If omitted, defaults to the scope specified by the caller. + * @param {Array} args (optional) Override arguments for the call. Defaults to the arguments + * passed by the caller. + * @return {Function} A function which invokes the passed function after buffering for the specified time. + */ + createBuffered: function(fn, buffer, scope, args) { + var timerId; + + return function() { + var callArgs = args || Array.prototype.slice.call(arguments, 0), + me = scope || this; + + if (timerId) { + clearTimeout(timerId); + } + + timerId = setTimeout(function(){ + fn.apply(me, callArgs); + }, buffer); + }; + }, + + /** + * Creates a throttled version of the passed function which, when called repeatedly and + * rapidly, invokes the passed function only after a certain interval has elapsed since the + * previous invocation. + * + * This is useful for wrapping functions which may be called repeatedly, such as + * a handler of a mouse move event when the processing is expensive. + * + * @param {Function} fn The function to execute at a regular time interval. + * @param {Number} interval The interval **in milliseconds** on which the passed function is executed. + * @param {Object} scope (optional) The scope (`this` reference) in which + * the passed function is executed. If omitted, defaults to the scope specified by the caller. + * @returns {Function} A function which invokes the passed function at the specified interval. + */ + createThrottled: function(fn, interval, scope) { + var lastCallTime, elapsed, lastArgs, timer, execute = function() { + fn.apply(scope || this, lastArgs); + lastCallTime = new Date().getTime(); + }; + + return function() { + elapsed = new Date().getTime() - lastCallTime; + lastArgs = arguments; + + clearTimeout(timer); + if (!lastCallTime || (elapsed >= interval)) { + execute(); + } else { + timer = setTimeout(execute, interval - elapsed); + } + }; + }, + + + /** + * Adds behavior to an existing method that is executed before the + * original behavior of the function. For example: + * + * var soup = { + * contents: [], + * add: function(ingredient) { + * this.contents.push(ingredient); + * } + * }; + * Ext.Function.interceptBefore(soup, "add", function(ingredient){ + * if (!this.contents.length && ingredient !== "water") { + * // Always add water to start with + * this.contents.push("water"); + * } + * }); + * soup.add("onions"); + * soup.add("salt"); + * soup.contents; // will contain: water, onions, salt + * + * @param {Object} object The target object + * @param {String} methodName Name of the method to override + * @param {Function} fn Function with the new behavior. It will + * be called with the same arguments as the original method. The + * return value of this function will be the return value of the + * new method. + * @param {Object} [scope] The scope to execute the interceptor function. Defaults to the object. + * @return {Function} The new function just created. + */ + interceptBefore: function(object, methodName, fn, scope) { + var method = object[methodName] || Ext.emptyFn; + + return (object[methodName] = function() { + var ret = fn.apply(scope || this, arguments); + method.apply(this, arguments); + + return ret; + }); + }, + + /** + * Adds behavior to an existing method that is executed after the + * original behavior of the function. For example: + * + * var soup = { + * contents: [], + * add: function(ingredient) { + * this.contents.push(ingredient); + * } + * }; + * Ext.Function.interceptAfter(soup, "add", function(ingredient){ + * // Always add a bit of extra salt + * this.contents.push("salt"); + * }); + * soup.add("water"); + * soup.add("onions"); + * soup.contents; // will contain: water, salt, onions, salt + * + * @param {Object} object The target object + * @param {String} methodName Name of the method to override + * @param {Function} fn Function with the new behavior. It will + * be called with the same arguments as the original method. The + * return value of this function will be the return value of the + * new method. + * @param {Object} [scope] The scope to execute the interceptor function. Defaults to the object. + * @return {Function} The new function just created. + */ + interceptAfter: function(object, methodName, fn, scope) { + var method = object[methodName] || Ext.emptyFn; + + return (object[methodName] = function() { + method.apply(this, arguments); + return fn.apply(scope || this, arguments); + }); + } +}; + +/** + * @method + * @member Ext + * @inheritdoc Ext.Function#defer + */ +Ext.defer = Ext.Function.alias(Ext.Function, 'defer'); + +/** + * @method + * @member Ext + * @inheritdoc Ext.Function#pass + */ +Ext.pass = Ext.Function.alias(Ext.Function, 'pass'); + +/** + * @method + * @member Ext + * @inheritdoc Ext.Function#bind + */ +Ext.bind = Ext.Function.alias(Ext.Function, 'bind'); + +/** + * @author Jacky Nguyen + * @docauthor Jacky Nguyen + * @class Ext.Object + * + * A collection of useful static methods to deal with objects. + * + * @singleton + */ + +(function() { + +// The "constructor" for chain: +var TemplateClass = function(){}, + ExtObject = Ext.Object = { + + /** + * Returns a new object with the given object as the prototype chain. + * @param {Object} object The prototype chain for the new object. + */ + chain: function (object) { + TemplateClass.prototype = object; + var result = new TemplateClass(); + TemplateClass.prototype = null; + return result; + }, + + /** + * Converts a `name` - `value` pair to an array of objects with support for nested structures. Useful to construct + * query strings. For example: + * + * var objects = Ext.Object.toQueryObjects('hobbies', ['reading', 'cooking', 'swimming']); + * + * // objects then equals: + * [ + * { name: 'hobbies', value: 'reading' }, + * { name: 'hobbies', value: 'cooking' }, + * { name: 'hobbies', value: 'swimming' }, + * ]; + * + * var objects = Ext.Object.toQueryObjects('dateOfBirth', { + * day: 3, + * month: 8, + * year: 1987, + * extra: { + * hour: 4 + * minute: 30 + * } + * }, true); // Recursive + * + * // objects then equals: + * [ + * { name: 'dateOfBirth[day]', value: 3 }, + * { name: 'dateOfBirth[month]', value: 8 }, + * { name: 'dateOfBirth[year]', value: 1987 }, + * { name: 'dateOfBirth[extra][hour]', value: 4 }, + * { name: 'dateOfBirth[extra][minute]', value: 30 }, + * ]; + * + * @param {String} name + * @param {Object/Array} value + * @param {Boolean} [recursive=false] True to traverse object recursively + * @return {Array} + */ + toQueryObjects: function(name, value, recursive) { + var self = ExtObject.toQueryObjects, + objects = [], + i, ln; + + if (Ext.isArray(value)) { + for (i = 0, ln = value.length; i < ln; i++) { + if (recursive) { + objects = objects.concat(self(name + '[' + i + ']', value[i], true)); + } + else { + objects.push({ + name: name, + value: value[i] + }); + } + } + } + else if (Ext.isObject(value)) { + for (i in value) { + if (value.hasOwnProperty(i)) { + if (recursive) { + objects = objects.concat(self(name + '[' + i + ']', value[i], true)); + } + else { + objects.push({ + name: name, + value: value[i] + }); + } + } + } + } + else { + objects.push({ + name: name, + value: value + }); + } + + return objects; + }, + + /** + * Takes an object and converts it to an encoded query string. + * + * Non-recursive: + * + * Ext.Object.toQueryString({foo: 1, bar: 2}); // returns "foo=1&bar=2" + * Ext.Object.toQueryString({foo: null, bar: 2}); // returns "foo=&bar=2" + * Ext.Object.toQueryString({'some price': '$300'}); // returns "some%20price=%24300" + * Ext.Object.toQueryString({date: new Date(2011, 0, 1)}); // returns "date=%222011-01-01T00%3A00%3A00%22" + * Ext.Object.toQueryString({colors: ['red', 'green', 'blue']}); // returns "colors=red&colors=green&colors=blue" + * + * Recursive: + * + * Ext.Object.toQueryString({ + * username: 'Jacky', + * dateOfBirth: { + * day: 1, + * month: 2, + * year: 1911 + * }, + * hobbies: ['coding', 'eating', 'sleeping', ['nested', 'stuff']] + * }, true); // returns the following string (broken down and url-decoded for ease of reading purpose): + * // username=Jacky + * // &dateOfBirth[day]=1&dateOfBirth[month]=2&dateOfBirth[year]=1911 + * // &hobbies[0]=coding&hobbies[1]=eating&hobbies[2]=sleeping&hobbies[3][0]=nested&hobbies[3][1]=stuff + * + * @param {Object} object The object to encode + * @param {Boolean} [recursive=false] Whether or not to interpret the object in recursive format. + * (PHP / Ruby on Rails servers and similar). + * @return {String} queryString + */ + toQueryString: function(object, recursive) { + var paramObjects = [], + params = [], + i, j, ln, paramObject, value; + + for (i in object) { + if (object.hasOwnProperty(i)) { + paramObjects = paramObjects.concat(ExtObject.toQueryObjects(i, object[i], recursive)); + } + } + + for (j = 0, ln = paramObjects.length; j < ln; j++) { + paramObject = paramObjects[j]; + value = paramObject.value; + + if (Ext.isEmpty(value)) { + value = ''; + } + else if (Ext.isDate(value)) { + value = Ext.Date.toString(value); + } + + params.push(encodeURIComponent(paramObject.name) + '=' + encodeURIComponent(String(value))); + } + + return params.join('&'); + }, + + /** + * Converts a query string back into an object. + * + * Non-recursive: + * + * Ext.Object.fromQueryString("foo=1&bar=2"); // returns {foo: 1, bar: 2} + * Ext.Object.fromQueryString("foo=&bar=2"); // returns {foo: null, bar: 2} + * Ext.Object.fromQueryString("some%20price=%24300"); // returns {'some price': '$300'} + * Ext.Object.fromQueryString("colors=red&colors=green&colors=blue"); // returns {colors: ['red', 'green', 'blue']} + * + * Recursive: + * + * Ext.Object.fromQueryString( + * "username=Jacky&"+ + * "dateOfBirth[day]=1&dateOfBirth[month]=2&dateOfBirth[year]=1911&"+ + * "hobbies[0]=coding&hobbies[1]=eating&hobbies[2]=sleeping&"+ + * "hobbies[3][0]=nested&hobbies[3][1]=stuff", true); + * + * // returns + * { + * username: 'Jacky', + * dateOfBirth: { + * day: '1', + * month: '2', + * year: '1911' + * }, + * hobbies: ['coding', 'eating', 'sleeping', ['nested', 'stuff']] + * } + * + * @param {String} queryString The query string to decode + * @param {Boolean} [recursive=false] Whether or not to recursively decode the string. This format is supported by + * PHP / Ruby on Rails servers and similar. + * @return {Object} + */ + fromQueryString: function(queryString, recursive) { + var parts = queryString.replace(/^\?/, '').split('&'), + object = {}, + temp, components, name, value, i, ln, + part, j, subLn, matchedKeys, matchedName, + keys, key, nextKey; + + for (i = 0, ln = parts.length; i < ln; i++) { + part = parts[i]; + + if (part.length > 0) { + components = part.split('='); + name = decodeURIComponent(components[0]); + value = (components[1] !== undefined) ? decodeURIComponent(components[1]) : ''; + + if (!recursive) { + if (object.hasOwnProperty(name)) { + if (!Ext.isArray(object[name])) { + object[name] = [object[name]]; + } + + object[name].push(value); + } + else { + object[name] = value; + } + } + else { + matchedKeys = name.match(/(\[):?([^\]]*)\]/g); + matchedName = name.match(/^([^\[]+)/); + + if (!matchedName) { + throw new Error('[Ext.Object.fromQueryString] Malformed query string given, failed parsing name from "' + part + '"'); + } + + name = matchedName[0]; + keys = []; + + if (matchedKeys === null) { + object[name] = value; + continue; + } + + for (j = 0, subLn = matchedKeys.length; j < subLn; j++) { + key = matchedKeys[j]; + key = (key.length === 2) ? '' : key.substring(1, key.length - 1); + keys.push(key); + } + + keys.unshift(name); + + temp = object; + + for (j = 0, subLn = keys.length; j < subLn; j++) { + key = keys[j]; + + if (j === subLn - 1) { + if (Ext.isArray(temp) && key === '') { + temp.push(value); + } + else { + temp[key] = value; + } + } + else { + if (temp[key] === undefined || typeof temp[key] === 'string') { + nextKey = keys[j+1]; + + temp[key] = (Ext.isNumeric(nextKey) || nextKey === '') ? [] : {}; + } + + temp = temp[key]; + } + } + } + } + } + + return object; + }, + + /** + * Iterates through an object and invokes the given callback function for each iteration. + * The iteration can be stopped by returning `false` in the callback function. For example: + * + * var person = { + * name: 'Jacky' + * hairColor: 'black' + * loves: ['food', 'sleeping', 'wife'] + * }; + * + * Ext.Object.each(person, function(key, value, myself) { + * console.log(key + ":" + value); + * + * if (key === 'hairColor') { + * return false; // stop the iteration + * } + * }); + * + * @param {Object} object The object to iterate + * @param {Function} fn The callback function. + * @param {String} fn.key + * @param {Object} fn.value + * @param {Object} fn.object The object itself + * @param {Object} [scope] The execution scope (`this`) of the callback function + */ + each: function(object, fn, scope) { + for (var property in object) { + if (object.hasOwnProperty(property)) { + if (fn.call(scope || object, property, object[property], object) === false) { + return; + } + } + } + }, + + /** + * Merges any number of objects recursively without referencing them or their children. + * + * var extjs = { + * companyName: 'Ext JS', + * products: ['Ext JS', 'Ext GWT', 'Ext Designer'], + * isSuperCool: true, + * office: { + * size: 2000, + * location: 'Palo Alto', + * isFun: true + * } + * }; + * + * var newStuff = { + * companyName: 'Sencha Inc.', + * products: ['Ext JS', 'Ext GWT', 'Ext Designer', 'Sencha Touch', 'Sencha Animator'], + * office: { + * size: 40000, + * location: 'Redwood City' + * } + * }; + * + * var sencha = Ext.Object.merge(extjs, newStuff); + * + * // extjs and sencha then equals to + * { + * companyName: 'Sencha Inc.', + * products: ['Ext JS', 'Ext GWT', 'Ext Designer', 'Sencha Touch', 'Sencha Animator'], + * isSuperCool: true, + * office: { + * size: 40000, + * location: 'Redwood City', + * isFun: true + * } + * } + * + * @param {Object} destination The object into which all subsequent objects are merged. + * @param {Object...} object Any number of objects to merge into the destination. + * @return {Object} merged The destination object with all passed objects merged in. + */ + merge: function(destination) { + var i = 1, + ln = arguments.length, + mergeFn = ExtObject.merge, + cloneFn = Ext.clone, + object, key, value, sourceKey; + + for (; i < ln; i++) { + object = arguments[i]; + + for (key in object) { + value = object[key]; + if (value && value.constructor === Object) { + sourceKey = destination[key]; + if (sourceKey && sourceKey.constructor === Object) { + mergeFn(sourceKey, value); + } + else { + destination[key] = cloneFn(value); + } + } + else { + destination[key] = value; + } + } + } + + return destination; + }, + + /** + * @private + * @param destination + */ + mergeIf: function(destination) { + var i = 1, + ln = arguments.length, + cloneFn = Ext.clone, + object, key, value; + + for (; i < ln; i++) { + object = arguments[i]; + + for (key in object) { + if (!(key in destination)) { + value = object[key]; + + if (value && value.constructor === Object) { + destination[key] = cloneFn(value); + } + else { + destination[key] = value; + } + } + } + } + + return destination; + }, + + /** + * Returns the first matching key corresponding to the given value. + * If no matching value is found, null is returned. + * + * var person = { + * name: 'Jacky', + * loves: 'food' + * }; + * + * alert(Ext.Object.getKey(person, 'food')); // alerts 'loves' + * + * @param {Object} object + * @param {Object} value The value to find + */ + getKey: function(object, value) { + for (var property in object) { + if (object.hasOwnProperty(property) && object[property] === value) { + return property; + } + } + + return null; + }, + + /** + * Gets all values of the given object as an array. + * + * var values = Ext.Object.getValues({ + * name: 'Jacky', + * loves: 'food' + * }); // ['Jacky', 'food'] + * + * @param {Object} object + * @return {Array} An array of values from the object + */ + getValues: function(object) { + var values = [], + property; + + for (property in object) { + if (object.hasOwnProperty(property)) { + values.push(object[property]); + } + } + + return values; + }, + + /** + * Gets all keys of the given object as an array. + * + * var values = Ext.Object.getKeys({ + * name: 'Jacky', + * loves: 'food' + * }); // ['name', 'loves'] + * + * @param {Object} object + * @return {String[]} An array of keys from the object + * @method + */ + getKeys: (typeof Object.keys == 'function') + ? function(object){ + if (!object) { + return []; + } + return Object.keys(object); + } + : function(object) { + var keys = [], + property; + + for (property in object) { + if (object.hasOwnProperty(property)) { + keys.push(property); + } + } + + return keys; + }, + + /** + * Gets the total number of this object's own properties + * + * var size = Ext.Object.getSize({ + * name: 'Jacky', + * loves: 'food' + * }); // size equals 2 + * + * @param {Object} object + * @return {Number} size + */ + getSize: function(object) { + var size = 0, + property; + + for (property in object) { + if (object.hasOwnProperty(property)) { + size++; + } + } + + return size; + }, + + /** + * @private + */ + classify: function(object) { + var prototype = object, + objectProperties = [], + propertyClassesMap = {}, + objectClass = function() { + var i = 0, + ln = objectProperties.length, + property; + + for (; i < ln; i++) { + property = objectProperties[i]; + this[property] = new propertyClassesMap[property](); + } + }, + key, value; + + for (key in object) { + if (object.hasOwnProperty(key)) { + value = object[key]; + + if (value && value.constructor === Object) { + objectProperties.push(key); + propertyClassesMap[key] = ExtObject.classify(value); + } + } + } + + objectClass.prototype = prototype; + + return objectClass; + } +}; + +/** + * A convenient alias method for {@link Ext.Object#merge}. + * + * @member Ext + * @method merge + * @inheritdoc Ext.Object#merge + */ +Ext.merge = Ext.Object.merge; + +/** + * @private + */ +Ext.mergeIf = Ext.Object.mergeIf; + +/** + * + * @member Ext + * @method urlEncode + * @inheritdoc Ext.Object#toQueryString + * @deprecated 4.0.0 Use {@link Ext.Object#toQueryString} instead + */ +Ext.urlEncode = function() { + var args = Ext.Array.from(arguments), + prefix = ''; + + // Support for the old `pre` argument + if ((typeof args[1] === 'string')) { + prefix = args[1] + '&'; + args[1] = false; + } + + return prefix + ExtObject.toQueryString.apply(ExtObject, args); +}; + +/** + * Alias for {@link Ext.Object#fromQueryString}. + * + * @member Ext + * @method urlDecode + * @inheritdoc Ext.Object#fromQueryString + * @deprecated 4.0.0 Use {@link Ext.Object#fromQueryString} instead + */ +Ext.urlDecode = function() { + return ExtObject.fromQueryString.apply(ExtObject, arguments); +}; + +}()); + +/** + * @class Ext.Date + * A set of useful static methods to deal with date + * Note that if Ext.Date is required and loaded, it will copy all methods / properties to + * this object for convenience + * + * 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
    +  MS    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');
    +console.log(Ext.Date.format(dt, 'Y-m-d'));                          // 2007-01-10
    +console.log(Ext.Date.format(dt, 'F j, Y, g:i a'));                  // January 10, 2007, 3:05 pm
    +console.log(Ext.Date.format(dt, 'l, \\t\\he jS \\of F Y h:i:s A')); // Wednesday, the 10th of January 2007 03:05:01 PM
    +
    + * + * Here are some standard date/time patterns that you might find helpful. They + * are not part of the source of Ext.Date, but to use them you can simply copy this + * block of code into any script that is included after Ext.Date and they will also become + * globally available on the Date object. Feel free to add or remove patterns as needed in your code. + *
    
    +Ext.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();
    +console.log(Ext.Date.format(dt, Ext.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}.

    + * @singleton + */ + +/* + * 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() { + +// create private copy of Ext's Ext.util.Format.format() method +// - to remove unnecessary dependency +// - to resolve namespace conflict with MS-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]; + }); +} + +Ext.Date = { + /** + * Returns the current timestamp + * @return {Number} The current timestamp + * @method + */ + now: Date.now || function() { + return +new Date(); + }, + + /** + * @private + * Private for now + */ + toString: function(date) { + var pad = Ext.String.leftPad; + + return date.getFullYear() + "-" + + pad(date.getMonth() + 1, 2, '0') + "-" + + pad(date.getDate(), 2, '0') + "T" + + pad(date.getHours(), 2, '0') + ":" + + pad(date.getMinutes(), 2, '0') + ":" + + pad(date.getSeconds(), 2, '0'); + }, + + /** + * Returns the number of milliseconds between two dates + * @param {Date} dateA The first date + * @param {Date} dateB (optional) The second date, defaults to now + * @return {Number} The difference in milliseconds + */ + getElapsed: function(dateA, dateB) { + return Math.abs(dateA - (dateB || new Date())); + }, + + /** + * 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 #parse} for more information) + * Defaults to false. + * @type Boolean + */ + useStrict: false, + + // private + formatCodeToRegex: function(character, currentGroup) { + // Note: currentGroup - position in regex result array (see notes for Ext.Date.parseCodes below) + var p = utilDate.parseCodes[character]; + + if (p) { + p = typeof p == 'function'? p() : p; + utilDate.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.String.escapeRegex(character) // treat unrecognised characters as literals + }; + }, + + /** + *

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

    + *

    Example:

    
    +Ext.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 + * @type Object + */ + parseFunctions: { + "MS": function(input, strict) { + // note: the timezone offset is ignored since the MS Ajax server sends + // a UTC milliseconds-since-Unix-epoch value (negative values are allowed) + var re = new RegExp('\\/Date\\(([-+])?(\\d+)(?:[+-]\\d{4})?\\)\\/'), + r = (input || '').match(re); + return r? new Date(((r[1] || '') + r[2]) * 1) : 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:

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

    A formatting function should return a string representation of the passed Date object, and is passed the following parameters:

      + *
    • 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 + * @type Object + */ + formatFunctions: { + "MS": function() { + // UTC milliseconds since Unix epoch (MS-AJAX serialized date format (MRSF)) + return '\\/Date(' + this.getTime() + ')\\/'; + } + }, + + y2kYear : 50, + + /** + * Date interval constant + * @type String + */ + MILLI : "ms", + + /** + * Date interval constant + * @type String + */ + SECOND : "s", + + /** + * Date interval constant + * @type String + */ + MINUTE : "mi", + + /** Date interval constant + * @type String + */ + HOUR : "h", + + /** + * Date interval constant + * @type String + */ + DAY : "d", + + /** + * Date interval constant + * @type String + */ + MONTH : "mo", + + /** + * Date interval constant + * @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 #parse} 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
    +Ext.Date.defaults.d = 1;
    +
    +// parse a February date string containing only year and month values.
    +// setting the default day value to 1 prevents weird date rollover issues
    +// when attempting to parse the following date string on, for example, March 31st 2009.
    +Ext.Date.parse('2009-02', 'Y-m'); // returns a Date object representing February 1st 2009
    +
    + * @property defaults + * @type Object + */ + defaults: {}, + + // + /** + * @property {String[]} dayNames + * An array of textual day names. + * Override these values for international dates. + * Example: + *
    
    +Ext.Date.dayNames = [
    +    'SundayInYourLang',
    +    'MondayInYourLang',
    +    ...
    +];
    +
    + */ + dayNames : [ + "Sunday", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday" + ], + //
    + + // + /** + * @property {String[]} monthNames + * An array of textual month names. + * Override these values for international dates. + * Example: + *
    
    +Ext.Date.monthNames = [
    +    'JanInYourLang',
    +    'FebInYourLang',
    +    ...
    +];
    +
    + */ + monthNames : [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December" + ], + //
    + + // + /** + * @property {Object} monthNumbers + * 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: + *
    
    +Ext.Date.monthNumbers = {
    +    'LongJanNameInYourLang': 0,
    +    'ShortJanNameInYourLang':0,
    +    'LongFebNameInYourLang':1,
    +    'ShortFebNameInYourLang':1,
    +    ...
    +};
    +
    + */ + monthNumbers : { + January: 0, + Jan: 0, + February: 1, + Feb: 1, + March: 2, + Mar: 2, + April: 3, + Apr: 3, + May: 4, + June: 5, + Jun: 5, + July: 6, + Jul: 6, + August: 7, + Aug: 7, + September: 8, + Sep: 8, + October: 9, + Oct: 9, + November: 10, + Nov: 10, + December: 11, + Dec: 11 + }, + //
    + + // + /** + * @property {String} defaultFormat + *

    The date format string that the {@link Ext.util.Format#dateRenderer} + * and {@link Ext.util.Format#date} functions use. See {@link Ext.Date} for details.

    + *

    This may be overridden in a locale file.

    + */ + defaultFormat : "m/d/Y", + //
    + // + /** + * 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. + */ + getShortMonthName : function(month) { + return Ext.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. + */ + getShortDayName : function(day) { + return Ext.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. + */ + getMonthNumber : function(name) { + // handle camel casing for english month names (since the keys for the Ext.Date.monthNumbers hash are case sensitive) + return Ext.Date.monthNumbers[name.substring(0, 1).toUpperCase() + name.substring(1, 3).toLowerCase()]; + }, + // + + /** + * Checks if the specified format contains hour information + * @param {String} format The format to check + * @return {Boolean} True if the format contains hour information + * @method + */ + formatContainsHourInfo : (function(){ + var stripEscapeRe = /(\\.)/g, + hourInfoRe = /([gGhHisucUOPZ]|MS)/; + return function(format){ + return hourInfoRe.test(format.replace(stripEscapeRe, '')); + }; + }()), + + /** + * Checks if the specified format contains information about + * anything other than the time. + * @param {String} format The format to check + * @return {Boolean} True if the format contains information about + * date/day information. + * @method + */ + formatContainsDateInfo : (function(){ + var stripEscapeRe = /(\\.)/g, + dateInfoRe = /([djzmnYycU]|MS)/; + + return function(format){ + return dateInfoRe.test(format.replace(stripEscapeRe, '')); + }; + }()), + + /** + * Removes all escaping for a date format string. In date formats, + * using a '\' can be used to escape special characters. + * @param {String} format The format to unescape + * @return {String} The unescaped format + * @method + */ + unescapeFormat: (function() { + var slashRe = /\\/gi; + return function(format) { + // Escape the format, since \ can be used to escape special + // characters in a date format. For example, in a spanish + // locale the format may be: 'd \\de F \\de Y' + return format.replace(slashRe, ''); + } + }()), + + /** + * 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: Ext.Date.format() treats characters as literals if an appropriate mapping cannot be found. + * Example: + *
    
    +Ext.Date.formatCodes.x = "Ext.util.Format.leftPad(this.getDate(), 2, '0')";
    +console.log(Ext.Date.format(new Date(), 'X'); // returns the current day of the month
    +
    + * @type Object + */ + formatCodes : { + d: "Ext.String.leftPad(this.getDate(), 2, '0')", + D: "Ext.Date.getShortDayName(this.getDay())", // get localised short day name + j: "this.getDate()", + l: "Ext.Date.dayNames[this.getDay()]", + N: "(this.getDay() ? this.getDay() : 7)", + S: "Ext.Date.getSuffix(this)", + w: "this.getDay()", + z: "Ext.Date.getDayOfYear(this)", + W: "Ext.String.leftPad(Ext.Date.getWeekOfYear(this), 2, '0')", + F: "Ext.Date.monthNames[this.getMonth()]", + m: "Ext.String.leftPad(this.getMonth() + 1, 2, '0')", + M: "Ext.Date.getShortMonthName(this.getMonth())", // get localised short month name + n: "(this.getMonth() + 1)", + t: "Ext.Date.getDaysInMonth(this)", + L: "(Ext.Date.isLeapYear(this) ? 1 : 0)", + o: "(this.getFullYear() + (Ext.Date.getWeekOfYear(this) == 1 && this.getMonth() > 0 ? +1 : (Ext.Date.getWeekOfYear(this) >= 52 && this.getMonth() < 11 ? -1 : 0)))", + Y: "Ext.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: "Ext.String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0')", + H: "Ext.String.leftPad(this.getHours(), 2, '0')", + i: "Ext.String.leftPad(this.getMinutes(), 2, '0')", + s: "Ext.String.leftPad(this.getSeconds(), 2, '0')", + u: "Ext.String.leftPad(this.getMilliseconds(), 3, '0')", + O: "Ext.Date.getGMTOffset(this)", + P: "Ext.Date.getGMTOffset(this, true)", + T: "Ext.Date.getTimezone(this)", + Z: "(this.getTimezoneOffset() * -60)", + + c: function() { // ISO-8601 -- GMT format + var c, code, i, l, e; + for (c = "Y-m-dTH:i:sP", code = [], i = 0, l = c.length; i < l; ++i) { + e = c.charAt(i); + code.push(e == "T" ? "'T'" : utilDate.getFormatCode(e)); // treat T as a character literal + } + return code.join(" + "); + }, + /* + c: function() { // ISO-8601 -- UTC format + return [ + "this.getUTCFullYear()", "'-'", + "Ext.util.Format.leftPad(this.getUTCMonth() + 1, 2, '0')", "'-'", + "Ext.util.Format.leftPad(this.getUTCDate(), 2, '0')", + "'T'", + "Ext.util.Format.leftPad(this.getUTCHours(), 2, '0')", "':'", + "Ext.util.Format.leftPad(this.getUTCMinutes(), 2, '0')", "':'", + "Ext.util.Format.leftPad(this.getUTCSeconds(), 2, '0')", + "'Z'" + ].join(" + "); + }, + */ + + U: "Math.round(this.getTime() / 1000)" + }, + + /** + * Checks if the passed Date parameters will cause a javascript Date "rollover". + * @param {Number} year 4-digit year + * @param {Number} month 1-based month-of-year + * @param {Number} day Day of month + * @param {Number} hour (optional) Hour + * @param {Number} minute (optional) Minute + * @param {Number} second (optional) Second + * @param {Number} millisecond (optional) Millisecond + * @return {Boolean} true if the passed parameters do not cause a Date "rollover", false otherwise. + */ + isValid : function(y, m, d, h, i, s, ms) { + // setup defaults + h = h || 0; + i = i || 0; + s = s || 0; + ms = ms || 0; + + // Special handling for year < 100 + var dt = utilDate.add(new Date(y < 100 ? 100 : y, m - 1, d, h, i, s, ms), utilDate.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(); + }, + + /** + * 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 = Ext.Date.parse("2006", "Y");
    +
    +//dt = Sun Jan 15 2006 (all date parts specified)
    +dt = Ext.Date.parse("2006-01-15", "Y-m-d");
    +
    +//dt = Sun Jan 15 2006 15:20:01
    +dt = Ext.Date.parse("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 = Ext.Date.parse("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. + */ + parse : function(input, format, strict) { + var p = utilDate.parseFunctions; + if (p[format] == null) { + utilDate.createParser(format); + } + return p[format](input, Ext.isDefined(strict) ? strict : utilDate.useStrict); + }, + + // Backwards compat + parseDate: function(input, format, strict){ + return utilDate.parse(input, format, strict); + }, + + + // private + getFormatCode : function(character) { + var f = utilDate.formatCodes[character]; + + if (f) { + f = typeof f == 'function'? f() : f; + utilDate.formatCodes[character] = f; // reassign function result to prevent repeated execution + } + + // note: unknown characters are treated as literals + return f || ("'" + Ext.String.escape(character) + "'"); + }, + + // private + createFormat : function(format) { + var code = [], + special = false, + ch = '', + i; + + for (i = 0; i < format.length; ++i) { + ch = format.charAt(i); + if (!special && ch == "\\") { + special = true; + } else if (special) { + special = false; + code.push("'" + Ext.String.escape(ch) + "'"); + } else { + code.push(utilDate.getFormatCode(ch)); + } + } + utilDate.formatFunctions[format] = Ext.functionFactory("return " + code.join('+')); + }, + + // private + createParser : (function() { + var code = [ + "var dt, y, m, d, h, i, s, ms, o, z, zz, u, v,", + "def = Ext.Date.defaults,", + "results = String(input).match(Ext.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 = Ext.Date.clearTime(new Date);", + + // date calculations (note: these calculations create a dependency on Ext.Number.from()) + "y = Ext.Number.from(y, Ext.Number.from(def.y, dt.getFullYear()));", + "m = Ext.Number.from(m, Ext.Number.from(def.m - 1, dt.getMonth()));", + "d = Ext.Number.from(d, Ext.Number.from(def.d, dt.getDate()));", + + // time calculations (note: these calculations create a dependency on Ext.Number.from()) + "h = Ext.Number.from(h, Ext.Number.from(def.h, dt.getHours()));", + "i = Ext.Number.from(i, Ext.Number.from(def.i, dt.getMinutes()));", + "s = Ext.Number.from(s, Ext.Number.from(def.s, dt.getSeconds()));", + "ms = Ext.Number.from(ms, Ext.Number.from(def.ms, dt.getMilliseconds()));", + + "if(z >= 0 && y >= 0){", + // both the year and zero-based day of year are defined and >= 0. + // these 2 values alone provide sufficient info to create a full date object + + // create Date object representing January 1st for the given year + // handle years < 100 appropriately + "v = Ext.Date.add(new Date(y < 100 ? 100 : y, 0, 1, h, i, s, ms), Ext.Date.YEAR, y < 100 ? y - 100 : 0);", + + // then add day of year, checking for Date "rollover" if necessary + "v = !strict? v : (strict === true && (z <= 364 || (Ext.Date.isLeapYear(v) && z <= 365))? Ext.Date.add(v, Ext.Date.DAY, z) : null);", + "}else if(strict === true && !Ext.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 + // handle years < 100 properly + "v = Ext.Date.add(new Date(y < 100 ? 100 : y, m, d, h, i, s, ms), Ext.Date.YEAR, y < 100 ? y - 100 : 0);", + "}", + "}", + "}", + + "if(v){", + // favour UTC offset over GMT offset + "if(zz != null){", + // reset to UTC, then add offset + "v = Ext.Date.add(v, Ext.Date.SECOND, -v.getTimezoneOffset() * 60 - zz);", + "}else if(o){", + // reset to GMT, then add offset + "v = Ext.Date.add(v, Ext.Date.MINUTE, -v.getTimezoneOffset() + (sn == '+'? -1 : 1) * (hr * 60 + mn));", + "}", + "}", + + "return v;" + ].join('\n'); + + return function(format) { + var regexNum = utilDate.parseRegexes.length, + currentGroup = 1, + calc = [], + regex = [], + special = false, + ch = "", + i = 0, + len = format.length, + atEnd = [], + obj; + + for (; i < len; ++i) { + ch = format.charAt(i); + if (!special && ch == "\\") { + special = true; + } else if (special) { + special = false; + regex.push(Ext.String.escape(ch)); + } else { + obj = utilDate.formatCodeToRegex(ch, currentGroup); + currentGroup += obj.g; + regex.push(obj.s); + if (obj.g && obj.c) { + if (obj.calcAtEnd) { + atEnd.push(obj.c); + } else { + calc.push(obj.c); + } + } + } + } + + calc = calc.concat(atEnd); + + utilDate.parseRegexes[regexNum] = new RegExp("^" + regex.join('') + "$", 'i'); + utilDate.parseFunctions[format] = Ext.functionFactory("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:"(3[0-1]|[1-2][0-9]|0[1-9])" // day of month with leading zeroes (01 - 31) + }, + j: { + g:1, + c:"d = parseInt(results[{0}], 10);\n", + s:"(3[0-1]|[1-2][0-9]|[1-9])" // day of month without leading zeroes (1 - 31) + }, + D: function() { + for (var a = [], i = 0; i < 7; a.push(utilDate.getShortDayName(i)), ++i); // get localised short day names + return { + g:0, + c:null, + s:"(?:" + a.join("|") +")" + }; + }, + l: function() { + return { + g:0, + c:null, + s:"(?:" + utilDate.dayNames.join("|") + ")" + }; + }, + N: { + g:0, + c:null, + s:"[1-7]" // ISO-8601 day number (1 (monday) - 7 (sunday)) + }, + // + S: { + g:0, + c:null, + s:"(?:st|nd|rd|th)" + }, + // + w: { + g:0, + c:null, + s:"[0-6]" // javascript day number (0 (sunday) - 6 (saturday)) + }, + z: { + g:1, + c:"z = parseInt(results[{0}], 10);\n", + s:"(\\d{1,3})" // day of the year (0 - 364 (365 in leap years)) + }, + W: { + g:0, + c:null, + s:"(?:\\d{2})" // ISO-8601 week number (with leading zero) + }, + F: function() { + return { + g:1, + c:"m = parseInt(Ext.Date.getMonthNumber(results[{0}]), 10);\n", // get localised month number + s:"(" + utilDate.monthNames.join("|") + ")" + }; + }, + M: function() { + for (var a = [], i = 0; i < 12; a.push(utilDate.getShortMonthName(i)), ++i); // get localised short month names + return Ext.applyIf({ + s:"(" + a.join("|") + ")" + }, utilDate.formatCodeToRegex("F")); + }, + m: { + g:1, + c:"m = parseInt(results[{0}], 10) - 1;\n", + s:"(1[0-2]|0[1-9])" // month number with leading zeros (01 - 12) + }, + n: { + g:1, + c:"m = parseInt(results[{0}], 10) - 1;\n", + s:"(1[0-2]|[1-9])" // 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 utilDate.formatCodeToRegex("Y"); + }, + Y: { + g:1, + c:"y = parseInt(results[{0}], 10);\n", + s:"(\\d{4})" // 4-digit year + }, + y: { + g:1, + c:"var ty = parseInt(results[{0}], 10);\n" + + "y = ty > Ext.Date.y2kYear ? 1900 + ty : 2000 + ty;\n", // 2-digit year + s:"(\\d{1,2})" + }, + /* + * In the am/pm parsing routines, we allow both upper and lower case + * even though it doesn't exactly match the spec. It gives much more flexibility + * in being able to specify case insensitive regexes. + */ + // + a: { + 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)", + calcAtEnd: true + }, + // + // + A: { + 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)", + calcAtEnd: true + }, + // + g: { + g:1, + c:"h = parseInt(results[{0}], 10);\n", + s:"(1[0-2]|[0-9])" // 12-hr format of an hour without leading zeroes (1 - 12) + }, + G: { + g:1, + c:"h = parseInt(results[{0}], 10);\n", + s:"(2[0-3]|1[0-9]|[0-9])" // 24-hr format of an hour without leading zeroes (0 - 23) + }, + h: { + g:1, + c:"h = parseInt(results[{0}], 10);\n", + s:"(1[0-2]|0[1-9])" // 12-hr format of an hour with leading zeroes (01 - 12) + }, + H: { + g:1, + c:"h = parseInt(results[{0}], 10);\n", + s:"(2[0-3]|[0-1][0-9])" // 24-hr format of an hour with leading zeroes (00 - 23) + }, + i: { + g:1, + c:"i = parseInt(results[{0}], 10);\n", + s:"([0-5][0-9])" // minutes with leading zeros (00 - 59) + }, + s: { + g:1, + c:"s = parseInt(results[{0}], 10);\n", + s:"([0-5][0-9])" // seconds with leading zeros (00 - 59) + }, + u: { + g:1, + c:"ms = results[{0}]; ms = parseInt(ms, 10)/Math.pow(10, ms.length - 3);\n", + s:"(\\d+)" // decimal fraction of a second (minimum = 1 digit, maximum = unlimited) + }, + O: { + g:1, + c:[ + "o = results[{0}];", + "var sn = o.substring(0,1),", // get + / - sign + "hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60),", // get hours (performs minutes-to-hour conversion also, just in case) + "mn = o.substring(3,5) % 60;", // get minutes + "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))? (sn + Ext.String.leftPad(hr, 2, '0') + Ext.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 + Ext.String.leftPad(hr, 2, '0') + Ext.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 = [ + utilDate.formatCodeToRegex("Y", 1), // year + utilDate.formatCodeToRegex("m", 2), // month + utilDate.formatCodeToRegex("d", 3), // day + utilDate.formatCodeToRegex("H", 4), // hour + utilDate.formatCodeToRegex("i", 5), // minute + utilDate.formatCodeToRegex("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){", + utilDate.formatCodeToRegex("P", 8).c, // timezone offset with colon separator + "}else{", + utilDate.formatCodeToRegex("O", 8).c, // timezone offset without colon separator + "}", + "}" + ].join('\n')} + ], + i, + l; + + for (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 + } + }, + + //Old Ext.Date prototype methods. + // private + dateFormat: function(date, format) { + return utilDate.format(date, format); + }, + + /** + * Compares if two dates are equal by comparing their values. + * @param {Date} date1 + * @param {Date} date2 + * @return {Boolean} True if the date values are equal + */ + isEqual: function(date1, date2) { + // check we have 2 date objects + if (date1 && date2) { + return (date1.getTime() === date2.getTime()); + } + // one or both isn't a date, only equal if both are falsey + return !(date1 || date2); + }, + + /** + * Formats a date given the supplied format string. + * @param {Date} date The date to format + * @param {String} format The format string + * @return {String} The formatted date or an empty string if date parameter is not a JavaScript Date object + */ + format: function(date, format) { + var formatFunctions = utilDate.formatFunctions; + + if (!Ext.isDate(date)) { + return ''; + } + + if (formatFunctions[format] == null) { + utilDate.createFormat(format); + } + + return formatFunctions[format].call(date) + ''; + }, + + /** + * 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. + * @param {Date} date The date + * @return {String} The abbreviated timezone name (e.g. 'CST', 'PDT', 'EDT', 'MPST' ...). + */ + getTimezone : function(date) { + // 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 date.toString().replace(/^.* (?:\((.*)\)|([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?)$/, "$1$2").replace(/[^A-Z]/g, ""); + }, + + /** + * Get the offset from GMT of the current date (equivalent to the format specifier 'O'). + * @param {Date} date The date + * @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(date, colon) { + var offset = date.getTimezoneOffset(); + return (offset > 0 ? "-" : "+") + + Ext.String.leftPad(Math.floor(Math.abs(offset) / 60), 2, "0") + + (colon ? ":" : "") + + Ext.String.leftPad(Math.abs(offset % 60), 2, "0"); + }, + + /** + * Get the numeric day number of the year, adjusted for leap year. + * @param {Date} date The date + * @return {Number} 0 to 364 (365 in leap years). + */ + getDayOfYear: function(date) { + var num = 0, + d = Ext.Date.clone(date), + m = date.getMonth(), + i; + + for (i = 0, d.setDate(1), d.setMonth(0); i < m; d.setMonth(++i)) { + num += utilDate.getDaysInMonth(d); + } + return num + date.getDate() - 1; + }, + + /** + * Get the numeric ISO-8601 week number of the year. + * (equivalent to the format specifier 'W', but without a leading zero). + * @param {Date} date The date + * @return {Number} 1 to 53 + * @method + */ + getWeekOfYear : (function() { + // adapted from http://www.merlyn.demon.co.uk/weekcalc.htm + var ms1d = 864e5, // milliseconds in a day + ms7d = 7 * ms1d; // milliseconds in a week + + return function(date) { // return a closure so constants get calculated only once + var DC3 = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate() + 3) / ms1d, // an Absolute Day Number + AWN = Math.floor(DC3 / 7), // an Absolute Week Number + Wyr = new Date(AWN * ms7d).getUTCFullYear(); + + return AWN - Math.floor(Date.UTC(Wyr, 0, 7) / ms7d) + 1; + }; + }()), + + /** + * Checks if the current date falls within a leap year. + * @param {Date} date The date + * @return {Boolean} True if the current date falls within a leap year, false otherwise. + */ + isLeapYear : function(date) { + var year = date.getFullYear(); + return !!((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year))); + }, + + /** + * Get the first day of the current month, adjusted for leap year. The returned value + * is the numeric day index within the week (0-6) which can be used in conjunction with + * the {@link #monthNames} array to retrieve the textual day name. + * Example: + *
    
    +var dt = new Date('1/10/2007'),
    +    firstDay = Ext.Date.getFirstDayOfMonth(dt);
    +console.log(Ext.Date.dayNames[firstDay]); //output: 'Monday'
    +     * 
    + * @param {Date} date The date + * @return {Number} The day number (0-6). + */ + getFirstDayOfMonth : function(date) { + var day = (date.getDay() - (date.getDate() - 1)) % 7; + return (day < 0) ? (day + 7) : day; + }, + + /** + * Get the last day of the current month, adjusted for leap year. The returned value + * is the numeric day index within the week (0-6) which can be used in conjunction with + * the {@link #monthNames} array to retrieve the textual day name. + * Example: + *
    
    +var dt = new Date('1/10/2007'),
    +    lastDay = Ext.Date.getLastDayOfMonth(dt);
    +console.log(Ext.Date.dayNames[lastDay]); //output: 'Wednesday'
    +     * 
    + * @param {Date} date The date + * @return {Number} The day number (0-6). + */ + getLastDayOfMonth : function(date) { + return utilDate.getLastDateOfMonth(date).getDay(); + }, + + + /** + * Get the date of the first day of the month in which this date resides. + * @param {Date} date The date + * @return {Date} + */ + getFirstDateOfMonth : function(date) { + return new Date(date.getFullYear(), date.getMonth(), 1); + }, + + /** + * Get the date of the last day of the month in which this date resides. + * @param {Date} date The date + * @return {Date} + */ + getLastDateOfMonth : function(date) { + return new Date(date.getFullYear(), date.getMonth(), utilDate.getDaysInMonth(date)); + }, + + /** + * Get the number of days in the current month, adjusted for leap year. + * @param {Date} date The date + * @return {Number} The number of days in the month. + * @method + */ + getDaysInMonth: (function() { + var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + + return function(date) { // return a closure for efficiency + var m = date.getMonth(); + + return m == 1 && utilDate.isLeapYear(date) ? 29 : daysInMonth[m]; + }; + }()), + + // + /** + * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S'). + * @param {Date} date The date + * @return {String} 'st, 'nd', 'rd' or 'th'. + */ + getSuffix : function(date) { + switch (date.getDate()) { + case 1: + case 21: + case 31: + return "st"; + case 2: + case 22: + return "nd"; + case 3: + case 23: + return "rd"; + default: + return "th"; + } + }, + // + + /** + * Creates and returns a new Date instance with the exact same date value as the called instance. + * Dates are copied and passed by reference, so if a copied date variable is modified later, the original + * variable will also be changed. When the intention is to create a new variable that will not + * modify the original instance, you should create a clone. + * + * Example of correctly cloning a date: + *
    
    +//wrong way:
    +var orig = new Date('10/1/2006');
    +var copy = orig;
    +copy.setDate(5);
    +console.log(orig);  //returns 'Thu Oct 05 2006'!
    +
    +//correct way:
    +var orig = new Date('10/1/2006'),
    +    copy = Ext.Date.clone(orig);
    +copy.setDate(5);
    +console.log(orig);  //returns 'Thu Oct 01 2006'
    +     * 
    + * @param {Date} date The date + * @return {Date} The new Date instance. + */ + clone : function(date) { + return new Date(date.getTime()); + }, + + /** + * Checks if the current date is affected by Daylight Saving Time (DST). + * @param {Date} date The date + * @return {Boolean} True if the current date is affected by DST. + */ + isDST : function(date) { + // adapted from http://sencha.com/forum/showthread.php?p=247172#post247172 + // courtesy of @geoffrey.mcgill + return new Date(date.getFullYear(), 0, 1).getTimezoneOffset() != date.getTimezoneOffset(); + }, + + /** + * Attempts to clear all time information from this Date by setting the time to midnight of the same day, + * automatically adjusting for Daylight Saving Time (DST) where applicable. + * (note: DST timezone information for the browser's host operating system is assumed to be up-to-date) + * @param {Date} date The 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(date, clone) { + if (clone) { + return Ext.Date.clearTime(Ext.Date.clone(date)); + } + + // get current date before clearing time + var d = date.getDate(), + hr, + c; + + // clear time + date.setHours(0); + date.setMinutes(0); + date.setSeconds(0); + date.setMilliseconds(0); + + if (date.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 (hr = 1, c = utilDate.add(date, Ext.Date.HOUR, hr); c.getDate() != d; hr++, c = utilDate.add(date, Ext.Date.HOUR, hr)); + + date.setDate(d); + date.setHours(c.getHours()); + } + + return date; + }, + + /** + * 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 = Ext.Date.add(new Date('10/29/2006'), Ext.Date.DAY, 5);
    +console.log(dt); //returns 'Fri Nov 03 2006 00:00:00'
    +
    +// Negative values will be subtracted:
    +var dt2 = Ext.Date.add(new Date('10/1/2006'), Ext.Date.DAY, -5);
    +console.log(dt2); //returns 'Tue Sep 26 2006 00:00:00'
    +
    +     * 
    + * + * @param {Date} date The date to modify + * @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(date, interval, value) { + var d = Ext.Date.clone(date), + Date = Ext.Date, + day; + if (!interval || value === 0) { + return d; + } + + switch(interval.toLowerCase()) { + case Ext.Date.MILLI: + d.setMilliseconds(d.getMilliseconds() + value); + break; + case Ext.Date.SECOND: + d.setSeconds(d.getSeconds() + value); + break; + case Ext.Date.MINUTE: + d.setMinutes(d.getMinutes() + value); + break; + case Ext.Date.HOUR: + d.setHours(d.getHours() + value); + break; + case Ext.Date.DAY: + d.setDate(d.getDate() + value); + break; + case Ext.Date.MONTH: + day = date.getDate(); + if (day > 28) { + day = Math.min(day, Ext.Date.getLastDateOfMonth(Ext.Date.add(Ext.Date.getFirstDateOfMonth(date), Ext.Date.MONTH, value)).getDate()); + } + d.setDate(day); + d.setMonth(date.getMonth() + value); + break; + case Ext.Date.YEAR: + day = date.getDate(); + if (day > 28) { + day = Math.min(day, Ext.Date.getLastDateOfMonth(Ext.Date.add(Ext.Date.getFirstDateOfMonth(date), Ext.Date.YEAR, value)).getDate()); + } + d.setDate(day); + d.setFullYear(date.getFullYear() + value); + break; + } + return d; + }, + + /** + * Checks if a date falls on or between the given start and end dates. + * @param {Date} date The date to check + * @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(date, start, end) { + var t = date.getTime(); + return start.getTime() <= t && t <= end.getTime(); + }, + + //Maintains compatibility with old static and prototype window.Date methods. + compat: function() { + var nativeDate = window.Date, + p, u, + statics = ['useStrict', 'formatCodeToRegex', 'parseFunctions', 'parseRegexes', 'formatFunctions', 'y2kYear', 'MILLI', 'SECOND', 'MINUTE', 'HOUR', 'DAY', 'MONTH', 'YEAR', 'defaults', 'dayNames', 'monthNames', 'monthNumbers', 'getShortMonthName', 'getShortDayName', 'getMonthNumber', 'formatCodes', 'isValid', 'parseDate', 'getFormatCode', 'createFormat', 'createParser', 'parseCodes'], + proto = ['dateFormat', 'format', 'getTimezone', 'getGMTOffset', 'getDayOfYear', 'getWeekOfYear', 'isLeapYear', 'getFirstDayOfMonth', 'getLastDayOfMonth', 'getDaysInMonth', 'getSuffix', 'clone', 'isDST', 'clearTime', 'add', 'between'], + sLen = statics.length, + pLen = proto.length, + stat, prot, s; + + //Append statics + for (s = 0; s < sLen; s++) { + stat = statics[s]; + nativeDate[stat] = utilDate[stat]; + } + + //Append to prototype + for (p = 0; p < pLen; p++) { + prot = proto[p]; + nativeDate.prototype[prot] = function() { + var args = Array.prototype.slice.call(arguments); + args.unshift(this); + return utilDate[prot].apply(utilDate, args); + }; + } + } +}; + +var utilDate = Ext.Date; + +}()); + +/** + * @author Jacky Nguyen + * @docauthor Jacky Nguyen + * @class Ext.Base + * + * The root of all classes created with {@link Ext#define}. + * + * Ext.Base is the building block of all Ext classes. All classes in Ext inherit from Ext.Base. + * All prototype and static members of this class are inherited by all other classes. + */ +(function(flexSetter) { + +var noArgs = [], + Base = function(){}; + + // These static properties will be copied to every newly created class with {@link Ext#define} + Ext.apply(Base, { + $className: 'Ext.Base', + + $isClass: true, + + /** + * Create a new instance of this Class. + * + * Ext.define('My.cool.Class', { + * ... + * }); + * + * My.cool.Class.create({ + * someConfig: true + * }); + * + * All parameters are passed to the constructor of the class. + * + * @return {Object} the created instance. + * @static + * @inheritable + */ + create: function() { + return Ext.create.apply(Ext, [this].concat(Array.prototype.slice.call(arguments, 0))); + }, + + /** + * @private + * @param config + */ + extend: function(parent) { + var parentPrototype = parent.prototype, + basePrototype, prototype, i, ln, name, statics; + + prototype = this.prototype = Ext.Object.chain(parentPrototype); + prototype.self = this; + + this.superclass = prototype.superclass = parentPrototype; + + if (!parent.$isClass) { + basePrototype = Ext.Base.prototype; + + for (i in basePrototype) { + if (i in prototype) { + prototype[i] = basePrototype[i]; + } + } + } + + // Statics inheritance + statics = parentPrototype.$inheritableStatics; + + if (statics) { + for (i = 0,ln = statics.length; i < ln; i++) { + name = statics[i]; + + if (!this.hasOwnProperty(name)) { + this[name] = parent[name]; + } + } + } + + if (parent.$onExtended) { + this.$onExtended = parent.$onExtended.slice(); + } + + prototype.config = new prototype.configClass(); + prototype.initConfigList = prototype.initConfigList.slice(); + prototype.initConfigMap = Ext.clone(prototype.initConfigMap); + prototype.configMap = Ext.Object.chain(prototype.configMap); + }, + + /** + * @private + */ + $onExtended: [], + + /** + * @private + */ + triggerExtended: function() { + var callbacks = this.$onExtended, + ln = callbacks.length, + i, callback; + + if (ln > 0) { + for (i = 0; i < ln; i++) { + callback = callbacks[i]; + callback.fn.apply(callback.scope || this, arguments); + } + } + }, + + /** + * @private + */ + onExtended: function(fn, scope) { + this.$onExtended.push({ + fn: fn, + scope: scope + }); + + return this; + }, + + /** + * @private + * @param config + */ + addConfig: function(config, fullMerge) { + var prototype = this.prototype, + configNameCache = Ext.Class.configNameCache, + hasConfig = prototype.configMap, + initConfigList = prototype.initConfigList, + initConfigMap = prototype.initConfigMap, + defaultConfig = prototype.config, + initializedName, name, value; + + for (name in config) { + if (config.hasOwnProperty(name)) { + if (!hasConfig[name]) { + hasConfig[name] = true; + } + + value = config[name]; + + initializedName = configNameCache[name].initialized; + + if (!initConfigMap[name] && value !== null && !prototype[initializedName]) { + initConfigMap[name] = true; + initConfigList.push(name); + } + } + } + + if (fullMerge) { + Ext.merge(defaultConfig, config); + } + else { + Ext.mergeIf(defaultConfig, config); + } + + prototype.configClass = Ext.Object.classify(defaultConfig); + }, + + /** + * Add / override static properties of this class. + * + * Ext.define('My.cool.Class', { + * ... + * }); + * + * My.cool.Class.addStatics({ + * someProperty: 'someValue', // My.cool.Class.someProperty = 'someValue' + * method1: function() { ... }, // My.cool.Class.method1 = function() { ... }; + * method2: function() { ... } // My.cool.Class.method2 = function() { ... }; + * }); + * + * @param {Object} members + * @return {Ext.Base} this + * @static + * @inheritable + */ + addStatics: function(members) { + var member, name; + + for (name in members) { + if (members.hasOwnProperty(name)) { + member = members[name]; + if (typeof member == 'function') { + member.displayName = Ext.getClassName(this) + '.' + name; + } + this[name] = member; + } + } + + return this; + }, + + /** + * @private + * @param {Object} members + */ + addInheritableStatics: function(members) { + var inheritableStatics, + hasInheritableStatics, + prototype = this.prototype, + name, member; + + inheritableStatics = prototype.$inheritableStatics; + hasInheritableStatics = prototype.$hasInheritableStatics; + + if (!inheritableStatics) { + inheritableStatics = prototype.$inheritableStatics = []; + hasInheritableStatics = prototype.$hasInheritableStatics = {}; + } + + for (name in members) { + if (members.hasOwnProperty(name)) { + member = members[name]; + if (typeof member == 'function') { + member.displayName = Ext.getClassName(this) + '.' + name; + } + this[name] = member; + + if (!hasInheritableStatics[name]) { + hasInheritableStatics[name] = true; + inheritableStatics.push(name); + } + } + } + + return this; + }, + + /** + * Add methods / properties to the prototype of this class. + * + * Ext.define('My.awesome.Cat', { + * constructor: function() { + * ... + * } + * }); + * + * My.awesome.Cat.implement({ + * meow: function() { + * alert('Meowww...'); + * } + * }); + * + * var kitty = new My.awesome.Cat; + * kitty.meow(); + * + * @param {Object} members + * @static + * @inheritable + */ + addMembers: function(members) { + var prototype = this.prototype, + enumerables = Ext.enumerables, + names = [], + i, ln, name, member; + + for (name in members) { + names.push(name); + } + + if (enumerables) { + names.push.apply(names, enumerables); + } + + for (i = 0,ln = names.length; i < ln; i++) { + name = names[i]; + + if (members.hasOwnProperty(name)) { + member = members[name]; + + if (typeof member == 'function' && !member.$isClass && member !== Ext.emptyFn) { + member.$owner = this; + member.$name = name; + member.displayName = (this.$className || '') + '#' + name; + } + + prototype[name] = member; + } + } + + return this; + }, + + /** + * @private + * @param name + * @param member + */ + addMember: function(name, member) { + if (typeof member == 'function' && !member.$isClass && member !== Ext.emptyFn) { + member.$owner = this; + member.$name = name; + member.displayName = (this.$className || '') + '#' + name; + } + + this.prototype[name] = member; + + return this; + }, + + /** + * @private + */ + implement: function() { + this.addMembers.apply(this, arguments); + }, + + /** + * Borrow another class' members to the prototype of this class. + * + * Ext.define('Bank', { + * money: '$$$', + * printMoney: function() { + * alert('$$$$$$$'); + * } + * }); + * + * Ext.define('Thief', { + * ... + * }); + * + * Thief.borrow(Bank, ['money', 'printMoney']); + * + * var steve = new Thief(); + * + * alert(steve.money); // alerts '$$$' + * steve.printMoney(); // alerts '$$$$$$$' + * + * @param {Ext.Base} fromClass The class to borrow members from + * @param {Array/String} members The names of the members to borrow + * @return {Ext.Base} this + * @static + * @inheritable + * @private + */ + borrow: function(fromClass, members) { + var prototype = this.prototype, + fromPrototype = fromClass.prototype, + className = Ext.getClassName(this), + i, ln, name, fn, toBorrow; + + members = Ext.Array.from(members); + + for (i = 0,ln = members.length; i < ln; i++) { + name = members[i]; + + toBorrow = fromPrototype[name]; + + if (typeof toBorrow == 'function') { + fn = Ext.Function.clone(toBorrow); + + if (className) { + fn.displayName = className + '#' + name; + } + + fn.$owner = this; + fn.$name = name; + + prototype[name] = fn; + } + else { + prototype[name] = toBorrow; + } + } + + return this; + }, + + /** + * Override members of this class. Overridden methods can be invoked via + * {@link Ext.Base#callParent}. + * + * Ext.define('My.Cat', { + * constructor: function() { + * alert("I'm a cat!"); + * } + * }); + * + * My.Cat.override({ + * constructor: function() { + * alert("I'm going to be a cat!"); + * + * this.callParent(arguments); + * + * alert("Meeeeoooowwww"); + * } + * }); + * + * var kitty = new My.Cat(); // alerts "I'm going to be a cat!" + * // alerts "I'm a cat!" + * // alerts "Meeeeoooowwww" + * + * As of 4.1, direct use of this method is deprecated. Use {@link Ext#define Ext.define} + * instead: + * + * Ext.define('My.CatOverride', { + * override: 'My.Cat', + * constructor: function() { + * alert("I'm going to be a cat!"); + * + * this.callParent(arguments); + * + * alert("Meeeeoooowwww"); + * } + * }); + * + * The above accomplishes the same result but can be managed by the {@link Ext.Loader} + * which can properly order the override and its target class and the build process + * can determine whether the override is needed based on the required state of the + * target class (My.Cat). + * + * @param {Object} members The properties to add to this class. This should be + * specified as an object literal containing one or more properties. + * @return {Ext.Base} this class + * @static + * @inheritable + * @markdown + * @deprecated 4.1.0 Use {@link Ext#define Ext.define} instead + */ + override: function(members) { + var me = this, + enumerables = Ext.enumerables, + target = me.prototype, + cloneFunction = Ext.Function.clone, + name, index, member, statics, names, previous; + + if (arguments.length === 2) { + name = members; + members = {}; + members[name] = arguments[1]; + enumerables = null; + } + + do { + names = []; // clean slate for prototype (1st pass) and static (2nd pass) + statics = null; // not needed 1st pass, but needs to be cleared for 2nd pass + + for (name in members) { // hasOwnProperty is checked in the next loop... + if (name == 'statics') { + statics = members[name]; + } else if (name == 'config') { + me.addConfig(members[name], true); + } else { + names.push(name); + } + } + + if (enumerables) { + names.push.apply(names, enumerables); + } + + for (index = names.length; index--; ) { + name = names[index]; + + if (members.hasOwnProperty(name)) { + member = members[name]; + + if (typeof member == 'function' && !member.$className && member !== Ext.emptyFn) { + if (typeof member.$owner != 'undefined') { + member = cloneFunction(member); + } + + if (me.$className) { + member.displayName = me.$className + '#' + name; + } + + member.$owner = me; + member.$name = name; + + previous = target[name]; + if (previous) { + member.$previous = previous; + } + } + + target[name] = member; + } + } + + target = me; // 2nd pass is for statics + members = statics; // statics will be null on 2nd pass + } while (members); + + return this; + }, + + // Documented downwards + callParent: function(args) { + var method; + + // This code is intentionally inlined for the least number of debugger stepping + return (method = this.callParent.caller) && (method.$previous || + ((method = method.$owner ? method : method.caller) && + method.$owner.superclass.$class[method.$name])).apply(this, args || noArgs); + }, + + /** + * Used internally by the mixins pre-processor + * @private + * @inheritable + */ + mixin: function(name, mixinClass) { + var mixin = mixinClass.prototype, + prototype = this.prototype, + key; + + if (typeof mixin.onClassMixedIn != 'undefined') { + mixin.onClassMixedIn.call(mixinClass, this); + } + + if (!prototype.hasOwnProperty('mixins')) { + if ('mixins' in prototype) { + prototype.mixins = Ext.Object.chain(prototype.mixins); + } + else { + prototype.mixins = {}; + } + } + + for (key in mixin) { + if (key === 'mixins') { + Ext.merge(prototype.mixins, mixin[key]); + } + else if (typeof prototype[key] == 'undefined' && key != 'mixinId' && key != 'config') { + prototype[key] = mixin[key]; + } + } + + if ('config' in mixin) { + this.addConfig(mixin.config, false); + } + + prototype.mixins[name] = mixin; + }, + + /** + * Get the current class' name in string format. + * + * Ext.define('My.cool.Class', { + * constructor: function() { + * alert(this.self.getName()); // alerts 'My.cool.Class' + * } + * }); + * + * My.cool.Class.getName(); // 'My.cool.Class' + * + * @return {String} className + * @static + * @inheritable + */ + getName: function() { + return Ext.getClassName(this); + }, + + /** + * Create aliases for existing prototype methods. Example: + * + * Ext.define('My.cool.Class', { + * method1: function() { ... }, + * method2: function() { ... } + * }); + * + * var test = new My.cool.Class(); + * + * My.cool.Class.createAlias({ + * method3: 'method1', + * method4: 'method2' + * }); + * + * test.method3(); // test.method1() + * + * My.cool.Class.createAlias('method5', 'method3'); + * + * test.method5(); // test.method3() -> test.method1() + * + * @param {String/Object} alias The new method name, or an object to set multiple aliases. See + * {@link Ext.Function#flexSetter flexSetter} + * @param {String/Object} origin The original method name + * @static + * @inheritable + * @method + */ + createAlias: flexSetter(function(alias, origin) { + this.override(alias, function() { + return this[origin].apply(this, arguments); + }); + }), + + /** + * @private + */ + addXtype: function(xtype) { + var prototype = this.prototype, + xtypesMap = prototype.xtypesMap, + xtypes = prototype.xtypes, + xtypesChain = prototype.xtypesChain; + + if (!prototype.hasOwnProperty('xtypesMap')) { + xtypesMap = prototype.xtypesMap = Ext.merge({}, prototype.xtypesMap || {}); + xtypes = prototype.xtypes = prototype.xtypes ? [].concat(prototype.xtypes) : []; + xtypesChain = prototype.xtypesChain = prototype.xtypesChain ? [].concat(prototype.xtypesChain) : []; + prototype.xtype = xtype; + } + + if (!xtypesMap[xtype]) { + xtypesMap[xtype] = true; + xtypes.push(xtype); + xtypesChain.push(xtype); + Ext.ClassManager.setAlias(this, 'widget.' + xtype); + } + + return this; + } + }); + + Base.implement({ + isInstance: true, + + $className: 'Ext.Base', + + configClass: Ext.emptyFn, + + initConfigList: [], + + configMap: {}, + + initConfigMap: {}, + + /** + * Get the reference to the class from which this object was instantiated. Note that unlike {@link Ext.Base#self}, + * `this.statics()` is scope-independent and it always returns the class from which it was called, regardless of what + * `this` points to during run-time + * + * Ext.define('My.Cat', { + * statics: { + * totalCreated: 0, + * speciesName: 'Cat' // My.Cat.speciesName = 'Cat' + * }, + * + * constructor: function() { + * var statics = this.statics(); + * + * alert(statics.speciesName); // always equals to 'Cat' no matter what 'this' refers to + * // equivalent to: My.Cat.speciesName + * + * alert(this.self.speciesName); // dependent on 'this' + * + * statics.totalCreated++; + * }, + * + * clone: function() { + * var cloned = new this.self; // dependent on 'this' + * + * cloned.groupName = this.statics().speciesName; // equivalent to: My.Cat.speciesName + * + * return cloned; + * } + * }); + * + * + * Ext.define('My.SnowLeopard', { + * extend: 'My.Cat', + * + * statics: { + * speciesName: 'Snow Leopard' // My.SnowLeopard.speciesName = 'Snow Leopard' + * }, + * + * constructor: function() { + * this.callParent(); + * } + * }); + * + * var cat = new My.Cat(); // alerts 'Cat', then alerts 'Cat' + * + * var snowLeopard = new My.SnowLeopard(); // alerts 'Cat', then alerts 'Snow Leopard' + * + * var clone = snowLeopard.clone(); + * alert(Ext.getClassName(clone)); // alerts 'My.SnowLeopard' + * alert(clone.groupName); // alerts 'Cat' + * + * alert(My.Cat.totalCreated); // alerts 3 + * + * @protected + * @return {Ext.Class} + */ + statics: function() { + var method = this.statics.caller, + self = this.self; + + if (!method) { + return self; + } + + return method.$owner; + }, + + /** + * Call the "parent" method of the current method. That is the method previously + * overridden by derivation or by an override (see {@link Ext#define}). + * + * Ext.define('My.Base', { + * constructor: function (x) { + * this.x = x; + * }, + * + * statics: { + * method: function (x) { + * return x; + * } + * } + * }); + * + * Ext.define('My.Derived', { + * extend: 'My.Base', + * + * constructor: function () { + * this.callParent([21]); + * } + * }); + * + * var obj = new My.Derived(); + * + * alert(obj.x); // alerts 21 + * + * This can be used with an override as follows: + * + * Ext.define('My.DerivedOverride', { + * override: 'My.Derived', + * + * constructor: function (x) { + * this.callParent([x*2]); // calls original My.Derived constructor + * } + * }); + * + * var obj = new My.Derived(); + * + * alert(obj.x); // now alerts 42 + * + * This also works with static methods. + * + * Ext.define('My.Derived2', { + * extend: 'My.Base', + * + * statics: { + * method: function (x) { + * return this.callParent([x*2]); // calls My.Base.method + * } + * } + * }); + * + * alert(My.Base.method(10); // alerts 10 + * alert(My.Derived2.method(10); // alerts 20 + * + * Lastly, it also works with overridden static methods. + * + * Ext.define('My.Derived2Override', { + * override: 'My.Derived2', + * + * statics: { + * method: function (x) { + * return this.callParent([x*2]); // calls My.Derived2.method + * } + * } + * }); + * + * alert(My.Derived2.method(10); // now alerts 40 + * + * @protected + * @param {Array/Arguments} args The arguments, either an array or the `arguments` object + * from the current method, for example: `this.callParent(arguments)` + * @return {Object} Returns the result of calling the parent method + */ + callParent: function(args) { + // NOTE: this code is deliberately as few expressions (and no function calls) + // as possible so that a debugger can skip over this noise with the minimum number + // of steps. Basically, just hit Step Into until you are where you really wanted + // to be. + var method, + superMethod = (method = this.callParent.caller) && (method.$previous || + ((method = method.$owner ? method : method.caller) && + method.$owner.superclass[method.$name])); + + if (!superMethod) { + method = this.callParent.caller; + var parentClass, methodName; + + if (!method.$owner) { + if (!method.caller) { + throw new Error("Attempting to call a protected method from the public scope, which is not allowed"); + } + + method = method.caller; + } + + parentClass = method.$owner.superclass; + methodName = method.$name; + + if (!(methodName in parentClass)) { + throw new Error("this.callParent() was called but there's no such method (" + methodName + + ") found in the parent class (" + (Ext.getClassName(parentClass) || 'Object') + ")"); + } + } + + return superMethod.apply(this, args || noArgs); + }, + + /** + * @property {Ext.Class} self + * + * Get the reference to the current class from which this object was instantiated. Unlike {@link Ext.Base#statics}, + * `this.self` is scope-dependent and it's meant to be used for dynamic inheritance. See {@link Ext.Base#statics} + * for a detailed comparison + * + * Ext.define('My.Cat', { + * statics: { + * speciesName: 'Cat' // My.Cat.speciesName = 'Cat' + * }, + * + * constructor: function() { + * alert(this.self.speciesName); // dependent on 'this' + * }, + * + * clone: function() { + * return new this.self(); + * } + * }); + * + * + * Ext.define('My.SnowLeopard', { + * extend: 'My.Cat', + * statics: { + * speciesName: 'Snow Leopard' // My.SnowLeopard.speciesName = 'Snow Leopard' + * } + * }); + * + * var cat = new My.Cat(); // alerts 'Cat' + * var snowLeopard = new My.SnowLeopard(); // alerts 'Snow Leopard' + * + * var clone = snowLeopard.clone(); + * alert(Ext.getClassName(clone)); // alerts 'My.SnowLeopard' + * + * @protected + */ + self: Base, + + // Default constructor, simply returns `this` + constructor: function() { + return this; + }, + + /** + * Initialize configuration for this class. a typical example: + * + * Ext.define('My.awesome.Class', { + * // The default config + * config: { + * name: 'Awesome', + * isAwesome: true + * }, + * + * constructor: function(config) { + * this.initConfig(config); + * } + * }); + * + * var awesome = new My.awesome.Class({ + * name: 'Super Awesome' + * }); + * + * alert(awesome.getName()); // 'Super Awesome' + * + * @protected + * @param {Object} config + * @return {Object} mixins The mixin prototypes as key - value pairs + */ + initConfig: function(config) { + var instanceConfig = config, + configNameCache = Ext.Class.configNameCache, + defaultConfig = new this.configClass(), + defaultConfigList = this.initConfigList, + hasConfig = this.configMap, + nameMap, i, ln, name, initializedName; + + this.initConfig = Ext.emptyFn; + + this.initialConfig = instanceConfig || {}; + + this.config = config = (instanceConfig) ? Ext.merge(defaultConfig, config) : defaultConfig; + + if (instanceConfig) { + defaultConfigList = defaultConfigList.slice(); + + for (name in instanceConfig) { + if (hasConfig[name]) { + if (instanceConfig[name] !== null) { + defaultConfigList.push(name); + this[configNameCache[name].initialized] = false; + } + } + } + } + + for (i = 0,ln = defaultConfigList.length; i < ln; i++) { + name = defaultConfigList[i]; + nameMap = configNameCache[name]; + initializedName = nameMap.initialized; + + if (!this[initializedName]) { + this[initializedName] = true; + this[nameMap.set].call(this, config[name]); + } + } + + return this; + }, + + /** + * @private + * @param config + */ + hasConfig: function(name) { + return Boolean(this.configMap[name]); + }, + + /** + * @private + */ + setConfig: function(config, applyIfNotSet) { + if (!config) { + return this; + } + + var configNameCache = Ext.Class.configNameCache, + currentConfig = this.config, + hasConfig = this.configMap, + initialConfig = this.initialConfig, + name, value; + + applyIfNotSet = Boolean(applyIfNotSet); + + for (name in config) { + if (applyIfNotSet && initialConfig.hasOwnProperty(name)) { + continue; + } + + value = config[name]; + currentConfig[name] = value; + + if (hasConfig[name]) { + this[configNameCache[name].set](value); + } + } + + return this; + }, + + /** + * @private + * @param name + */ + getConfig: function(name) { + var configNameCache = Ext.Class.configNameCache; + + return this[configNameCache[name].get](); + }, + + /** + * + * @param name + */ + getInitialConfig: function(name) { + var config = this.config; + + if (!name) { + return config; + } + else { + return config[name]; + } + }, + + /** + * @private + * @param names + * @param callback + * @param scope + */ + onConfigUpdate: function(names, callback, scope) { + var self = this.self, + className = self.$className, + i, ln, name, + updaterName, updater, newUpdater; + + names = Ext.Array.from(names); + + scope = scope || this; + + for (i = 0,ln = names.length; i < ln; i++) { + name = names[i]; + updaterName = 'update' + Ext.String.capitalize(name); + updater = this[updaterName] || Ext.emptyFn; + newUpdater = function() { + updater.apply(this, arguments); + scope[callback].apply(scope, arguments); + }; + newUpdater.$name = updaterName; + newUpdater.$owner = self; + newUpdater.displayName = className + '#' + updaterName; + + this[updaterName] = newUpdater; + } + }, + + destroy: function() { + this.destroy = Ext.emptyFn; + } + }); + + /** + * Call the original method that was previously overridden with {@link Ext.Base#override} + * + * Ext.define('My.Cat', { + * constructor: function() { + * alert("I'm a cat!"); + * } + * }); + * + * My.Cat.override({ + * constructor: function() { + * alert("I'm going to be a cat!"); + * + * this.callOverridden(); + * + * alert("Meeeeoooowwww"); + * } + * }); + * + * var kitty = new My.Cat(); // alerts "I'm going to be a cat!" + * // alerts "I'm a cat!" + * // alerts "Meeeeoooowwww" + * + * @param {Array/Arguments} args The arguments, either an array or the `arguments` object + * from the current method, for example: `this.callOverridden(arguments)` + * @return {Object} Returns the result of calling the overridden method + * @protected + * @deprecated as of 4.1. Use {@link #callParent} instead. + */ + Base.prototype.callOverridden = Base.prototype.callParent; + + Ext.Base = Base; + +}(Ext.Function.flexSetter)); + +/** + * @author Jacky Nguyen + * @docauthor Jacky Nguyen + * @class Ext.Class + * + * Handles class creation throughout the framework. This is a low level factory that is used by Ext.ClassManager and generally + * should not be used directly. If you choose to use Ext.Class you will lose out on the namespace, aliasing and depency loading + * features made available by Ext.ClassManager. The only time you would use Ext.Class directly is to create an anonymous class. + * + * If you wish to create a class you should use {@link Ext#define Ext.define} which aliases + * {@link Ext.ClassManager#create Ext.ClassManager.create} to enable namespacing and dynamic dependency resolution. + * + * Ext.Class is the factory and **not** the superclass of everything. For the base class that **all** Ext classes inherit + * from, see {@link Ext.Base}. + */ +(function() { + var ExtClass, + Base = Ext.Base, + baseStaticMembers = [], + baseStaticMember, baseStaticMemberLength; + + for (baseStaticMember in Base) { + if (Base.hasOwnProperty(baseStaticMember)) { + baseStaticMembers.push(baseStaticMember); + } + } + + baseStaticMemberLength = baseStaticMembers.length; + + // Creates a constructor that has nothing extra in its scope chain. + function makeCtor (className) { + function constructor () { + // Opera has some problems returning from a constructor when Dragonfly isn't running. The || null seems to + // be sufficient to stop it misbehaving. Known to be required against 10.53, 11.51 and 11.61. + return this.constructor.apply(this, arguments) || null; + } + if (className) { + constructor.displayName = className; + } + return constructor; + } + + /** + * @method constructor + * Create a new anonymous class. + * + * @param {Object} data An object represent the properties of this class + * @param {Function} onCreated Optional, the callback function to be executed when this class is fully created. + * Note that the creation process can be asynchronous depending on the pre-processors used. + * + * @return {Ext.Base} The newly created class + */ + Ext.Class = ExtClass = function(Class, data, onCreated) { + if (typeof Class != 'function') { + onCreated = data; + data = Class; + Class = null; + } + + if (!data) { + data = {}; + } + + Class = ExtClass.create(Class, data); + + ExtClass.process(Class, data, onCreated); + + return Class; + }; + + Ext.apply(ExtClass, { + /** + * @private + * @param Class + * @param data + * @param hooks + */ + onBeforeCreated: function(Class, data, hooks) { + Class.addMembers(data); + + hooks.onCreated.call(Class, Class); + }, + + /** + * @private + * @param Class + * @param classData + * @param onClassCreated + */ + create: function(Class, data) { + var name, i; + + if (!Class) { + // This "helped" a bit in IE8 when we create 450k instances (3400ms->2700ms), + // but removes some flexibility as a result because overrides cannot override + // the constructor method... kept in case we want to reconsider because it is + // more involved than just use the pass 'constructor' + // + //if (data.hasOwnProperty('constructor')) { + // Class = data.constructor; + // delete data.constructor; + // Class.$owner = Class; + // Class.$name = 'constructor'; + //} else { + Class = makeCtor( + data.$className + ); + //} + } + + for (i = 0; i < baseStaticMemberLength; i++) { + name = baseStaticMembers[i]; + Class[name] = Base[name]; + } + + return Class; + }, + + /** + * @private + * @param Class + * @param data + * @param onCreated + */ + process: function(Class, data, onCreated) { + var preprocessorStack = data.preprocessors || ExtClass.defaultPreprocessors, + registeredPreprocessors = this.preprocessors, + hooks = { + onBeforeCreated: this.onBeforeCreated + }, + preprocessors = [], + preprocessor, preprocessorsProperties, + i, ln, j, subLn, preprocessorProperty, process; + + delete data.preprocessors; + + for (i = 0,ln = preprocessorStack.length; i < ln; i++) { + preprocessor = preprocessorStack[i]; + + if (typeof preprocessor == 'string') { + preprocessor = registeredPreprocessors[preprocessor]; + preprocessorsProperties = preprocessor.properties; + + if (preprocessorsProperties === true) { + preprocessors.push(preprocessor.fn); + } + else if (preprocessorsProperties) { + for (j = 0,subLn = preprocessorsProperties.length; j < subLn; j++) { + preprocessorProperty = preprocessorsProperties[j]; + + if (data.hasOwnProperty(preprocessorProperty)) { + preprocessors.push(preprocessor.fn); + break; + } + } + } + } + else { + preprocessors.push(preprocessor); + } + } + + hooks.onCreated = onCreated ? onCreated : Ext.emptyFn; + hooks.preprocessors = preprocessors; + + this.doProcess(Class, data, hooks); + }, + + doProcess: function(Class, data, hooks){ + var me = this, + preprocessor = hooks.preprocessors.shift(); + + if (!preprocessor) { + hooks.onBeforeCreated.apply(me, arguments); + return; + } + + if (preprocessor.call(me, Class, data, hooks, me.doProcess) !== false) { + me.doProcess(Class, data, hooks); + } + }, + + /** @private */ + preprocessors: {}, + + /** + * Register a new pre-processor to be used during the class creation process + * + * @param {String} name The pre-processor's name + * @param {Function} fn The callback function to be executed. Typical format: + * + * function(cls, data, fn) { + * // Your code here + * + * // Execute this when the processing is finished. + * // Asynchronous processing is perfectly ok + * if (fn) { + * fn.call(this, cls, data); + * } + * }); + * + * @param {Function} fn.cls The created class + * @param {Object} fn.data The set of properties passed in {@link Ext.Class} constructor + * @param {Function} fn.fn The callback function that **must** to be executed when this + * pre-processor finishes, regardless of whether the processing is synchronous or aynchronous. + * @return {Ext.Class} this + * @private + * @static + */ + registerPreprocessor: function(name, fn, properties, position, relativeTo) { + if (!position) { + position = 'last'; + } + + if (!properties) { + properties = [name]; + } + + this.preprocessors[name] = { + name: name, + properties: properties || false, + fn: fn + }; + + this.setDefaultPreprocessorPosition(name, position, relativeTo); + + return this; + }, + + /** + * Retrieve a pre-processor callback function by its name, which has been registered before + * + * @param {String} name + * @return {Function} preprocessor + * @private + * @static + */ + getPreprocessor: function(name) { + return this.preprocessors[name]; + }, + + /** + * @private + */ + getPreprocessors: function() { + return this.preprocessors; + }, + + /** + * @private + */ + defaultPreprocessors: [], + + /** + * Retrieve the array stack of default pre-processors + * @return {Function[]} defaultPreprocessors + * @private + * @static + */ + getDefaultPreprocessors: function() { + return this.defaultPreprocessors; + }, + + /** + * Set the default array stack of default pre-processors + * + * @private + * @param {Array} preprocessors + * @return {Ext.Class} this + * @static + */ + setDefaultPreprocessors: function(preprocessors) { + this.defaultPreprocessors = Ext.Array.from(preprocessors); + + return this; + }, + + /** + * Insert this pre-processor at a specific position in the stack, optionally relative to + * any existing pre-processor. For example: + * + * Ext.Class.registerPreprocessor('debug', function(cls, data, fn) { + * // Your code here + * + * if (fn) { + * fn.call(this, cls, data); + * } + * }).setDefaultPreprocessorPosition('debug', 'last'); + * + * @private + * @param {String} name The pre-processor name. Note that it needs to be registered with + * {@link Ext#registerPreprocessor registerPreprocessor} before this + * @param {String} offset The insertion position. Four possible values are: + * 'first', 'last', or: 'before', 'after' (relative to the name provided in the third argument) + * @param {String} relativeName + * @return {Ext.Class} this + * @static + */ + setDefaultPreprocessorPosition: function(name, offset, relativeName) { + var defaultPreprocessors = this.defaultPreprocessors, + index; + + if (typeof offset == 'string') { + if (offset === 'first') { + defaultPreprocessors.unshift(name); + + return this; + } + else if (offset === 'last') { + defaultPreprocessors.push(name); + + return this; + } + + offset = (offset === 'after') ? 1 : -1; + } + + index = Ext.Array.indexOf(defaultPreprocessors, relativeName); + + if (index !== -1) { + Ext.Array.splice(defaultPreprocessors, Math.max(0, index + offset), 0, name); + } + + return this; + }, + + configNameCache: {}, + + getConfigNameMap: function(name) { + var cache = this.configNameCache, + map = cache[name], + capitalizedName; + + if (!map) { + capitalizedName = name.charAt(0).toUpperCase() + name.substr(1); + + map = cache[name] = { + internal: name, + initialized: '_is' + capitalizedName + 'Initialized', + apply: 'apply' + capitalizedName, + update: 'update' + capitalizedName, + 'set': 'set' + capitalizedName, + 'get': 'get' + capitalizedName, + doSet : 'doSet' + capitalizedName, + changeEvent: name.toLowerCase() + 'change' + }; + } + + return map; + } + }); + + /** + * @cfg {String} extend + * The parent class that this class extends. For example: + * + * Ext.define('Person', { + * say: function(text) { alert(text); } + * }); + * + * Ext.define('Developer', { + * extend: 'Person', + * say: function(text) { this.callParent(["print "+text]); } + * }); + */ + ExtClass.registerPreprocessor('extend', function(Class, data) { + var Base = Ext.Base, + basePrototype = Base.prototype, + extend = data.extend, + Parent, parentPrototype, i; + + delete data.extend; + + if (extend && extend !== Object) { + Parent = extend; + } + else { + Parent = Base; + } + + parentPrototype = Parent.prototype; + + if (!Parent.$isClass) { + for (i in basePrototype) { + if (!parentPrototype[i]) { + parentPrototype[i] = basePrototype[i]; + } + } + } + + Class.extend(Parent); + + Class.triggerExtended.apply(Class, arguments); + + if (data.onClassExtended) { + Class.onExtended(data.onClassExtended, Class); + delete data.onClassExtended; + } + + }, true); + + /** + * @cfg {Object} statics + * List of static methods for this class. For example: + * + * Ext.define('Computer', { + * statics: { + * factory: function(brand) { + * // 'this' in static methods refer to the class itself + * return new this(brand); + * } + * }, + * + * constructor: function() { ... } + * }); + * + * var dellComputer = Computer.factory('Dell'); + */ + ExtClass.registerPreprocessor('statics', function(Class, data) { + Class.addStatics(data.statics); + + delete data.statics; + }); + + /** + * @cfg {Object} inheritableStatics + * List of inheritable static methods for this class. + * Otherwise just like {@link #statics} but subclasses inherit these methods. + */ + ExtClass.registerPreprocessor('inheritableStatics', function(Class, data) { + Class.addInheritableStatics(data.inheritableStatics); + + delete data.inheritableStatics; + }); + + /** + * @cfg {Object} config + * List of configuration options with their default values, for which automatically + * accessor methods are generated. For example: + * + * Ext.define('SmartPhone', { + * config: { + * hasTouchScreen: false, + * operatingSystem: 'Other', + * price: 500 + * }, + * constructor: function(cfg) { + * this.initConfig(cfg); + * } + * }); + * + * var iPhone = new SmartPhone({ + * hasTouchScreen: true, + * operatingSystem: 'iOS' + * }); + * + * iPhone.getPrice(); // 500; + * iPhone.getOperatingSystem(); // 'iOS' + * iPhone.getHasTouchScreen(); // true; + */ + ExtClass.registerPreprocessor('config', function(Class, data) { + var config = data.config, + prototype = Class.prototype; + + delete data.config; + + Ext.Object.each(config, function(name, value) { + var nameMap = ExtClass.getConfigNameMap(name), + internalName = nameMap.internal, + initializedName = nameMap.initialized, + applyName = nameMap.apply, + updateName = nameMap.update, + setName = nameMap.set, + getName = nameMap.get, + hasOwnSetter = (setName in prototype) || data.hasOwnProperty(setName), + hasOwnApplier = (applyName in prototype) || data.hasOwnProperty(applyName), + hasOwnUpdater = (updateName in prototype) || data.hasOwnProperty(updateName), + optimizedGetter, customGetter; + + if (value === null || (!hasOwnSetter && !hasOwnApplier && !hasOwnUpdater)) { + prototype[internalName] = value; + prototype[initializedName] = true; + } + else { + prototype[initializedName] = false; + } + + if (!hasOwnSetter) { + data[setName] = function(value) { + var oldValue = this[internalName], + applier = this[applyName], + updater = this[updateName]; + + if (!this[initializedName]) { + this[initializedName] = true; + } + + if (applier) { + value = applier.call(this, value, oldValue); + } + + if (typeof value != 'undefined') { + this[internalName] = value; + + if (updater && value !== oldValue) { + updater.call(this, value, oldValue); + } + } + + return this; + }; + } + + if (!(getName in prototype) || data.hasOwnProperty(getName)) { + customGetter = data[getName] || false; + + if (customGetter) { + optimizedGetter = function() { + return customGetter.apply(this, arguments); + }; + } + else { + optimizedGetter = function() { + return this[internalName]; + }; + } + + data[getName] = function() { + var currentGetter; + + if (!this[initializedName]) { + this[initializedName] = true; + this[setName](this.config[name]); + } + + currentGetter = this[getName]; + + if ('$previous' in currentGetter) { + currentGetter.$previous = optimizedGetter; + } + else { + this[getName] = optimizedGetter; + } + + return optimizedGetter.apply(this, arguments); + }; + } + }); + + Class.addConfig(config, true); + }); + + /** + * @cfg {String[]/Object} mixins + * List of classes to mix into this class. For example: + * + * Ext.define('CanSing', { + * sing: function() { + * alert("I'm on the highway to hell...") + * } + * }); + * + * Ext.define('Musician', { + * mixins: ['CanSing'] + * }) + * + * In this case the Musician class will get a `sing` method from CanSing mixin. + * + * But what if the Musician already has a `sing` method? Or you want to mix + * in two classes, both of which define `sing`? In such a cases it's good + * to define mixins as an object, where you assign a name to each mixin: + * + * Ext.define('Musician', { + * mixins: { + * canSing: 'CanSing' + * }, + * + * sing: function() { + * // delegate singing operation to mixin + * this.mixins.canSing.sing.call(this); + * } + * }) + * + * In this case the `sing` method of Musician will overwrite the + * mixed in `sing` method. But you can access the original mixed in method + * through special `mixins` property. + */ + ExtClass.registerPreprocessor('mixins', function(Class, data, hooks) { + var mixins = data.mixins, + name, mixin, i, ln; + + delete data.mixins; + + Ext.Function.interceptBefore(hooks, 'onCreated', function() { + if (mixins instanceof Array) { + for (i = 0,ln = mixins.length; i < ln; i++) { + mixin = mixins[i]; + name = mixin.prototype.mixinId || mixin.$className; + + Class.mixin(name, mixin); + } + } + else { + for (var mixinName in mixins) { + if (mixins.hasOwnProperty(mixinName)) { + Class.mixin(mixinName, mixins[mixinName]); + } + } + } + }); + }); + + // Backwards compatible + Ext.extend = function(Class, Parent, members) { + if (arguments.length === 2 && Ext.isObject(Parent)) { + members = Parent; + Parent = Class; + Class = null; + } + + var cls; + + if (!Parent) { + throw new Error("[Ext.extend] Attempting to extend from a class which has not been loaded on the page."); + } + + members.extend = Parent; + members.preprocessors = [ + 'extend' + ,'statics' + ,'inheritableStatics' + ,'mixins' + ,'config' + ]; + + if (Class) { + cls = new ExtClass(Class, members); + } + else { + cls = new ExtClass(members); + } + + cls.prototype.override = function(o) { + for (var m in o) { + if (o.hasOwnProperty(m)) { + this[m] = o[m]; + } + } + }; + + return cls; + }; + +}()); + +/** + * @author Jacky Nguyen + * @docauthor Jacky Nguyen + * @class Ext.ClassManager + * + * Ext.ClassManager manages all classes and handles mapping from string class name to + * actual class objects throughout the whole framework. It is not generally accessed directly, rather through + * these convenient shorthands: + * + * - {@link Ext#define Ext.define} + * - {@link Ext#create Ext.create} + * - {@link Ext#widget Ext.widget} + * - {@link Ext#getClass Ext.getClass} + * - {@link Ext#getClassName Ext.getClassName} + * + * # Basic syntax: + * + * Ext.define(className, properties); + * + * in which `properties` is an object represent a collection of properties that apply to the class. See + * {@link Ext.ClassManager#create} for more detailed instructions. + * + * Ext.define('Person', { + * name: 'Unknown', + * + * constructor: function(name) { + * if (name) { + * this.name = name; + * } + * }, + * + * eat: function(foodType) { + * alert("I'm eating: " + foodType); + * + * return this; + * } + * }); + * + * var aaron = new Person("Aaron"); + * aaron.eat("Sandwich"); // alert("I'm eating: Sandwich"); + * + * Ext.Class has a powerful set of extensible {@link Ext.Class#registerPreprocessor pre-processors} which takes care of + * everything related to class creation, including but not limited to inheritance, mixins, configuration, statics, etc. + * + * # Inheritance: + * + * Ext.define('Developer', { + * extend: 'Person', + * + * constructor: function(name, isGeek) { + * this.isGeek = isGeek; + * + * // Apply a method from the parent class' prototype + * this.callParent([name]); + * }, + * + * code: function(language) { + * alert("I'm coding in: " + language); + * + * this.eat("Bugs"); + * + * return this; + * } + * }); + * + * var jacky = new Developer("Jacky", true); + * jacky.code("JavaScript"); // alert("I'm coding in: JavaScript"); + * // alert("I'm eating: Bugs"); + * + * See {@link Ext.Base#callParent} for more details on calling superclass' methods + * + * # Mixins: + * + * Ext.define('CanPlayGuitar', { + * playGuitar: function() { + * alert("F#...G...D...A"); + * } + * }); + * + * Ext.define('CanComposeSongs', { + * composeSongs: function() { ... } + * }); + * + * Ext.define('CanSing', { + * sing: function() { + * alert("I'm on the highway to hell...") + * } + * }); + * + * Ext.define('Musician', { + * extend: 'Person', + * + * mixins: { + * canPlayGuitar: 'CanPlayGuitar', + * canComposeSongs: 'CanComposeSongs', + * canSing: 'CanSing' + * } + * }) + * + * Ext.define('CoolPerson', { + * extend: 'Person', + * + * mixins: { + * canPlayGuitar: 'CanPlayGuitar', + * canSing: 'CanSing' + * }, + * + * sing: function() { + * alert("Ahem...."); + * + * this.mixins.canSing.sing.call(this); + * + * alert("[Playing guitar at the same time...]"); + * + * this.playGuitar(); + * } + * }); + * + * var me = new CoolPerson("Jacky"); + * + * me.sing(); // alert("Ahem..."); + * // alert("I'm on the highway to hell..."); + * // alert("[Playing guitar at the same time...]"); + * // alert("F#...G...D...A"); + * + * # Config: + * + * Ext.define('SmartPhone', { + * config: { + * hasTouchScreen: false, + * operatingSystem: 'Other', + * price: 500 + * }, + * + * isExpensive: false, + * + * constructor: function(config) { + * this.initConfig(config); + * }, + * + * applyPrice: function(price) { + * this.isExpensive = (price > 500); + * + * return price; + * }, + * + * applyOperatingSystem: function(operatingSystem) { + * if (!(/^(iOS|Android|BlackBerry)$/i).test(operatingSystem)) { + * return 'Other'; + * } + * + * return operatingSystem; + * } + * }); + * + * var iPhone = new SmartPhone({ + * hasTouchScreen: true, + * operatingSystem: 'iOS' + * }); + * + * iPhone.getPrice(); // 500; + * iPhone.getOperatingSystem(); // 'iOS' + * iPhone.getHasTouchScreen(); // true; + * iPhone.hasTouchScreen(); // true + * + * iPhone.isExpensive; // false; + * iPhone.setPrice(600); + * iPhone.getPrice(); // 600 + * iPhone.isExpensive; // true; + * + * iPhone.setOperatingSystem('AlienOS'); + * iPhone.getOperatingSystem(); // 'Other' + * + * # Statics: + * + * Ext.define('Computer', { + * statics: { + * factory: function(brand) { + * // 'this' in static methods refer to the class itself + * return new this(brand); + * } + * }, + * + * constructor: function() { ... } + * }); + * + * var dellComputer = Computer.factory('Dell'); + * + * Also see {@link Ext.Base#statics} and {@link Ext.Base#self} for more details on accessing + * static properties within class methods + * + * @singleton + */ +(function(Class, alias, arraySlice, arrayFrom, global) { + + var Manager = Ext.ClassManager = { + + /** + * @property {Object} classes + * All classes which were defined through the ClassManager. Keys are the + * name of the classes and the values are references to the classes. + * @private + */ + classes: {}, + + /** + * @private + */ + existCache: {}, + + /** + * @private + */ + namespaceRewrites: [{ + from: 'Ext.', + to: Ext + }], + + /** + * @private + */ + maps: { + alternateToName: {}, + aliasToName: {}, + nameToAliases: {}, + nameToAlternates: {} + }, + + /** @private */ + enableNamespaceParseCache: true, + + /** @private */ + namespaceParseCache: {}, + + /** @private */ + instantiators: [], + + /** + * Checks if a class has already been created. + * + * @param {String} className + * @return {Boolean} exist + */ + isCreated: function(className) { + var existCache = this.existCache, + i, ln, part, root, parts; + + if (typeof className != 'string' || className.length < 1) { + throw new Error("[Ext.ClassManager] Invalid classname, must be a string and must not be empty"); + } + + if (this.classes[className] || existCache[className]) { + return true; + } + + root = global; + parts = this.parseNamespace(className); + + for (i = 0, ln = parts.length; i < ln; i++) { + part = parts[i]; + + if (typeof part != 'string') { + root = part; + } else { + if (!root || !root[part]) { + return false; + } + + root = root[part]; + } + } + + existCache[className] = true; + + this.triggerCreated(className); + + return true; + }, + + /** + * @private + */ + createdListeners: [], + + /** + * @private + */ + nameCreatedListeners: {}, + + /** + * @private + */ + triggerCreated: function(className) { + var listeners = this.createdListeners, + nameListeners = this.nameCreatedListeners, + alternateNames = this.maps.nameToAlternates[className], + names = [className], + i, ln, j, subLn, listener, name; + + for (i = 0,ln = listeners.length; i < ln; i++) { + listener = listeners[i]; + listener.fn.call(listener.scope, className); + } + + if (alternateNames) { + names.push.apply(names, alternateNames); + } + + for (i = 0,ln = names.length; i < ln; i++) { + name = names[i]; + listeners = nameListeners[name]; + + if (listeners) { + for (j = 0,subLn = listeners.length; j < subLn; j++) { + listener = listeners[j]; + listener.fn.call(listener.scope, name); + } + delete nameListeners[name]; + } + } + }, + + /** + * @private + */ + onCreated: function(fn, scope, className) { + var listeners = this.createdListeners, + nameListeners = this.nameCreatedListeners, + listener = { + fn: fn, + scope: scope + }; + + if (className) { + if (this.isCreated(className)) { + fn.call(scope, className); + return; + } + + if (!nameListeners[className]) { + nameListeners[className] = []; + } + + nameListeners[className].push(listener); + } + else { + listeners.push(listener); + } + }, + + /** + * Supports namespace rewriting + * @private + */ + parseNamespace: function(namespace) { + if (typeof namespace != 'string') { + throw new Error("[Ext.ClassManager] Invalid namespace, must be a string"); + } + + var cache = this.namespaceParseCache, + parts, + rewrites, + root, + name, + rewrite, from, to, i, ln; + + if (this.enableNamespaceParseCache) { + if (cache.hasOwnProperty(namespace)) { + return cache[namespace]; + } + } + + parts = []; + rewrites = this.namespaceRewrites; + root = global; + name = namespace; + + for (i = 0, ln = rewrites.length; i < ln; i++) { + rewrite = rewrites[i]; + from = rewrite.from; + to = rewrite.to; + + if (name === from || name.substring(0, from.length) === from) { + name = name.substring(from.length); + + if (typeof to != 'string') { + root = to; + } else { + parts = parts.concat(to.split('.')); + } + + break; + } + } + + parts.push(root); + + parts = parts.concat(name.split('.')); + + if (this.enableNamespaceParseCache) { + cache[namespace] = parts; + } + + return parts; + }, + + /** + * Creates a namespace and assign the `value` to the created object + * + * Ext.ClassManager.setNamespace('MyCompany.pkg.Example', someObject); + * + * alert(MyCompany.pkg.Example === someObject); // alerts true + * + * @param {String} name + * @param {Object} value + */ + setNamespace: function(name, value) { + var root = global, + parts = this.parseNamespace(name), + ln = parts.length - 1, + leaf = parts[ln], + i, part; + + for (i = 0; i < ln; i++) { + part = parts[i]; + + if (typeof part != 'string') { + root = part; + } else { + if (!root[part]) { + root[part] = {}; + } + + root = root[part]; + } + } + + root[leaf] = value; + + return root[leaf]; + }, + + /** + * The new Ext.ns, supports namespace rewriting + * @private + */ + createNamespaces: function() { + var root = global, + parts, part, i, j, ln, subLn; + + for (i = 0, ln = arguments.length; i < ln; i++) { + parts = this.parseNamespace(arguments[i]); + + for (j = 0, subLn = parts.length; j < subLn; j++) { + part = parts[j]; + + if (typeof part != 'string') { + root = part; + } else { + if (!root[part]) { + root[part] = {}; + } + + root = root[part]; + } + } + } + + return root; + }, + + /** + * Sets a name reference to a class. + * + * @param {String} name + * @param {Object} value + * @return {Ext.ClassManager} this + */ + set: function(name, value) { + var me = this, + maps = me.maps, + nameToAlternates = maps.nameToAlternates, + targetName = me.getName(value), + alternates; + + me.classes[name] = me.setNamespace(name, value); + + if (targetName && targetName !== name) { + maps.alternateToName[name] = targetName; + alternates = nameToAlternates[targetName] || (nameToAlternates[targetName] = []); + alternates.push(name); + } + + return this; + }, + + /** + * Retrieve a class by its name. + * + * @param {String} name + * @return {Ext.Class} class + */ + get: function(name) { + var classes = this.classes, + root, + parts, + part, i, ln; + + if (classes[name]) { + return classes[name]; + } + + root = global; + parts = this.parseNamespace(name); + + for (i = 0, ln = parts.length; i < ln; i++) { + part = parts[i]; + + if (typeof part != 'string') { + root = part; + } else { + if (!root || !root[part]) { + return null; + } + + root = root[part]; + } + } + + return root; + }, + + /** + * Register the alias for a class. + * + * @param {Ext.Class/String} cls a reference to a class or a className + * @param {String} alias Alias to use when referring to this class + */ + setAlias: function(cls, alias) { + var aliasToNameMap = this.maps.aliasToName, + nameToAliasesMap = this.maps.nameToAliases, + className; + + if (typeof cls == 'string') { + className = cls; + } else { + className = this.getName(cls); + } + + if (alias && aliasToNameMap[alias] !== className) { + if (aliasToNameMap[alias] && Ext.isDefined(global.console)) { + global.console.log("[Ext.ClassManager] Overriding existing alias: '" + alias + "' " + + "of: '" + aliasToNameMap[alias] + "' with: '" + className + "'. Be sure it's intentional."); + } + + aliasToNameMap[alias] = className; + } + + if (!nameToAliasesMap[className]) { + nameToAliasesMap[className] = []; + } + + if (alias) { + Ext.Array.include(nameToAliasesMap[className], alias); + } + + return this; + }, + + /** + * Get a reference to the class by its alias. + * + * @param {String} alias + * @return {Ext.Class} class + */ + getByAlias: function(alias) { + return this.get(this.getNameByAlias(alias)); + }, + + /** + * Get the name of a class by its alias. + * + * @param {String} alias + * @return {String} className + */ + getNameByAlias: function(alias) { + return this.maps.aliasToName[alias] || ''; + }, + + /** + * Get the name of a class by its alternate name. + * + * @param {String} alternate + * @return {String} className + */ + getNameByAlternate: function(alternate) { + return this.maps.alternateToName[alternate] || ''; + }, + + /** + * Get the aliases of a class by the class name + * + * @param {String} name + * @return {Array} aliases + */ + getAliasesByName: function(name) { + return this.maps.nameToAliases[name] || []; + }, + + /** + * Get the name of the class by its reference or its instance; + * usually invoked by the shorthand {@link Ext#getClassName Ext.getClassName} + * + * Ext.ClassManager.getName(Ext.Action); // returns "Ext.Action" + * + * @param {Ext.Class/Object} object + * @return {String} className + */ + getName: function(object) { + return object && object.$className || ''; + }, + + /** + * Get the class of the provided object; returns null if it's not an instance + * of any class created with Ext.define. This is usually invoked by the shorthand {@link Ext#getClass Ext.getClass} + * + * var component = new Ext.Component(); + * + * Ext.ClassManager.getClass(component); // returns Ext.Component + * + * @param {Object} object + * @return {Ext.Class} class + */ + getClass: function(object) { + return object && object.self || null; + }, + + /** + * Defines a class. + * @deprecated 4.1.0 Use {@link Ext#define} instead, as that also supports creating overrides. + */ + create: function(className, data, createdFn) { + if (typeof className != 'string') { + throw new Error("[Ext.define] Invalid class name '" + className + "' specified, must be a non-empty string"); + } + + data.$className = className; + + return new Class(data, function() { + var postprocessorStack = data.postprocessors || Manager.defaultPostprocessors, + registeredPostprocessors = Manager.postprocessors, + postprocessors = [], + postprocessor, i, ln, j, subLn, postprocessorProperties, postprocessorProperty; + + delete data.postprocessors; + + for (i = 0,ln = postprocessorStack.length; i < ln; i++) { + postprocessor = postprocessorStack[i]; + + if (typeof postprocessor == 'string') { + postprocessor = registeredPostprocessors[postprocessor]; + postprocessorProperties = postprocessor.properties; + + if (postprocessorProperties === true) { + postprocessors.push(postprocessor.fn); + } + else if (postprocessorProperties) { + for (j = 0,subLn = postprocessorProperties.length; j < subLn; j++) { + postprocessorProperty = postprocessorProperties[j]; + + if (data.hasOwnProperty(postprocessorProperty)) { + postprocessors.push(postprocessor.fn); + break; + } + } + } + } + else { + postprocessors.push(postprocessor); + } + } + + data.postprocessors = postprocessors; + data.createdFn = createdFn; + Manager.processCreate(className, this, data); + }); + }, + + processCreate: function(className, cls, clsData){ + var me = this, + postprocessor = clsData.postprocessors.shift(), + createdFn = clsData.createdFn; + + if (!postprocessor) { + me.set(className, cls); + + if (createdFn) { + createdFn.call(cls, cls); + } + + me.triggerCreated(className); + return; + } + + if (postprocessor.call(me, className, cls, clsData, me.processCreate) !== false) { + me.processCreate(className, cls, clsData); + } + }, + + createOverride: function (className, data, createdFn) { + var me = this, + overriddenClassName = data.override, + requires = data.requires, + uses = data.uses, + classReady = function () { + var cls, temp; + + if (requires) { + temp = requires; + requires = null; // do the real thing next time (which may be now) + + // Since the override is going to be used (its target class is now + // created), we need to fetch the required classes for the override + // and call us back once they are loaded: + Ext.Loader.require(temp, classReady); + } else { + // The target class and the required classes for this override are + // ready, so we can apply the override now: + cls = me.get(overriddenClassName); + + // We don't want to apply these: + delete data.override; + delete data.requires; + delete data.uses; + + Ext.override(cls, data); + + // This pushes the overridding file itself into Ext.Loader.history + // Hence if the target class never exists, the overriding file will + // never be included in the build. + me.triggerCreated(className); + + if (uses) { + Ext.Loader.addUsedClasses(uses); // get these classes too! + } + + if (createdFn) { + createdFn.call(cls); // last but not least! + } + } + }; + + me.existCache[className] = true; + + // Override the target class right after it's created + me.onCreated(classReady, me, overriddenClassName); + + return me; + }, + + /** + * Instantiate a class by its alias; usually invoked by the convenient shorthand {@link Ext#createByAlias Ext.createByAlias} + * If {@link Ext.Loader} is {@link Ext.Loader#setConfig enabled} and the class has not been defined yet, it will + * attempt to load the class via synchronous loading. + * + * var window = Ext.ClassManager.instantiateByAlias('widget.window', { width: 600, height: 800, ... }); + * + * @param {String} alias + * @param {Object...} args Additional arguments after the alias will be passed to the + * class constructor. + * @return {Object} instance + */ + instantiateByAlias: function() { + var alias = arguments[0], + args = arraySlice.call(arguments), + className = this.getNameByAlias(alias); + + if (!className) { + className = this.maps.aliasToName[alias]; + + if (!className) { + throw new Error("[Ext.createByAlias] Cannot create an instance of unrecognized alias: " + alias); + } + + if (global.console) { + global.console.warn("[Ext.Loader] Synchronously loading '" + className + "'; consider adding " + + "Ext.require('" + alias + "') above Ext.onReady"); + } + + Ext.syncRequire(className); + } + + args[0] = className; + + return this.instantiate.apply(this, args); + }, + + /** + * @private + */ + instantiate: function() { + var name = arguments[0], + nameType = typeof name, + args = arraySlice.call(arguments, 1), + alias = name, + possibleName, cls; + + if (nameType != 'function') { + if (nameType != 'string' && args.length === 0) { + args = [name]; + name = name.xclass; + } + + if (typeof name != 'string' || name.length < 1) { + throw new Error("[Ext.create] Invalid class name or alias '" + name + "' specified, must be a non-empty string"); + } + + cls = this.get(name); + } + else { + cls = name; + } + + // No record of this class name, it's possibly an alias, so look it up + if (!cls) { + possibleName = this.getNameByAlias(name); + + if (possibleName) { + name = possibleName; + + cls = this.get(name); + } + } + + // Still no record of this class name, it's possibly an alternate name, so look it up + if (!cls) { + possibleName = this.getNameByAlternate(name); + + if (possibleName) { + name = possibleName; + + cls = this.get(name); + } + } + + // Still not existing at this point, try to load it via synchronous mode as the last resort + if (!cls) { + if (global.console) { + global.console.warn("[Ext.Loader] Synchronously loading '" + name + "'; consider adding " + + "Ext.require('" + ((possibleName) ? alias : name) + "') above Ext.onReady"); + } + + Ext.syncRequire(name); + + cls = this.get(name); + } + + if (!cls) { + throw new Error("[Ext.create] Cannot create an instance of unrecognized class name / alias: " + alias); + } + + if (typeof cls != 'function') { + throw new Error("[Ext.create] '" + name + "' is a singleton and cannot be instantiated"); + } + + return this.getInstantiator(args.length)(cls, args); + }, + + /** + * @private + * @param name + * @param args + */ + dynInstantiate: function(name, args) { + args = arrayFrom(args, true); + args.unshift(name); + + return this.instantiate.apply(this, args); + }, + + /** + * @private + * @param length + */ + getInstantiator: function(length) { + var instantiators = this.instantiators, + instantiator, + i, + args; + + instantiator = instantiators[length]; + + if (!instantiator) { + i = length; + args = []; + + for (i = 0; i < length; i++) { + args.push('a[' + i + ']'); + } + + instantiator = instantiators[length] = new Function('c', 'a', 'return new c(' + args.join(',') + ')'); + instantiator.displayName = "Ext.ClassManager.instantiate" + length; + } + + return instantiator; + }, + + /** + * @private + */ + postprocessors: {}, + + /** + * @private + */ + defaultPostprocessors: [], + + /** + * Register a post-processor function. + * + * @private + * @param {String} name + * @param {Function} postprocessor + */ + registerPostprocessor: function(name, fn, properties, position, relativeTo) { + if (!position) { + position = 'last'; + } + + if (!properties) { + properties = [name]; + } + + this.postprocessors[name] = { + name: name, + properties: properties || false, + fn: fn + }; + + this.setDefaultPostprocessorPosition(name, position, relativeTo); + + return this; + }, + + /** + * Set the default post processors array stack which are applied to every class. + * + * @private + * @param {String/Array} The name of a registered post processor or an array of registered names. + * @return {Ext.ClassManager} this + */ + setDefaultPostprocessors: function(postprocessors) { + this.defaultPostprocessors = arrayFrom(postprocessors); + + return this; + }, + + /** + * Insert this post-processor at a specific position in the stack, optionally relative to + * any existing post-processor + * + * @private + * @param {String} name The post-processor name. Note that it needs to be registered with + * {@link Ext.ClassManager#registerPostprocessor} before this + * @param {String} offset The insertion position. Four possible values are: + * 'first', 'last', or: 'before', 'after' (relative to the name provided in the third argument) + * @param {String} relativeName + * @return {Ext.ClassManager} this + */ + setDefaultPostprocessorPosition: function(name, offset, relativeName) { + var defaultPostprocessors = this.defaultPostprocessors, + index; + + if (typeof offset == 'string') { + if (offset === 'first') { + defaultPostprocessors.unshift(name); + + return this; + } + else if (offset === 'last') { + defaultPostprocessors.push(name); + + return this; + } + + offset = (offset === 'after') ? 1 : -1; + } + + index = Ext.Array.indexOf(defaultPostprocessors, relativeName); + + if (index !== -1) { + Ext.Array.splice(defaultPostprocessors, Math.max(0, index + offset), 0, name); + } + + return this; + }, + + /** + * Converts a string expression to an array of matching class names. An expression can either refers to class aliases + * or class names. Expressions support wildcards: + * + * // returns ['Ext.window.Window'] + * var window = Ext.ClassManager.getNamesByExpression('widget.window'); + * + * // returns ['widget.panel', 'widget.window', ...] + * var allWidgets = Ext.ClassManager.getNamesByExpression('widget.*'); + * + * // returns ['Ext.data.Store', 'Ext.data.ArrayProxy', ...] + * var allData = Ext.ClassManager.getNamesByExpression('Ext.data.*'); + * + * @param {String} expression + * @return {String[]} classNames + */ + getNamesByExpression: function(expression) { + var nameToAliasesMap = this.maps.nameToAliases, + names = [], + name, alias, aliases, possibleName, regex, i, ln; + + if (typeof expression != 'string' || expression.length < 1) { + throw new Error("[Ext.ClassManager.getNamesByExpression] Expression " + expression + " is invalid, must be a non-empty string"); + } + + if (expression.indexOf('*') !== -1) { + expression = expression.replace(/\*/g, '(.*?)'); + regex = new RegExp('^' + expression + '$'); + + for (name in nameToAliasesMap) { + if (nameToAliasesMap.hasOwnProperty(name)) { + aliases = nameToAliasesMap[name]; + + if (name.search(regex) !== -1) { + names.push(name); + } + else { + for (i = 0, ln = aliases.length; i < ln; i++) { + alias = aliases[i]; + + if (alias.search(regex) !== -1) { + names.push(name); + break; + } + } + } + } + } + + } else { + possibleName = this.getNameByAlias(expression); + + if (possibleName) { + names.push(possibleName); + } else { + possibleName = this.getNameByAlternate(expression); + + if (possibleName) { + names.push(possibleName); + } else { + names.push(expression); + } + } + } + + return names; + } + }; + + /** + * @cfg {String[]} alias + * @member Ext.Class + * List of short aliases for class names. Most useful for defining xtypes for widgets: + * + * Ext.define('MyApp.CoolPanel', { + * extend: 'Ext.panel.Panel', + * alias: ['widget.coolpanel'], + * title: 'Yeah!' + * }); + * + * // Using Ext.create + * Ext.create('widget.coolpanel'); + * + * // Using the shorthand for defining widgets by xtype + * Ext.widget('panel', { + * items: [ + * {xtype: 'coolpanel', html: 'Foo'}, + * {xtype: 'coolpanel', html: 'Bar'} + * ] + * }); + * + * Besides "widget" for xtype there are alias namespaces like "feature" for ftype and "plugin" for ptype. + */ + Manager.registerPostprocessor('alias', function(name, cls, data) { + var aliases = data.alias, + i, ln; + + for (i = 0,ln = aliases.length; i < ln; i++) { + alias = aliases[i]; + + this.setAlias(cls, alias); + } + + }, ['xtype', 'alias']); + + /** + * @cfg {Boolean} singleton + * @member Ext.Class + * When set to true, the class will be instantiated as singleton. For example: + * + * Ext.define('Logger', { + * singleton: true, + * log: function(msg) { + * console.log(msg); + * } + * }); + * + * Logger.log('Hello'); + */ + Manager.registerPostprocessor('singleton', function(name, cls, data, fn) { + fn.call(this, name, new cls(), data); + return false; + }); + + /** + * @cfg {String/String[]} alternateClassName + * @member Ext.Class + * Defines alternate names for this class. For example: + * + * Ext.define('Developer', { + * alternateClassName: ['Coder', 'Hacker'], + * code: function(msg) { + * alert('Typing... ' + msg); + * } + * }); + * + * var joe = Ext.create('Developer'); + * joe.code('stackoverflow'); + * + * var rms = Ext.create('Hacker'); + * rms.code('hack hack'); + */ + Manager.registerPostprocessor('alternateClassName', function(name, cls, data) { + var alternates = data.alternateClassName, + i, ln, alternate; + + if (!(alternates instanceof Array)) { + alternates = [alternates]; + } + + for (i = 0, ln = alternates.length; i < ln; i++) { + alternate = alternates[i]; + + if (typeof alternate != 'string') { + throw new Error("[Ext.define] Invalid alternate of: '" + alternate + "' for class: '" + name + "'; must be a valid string"); + } + + this.set(alternate, cls); + } + }); + + Ext.apply(Ext, { + /** + * Instantiate a class by either full name, alias or alternate name. + * + * If {@link Ext.Loader} is {@link Ext.Loader#setConfig enabled} and the class has + * not been defined yet, it will attempt to load the class via synchronous loading. + * + * For example, all these three lines return the same result: + * + * // alias + * var window = Ext.create('widget.window', { + * width: 600, + * height: 800, + * ... + * }); + * + * // alternate name + * var window = Ext.create('Ext.Window', { + * width: 600, + * height: 800, + * ... + * }); + * + * // full class name + * var window = Ext.create('Ext.window.Window', { + * width: 600, + * height: 800, + * ... + * }); + * + * // single object with xclass property: + * var window = Ext.create({ + * xclass: 'Ext.window.Window', // any valid value for 'name' (above) + * width: 600, + * height: 800, + * ... + * }); + * + * @param {String} [name] The class name or alias. Can be specified as `xclass` + * property if only one object parameter is specified. + * @param {Object...} [args] Additional arguments after the name will be passed to + * the class' constructor. + * @return {Object} instance + * @member Ext + * @method create + */ + create: alias(Manager, 'instantiate'), + + /** + * Convenient shorthand to create a widget by its xtype or a config object. + * See also {@link Ext.ClassManager#instantiateByAlias}. + * + * var button = Ext.widget('button'); // Equivalent to Ext.create('widget.button'); + * + * var panel = Ext.widget('panel', { // Equivalent to Ext.create('widget.panel') + * title: 'Panel' + * }); + * + * var grid = Ext.widget({ + * xtype: 'grid', + * ... + * }); + * + * If a {@link Ext.Component component} instance is passed, it is simply returned. + * + * @member Ext + * @param {String} [name] The xtype of the widget to create. + * @param {Object} [config] The configuration object for the widget constructor. + * @return {Object} The widget instance + */ + widget: function(name, config) { + // forms: + // 1: (xtype) + // 2: (xtype, config) + // 3: (config) + // 4: (xtype, component) + // 5: (component) + // + var xtype = name, + alias, className, T, load; + + if (typeof xtype != 'string') { // if (form 3 or 5) + // first arg is config or component + config = name; // arguments[0] + xtype = config.xtype; + } else { + config = config || {}; + } + + if (config.isComponent) { + return config; + } + + alias = 'widget.' + xtype; + className = Manager.getNameByAlias(alias); + + // this is needed to support demand loading of the class + if (!className) { + load = true; + } + + T = Manager.get(className); + if (load || !T) { + return Manager.instantiateByAlias(alias, config); + } + return new T(config); + }, + + /** + * Convenient shorthand, see {@link Ext.ClassManager#instantiateByAlias} + * @member Ext + * @method createByAlias + */ + createByAlias: alias(Manager, 'instantiateByAlias'), + + /** + * @method + * Defines a class or override. A basic class is defined like this: + * + * Ext.define('My.awesome.Class', { + * someProperty: 'something', + * + * someMethod: function() { + * alert(s + this.someProperty); + * } + * + * ... + * }); + * + * var obj = new My.awesome.Class(); + * + * obj.someMethod('Say '); // alerts 'Say something' + * + * To defines an override, include the `override` property. The content of an + * override is aggregated with the specified class in order to extend or modify + * that class. This can be as simple as setting default property values or it can + * extend and/or replace methods. This can also extend the statics of the class. + * + * One use for an override is to break a large class into manageable pieces. + * + * // File: /src/app/Panel.js + * + * Ext.define('My.app.Panel', { + * extend: 'Ext.panel.Panel', + * requires: [ + * 'My.app.PanelPart2', + * 'My.app.PanelPart3' + * ] + * + * constructor: function (config) { + * this.callParent(arguments); // calls Ext.panel.Panel's constructor + * //... + * }, + * + * statics: { + * method: function () { + * return 'abc'; + * } + * } + * }); + * + * // File: /src/app/PanelPart2.js + * Ext.define('My.app.PanelPart2', { + * override: 'My.app.Panel', + * + * constructor: function (config) { + * this.callParent(arguments); // calls My.app.Panel's constructor + * //... + * } + * }); + * + * Another use of overrides is to provide optional parts of classes that can be + * independently required. In this case, the class may even be unaware of the + * override altogether. + * + * Ext.define('My.ux.CoolTip', { + * override: 'Ext.tip.ToolTip', + * + * constructor: function (config) { + * this.callParent(arguments); // calls Ext.tip.ToolTip's constructor + * //... + * } + * }); + * + * The above override can now be required as normal. + * + * Ext.define('My.app.App', { + * requires: [ + * 'My.ux.CoolTip' + * ] + * }); + * + * Overrides can also contain statics: + * + * Ext.define('My.app.BarMod', { + * override: 'Ext.foo.Bar', + * + * statics: { + * method: function (x) { + * return this.callParent([x * 2]); // call Ext.foo.Bar.method + * } + * } + * }); + * + * IMPORTANT: An override is only included in a build if the class it overrides is + * required. Otherwise, the override, like the target class, is not included. + * + * @param {String} className The class name to create in string dot-namespaced format, for example: + * 'My.very.awesome.Class', 'FeedViewer.plugin.CoolPager' + * It is highly recommended to follow this simple convention: + * - The root and the class name are 'CamelCased' + * - Everything else is lower-cased + * @param {Object} data The key - value pairs of properties to apply to this class. Property names can be of any valid + * strings, except those in the reserved listed below: + * - `mixins` + * - `statics` + * - `config` + * - `alias` + * - `self` + * - `singleton` + * - `alternateClassName` + * - `override` + * + * @param {Function} createdFn Optional callback to execute after the class is created, the execution scope of which + * (`this`) will be the newly created class itself. + * @return {Ext.Base} + * @markdown + * @member Ext + * @method define + */ + define: function (className, data, createdFn) { + if (data.override) { + return Manager.createOverride.apply(Manager, arguments); + } + + return Manager.create.apply(Manager, arguments); + }, + + /** + * Convenient shorthand, see {@link Ext.ClassManager#getName} + * @member Ext + * @method getClassName + */ + getClassName: alias(Manager, 'getName'), + + /** + * Returns the displayName property or className or object. When all else fails, returns "Anonymous". + * @param {Object} object + * @return {String} + */ + getDisplayName: function(object) { + if (object) { + if (object.displayName) { + return object.displayName; + } + + if (object.$name && object.$class) { + return Ext.getClassName(object.$class) + '#' + object.$name; + } + + if (object.$className) { + return object.$className; + } + } + + return 'Anonymous'; + }, + + /** + * Convenient shorthand, see {@link Ext.ClassManager#getClass} + * @member Ext + * @method getClass + */ + getClass: alias(Manager, 'getClass'), + + /** + * Creates namespaces to be used for scoping variables and classes so that they are not global. + * Specifying the last node of a namespace implicitly creates all other nodes. Usage: + * + * Ext.namespace('Company', 'Company.data'); + * + * // equivalent and preferable to the above syntax + * Ext.ns('Company.data'); + * + * Company.Widget = function() { ... }; + * + * Company.data.CustomStore = function(config) { ... }; + * + * @param {String...} namespaces + * @return {Object} The namespace object. + * (If multiple arguments are passed, this will be the last namespace created) + * @member Ext + * @method namespace + */ + namespace: alias(Manager, 'createNamespaces') + }); + + /** + * Old name for {@link Ext#widget}. + * @deprecated 4.0.0 Use {@link Ext#widget} instead. + * @method createWidget + * @member Ext + */ + Ext.createWidget = Ext.widget; + + /** + * Convenient alias for {@link Ext#namespace Ext.namespace}. + * @inheritdoc Ext#namespace + * @member Ext + * @method ns + */ + Ext.ns = Ext.namespace; + + Class.registerPreprocessor('className', function(cls, data) { + if (data.$className) { + cls.$className = data.$className; + cls.displayName = cls.$className; + } + }, true, 'first'); + + Class.registerPreprocessor('alias', function(cls, data) { + var prototype = cls.prototype, + xtypes = arrayFrom(data.xtype), + aliases = arrayFrom(data.alias), + widgetPrefix = 'widget.', + widgetPrefixLength = widgetPrefix.length, + xtypesChain = Array.prototype.slice.call(prototype.xtypesChain || []), + xtypesMap = Ext.merge({}, prototype.xtypesMap || {}), + i, ln, alias, xtype; + + for (i = 0,ln = aliases.length; i < ln; i++) { + alias = aliases[i]; + + if (typeof alias != 'string' || alias.length < 1) { + throw new Error("[Ext.define] Invalid alias of: '" + alias + "' for class: '" + name + "'; must be a valid string"); + } + + if (alias.substring(0, widgetPrefixLength) === widgetPrefix) { + xtype = alias.substring(widgetPrefixLength); + Ext.Array.include(xtypes, xtype); + } + } + + cls.xtype = data.xtype = xtypes[0]; + data.xtypes = xtypes; + + for (i = 0,ln = xtypes.length; i < ln; i++) { + xtype = xtypes[i]; + + if (!xtypesMap[xtype]) { + xtypesMap[xtype] = true; + xtypesChain.push(xtype); + } + } + + data.xtypesChain = xtypesChain; + data.xtypesMap = xtypesMap; + + Ext.Function.interceptAfter(data, 'onClassCreated', function() { + var mixins = prototype.mixins, + key, mixin; + + for (key in mixins) { + if (mixins.hasOwnProperty(key)) { + mixin = mixins[key]; + + xtypes = mixin.xtypes; + + if (xtypes) { + for (i = 0,ln = xtypes.length; i < ln; i++) { + xtype = xtypes[i]; + + if (!xtypesMap[xtype]) { + xtypesMap[xtype] = true; + xtypesChain.push(xtype); + } + } + } + } + } + }); + + for (i = 0,ln = xtypes.length; i < ln; i++) { + xtype = xtypes[i]; + + if (typeof xtype != 'string' || xtype.length < 1) { + throw new Error("[Ext.define] Invalid xtype of: '" + xtype + "' for class: '" + name + "'; must be a valid non-empty string"); + } + + Ext.Array.include(aliases, widgetPrefix + xtype); + } + + data.alias = aliases; + + }, ['xtype', 'alias']); + +}(Ext.Class, Ext.Function.alias, Array.prototype.slice, Ext.Array.from, Ext.global)); + +/** + * @author Jacky Nguyen + * @docauthor Jacky Nguyen + * @class Ext.Loader + * + * Ext.Loader is the heart of the new dynamic dependency loading capability in Ext JS 4+. It is most commonly used + * via the {@link Ext#require} shorthand. Ext.Loader supports both asynchronous and synchronous loading + * approaches, and leverage their advantages for the best development flow. We'll discuss about the pros and cons of each approach: + * + * # Asynchronous Loading # + * + * - Advantages: + * + Cross-domain + * + No web server needed: you can run the application via the file system protocol (i.e: `file://path/to/your/index + * .html`) + * + Best possible debugging experience: error messages come with the exact file name and line number + * + * - Disadvantages: + * + Dependencies need to be specified before-hand + * + * ### Method 1: Explicitly include what you need: ### + * + * // Syntax + * Ext.require({String/Array} expressions); + * + * // Example: Single alias + * Ext.require('widget.window'); + * + * // Example: Single class name + * Ext.require('Ext.window.Window'); + * + * // Example: Multiple aliases / class names mix + * Ext.require(['widget.window', 'layout.border', 'Ext.data.Connection']); + * + * // Wildcards + * Ext.require(['widget.*', 'layout.*', 'Ext.data.*']); + * + * ### Method 2: Explicitly exclude what you don't need: ### + * + * // Syntax: Note that it must be in this chaining format. + * Ext.exclude({String/Array} expressions) + * .require({String/Array} expressions); + * + * // Include everything except Ext.data.* + * Ext.exclude('Ext.data.*').require('*'); + * + * // Include all widgets except widget.checkbox*, + * // which will match widget.checkbox, widget.checkboxfield, widget.checkboxgroup, etc. + * Ext.exclude('widget.checkbox*').require('widget.*'); + * + * # Synchronous Loading on Demand # + * + * - Advantages: + * + There's no need to specify dependencies before-hand, which is always the convenience of including ext-all.js + * before + * + * - Disadvantages: + * + Not as good debugging experience since file name won't be shown (except in Firebug at the moment) + * + Must be from the same domain due to XHR restriction + * + Need a web server, same reason as above + * + * There's one simple rule to follow: Instantiate everything with Ext.create instead of the `new` keyword + * + * Ext.create('widget.window', { ... }); // Instead of new Ext.window.Window({...}); + * + * Ext.create('Ext.window.Window', {}); // Same as above, using full class name instead of alias + * + * Ext.widget('window', {}); // Same as above, all you need is the traditional `xtype` + * + * Behind the scene, {@link Ext.ClassManager} will automatically check whether the given class name / alias has already + * existed on the page. If it's not, Ext.Loader will immediately switch itself to synchronous mode and automatic load the given + * class and all its dependencies. + * + * # Hybrid Loading - The Best of Both Worlds # + * + * It has all the advantages combined from asynchronous and synchronous loading. The development flow is simple: + * + * ### Step 1: Start writing your application using synchronous approach. + * + * Ext.Loader will automatically fetch all dependencies on demand as they're needed during run-time. For example: + * + * Ext.onReady(function(){ + * var window = Ext.createWidget('window', { + * width: 500, + * height: 300, + * layout: { + * type: 'border', + * padding: 5 + * }, + * title: 'Hello Dialog', + * items: [{ + * title: 'Navigation', + * collapsible: true, + * region: 'west', + * width: 200, + * html: 'Hello', + * split: true + * }, { + * title: 'TabPanel', + * region: 'center' + * }] + * }); + * + * window.show(); + * }) + * + * ### Step 2: Along the way, when you need better debugging ability, watch the console for warnings like these: ### + * + * [Ext.Loader] Synchronously loading 'Ext.window.Window'; consider adding Ext.require('Ext.window.Window') before your application's code + * ClassManager.js:432 + * [Ext.Loader] Synchronously loading 'Ext.layout.container.Border'; consider adding Ext.require('Ext.layout.container.Border') before your application's code + * + * Simply copy and paste the suggested code above `Ext.onReady`, i.e: + * + * Ext.require('Ext.window.Window'); + * Ext.require('Ext.layout.container.Border'); + * + * Ext.onReady(...); + * + * Everything should now load via asynchronous mode. + * + * # Deployment # + * + * It's important to note that dynamic loading should only be used during development on your local machines. + * During production, all dependencies should be combined into one single JavaScript file. Ext.Loader makes + * the whole process of transitioning from / to between development / maintenance and production as easy as + * possible. Internally {@link Ext.Loader#history Ext.Loader.history} maintains the list of all dependencies your application + * needs in the exact loading sequence. It's as simple as concatenating all files in this array into one, + * then include it on top of your application. + * + * This process will be automated with Sencha Command, to be released and documented towards Ext JS 4 Final. + * + * @singleton + */ + +Ext.Loader = new function() { + var Loader = this, + Manager = Ext.ClassManager, + Class = Ext.Class, + flexSetter = Ext.Function.flexSetter, + alias = Ext.Function.alias, + pass = Ext.Function.pass, + defer = Ext.Function.defer, + arrayErase = Ext.Array.erase, + dependencyProperties = ['extend', 'mixins', 'requires'], + isInHistory = {}, + history = [], + slashDotSlashRe = /\/\.\//g, + dotRe = /\./g; + + Ext.apply(Loader, { + + /** + * @private + */ + isInHistory: isInHistory, + + /** + * An array of class names to keep track of the dependency loading order. + * This is not guaranteed to be the same everytime due to the asynchronous + * nature of the Loader. + * + * @property {Array} history + */ + history: history, + + /** + * Configuration + * @private + */ + config: { + /** + * @cfg {Boolean} enabled + * Whether or not to enable the dynamic dependency loading feature. + */ + enabled: false, + + /** + * @cfg {Boolean} scriptChainDelay + * millisecond delay between asynchronous script injection (prevents stack overflow on some user agents) + * 'false' disables delay but potentially increases stack load. + */ + scriptChainDelay : false, + + /** + * @cfg {Boolean} disableCaching + * Appends current timestamp to script files to prevent caching. + */ + disableCaching: true, + + /** + * @cfg {String} disableCachingParam + * The get parameter name for the cache buster's timestamp. + */ + disableCachingParam: '_dc', + + /** + * @cfg {Boolean} garbageCollect + * True to prepare an asynchronous script tag for garbage collection (effective only + * if {@link #preserveScripts preserveScripts} is false) + */ + garbageCollect : false, + + /** + * @cfg {Object} paths + * The mapping from namespaces to file paths + * + * { + * 'Ext': '.', // This is set by default, Ext.layout.container.Container will be + * // loaded from ./layout/Container.js + * + * 'My': './src/my_own_folder' // My.layout.Container will be loaded from + * // ./src/my_own_folder/layout/Container.js + * } + * + * Note that all relative paths are relative to the current HTML document. + * If not being specified, for example, Other.awesome.Class + * will simply be loaded from ./Other/awesome/Class.js + */ + paths: { + 'Ext': '.' + }, + + /** + * @cfg {Boolean} preserveScripts + * False to remove and optionally {@link #garbageCollect garbage-collect} asynchronously loaded scripts, + * True to retain script element for browser debugger compatibility and improved load performance. + */ + preserveScripts : true, + + /** + * @cfg {String} scriptCharset + * Optional charset to specify encoding of dynamic script content. + */ + scriptCharset : undefined + }, + + /** + * Set the configuration for the loader. This should be called right after ext-(debug).js + * is included in the page, and before Ext.onReady. i.e: + * + * + * + * + * + * Refer to config options of {@link Ext.Loader} for the list of possible properties + * + * @param {Object} config The config object to override the default values + * @return {Ext.Loader} this + */ + setConfig: function(name, value) { + if (Ext.isObject(name) && arguments.length === 1) { + Ext.merge(Loader.config, name); + } + else { + Loader.config[name] = (Ext.isObject(value)) ? Ext.merge(Loader.config[name], value) : value; + } + + return Loader; + }, + + /** + * Get the config value corresponding to the specified name. If no name is given, will return the config object + * @param {String} name The config property name + * @return {Object} + */ + getConfig: function(name) { + if (name) { + return Loader.config[name]; + } + + return Loader.config; + }, + + /** + * Sets the path of a namespace. + * For Example: + * + * Ext.Loader.setPath('Ext', '.'); + * + * @param {String/Object} name See {@link Ext.Function#flexSetter flexSetter} + * @param {String} path See {@link Ext.Function#flexSetter flexSetter} + * @return {Ext.Loader} this + * @method + */ + setPath: flexSetter(function(name, path) { + Loader.config.paths[name] = path; + + return Loader; + }), + + /** + * Translates a className to a file path by adding the + * the proper prefix and converting the .'s to /'s. For example: + * + * Ext.Loader.setPath('My', '/path/to/My'); + * + * alert(Ext.Loader.getPath('My.awesome.Class')); // alerts '/path/to/My/awesome/Class.js' + * + * Note that the deeper namespace levels, if explicitly set, are always resolved first. For example: + * + * Ext.Loader.setPath({ + * 'My': '/path/to/lib', + * 'My.awesome': '/other/path/for/awesome/stuff', + * 'My.awesome.more': '/more/awesome/path' + * }); + * + * alert(Ext.Loader.getPath('My.awesome.Class')); // alerts '/other/path/for/awesome/stuff/Class.js' + * + * alert(Ext.Loader.getPath('My.awesome.more.Class')); // alerts '/more/awesome/path/Class.js' + * + * alert(Ext.Loader.getPath('My.cool.Class')); // alerts '/path/to/lib/cool/Class.js' + * + * alert(Ext.Loader.getPath('Unknown.strange.Stuff')); // alerts 'Unknown/strange/Stuff.js' + * + * @param {String} className + * @return {String} path + */ + getPath: function(className) { + var path = '', + paths = Loader.config.paths, + prefix = Loader.getPrefix(className); + + if (prefix.length > 0) { + if (prefix === className) { + return paths[prefix]; + } + + path = paths[prefix]; + className = className.substring(prefix.length + 1); + } + + if (path.length > 0) { + path += '/'; + } + + return path.replace(slashDotSlashRe, '/') + className.replace(dotRe, "/") + '.js'; + }, + + /** + * @private + * @param {String} className + */ + getPrefix: function(className) { + var paths = Loader.config.paths, + prefix, deepestPrefix = ''; + + if (paths.hasOwnProperty(className)) { + return className; + } + + for (prefix in paths) { + if (paths.hasOwnProperty(prefix) && prefix + '.' === className.substring(0, prefix.length + 1)) { + if (prefix.length > deepestPrefix.length) { + deepestPrefix = prefix; + } + } + } + + return deepestPrefix; + }, + + /** + * @private + * @param {String} className + */ + isAClassNameWithAKnownPrefix: function(className) { + var prefix = Loader.getPrefix(className); + + // we can only say it's really a class if className is not equal to any known namespace + return prefix !== '' && prefix !== className; + }, + + /** + * Loads all classes by the given names and all their direct dependencies; optionally executes the given callback function when + * finishes, within the optional scope. This method is aliased by {@link Ext#require Ext.require} for convenience + * @param {String/Array} expressions Can either be a string or an array of string + * @param {Function} fn (Optional) The callback function + * @param {Object} scope (Optional) The execution scope (`this`) of the callback function + * @param {String/Array} excludes (Optional) Classes to be excluded, useful when being used with expressions + */ + require: function(expressions, fn, scope, excludes) { + if (fn) { + fn.call(scope); + } + }, + + /** + * Synchronously loads all classes by the given names and all their direct dependencies; optionally executes the given callback function when finishes, within the optional scope. This method is aliased by {@link Ext#syncRequire} for convenience + * @param {String/Array} expressions Can either be a string or an array of string + * @param {Function} fn (Optional) The callback function + * @param {Object} scope (Optional) The execution scope (`this`) of the callback function + * @param {String/Array} excludes (Optional) Classes to be excluded, useful when being used with expressions + */ + syncRequire: function() {}, + + /** + * Explicitly exclude files from being loaded. Useful when used in conjunction with a broad include expression. + * Can be chained with more `require` and `exclude` methods, eg: + * + * Ext.exclude('Ext.data.*').require('*'); + * + * Ext.exclude('widget.button*').require('widget.*'); + * + * @param {Array} excludes + * @return {Object} object contains `require` method for chaining + */ + exclude: function(excludes) { + return { + require: function(expressions, fn, scope) { + return Loader.require(expressions, fn, scope, excludes); + }, + + syncRequire: function(expressions, fn, scope) { + return Loader.syncRequire(expressions, fn, scope, excludes); + } + }; + }, + + /** + * Add a new listener to be executed when all required scripts are fully loaded + * + * @param {Function} fn The function callback to be executed + * @param {Object} scope The execution scope (this) of the callback function + * @param {Boolean} withDomReady Whether or not to wait for document dom ready as well + */ + onReady: function(fn, scope, withDomReady, options) { + var oldFn; + + if (withDomReady !== false && Ext.onDocumentReady) { + oldFn = fn; + + fn = function() { + Ext.onDocumentReady(oldFn, scope, options); + }; + } + + fn.call(scope); + } + }); + + var queue = [], + isClassFileLoaded = {}, + isFileLoaded = {}, + classNameToFilePathMap = {}, + scriptElements = {}, + readyListeners = [], + usedClasses = [], + requiresMap = {}; + + Ext.apply(Loader, { + /** + * @private + */ + documentHead: typeof document != 'undefined' && (document.head || document.getElementsByTagName('head')[0]), + + /** + * Flag indicating whether there are still files being loaded + * @private + */ + isLoading: false, + + /** + * Maintain the queue for all dependencies. Each item in the array is an object of the format: + * + * { + * requires: [...], // The required classes for this queue item + * callback: function() { ... } // The function to execute when all classes specified in requires exist + * } + * + * @private + */ + queue: queue, + + /** + * Maintain the list of files that have already been handled so that they never get double-loaded + * @private + */ + isClassFileLoaded: isClassFileLoaded, + + /** + * @private + */ + isFileLoaded: isFileLoaded, + + /** + * Maintain the list of listeners to execute when all required scripts are fully loaded + * @private + */ + readyListeners: readyListeners, + + /** + * Contains classes referenced in `uses` properties. + * @private + */ + optionalRequires: usedClasses, + + /** + * Map of fully qualified class names to an array of dependent classes. + * @private + */ + requiresMap: requiresMap, + + /** + * @private + */ + numPendingFiles: 0, + + /** + * @private + */ + numLoadedFiles: 0, + + /** @private */ + hasFileLoadError: false, + + /** + * @private + */ + classNameToFilePathMap: classNameToFilePathMap, + + /** + * The number of scripts loading via loadScript. + * @private + */ + scriptsLoading: 0, + + /** + * @private + */ + syncModeEnabled: false, + + scriptElements: scriptElements, + + /** + * Refresh all items in the queue. If all dependencies for an item exist during looping, + * it will execute the callback and call refreshQueue again. Triggers onReady when the queue is + * empty + * @private + */ + refreshQueue: function() { + var ln = queue.length, + i, item, j, requires; + + // When the queue of loading classes reaches zero, trigger readiness + + if (!ln && !Loader.scriptsLoading) { + return Loader.triggerReady(); + } + + for (i = 0; i < ln; i++) { + item = queue[i]; + + if (item) { + requires = item.requires; + + // Don't bother checking when the number of files loaded + // is still less than the array length + if (requires.length > Loader.numLoadedFiles) { + continue; + } + + // Remove any required classes that are loaded + for (j = 0; j < requires.length; ) { + if (Manager.isCreated(requires[j])) { + // Take out from the queue + arrayErase(requires, j, 1); + } + else { + j++; + } + } + + // If we've ended up with no required classes, call the callback + if (item.requires.length === 0) { + arrayErase(queue, i, 1); + item.callback.call(item.scope); + Loader.refreshQueue(); + break; + } + } + } + + return Loader; + }, + + /** + * Inject a script element to document's head, call onLoad and onError accordingly + * @private + */ + injectScriptElement: function(url, onLoad, onError, scope, charset) { + var script = document.createElement('script'), + dispatched = false, + config = Loader.config, + onLoadFn = function() { + + if(!dispatched) { + dispatched = true; + script.onload = script.onreadystatechange = script.onerror = null; + if (typeof config.scriptChainDelay == 'number') { + //free the stack (and defer the next script) + defer(onLoad, config.scriptChainDelay, scope); + } else { + onLoad.call(scope); + } + Loader.cleanupScriptElement(script, config.preserveScripts === false, config.garbageCollect); + } + + }, + onErrorFn = function(arg) { + defer(onError, 1, scope); //free the stack + Loader.cleanupScriptElement(script, config.preserveScripts === false, config.garbageCollect); + }; + + script.type = 'text/javascript'; + script.onerror = onErrorFn; + charset = charset || config.scriptCharset; + if (charset) { + script.charset = charset; + } + + /* + * IE9 Standards mode (and others) SHOULD follow the load event only + * (Note: IE9 supports both onload AND readystatechange events) + */ + if ('addEventListener' in script ) { + script.onload = onLoadFn; + } else if ('readyState' in script) { // for = 200 && status < 300) || (status === 304) + ) { + // Debugger friendly, file names are still shown even though they're eval'ed code + // Breakpoints work on both Firebug and Chrome's Web Inspector + Ext.globalEval(xhr.responseText + "\n//@ sourceURL=" + url); + + onLoad.call(scope); + } + else { + onError.call(Loader, "Failed loading synchronously via XHR: '" + url + "'; please " + + "verify that the file exists. " + + "XHR status code: " + status, synchronous); + } + + // Prevent potential IE memory leak + xhr = null; + } + }, + + // documented above + syncRequire: function() { + var syncModeEnabled = Loader.syncModeEnabled; + + if (!syncModeEnabled) { + Loader.syncModeEnabled = true; + } + + Loader.require.apply(Loader, arguments); + + if (!syncModeEnabled) { + Loader.syncModeEnabled = false; + } + + Loader.refreshQueue(); + }, + + // documented above + require: function(expressions, fn, scope, excludes) { + var excluded = {}, + included = {}, + excludedClassNames = [], + possibleClassNames = [], + classNames = [], + references = [], + callback, + syncModeEnabled, + filePath, expression, exclude, className, + possibleClassName, i, j, ln, subLn; + + if (excludes) { + // Convert possible single string to an array. + excludes = (typeof excludes === 'string') ? [ excludes ] : excludes; + + for (i = 0,ln = excludes.length; i < ln; i++) { + exclude = excludes[i]; + + if (typeof exclude == 'string' && exclude.length > 0) { + excludedClassNames = Manager.getNamesByExpression(exclude); + + for (j = 0,subLn = excludedClassNames.length; j < subLn; j++) { + excluded[excludedClassNames[j]] = true; + } + } + } + } + + // Convert possible single string to an array. + expressions = (typeof expressions === 'string') ? [ expressions ] : (expressions ? expressions : []); + + if (fn) { + if (fn.length > 0) { + callback = function() { + var classes = [], + i, ln; + + for (i = 0,ln = references.length; i < ln; i++) { + classes.push(Manager.get(references[i])); + } + + return fn.apply(this, classes); + }; + } + else { + callback = fn; + } + } + else { + callback = Ext.emptyFn; + } + + scope = scope || Ext.global; + + for (i = 0,ln = expressions.length; i < ln; i++) { + expression = expressions[i]; + + if (typeof expression == 'string' && expression.length > 0) { + possibleClassNames = Manager.getNamesByExpression(expression); + subLn = possibleClassNames.length; + + for (j = 0; j < subLn; j++) { + possibleClassName = possibleClassNames[j]; + + if (excluded[possibleClassName] !== true) { + references.push(possibleClassName); + + if (!Manager.isCreated(possibleClassName) && !included[possibleClassName]) { + included[possibleClassName] = true; + classNames.push(possibleClassName); + } + } + } + } + } + + // If the dynamic dependency feature is not being used, throw an error + // if the dependencies are not defined + if (classNames.length > 0) { + if (!Loader.config.enabled) { + throw new Error("Ext.Loader is not enabled, so dependencies cannot be resolved dynamically. " + + "Missing required class" + ((classNames.length > 1) ? "es" : "") + ": " + classNames.join(', ')); + } + } + else { + callback.call(scope); + return Loader; + } + + syncModeEnabled = Loader.syncModeEnabled; + + if (!syncModeEnabled) { + queue.push({ + requires: classNames.slice(), // this array will be modified as the queue is processed, + // so we need a copy of it + callback: callback, + scope: scope + }); + } + + ln = classNames.length; + + for (i = 0; i < ln; i++) { + className = classNames[i]; + + filePath = Loader.getPath(className); + + // If we are synchronously loading a file that has already been asychronously loaded before + // we need to destroy the script tag and revert the count + // This file will then be forced loaded in synchronous + if (syncModeEnabled && isClassFileLoaded.hasOwnProperty(className)) { + Loader.numPendingFiles--; + Loader.removeScriptElement(filePath); + delete isClassFileLoaded[className]; + } + + if (!isClassFileLoaded.hasOwnProperty(className)) { + isClassFileLoaded[className] = false; + + classNameToFilePathMap[className] = filePath; + + Loader.numPendingFiles++; + Loader.loadScriptFile( + filePath, + pass(Loader.onFileLoaded, [className, filePath], Loader), + pass(Loader.onFileLoadError, [className, filePath], Loader), + Loader, + syncModeEnabled + ); + } + } + + if (syncModeEnabled) { + callback.call(scope); + + if (ln === 1) { + return Manager.get(className); + } + } + + return Loader; + }, + + /** + * @private + * @param {String} className + * @param {String} filePath + */ + onFileLoaded: function(className, filePath) { + Loader.numLoadedFiles++; + + isClassFileLoaded[className] = true; + isFileLoaded[filePath] = true; + + Loader.numPendingFiles--; + + if (Loader.numPendingFiles === 0) { + Loader.refreshQueue(); + } + + if (!Loader.syncModeEnabled && Loader.numPendingFiles === 0 && Loader.isLoading && !Loader.hasFileLoadError) { + var missingClasses = [], + missingPaths = [], + requires, + i, ln, j, subLn; + + for (i = 0,ln = queue.length; i < ln; i++) { + requires = queue[i].requires; + + for (j = 0,subLn = requires.length; j < subLn; j++) { + if (isClassFileLoaded[requires[j]]) { + missingClasses.push(requires[j]); + } + } + } + + if (missingClasses.length < 1) { + return; + } + + missingClasses = Ext.Array.filter(Ext.Array.unique(missingClasses), function(item) { + return !requiresMap.hasOwnProperty(item); + }, Loader); + + for (i = 0,ln = missingClasses.length; i < ln; i++) { + missingPaths.push(classNameToFilePathMap[missingClasses[i]]); + } + + throw new Error("The following classes are not declared even if their files have been " + + "loaded: '" + missingClasses.join("', '") + "'. Please check the source code of their " + + "corresponding files for possible typos: '" + missingPaths.join("', '")); + } + }, + + /** + * @private + */ + onFileLoadError: function(className, filePath, errorMessage, isSynchronous) { + Loader.numPendingFiles--; + Loader.hasFileLoadError = true; + + throw new Error("[Ext.Loader] " + errorMessage); + }, + + /** + * @private + * Ensure that any classes referenced in the `uses` property are loaded. + */ + addUsedClasses: function (classes) { + var cls, i, ln; + + if (classes) { + classes = (typeof classes == 'string') ? [classes] : classes; + for (i = 0, ln = classes.length; i < ln; i++) { + cls = classes[i]; + if (typeof cls == 'string' && !Ext.Array.contains(usedClasses, cls)) { + usedClasses.push(cls); + } + } + } + + return Loader; + }, + + /** + * @private + */ + triggerReady: function() { + var listener, + i, refClasses = usedClasses; + + if (Loader.isLoading) { + Loader.isLoading = false; + + if (refClasses.length !== 0) { + // Clone then empty the array to eliminate potential recursive loop issue + refClasses = refClasses.slice(); + usedClasses.length = 0; + // this may immediately call us back if all 'uses' classes + // have been loaded + Loader.require(refClasses, Loader.triggerReady, Loader); + return Loader; + } + } + + // this method can be called with Loader.isLoading either true or false + // (can be called with false when all 'uses' classes are already loaded) + // this may bypass the above if condition + while (readyListeners.length && !Loader.isLoading) { + // calls to refreshQueue may re-enter triggerReady + // so we cannot necessarily iterate the readyListeners array + listener = readyListeners.shift(); + listener.fn.call(listener.scope); + } + + return Loader; + }, + + // Documented above already + onReady: function(fn, scope, withDomReady, options) { + var oldFn; + + if (withDomReady !== false && Ext.onDocumentReady) { + oldFn = fn; + + fn = function() { + Ext.onDocumentReady(oldFn, scope, options); + }; + } + + if (!Loader.isLoading) { + fn.call(scope); + } + else { + readyListeners.push({ + fn: fn, + scope: scope + }); + } + }, + + /** + * @private + * @param {String} className + */ + historyPush: function(className) { + if (className && isClassFileLoaded.hasOwnProperty(className) && !isInHistory[className]) { + isInHistory[className] = true; + history.push(className); + } + return Loader; + } + }); + + /** + * Turns on or off the "cache buster" applied to dynamically loaded scripts. Normally + * dynamically loaded scripts have an extra query parameter appended to avoid stale + * cached scripts. This method can be used to disable this mechanism, and is primarily + * useful for testing. This is done using a cookie. + * @param {Boolean} disable True to disable the cache buster. + * @param {String} [path="/"] An optional path to scope the cookie. + * @private + */ + Ext.disableCacheBuster = function (disable, path) { + var date = new Date(); + date.setTime(date.getTime() + (disable ? 10*365 : -1) * 24*60*60*1000); + date = date.toGMTString(); + document.cookie = 'ext-cache=1; expires=' + date + '; path='+(path || '/'); + }; + + + /** + * Convenient alias of {@link Ext.Loader#require}. Please see the introduction documentation of + * {@link Ext.Loader} for examples. + * @member Ext + * @method require + */ + Ext.require = alias(Loader, 'require'); + + /** + * Synchronous version of {@link Ext#require}, convenient alias of {@link Ext.Loader#syncRequire}. + * + * @member Ext + * @method syncRequire + */ + Ext.syncRequire = alias(Loader, 'syncRequire'); + + /** + * Convenient shortcut to {@link Ext.Loader#exclude} + * @member Ext + * @method exclude + */ + Ext.exclude = alias(Loader, 'exclude'); + + /** + * @member Ext + * @method onReady + */ + Ext.onReady = function(fn, scope, options) { + Loader.onReady(fn, scope, true, options); + }; + + /** + * @cfg {String[]} requires + * @member Ext.Class + * List of classes that have to be loaded before instantiating this class. + * For example: + * + * Ext.define('Mother', { + * requires: ['Child'], + * giveBirth: function() { + * // we can be sure that child class is available. + * return new Child(); + * } + * }); + */ + Class.registerPreprocessor('loader', function(cls, data, hooks, continueFn) { + var me = this, + dependencies = [], + dependency, + className = Manager.getName(cls), + i, j, ln, subLn, value, propertyName, propertyValue, + requiredMap, requiredDep; + + /* + Loop through the dependencyProperties, look for string class names and push + them into a stack, regardless of whether the property's value is a string, array or object. For example: + { + extend: 'Ext.MyClass', + requires: ['Ext.some.OtherClass'], + mixins: { + observable: 'Ext.util.Observable'; + } + } + which will later be transformed into: + { + extend: Ext.MyClass, + requires: [Ext.some.OtherClass], + mixins: { + observable: Ext.util.Observable; + } + } + */ + + for (i = 0,ln = dependencyProperties.length; i < ln; i++) { + propertyName = dependencyProperties[i]; + + if (data.hasOwnProperty(propertyName)) { + propertyValue = data[propertyName]; + + if (typeof propertyValue == 'string') { + dependencies.push(propertyValue); + } + else if (propertyValue instanceof Array) { + for (j = 0, subLn = propertyValue.length; j < subLn; j++) { + value = propertyValue[j]; + + if (typeof value == 'string') { + dependencies.push(value); + } + } + } + else if (typeof propertyValue != 'function') { + for (j in propertyValue) { + if (propertyValue.hasOwnProperty(j)) { + value = propertyValue[j]; + + if (typeof value == 'string') { + dependencies.push(value); + } + } + } + } + } + } + + if (dependencies.length === 0) { + return; + } + + var deadlockPath = [], + detectDeadlock; + + /* + Automatically detect deadlocks before-hand, + will throw an error with detailed path for ease of debugging. Examples of deadlock cases: + + - A extends B, then B extends A + - A requires B, B requires C, then C requires A + + The detectDeadlock function will recursively transverse till the leaf, hence it can detect deadlocks + no matter how deep the path is. + */ + + if (className) { + requiresMap[className] = dependencies; + requiredMap = Loader.requiredByMap || (Loader.requiredByMap = {}); + + for (i = 0,ln = dependencies.length; i < ln; i++) { + dependency = dependencies[i]; + (requiredMap[dependency] || (requiredMap[dependency] = [])).push(className); + } + detectDeadlock = function(cls) { + deadlockPath.push(cls); + + if (requiresMap[cls]) { + if (Ext.Array.contains(requiresMap[cls], className)) { + throw new Error("Deadlock detected while loading dependencies! '" + className + "' and '" + + deadlockPath[1] + "' " + "mutually require each other. Path: " + + deadlockPath.join(' -> ') + " -> " + deadlockPath[0]); + } + + for (i = 0,ln = requiresMap[cls].length; i < ln; i++) { + detectDeadlock(requiresMap[cls][i]); + } + } + }; + + detectDeadlock(className); + } + + + Loader.require(dependencies, function() { + for (i = 0,ln = dependencyProperties.length; i < ln; i++) { + propertyName = dependencyProperties[i]; + + if (data.hasOwnProperty(propertyName)) { + propertyValue = data[propertyName]; + + if (typeof propertyValue == 'string') { + data[propertyName] = Manager.get(propertyValue); + } + else if (propertyValue instanceof Array) { + for (j = 0, subLn = propertyValue.length; j < subLn; j++) { + value = propertyValue[j]; + + if (typeof value == 'string') { + data[propertyName][j] = Manager.get(value); + } + } + } + else if (typeof propertyValue != 'function') { + for (var k in propertyValue) { + if (propertyValue.hasOwnProperty(k)) { + value = propertyValue[k]; + + if (typeof value == 'string') { + data[propertyName][k] = Manager.get(value); + } + } + } + } + } + } + + continueFn.call(me, cls, data, hooks); + }); + + return false; + }, true, 'after', 'className'); + + /** + * @cfg {String[]} uses + * @member Ext.Class + * List of optional classes to load together with this class. These aren't neccessarily loaded before + * this class is created, but are guaranteed to be available before Ext.onReady listeners are + * invoked. For example: + * + * Ext.define('Mother', { + * uses: ['Child'], + * giveBirth: function() { + * // This code might, or might not work: + * // return new Child(); + * + * // Instead use Ext.create() to load the class at the spot if not loaded already: + * return Ext.create('Child'); + * } + * }); + */ + Manager.registerPostprocessor('uses', function(name, cls, data) { + var uses = data.uses; + if (uses) { + Loader.addUsedClasses(uses); + } + }); + + Manager.onCreated(Loader.historyPush); +}; + +/** + * @author Brian Moeskau + * @docauthor Brian Moeskau + * + * A wrapper class for the native JavaScript Error object that adds a few useful capabilities for handling + * errors in an Ext application. When you use Ext.Error to {@link #raise} an error from within any class that + * uses the Ext 4 class system, the Error class can automatically add the source class and method from which + * the error was raised. It also includes logic to automatically log the eroor to the console, if available, + * with additional metadata about the error. In all cases, the error will always be thrown at the end so that + * execution will halt. + * + * Ext.Error also offers a global error {@link #handle handling} method that can be overridden in order to + * handle application-wide errors in a single spot. You can optionally {@link #ignore} errors altogether, + * although in a real application it's usually a better idea to override the handling function and perform + * logging or some other method of reporting the errors in a way that is meaningful to the application. + * + * At its simplest you can simply raise an error as a simple string from within any code: + * + * Example usage: + * + * Ext.Error.raise('Something bad happened!'); + * + * If raised from plain JavaScript code, the error will be logged to the console (if available) and the message + * displayed. In most cases however you'll be raising errors from within a class, and it may often be useful to add + * additional metadata about the error being raised. The {@link #raise} method can also take a config object. + * In this form the `msg` attribute becomes the error description, and any other data added to the config gets + * added to the error object and, if the console is available, logged to the console for inspection. + * + * Example usage: + * + * Ext.define('Ext.Foo', { + * doSomething: function(option){ + * if (someCondition === false) { + * Ext.Error.raise({ + * msg: 'You cannot do that!', + * option: option, // whatever was passed into the method + * 'error code': 100 // other arbitrary info + * }); + * } + * } + * }); + * + * If a console is available (that supports the `console.dir` function) you'll see console output like: + * + * An error was raised with the following data: + * option: Object { foo: "bar"} + * foo: "bar" + * error code: 100 + * msg: "You cannot do that!" + * sourceClass: "Ext.Foo" + * sourceMethod: "doSomething" + * + * uncaught exception: You cannot do that! + * + * As you can see, the error will report exactly where it was raised and will include as much information as the + * raising code can usefully provide. + * + * If you want to handle all application errors globally you can simply override the static {@link #handle} method + * and provide whatever handling logic you need. If the method returns true then the error is considered handled + * and will not be thrown to the browser. If anything but true is returned then the error will be thrown normally. + * + * Example usage: + * + * Ext.Error.handle = function(err) { + * if (err.someProperty == 'NotReallyAnError') { + * // maybe log something to the application here if applicable + * return true; + * } + * // any non-true return value (including none) will cause the error to be thrown + * } + * + */ +Ext.Error = Ext.extend(Error, { + statics: { + /** + * @property {Boolean} ignore + * Static flag that can be used to globally disable error reporting to the browser if set to true + * (defaults to false). Note that if you ignore Ext errors it's likely that some other code may fail + * and throw a native JavaScript error thereafter, so use with caution. In most cases it will probably + * be preferable to supply a custom error {@link #handle handling} function instead. + * + * Example usage: + * + * Ext.Error.ignore = true; + * + * @static + */ + ignore: false, + + /** + * @property {Boolean} notify + * Static flag that can be used to globally control error notification to the user. Unlike + * Ex.Error.ignore, this does not effect exceptions. They are still thrown. This value can be + * set to false to disable the alert notification (default is true for IE6 and IE7). + * + * Only the first error will generate an alert. Internally this flag is set to false when the + * first error occurs prior to displaying the alert. + * + * This flag is not used in a release build. + * + * Example usage: + * + * Ext.Error.notify = false; + * + * @static + */ + //notify: Ext.isIE6 || Ext.isIE7, + + /** + * Raise an error that can include additional data and supports automatic console logging if available. + * You can pass a string error message or an object with the `msg` attribute which will be used as the + * error message. The object can contain any other name-value attributes (or objects) to be logged + * along with the error. + * + * Note that after displaying the error message a JavaScript error will ultimately be thrown so that + * execution will halt. + * + * Example usage: + * + * Ext.Error.raise('A simple string error message'); + * + * // or... + * + * Ext.define('Ext.Foo', { + * doSomething: function(option){ + * if (someCondition === false) { + * Ext.Error.raise({ + * msg: 'You cannot do that!', + * option: option, // whatever was passed into the method + * 'error code': 100 // other arbitrary info + * }); + * } + * } + * }); + * + * @param {String/Object} err The error message string, or an object containing the attribute "msg" that will be + * used as the error message. Any other data included in the object will also be logged to the browser console, + * if available. + * @static + */ + raise: function(err){ + err = err || {}; + if (Ext.isString(err)) { + err = { msg: err }; + } + + var method = this.raise.caller, + msg; + + if (method) { + if (method.$name) { + err.sourceMethod = method.$name; + } + if (method.$owner) { + err.sourceClass = method.$owner.$className; + } + } + + if (Ext.Error.handle(err) !== true) { + msg = Ext.Error.prototype.toString.call(err); + + Ext.log({ + msg: msg, + level: 'error', + dump: err, + stack: true + }); + + throw new Ext.Error(err); + } + }, + + /** + * Globally handle any Ext errors that may be raised, optionally providing custom logic to + * handle different errors individually. Return true from the function to bypass throwing the + * error to the browser, otherwise the error will be thrown and execution will halt. + * + * Example usage: + * + * Ext.Error.handle = function(err) { + * if (err.someProperty == 'NotReallyAnError') { + * // maybe log something to the application here if applicable + * return true; + * } + * // any non-true return value (including none) will cause the error to be thrown + * } + * + * @param {Ext.Error} err The Ext.Error object being raised. It will contain any attributes that were originally + * raised with it, plus properties about the method and class from which the error originated (if raised from a + * class that uses the Ext 4 class system). + * @static + */ + handle: function(){ + return Ext.Error.ignore; + } + }, + + // This is the standard property that is the name of the constructor. + name: 'Ext.Error', + + /** + * Creates new Error object. + * @param {String/Object} config The error message string, or an object containing the + * attribute "msg" that will be used as the error message. Any other data included in + * the object will be applied to the error instance and logged to the browser console, if available. + */ + constructor: function(config){ + if (Ext.isString(config)) { + config = { msg: config }; + } + + var me = this; + + Ext.apply(me, config); + + me.message = me.message || me.msg; // 'message' is standard ('msg' is non-standard) + // note: the above does not work in old WebKit (me.message is readonly) (Safari 4) + }, + + /** + * Provides a custom string representation of the error object. This is an override of the base JavaScript + * `Object.toString` method, which is useful so that when logged to the browser console, an error object will + * be displayed with a useful message instead of `[object Object]`, the default `toString` result. + * + * The default implementation will include the error message along with the raising class and method, if available, + * but this can be overridden with a custom implementation either at the prototype level (for all errors) or on + * a particular error instance, if you want to provide a custom description that will show up in the console. + * @return {String} The error message. If raised from within the Ext 4 class system, the error message will also + * include the raising class and method names, if available. + */ + toString: function(){ + var me = this, + className = me.sourceClass ? me.sourceClass : '', + methodName = me.sourceMethod ? '.' + me.sourceMethod + '(): ' : '', + msg = me.msg || '(No description provided)'; + + return className + methodName + msg; + } +}); + +/* + * Create a function that will throw an error if called (in debug mode) with a message that + * indicates the method has been removed. + * @param {String} suggestion Optional text to include in the message (a workaround perhaps). + * @return {Function} The generated function. + * @private + */ +Ext.deprecated = function (suggestion) { + if (!suggestion) { + suggestion = ''; + } + + function fail () { + Ext.Error.raise('The method "' + fail.$owner.$className + '.' + fail.$name + + '" has been removed. ' + suggestion); + } + + return fail; + return Ext.emptyFn; +}; + +/* + * This mechanism is used to notify the user of the first error encountered on the page. This + * was previously internal to Ext.Error.raise and is a desirable feature since errors often + * slip silently under the radar. It cannot live in Ext.Error.raise since there are times + * where exceptions are handled in a try/catch. + */ +(function () { + var timer, errors = 0, + win = Ext.global, + msg; + + if (typeof window === 'undefined') { + return; // build system or some such environment... + } + + // This method is called to notify the user of the current error status. + function notify () { + var counters = Ext.log.counters, + supports = Ext.supports, + hasOnError = supports && supports.WindowOnError; // TODO - timing + + // Put log counters to the status bar (for most browsers): + if (counters && (counters.error + counters.warn + counters.info + counters.log)) { + msg = [ 'Logged Errors:',counters.error, 'Warnings:',counters.warn, + 'Info:',counters.info, 'Log:',counters.log].join(' '); + if (errors) { + msg = '*** Errors: ' + errors + ' - ' + msg; + } else if (counters.error) { + msg = '*** ' + msg; + } + win.status = msg; + } + + // Display an alert on the first error: + if (!Ext.isDefined(Ext.Error.notify)) { + Ext.Error.notify = Ext.isIE6 || Ext.isIE7; // TODO - timing + } + if (Ext.Error.notify && (hasOnError ? errors : (counters && counters.error))) { + Ext.Error.notify = false; + + if (timer) { + win.clearInterval(timer); // ticks can queue up so stop... + timer = null; + } + + alert('Unhandled error on page: See console or log'); + poll(); + } + } + + // Sets up polling loop. This is the only way to know about errors in some browsers + // (Opera/Safari) and is the only way to update the status bar for warnings and other + // non-errors. + function poll () { + timer = win.setInterval(notify, 1000); + } + + // window.onerror sounds ideal but it prevents the built-in error dialog from doing + // its (better) thing. + poll(); +}()); + + +/** + * @class Ext.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.JSON = (new(function() { + var me = this, + encodingFunction, + decodingFunction, + useNative = null, + useHasOwn = !! {}.hasOwnProperty, + isNative = function() { + if (useNative === null) { + useNative = Ext.USE_NATIVE_JSON && window.JSON && JSON.toString() == '[object JSON]'; + } + return useNative; + }, + pad = function(n) { + return n < 10 ? "0" + n : n; + }, + doDecode = function(json) { + return eval("(" + json + ')'); + }, + doEncode = function(o, newline) { + // http://jsperf.com/is-undefined + if (o === null || o === undefined) { + return "null"; + } else if (Ext.isDate(o)) { + return Ext.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); + } + // Allow custom zerialization by adding a toJSON method to any object type. + // Date/String have a toJSON in some environments, so check these first. + else if (o.toJSON) { + return o.toJSON(); + } else if (Ext.isArray(o)) { + return encodeArray(o, newline); + } else if (Ext.isObject(o)) { + return encodeObject(o, newline); + } else if (typeof o === "function") { + return "null"; + } + return 'undefined'; + }, + m = { + "\b": '\\b', + "\t": '\\t', + "\n": '\\n', + "\f": '\\f', + "\r": '\\r', + '"': '\\"', + "\\": '\\\\', + '\x0b': '\\u000b' //ie doesn't handle \v + }, + charToReplace = /[\\\"\x00-\x1f\x7f-\uffff]/g, + encodeString = function(s) { + return '"' + s.replace(charToReplace, function(a) { + var c = m[a]; + return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); + }) + '"'; + }, + + encodeArrayPretty = function(o, newline) { + var len = o.length, + cnewline = newline + ' ', + sep = ',' + cnewline, + a = ["[", cnewline], // Note newline in case there are no members + i; + + for (i = 0; i < len; i += 1) { + a.push(doEncode(o[i], cnewline), sep); + } + + // Overwrite trailing comma (or empty string) + a[a.length - 1] = newline + ']'; + + return a.join(''); + }, + + encodeObjectPretty = function(o, newline) { + var cnewline = newline + ' ', + sep = ',' + cnewline, + a = ["{", cnewline], // Note newline in case there are no members + i; + + for (i in o) { + if (!useHasOwn || o.hasOwnProperty(i)) { + a.push(doEncode(i) + ': ' + doEncode(o[i], cnewline), sep); + } + } + + // Overwrite trailing comma (or empty string) + a[a.length - 1] = newline + '}'; + + return a.join(''); + }, + + encodeArray = function(o, newline) { + if (newline) { + return encodeArrayPretty(o, newline); + } + + var a = ["[", ""], // Note empty string in case there are no serializable members. + len = o.length, + i; + for (i = 0; i < len; i += 1) { + a.push(doEncode(o[i]), ','); + } + // Overwrite trailing comma (or empty string) + a[a.length - 1] = ']'; + return a.join(""); + }, + + encodeObject = function(o, newline) { + if (newline) { + return encodeObjectPretty(o, newline); + } + + var a = ["{", ""], // Note empty string in case there are no serializable members. + i; + for (i in o) { + if (!useHasOwn || o.hasOwnProperty(i)) { + a.push(doEncode(i), ":", doEncode(o[i]), ','); + } + } + // Overwrite trailing comma (or empty string) + a[a.length - 1] = '}'; + return a.join(""); + }; + + /** + * The function which {@link #encode} uses to encode all javascript values to their JSON representations + * when {@link Ext#USE_NATIVE_JSON} is `false`. + * + * This is made public so that it can be replaced with a custom implementation. + * + * @param {Object} o Any javascript value to be converted to its JSON representation + * @return {String} The JSON representation of the passed value. + * @method + */ + me.encodeValue = doEncode; + + /** + * Encodes a Date. This returns the actual string which is inserted into the JSON string as the literal expression. + * **The returned value includes enclosing double quotation marks.** + * + * The default return format is "yyyy-mm-ddThh:mm:ss". + * + * To override this: + * Ext.JSON.encodeDate = function(d) { + * return Ext.Date.format(d, '"Y-m-d"'); + * }; + * + * @param {Date} d The Date to encode + * @return {String} The string literal to use in a JSON string. + */ + me.encodeDate = function(o) { + return '"' + o.getFullYear() + "-" + + pad(o.getMonth() + 1) + "-" + + pad(o.getDate()) + "T" + + pad(o.getHours()) + ":" + + pad(o.getMinutes()) + ":" + + pad(o.getSeconds()) + '"'; + }; + + /** + * Encodes an Object, Array or other value. + * + * If the environment's native JSON encoding is not being used ({@link Ext#USE_NATIVE_JSON} is not set, or the environment does not support it), then + * ExtJS's encoding will be used. This allows the developer to add a `toJSON` method to their classes which need serializing to return a valid + * JSON representation of the object. + * + * @param {Object} o The variable to encode + * @return {String} The JSON string + */ + me.encode = function(o) { + if (!encodingFunction) { + // setup encoding function on first access + encodingFunction = isNative() ? JSON.stringify : me.encodeValue; + } + return encodingFunction(o); + }; + + /** + * Decodes (parses) a JSON string to an object. If the JSON is invalid, this function throws a SyntaxError unless the safe option is set. + * @param {String} json The JSON string + * @param {Boolean} safe (optional) Whether to return null or throw an exception if the JSON is invalid. + * @return {Object} The resulting object + */ + me.decode = function(json, safe) { + if (!decodingFunction) { + // setup decoding function on first access + decodingFunction = isNative() ? JSON.parse : doDecode; + } + try { + return decodingFunction(json); + } catch (e) { + if (safe === true) { + return null; + } + Ext.Error.raise({ + sourceClass: "Ext.JSON", + sourceMethod: "decode", + msg: "You're trying to decode an invalid JSON String: " + json + }); + } + }; +})()); +/** + * Shorthand for {@link Ext.JSON#encode} + * @member Ext + * @method encode + * @inheritdoc Ext.JSON#encode + */ +Ext.encode = Ext.JSON.encode; +/** + * Shorthand for {@link Ext.JSON#decode} + * @member Ext + * @method decode + * @inheritdoc Ext.JSON#decode + */ +Ext.decode = Ext.JSON.decode; +/** + * @class Ext + * + * The Ext namespace (global object) encapsulates all classes, singletons, and + * utility methods provided by Sencha's libraries. + * + * Most user interface Components are at a lower level of nesting in the namespace, + * but many common utility functions are provided as direct properties of the Ext namespace. + * + * Also many frequently used methods from other classes are provided as shortcuts + * within the Ext namespace. For example {@link Ext#getCmp Ext.getCmp} aliases + * {@link Ext.ComponentManager#get Ext.ComponentManager.get}. + * + * Many applications are initiated with {@link Ext#onReady Ext.onReady} which is + * called once the DOM is ready. This ensures all scripts have been loaded, + * preventing dependency issues. For example: + * + * Ext.onReady(function(){ + * new Ext.Component({ + * renderTo: document.body, + * html: 'DOM ready!' + * }); + * }); + * + * For more information about how to use the Ext classes, see: + * + * - The Learning Center + * - The FAQ + * - The forums + * + * @singleton + */ +Ext.apply(Ext, { + userAgent: navigator.userAgent.toLowerCase(), + cache: {}, + idSeed: 1000, + windowId: 'ext-window', + documentId: 'ext-document', + + /** + * True when the document is fully initialized and ready for action + */ + isReady: false, + + /** + * True to automatically uncache orphaned Ext.Elements periodically + */ + enableGarbageCollector: true, + + /** + * True to automatically purge event listeners during garbageCollection. + */ + enableListenerCollection: true, + + addCacheEntry: function(id, el, dom) { + dom = dom || el.dom; + + if (!dom) { + // Without the DOM node we can't GC the entry + Ext.Error.raise('Cannot add an entry to the element cache without the DOM node'); + } + + var key = id || (el && el.id) || dom.id, + entry = Ext.cache[key] || (Ext.cache[key] = { + data: {}, + events: {}, + + dom: dom, + + // Skip garbage collection for special elements (window, document, iframes) + skipGarbageCollection: !!(dom.getElementById || dom.navigator) + }); + + if (el) { + el.$cache = entry; + // Inject the back link from the cache in case the cache entry + // had already been created by Ext.fly. Ext.fly creates a cache entry with no el link. + entry.el = el; + } + + return entry; + }, + + /** + * Generates unique ids. If the element already has an id, it is unchanged + * @param {HTMLElement/Ext.Element} [el] The element to generate an id for + * @param {String} prefix (optional) Id prefix (defaults "ext-gen") + * @return {String} The generated Id. + */ + id: function(el, prefix) { + var me = this, + sandboxPrefix = ''; + el = Ext.getDom(el, true) || {}; + if (el === document) { + el.id = me.documentId; + } + else if (el === window) { + el.id = me.windowId; + } + if (!el.id) { + if (me.isSandboxed) { + sandboxPrefix = Ext.sandboxName.toLowerCase() + '-'; + } + el.id = sandboxPrefix + (prefix || "ext-gen") + (++Ext.idSeed); + } + return el.id; + }, + + escapeId: (function(){ + var validIdRe = /^[a-zA-Z_][a-zA-Z0-9_\-]*$/i, + escapeRx = /([\W]{1})/g, + leadingNumRx = /^(\d)/g, + escapeFn = function(match, capture){ + return "\\" + capture; + }, + numEscapeFn = function(match, capture){ + return '\\00' + capture.charCodeAt(0).toString(16) + ' '; + }; + + return function(id) { + return validIdRe.test(id) + ? id + // replace the number portion last to keep the trailing ' ' + // from being escaped + : id.replace(escapeRx, escapeFn) + .replace(leadingNumRx, numEscapeFn); + }; + }()), + + /** + * Returns the current document body as an {@link Ext.Element}. + * @return Ext.Element The document body + */ + getBody: (function() { + var body; + return function() { + return body || (body = Ext.get(document.body)); + }; + }()), + + /** + * Returns the current document head as an {@link Ext.Element}. + * @return Ext.Element The document head + * @method + */ + getHead: (function() { + var head; + return function() { + return head || (head = Ext.get(document.getElementsByTagName("head")[0])); + }; + }()), + + /** + * Returns the current HTML document object as an {@link Ext.Element}. + * @return Ext.Element The document + */ + getDoc: (function() { + var doc; + return function() { + return doc || (doc = Ext.get(document)); + }; + }()), + + /** + * This is shorthand reference to {@link Ext.ComponentManager#get}. + * Looks up an existing {@link Ext.Component Component} by {@link Ext.Component#id id} + * + * @param {String} id The component {@link Ext.Component#id id} + * @return Ext.Component The Component, `undefined` if not found, or `null` if a + * Class was found. + */ + getCmp: function(id) { + return Ext.ComponentManager.get(id); + }, + + /** + * Returns the current orientation of the mobile device + * @return {String} Either 'portrait' or 'landscape' + */ + getOrientation: function() { + return window.innerHeight > window.innerWidth ? 'portrait' : 'landscape'; + }, + + /** + * Attempts to destroy any objects passed to it by removing all event listeners, removing them from the + * DOM (if applicable) and calling their destroy functions (if available). This method is primarily + * intended for arguments of type {@link Ext.Element} and {@link Ext.Component}, but any subclass of + * {@link Ext.util.Observable} can be passed in. Any number of elements and/or components can be + * passed into this function in a single call as separate arguments. + * + * @param {Ext.Element/Ext.Component/Ext.Element[]/Ext.Component[]...} args + * An {@link Ext.Element}, {@link Ext.Component}, or an Array of either of these to destroy + */ + destroy: function() { + var ln = arguments.length, + i, arg; + + for (i = 0; i < ln; i++) { + arg = arguments[i]; + if (arg) { + if (Ext.isArray(arg)) { + this.destroy.apply(this, arg); + } + else if (Ext.isFunction(arg.destroy)) { + arg.destroy(); + } + else if (arg.dom) { + arg.remove(); + } + } + } + }, + + /** + * Execute a callback function in a particular scope. If no function is passed the call is ignored. + * + * For example, these lines are equivalent: + * + * Ext.callback(myFunc, this, [arg1, arg2]); + * Ext.isFunction(myFunc) && myFunc.apply(this, [arg1, arg2]); + * + * @param {Function} callback The callback to execute + * @param {Object} [scope] The scope to execute in + * @param {Array} [args] The arguments to pass to the function + * @param {Number} [delay] Pass a number to delay the call by a number of milliseconds. + */ + callback: function(callback, scope, args, delay){ + if(Ext.isFunction(callback)){ + args = args || []; + scope = scope || window; + if (delay) { + Ext.defer(callback, delay, scope, args); + } else { + callback.apply(scope, args); + } + } + }, + + /** + * Alias for {@link Ext.String#htmlEncode}. + * @inheritdoc Ext.String#htmlEncode + */ + htmlEncode : function(value) { + return Ext.String.htmlEncode(value); + }, + + /** + * Alias for {@link Ext.String#htmlDecode}. + * @inheritdoc Ext.String#htmlDecode + */ + htmlDecode : function(value) { + return Ext.String.htmlDecode(value); + }, + + /** + * Alias for {@link Ext.String#urlAppend}. + * @inheritdoc Ext.String#urlAppend + */ + urlAppend : function(url, s) { + return Ext.String.urlAppend(url, s); + } +}); + + +Ext.ns = Ext.namespace; + +// for old browsers +window.undefined = window.undefined; + +/** + * @class Ext + */ +(function(){ +/* +FF 3.6 - Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.17) Gecko/20110420 Firefox/3.6.17 +FF 4.0.1 - Mozilla/5.0 (Windows NT 5.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1 +FF 5.0 - Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0 + +IE6 - Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1;) +IE7 - Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1;) +IE8 - Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0) +IE9 - Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E) + +Chrome 11 - Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.60 Safari/534.24 + +Safari 5 - Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1 + +Opera 11.11 - Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11 +*/ + var check = function(regex){ + return regex.test(Ext.userAgent); + }, + isStrict = document.compatMode == "CSS1Compat", + version = function (is, regex) { + var m; + return (is && (m = regex.exec(Ext.userAgent))) ? parseFloat(m[1]) : 0; + }, + docMode = document.documentMode, + isOpera = check(/opera/), + isOpera10_5 = isOpera && check(/version\/10\.5/), + isChrome = check(/\bchrome\b/), + isWebKit = check(/webkit/), + isSafari = !isChrome && check(/safari/), + isSafari2 = isSafari && check(/applewebkit\/4/), // unique to Safari 2 + isSafari3 = isSafari && check(/version\/3/), + isSafari4 = isSafari && check(/version\/4/), + isSafari5_0 = isSafari && check(/version\/5\.0/), + isSafari5 = isSafari && check(/version\/5/), + isIE = !isOpera && check(/msie/), + isIE7 = isIE && ((check(/msie 7/) && docMode != 8 && docMode != 9) || docMode == 7), + isIE8 = isIE && ((check(/msie 8/) && docMode != 7 && docMode != 9) || docMode == 8), + isIE9 = isIE && ((check(/msie 9/) && docMode != 7 && docMode != 8) || docMode == 9), + isIE6 = isIE && check(/msie 6/), + isGecko = !isWebKit && check(/gecko/), + isGecko3 = isGecko && check(/rv:1\.9/), + isGecko4 = isGecko && check(/rv:2\.0/), + isGecko5 = isGecko && check(/rv:5\./), + isGecko10 = isGecko && check(/rv:10\./), + isFF3_0 = isGecko3 && check(/rv:1\.9\.0/), + isFF3_5 = isGecko3 && check(/rv:1\.9\.1/), + isFF3_6 = isGecko3 && check(/rv:1\.9\.2/), + isWindows = check(/windows|win32/), + isMac = check(/macintosh|mac os x/), + isLinux = check(/linux/), + scrollbarSize = null, + chromeVersion = version(true, /\bchrome\/(\d+\.\d+)/), + firefoxVersion = version(true, /\bfirefox\/(\d+\.\d+)/), + ieVersion = version(isIE, /msie (\d+\.\d+)/), + operaVersion = version(isOpera, /version\/(\d+\.\d+)/), + safariVersion = version(isSafari, /version\/(\d+\.\d+)/), + webKitVersion = version(isWebKit, /webkit\/(\d+\.\d+)/), + isSecure = /^https/i.test(window.location.protocol), + nullLog; + + // remove css image flicker + try { + document.execCommand("BackgroundImageCache", false, true); + } catch(e) {} + + + var primitiveRe = /string|number|boolean/; + function dumpObject (object) { + var member, type, value, name, + members = []; + + // Cannot use Ext.encode since it can recurse endlessly (if we're lucky) + // ...and the data could be prettier! + for (name in object) { + if (object.hasOwnProperty(name)) { + value = object[name]; + + type = typeof value; + if (type == "function") { + continue; + } + + if (type == 'undefined') { + member = type; + } else if (value === null || primitiveRe.test(type) || Ext.isDate(value)) { + member = Ext.encode(value); + } else if (Ext.isArray(value)) { + member = '[ ]'; + } else if (Ext.isObject(value)) { + member = '{ }'; + } else { + member = type; + } + members.push(Ext.encode(name) + ': ' + member); + } + } + + if (members.length) { + return ' \nData: {\n ' + members.join(',\n ') + '\n}'; + } + return ''; + } + + function log (message) { + var options, dump, + con = Ext.global.console, + level = 'log', + indent = log.indent || 0, + stack, + out, + max; + + log.indent = indent; + + if (typeof message != 'string') { + options = message; + message = options.msg || ''; + level = options.level || level; + dump = options.dump; + stack = options.stack; + + if (options.indent) { + ++log.indent; + } else if (options.outdent) { + log.indent = indent = Math.max(indent - 1, 0); + } + + if (dump && !(con && con.dir)) { + message += dumpObject(dump); + dump = null; + } + } + + if (arguments.length > 1) { + message += Array.prototype.slice.call(arguments, 1).join(''); + } + + message = indent ? Ext.String.repeat(' ', log.indentSize * indent) + message : message; + // w/o console, all messages are equal, so munge the level into the message: + if (level != 'log') { + message = '[' + level.charAt(0).toUpperCase() + '] ' + message; + } + + // Not obvious, but 'console' comes and goes when Firebug is turned on/off, so + // an early test may fail either direction if Firebug is toggled. + // + if (con) { // if (Firebug-like console) + if (con[level]) { + con[level](message); + } else { + con.log(message); + } + + if (dump) { + con.dir(dump); + } + + if (stack && con.trace) { + // Firebug's console.error() includes a trace already... + if (!con.firebug || level != 'error') { + con.trace(); + } + } + } else { + if (Ext.isOpera) { + opera.postError(message); + } else { + out = log.out; + max = log.max; + + if (out.length >= max) { + // this formula allows out.max to change (via debugger), where the + // more obvious "max/4" would not quite be the same + Ext.Array.erase(out, 0, out.length - 3 * Math.floor(max / 4)); // keep newest 75% + } + + out.push(message); + } + } + + // Mostly informational, but the Ext.Error notifier uses them: + ++log.count; + ++log.counters[level]; + } + + function logx (level, args) { + if (typeof args[0] == 'string') { + args.unshift({}); + } + args[0].level = level; + log.apply(this, args); + } + + log.error = function () { + logx('error', Array.prototype.slice.call(arguments)); + }; + log.info = function () { + logx('info', Array.prototype.slice.call(arguments)); + }; + log.warn = function () { + logx('warn', Array.prototype.slice.call(arguments)); + }; + + log.count = 0; + log.counters = { error: 0, warn: 0, info: 0, log: 0 }; + log.indentSize = 2; + log.out = []; + log.max = 750; + log.show = function () { + window.open('','extlog').document.write([ + ''].join('')); + }; + + nullLog = function () {}; + nullLog.info = nullLog.warn = nullLog.error = Ext.emptyFn; + + Ext.setVersion('extjs', '4.1.0'); + Ext.apply(Ext, { + /** + * @property {String} SSL_SECURE_URL + * URL to a blank file used by Ext when in secure mode for iframe src and onReady src + * to prevent the IE insecure content warning (`'about:blank'`, except for IE + * in secure mode, which is `'javascript:""'`). + */ + SSL_SECURE_URL : isSecure && isIE ? 'javascript:\'\'' : 'about:blank', + + /** + * @property {Boolean} enableFx + * True if the {@link Ext.fx.Anim} Class is available. + */ + + /** + * @property {Boolean} scopeResetCSS + * True to scope the reset CSS to be just applied to Ext components. Note that this + * wraps root containers with an additional element. Also remember that when you turn + * on this option, you have to use ext-all-scoped (unless you use the bootstrap.js to + * load your javascript, in which case it will be handled for you). + */ + scopeResetCSS : Ext.buildSettings.scopeResetCSS, + + /** + * @property {String} resetCls + * The css class used to wrap Ext components when the {@link #scopeResetCSS} option + * is used. + */ + resetCls: Ext.buildSettings.baseCSSPrefix + 'reset', + + /** + * @property {Boolean} enableNestedListenerRemoval + * **Experimental.** True to cascade listener removal to child elements when an element + * is removed. Currently not optimized for performance. + */ + enableNestedListenerRemoval : false, + + /** + * @property {Boolean} USE_NATIVE_JSON + * Indicates whether to use native browser parsing for JSON methods. + * This option is ignored if the browser does not support native JSON methods. + * + * **Note:** Native JSON methods will not work with objects that have functions. + * Also, property names must be quoted, otherwise the data will not parse. + */ + USE_NATIVE_JSON : false, + + /** + * Returns the dom node for the passed String (id), dom node, or Ext.Element. + * Optional 'strict' flag is needed for IE since it can return 'name' and + * 'id' elements by using getElementById. + * + * Here are some examples: + * + * // gets dom node based on id + * var elDom = Ext.getDom('elId'); + * // gets dom node based on the dom node + * var elDom1 = Ext.getDom(elDom); + * + * // If we don't know if we are working with an + * // Ext.Element or a dom node use Ext.getDom + * function(el){ + * var dom = Ext.getDom(el); + * // do something with the dom node + * } + * + * **Note:** the dom node to be found actually needs to exist (be rendered, etc) + * when this method is called to be successful. + * + * @param {String/HTMLElement/Ext.Element} el + * @return HTMLElement + */ + getDom : function(el, strict) { + if (!el || !document) { + return null; + } + if (el.dom) { + return el.dom; + } else { + if (typeof el == 'string') { + var e = Ext.getElementById(el); + // IE returns elements with the 'name' and 'id' attribute. + // we do a strict check to return the element with only the id attribute + if (e && isIE && strict) { + if (el == e.getAttribute('id')) { + return e; + } else { + return null; + } + } + return e; + } else { + return el; + } + } + }, + + /** + * Removes a DOM node from the document. + * + * Removes this element from the document, removes all DOM event listeners, and + * deletes the cache reference. All DOM event listeners are removed from this element. + * If {@link Ext#enableNestedListenerRemoval Ext.enableNestedListenerRemoval} is + * `true`, then DOM event listeners are also removed from all child nodes. + * The body node will be ignored if passed in. + * + * @param {HTMLElement} node The node to remove + * @method + */ + removeNode : isIE6 || isIE7 || isIE8 + ? (function() { + var d; + return function(n){ + if(n && n.tagName.toUpperCase() != 'BODY'){ + (Ext.enableNestedListenerRemoval) ? Ext.EventManager.purgeElement(n) : Ext.EventManager.removeAll(n); + + var cache = Ext.cache, + id = n.id; + + if (cache[id]) { + delete cache[id].dom; + delete cache[id]; + } + + // removing an iframe this way can cause severe leaks + // fixes leak issue with htmleditor in themes example + if (n.tagName.toUpperCase() != 'IFRAME') { + if (isIE8 && n.parentNode) { + n.parentNode.removeChild(n); + } + d = d || document.createElement('div'); + d.appendChild(n); + d.innerHTML = ''; + } + } + }; + }()) + : function(n) { + if (n && n.parentNode && n.tagName.toUpperCase() != 'BODY') { + (Ext.enableNestedListenerRemoval) ? Ext.EventManager.purgeElement(n) : Ext.EventManager.removeAll(n); + + var cache = Ext.cache, + id = n.id; + + if (cache[id]) { + delete cache[id].dom; + delete cache[id]; + } + + n.parentNode.removeChild(n); + } + }, + + isStrict: isStrict, + + isIEQuirks: isIE && !isStrict, + + /** + * True if the detected browser is Opera. + * @type Boolean + */ + isOpera : isOpera, + + /** + * True if the detected browser is Opera 10.5x. + * @type Boolean + */ + isOpera10_5 : isOpera10_5, + + /** + * True if the detected browser uses WebKit. + * @type Boolean + */ + isWebKit : isWebKit, + + /** + * True if the detected browser is Chrome. + * @type Boolean + */ + isChrome : isChrome, + + /** + * True if the detected browser is Safari. + * @type Boolean + */ + isSafari : isSafari, + + /** + * True if the detected browser is Safari 3.x. + * @type Boolean + */ + isSafari3 : isSafari3, + + /** + * True if the detected browser is Safari 4.x. + * @type Boolean + */ + isSafari4 : isSafari4, + + /** + * True if the detected browser is Safari 5.x. + * @type Boolean + */ + isSafari5 : isSafari5, + + /** + * True if the detected browser is Safari 5.0.x. + * @type Boolean + */ + isSafari5_0 : isSafari5_0, + + + /** + * True if the detected browser is Safari 2.x. + * @type Boolean + */ + isSafari2 : isSafari2, + + /** + * True if the detected browser is Internet Explorer. + * @type Boolean + */ + isIE : isIE, + + /** + * True if the detected browser is Internet Explorer 6.x. + * @type Boolean + */ + isIE6 : isIE6, + + /** + * True if the detected browser is Internet Explorer 7.x. + * @type Boolean + */ + isIE7 : isIE7, + + /** + * True if the detected browser is Internet Explorer 8.x. + * @type Boolean + */ + isIE8 : isIE8, + + /** + * True if the detected browser is Internet Explorer 9.x. + * @type Boolean + */ + isIE9 : isIE9, + + /** + * True if the detected browser uses the Gecko layout engine (e.g. Mozilla, Firefox). + * @type Boolean + */ + isGecko : isGecko, + + /** + * True if the detected browser uses a Gecko 1.9+ layout engine (e.g. Firefox 3.x). + * @type Boolean + */ + isGecko3 : isGecko3, + + /** + * True if the detected browser uses a Gecko 2.0+ layout engine (e.g. Firefox 4.x). + * @type Boolean + */ + isGecko4 : isGecko4, + + /** + * True if the detected browser uses a Gecko 5.0+ layout engine (e.g. Firefox 5.x). + * @type Boolean + */ + isGecko5 : isGecko5, + + /** + * True if the detected browser uses a Gecko 5.0+ layout engine (e.g. Firefox 5.x). + * @type Boolean + */ + isGecko10 : isGecko10, + + /** + * True if the detected browser uses FireFox 3.0 + * @type Boolean + */ + isFF3_0 : isFF3_0, + + /** + * True if the detected browser uses FireFox 3.5 + * @type Boolean + */ + isFF3_5 : isFF3_5, + + /** + * True if the detected browser uses FireFox 3.6 + * @type Boolean + */ + isFF3_6 : isFF3_6, + + /** + * True if the detected browser uses FireFox 4 + * @type Boolean + */ + isFF4 : 4 <= firefoxVersion && firefoxVersion < 5, + + /** + * True if the detected browser uses FireFox 5 + * @type Boolean + */ + isFF5 : 5 <= firefoxVersion && firefoxVersion < 6, + + /** + * True if the detected browser uses FireFox 10 + * @type Boolean + */ + isFF10 : 10 <= firefoxVersion && firefoxVersion < 11, + + /** + * True if the detected platform is Linux. + * @type Boolean + */ + isLinux : isLinux, + + /** + * True if the detected platform is Windows. + * @type Boolean + */ + isWindows : isWindows, + + /** + * True if the detected platform is Mac OS. + * @type Boolean + */ + isMac : isMac, + + /** + * The current version of Chrome (0 if the browser is not Chrome). + * @type Number + */ + chromeVersion: chromeVersion, + + /** + * The current version of Firefox (0 if the browser is not Firefox). + * @type Number + */ + firefoxVersion: firefoxVersion, + + /** + * The current version of IE (0 if the browser is not IE). This does not account + * for the documentMode of the current page, which is factored into {@link #isIE7}, + * {@link #isIE8} and {@link #isIE9}. Thus this is not always true: + * + * Ext.isIE8 == (Ext.ieVersion == 8) + * + * @type Number + */ + ieVersion: ieVersion, + + /** + * The current version of Opera (0 if the browser is not Opera). + * @type Number + */ + operaVersion: operaVersion, + + /** + * The current version of Safari (0 if the browser is not Safari). + * @type Number + */ + safariVersion: safariVersion, + + /** + * The current version of WebKit (0 if the browser does not use WebKit). + * @type Number + */ + webKitVersion: webKitVersion, + + /** + * True if the page is running over SSL + * @type Boolean + */ + isSecure: isSecure, + + /** + * URL to a 1x1 transparent gif image used by Ext to create inline icons with + * CSS background images. In older versions of IE, this defaults to + * "http://sencha.com/s.gif" and you should change this to a URL on your server. + * For other browsers it uses an inline data URL. + * @type String + */ + BLANK_IMAGE_URL : (isIE6 || isIE7) ? '/' + '/www.sencha.com/s.gif' : 'data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==', + + /** + * Utility method for returning a default value if the passed value is empty. + * + * The value is deemed to be empty if it is: + * + * - null + * - undefined + * - an empty array + * - a zero length string (Unless the `allowBlank` parameter is `true`) + * + * @param {Object} value The value to test + * @param {Object} defaultValue The value to return if the original value is empty + * @param {Boolean} [allowBlank=false] true to allow zero length strings to qualify as non-empty. + * @return {Object} value, if non-empty, else defaultValue + * @deprecated 4.0.0 Use {@link Ext#valueFrom} instead + */ + value : function(v, defaultValue, allowBlank){ + return Ext.isEmpty(v, allowBlank) ? defaultValue : v; + }, + + /** + * Escapes the passed string for use in a regular expression. + * @param {String} str + * @return {String} + * @deprecated 4.0.0 Use {@link Ext.String#escapeRegex} instead + */ + escapeRe : function(s) { + return s.replace(/([-.*+?\^${}()|\[\]\/\\])/g, "\\$1"); + }, + + /** + * Applies event listeners to elements by selectors when the document is ready. + * The event name is specified with an `@` suffix. + * + * Ext.addBehaviors({ + * // add a listener for click on all anchors in element with id foo + * '#foo a@click' : function(e, t){ + * // do something + * }, + * + * // add the same listener to multiple selectors (separated by comma BEFORE the @) + * '#foo a, #bar span.some-class@mouseover' : function(){ + * // do something + * } + * }); + * + * @param {Object} obj The list of behaviors to apply + */ + addBehaviors : function(o){ + if(!Ext.isReady){ + Ext.onReady(function(){ + Ext.addBehaviors(o); + }); + } else { + var cache = {}, // simple cache for applying multiple behaviors to same selector does query multiple times + parts, + b, + s; + for (b in o) { + if ((parts = b.split('@'))[1]) { // for Object prototype breakers + s = parts[0]; + if(!cache[s]){ + cache[s] = Ext.select(s); + } + cache[s].on(parts[1], o[b]); + } + } + cache = null; + } + }, + + /** + * Returns the size of the browser scrollbars. This can differ depending on + * operating system settings, such as the theme or font size. + * @param {Boolean} [force] true to force a recalculation of the value. + * @return {Object} An object containing scrollbar sizes. + * @return.width {Number} The width of the vertical scrollbar. + * @return.height {Number} The height of the horizontal scrollbar. + */ + getScrollbarSize: function (force) { + if (!Ext.isReady) { + return {}; + } + + if (force || !scrollbarSize) { + var db = document.body, + div = document.createElement('div'); + + div.style.width = div.style.height = '100px'; + div.style.overflow = 'scroll'; + div.style.position = 'absolute'; + + db.appendChild(div); // now we can measure the div... + + // at least in iE9 the div is not 100px - the scrollbar size is removed! + scrollbarSize = { + width: div.offsetWidth - div.clientWidth, + height: div.offsetHeight - div.clientHeight + }; + + db.removeChild(div); + } + + return scrollbarSize; + }, + + /** + * Utility method for getting the width of the browser's vertical scrollbar. This + * can differ depending on operating system settings, such as the theme or font size. + * + * This method is deprected in favor of {@link #getScrollbarSize}. + * + * @param {Boolean} [force] true to force a recalculation of the value. + * @return {Number} The width of a vertical scrollbar. + * @deprecated + */ + getScrollBarWidth: function(force){ + var size = Ext.getScrollbarSize(force); + return size.width + 2; // legacy fudge factor + }, + + /** + * Copies a set of named properties fom the source object to the destination object. + * + * Example: + * + * ImageComponent = Ext.extend(Ext.Component, { + * initComponent: function() { + * this.autoEl = { tag: 'img' }; + * MyComponent.superclass.initComponent.apply(this, arguments); + * this.initialBox = Ext.copyTo({}, this.initialConfig, 'x,y,width,height'); + * } + * }); + * + * Important note: To borrow class prototype methods, use {@link Ext.Base#borrow} instead. + * + * @param {Object} dest The destination object. + * @param {Object} source The source object. + * @param {String/String[]} names Either an Array of property names, or a comma-delimited list + * of property names to copy. + * @param {Boolean} [usePrototypeKeys] Defaults to false. Pass true to copy keys off of the + * prototype as well as the instance. + * @return {Object} The modified object. + */ + copyTo : function(dest, source, names, usePrototypeKeys){ + if(typeof names == 'string'){ + names = names.split(/[,;\s]/); + } + + var n, + nLen = names.length, + name; + + for(n = 0; n < nLen; n++) { + name = names[n]; + + if(usePrototypeKeys || source.hasOwnProperty(name)){ + dest[name] = source[name]; + } + } + + return dest; + }, + + /** + * Attempts to destroy and then remove a set of named properties of the passed object. + * @param {Object} o The object (most likely a Component) who's properties you wish to destroy. + * @param {String...} args One or more names of the properties to destroy and remove from the object. + */ + destroyMembers : function(o){ + for (var i = 1, a = arguments, len = a.length; i < len; i++) { + Ext.destroy(o[a[i]]); + delete o[a[i]]; + } + }, + + /** + * Logs a message. If a console is present it will be used. On Opera, the method + * "opera.postError" is called. In other cases, the message is logged to an array + * "Ext.log.out". An attached debugger can watch this array and view the log. The + * log buffer is limited to a maximum of "Ext.log.max" entries (defaults to 250). + * The `Ext.log.out` array can also be written to a popup window by entering the + * following in the URL bar (a "bookmarklet"): + * + * javascript:void(Ext.log.show()); + * + * If additional parameters are passed, they are joined and appended to the message. + * A technique for tracing entry and exit of a function is this: + * + * function foo () { + * Ext.log({ indent: 1 }, '>> foo'); + * + * // log statements in here or methods called from here will be indented + * // by one step + * + * Ext.log({ outdent: 1 }, '<< foo'); + * } + * + * This method does nothing in a release build. + * + * @param {String/Object} message The message to log or an options object with any + * of the following properties: + * + * - `msg`: The message to log (required). + * - `level`: One of: "error", "warn", "info" or "log" (the default is "log"). + * - `dump`: An object to dump to the log as part of the message. + * - `stack`: True to include a stack trace in the log. + * - `indent`: Cause subsequent log statements to be indented one step. + * - `outdent`: Cause this and following statements to be one step less indented. + * + * @method + */ + log : + log || + nullLog, + + /** + * Partitions the set into two sets: a true set and a false set. + * + * Example 1: + * + * Ext.partition([true, false, true, true, false]); + * // returns [[true, true, true], [false, false]] + * + * Example 2: + * + * Ext.partition( + * Ext.query("p"), + * function(val){ + * return val.className == "class1" + * } + * ); + * // true are those paragraph elements with a className of "class1", + * // false set are those that do not have that className. + * + * @param {Array/NodeList} arr The array to partition + * @param {Function} truth (optional) a function to determine truth. + * If this is omitted the element itself must be able to be evaluated for its truthfulness. + * @return {Array} [array of truish values, array of falsy values] + * @deprecated 4.0.0 Will be removed in the next major version + */ + partition : function(arr, truth){ + var ret = [[],[]], + a, v, + aLen = arr.length; + + for (a = 0; a < aLen; a++) { + v = arr[a]; + ret[ (truth && truth(v, a, arr)) || (!truth && v) ? 0 : 1].push(v); + } + + return ret; + }, + + /** + * Invokes a method on each item in an Array. + * + * Example: + * + * Ext.invoke(Ext.query("p"), "getAttribute", "id"); + * // [el1.getAttribute("id"), el2.getAttribute("id"), ..., elN.getAttribute("id")] + * + * @param {Array/NodeList} arr The Array of items to invoke the method on. + * @param {String} methodName The method name to invoke. + * @param {Object...} args Arguments to send into the method invocation. + * @return {Array} The results of invoking the method on each item in the array. + * @deprecated 4.0.0 Will be removed in the next major version + */ + invoke : function(arr, methodName){ + var ret = [], + args = Array.prototype.slice.call(arguments, 2), + a, v, + aLen = arr.length; + + for (a = 0; a < aLen; a++) { + v = arr[a]; + + if (v && typeof v[methodName] == 'function') { + ret.push(v[methodName].apply(v, args)); + } else { + ret.push(undefined); + } + } + + return ret; + }, + + /** + * Zips N sets together. + * + * Example 1: + * + * Ext.zip([1,2,3],[4,5,6]); // [[1,4],[2,5],[3,6]] + * + * Example 2: + * + * Ext.zip( + * [ "+", "-", "+"], + * [ 12, 10, 22], + * [ 43, 15, 96], + * function(a, b, c){ + * return "$" + a + "" + b + "." + c + * } + * ); // ["$+12.43", "$-10.15", "$+22.96"] + * + * @param {Array/NodeList...} arr This argument may be repeated. Array(s) + * to contribute values. + * @param {Function} zipper (optional) The last item in the argument list. + * This will drive how the items are zipped together. + * @return {Array} The zipped set. + * @deprecated 4.0.0 Will be removed in the next major version + */ + 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 = [], + i, + j, + aLen; + + for (i = 0; i < len; i++) { + ret[i] = []; + if(fn){ + ret[i] = fn.apply(fn, Ext.pluck(arrs, i)); + }else{ + for (j = 0, aLen = arrs.length; j < aLen; j++){ + ret[i].push( arrs[j][i] ); + } + } + } + return ret; + }, + + /** + * Turns an array into a sentence, joined by a specified connector - e.g.: + * + * Ext.toSentence(['Adama', 'Tigh', 'Roslin']); //'Adama, Tigh and Roslin' + * Ext.toSentence(['Adama', 'Tigh', 'Roslin'], 'or'); //'Adama, Tigh or Roslin' + * + * @param {String[]} items The array to create a sentence from + * @param {String} connector The string to use to connect the last two words. + * Usually 'and' or 'or' - defaults to 'and'. + * @return {String} The sentence string + * @deprecated 4.0.0 Will be removed in the next major version + */ + toSentence: function(items, connector) { + var length = items.length, + head, + tail; + + if (length <= 1) { + return items[0]; + } else { + head = items.slice(0, length - 1); + tail = items[length - 1]; + + return Ext.util.Format.format("{0} {1} {2}", head.join(", "), connector || 'and', tail); + } + }, + + /** + * @property {Boolean} useShims + * By default, Ext intelligently decides whether floating elements should be shimmed. + * If you are using flash, you may want to set this to true. + */ + useShims: isIE6 + }); +}()); + +/** + * Loads Ext.app.Application class and starts it up with given configuration after the page is ready. + * + * See Ext.app.Application for details. + * + * @param {Object} config + */ +Ext.application = function(config) { + Ext.require('Ext.app.Application'); + + Ext.onReady(function() { + new Ext.app.Application(config); + }); +}; + +/** + * @class Ext.util.Format + +This class is a centralized place for formatting functions. It includes +functions to format various different types of data, such as text, dates and numeric values. + +__Localization__ +This class contains several options for localization. These can be set once the library has loaded, +all calls to the functions from that point will use the locale settings that were specified. +Options include: +- thousandSeparator +- decimalSeparator +- currenyPrecision +- currencySign +- currencyAtEnd +This class also uses the default date format defined here: {@link Ext.Date#defaultFormat}. + +__Using with renderers__ +There are two helper functions that return a new function that can be used in conjunction with +grid renderers: + + columns: [{ + dataIndex: 'date', + renderer: Ext.util.Format.dateRenderer('Y-m-d') + }, { + dataIndex: 'time', + renderer: Ext.util.Format.numberRenderer('0.000') + }] + +Functions that only take a single argument can also be passed directly: + columns: [{ + dataIndex: 'cost', + renderer: Ext.util.Format.usMoney + }, { + dataIndex: 'productCode', + renderer: Ext.util.Format.uppercase + }] + +__Using with XTemplates__ +XTemplates can also directly use Ext.util.Format functions: + + new Ext.XTemplate([ + 'Date: {startDate:date("Y-m-d")}', + 'Cost: {cost:usMoney}' + ]); + + * @markdown + * @singleton + */ +(function() { + Ext.ns('Ext.util'); + + Ext.util.Format = {}; + var UtilFormat = Ext.util.Format, + stripTagsRE = /<\/?[^>]+>/gi, + stripScriptsRe = /(?:)((\n|\r|.)*?)(?:<\/script>)/ig, + nl2brRe = /\r?\n/g, + + // A RegExp to remove from a number format string, all characters except digits and '.' + formatCleanRe = /[^\d\.]/g, + + // A RegExp to remove from a number format string, all characters except digits and the local decimal separator. + // Created on first use. The local decimal separator character must be initialized for this to be created. + I18NFormatCleanRe; + + Ext.apply(UtilFormat, { + /** + * @property {String} thousandSeparator + *

    The character that the {@link #number} function uses as a thousand separator.

    + *

    This may be overridden in a locale file.

    + */ + // + thousandSeparator: ',', + // + + /** + * @property {String} decimalSeparator + *

    The character that the {@link #number} function uses as a decimal point.

    + *

    This may be overridden in a locale file.

    + */ + // + decimalSeparator: '.', + // + + /** + * @property {Number} currencyPrecision + *

    The number of decimal places that the {@link #currency} function displays.

    + *

    This may be overridden in a locale file.

    + */ + // + currencyPrecision: 2, + // + + /** + * @property {String} currencySign + *

    The currency sign that the {@link #currency} function displays.

    + *

    This may be overridden in a locale file.

    + */ + // + currencySign: '$', + // + + /** + * @property {Boolean} currencyAtEnd + *

    This may be set to true to make the {@link #currency} function + * append the currency sign to the formatted value.

    + *

    This may be overridden in a locale file.

    + */ + // + currencyAtEnd: false, + // + + /** + * Checks a reference and converts it to empty string if it is undefined + * @param {Object} value Reference to check + * @return {Object} 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 {Object} 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; + }, + + /** + * 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 : 'ab'.substr(-1) != 'b' + ? function (value, start, length) { + var str = String(value); + return (start < 0) + ? str.substr(Math.max(str.length + start, 0), length) + : str.substr(start, length); + } + : 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(); + }, + + /** + * Format a number as US currency + * @param {Number/String} value The numeric value to format + * @return {String} The formatted currency string + */ + usMoney : function(v) { + return UtilFormat.currency(v, '$', 2); + }, + + /** + * Format a number as a currency + * @param {Number/String} value The numeric value to format + * @param {String} sign The currency sign to use (defaults to {@link #currencySign}) + * @param {Number} decimals The number of decimals to use for the currency (defaults to {@link #currencyPrecision}) + * @param {Boolean} end True if the currency sign should be at the end of the string (defaults to {@link #currencyAtEnd}) + * @return {String} The formatted currency string + */ + currency: function(v, currencySign, decimals, end) { + var negativeSign = '', + format = ",0", + i = 0; + v = v - 0; + if (v < 0) { + v = -v; + negativeSign = '-'; + } + decimals = Ext.isDefined(decimals) ? decimals : UtilFormat.currencyPrecision; + format += format + (decimals > 0 ? '.' : ''); + for (; i < decimals; i++) { + format += '0'; + } + v = UtilFormat.number(v, format); + if ((end || UtilFormat.currencyAtEnd) === true) { + return Ext.String.format("{0}{1}{2}", negativeSign, v, currencySign || UtilFormat.currencySign); + } else { + return Ext.String.format("{0}{1}{2}", negativeSign, currencySign || UtilFormat.currencySign, v); + } + }, + + /** + * Formats the passed date using the specified format pattern. + * @param {String/Date} value The value to format. If a string is passed, it is converted to a Date by the Javascript + * Date object's parse() method. + * @param {String} format (Optional) Any valid date format string. Defaults to {@link Ext.Date#defaultFormat}. + * @return {String} The formatted date string. + */ + date: function(v, format) { + if (!v) { + return ""; + } + if (!Ext.isDate(v)) { + v = new Date(Date.parse(v)); + } + return Ext.Date.dateFormat(v, format || Ext.Date.defaultFormat); + }, + + /** + * 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. Defaults to {@link Ext.Date#defaultFormat}. + * @return {Function} The date formatting function + */ + dateRenderer : function(format) { + return function(v) { + return UtilFormat.date(v, format); + }; + }, + + /** + * Strips all HTML tags + * @param {Object} value The text from which to strip tags + * @return {String} The stripped text + */ + stripTags : function(v) { + return !v ? v : String(v).replace(stripTagsRE, ""); + }, + + /** + * Strips all script tags + * @param {Object} value The text from which to strip script tags + * @return {String} The stripped text + */ + stripScripts : function(v) { + return !v ? v : String(v).replace(stripScriptsRe, ""); + }, + + /** + * Simple format for a file size (xxx bytes, xxx KB, xxx MB) + * @param {Number/String} size The numeric value to format + * @return {String} The formatted file size + */ + fileSize : function(size) { + if (size < 1024) { + return size + " bytes"; + } else if (size < 1048576) { + return (Math.round(((size*10) / 1024))/10) + " KB"; + } else { + return (Math.round(((size*10) / 1048576))/10) + " MB"; + } + }, + + /** + * It does simple math for use in a template, for example:
    
    +         * var tpl = new Ext.Template('{value} * 10 = {value:math("* 10")}');
    +         * 
    + * @return {Function} A function that operates on the passed value. + * @method + */ + math : (function(){ + var fns = {}; + + return function(v, a){ + if (!fns[a]) { + fns[a] = Ext.functionFactory('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 passed number according to the passed format string.

    + *

    The number of digits after the decimal separator character specifies the number of + * decimal places in the resulting string. The local-specific decimal character is used in the result.

    + *

    The presence of a thousand separator character in the format string specifies that + * the locale-specific thousand separator (if any) is inserted separating thousand groups.

    + *

    By default, "," is expected as the thousand separator, and "." is expected as the decimal separator.

    + *

    New to Ext JS 4

    + *

    Locale-specific characters are always used in the formatted output when inserting + * thousand and decimal separators.

    + *

    The format string must specify separator characters according to US/UK conventions ("," as the + * thousand separator, and "." as the decimal separator)

    + *

    To allow specification of format strings according to local conventions for separator characters, add + * the string /i to the end of 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 allow specification of the formatting string using UK/US grouping characters (,) 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, formatString) { + if (!formatString) { + return v; + } + v = Ext.Number.from(v, NaN); + if (isNaN(v)) { + return ''; + } + var comma = UtilFormat.thousandSeparator, + dec = UtilFormat.decimalSeparator, + i18n = false, + neg = v < 0, + hasComma, + psplit, + fnum, + cnum, + parr, + j, + m, + n, + i; + + v = Math.abs(v); + + // The "/i" suffix allows caller to use a locale-specific formatting string. + // Clean the format string by removing all but numerals and the decimal separator. + // Then split the format string into pre and post decimal segments according to *what* the + // decimal separator is. If they are specifying "/i", they are using the local convention in the format string. + if (formatString.substr(formatString.length - 2) == '/i') { + if (!I18NFormatCleanRe) { + I18NFormatCleanRe = new RegExp('[^\\d\\' + UtilFormat.decimalSeparator + ']','g'); + } + formatString = formatString.substr(0, formatString.length - 2); + i18n = true; + hasComma = formatString.indexOf(comma) != -1; + psplit = formatString.replace(I18NFormatCleanRe, '').split(dec); + } else { + hasComma = formatString.indexOf(',') != -1; + psplit = formatString.replace(formatCleanRe, '').split('.'); + } + + if (psplit.length > 2) { + Ext.Error.raise({ + sourceClass: "Ext.util.Format", + sourceMethod: "number", + value: v, + formatString: formatString, + msg: "Invalid number format, should have no more than 1 decimal" + }); + } else if (psplit.length > 1) { + v = Ext.Number.toFixed(v, psplit[1].length); + } else { + v = Ext.Number.toFixed(v, 0); + } + + fnum = v.toString(); + + psplit = fnum.split('.'); + + if (hasComma) { + cnum = psplit[0]; + parr = []; + j = cnum.length; + m = Math.floor(j / 3); + n = cnum.length % 3 || 3; + + 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]; + } + } + + if (neg) { + /* + * Edge case. If we have a very small negative number it will get rounded to 0, + * however the initial check at the top will still report as negative. Replace + * everything but 1-9 and check if the string is empty to determine a 0 value. + */ + neg = fnum.replace(/[^1-9]/g, '') !== ''; + } + + return (neg ? '-' : '') + formatString.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 UtilFormat.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 Ext.isEmpty(v) ? '' : v.replace(nl2brRe, '
    '); + }, + + /** + * Alias for {@link Ext.String#capitalize}. + * @method + * @inheritdoc Ext.String#capitalize + */ + capitalize: Ext.String.capitalize, + + /** + * Alias for {@link Ext.String#ellipsis}. + * @method + * @inheritdoc Ext.String#ellipsis + */ + ellipsis: Ext.String.ellipsis, + + /** + * Alias for {@link Ext.String#format}. + * @method + * @inheritdoc Ext.String#format + */ + format: Ext.String.format, + + /** + * Alias for {@link Ext.String#htmlDecode}. + * @method + * @inheritdoc Ext.String#htmlDecode + */ + htmlDecode: Ext.String.htmlDecode, + + /** + * Alias for {@link Ext.String#htmlEncode}. + * @method + * @inheritdoc Ext.String#htmlEncode + */ + htmlEncode: Ext.String.htmlEncode, + + /** + * Alias for {@link Ext.String#leftPad}. + * @method + * @inheritdoc Ext.String#leftPad + */ + leftPad: Ext.String.leftPad, + + /** + * Alias for {@link Ext.String#trim}. + * @method + * @inheritdoc Ext.String#trim + */ + trim : Ext.String.trim, + + /** + * Parses a number or string representing margin sizes into an object. Supports CSS-style margin declarations + * (e.g. 10, "10", "10 10", "10 10 10" and "10 10 10 10" are all valid options and would return the same result) + * @param {Number/String} v The encoded margins + * @return {Object} An object with margin sizes for top, right, bottom and left + */ + parseBox : function(box) { + box = Ext.isEmpty(box) ? '' : box; + if (Ext.isNumber(box)) { + box = box.toString(); + } + var parts = box.split(' '), + ln = parts.length; + + if (ln == 1) { + parts[1] = parts[2] = parts[3] = parts[0]; + } + else if (ln == 2) { + parts[2] = parts[0]; + parts[3] = parts[1]; + } + else if (ln == 3) { + parts[3] = parts[1]; + } + + return { + top :parseInt(parts[0], 10) || 0, + right :parseInt(parts[1], 10) || 0, + bottom:parseInt(parts[2], 10) || 0, + left :parseInt(parts[3], 10) || 0 + }; + }, + + /** + * Escapes the passed string for use in a regular expression + * @param {String} str + * @return {String} + */ + escapeRegex : function(s) { + return s.replace(/([\-.*+?\^${}()|\[\]\/\\])/g, "\\$1"); + } + }); +}()); + +/** + * Provides the ability to execute one or more arbitrary tasks in a asynchronous manner. + * Generally, you can use the singleton {@link Ext.TaskManager} instead, but if needed, + * you can create separate instances of TaskRunner. Any number of separate tasks can be + * started at any time and will run independently of each other. + * + * Example usage: + * + * // Start a simple clock task that updates a div once per second + * var updateClock = function () { + * Ext.fly('clock').update(new Date().format('g:i:s A')); + * } + * + * var runner = new Ext.util.TaskRunner(); + * var task = runner.start({ + * run: updateClock, + * interval: 1000 + * } + * + * The equivalent using TaskManager: + * + * var task = Ext.TaskManager.start({ + * run: updateClock, + * interval: 1000 + * }); + * + * To end a running task: + * + * task.destroy(); + * + * If a task needs to be started and stopped repeated over time, you can create a + * {@link Ext.util.TaskRunner.Task Task} instance. + * + * var task = runner.newTask({ + * run: function () { + * // useful code + * }, + * interval: 1000 + * }); + * + * task.start(); + * + * // ... + * + * task.stop(); + * + * // ... + * + * task.start(); + * + * A re-usable, one-shot task can be managed similar to the above: + * + * var task = runner.newTask({ + * run: function () { + * // useful code to run once + * }, + * repeat: 1 + * }); + * + * task.start(); + * + * // ... + * + * task.start(); + * + * See the {@link #start} method for details about how to configure a task object. + * + * Also see {@link Ext.util.DelayedTask}. + * + * @constructor + * @param {Number/Object} [interval=10] The minimum precision in milliseconds supported by this + * TaskRunner instance. Alternatively, a config object to apply to the new instance. + */ +Ext.define('Ext.util.TaskRunner', { + /** + * @cfg interval + * The timer resolution. + */ + interval: 10, + + /** + * @property timerId + * The id of the current timer. + * @private + */ + timerId: null, + + constructor: function (interval) { + var me = this; + + if (typeof interval == 'number') { + me.interval = interval; + } else if (interval) { + Ext.apply(me, interval); + } + + me.tasks = []; + me.timerFn = Ext.Function.bind(me.onTick, me); + }, + + /** + * Creates a new {@link Ext.util.TaskRunner.Task Task} instance. These instances can + * be easily started and stopped. + * @param {Object} config The config object. For details on the supported properties, + * see {@link #start}. + */ + newTask: function (config) { + var task = new Ext.util.TaskRunner.Task(config); + task.manager = this; + return task; + }, + + /** + * Starts a new task. + * + * Before each invocation, Ext injects the property `taskRunCount` into the task object + * so that calculations based on the repeat count can be performed. + * + * The returned task will contain a `destroy` method that can be used to destroy the + * task and cancel further calls. This is equivalent to the {@link #stop} method. + * + * @param {Object} task A config object that supports the following properties: + * @param {Function} task.run The function to execute each time the task is invoked. The + * function will be called at each interval and passed the `args` argument if specified, + * and the current invocation count if not. + * + * If a particular scope (`this` reference) is required, be sure to specify it using + * the `scope` argument. + * + * @param {Function} task.onError The function to execute in case of unhandled + * error on task.run. + * + * @param {Boolean} task.run.return `false` from this function to terminate the task. + * + * @param {Number} task.interval The frequency in milliseconds with which the task + * should be invoked. + * + * @param {Object[]} task.args An array of arguments to be passed to the function + * specified by `run`. If not specified, the current invocation count is passed. + * + * @param {Object} task.scope The scope (`this` reference) in which to execute the + * `run` function. Defaults to the task config object. + * + * @param {Number} task.duration The length of time in milliseconds to invoke the task + * before stopping automatically (defaults to indefinite). + * + * @param {Number} task.repeat The number of times to invoke the task before stopping + * automatically (defaults to indefinite). + * @return {Object} The task + */ + start: function(task) { + var me = this, + now = new Date().getTime(); + + if (!task.pending) { + me.tasks.push(task); + task.pending = true; // don't allow the task to be added to me.tasks again + } + + task.stopped = false; // might have been previously stopped... + task.taskStartTime = now; + task.taskRunTime = task.fireOnStart !== false ? 0 : task.taskStartTime; + task.taskRunCount = 0; + + if (!me.firing) { + if (task.fireOnStart !== false) { + me.startTimer(0, now); + } else { + me.startTimer(task.interval, now); + } + } + + return task; + }, + + /** + * Stops an existing running task. + * @param {Object} task The task to stop + * @return {Object} The task + */ + stop: function(task) { + // NOTE: we don't attempt to remove the task from me.tasks at this point because + // this could be called from inside a task which would then corrupt the state of + // the loop in onTick + if (!task.stopped) { + task.stopped = true; + + if (task.onStop) { + task.onStop.call(task.scope || task, task); + } + } + + return task; + }, + + /** + * Stops all tasks that are currently running. + */ + stopAll: function() { + // onTick will take care of cleaning up the mess after this point... + Ext.each(this.tasks, this.stop, this); + }, + + //------------------------------------------------------------------------- + + firing: false, + + nextExpires: 1e99, + + // private + onTick: function () { + var me = this, + tasks = me.tasks, + now = new Date().getTime(), + nextExpires = 1e99, + len = tasks.length, + expires, newTasks, i, task, rt, remove; + + me.timerId = null; + me.firing = true; // ensure we don't startTimer during this loop... + + // tasks.length can be > len if start is called during a task.run call... so we + // first check len to avoid tasks.length reference but eventually we need to also + // check tasks.length. we avoid repeating use of tasks.length by setting len at + // that time (to help the next loop) + for (i = 0; i < len || i < (len = tasks.length); ++i) { + task = tasks[i]; + + if (!(remove = task.stopped)) { + expires = task.taskRunTime + task.interval; + + if (expires <= now) { + rt = 1; // otherwise we have a stale "rt" + try { + rt = task.run.apply(task.scope || task, task.args || [++task.taskRunCount]); + } catch (taskError) { + try { + if (task.onError) { + rt = task.onError.call(task.scope || task, task, taskError); + } + } catch (ignore) { } + } + task.taskRunTime = now; + if (rt === false || task.taskRunCount === task.repeat) { + me.stop(task); + remove = true; + } else { + remove = task.stopped; // in case stop was called by run + expires = now + task.interval; + } + } + + if (!remove && task.duration && task.duration <= (now - task.taskStartTime)) { + me.stop(task); + remove = true; + } + } + + if (remove) { + task.pending = false; // allow the task to be added to me.tasks again + + // once we detect that a task needs to be removed, we copy the tasks that + // will carry forward into newTasks... this way we avoid O(N*N) to remove + // each task from the tasks array (and ripple the array down) and also the + // potentially wasted effort of making a new tasks[] even if all tasks are + // going into the next wave. + if (!newTasks) { + newTasks = tasks.slice(0, i); + // we don't set me.tasks here because callbacks can also start tasks, + // which get added to me.tasks... so we will visit them in this loop + // and account for their expirations in nextExpires... + } + } else { + if (newTasks) { + newTasks.push(task); // we've cloned the tasks[], so keep this one... + } + + if (nextExpires > expires) { + nextExpires = expires; // track the nearest expiration time + } + } + } + + if (newTasks) { + // only now can we copy the newTasks to me.tasks since no user callbacks can + // take place + me.tasks = newTasks; + } + + me.firing = false; // we're done, so allow startTimer afterwards + + if (me.tasks.length) { + // we create a new Date here because all the callbacks could have taken a long + // time... we want to base the next timeout on the current time (after the + // callback storm): + me.startTimer(nextExpires - now, new Date().getTime()); + } + }, + + // private + startTimer: function (timeout, now) { + var me = this, + expires = now + timeout, + timerId = me.timerId; + + // Check to see if this request is enough in advance of the current timer. If so, + // we reschedule the timer based on this new expiration. + if (timerId && me.nextExpires - expires > me.interval) { + clearTimeout(timerId); + timerId = null; + } + + if (!timerId) { + if (timeout < me.interval) { + timeout = me.interval; + } + + me.timerId = setTimeout(me.timerFn, timeout); + me.nextExpires = expires; + } + } +}, +function () { + var me = this, + proto = me.prototype; + + /** + * Destroys this instance, stopping all tasks that are currently running. + * @method destroy + */ + proto.destroy = proto.stopAll; + + /** + * @class Ext.TaskManager + * @extends Ext.util.TaskRunner + * @singleton + * + * A static {@link Ext.util.TaskRunner} instance that can be used to start and stop + * arbitrary tasks. See {@link Ext.util.TaskRunner} for supported methods and task + * config properties. + * + * // Start a simple clock task that updates a div once per second + * var task = { + * run: function(){ + * Ext.fly('clock').update(new Date().format('g:i:s A')); + * }, + * interval: 1000 //1 second + * } + * + * Ext.TaskManager.start(task); + * + * See the {@link #start} method for details about how to configure a task object. + */ + Ext.util.TaskManager = Ext.TaskManager = new me(); + + /** + * Instances of this class are created by {@link Ext.util.TaskRunner#newTask} method. + * + * For details on config properties, see {@link Ext.util.TaskRunner#start}. + * @class Ext.util.TaskRunner.Task + */ + me.Task = new Ext.Class({ + isTask: true, + + /** + * This flag is set to `true` by {@link #stop}. + * @private + */ + stopped: true, // this avoids the odd combination of !stopped && !pending + + /** + * Override default behavior + */ + fireOnStart: false, + + constructor: function (config) { + Ext.apply(this, config); + }, + + /** + * Restarts this task, clearing it duration, expiration and run count. + * @param {Number} [interval] Optionally reset this task's interval. + */ + restart: function (interval) { + if (interval !== undefined) { + this.interval = interval; + } + + this.manager.start(this); + }, + + /** + * Starts this task if it is not already started. + * @param {Number} [interval] Optionally reset this task's interval. + */ + start: function (interval) { + if (this.stopped) { + this.restart(interval); + } + }, + + /** + * Stops this task. + */ + stop: function () { + this.manager.stop(this); + } + }); + + proto = me.Task.prototype; + + /** + * Destroys this instance, stopping this task's execution. + * @method destroy + */ + proto.destroy = proto.stop; +}); + +/** + * @class Ext.perf.Accumulator + * @private + */ +Ext.define('Ext.perf.Accumulator', (function () { + var currentFrame = null, + khrome = Ext.global['chrome'], + formatTpl, + // lazy init on first request for timestamp (avoids infobar in IE until needed) + // Also avoids kicking off Chrome's microsecond timer until first needed + getTimestamp = function () { + + getTimestamp = function () { + return new Date().getTime(); + }; + + var interval, toolbox; + + // If Chrome is started with the --enable-benchmarking switch + if (Ext.isChrome && khrome && khrome.Interval) { + interval = new khrome.Interval(); + interval.start(); + getTimestamp = function () { + return interval.microseconds() / 1000; + }; + } else if (window.ActiveXObject) { + try { + // the above technique is not very accurate for small intervals... + toolbox = new ActiveXObject('SenchaToolbox.Toolbox'); + Ext.senchaToolbox = toolbox; // export for other uses + getTimestamp = function () { + return toolbox.milliseconds; + }; + } catch (e) { + // ignore + } + } else if (Date.now) { + getTimestamp = Date.now; + } + + Ext.perf.getTimestamp = Ext.perf.Accumulator.getTimestamp = getTimestamp; + return getTimestamp(); + }; + + function adjustSet (set, time) { + set.sum += time; + set.min = Math.min(set.min, time); + set.max = Math.max(set.max, time); + } + + function leaveFrame (time) { + var totalTime = time ? time : (getTimestamp() - this.time), // do this first + me = this, // me = frame + accum = me.accum; + + ++accum.count; + if (! --accum.depth) { + adjustSet(accum.total, totalTime); + } + adjustSet(accum.pure, totalTime - me.childTime); + + currentFrame = me.parent; + if (currentFrame) { + ++currentFrame.accum.childCount; + currentFrame.childTime += totalTime; + } + } + + function makeSet () { + return { + min: Number.MAX_VALUE, + max: 0, + sum: 0 + }; + } + + function makeTap (me, fn) { + return function () { + var frame = me.enter(), + ret = fn.apply(this, arguments); + + frame.leave(); + return ret; + }; + } + + function round (x) { + return Math.round(x * 100) / 100; + } + + function setToJSON (count, childCount, calibration, set) { + var data = { + avg: 0, + min: set.min, + max: set.max, + sum: 0 + }; + + if (count) { + calibration = calibration || 0; + data.sum = set.sum - childCount * calibration; + data.avg = data.sum / count; + // min and max cannot be easily corrected since we don't know the number of + // child calls for them. + } + + return data; + } + + return { + constructor: function (name) { + var me = this; + + me.count = me.childCount = me.depth = me.maxDepth = 0; + me.pure = makeSet(); + me.total = makeSet(); + me.name = name; + }, + + statics: { + getTimestamp: getTimestamp + }, + + format: function (calibration) { + if (!formatTpl) { + formatTpl = new Ext.XTemplate([ + '{name} - {count} call(s)', + '', + '', + ' ({childCount} children)', + '', + '', + ' ({depth} deep)', + '', + '', + ', {type}: {[this.time(values.sum)]} msec (', + //'min={[this.time(values.min)]}, ', + 'avg={[this.time(values.sum / parent.count)]}', + //', max={[this.time(values.max)]}', + ')', + '', + '' + ].join(''), { + time: function (t) { + return Math.round(t * 100) / 100; + } + }); + } + + var data = this.getData(calibration); + data.name = this.name; + data.pure.type = 'Pure'; + data.total.type = 'Total'; + data.times = [data.pure, data.total]; + return formatTpl.apply(data); + }, + + getData: function (calibration) { + var me = this; + + return { + count: me.count, + childCount: me.childCount, + depth: me.maxDepth, + pure: setToJSON(me.count, me.childCount, calibration, me.pure), + total: setToJSON(me.count, me.childCount, calibration, me.total) + }; + }, + + enter: function () { + var me = this, + frame = { + accum: me, + leave: leaveFrame, + childTime: 0, + parent: currentFrame + }; + + ++me.depth; + if (me.maxDepth < me.depth) { + me.maxDepth = me.depth; + } + + currentFrame = frame; + frame.time = getTimestamp(); // do this last + return frame; + }, + + monitor: function (fn, scope, args) { + var frame = this.enter(); + if (args) { + fn.apply(scope, args); + } else { + fn.call(scope); + } + frame.leave(); + }, + + report: function () { + Ext.log(this.format()); + }, + + tap: function (className, methodName) { + var me = this, + methods = typeof methodName == 'string' ? [methodName] : methodName, + klass, statik, i, parts, length, name, src, + tapFunc; + + tapFunc = function(){ + if (typeof className == 'string') { + klass = Ext.global; + parts = className.split('.'); + for (i = 0, length = parts.length; i < length; ++i) { + klass = klass[parts[i]]; + } + } else { + klass = className; + } + + for (i = 0, length = methods.length; i < length; ++i) { + name = methods[i]; + statik = name.charAt(0) == '!'; + + if (statik) { + name = name.substring(1); + } else { + statik = !(name in klass.prototype); + } + + src = statik ? klass : klass.prototype; + src[name] = makeTap(me, src[name]); + } + }; + + Ext.ClassManager.onCreated(tapFunc, me, className); + + return me; + } + }; +}()), + +function () { + Ext.perf.getTimestamp = this.getTimestamp; +}); + +/** + * @class Ext.perf.Monitor + * @singleton + * @private + */ +Ext.define('Ext.perf.Monitor', { + singleton: true, + alternateClassName: 'Ext.Perf', + + requires: [ + 'Ext.perf.Accumulator' + ], + + constructor: function () { + this.accumulators = []; + this.accumulatorsByName = {}; + }, + + calibrate: function () { + var accum = new Ext.perf.Accumulator('$'), + total = accum.total, + getTimestamp = Ext.perf.Accumulator.getTimestamp, + count = 0, + frame, + endTime, + startTime; + + startTime = getTimestamp(); + + do { + frame = accum.enter(); + frame.leave(); + ++count; + } while (total.sum < 100); + + endTime = getTimestamp(); + + return (endTime - startTime) / count; + }, + + get: function (name) { + var me = this, + accum = me.accumulatorsByName[name]; + + if (!accum) { + me.accumulatorsByName[name] = accum = new Ext.perf.Accumulator(name); + me.accumulators.push(accum); + } + + return accum; + }, + + enter: function (name) { + return this.get(name).enter(); + }, + + monitor: function (name, fn, scope) { + this.get(name).monitor(fn, scope); + }, + + report: function () { + var me = this, + accumulators = me.accumulators, + calibration = me.calibrate(); + + accumulators.sort(function (a, b) { + return (a.name < b.name) ? -1 : ((b.name < a.name) ? 1 : 0); + }); + + me.updateGC(); + + Ext.log('Calibration: ' + Math.round(calibration * 100) / 100 + ' msec/sample'); + Ext.each(accumulators, function (accum) { + Ext.log(accum.format(calibration)); + }); + }, + + getData: function (all) { + var ret = {}, + accumulators = this.accumulators; + + Ext.each(accumulators, function (accum) { + if (all || accum.count) { + ret[accum.name] = accum.getData(); + } + }); + + return ret; + }, + + updateGC: function () { + var accumGC = this.accumulatorsByName.GC, + toolbox = Ext.senchaToolbox, + bucket; + + if (accumGC) { + accumGC.count = toolbox.garbageCollectionCounter || 0; + + if (accumGC.count) { + bucket = accumGC.pure; + accumGC.total.sum = bucket.sum = toolbox.garbageCollectionMilliseconds; + bucket.min = bucket.max = bucket.sum / accumGC.count; + bucket = accumGC.total; + bucket.min = bucket.max = bucket.sum / accumGC.count; + } + } + }, + + watchGC: function () { + Ext.perf.getTimestamp(); // initializes SenchaToolbox (if available) + + var toolbox = Ext.senchaToolbox; + + if (toolbox) { + this.get("GC"); + toolbox.watchGarbageCollector(false); // no logging, just totals + } + }, + + setup: function (config) { + if (!config) { + config = { + /*insertHtml: { + 'Ext.dom.Helper': 'insertHtml' + },*/ + /*xtplCompile: { + 'Ext.XTemplateCompiler': 'compile' + },*/ +// doInsert: { +// 'Ext.Template': 'doInsert' +// }, +// applyOut: { +// 'Ext.XTemplate': 'applyOut' +// }, + render: { + 'Ext.AbstractComponent': 'render' + }, +// fnishRender: { +// 'Ext.AbstractComponent': 'finishRender' +// }, +// renderSelectors: { +// 'Ext.AbstractComponent': 'applyRenderSelectors' +// }, +// compAddCls: { +// 'Ext.AbstractComponent': 'addCls' +// }, +// compRemoveCls: { +// 'Ext.AbstractComponent': 'removeCls' +// }, +// getStyle: { +// 'Ext.core.Element': 'getStyle' +// }, +// setStyle: { +// 'Ext.core.Element': 'setStyle' +// }, +// addCls: { +// 'Ext.core.Element': 'addCls' +// }, +// removeCls: { +// 'Ext.core.Element': 'removeCls' +// }, +// measure: { +// 'Ext.layout.component.Component': 'measureAutoDimensions' +// }, +// moveItem: { +// 'Ext.layout.Layout': 'moveItem' +// }, +// layoutFlush: { +// 'Ext.layout.Context': 'flush' +// }, + layout: { + 'Ext.layout.Context': 'run' + } + }; + } + + this.currentConfig = config; + + var key, prop, + accum, className, methods; + for (key in config) { + if (config.hasOwnProperty(key)) { + prop = config[key]; + accum = Ext.Perf.get(key); + + for (className in prop) { + if (prop.hasOwnProperty(className)) { + methods = prop[className]; + accum.tap(className, methods); + } + } + } + } + + this.watchGC(); + } +}); + +/** + * @class Ext.is + * + * Determines information about the current platform the application is running on. + * + * @singleton + */ +Ext.is = { + init : function(navigator) { + var platforms = this.platforms, + ln = platforms.length, + i, platform; + + navigator = navigator || window.navigator; + + for (i = 0; i < ln; i++) { + platform = platforms[i]; + this[platform.identity] = platform.regex.test(navigator[platform.property]); + } + + /** + * @property Desktop True if the browser is running on a desktop machine + * @type {Boolean} + */ + this.Desktop = this.Mac || this.Windows || (this.Linux && !this.Android); + /** + * @property Tablet True if the browser is running on a tablet (iPad) + */ + this.Tablet = this.iPad; + /** + * @property Phone True if the browser is running on a phone. + * @type {Boolean} + */ + this.Phone = !this.Desktop && !this.Tablet; + /** + * @property iOS True if the browser is running on iOS + * @type {Boolean} + */ + this.iOS = this.iPhone || this.iPad || this.iPod; + + /** + * @property Standalone Detects when application has been saved to homescreen. + * @type {Boolean} + */ + this.Standalone = !!window.navigator.standalone; + }, + + /** + * @property iPhone True when the browser is running on a iPhone + * @type {Boolean} + */ + platforms: [{ + property: 'platform', + regex: /iPhone/i, + identity: 'iPhone' + }, + + /** + * @property iPod True when the browser is running on a iPod + * @type {Boolean} + */ + { + property: 'platform', + regex: /iPod/i, + identity: 'iPod' + }, + + /** + * @property iPad True when the browser is running on a iPad + * @type {Boolean} + */ + { + property: 'userAgent', + regex: /iPad/i, + identity: 'iPad' + }, + + /** + * @property Blackberry True when the browser is running on a Blackberry + * @type {Boolean} + */ + { + property: 'userAgent', + regex: /Blackberry/i, + identity: 'Blackberry' + }, + + /** + * @property Android True when the browser is running on an Android device + * @type {Boolean} + */ + { + property: 'userAgent', + regex: /Android/i, + identity: 'Android' + }, + + /** + * @property Mac True when the browser is running on a Mac + * @type {Boolean} + */ + { + property: 'platform', + regex: /Mac/i, + identity: 'Mac' + }, + + /** + * @property Windows True when the browser is running on Windows + * @type {Boolean} + */ + { + property: 'platform', + regex: /Win/i, + identity: 'Windows' + }, + + /** + * @property Linux True when the browser is running on Linux + * @type {Boolean} + */ + { + property: 'platform', + regex: /Linux/i, + identity: 'Linux' + }] +}; + +Ext.is.init(); + +/** + * @class Ext.supports + * + * Determines information about features are supported in the current environment + * + * @singleton + */ +(function(){ + + // this is a local copy of certain logic from (Abstract)Element.getStyle + // to break a dependancy between the supports mechanism and Element + // use this instead of element references to check for styling info + var getStyle = function(element, styleName){ + var view = element.ownerDocument.defaultView, + style = (view ? view.getComputedStyle(element, null) : element.currentStyle) || element.style; + return style[styleName]; + }; + +Ext.supports = { + /** + * Runs feature detection routines and sets the various flags. This is called when + * the scripts loads (very early) and again at {@link Ext#onReady}. Some detections + * are flagged as `early` and run immediately. Others that require the document body + * will not run until ready. + * + * Each test is run only once, so calling this method from an onReady function is safe + * and ensures that all flags have been set. + * @markdown + * @private + */ + init : function() { + var me = this, + doc = document, + tests = me.tests, + n = tests.length, + div = n && Ext.isReady && doc.createElement('div'), + test, notRun = []; + + if (div) { + div.innerHTML = [ + '
    ', + '
    ', + '
    ', + '
    ', + '
    ', + '
    ', + '
    ', + '
    ' + ].join(''); + + doc.body.appendChild(div); + } + + while (n--) { + test = tests[n]; + if (div || test.early) { + me[test.identity] = test.fn.call(me, doc, div); + } else { + notRun.push(test); + } + } + + if (div) { + doc.body.removeChild(div); + } + + me.tests = notRun; + }, + + /** + * @property PointerEvents True if document environment supports the CSS3 pointer-events style. + * @type {Boolean} + */ + PointerEvents: 'pointerEvents' in document.documentElement.style, + + /** + * @property CSS3BoxShadow True if document environment supports the CSS3 box-shadow style. + * @type {Boolean} + */ + CSS3BoxShadow: 'boxShadow' in document.documentElement.style || 'WebkitBoxShadow' in document.documentElement.style || 'MozBoxShadow' in document.documentElement.style, + + /** + * @property ClassList True if document environment supports the HTML5 classList API. + * @type {Boolean} + */ + ClassList: !!document.documentElement.classList, + + /** + * @property OrientationChange True if the device supports orientation change + * @type {Boolean} + */ + OrientationChange: ((typeof window.orientation != 'undefined') && ('onorientationchange' in window)), + + /** + * @property DeviceMotion True if the device supports device motion (acceleration and rotation rate) + * @type {Boolean} + */ + DeviceMotion: ('ondevicemotion' in window), + + /** + * @property Touch True if the device supports touch + * @type {Boolean} + */ + // is.Desktop is needed due to the bug in Chrome 5.0.375, Safari 3.1.2 + // and Safari 4.0 (they all have 'ontouchstart' in the window object). + Touch: ('ontouchstart' in window) && (!Ext.is.Desktop), + + /** + * @property TimeoutActualLateness True if the browser passes the "actualLateness" parameter to + * setTimeout. See: https://developer.mozilla.org/en/DOM/window.setTimeout + * @type {Boolean} + */ + TimeoutActualLateness: (function(){ + setTimeout(function(){ + Ext.supports.TimeoutActualLateness = arguments.length !== 0; + }, 0); + }()), + + tests: [ + /** + * @property Transitions True if the device supports CSS3 Transitions + * @type {Boolean} + */ + { + identity: 'Transitions', + fn: function(doc, div) { + var prefix = [ + 'webkit', + 'Moz', + 'o', + 'ms', + 'khtml' + ], + TE = 'TransitionEnd', + transitionEndName = [ + prefix[0] + TE, + 'transitionend', //Moz bucks the prefixing convention + prefix[2] + TE, + prefix[3] + TE, + prefix[4] + TE + ], + ln = prefix.length, + i = 0, + out = false; + + for (; i < ln; i++) { + if (getStyle(div, prefix[i] + "TransitionProperty")) { + Ext.supports.CSS3Prefix = prefix[i]; + Ext.supports.CSS3TransitionEnd = transitionEndName[i]; + out = true; + break; + } + } + return out; + } + }, + + /** + * @property RightMargin True if the device supports right margin. + * See https://bugs.webkit.org/show_bug.cgi?id=13343 for why this is needed. + * @type {Boolean} + */ + { + identity: 'RightMargin', + fn: function(doc, div) { + var view = doc.defaultView; + return !(view && view.getComputedStyle(div.firstChild.firstChild, null).marginRight != '0px'); + } + }, + + /** + * @property DisplayChangeInputSelectionBug True if INPUT elements lose their + * selection when their display style is changed. Essentially, if a text input + * has focus and its display style is changed, the I-beam disappears. + * + * This bug is encountered due to the work around in place for the {@link #RightMargin} + * bug. This has been observed in Safari 4.0.4 and older, and appears to be fixed + * in Safari 5. It's not clear if Safari 4.1 has the bug, but it has the same WebKit + * version number as Safari 5 (according to http://unixpapa.com/js/gecko.html). + */ + { + identity: 'DisplayChangeInputSelectionBug', + early: true, + fn: function() { + var webKitVersion = Ext.webKitVersion; + // WebKit but older than Safari 5 or Chrome 6: + return 0 < webKitVersion && webKitVersion < 533; + } + }, + + /** + * @property DisplayChangeTextAreaSelectionBug True if TEXTAREA elements lose their + * selection when their display style is changed. Essentially, if a text area has + * focus and its display style is changed, the I-beam disappears. + * + * This bug is encountered due to the work around in place for the {@link #RightMargin} + * bug. This has been observed in Chrome 10 and Safari 5 and older, and appears to + * be fixed in Chrome 11. + */ + { + identity: 'DisplayChangeTextAreaSelectionBug', + early: true, + fn: function() { + var webKitVersion = Ext.webKitVersion; + + /* + Has bug w/textarea: + + (Chrome) Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7; en-US) + AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.127 + Safari/534.16 + (Safari) Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7; en-us) + AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 + Safari/533.21.1 + + No bug: + + (Chrome) Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_7) + AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.57 + Safari/534.24 + */ + return 0 < webKitVersion && webKitVersion < 534.24; + } + }, + + /** + * @property TransparentColor True if the device supports transparent color + * @type {Boolean} + */ + { + identity: 'TransparentColor', + fn: function(doc, div, view) { + view = doc.defaultView; + return !(view && view.getComputedStyle(div.lastChild, null).backgroundColor != 'transparent'); + } + }, + + /** + * @property ComputedStyle True if the browser supports document.defaultView.getComputedStyle() + * @type {Boolean} + */ + { + identity: 'ComputedStyle', + fn: function(doc, div, view) { + view = doc.defaultView; + return view && view.getComputedStyle; + } + }, + + /** + * @property SVG True if the device supports SVG + * @type {Boolean} + */ + { + identity: 'Svg', + fn: function(doc) { + return !!doc.createElementNS && !!doc.createElementNS( "http:/" + "/www.w3.org/2000/svg", "svg").createSVGRect; + } + }, + + /** + * @property Canvas True if the device supports Canvas + * @type {Boolean} + */ + { + identity: 'Canvas', + fn: function(doc) { + return !!doc.createElement('canvas').getContext; + } + }, + + /** + * @property VML True if the device supports VML + * @type {Boolean} + */ + { + identity: 'Vml', + fn: function(doc) { + var d = doc.createElement("div"); + d.innerHTML = ""; + return (d.childNodes.length == 2); + } + }, + + /** + * @property Float True if the device supports CSS float + * @type {Boolean} + */ + { + identity: 'Float', + fn: function(doc, div) { + return !!div.lastChild.style.cssFloat; + } + }, + + /** + * @property AudioTag True if the device supports the HTML5 audio tag + * @type {Boolean} + */ + { + identity: 'AudioTag', + fn: function(doc) { + return !!doc.createElement('audio').canPlayType; + } + }, + + /** + * @property History True if the device supports HTML5 history + * @type {Boolean} + */ + { + identity: 'History', + fn: function() { + var history = window.history; + return !!(history && history.pushState); + } + }, + + /** + * @property CSS3DTransform True if the device supports CSS3DTransform + * @type {Boolean} + */ + { + identity: 'CSS3DTransform', + fn: function() { + return (typeof WebKitCSSMatrix != 'undefined' && new WebKitCSSMatrix().hasOwnProperty('m41')); + } + }, + + /** + * @property CSS3LinearGradient True if the device supports CSS3 linear gradients + * @type {Boolean} + */ + { + identity: 'CSS3LinearGradient', + fn: function(doc, div) { + var property = 'background-image:', + webkit = '-webkit-gradient(linear, left top, right bottom, from(black), to(white))', + w3c = 'linear-gradient(left top, black, white)', + moz = '-moz-' + w3c, + opera = '-o-' + w3c, + options = [property + webkit, property + w3c, property + moz, property + opera]; + + div.style.cssText = options.join(';'); + + return ("" + div.style.backgroundImage).indexOf('gradient') !== -1; + } + }, + + /** + * @property CSS3BorderRadius True if the device supports CSS3 border radius + * @type {Boolean} + */ + { + identity: 'CSS3BorderRadius', + fn: function(doc, div) { + var domPrefixes = ['borderRadius', 'BorderRadius', 'MozBorderRadius', 'WebkitBorderRadius', 'OBorderRadius', 'KhtmlBorderRadius'], + pass = false, + i; + for (i = 0; i < domPrefixes.length; i++) { + if (document.body.style[domPrefixes[i]] !== undefined) { + return true; + } + } + return pass; + } + }, + + /** + * @property GeoLocation True if the device supports GeoLocation + * @type {Boolean} + */ + { + identity: 'GeoLocation', + fn: function() { + return (typeof navigator != 'undefined' && typeof navigator.geolocation != 'undefined') || (typeof google != 'undefined' && typeof google.gears != 'undefined'); + } + }, + /** + * @property MouseEnterLeave True if the browser supports mouseenter and mouseleave events + * @type {Boolean} + */ + { + identity: 'MouseEnterLeave', + fn: function(doc, div){ + return ('onmouseenter' in div && 'onmouseleave' in div); + } + }, + /** + * @property MouseWheel True if the browser supports the mousewheel event + * @type {Boolean} + */ + { + identity: 'MouseWheel', + fn: function(doc, div) { + return ('onmousewheel' in div); + } + }, + /** + * @property Opacity True if the browser supports normal css opacity + * @type {Boolean} + */ + { + identity: 'Opacity', + fn: function(doc, div){ + // Not a strict equal comparison in case opacity can be converted to a number. + if (Ext.isIE6 || Ext.isIE7 || Ext.isIE8) { + return false; + } + div.firstChild.style.cssText = 'opacity:0.73'; + return div.firstChild.style.opacity == '0.73'; + } + }, + /** + * @property Placeholder True if the browser supports the HTML5 placeholder attribute on inputs + * @type {Boolean} + */ + { + identity: 'Placeholder', + fn: function(doc) { + return 'placeholder' in doc.createElement('input'); + } + }, + + /** + * @property Direct2DBug True if when asking for an element's dimension via offsetWidth or offsetHeight, + * getBoundingClientRect, etc. the browser returns the subpixel width rounded to the nearest pixel. + * @type {Boolean} + */ + { + identity: 'Direct2DBug', + fn: function() { + return Ext.isString(document.body.style.msTransformOrigin); + } + }, + /** + * @property BoundingClientRect True if the browser supports the getBoundingClientRect method on elements + * @type {Boolean} + */ + { + identity: 'BoundingClientRect', + fn: function(doc, div) { + return Ext.isFunction(div.getBoundingClientRect); + } + }, + { + identity: 'IncludePaddingInWidthCalculation', + fn: function(doc, div){ + return div.childNodes[1].firstChild.offsetWidth == 210; + } + }, + { + identity: 'IncludePaddingInHeightCalculation', + fn: function(doc, div){ + return div.childNodes[1].firstChild.offsetHeight == 210; + } + }, + + /** + * @property ArraySort True if the Array sort native method isn't bugged. + * @type {Boolean} + */ + { + identity: 'ArraySort', + fn: function() { + var a = [1,2,3,4,5].sort(function(){ return 0; }); + return a[0] === 1 && a[1] === 2 && a[2] === 3 && a[3] === 4 && a[4] === 5; + } + }, + /** + * @property Range True if browser support document.createRange native method. + * @type {Boolean} + */ + { + identity: 'Range', + fn: function() { + return !!document.createRange; + } + }, + /** + * @property CreateContextualFragment True if browser support CreateContextualFragment range native methods. + * @type {Boolean} + */ + { + identity: 'CreateContextualFragment', + fn: function() { + var range = Ext.supports.Range ? document.createRange() : false; + + return range && !!range.createContextualFragment; + } + }, + + /** + * @property WindowOnError True if browser supports window.onerror. + * @type {Boolean} + */ + { + identity: 'WindowOnError', + fn: function () { + // sadly, we cannot feature detect this... + return Ext.isIE || Ext.isGecko || Ext.webKitVersion >= 534.16; // Chrome 10+ + } + }, + + /** + * @property TextAreaMaxLength True if the browser supports maxlength on textareas. + * @type {Boolean} + */ + { + identity: 'TextAreaMaxLength', + fn: function(){ + var el = document.createElement('textarea'); + return ('maxlength' in el); + } + }, + /** + * @property GetPositionPercentage True if the browser will return the left/top/right/bottom + * position as a percentage when explicitly set as a percentage value. + * @type {Boolean} + */ + // Related bug: https://bugzilla.mozilla.org/show_bug.cgi?id=707691#c7 + { + identity: 'GetPositionPercentage', + fn: function(doc, div){ + return getStyle(div.childNodes[2], 'left') == '10%'; + } + } + ] +}; +}()); + +Ext.supports.init(); // run the "early" detections now + + +/** + * @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. If not specified here, it must be specified during the {@link #delay} call. + * @param {Object} scope (optional) 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 + */ + this.delay = function(delay, newFn, newScope, newArgs) { + me.cancel(); + fn = newFn || fn; + scope = newScope || scope; + args = newArgs || args; + id = setInterval(call, delay); + }; + + /** + * Cancel the last queued timeout + */ + this.cancel = function(){ + if (id) { + clearInterval(id); + id = null; + } + }; +}; +Ext.require('Ext.util.DelayedTask', function() { + + /** + * Represents single event type that an Observable object listens to. + * All actual listeners are tracked inside here. When the event fires, + * it calls all the registered listener functions. + * + * @private + */ + Ext.util.Event = Ext.extend(Object, (function() { + function createTargeted(handler, listener, o, scope){ + return function(){ + if (o.target === arguments[0]){ + handler.apply(scope, arguments); + } + }; + } + + function createBuffered(handler, listener, o, scope) { + listener.task = new Ext.util.DelayedTask(); + return function() { + listener.task.delay(o.buffer, handler, scope, Ext.Array.toArray(arguments)); + }; + } + + function createDelayed(handler, listener, o, scope) { + return function() { + var task = new Ext.util.DelayedTask(); + if (!listener.tasks) { + listener.tasks = []; + } + listener.tasks.push(task); + task.delay(o.delay || 10, handler, scope, Ext.Array.toArray(arguments)); + }; + } + + function createSingle(handler, listener, o, scope) { + return function() { + var event = listener.ev; + + if (event.removeListener(listener.fn, scope) && event.observable) { + // Removing from a regular Observable-owned, named event (not an anonymous + // event such as Ext's readyEvent): Decrement the listeners count + event.observable.hasListeners[event.name]--; + } + + return handler.apply(scope, arguments); + }; + } + + return { + /** + * @property {Boolean} isEvent + * `true` in this class to identify an object as an instantiated Event, or subclass thereof. + */ + isEvent: true, + + constructor: function(observable, name) { + this.name = name; + this.observable = observable; + this.listeners = []; + }, + + addListener: function(fn, scope, options) { + var me = this, + listener; + scope = scope || me.observable; + + if (!fn) { + Ext.Error.raise({ + sourceClass: Ext.getClassName(this.observable), + sourceMethod: "addListener", + msg: "The specified callback function is undefined" + }); + } + + if (!me.isListening(fn, scope)) { + listener = me.createListener(fn, scope, options); + if (me.firing) { + // if we are currently firing this event, don't disturb the listener loop + me.listeners = me.listeners.slice(0); + } + me.listeners.push(listener); + } + }, + + createListener: function(fn, scope, o) { + o = o || {}; + scope = scope || this.observable; + + var listener = { + fn: fn, + scope: scope, + o: o, + ev: this + }, + handler = fn; + + // The order is important. The 'single' wrapper must be wrapped by the 'buffer' and 'delayed' wrapper + // because the event removal that the single listener does destroys the listener's DelayedTask(s) + if (o.single) { + handler = createSingle(handler, listener, o, scope); + } + if (o.target) { + handler = createTargeted(handler, listener, o, scope); + } + if (o.delay) { + handler = createDelayed(handler, listener, o, scope); + } + if (o.buffer) { + handler = createBuffered(handler, listener, o, scope); + } + + listener.fireFn = handler; + return listener; + }, + + findListener: function(fn, scope) { + var listeners = this.listeners, + i = listeners.length, + listener, + s; + + while (i--) { + listener = listeners[i]; + if (listener) { + s = listener.scope; + if (listener.fn == fn && (s == scope || s == this.observable)) { + return i; + } + } + } + + return - 1; + }, + + isListening: function(fn, scope) { + return this.findListener(fn, scope) !== -1; + }, + + removeListener: function(fn, scope) { + var me = this, + index, + listener, + k; + index = me.findListener(fn, scope); + if (index != -1) { + listener = me.listeners[index]; + + if (me.firing) { + me.listeners = me.listeners.slice(0); + } + + // cancel and remove a buffered handler that hasn't fired yet + if (listener.task) { + listener.task.cancel(); + delete listener.task; + } + + // cancel and remove all delayed handlers that haven't fired yet + k = listener.tasks && listener.tasks.length; + if (k) { + while (k--) { + listener.tasks[k].cancel(); + } + delete listener.tasks; + } + + // remove this listener from the listeners array + Ext.Array.erase(me.listeners, index, 1); + return true; + } + + return false; + }, + + // Iterate to stop any buffered/delayed events + clearListeners: function() { + var listeners = this.listeners, + i = listeners.length; + + while (i--) { + this.removeListener(listeners[i].fn, listeners[i].scope); + } + }, + + fire: function() { + var me = this, + listeners = me.listeners, + count = listeners.length, + i, + args, + listener; + + if (count > 0) { + me.firing = true; + for (i = 0; i < count; i++) { + listener = listeners[i]; + args = arguments.length ? Array.prototype.slice.call(arguments, 0) : []; + if (listener.o) { + args.push(listener.o); + } + if (listener && listener.fireFn.apply(listener.scope || me.observable, args) === false) { + return (me.firing = false); + } + } + } + me.firing = false; + return true; + } + }; + }())); +}); + +/** + * @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 = new function() { + var EventManager = this, + doc = document, + win = window, + initExtCss = function() { + // find the body element + var bd = doc.body || doc.getElementsByTagName('body')[0], + baseCSSPrefix = Ext.baseCSSPrefix, + cls = [baseCSSPrefix + 'body'], + htmlCls = [], + html; + + if (!bd) { + return false; + } + + html = bd.parentNode; + + function add (c) { + cls.push(baseCSSPrefix + c); + } + + //Let's keep this human readable! + if (Ext.isIE) { + add('ie'); + + // very often CSS needs to do checks like "IE7+" or "IE6 or 7". To help + // reduce the clutter (since CSS/SCSS cannot do these tests), we add some + // additional classes: + // + // x-ie7p : IE7+ : 7 <= ieVer + // x-ie7m : IE7- : ieVer <= 7 + // x-ie8p : IE8+ : 8 <= ieVer + // x-ie8m : IE8- : ieVer <= 8 + // x-ie9p : IE9+ : 9 <= ieVer + // x-ie78 : IE7 or 8 : 7 <= ieVer <= 8 + // + if (Ext.isIE6) { + add('ie6'); + } else { // ignore pre-IE6 :) + add('ie7p'); + + if (Ext.isIE7) { + add('ie7'); + } else { + add('ie8p'); + + if (Ext.isIE8) { + add('ie8'); + } else { + add('ie9p'); + + if (Ext.isIE9) { + add('ie9'); + } + } + } + } + + if (Ext.isIE6 || Ext.isIE7) { + add('ie7m'); + } + if (Ext.isIE6 || Ext.isIE7 || Ext.isIE8) { + add('ie8m'); + } + if (Ext.isIE7 || Ext.isIE8) { + add('ie78'); + } + } + if (Ext.isGecko) { + add('gecko'); + if (Ext.isGecko3) { + add('gecko3'); + } + if (Ext.isGecko4) { + add('gecko4'); + } + if (Ext.isGecko5) { + add('gecko5'); + } + } + if (Ext.isOpera) { + add('opera'); + } + if (Ext.isWebKit) { + add('webkit'); + } + if (Ext.isSafari) { + add('safari'); + if (Ext.isSafari2) { + add('safari2'); + } + if (Ext.isSafari3) { + add('safari3'); + } + if (Ext.isSafari4) { + add('safari4'); + } + if (Ext.isSafari5) { + add('safari5'); + } + if (Ext.isSafari5_0) { + add('safari5_0') + } + } + if (Ext.isChrome) { + add('chrome'); + } + if (Ext.isMac) { + add('mac'); + } + if (Ext.isLinux) { + add('linux'); + } + if (!Ext.supports.CSS3BorderRadius) { + add('nbr'); + } + if (!Ext.supports.CSS3LinearGradient) { + add('nlg'); + } + if (!Ext.scopeResetCSS) { + add('reset'); + } + + // add to the parent to allow for selectors x-strict x-border-box, also set the isBorderBox property correctly + if (html) { + if (Ext.isStrict && (Ext.isIE6 || Ext.isIE7)) { + Ext.isBorderBox = false; + } + else { + Ext.isBorderBox = true; + } + + if(Ext.isBorderBox) { + htmlCls.push(baseCSSPrefix + 'border-box'); + } + if (Ext.isStrict) { + htmlCls.push(baseCSSPrefix + 'strict'); + } else { + htmlCls.push(baseCSSPrefix + 'quirks'); + } + Ext.fly(html, '_internal').addCls(htmlCls); + } + + Ext.fly(bd, '_internal').addCls(cls); + return true; + }; + + Ext.apply(EventManager, { + /** + * Check if we have bound our global onReady listener + * @private + */ + hasBoundOnReady: false, + + /** + * Check if fireDocReady has been called + * @private + */ + hasFiredReady: false, + + /** + * Additionally, allow the 'DOM' listener thread to complete (usually desirable with mobWebkit, Gecko) + * before firing the entire onReady chain (high stack load on Loader) by specifying a delay value + * @default 1ms + * @private + */ + deferReadyEvent : 1, + + /* + * diags: a list of event names passed to onReadyEvent (in chron order) + * @private + */ + onReadyChain : [], + + /** + * Holds references to any onReady functions + * @private + */ + readyEvent: + (function () { + var event = new Ext.util.Event(); + event.fire = function () { + Ext._beforeReadyTime = Ext._beforeReadyTime || new Date().getTime(); + event.self.prototype.fire.apply(event, arguments); + Ext._afterReadytime = new Date().getTime(); + }; + return event; + }()), + + /** + * Fires when a DOM event handler finishes its run, just before returning to browser control. + * This can be useful for performing cleanup, or upfdate tasks which need to happen only + * after all code in an event handler has been run, but which should not be executed in a timer + * due to the intervening browser reflow/repaint which would take place. + * + */ + idleEvent: new Ext.util.Event(), + + /** + * detects whether the EventManager has been placed in a paused state for synchronization + * with external debugging / perf tools (PageAnalyzer) + * @private + */ + isReadyPaused: function(){ + return (/[?&]ext-pauseReadyFire\b/i.test(location.search) && !Ext._continueFireReady); + }, + + /** + * Binds the appropriate browser event for checking if the DOM has loaded. + * @private + */ + bindReadyEvent: function() { + if (EventManager.hasBoundOnReady) { + return; + } + + // Test scenario where Core is dynamically loaded AFTER window.load + if ( doc.readyState == 'complete' ) { // Firefox4+ got support for this state, others already do. + EventManager.onReadyEvent({ + type: doc.readyState || 'body' + }); + } else { + document.addEventListener('DOMContentLoaded', EventManager.onReadyEvent, false); + window.addEventListener('load', EventManager.onReadyEvent, false); + EventManager.hasBoundOnReady = true; + } + }, + + onReadyEvent : function(e) { + if (e && e.type) { + EventManager.onReadyChain.push(e.type); + } + + if (EventManager.hasBoundOnReady) { + document.removeEventListener('DOMContentLoaded', EventManager.onReadyEvent, false); + window.removeEventListener('load', EventManager.onReadyEvent, false); + } + + if (!Ext.isReady) { + EventManager.fireDocReady(); + } + }, + + /** + * We know the document is loaded, so trigger any onReady events. + * @private + */ + fireDocReady: function() { + if (!Ext.isReady) { + Ext._readyTime = new Date().getTime(); + Ext.isReady = true; + + Ext.supports.init(); + EventManager.onWindowUnload(); + EventManager.readyEvent.onReadyChain = EventManager.onReadyChain; //diags report + + if (Ext.isNumber(EventManager.deferReadyEvent)) { + Ext.Function.defer(EventManager.fireReadyEvent, EventManager.deferReadyEvent); + EventManager.hasDocReadyTimer = true; + } else { + EventManager.fireReadyEvent(); + } + } + }, + + /** + * Fires the ready event + * @private + */ + fireReadyEvent: function(){ + var readyEvent = EventManager.readyEvent; + + // Unset the timer flag here since other onReady events may be + // added during the fire() call and we don't want to block them + EventManager.hasDocReadyTimer = false; + EventManager.isFiring = true; + + // Ready events are all single: true, if we get to the end + // & there are more listeners, it means they were added + // inside some other ready event + while (readyEvent.listeners.length && !EventManager.isReadyPaused()) { + readyEvent.fire(); + } + EventManager.isFiring = false; + EventManager.hasFiredReady = true; + }, + + /** + * 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}. + */ + onDocumentReady: function(fn, scope, options) { + options = options || {}; + // force single, only ever fire it once + options.single = true; + EventManager.readyEvent.addListener(fn, scope, options); + + // If we're in the middle of firing, or we have a deferred timer + // pending, drop out since the event will be fired later + if (!(EventManager.isFiring || EventManager.hasDocReadyTimer)) { + if (Ext.isReady) { + EventManager.fireReadyEvent(); + } else { + EventManager.bindReadyEvent(); + } + } + }, + + // --------------------- event binding --------------------- + + /** + * Contains a list of all document mouse downs, so we can ensure they fire even when stopEvent is called. + * @private + */ + stoppedMouseDownEvent: new Ext.util.Event(), + + /** + * Options to parse for the 4th argument to addListener. + * @private + */ + propRe: /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate|freezeEvent)$/, + + /** + * Get the id of the element. If one has not been assigned, automatically assign it. + * @param {HTMLElement/Ext.Element} element The element to get the id for. + * @return {String} id + */ + getId : function(element) { + var id; + + element = Ext.getDom(element); + + if (element === doc || element === win) { + id = element === doc ? Ext.documentId : Ext.windowId; + } + else { + id = Ext.id(element); + } + + if (!Ext.cache[id]) { + Ext.addCacheEntry(id, null, element); + } + + return id; + }, + + /** + * Convert a "config style" listener into a set of flat arguments so they can be passed to addListener + * @private + * @param {Object} element The element the event is for + * @param {Object} event The event configuration + * @param {Object} isRemove True if a removal should be performed, otherwise an add will be done. + */ + prepareListenerConfig: function(element, config, isRemove) { + var propRe = EventManager.propRe, + key, value, args; + + // loop over all the keys in the object + for (key in config) { + if (config.hasOwnProperty(key)) { + // if the key is something else then an event option + if (!propRe.test(key)) { + value = config[key]; + // if the value is a function it must be something like click: function() {}, scope: this + // which means that there might be multiple event listeners with shared options + if (typeof value == 'function') { + // shared options + args = [element, key, value, config.scope, config]; + } else { + // if its not a function, it must be an object like click: {fn: function() {}, scope: this} + args = [element, key, value.fn, value.scope, value]; + } + + if (isRemove) { + EventManager.removeListener.apply(EventManager, args); + } else { + EventManager.addListener.apply(EventManager, args); + } + } + } + } + }, + + mouseEnterLeaveRe: /mouseenter|mouseleave/, + + /** + * Normalize cross browser event differences + * @private + * @param {Object} eventName The event name + * @param {Object} fn The function to execute + * @return {Object} The new event name/function + */ + normalizeEvent: function(eventName, fn) { + if (EventManager.mouseEnterLeaveRe.test(eventName) && !Ext.supports.MouseEnterLeave) { + if (fn) { + fn = Ext.Function.createInterceptor(fn, EventManager.contains); + } + eventName = eventName == 'mouseenter' ? 'mouseover' : 'mouseout'; + } else if (eventName == 'mousewheel' && !Ext.supports.MouseWheel && !Ext.isOpera) { + eventName = 'DOMMouseScroll'; + } + return { + eventName: eventName, + fn: fn + }; + }, + + /** + * Checks whether the event's relatedTarget is contained inside (or is) the element. + * @private + * @param {Object} event + */ + contains: function(event) { + var parent = event.browserEvent.currentTarget, + child = EventManager.getRelatedTarget(event); + + if (parent && parent.firstChild) { + while (child) { + if (child === parent) { + return false; + } + child = child.parentNode; + if (child && (child.nodeType != 1)) { + child = null; + } + } + } + return true; + }, + + /** + * 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:
      + *
    • evt : EventObject
      The {@link Ext.EventObject EventObject} describing the event.
    • + *
    • t : Element
      The {@link Ext.Element Element} which was the target of the event. + * Note that this may be filtered by using the delegate option.
    • + *
    • o : Object
      The options object from the addListener call.
    • + *
    + * @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:
      + *
    • scope : Object
      The scope (this reference) in which the handler function is executed. Defaults to the Element.
    • + *
    • delegate : String
      A simple selector to filter the target or look for a descendant of the target
    • + *
    • stopEvent : Boolean
      True to stop the event. That is stop propagation, and prevent the default action.
    • + *
    • preventDefault : Boolean
      True to prevent the default action
    • + *
    • stopPropagation : Boolean
      True to prevent event propagation
    • + *
    • normalized : Boolean
      False to pass a browser event to the handler function instead of an Ext.EventObject
    • + *
    • delay : Number
      The number of milliseconds to delay the invocation of the handler after te event fires.
    • + *
    • single : Boolean
      True to add a handler to handle just the next firing of the event, and then remove itself.
    • + *
    • buffer : Number
      Causes the handler to be scheduled to run in an {@link Ext.util.DelayedTask} delayed + * by the specified number of milliseconds. If the event fires again within that time, the original + * handler is not invoked, but the new handler is scheduled in its place.
    • + *
    • target : Element
      Only call the handler if the event was fired on the target Element, not if the event was bubbled up from a child node.
    • + *

    + *

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

    + */ + addListener: function(element, eventName, fn, scope, options) { + // Check if we've been passed a "config style" event. + if (typeof eventName !== 'string') { + EventManager.prepareListenerConfig(element, eventName); + return; + } + + var dom = element.dom || Ext.getDom(element), + bind, wrap; + + if (!fn) { + Ext.Error.raise({ + sourceClass: 'Ext.EventManager', + sourceMethod: 'addListener', + targetElement: element, + eventName: eventName, + msg: 'Error adding "' + eventName + '\" listener. The handler function is undefined.' + }); + } + + // create the wrapper function + options = options || {}; + + bind = EventManager.normalizeEvent(eventName, fn); + wrap = EventManager.createListenerWrap(dom, eventName, bind.fn, scope, options); + + if (dom.attachEvent) { + dom.attachEvent('on' + bind.eventName, wrap); + } else { + dom.addEventListener(bind.eventName, wrap, options.capture || false); + } + + if (dom == doc && eventName == 'mousedown') { + EventManager.stoppedMouseDownEvent.addListener(wrap); + } + + // add all required data into the event cache + EventManager.getEventListenerCache(element.dom ? element : dom, eventName).push({ + fn: fn, + wrap: wrap, + scope: scope + }); + }, + + /** + * Removes an event handler from an element. The shorthand version {@link #un} is equivalent. Typically + * you will use {@link Ext.Element#removeListener} directly on an Element in favor of calling this version. + * @param {String/HTMLElement} el The id or html element from which to remove the listener. + * @param {String} eventName The name of the event. + * @param {Function} fn The handler function to remove. 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) { + // handle our listener config object syntax + if (typeof eventName !== 'string') { + EventManager.prepareListenerConfig(element, eventName, true); + return; + } + + var dom = Ext.getDom(element), + el = element.dom ? element : Ext.get(dom), + cache = EventManager.getEventListenerCache(el, eventName), + bindName = EventManager.normalizeEvent(eventName).eventName, + i = cache.length, j, + listener, wrap, tasks; + + + while (i--) { + listener = cache[i]; + + if (listener && (!fn || listener.fn == fn) && (!scope || listener.scope === scope)) { + wrap = listener.wrap; + + // clear buffered calls + if (wrap.task) { + clearTimeout(wrap.task); + delete wrap.task; + } + + // clear delayed calls + j = wrap.tasks && wrap.tasks.length; + if (j) { + while (j--) { + clearTimeout(wrap.tasks[j]); + } + delete wrap.tasks; + } + + if (dom.detachEvent) { + dom.detachEvent('on' + bindName, wrap); + } else { + dom.removeEventListener(bindName, wrap, false); + } + + if (wrap && dom == doc && eventName == 'mousedown') { + EventManager.stoppedMouseDownEvent.removeListener(wrap); + } + + // remove listener from cache + Ext.Array.erase(cache, i, 1); + } + } + }, + + /** + * 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(element) { + var el = element.dom ? element : Ext.get(element), + cache, events, eventName; + + if (!el) { + return; + } + cache = (el.$cache || el.getCache()); + events = cache.events; + + for (eventName in events) { + if (events.hasOwnProperty(eventName)) { + EventManager.removeListener(el, eventName); + } + } + cache.events = {}; + }, + + /** + * Recursively removes all previous added listeners from an element and its children. Typically you will use {@link Ext.Element#purgeAllListeners} + * 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. + * @param {String} eventName (optional) The name of the event. + */ + purgeElement : function(element, eventName) { + var dom = Ext.getDom(element), + i = 0, len; + + if (eventName) { + EventManager.removeListener(element, eventName); + } + else { + EventManager.removeAll(element); + } + + if (dom && dom.childNodes) { + for (len = element.childNodes.length; i < len; i++) { + EventManager.purgeElement(element.childNodes[i], eventName); + } + } + }, + + /** + * Create the wrapper function for the event + * @private + * @param {HTMLElement} dom The dom element + * @param {String} ename The event name + * @param {Function} fn The function to execute + * @param {Object} scope The scope to execute callback in + * @param {Object} options The options + * @return {Function} the wrapper function + */ + createListenerWrap : function(dom, ename, fn, scope, options) { + options = options || {}; + + var f, gen, escapeRx = /\\/g, wrap = function(e, args) { + // Compile the implementation upon first firing + if (!gen) { + f = ['if(!' + Ext.name + ') {return;}']; + + if(options.buffer || options.delay || options.freezeEvent) { + f.push('e = new X.EventObjectImpl(e, ' + (options.freezeEvent ? 'true' : 'false' ) + ');'); + } else { + f.push('e = X.EventObject.setEvent(e);'); + } + + if (options.delegate) { + // double up '\' characters so escape sequences survive the + // string-literal translation + f.push('var t = e.getTarget("' + (options.delegate + '').replace(escapeRx, '\\\\') + '", this);'); + f.push('if(!t) {return;}'); + } else { + f.push('var t = e.target;'); + } + + if (options.target) { + f.push('if(e.target !== options.target) {return;}'); + } + + if(options.stopEvent) { + f.push('e.stopEvent();'); + } else { + if(options.preventDefault) { + f.push('e.preventDefault();'); + } + if(options.stopPropagation) { + f.push('e.stopPropagation();'); + } + } + + if(options.normalized === false) { + f.push('e = e.browserEvent;'); + } + + if(options.buffer) { + f.push('(wrap.task && clearTimeout(wrap.task));'); + f.push('wrap.task = setTimeout(function() {'); + } + + if(options.delay) { + f.push('wrap.tasks = wrap.tasks || [];'); + f.push('wrap.tasks.push(setTimeout(function() {'); + } + + // finally call the actual handler fn + f.push('fn.call(scope || dom, e, t, options);'); + + if(options.single) { + f.push('evtMgr.removeListener(dom, ename, fn, scope);'); + } + + // Fire the global idle event for all events except mousemove which is too common, and + // fires too frequently and fast to be use in tiggering onIdle processing. + if (ename !== 'mousemove') { + f.push('if (evtMgr.idleEvent.listeners.length) {'); + f.push('evtMgr.idleEvent.fire();'); + f.push('}'); + } + + if(options.delay) { + f.push('}, ' + options.delay + '));'); + } + + if(options.buffer) { + f.push('}, ' + options.buffer + ');'); + } + + gen = Ext.cacheableFunctionFactory('e', 'options', 'fn', 'scope', 'ename', 'dom', 'wrap', 'args', 'X', 'evtMgr', f.join('\n')); + } + + gen.call(dom, e, options, fn, scope, ename, dom, wrap, args, Ext, EventManager); + }; + return wrap; + }, + + /** + * Get the event cache for a particular element for a particular event + * @private + * @param {HTMLElement} element The element + * @param {Object} eventName The event name + * @return {Array} The events for the element + */ + getEventListenerCache : function(element, eventName) { + var elementCache, eventCache; + if (!element) { + return []; + } + + if (element.$cache) { + elementCache = element.$cache; + } else { + // getId will populate the cache for this element if it isn't already present + elementCache = Ext.cache[EventManager.getId(element)]; + } + eventCache = elementCache.events || (elementCache.events = {}); + + return eventCache[eventName] || (eventCache[eventName] = []); + }, + + // --------------------- utility methods --------------------- + mouseLeaveRe: /(mouseout|mouseleave)/, + mouseEnterRe: /(mouseover|mouseenter)/, + + /** + * Stop the event (preventDefault and stopPropagation) + * @param {Event} The event to stop + */ + stopEvent: function(event) { + EventManager.stopPropagation(event); + EventManager.preventDefault(event); + }, + + /** + * Cancels bubbling of the event. + * @param {Event} The event to stop bubbling. + */ + stopPropagation: function(event) { + event = event.browserEvent || event; + if (event.stopPropagation) { + event.stopPropagation(); + } else { + event.cancelBubble = true; + } + }, + + /** + * Prevents the browsers default handling of the event. + * @param {Event} The event to prevent the default + */ + preventDefault: function(event) { + event = event.browserEvent || event; + if (event.preventDefault) { + event.preventDefault(); + } else { + event.returnValue = false; + // Some keys events require setting the keyCode to -1 to be prevented + try { + // all ctrl + X and F1 -> F12 + if (event.ctrlKey || event.keyCode > 111 && event.keyCode < 124) { + event.keyCode = -1; + } + } catch (e) { + // see this outdated document http://support.microsoft.com/kb/934364/en-us for more info + } + } + }, + + /** + * Gets the related target from the event. + * @param {Object} event The event + * @return {HTMLElement} The related target. + */ + getRelatedTarget: function(event) { + event = event.browserEvent || event; + var target = event.relatedTarget; + if (!target) { + if (EventManager.mouseLeaveRe.test(event.type)) { + target = event.toElement; + } else if (EventManager.mouseEnterRe.test(event.type)) { + target = event.fromElement; + } + } + return EventManager.resolveTextNode(target); + }, + + /** + * Gets the x coordinate from the event + * @param {Object} event The event + * @return {Number} The x coordinate + */ + getPageX: function(event) { + return EventManager.getPageXY(event)[0]; + }, + + /** + * Gets the y coordinate from the event + * @param {Object} event The event + * @return {Number} The y coordinate + */ + getPageY: function(event) { + return EventManager.getPageXY(event)[1]; + }, + + /** + * Gets the x & y coordinate from the event + * @param {Object} event The event + * @return {Number[]} The x/y coordinate + */ + getPageXY: function(event) { + event = event.browserEvent || event; + var x = event.pageX, + y = event.pageY, + docEl = doc.documentElement, + body = doc.body; + + // pageX/pageY not available (undefined, not null), use clientX/clientY instead + if (!x && x !== 0) { + x = event.clientX + (docEl && docEl.scrollLeft || body && body.scrollLeft || 0) - (docEl && docEl.clientLeft || body && body.clientLeft || 0); + y = event.clientY + (docEl && docEl.scrollTop || body && body.scrollTop || 0) - (docEl && docEl.clientTop || body && body.clientTop || 0); + } + return [x, y]; + }, + + /** + * Gets the target of the event. + * @param {Object} event The event + * @return {HTMLElement} target + */ + getTarget: function(event) { + event = event.browserEvent || event; + return EventManager.resolveTextNode(event.target || event.srcElement); + }, + + // technically no need to browser sniff this, however it makes + // no sense to check this every time, for every event, whether + // the string is equal. + /** + * Resolve any text nodes accounting for browser differences. + * @private + * @param {HTMLElement} node The node + * @return {HTMLElement} The resolved node + */ + resolveTextNode: Ext.isGecko ? + function(node) { + if (!node) { + return; + } + // work around firefox bug, https://bugzilla.mozilla.org/show_bug.cgi?id=101197 + var s = HTMLElement.prototype.toString.call(node); + if (s == '[xpconnect wrapped native prototype]' || s == '[object XULElement]') { + return; + } + return node.nodeType == 3 ? node.parentNode: node; + }: function(node) { + return node && node.nodeType == 3 ? node.parentNode: node; + }, + + // --------------------- custom event binding --------------------- + + // Keep track of the current width/height + curWidth: 0, + curHeight: 0, + + /** + * Adds a listener to be notified when the browser window is resized and provides resize event buffering (100 milliseconds), + * passes new viewport width and height to handlers. + * @param {Function} fn The handler function the window resize event invokes. + * @param {Object} scope The scope (this reference) in which the handler function executes. Defaults to the browser window. + * @param {Boolean} options Options object as passed to {@link Ext.Element#addListener} + */ + onWindowResize: function(fn, scope, options) { + var resize = EventManager.resizeEvent; + + if (!resize) { + EventManager.resizeEvent = resize = new Ext.util.Event(); + EventManager.on(win, 'resize', EventManager.fireResize, null, {buffer: 100}); + } + resize.addListener(fn, scope, options); + }, + + /** + * Fire the resize event. + * @private + */ + fireResize: function() { + var w = Ext.Element.getViewWidth(), + h = Ext.Element.getViewHeight(); + + //whacky problem in IE where the resize event will sometimes fire even though the w/h are the same. + if (EventManager.curHeight != h || EventManager.curWidth != w) { + EventManager.curHeight = h; + EventManager.curWidth = w; + EventManager.resizeEvent.fire(w, h); + } + }, + + /** + * 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) { + var resize = EventManager.resizeEvent; + if (resize) { + resize.removeListener(fn, scope); + } + }, + + /** + * Adds a listener to be notified when the browser window is unloaded. + * @param {Function} fn The handler function the window unload event invokes. + * @param {Object} scope The scope (this reference) in which the handler function executes. Defaults to the browser window. + * @param {Boolean} options Options object as passed to {@link Ext.Element#addListener} + */ + onWindowUnload: function(fn, scope, options) { + var unload = EventManager.unloadEvent; + + if (!unload) { + EventManager.unloadEvent = unload = new Ext.util.Event(); + EventManager.addListener(win, 'unload', EventManager.fireUnload); + } + if (fn) { + unload.addListener(fn, scope, options); + } + }, + + /** + * Fires the unload event for items bound with onWindowUnload + * @private + */ + fireUnload: function() { + // wrap in a try catch, could have some problems during unload + try { + // relinquish references. + doc = win = undefined; + + var gridviews, i, ln, + el, cache; + + EventManager.unloadEvent.fire(); + // Work around FF3 remembering the last scroll position when refreshing the grid and then losing grid view + if (Ext.isGecko3) { + gridviews = Ext.ComponentQuery.query('gridview'); + i = 0; + ln = gridviews.length; + for (; i < ln; i++) { + gridviews[i].scrollToTop(); + } + } + // Purge all elements in the cache + cache = Ext.cache; + + for (el in cache) { + if (cache.hasOwnProperty(el)) { + EventManager.removeAll(el); + } + } + } catch(e) { + } + }, + + /** + * Removes the passed window unload listener. + * @param {Function} fn The method the event invokes + * @param {Object} scope The scope of handler + */ + removeUnloadListener: function(fn, scope) { + var unload = EventManager.unloadEvent; + if (unload) { + unload.removeListener(fn, scope); + } + }, + + /** + * 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) + * @private + */ + useKeyDown: Ext.isWebKit ? + parseInt(navigator.userAgent.match(/AppleWebKit\/(\d+)/)[1], 10) >= 525 : + !((Ext.isGecko && !Ext.isWindows) || Ext.isOpera), + + /** + * Indicates which event to use for getting key presses. + * @return {String} The appropriate event name. + */ + getKeyEvent: function() { + return EventManager.useKeyDown ? 'keydown' : 'keypress'; + } + }); + + // route "< ie9-Standards" to a legacy IE onReady implementation + if(!('addEventListener' in document) && document.attachEvent) { + Ext.apply( EventManager, { + /* Customized implementation for Legacy IE. The default implementation is configured for use + * with all other 'standards compliant' agents. + * References: http://javascript.nwbox.com/IEContentLoaded/ + * licensed courtesy of http://developer.yahoo.com/yui/license.html + */ + + /** + * This strategy has minimal benefits for Sencha solutions that build themselves (ie. minimal initial page markup). + * However, progressively-enhanced pages (with image content and/or embedded frames) will benefit the most from it. + * Browser timer resolution is too poor to ensure a doScroll check more than once on a page loaded with minimal + * assets (the readystatechange event 'complete' usually beats the doScroll timer on a 'lightly-loaded' initial document). + */ + pollScroll : function() { + var scrollable = true; + + try { + document.documentElement.doScroll('left'); + } catch(e) { + scrollable = false; + } + + if (scrollable) { + EventManager.onReadyEvent({ + type:'doScroll' + }); + } else { + /* + * minimize thrashing -- + * adjusted for setTimeout's close-to-minimums (not too low), + * as this method SHOULD always be called once initially + */ + EventManager.scrollTimeout = setTimeout(EventManager.pollScroll, 20); + } + + return scrollable; + }, + + /** + * Timer for doScroll polling + * @private + */ + scrollTimeout: null, + + /* @private + */ + readyStatesRe : /complete/i, + + /* @private + */ + checkReadyState: function() { + var state = document.readyState; + + if (EventManager.readyStatesRe.test(state)) { + EventManager.onReadyEvent({ + type: state + }); + } + }, + + bindReadyEvent: function() { + var topContext = true; + + if (EventManager.hasBoundOnReady) { + return; + } + + //are we in an IFRAME? (doScroll ineffective here) + try { + topContext = !window.frameElement; + } catch(e) { + } + + if (!topContext || !doc.documentElement.doScroll) { + EventManager.pollScroll = Ext.emptyFn; //then noop this test altogether + } + + // starts doScroll polling if necessary + if (EventManager.pollScroll() === true) { + return; + } + + // Core is loaded AFTER initial document write/load ? + if (doc.readyState == 'complete' ) { + EventManager.onReadyEvent({type: 'already ' + (doc.readyState || 'body') }); + } else { + doc.attachEvent('onreadystatechange', EventManager.checkReadyState); + window.attachEvent('onload', EventManager.onReadyEvent); + EventManager.hasBoundOnReady = true; + } + }, + + onReadyEvent : function(e) { + if (e && e.type) { + EventManager.onReadyChain.push(e.type); + } + + if (EventManager.hasBoundOnReady) { + document.detachEvent('onreadystatechange', EventManager.checkReadyState); + window.detachEvent('onload', EventManager.onReadyEvent); + } + + if (Ext.isNumber(EventManager.scrollTimeout)) { + clearTimeout(EventManager.scrollTimeout); + delete EventManager.scrollTimeout; + } + + if (!Ext.isReady) { + EventManager.fireDocReady(); + } + }, + + //diags: a list of event types passed to onReadyEvent (in chron order) + onReadyChain : [] + }); + } + + + /** + * Alias for {@link Ext.Loader#onReady Ext.Loader.onReady} with withDomReady set to true + * @member Ext + * @method onReady + */ + Ext.onReady = function(fn, scope, options) { + Ext.Loader.onReady(fn, scope, true, options); + }; + + /** + * Alias for {@link Ext.EventManager#onDocumentReady Ext.EventManager.onDocumentReady} + * @member Ext + * @method onDocumentReady + */ + Ext.onDocumentReady = EventManager.onDocumentReady; + + /** + * Alias for {@link Ext.EventManager#addListener Ext.EventManager.addListener} + * @member Ext.EventManager + * @method on + */ + EventManager.on = EventManager.addListener; + + /** + * Alias for {@link Ext.EventManager#removeListener Ext.EventManager.removeListener} + * @member Ext.EventManager + * @method un + */ + EventManager.un = EventManager.removeListener; + + Ext.onReady(initExtCss); +}; + +/** + * @class Ext.EventObject + +Just as {@link Ext.Element} wraps around a native DOM node, Ext.EventObject +wraps the browser's native event-object normalizing cross-browser differences, +such as which mouse button is clicked, keys pressed, mechanisms to stop +event-propagation along with a method to prevent default actions from taking place. + +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 + * @markdown + */ +Ext.define('Ext.EventObjectImpl', { + uses: ['Ext.util.Point'], + + /** 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, + /** 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, + /** Key constant @type Number */ + PAGE_DOWN: 34, + /** 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, + /** + * The mouse wheel delta scaling factor. This value depends on browser version and OS and + * attempts to produce a similar scrolling experience across all platforms and browsers. + * + * To change this value: + * + * Ext.EventObjectImpl.prototype.WHEEL_SCALE = 72; + * + * @type Number + * @markdown + */ + WHEEL_SCALE: (function () { + var scale; + + if (Ext.isGecko) { + // Firefox uses 3 on all platforms + scale = 3; + } else if (Ext.isMac) { + // Continuous scrolling devices have momentum and produce much more scroll than + // discrete devices on the same OS and browser. To make things exciting, Safari + // (and not Chrome) changed from small values to 120 (like IE). + + if (Ext.isSafari && Ext.webKitVersion >= 532.0) { + // Safari changed the scrolling factor to match IE (for details see + // https://bugs.webkit.org/show_bug.cgi?id=24368). The WebKit version where this + // change was introduced was 532.0 + // Detailed discussion: + // https://bugs.webkit.org/show_bug.cgi?id=29601 + // http://trac.webkit.org/browser/trunk/WebKit/chromium/src/mac/WebInputEventFactory.mm#L1063 + scale = 120; + } else { + // MS optical wheel mouse produces multiples of 12 which is close enough + // to help tame the speed of the continuous mice... + scale = 12; + } + + // Momentum scrolling produces very fast scrolling, so increase the scale factor + // to help produce similar results cross platform. This could be even larger and + // it would help those mice, but other mice would become almost unusable as a + // result (since we cannot tell which device type is in use). + scale *= 3; + } else { + // IE, Opera and other Windows browsers use 120. + scale = 120; + } + + return scale; + }()), + + /** + * Simple click regex + * @private + */ + clickRe: /(dbl)?click/, + // 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, don't see any way to feature detect this. + btnMap: Ext.isIE ? { + 1: 0, + 4: 1, + 2: 2 + } : { + 0: 0, + 1: 1, + 2: 2 + }, + + /** + * @property {Boolean} ctrlKey + * True if the control key was down during the event. + * In Mac this will also be true when meta key was down. + */ + /** + * @property {Boolean} altKey + * True if the alt key was down during the event. + */ + /** + * @property {Boolean} shiftKey + * True if the shift key was down during the event. + */ + + constructor: function(event, freezeEvent){ + if (event) { + this.setEvent(event.browserEvent || event, freezeEvent); + } + }, + + setEvent: function(event, freezeEvent){ + var me = this, button, options; + + if (event == me || (event && event.browserEvent)) { // already wrapped + return event; + } + me.browserEvent = event; + if (event) { + // normalize buttons + button = event.button ? me.btnMap[event.button] : (event.which ? event.which - 1 : -1); + if (me.clickRe.test(event.type) && button == -1) { + button = 0; + } + options = { + type: event.type, + button: button, + shiftKey: event.shiftKey, + // mac metaKey behaves like ctrlKey + ctrlKey: event.ctrlKey || event.metaKey || false, + altKey: event.altKey, + // in getKey these will be normalized for the mac + keyCode: event.keyCode, + charCode: event.charCode, + // cache the targets for the delayed and or buffered events + target: Ext.EventManager.getTarget(event), + relatedTarget: Ext.EventManager.getRelatedTarget(event), + currentTarget: event.currentTarget, + xy: (freezeEvent ? me.getXY() : null) + }; + } else { + options = { + button: -1, + shiftKey: false, + ctrlKey: false, + altKey: false, + keyCode: 0, + charCode: 0, + target: null, + xy: [0, 0] + }; + } + Ext.apply(me, options); + return me; + }, + + /** + * Stop the event (preventDefault and stopPropagation) + */ + stopEvent: function(){ + this.stopPropagation(); + this.preventDefault(); + }, + + /** + * Prevents the browsers default handling of the event. + */ + preventDefault: function(){ + if (this.browserEvent) { + Ext.EventManager.preventDefault(this.browserEvent); + } + }, + + /** + * Cancels bubbling of the event. + */ + stopPropagation: function(){ + var browserEvent = this.browserEvent; + + if (browserEvent) { + if (browserEvent.type == 'mousedown') { + Ext.EventManager.stoppedMouseDownEvent.fire(this); + } + Ext.EventManager.stopPropagation(browserEvent); + } + }, + + /** + * Gets the character code for the event. + * @return {Number} + */ + getCharCode: function(){ + return this.charCode || this.keyCode; + }, + + /** + * Returns a normalized keyCode for the event. + * @return {Number} The key code + */ + getKey: function(){ + return this.normalizeKey(this.keyCode || this.charCode); + }, + + /** + * Normalize key codes across browsers + * @private + * @param {Number} key The key code + * @return {Number} The normalized code + */ + normalizeKey: function(key){ + // can't feature detect this + return Ext.isWebKit ? (this.safariKeys[key] || key) : key; + }, + + /** + * Gets the x coordinate of the event. + * @return {Number} + * @deprecated 4.0 Replaced by {@link #getX} + */ + getPageX: function(){ + return this.getX(); + }, + + /** + * Gets the y coordinate of the event. + * @return {Number} + * @deprecated 4.0 Replaced by {@link #getY} + */ + getPageY: function(){ + return this.getY(); + }, + + /** + * Gets the x coordinate of the event. + * @return {Number} + */ + getX: function() { + return this.getXY()[0]; + }, + + /** + * Gets the y coordinate of the event. + * @return {Number} + */ + getY: function() { + return this.getXY()[1]; + }, + + /** + * Gets the page coordinates of the event. + * @return {Number[]} The xy values like [x, y] + */ + getXY: function() { + if (!this.xy) { + // same for XY + this.xy = Ext.EventManager.getPageXY(this.browserEvent); + } + return this.xy; + }, + + /** + * Gets the target for the event. + * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target + * @param {Number/HTMLElement} 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){ + if (selector) { + return Ext.fly(this.target).findParent(selector, maxDepth, returnEl); + } + return returnEl ? Ext.get(this.target) : this.target; + }, + + /** + * Gets the related target. + * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target + * @param {Number/HTMLElement} 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} + */ + getRelatedTarget : function(selector, maxDepth, returnEl){ + if (selector) { + return Ext.fly(this.relatedTarget).findParent(selector, maxDepth, returnEl); + } + return returnEl ? Ext.get(this.relatedTarget) : this.relatedTarget; + }, + + /** + * Correctly scales a given wheel delta. + * @param {Number} delta The delta value. + */ + correctWheelDelta : function (delta) { + var scale = this.WHEEL_SCALE, + ret = Math.round(delta / scale); + + if (!ret && delta) { + ret = (delta < 0) ? -1 : 1; // don't allow non-zero deltas to go to zero! + } + + return ret; + }, + + /** + * Returns the mouse wheel deltas for this event. + * @return {Object} An object with "x" and "y" properties holding the mouse wheel deltas. + */ + getWheelDeltas : function () { + var me = this, + event = me.browserEvent, + dx = 0, dy = 0; // the deltas + + if (Ext.isDefined(event.wheelDeltaX)) { // WebKit has both dimensions + dx = event.wheelDeltaX; + dy = event.wheelDeltaY; + } else if (event.wheelDelta) { // old WebKit and IE + dy = event.wheelDelta; + } else if (event.detail) { // Gecko + dy = -event.detail; // gecko is backwards + + // Gecko sometimes returns really big values if the user changes settings to + // scroll a whole page per scroll + if (dy > 100) { + dy = 3; + } else if (dy < -100) { + dy = -3; + } + + // Firefox 3.1 adds an axis field to the event to indicate direction of + // scroll. See https://developer.mozilla.org/en/Gecko-Specific_DOM_Events + if (Ext.isDefined(event.axis) && event.axis === event.HORIZONTAL_AXIS) { + dx = dy; + dy = 0; + } + } + + return { + x: me.correctWheelDelta(dx), + y: me.correctWheelDelta(dy) + }; + }, + + /** + * Normalizes mouse wheel y-delta across browsers. To get x-delta information, use + * {@link #getWheelDeltas} instead. + * @return {Number} The mouse wheel y-delta + */ + getWheelDelta : function(){ + var deltas = this.getWheelDeltas(); + + return deltas.y; + }, + + /** + * 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!');
    +    }
    +});
    +
    +// 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!');
    +    }
    +});
    +
    + * @param {String/HTMLElement/Ext.Element} 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 = related ? this.getRelatedTarget() : this.getTarget(), + result; + + if (t) { + result = Ext.fly(el).contains(t); + if (!result && allowEl) { + result = t == Ext.getDom(el); + } + return result; + } + } + return false; + }, + + /** + * Checks if the key pressed was a "navigation" key + * @return {Boolean} True if the press is a navigation keypress + */ + 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; + }, + + /** + * Checks if the key pressed was a "special" key + * @return {Boolean} True if the press is a special keypress + */ + isSpecialKey : function(){ + var k = this.normalizeKey(this.keyCode); + return (this.type == 'keypress' && this.ctrlKey) || + this.isNavKeyPress() || + (k == this.BACKSPACE) || // Backspace + (k >= 16 && k <= 20) || // Shift, Ctrl, Alt, Pause, Caps Lock + (k >= 44 && k <= 46); // Print Screen, Insert, Delete + }, + + /** + * Returns a point object that consists of the object coordinates. + * @return {Ext.util.Point} point + */ + getPoint : function(){ + var xy = this.getXY(); + return new Ext.util.Point(xy[0], 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 || this.metaKey; + }, + + /** + * Injects a DOM event using the data in this object and (optionally) a new target. + * This is a low-level technique and not likely to be used by application code. The + * currently supported event types are: + *

    HTMLEvents

    + *
      + *
    • load
    • + *
    • unload
    • + *
    • select
    • + *
    • change
    • + *
    • submit
    • + *
    • reset
    • + *
    • resize
    • + *
    • scroll
    • + *
    + *

    MouseEvents

    + *
      + *
    • click
    • + *
    • dblclick
    • + *
    • mousedown
    • + *
    • mouseup
    • + *
    • mouseover
    • + *
    • mousemove
    • + *
    • mouseout
    • + *
    + *

    UIEvents

    + *
      + *
    • focusin
    • + *
    • focusout
    • + *
    • activate
    • + *
    • focus
    • + *
    • blur
    • + *
    + * @param {Ext.Element/HTMLElement} target (optional) If specified, the target for the event. This + * is likely to be used when relaying a DOM event. If not specified, {@link #getTarget} + * is used to determine the target. + */ + injectEvent: (function () { + var API, + dispatchers = {}, // keyed by event type (e.g., 'mousedown') + crazyIEButtons; + + // Good reference: http://developer.yahoo.com/yui/docs/UserAction.js.html + + // IE9 has createEvent, but this code causes major problems with htmleditor (it + // blocks all mouse events and maybe more). TODO + + if (!Ext.isIE && document.createEvent) { // if (DOM compliant) + API = { + createHtmlEvent: function (doc, type, bubbles, cancelable) { + var event = doc.createEvent('HTMLEvents'); + + event.initEvent(type, bubbles, cancelable); + return event; + }, + + createMouseEvent: function (doc, type, bubbles, cancelable, detail, + clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, + button, relatedTarget) { + var event = doc.createEvent('MouseEvents'), + view = doc.defaultView || window; + + if (event.initMouseEvent) { + event.initMouseEvent(type, bubbles, cancelable, view, detail, + clientX, clientY, clientX, clientY, ctrlKey, altKey, + shiftKey, metaKey, button, relatedTarget); + } else { // old Safari + event = doc.createEvent('UIEvents'); + event.initEvent(type, bubbles, cancelable); + event.view = view; + event.detail = detail; + event.screenX = clientX; + event.screenY = clientY; + event.clientX = clientX; + event.clientY = clientY; + event.ctrlKey = ctrlKey; + event.altKey = altKey; + event.metaKey = metaKey; + event.shiftKey = shiftKey; + event.button = button; + event.relatedTarget = relatedTarget; + } + + return event; + }, + + createUIEvent: function (doc, type, bubbles, cancelable, detail) { + var event = doc.createEvent('UIEvents'), + view = doc.defaultView || window; + + event.initUIEvent(type, bubbles, cancelable, view, detail); + return event; + }, + + fireEvent: function (target, type, event) { + target.dispatchEvent(event); + }, + + fixTarget: function (target) { + // Safari3 doesn't have window.dispatchEvent() + if (target == window && !target.dispatchEvent) { + return document; + } + + return target; + } + }; + } else if (document.createEventObject) { // else if (IE) + crazyIEButtons = { 0: 1, 1: 4, 2: 2 }; + + API = { + createHtmlEvent: function (doc, type, bubbles, cancelable) { + var event = doc.createEventObject(); + event.bubbles = bubbles; + event.cancelable = cancelable; + return event; + }, + + createMouseEvent: function (doc, type, bubbles, cancelable, detail, + clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, + button, relatedTarget) { + var event = doc.createEventObject(); + event.bubbles = bubbles; + event.cancelable = cancelable; + event.detail = detail; + event.screenX = clientX; + event.screenY = clientY; + event.clientX = clientX; + event.clientY = clientY; + event.ctrlKey = ctrlKey; + event.altKey = altKey; + event.shiftKey = shiftKey; + event.metaKey = metaKey; + event.button = crazyIEButtons[button] || button; + event.relatedTarget = relatedTarget; // cannot assign to/fromElement + return event; + }, + + createUIEvent: function (doc, type, bubbles, cancelable, detail) { + var event = doc.createEventObject(); + event.bubbles = bubbles; + event.cancelable = cancelable; + return event; + }, + + fireEvent: function (target, type, event) { + target.fireEvent('on' + type, event); + }, + + fixTarget: function (target) { + if (target == document) { + // IE6,IE7 thinks window==document and doesn't have window.fireEvent() + // IE6,IE7 cannot properly call document.fireEvent() + return document.documentElement; + } + + return target; + } + }; + } + + //---------------- + // HTMLEvents + + Ext.Object.each({ + load: [false, false], + unload: [false, false], + select: [true, false], + change: [true, false], + submit: [true, true], + reset: [true, false], + resize: [true, false], + scroll: [true, false] + }, + function (name, value) { + var bubbles = value[0], cancelable = value[1]; + dispatchers[name] = function (targetEl, srcEvent) { + var e = API.createHtmlEvent(name, bubbles, cancelable); + API.fireEvent(targetEl, name, e); + }; + }); + + //---------------- + // MouseEvents + + function createMouseEventDispatcher (type, detail) { + var cancelable = (type != 'mousemove'); + return function (targetEl, srcEvent) { + var xy = srcEvent.getXY(), + e = API.createMouseEvent(targetEl.ownerDocument, type, true, cancelable, + detail, xy[0], xy[1], srcEvent.ctrlKey, srcEvent.altKey, + srcEvent.shiftKey, srcEvent.metaKey, srcEvent.button, + srcEvent.relatedTarget); + API.fireEvent(targetEl, type, e); + }; + } + + Ext.each(['click', 'dblclick', 'mousedown', 'mouseup', 'mouseover', 'mousemove', 'mouseout'], + function (eventName) { + dispatchers[eventName] = createMouseEventDispatcher(eventName, 1); + }); + + //---------------- + // UIEvents + + Ext.Object.each({ + focusin: [true, false], + focusout: [true, false], + activate: [true, true], + focus: [false, false], + blur: [false, false] + }, + function (name, value) { + var bubbles = value[0], cancelable = value[1]; + dispatchers[name] = function (targetEl, srcEvent) { + var e = API.createUIEvent(targetEl.ownerDocument, name, bubbles, cancelable, 1); + API.fireEvent(targetEl, name, e); + }; + }); + + //--------- + if (!API) { + // not even sure what ancient browsers fall into this category... + + dispatchers = {}; // never mind all those we just built :P + + API = { + fixTarget: function (t) { + return t; + } + }; + } + + function cannotInject (target, srcEvent) { + // TODO log something + } + + return function (target) { + var me = this, + dispatcher = dispatchers[me.type] || cannotInject, + t = target ? (target.dom || target) : me.getTarget(); + + t = API.fixTarget(t); + dispatcher(t, me); + }; + }()) // call to produce method + +}, function() { + +Ext.EventObject = new Ext.EventObjectImpl(); + +}); + + +/** + * @class Ext.dom.AbstractQuery + * @private + */ +Ext.define('Ext.dom.AbstractQuery', { + /** + * Selects a group of elements. + * @param {String} selector The selector/xpath query (can be a comma separated list of selectors) + * @param {HTMLElement/String} [root] The start of the query (defaults to document). + * @return {HTMLElement[]} An Array of DOM elements which match the selector. If there are + * no matches, and empty Array is returned. + */ + select: function(q, root) { + var results = [], + nodes, + i, + j, + qlen, + nlen; + + root = root || document; + + if (typeof root == 'string') { + root = document.getElementById(root); + } + + q = q.split(","); + + for (i = 0,qlen = q.length; i < qlen; i++) { + if (typeof q[i] == 'string') { + + //support for node attribute selection + if (typeof q[i][0] == '@') { + nodes = root.getAttributeNode(q[i].substring(1)); + results.push(nodes); + } else { + nodes = root.querySelectorAll(q[i]); + + for (j = 0,nlen = nodes.length; j < nlen; j++) { + results.push(nodes[j]); + } + } + } + } + + return results; + }, + + /** + * Selects a single element. + * @param {String} selector The selector/xpath query + * @param {HTMLElement/String} [root] The start of the query (defaults to document). + * @return {HTMLElement} The DOM element which matched the selector. + */ + selectNode: function(q, root) { + return this.select(q, root)[0]; + }, + + /** + * 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, q) { + if (typeof el == "string") { + el = document.getElementById(el); + } + return this.select(q).indexOf(el) !== -1; + } + +}); + +/** + * @class Ext.dom.AbstractHelper + * @private + * Abstract base class for {@link Ext.dom.Helper}. + * @private + */ +Ext.define('Ext.dom.AbstractHelper', { + emptyTags : /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i, + confRe : /tag|children|cn|html|tpl|tplData$/i, + endRe : /end/i, + + attribXlat: { cls : 'class', htmlFor : 'for' }, + + closeTags: {}, + + decamelizeName : (function () { + var camelCaseRe = /([a-z])([A-Z])/g, + cache = {}; + + function decamel (match, p1, p2) { + return p1 + '-' + p2.toLowerCase(); + } + + return function (s) { + return cache[s] || (cache[s] = s.replace(camelCaseRe, decamel)); + }; + }()), + + generateMarkup: function(spec, buffer) { + var me = this, + attr, val, tag, i, closeTags; + + if (typeof spec == "string") { + buffer.push(spec); + } else if (Ext.isArray(spec)) { + for (i = 0; i < spec.length; i++) { + if (spec[i]) { + me.generateMarkup(spec[i], buffer); + } + } + } else { + tag = spec.tag || 'div'; + buffer.push('<', tag); + + for (attr in spec) { + if (spec.hasOwnProperty(attr)) { + val = spec[attr]; + if (!me.confRe.test(attr)) { + if (typeof val == "object") { + buffer.push(' ', attr, '="'); + me.generateStyles(val, buffer).push('"'); + } else { + buffer.push(' ', me.attribXlat[attr] || attr, '="', val, '"'); + } + } + } + } + + // Now either just close the tag or try to add children and close the tag. + if (me.emptyTags.test(tag)) { + buffer.push('/>'); + } else { + buffer.push('>'); + + // Apply the tpl html, and cn specifications + if ((val = spec.tpl)) { + val.applyOut(spec.tplData, buffer); + } + if ((val = spec.html)) { + buffer.push(val); + } + if ((val = spec.cn || spec.children)) { + me.generateMarkup(val, buffer); + } + + // we generate a lot of close tags, so cache them rather than push 3 parts + closeTags = me.closeTags; + buffer.push(closeTags[tag] || (closeTags[tag] = '')); + } + } + + return buffer; + }, + + /** + * Converts the styles from the given object to text. The styles are CSS style names + * with their associated value. + * + * The basic form of this method returns a string: + * + * var s = Ext.DomHelper.generateStyles({ + * backgroundColor: 'red' + * }); + * + * // s = 'background-color:red;' + * + * Alternatively, this method can append to an output array. + * + * var buf = []; + * + * ... + * + * Ext.DomHelper.generateStyles({ + * backgroundColor: 'red' + * }, buf); + * + * In this case, the style text is pushed on to the array and the array is returned. + * + * @param {Object} styles The object describing the styles. + * @param {String[]} [buffer] The output buffer. + * @return {String/String[]} If buffer is passed, it is returned. Otherwise the style + * string is returned. + */ + generateStyles: function (styles, buffer) { + var a = buffer || [], + name; + + for (name in styles) { + if (styles.hasOwnProperty(name)) { + a.push(this.decamelizeName(name), ':', styles[name], ';'); + } + } + + return buffer || a.join(''); + }, + + /** + * Returns the markup for the passed Element(s) config. + * @param {Object} spec The DOM object spec (and children) + * @return {String} + */ + markup: function(spec) { + if (typeof spec == "string") { + return spec; + } + + var buf = this.generateMarkup(spec, []); + return buf.join(''); + }, + + /** + * 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 (typeof styles == 'function') { + styles = styles.call(); + } + if (typeof styles == 'string'){ + styles = Ext.util.Format.trim(styles).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. + * + * For example take the following HTML: `
    Contents
    ` + * + * Using different `where` values inserts element to the following places: + * + * - beforeBegin: `
    Contents
    ` + * - afterBegin: `
    Contents
    ` + * - beforeEnd: `
    Contents
    ` + * - afterEnd: `
    Contents
    ` + * + * @param {HTMLElement/TextNode} 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']; + + range = el.ownerDocument.createRange(); + setStart = 'setStart' + (this.endRe.test(where) ? 'After' : 'Before'); + if (hash[where]) { + range[setStart](el); + frag = range.createContextualFragment(html); + el.parentNode.insertBefore(frag, where == 'beforebegin' ? el : el.nextSibling); + return el[(where == 'beforebegin' ? 'previous' : 'next') + 'Sibling']; + } + else { + rangeEl = (where == 'afterbegin' ? 'first' : 'last') + 'Child'; + if (el.firstChild) { + range[setStart](el[rangeEl]); + frag = range.createContextualFragment(html); + if (where == 'afterbegin') { + el.insertBefore(frag, el.firstChild); + } + else { + el.appendChild(frag); + } + } + else { + el.innerHTML = html; + } + return el[rangeEl]; + } + + throw 'Illegal insertion point -> "' + where + '"'; + }, + + /** + * Creates new DOM element(s) and inserts them before el. + * @param {String/HTMLElement/Ext.Element} el The context element + * @param {Object/String} o The DOM object spec (and children) or raw HTML blob + * @param {Boolean} [returnElement] true to return a Ext.Element + * @return {HTMLElement/Ext.Element} The new node + */ + insertBefore: function(el, o, returnElement) { + return this.doInsert(el, o, returnElement, 'beforebegin'); + }, + + /** + * Creates new DOM element(s) and inserts them after el. + * @param {String/HTMLElement/Ext.Element} el The context element + * @param {Object} o The DOM object spec (and children) + * @param {Boolean} [returnElement] true to return a Ext.Element + * @return {HTMLElement/Ext.Element} The new node + */ + insertAfter: function(el, o, returnElement) { + return this.doInsert(el, o, returnElement, 'afterend', 'nextSibling'); + }, + + /** + * Creates new DOM element(s) and inserts them as the first child of el. + * @param {String/HTMLElement/Ext.Element} el The context element + * @param {Object/String} o The DOM object spec (and children) or raw HTML blob + * @param {Boolean} [returnElement] true to return a Ext.Element + * @return {HTMLElement/Ext.Element} The new node + */ + insertFirst: function(el, o, returnElement) { + return this.doInsert(el, o, returnElement, 'afterbegin', 'firstChild'); + }, + + /** + * Creates new DOM element(s) and appends them to el. + * @param {String/HTMLElement/Ext.Element} el The context element + * @param {Object/String} o The DOM object spec (and children) or raw HTML blob + * @param {Boolean} [returnElement] true to return a Ext.Element + * @return {HTMLElement/Ext.Element} The new node + */ + append: function(el, o, returnElement) { + return this.doInsert(el, o, returnElement, 'beforeend', '', true); + }, + + /** + * Creates new DOM element(s) and overwrites the contents of el with them. + * @param {String/HTMLElement/Ext.Element} el The context element + * @param {Object/String} o The DOM object spec (and children) or raw HTML blob + * @param {Boolean} [returnElement] true to return a Ext.Element + * @return {HTMLElement/Ext.Element} The new node + */ + overwrite: function(el, o, returnElement) { + el = Ext.getDom(el); + el.innerHTML = this.markup(o); + return returnElement ? Ext.get(el.firstChild) : el.firstChild; + }, + + doInsert: function(el, o, returnElement, pos, sibling, append) { + var newNode = this.insertHtml(pos, Ext.getDom(el), this.markup(o)); + return returnElement ? Ext.get(newNode, true) : newNode; + } + +}); + +/** + * @class Ext.dom.AbstractElement + * @extend Ext.Base + * @private + */ +(function() { + +var document = window.document, + trimRe = /^\s+|\s+$/g, + whitespaceRe = /\s/; + +if (!Ext.cache){ + Ext.cache = {}; +} + +Ext.define('Ext.dom.AbstractElement', { + + inheritableStatics: { + + /** + * Retrieves Ext.dom.Element objects. {@link Ext#get} is alias for {@link Ext.dom.Element#get}. + * + * **This method does not retrieve {@link Ext.Component Component}s.** This method retrieves Ext.dom.Element + * objects which encapsulate DOM elements. To retrieve a Component by its ID, use {@link Ext.ComponentManager#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 {String/HTMLElement/Ext.Element} el The id of the node, a DOM Node or an existing Element. + * @return {Ext.dom.Element} The Element object (or null if no matching element was found) + * @static + * @inheritable + */ + get: function(el) { + var me = this, + El = Ext.dom.Element, + cache, + extEl, + dom, + id; + + if (!el) { + return null; + } + + if (typeof el == "string") { // element id + if (el == Ext.windowId) { + return El.get(window); + } else if (el == Ext.documentId) { + return El.get(document); + } + + cache = Ext.cache[el]; + // This code is here to catch the case where we've got a reference to a document of an iframe + // It getElementById will fail because it's not part of the document, so if we're skipping + // GC it means it's a window/document object that isn't the default window/document, which we have + // already handled above + if (cache && cache.skipGarbageCollection) { + extEl = cache.el; + return extEl; + } + + if (!(dom = document.getElementById(el))) { + return null; + } + + if (cache && cache.el) { + extEl = cache.el; + extEl.dom = dom; + } else { + // Force new element if there's a cache but no el attached + extEl = new El(dom, !!cache); + } + return extEl; + } else if (el.tagName) { // dom element + if (!(id = el.id)) { + id = Ext.id(el); + } + cache = Ext.cache[id]; + if (cache && cache.el) { + extEl = Ext.cache[id].el; + extEl.dom = el; + } else { + // Force new element if there's a cache but no el attached + extEl = new El(el, !!cache); + } + return extEl; + } else if (el instanceof me) { + if (el != me.docEl && el != me.winEl) { + // refresh dom element in case no longer valid, + // catch case where it hasn't been appended + el.dom = document.getElementById(el.id) || el.dom; + } + return el; + } else if (el.isComposite) { + return el; + } else if (Ext.isArray(el)) { + return me.select(el); + } else if (el === document) { + // create a bogus element object representing the document object + if (!me.docEl) { + me.docEl = Ext.Object.chain(El.prototype); + me.docEl.dom = document; + me.docEl.id = Ext.id(document); + me.addToCache(me.docEl); + } + return me.docEl; + } else if (el === window) { + if (!me.winEl) { + me.winEl = Ext.Object.chain(El.prototype); + me.winEl.dom = window; + me.winEl.id = Ext.id(window); + me.addToCache(me.winEl); + } + return me.winEl; + } + return null; + }, + + addToCache: function(el, id) { + if (el) { + Ext.addCacheEntry(id, el); + } + return el; + }, + + addMethods: function() { + this.override.apply(this, arguments); + }, + + /** + *

    Returns an array of unique class names based upon the input strings, or string arrays.

    + *

    The number of parameters is unlimited.

    + *

    Example

    +// Add x-invalid and x-mandatory classes, do not duplicate
    +myElement.dom.className = Ext.core.Element.mergeClsList(this.initialClasses, 'x-invalid x-mandatory');
    +
    + * @param {Mixed} clsList1 A string of class names, or an array of class names. + * @param {Mixed} clsList2 A string of class names, or an array of class names. + * @return {Array} An array of strings representing remaining unique, merged class names. If class names were added to the first list, the changed property will be true. + * @static + * @inheritable + */ + mergeClsList: function() { + var clsList, clsHash = {}, + i, length, j, listLength, clsName, result = [], + changed = false; + + for (i = 0, length = arguments.length; i < length; i++) { + clsList = arguments[i]; + if (Ext.isString(clsList)) { + clsList = clsList.replace(trimRe, '').split(whitespaceRe); + } + if (clsList) { + for (j = 0, listLength = clsList.length; j < listLength; j++) { + clsName = clsList[j]; + if (!clsHash[clsName]) { + if (i) { + changed = true; + } + clsHash[clsName] = true; + } + } + } + } + + for (clsName in clsHash) { + result.push(clsName); + } + result.changed = changed; + return result; + }, + + /** + *

    Returns an array of unique class names deom the first parameter with all class names + * from the second parameter removed.

    + *

    Example

    +// Remove x-invalid and x-mandatory classes if present.
    +myElement.dom.className = Ext.core.Element.removeCls(this.initialClasses, 'x-invalid x-mandatory');
    +
    + * @param {Mixed} existingClsList A string of class names, or an array of class names. + * @param {Mixed} removeClsList A string of class names, or an array of class names to remove from existingClsList. + * @return {Array} An array of strings representing remaining class names. If class names were removed, the changed property will be true. + * @static + * @inheritable + */ + removeCls: function(existingClsList, removeClsList) { + var clsHash = {}, + i, length, clsName, result = [], + changed = false; + + if (existingClsList) { + if (Ext.isString(existingClsList)) { + existingClsList = existingClsList.replace(trimRe, '').split(whitespaceRe); + } + for (i = 0, length = existingClsList.length; i < length; i++) { + clsHash[existingClsList[i]] = true; + } + } + if (removeClsList) { + if (Ext.isString(removeClsList)) { + removeClsList = removeClsList.split(whitespaceRe); + } + for (i = 0, length = removeClsList.length; i < length; i++) { + clsName = removeClsList[i]; + if (clsHash[clsName]) { + changed = true; + delete clsHash[clsName]; + } + } + } + for (clsName in clsHash) { + result.push(clsName); + } + result.changed = changed; + return result; + }, + + /** + * @property + * Visibility mode constant for use with {@link Ext.dom.Element#setVisibilityMode}. + * Use the CSS 'visibility' property to hide the element. + * + * Note that in this mode, {@link #isVisible} may return true for an element even though + * it actually has a parent element that is hidden. For this reason, and in most cases, + * using the {@link #OFFSETS} mode is a better choice. + * @static + * @inheritable + */ + VISIBILITY: 1, + + /** + * @property + * Visibility mode constant for use with {@link Ext.dom.Element#setVisibilityMode}. + * Use the CSS 'display' property to hide the element. + * @static + * @inheritable + */ + DISPLAY: 2, + + /** + * @property + * Visibility mode constant for use with {@link Ext.dom.Element#setVisibilityMode}. + * Use CSS absolute positioning and top/left offsets to hide the element. + * @static + * @inheritable + */ + OFFSETS: 3, + + /** + * @property + * Visibility mode constant for use with {@link Ext.dom.Element#setVisibilityMode}. + * Add or remove the {@link Ext.Layer#visibilityCls} class to hide the element. + * @static + * @inheritable + */ + ASCLASS: 4 + }, + + constructor: function(element, forceNew) { + var me = this, + dom = typeof element == 'string' + ? document.getElementById(element) + : element, + id; + + if (!dom) { + return null; + } + + id = dom.id; + if (!forceNew && id && Ext.cache[id]) { + // element object already exists + return Ext.cache[id].el; + } + + /** + * @property {HTMLElement} dom + * The DOM element + */ + me.dom = dom; + + /** + * @property {String} id + * The DOM element ID + */ + me.id = id || Ext.id(dom); + + me.self.addToCache(me); + }, + + /** + * 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=true] false to override the default setAttribute to use expandos. + * @return {Ext.dom.Element} this + */ + set: function(o, useSet) { + var el = this.dom, + attr, + value; + + for (attr in o) { + if (o.hasOwnProperty(attr)) { + value = o[attr]; + if (attr == 'style') { + this.applyStyles(value); + } + else if (attr == 'cls') { + el.className = value; + } + else if (useSet !== false) { + if (value === undefined) { + el.removeAttribute(attr); + } else { + el.setAttribute(attr, value); + } + } + else { + el[attr] = value; + } + } + } + return this; + }, + + /** + * @property {String} defaultUnit + * The default unit to append to CSS values where a unit isn't provided. + */ + 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); + }, + + /** + * 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; + }, + + /** + * Removes this element's dom reference. Note that event and cache removal is handled at {@link Ext#removeNode + * Ext.removeNode} + */ + remove: function() { + var me = this, + dom = me.dom; + + if (dom) { + Ext.removeNode(dom); + delete me.dom; + } + }, + + /** + * 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) { + if (!el) { + return false; + } + + var me = this, + dom = el.dom || el; + + // we need el-contains-itself logic here because isAncestor does not do that: + return (dom === me.dom) || Ext.dom.AbstractElement.isAncestor(me.dom, dom); + }, + + /** + * Returns the value of an attribute from the element's underlying DOM node. + * @param {String} name The attribute name + * @param {String} [namespace] The namespace in which to look for the attribute + * @return {String} The attribute value + */ + getAttribute: function(name, ns) { + var dom = this.dom; + return dom.getAttributeNS(ns, name) || dom.getAttribute(ns + ":" + name) || dom.getAttribute(name) || dom[name]; + }, + + /** + * Update the innerHTML of this element + * @param {String} html The new HTML + * @return {Ext.dom.Element} this + */ + update: function(html) { + if (this.dom) { + this.dom.innerHTML = html; + } + return this; + }, + + + /** + * Set the innerHTML of this element + * @param {String} html The new HTML + * @return {Ext.Element} this + */ + setHTML: function(html) { + if(this.dom) { + this.dom.innerHTML = html; + } + return this; + }, + + /** + * Returns the innerHTML of an Element or an empty string if the element's + * dom no longer exists. + */ + getHTML: function() { + return this.dom ? this.dom.innerHTML : ''; + }, + + /** + * 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() { + this.setVisible(false); + 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() { + this.setVisible(true); + return this; + }, + + /** + * 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, + statics = me.self, + mode = me.getVisibilityMode(), + prefix = Ext.baseCSSPrefix; + + switch (mode) { + case statics.VISIBILITY: + me.removeCls([prefix + 'hidden-display', prefix + 'hidden-offsets']); + me[visible ? 'removeCls' : 'addCls'](prefix + 'hidden-visibility'); + break; + + case statics.DISPLAY: + me.removeCls([prefix + 'hidden-visibility', prefix + 'hidden-offsets']); + me[visible ? 'removeCls' : 'addCls'](prefix + 'hidden-display'); + break; + + case statics.OFFSETS: + me.removeCls([prefix + 'hidden-visibility', prefix + 'hidden-display']); + me[visible ? 'removeCls' : 'addCls'](prefix + 'hidden-offsets'); + break; + } + + return me; + }, + + getVisibilityMode: function() { + // Only flyweights won't have a $cache object, by calling getCache the cache + // will be created for future accesses. As such, we're eliminating the method + // call since it's mostly redundant + var data = (this.$cache || this.getCache()).data, + visMode = data.visibilityMode; + + if (visMode === undefined) { + data.visibilityMode = visMode = this.self.DISPLAY; + } + + return visMode; + }, + + /** + * Use this to change the visibility mode between {@link #VISIBILITY}, {@link #DISPLAY}, {@link #OFFSETS} or {@link #ASCLASS}. + */ + setVisibilityMode: function(mode) { + (this.$cache || this.getCache()).data.visibilityMode = mode; + return this; + }, + + getCache: function() { + var me = this, + id = me.dom.id || Ext.id(me.dom); + + // Note that we do not assign an ID to the calling object here. + // An Ext.dom.Element will have one assigned at construction, and an Ext.dom.AbstractElement.Fly must not have one. + // We assign an ID to the DOM element if it does not have one. + me.$cache = Ext.cache[id] || Ext.addCacheEntry(id, null, me.dom); + + return me.$cache; + } + +}, function() { + var AbstractElement = this; + + Ext.getDetachedBody = function () { + var detachedEl = AbstractElement.detachedBodyEl; + + if (!detachedEl) { + detachedEl = document.createElement('div'); + AbstractElement.detachedBodyEl = detachedEl = new AbstractElement.Fly(detachedEl); + detachedEl.isDetachedBody = true; + } + + return detachedEl; + }; + + Ext.getElementById = function (id) { + var el = document.getElementById(id), + detachedBodyEl; + + if (!el && (detachedBodyEl = AbstractElement.detachedBodyEl)) { + el = detachedBodyEl.dom.querySelector('#' + Ext.escapeId(id)); + } + + return el; + }; + + /** + * @member Ext + * @method get + * @inheritdoc Ext.dom.Element#get + */ + Ext.get = function(el) { + return Ext.dom.Element.get(el); + }; + + this.addStatics({ + /** + * @class Ext.dom.AbstractElement.Fly + * @extends Ext.dom.AbstractElement + * + * A non-persistent wrapper for a DOM element which may be used to execute methods of {@link Ext.dom.Element} + * upon a DOM element without creating an instance of {@link Ext.dom.Element}. + * + * A **singleton** instance of this class is returned when you use {@link Ext#fly} + * + * Because it is a singleton, this Flyweight does not have an ID, and must be used and discarded in a single line. + * You should not keep and use the reference to this singleton over multiple lines because methods that you call + * may themselves make use of {@link Ext#fly} and may change the DOM element to which the instance refers. + */ + Fly: new Ext.Class({ + extend: AbstractElement, + + /** + * @property {Boolean} isFly + * This is `true` to identify Element flyweights + */ + isFly: true, + + constructor: function(dom) { + this.dom = dom; + }, + + /** + * @private + * Attach this fliyweight instance to the passed DOM element. + * + * Note that a flightweight does **not** have an ID, and does not acquire the ID of the DOM element. + */ + attach: function (dom) { + + // Attach to the passed DOM element. The same code as in Ext.Fly + this.dom = dom; + // Use cached data if there is existing cached data for the referenced DOM element, + // otherwise it will be created when needed by getCache. + this.$cache = dom.id ? Ext.cache[dom.id] : null; + return this; + } + }), + + _flyweights: {}, + + /** + * Gets the singleton {@link Ext.dom.AbstractElement.Fly flyweight} element, with the passed node as the active element. + * + * Because it is a singleton, this Flyweight does not have an ID, and must be used and discarded in a single line. + * You may not keep and use the reference to this singleton over multiple lines because methods that you call + * may themselves make use of {@link Ext#fly} and may change the DOM element to which the instance refers. + * + * {@link Ext#fly} is alias for {@link Ext.dom.AbstractElement#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 Ext.get} will be more appropriate to take advantage of the caching provided by the Ext.dom.Element + * class. + * + * @param {String/HTMLElement} dom The dom node or id + * @param {String} [named] Allows for creation of named reusable flyweights to prevent conflicts (e.g. + * internally Ext uses "_global") + * @return {Ext.dom.AbstractElement.Fly} The singleton flyweight object (or null if no matching element was found) + * @static + * @member Ext.dom.AbstractElement + */ + fly: function(dom, named) { + var fly = null, + _flyweights = AbstractElement._flyweights; + + named = named || '_global'; + + dom = Ext.getDom(dom); + + if (dom) { + fly = _flyweights[named] || (_flyweights[named] = new AbstractElement.Fly()); + + // Attach to the passed DOM element. + // This code performs the same function as Fly.attach, but inline it for efficiency + fly.dom = dom; + // Use cached data if there is existing cached data for the referenced DOM element, + // otherwise it will be created when needed by getCache. + fly.$cache = dom.id ? Ext.cache[dom.id] : null; + } + return fly; + } + }); + + /** + * @member Ext + * @method fly + * @inheritdoc Ext.dom.AbstractElement#fly + */ + Ext.fly = function() { + return AbstractElement.fly.apply(AbstractElement, arguments); + }; + + (function (proto) { + /** + * @method destroy + * @member Ext.dom.AbstractElement + * @inheritdoc Ext.dom.AbstractElement#remove + * Alias to {@link #remove}. + */ + proto.destroy = proto.remove; + + /** + * Returns a child element of this element given its `id`. + * @method getById + * @member Ext.dom.AbstractElement + * @param {String} id The id of the desired child element. + * @param {Boolean} [asDom=false] True to return the DOM element, false to return a + * wrapped Element object. + */ + if (document.querySelector) { + proto.getById = function (id, asDom) { + // for normal elements getElementById is the best solution, but if the el is + // not part of the document.body, we have to resort to querySelector + var dom = document.getElementById(id) || + this.dom.querySelector('#'+Ext.escapeId(id)); + return asDom ? dom : (dom ? Ext.get(dom) : null); + }; + } else { + proto.getById = function (id, asDom) { + var dom = document.getElementById(id); + return asDom ? dom : (dom ? Ext.get(dom) : null); + }; + } + }(this.prototype)); +}); + +}()); + +/** + * @class Ext.dom.AbstractElement + */ +Ext.dom.AbstractElement.addInheritableStatics({ + unitRe: /\d+(px|em|%|en|ex|pt|in|cm|mm|pc)$/i, + camelRe: /(-[a-z])/gi, + cssRe: /([a-z0-9\-]+)\s*:\s*([^;\s]+(?:\s*[^;\s]+)*);?/gi, + opacityRe: /alpha\(opacity=(.*)\)/i, + propertyCache: {}, + defaultUnit : "px", + 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'}, + /** + * Test if size has a unit, otherwise appends the passed unit string, or the default for this Element. + * @param size {Object} The size to set + * @param units {String} The units to append to a numeric size value + * @private + * @static + */ + addUnits: function(size, units) { + // Most common case first: Size is set to a number + if (typeof size == 'number') { + return size + (units || this.defaultUnit || 'px'); + } + + // Size set to a value which means "auto" + if (size === "" || size == "auto" || size === undefined || size === null) { + return size || ''; + } + + // Otherwise, warn if it's not a valid CSS measurement + if (!this.unitRe.test(size)) { + if (Ext.isDefined(Ext.global.console)) { + Ext.global.console.warn("Warning, size detected as NaN on Element.addUnits."); + } + return size || ''; + } + + return size; + }, + + /** + * @static + * @private + */ + isAncestor: function(p, c) { + var ret = false; + + p = Ext.getDom(p); + c = Ext.getDom(c); + if (p && c) { + if (p.contains) { + return p.contains(c); + } else if (p.compareDocumentPosition) { + return !!(p.compareDocumentPosition(c) & 16); + } else { + while ((c = c.parentNode)) { + ret = c == p || ret; + } + } + } + return ret; + }, + + /** + * Parses a number or string representing margin sizes into an object. Supports CSS-style margin declarations + * (e.g. 10, "10", "10 10", "10 10 10" and "10 10 10 10" are all valid options and would return the same result) + * @static + * @param {Number/String} box The encoded margins + * @return {Object} An object with margin sizes for top, right, bottom and left + */ + parseBox: function(box) { + if (typeof box != 'string') { + box = box.toString(); + } + var parts = box.split(' '), + ln = parts.length; + + if (ln == 1) { + parts[1] = parts[2] = parts[3] = parts[0]; + } + else if (ln == 2) { + parts[2] = parts[0]; + parts[3] = parts[1]; + } + else if (ln == 3) { + parts[3] = parts[1]; + } + + return { + top :parseFloat(parts[0]) || 0, + right :parseFloat(parts[1]) || 0, + bottom:parseFloat(parts[2]) || 0, + left :parseFloat(parts[3]) || 0 + }; + }, + + /** + * Parses a number or string representing margin sizes into an object. Supports CSS-style margin declarations + * (e.g. 10, "10", "10 10", "10 10 10" and "10 10 10 10" are all valid options and would return the same result) + * @static + * @param {Number/String} box The encoded margins + * @param {String} units The type of units to add + * @return {String} An string with unitized (px if units is not specified) metrics for top, right, bottom and left + */ + unitizeBox: function(box, units) { + var a = this.addUnits, + b = this.parseBox(box); + + return a(b.top, units) + ' ' + + a(b.right, units) + ' ' + + a(b.bottom, units) + ' ' + + a(b.left, units); + + }, + + // private + camelReplaceFn: function(m, a) { + return a.charAt(1).toUpperCase(); + }, + + /** + * Normalizes CSS property keys from dash delimited to camel case JavaScript Syntax. + * For example: + * + * - border-width -> borderWidth + * - padding-top -> paddingTop + * + * @static + * @param {String} prop The property to normalize + * @return {String} The normalized string + */ + normalize: function(prop) { + // TODO: Mobile optimization? + if (prop == 'float') { + prop = Ext.supports.Float ? 'cssFloat' : 'styleFloat'; + } + return this.propertyCache[prop] || (this.propertyCache[prop] = prop.replace(this.camelRe, this.camelReplaceFn)); + }, + + /** + * Retrieves the document height + * @static + * @return {Number} documentHeight + */ + getDocumentHeight: function() { + return Math.max(!Ext.isStrict ? document.body.scrollHeight : document.documentElement.scrollHeight, this.getViewportHeight()); + }, + + /** + * Retrieves the document width + * @static + * @return {Number} documentWidth + */ + getDocumentWidth: function() { + return Math.max(!Ext.isStrict ? document.body.scrollWidth : document.documentElement.scrollWidth, this.getViewportWidth()); + }, + + /** + * Retrieves the viewport height of the window. + * @static + * @return {Number} viewportHeight + */ + getViewportHeight: function(){ + return window.innerHeight; + }, + + /** + * Retrieves the viewport width of the window. + * @static + * @return {Number} viewportWidth + */ + getViewportWidth: function() { + return window.innerWidth; + }, + + /** + * Retrieves the viewport size of the window. + * @static + * @return {Object} object containing width and height properties + */ + getViewSize: function() { + return { + width: window.innerWidth, + height: window.innerHeight + }; + }, + + /** + * Retrieves the current orientation of the window. This is calculated by + * determing if the height is greater than the width. + * @static + * @return {String} Orientation of window: 'portrait' or 'landscape' + */ + getOrientation: function() { + if (Ext.supports.OrientationChange) { + return (window.orientation == 0) ? 'portrait' : 'landscape'; + } + + return (window.innerHeight > window.innerWidth) ? 'portrait' : 'landscape'; + }, + + /** + * Returns the top Element that is located at the passed coordinates + * @static + * @param {Number} x The x coordinate + * @param {Number} y The y coordinate + * @return {String} The found Element + */ + fromPoint: function(x, y) { + return Ext.get(document.elementFromPoint(x, y)); + }, + + /** + * Converts a CSS string into an object with a property for each style. + * + * The sample code below would return an object with 2 properties, one + * for background-color and one for color. + * + * var css = 'background-color: red;color: blue; '; + * console.log(Ext.dom.Element.parseStyles(css)); + * + * @static + * @param {String} styles A CSS string + * @return {Object} styles + */ + parseStyles: function(styles){ + var out = {}, + cssRe = this.cssRe, + matches; + + if (styles) { + // Since we're using the g flag on the regex, we need to set the lastIndex. + // This automatically happens on some implementations, but not others, see: + // http://stackoverflow.com/questions/2645273/javascript-regular-expression-literal-persists-between-function-calls + // http://blog.stevenlevithan.com/archives/fixing-javascript-regexp + cssRe.lastIndex = 0; + while ((matches = cssRe.exec(styles))) { + out[matches[1]] = matches[2]; + } + } + return out; + } +}); + +//TODO Need serious cleanups +(function(){ + var doc = document, + AbstractElement = Ext.dom.AbstractElement, + activeElement = null, + isCSS1 = doc.compatMode == "CSS1Compat", + flyInstance, + fly = function (el) { + if (!flyInstance) { + flyInstance = new AbstractElement.Fly(); + } + flyInstance.attach(el); + return flyInstance; + }; + + // If the browser does not support document.activeElement we need some assistance. + // This covers old Safari 3.2 (4.0 added activeElement along with just about all + // other browsers). We need this support to handle issues with old Safari. + if (!('activeElement' in doc) && doc.addEventListener) { + doc.addEventListener('focus', + function (ev) { + if (ev && ev.target) { + activeElement = (ev.target == doc) ? null : ev.target; + } + }, true); + } + + /* + * Helper function to create the function that will restore the selection. + */ + function makeSelectionRestoreFn (activeEl, start, end) { + return function () { + activeEl.selectionStart = start; + activeEl.selectionEnd = end; + }; + } + + AbstractElement.addInheritableStatics({ + /** + * Returns the active element in the DOM. If the browser supports activeElement + * on the document, this is returned. If not, the focus is tracked and the active + * element is maintained internally. + * @return {HTMLElement} The active (focused) element in the document. + */ + getActiveElement: function () { + return doc.activeElement || activeElement; + }, + + /** + * Creates a function to call to clean up problems with the work-around for the + * WebKit RightMargin bug. The work-around is to add "display: 'inline-block'" to + * the element before calling getComputedStyle and then to restore its original + * display value. The problem with this is that it corrupts the selection of an + * INPUT or TEXTAREA element (as in the "I-beam" goes away but ths focus remains). + * To cleanup after this, we need to capture the selection of any such element and + * then restore it after we have restored the display style. + * + * @param {Ext.dom.Element} target The top-most element being adjusted. + * @private + */ + getRightMarginFixCleaner: function (target) { + var supports = Ext.supports, + hasInputBug = supports.DisplayChangeInputSelectionBug, + hasTextAreaBug = supports.DisplayChangeTextAreaSelectionBug, + activeEl, + tag, + start, + end; + + if (hasInputBug || hasTextAreaBug) { + activeEl = doc.activeElement || activeElement; // save a call + tag = activeEl && activeEl.tagName; + + if ((hasTextAreaBug && tag == 'TEXTAREA') || + (hasInputBug && tag == 'INPUT' && activeEl.type == 'text')) { + if (Ext.dom.Element.isAncestor(target, activeEl)) { + start = activeEl.selectionStart; + end = activeEl.selectionEnd; + + if (Ext.isNumber(start) && Ext.isNumber(end)) { // to be safe... + // We don't create the raw closure here inline because that + // will be costly even if we don't want to return it (nested + // function decls and exprs are often instantiated on entry + // regardless of whether execution ever reaches them): + return makeSelectionRestoreFn(activeEl, start, end); + } + } + } + } + + return Ext.emptyFn; // avoid special cases, just return a nop + }, + + getViewWidth: function(full) { + return full ? Ext.dom.Element.getDocumentWidth() : Ext.dom.Element.getViewportWidth(); + }, + + getViewHeight: function(full) { + return full ? Ext.dom.Element.getDocumentHeight() : Ext.dom.Element.getViewportHeight(); + }, + + getDocumentHeight: function() { + return Math.max(!isCSS1 ? doc.body.scrollHeight : doc.documentElement.scrollHeight, Ext.dom.Element.getViewportHeight()); + }, + + getDocumentWidth: function() { + return Math.max(!isCSS1 ? doc.body.scrollWidth : doc.documentElement.scrollWidth, Ext.dom.Element.getViewportWidth()); + }, + + getViewportHeight: function(){ + return Ext.isIE ? + (Ext.isStrict ? doc.documentElement.clientHeight : doc.body.clientHeight) : + self.innerHeight; + }, + + getViewportWidth: function() { + return (!Ext.isStrict && !Ext.isOpera) ? doc.body.clientWidth : + Ext.isIE ? doc.documentElement.clientWidth : self.innerWidth; + }, + + getY: function(el) { + return Ext.dom.Element.getXY(el)[1]; + }, + + getX: function(el) { + return Ext.dom.Element.getXY(el)[0]; + }, + + getXY: function(el) { + var bd = doc.body, + docEl = doc.documentElement, + leftBorder = 0, + topBorder = 0, + ret = [0,0], + round = Math.round, + box, + scroll; + + el = Ext.getDom(el); + + if(el != doc && el != bd){ + // IE has the potential to throw when getBoundingClientRect called + // on element not attached to dom + if (Ext.isIE) { + try { + box = el.getBoundingClientRect(); + // In some versions of IE, the documentElement (HTML element) will have a 2px border that gets included, so subtract it off + topBorder = docEl.clientTop || bd.clientTop; + leftBorder = docEl.clientLeft || bd.clientLeft; + } catch (ex) { + box = { left: 0, top: 0 }; + } + } else { + box = el.getBoundingClientRect(); + } + + scroll = fly(document).getScroll(); + ret = [round(box.left + scroll.left - leftBorder), round(box.top + scroll.top - topBorder)]; + } + return ret; + }, + + setXY: function(el, xy) { + (el = Ext.fly(el, '_setXY')).position(); + + var pts = el.translatePoints(xy), + style = el.dom.style, + pos; + + for (pos in pts) { + if (!isNaN(pts[pos])) { + style[pos] = pts[pos] + "px"; + } + } + }, + + setX: function(el, x) { + Ext.dom.Element.setXY(el, [x, false]); + }, + + setY: function(el, y) { + Ext.dom.Element.setXY(el, [false, y]); + }, + + /** + * Serializes a DOM form into a url encoded string + * @param {Object} form The form + * @return {String} The url encoded form + */ + serializeForm: function(form) { + var fElements = form.elements || (document.forms[form] || Ext.getDom(form)).elements, + hasSubmit = false, + encoder = encodeURIComponent, + data = '', + eLen = fElements.length, + element, name, type, options, hasValue, e, + o, oLen, opt; + + for (e = 0; e < eLen; e++) { + element = fElements[e]; + name = element.name; + type = element.type; + options = element.options; + + if (!element.disabled && name) { + if (/select-(one|multiple)/i.test(type)) { + oLen = options.length; + for (o = 0; o < oLen; o++) { + opt = options[o]; + if (opt.selected) { + hasValue = opt.hasAttribute ? opt.hasAttribute('value') : opt.getAttributeNode('value').specified; + data += Ext.String.format("{0}={1}&", encoder(name), encoder(hasValue ? opt.value : opt.text)); + } + } + } else if (!(/file|undefined|reset|button/i.test(type))) { + if (!(/radio|checkbox/i.test(type) && !element.checked) && !(type == 'submit' && hasSubmit)) { + data += encoder(name) + '=' + encoder(element.value) + '&'; + hasSubmit = /submit/i.test(type); + } + } + } + } + return data.substr(0, data.length - 1); + } + }); +}()); + +/** + * @class Ext.dom.AbstractElement + */ +Ext.dom.AbstractElement.override({ + + /** + * Gets the x,y coordinates specified by the anchor position on the element. + * @param {String} [anchor] The specified anchor position (defaults to "c"). See {@link Ext.dom.Element#alignTo} + * for details on supported anchor positions. + * @param {Boolean} [local] True to get the local (element top/left-relative) anchor position instead + * of page coordinates + * @param {Object} [size] 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, size) { + //Passing a different size is useful for pre-calculating anchors, + //especially for anchored animations that change the el size. + anchor = (anchor || "tl").toLowerCase(); + size = size || {}; + + var me = this, + vp = me.dom == document.body || me.dom == document, + width = size.width || vp ? window.innerWidth: me.getWidth(), + height = size.height || vp ? window.innerHeight: me.getHeight(), + xy, + rnd = Math.round, + myXY = me.getXY(), + extraX = vp ? 0: !local ? myXY[0] : 0, + extraY = vp ? 0: !local ? myXY[1] : 0, + hash = { + c: [rnd(width * 0.5), rnd(height * 0.5)], + t: [rnd(width * 0.5), 0], + l: [0, rnd(height * 0.5)], + r: [width, rnd(height * 0.5)], + b: [rnd(width * 0.5), height], + tl: [0, 0], + bl: [0, height], + br: [width, height], + tr: [width, 0] + }; + + xy = hash[anchor]; + return [xy[0] + extraX, xy[1] + extraY]; + }, + + alignToRe: /^([a-z]+)-([a-z]+)(\?)?$/, + + /** + * Gets the x,y coordinates to align this element with another element. See {@link Ext.dom.Element#alignTo} for more info on the + * supported position values. + * @param {Ext.Element/HTMLElement/String} element The element to align to. + * @param {String} [position="tl-bl?"] The position to align to. + * @param {Array} [offsets=[0,0]] Offset the positioning by [x, y] + * @return {Array} [x, y] + */ + getAlignToXY: function(el, position, offsets, local) { + local = !!local; + el = Ext.get(el); + + if (!el || !el.dom) { + throw new Error("Element.alignToXY with an element that doesn't exist"); + } + offsets = offsets || [0, 0]; + + if (!position || position == '?') { + position = 'tl-bl?'; + } + else if (! (/-/).test(position) && position !== "") { + position = 'tl-' + position; + } + position = position.toLowerCase(); + + var me = this, + matches = position.match(this.alignToRe), + dw = window.innerWidth, + dh = window.innerHeight, + p1 = "", + p2 = "", + a1, + a2, + x, + y, + swapX, + swapY, + p1x, + p1y, + p2x, + p2y, + width, + height, + region, + constrain; + + if (!matches) { + throw "Element.alignTo with an invalid alignment " + position; + } + + p1 = matches[1]; + p2 = matches[2]; + constrain = !!matches[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, local); + + x = a2[0] - a1[0] + offsets[0]; + y = a2[1] - a1[1] + offsets[1]; + + if (constrain) { + width = me.getWidth(); + height = me.getHeight(); + + region = el.getPageBox(); + + //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 + width > dw) { + x = swapX ? region.left - width: dw - width; + } + if (x < 0) { + x = swapX ? region.right: 0; + } + if (y + height > dh) { + y = swapY ? region.top - height: dh - height; + } + if (y < 0) { + y = swapY ? region.bottom: 0; + } + } + + return [x, y]; + }, + + // private + getAnchor: function(){ + var data = (this.$cache || this.getCache()).data, + anchor; + + if (!this.dom) { + return; + } + anchor = data._anchor; + + if(!anchor){ + anchor = data._anchor = {}; + } + return anchor; + }, + + // private ==> used outside of core + adjustForConstraints: function(xy, parent) { + var vector = this.getConstrainVector(parent, xy); + if (vector) { + xy[0] += vector[0]; + xy[1] += vector[1]; + } + return xy; + } + +}); + +/** + * @class Ext.dom.AbstractElement + */ +Ext.dom.AbstractElement.addMethods({ + /** + * Appends the passed element(s) to this element + * @param {String/HTMLElement/Ext.dom.AbstractElement} el + * The id of the node, a DOM Node or an existing Element. + * @return {Ext.dom.AbstractElement} This element + */ + appendChild: function(el) { + return Ext.get(el).appendTo(this); + }, + + /** + * Appends this element to the passed element + * @param {String/HTMLElement/Ext.dom.AbstractElement} el The new parent element. + * The id of the node, a DOM Node or an existing Element. + * @return {Ext.dom.AbstractElement} This element + */ + appendTo: function(el) { + Ext.getDom(el).appendChild(this.dom); + return this; + }, + + /** + * Inserts this element before the passed element in the DOM + * @param {String/HTMLElement/Ext.dom.AbstractElement} el The element before which this element will be inserted. + * The id of the node, a DOM Node or an existing Element. + * @return {Ext.dom.AbstractElement} This element + */ + insertBefore: function(el) { + el = Ext.getDom(el); + el.parentNode.insertBefore(this.dom, el); + return this; + }, + + /** + * Inserts this element after the passed element in the DOM + * @param {String/HTMLElement/Ext.dom.AbstractElement} el The element to insert after. + * The id of the node, a DOM Node or an existing Element. + * @return {Ext.dom.AbstractElement} This element + */ + insertAfter: function(el) { + el = Ext.getDom(el); + 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 {String/HTMLElement/Ext.dom.AbstractElement/Object} el The id or element to insert or a DomHelper config + * to create and insert + * @return {Ext.dom.AbstractElement} The new child + */ + insertFirst: function(el, returnDom) { + el = el || {}; + if (el.nodeType || el.dom || typeof el == 'string') { // element + el = Ext.getDom(el); + this.dom.insertBefore(el, this.dom.firstChild); + return !returnDom ? Ext.get(el) : el; + } + else { // dh config + return this.createChild(el, this.dom.firstChild, returnDom); + } + }, + + /** + * Inserts (or creates) the passed element (or DomHelper config) as a sibling of this element + * @param {String/HTMLElement/Ext.dom.AbstractElement/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='before'] 'before' or 'after' + * @param {Boolean} [returnDom=false] True to return the .;ll;l,raw DOM element instead of Ext.dom.AbstractElement + * @return {Ext.dom.AbstractElement} The inserted Element. If an array is passed, the last inserted element is returned. + */ + insertSibling: function(el, where, returnDom){ + var me = this, + isAfter = (where || 'before').toLowerCase() == 'after', + rt, insertEl, eLen, e; + + if (Ext.isArray(el)) { + insertEl = me; + eLen = el.length; + + for (e = 0; e < eLen; e++) { + rt = Ext.fly(insertEl, '_internal').insertSibling(el[e], where, returnDom); + + if (isAfter) { + insertEl = rt; + } + } + + return rt; + } + + el = el || {}; + + if(el.nodeType || el.dom){ + rt = me.dom.parentNode.insertBefore(Ext.getDom(el), isAfter ? me.dom.nextSibling : me.dom); + if (!returnDom) { + rt = Ext.get(rt); + } + }else{ + if (isAfter && !me.dom.nextSibling) { + rt = Ext.core.DomHelper.append(me.dom.parentNode, el, !returnDom); + } else { + rt = Ext.core.DomHelper[isAfter ? 'insertAfter' : 'insertBefore'](me.dom, el, !returnDom); + } + } + return rt; + }, + + /** + * Replaces the passed element with this element + * @param {String/HTMLElement/Ext.dom.AbstractElement} el The element to replace. + * The id of the node, a DOM Node or an existing Element. + * @return {Ext.dom.AbstractElement} This element + */ + replace: function(el) { + el = Ext.get(el); + this.insertBefore(el); + el.remove(); + return this; + }, + + /** + * Replaces this element with the passed element + * @param {String/HTMLElement/Ext.dom.AbstractElement/Object} el The new element (id of the node, a DOM Node + * or an existing Element) or a DomHelper config of an element to create + * @return {Ext.dom.AbstractElement} This element + */ + replaceWith: function(el){ + var me = this; + + if(el.nodeType || el.dom || typeof el == 'string'){ + el = Ext.get(el); + me.dom.parentNode.insertBefore(el, me.dom); + }else{ + el = Ext.core.DomHelper.insertBefore(me.dom, el); + } + + delete Ext.cache[me.id]; + Ext.removeNode(me.dom); + me.id = Ext.id(me.dom = el); + Ext.dom.AbstractElement.addToCache(me.isFlyweight ? new Ext.dom.AbstractElement(me.dom) : me); + return me; + }, + + /** + * Creates the passed DomHelper config and appends it to this element or optionally inserts it before the passed child element. + * @param {Object} config DomHelper element config object. If no tag is specified (e.g., {tag:'input'}) then a div will be + * automatically generated with the specified attributes. + * @param {HTMLElement} [insertBefore] a child element of this element + * @param {Boolean} [returnDom=false] true to return the dom node instead of creating an Element + * @return {Ext.dom.AbstractElement} The new child element + */ + createChild: function(config, insertBefore, returnDom) { + config = config || {tag:'div'}; + if (insertBefore) { + return Ext.core.DomHelper.insertBefore(insertBefore, config, returnDom !== true); + } + else { + return Ext.core.DomHelper[!this.dom.firstChild ? 'insertFirst' : 'append'](this.dom, config, returnDom !== true); + } + }, + + /** + * Creates and wraps this element with another element + * @param {Object} [config] DomHelper element config object for the wrapper element or null for an empty div + * @param {Boolean} [returnDom=false] True to return the raw DOM element instead of Ext.dom.AbstractElement + * @return {HTMLElement/Ext.dom.AbstractElement} The newly created wrapper element + */ + wrap: function(config, returnDom) { + var newEl = Ext.core.DomHelper.insertBefore(this.dom, config || {tag: "div"}, !returnDom), + d = newEl.dom || newEl; + + d.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. + * See {@link Ext.dom.Helper#insertHtml} for details. + * @param {String} html The HTML fragment + * @param {Boolean} [returnEl=false] True to return an Ext.dom.AbstractElement + * @return {HTMLElement/Ext.dom.AbstractElement} The inserted node (or nearest related if more than 1 inserted) + */ + insertHtml: function(where, html, returnEl) { + var el = Ext.core.DomHelper.insertHtml(where, this.dom, html); + return returnEl ? Ext.get(el) : el; + } +}); + +/** + * @class Ext.dom.AbstractElement + */ +(function(){ + +var Element = Ext.dom.AbstractElement; + +Element.override({ + + /** + * 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(el) { + return this.getXY(el)[0]; + }, + + /** + * 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(el) { + return this.getXY(el)[1]; + }, + + /** + * 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() { + // @FEATUREDETECT + var point = window.webkitConvertPointFromNodeToPage(this.dom, new WebKitPoint(0, 0)); + return [point.x, point.y]; + }, + + /** + * 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 {Ext.Element/HTMLElement/String} 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] True for the default animation, or a standard Element + * animation config object + * @return {Ext.dom.AbstractElement} this + */ + setX: function(x){ + return this.setXY([x, this.getY()]); + }, + + /** + * 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] True for the default animation, or a standard Element + * animation config object + * @return {Ext.dom.AbstractElement} this + */ + setY: function(y) { + return this.setXY([this.getX(), y]); + }, + + /** + * Sets the element's left position directly using CSS style (instead of {@link #setX}). + * @param {String} left The left CSS property value + * @return {Ext.dom.AbstractElement} this + */ + setLeft: function(left) { + this.setStyle('left', Element.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.dom.AbstractElement} this + */ + setTop: function(top) { + this.setStyle('top', Element.addUnits(top)); + return this; + }, + + /** + * Sets the element's CSS right style. + * @param {String} right The right CSS property value + * @return {Ext.dom.AbstractElement} this + */ + setRight: function(right) { + this.setStyle('right', Element.addUnits(right)); + return this; + }, + + /** + * Sets the element's CSS bottom style. + * @param {String} bottom The bottom CSS property value + * @return {Ext.dom.AbstractElement} this + */ + setBottom: function(bottom) { + this.setStyle('bottom', Element.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] True for the default animation, or a standard Element animation config object + * @return {Ext.dom.AbstractElement} this + */ + setXY: function(pos) { + var me = this, + pts, + style, + pt; + + if (arguments.length > 1) { + pos = [pos, arguments[1]]; + } + + // me.position(); + pts = me.translatePoints(pos); + style = me.dom.style; + + for (pt in pts) { + if (!pts.hasOwnProperty(pt)) { + continue; + } + if (!isNaN(pts[pt])) { + style[pt] = pts[pt] + "px"; + } + } + return me; + }, + + /** + * 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 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) { + return parseInt(this.getStyle('right'), 10) || 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 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) { + return parseInt(this.getStyle('bottom'), 10) || 0; + }, + + /** + * 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] 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)}; + }, + + /** + * 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] Whether to adjust for box-model issues automatically + * @param {Boolean/Object} [animate] true for the default animation or a standard + * Element animation config object + * @return {Ext.dom.AbstractElement} this + */ + setBox: function(box) { + var me = this, + width = box.width, + height = box.height, + top = box.top, + left = box.left; + + if (left !== undefined) { + me.setLeft(left); + } + if (top !== undefined) { + me.setTop(top); + } + if (width !== undefined) { + me.setWidth(width); + } + if (height !== undefined) { + me.setHeight(height); + } + + return this; + }, + + /** + * Return an object defining the area of this Element which can be passed to {@link #setBox} to + * set another Element's size/location to match this element. + * + * @param {Boolean} [contentBox] If true a box for the content of the element is returned. + * @param {Boolean} [local] 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: , + * bottom: , + * right: + * } + * + * The returned object may also be addressed as an Array where index 0 contains the X position + * and index 1 contains the Y position. So the result may also be used for {@link #setXY} + */ + getBox: function(contentBox, local) { + var me = this, + dom = me.dom, + width = dom.offsetWidth, + height = dom.offsetHeight, + xy, box, l, r, t, b; + + if (!local) { + xy = me.getXY(); + } + else if (contentBox) { + xy = [0,0]; + } + else { + xy = [parseInt(me.getStyle("left"), 10) || 0, parseInt(me.getStyle("top"), 10) || 0]; + } + + if (!contentBox) { + box = { + x: xy[0], + y: xy[1], + 0: xy[0], + 1: xy[1], + width: width, + height: height + }; + } + else { + l = me.getBorderWidth.call(me, "l") + me.getPadding.call(me, "l"); + r = me.getBorderWidth.call(me, "r") + me.getPadding.call(me, "r"); + t = me.getBorderWidth.call(me, "t") + me.getPadding.call(me, "t"); + b = me.getBorderWidth.call(me, "b") + me.getPadding.call(me, "b"); + box = { + x: xy[0] + l, + y: xy[1] + t, + 0: xy[0] + l, + 1: xy[1] + t, + width: width - (l + r), + height: height - (t + b) + }; + } + + box.left = box.x; + box.top = box.y; + box.right = box.x + box.width; + box.bottom = box.y + box.height; + + return box; + }, + + /** + * Return an object defining the area of this Element which can be passed to {@link #setBox} to + * set another Element's size/location to match this element. + * + * @param {Boolean} [asRegion] If true an Ext.util.Region will be returned + * @return {Object} box An object in the format + * + * { + * x: , + * y: , + * width: , + * height: , + * bottom: , + * right: + * } + * + * The returned object may also be addressed as an Array where index 0 contains the X position + * and index 1 contains the Y position. So the result may also be used for {@link #setXY} + */ + getPageBox: function(getRegion) { + var me = this, + el = me.dom, + w = el.offsetWidth, + h = el.offsetHeight, + xy = me.getXY(), + t = xy[1], + r = xy[0] + w, + b = xy[1] + h, + l = xy[0]; + + if (!el) { + return new Ext.util.Region(); + } + + if (getRegion) { + return new Ext.util.Region(t, r, b, l); + } + else { + return { + left: l, + top: t, + width: w, + height: h, + right: r, + bottom: b + }; + } + } +}); + +}()); + +/** + * @class Ext.dom.AbstractElement + */ +(function(){ + // local style camelizing for speed + var Element = Ext.dom.AbstractElement, + view = document.defaultView, + array = Ext.Array, + trimRe = /^\s+|\s+$/g, + wordsRe = /\w/g, + spacesRe = /\s+/, + transparentRe = /^(?:transparent|(?:rgba[(](?:\s*\d+\s*[,]){3}\s*0\s*[)]))$/i, + hasClassList = Ext.supports.ClassList, + PADDING = 'padding', + MARGIN = 'margin', + BORDER = 'border', + LEFT_SUFFIX = '-left', + RIGHT_SUFFIX = '-right', + TOP_SUFFIX = '-top', + BOTTOM_SUFFIX = '-bottom', + WIDTH = '-width', + // special markup used throughout Ext when box wrapping elements + borders = {l: BORDER + LEFT_SUFFIX + WIDTH, r: BORDER + RIGHT_SUFFIX + WIDTH, t: BORDER + TOP_SUFFIX + WIDTH, b: BORDER + BOTTOM_SUFFIX + WIDTH}, + paddings = {l: PADDING + LEFT_SUFFIX, r: PADDING + RIGHT_SUFFIX, t: PADDING + TOP_SUFFIX, b: PADDING + BOTTOM_SUFFIX}, + margins = {l: MARGIN + LEFT_SUFFIX, r: MARGIN + RIGHT_SUFFIX, t: MARGIN + TOP_SUFFIX, b: MARGIN + BOTTOM_SUFFIX}; + + + Element.override({ + + /** + * This shared object is keyed by style name (e.g., 'margin-left' or 'marginLeft'). The + * values are objects with the following properties: + * + * * `name` (String) : The actual name to be presented to the DOM. This is typically the value + * returned by {@link #normalize}. + * * `get` (Function) : A hook function that will perform the get on this style. These + * functions receive "(dom, el)" arguments. The `dom` parameter is the DOM Element + * from which to get ths tyle. The `el` argument (may be null) is the Ext.Element. + * * `set` (Function) : A hook function that will perform the set on this style. These + * functions receive "(dom, value, el)" arguments. The `dom` parameter is the DOM Element + * from which to get ths tyle. The `value` parameter is the new value for the style. The + * `el` argument (may be null) is the Ext.Element. + * + * The `this` pointer is the object that contains `get` or `set`, which means that + * `this.name` can be accessed if needed. The hook functions are both optional. + * @private + */ + styleHooks: {}, + + // private + addStyles : function(sides, styles){ + var totalSize = 0, + sidesArr = (sides || '').match(wordsRe), + i, + len = sidesArr.length, + side, + styleSides = []; + + if (len == 1) { + totalSize = Math.abs(parseFloat(this.getStyle(styles[sidesArr[0]])) || 0); + } else if (len) { + for (i = 0; i < len; i++) { + side = sidesArr[i]; + styleSides.push(styles[side]); + } + //Gather all at once, returning a hash + styleSides = this.getStyle(styleSides); + + for (i=0; i < len; i++) { + side = sidesArr[i]; + totalSize += Math.abs(parseFloat(styleSides[styles[side]]) || 0); + } + } + + return totalSize; + }, + + /** + * Adds one or more CSS classes to the element. Duplicate classes are automatically filtered out. + * @param {String/String[]} className The CSS classes to add separated by space, or an array of classes + * @return {Ext.dom.Element} this + * @method + */ + addCls: hasClassList ? + function (className) { + if (String(className).indexOf('undefined') > -1) { + Ext.Logger.warn("called with an undefined className: " + className); + } + var me = this, + dom = me.dom, + classList, + newCls, + i, + len, + cls; + + if (typeof(className) == 'string') { + // split string on spaces to make an array of className + className = className.replace(trimRe, '').split(spacesRe); + } + + // the gain we have here is that we can skip parsing className and use the + // classList.contains method, so now O(M) not O(M+N) + if (dom && className && !!(len = className.length)) { + if (!dom.className) { + dom.className = className.join(' '); + } else { + classList = dom.classList; + for (i = 0; i < len; ++i) { + cls = className[i]; + if (cls) { + if (!classList.contains(cls)) { + if (newCls) { + newCls.push(cls); + } else { + newCls = dom.className.replace(trimRe, ''); + newCls = newCls ? [newCls, cls] : [cls]; + } + } + } + } + + if (newCls) { + dom.className = newCls.join(' '); // write to DOM once + } + } + } + return me; + } : + function(className) { + if (String(className).indexOf('undefined') > -1) { + Ext.Logger.warn("called with an undefined className: '" + className + "'"); + } + var me = this, + dom = me.dom, + changed, + elClasses; + + if (dom && className && className.length) { + elClasses = Ext.Element.mergeClsList(dom.className, className); + if (elClasses.changed) { + dom.className = elClasses.join(' '); // write to DOM once + } + } + return me; + }, + + + /** + * Removes one or more CSS classes from the element. + * @param {String/String[]} className The CSS classes to remove separated by space, or an array of classes + * @return {Ext.dom.Element} this + */ + removeCls: function(className) { + var me = this, + dom = me.dom, + len, + elClasses; + + if (typeof(className) == 'string') { + // split string on spaces to make an array of className + className = className.replace(trimRe, '').split(spacesRe); + } + + if (dom && dom.className && className && !!(len = className.length)) { + if (len == 1 && hasClassList) { + if (className[0]) { + dom.classList.remove(className[0]); // one DOM write + } + } else { + elClasses = Ext.Element.removeCls(dom.className, className); + if (elClasses.changed) { + dom.className = elClasses.join(' '); + } + } + } + return me; + }, + + /** + * Adds one or more CSS classes to this element and removes the same class(es) from all siblings. + * @param {String/String[]} className The CSS class to add, or an array of classes + * @return {Ext.dom.Element} this + */ + radioCls: 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').removeCls(className); + } + } + return this.addCls(className); + }, + + /** + * Toggles the specified CSS class on this element (removes it if it already exists, otherwise adds it). + * @param {String} className The CSS class to toggle + * @return {Ext.dom.Element} this + * @method + */ + toggleCls: hasClassList ? + function (className) { + var me = this, + dom = me.dom; + + if (dom) { + className = className.replace(trimRe, ''); + if (className) { + dom.classList.toggle(className); + } + } + + return me; + } : + function(className) { + var me = this; + return me.hasCls(className) ? me.removeCls(className) : me.addCls(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 + * @method + */ + hasCls: hasClassList ? + function (className) { + var dom = this.dom; + return (dom && className) ? dom.classList.contains(className) : false; + } : + function(className) { + var dom = this.dom; + return dom ? className && (' '+dom.className+' ').indexOf(' '+className+' ') != -1 : false; + }, + + /** + * 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.dom.Element} this + */ + replaceCls: function(oldClassName, newClassName){ + return this.removeCls(oldClassName).addCls(newClassName); + }, + + /** + * Checks if the current value of a style is equal to a given value. + * @param {String} style property whose value is returned. + * @param {String} value to check against. + * @return {Boolean} true for when the current value equals the given value. + */ + isStyle: function(style, val) { + return this.getStyle(style) == val; + }, + + /** + * Returns a named style property based on computed/currentStyle (primary) and + * inline-style if primary is not available. + * + * @param {String/String[]} property The style property (or multiple property names + * in an array) whose value is returned. + * @param {Boolean} [inline=false] if `true` only inline styles will be returned. + * @return {String/Object} The current value of the style property for this element + * (or a hash of named style values if multiple property arguments are requested). + * @method + */ + getStyle: function (property, inline) { + var me = this, + dom = me.dom, + multiple = typeof property != 'string', + hooks = me.styleHooks, + prop = property, + props = prop, + len = 1, + domStyle, camel, values, hook, out, style, i; + + if (multiple) { + values = {}; + prop = props[0]; + i = 0; + if (!(len = props.length)) { + return values; + } + } + + if (!dom || dom.documentElement) { + return values || ''; + } + + domStyle = dom.style; + + if (inline) { + style = domStyle; + } else { + // Caution: Firefox will not render "presentation" (ie. computed styles) in + // iframes that are display:none or those inheriting display:none. Similar + // issues with legacy Safari. + // + style = dom.ownerDocument.defaultView.getComputedStyle(dom, null); + + // fallback to inline style if rendering context not available + if (!style) { + inline = true; + style = domStyle; + } + } + + do { + hook = hooks[prop]; + + if (!hook) { + hooks[prop] = hook = { name: Element.normalize(prop) }; + } + + if (hook.get) { + out = hook.get(dom, me, inline, style); + } else { + camel = hook.name; + out = style[camel]; + } + + if (!multiple) { + return out; + } + + values[prop] = out; + prop = props[++i]; + } while (i < len); + + return values; + }, + + getStyles: function () { + var props = Ext.Array.slice(arguments), + len = props.length, + inline; + + if (len && typeof props[len-1] == 'boolean') { + inline = props.pop(); + } + + return this.getStyle(props, inline); + }, + + /** + * Returns true if the value of the given property is visually transparent. This + * may be due to a 'transparent' style value or an rgba value with 0 in the alpha + * component. + * @param {String} prop The style property whose value is to be tested. + * @return {Boolean} True if the style property is visually transparent. + */ + isTransparent: function (prop) { + var value = this.getStyle(prop); + return value ? transparentRe.test(value) : false; + }, + + /** + * 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] The value to apply to the given property, or null if an object was passed. + * @return {Ext.dom.Element} this + */ + setStyle: function(prop, value) { + var me = this, + dom = me.dom, + hooks = me.styleHooks, + style = dom.style, + name = prop, + hook; + + // we don't promote the 2-arg form to object-form to avoid the overhead... + if (typeof name == 'string') { + hook = hooks[name]; + if (!hook) { + hooks[name] = hook = { name: Element.normalize(name) }; + } + value = (value == null) ? '' : value; + if (hook.set) { + hook.set(dom, value, me); + } else { + style[hook.name] = value; + } + if (hook.afterSet) { + hook.afterSet(dom, value, me); + } + } else { + for (name in prop) { + if (prop.hasOwnProperty(name)) { + hook = hooks[name]; + if (!hook) { + hooks[name] = hook = { name: Element.normalize(name) }; + } + value = prop[name]; + value = (value == null) ? '' : value; + if (hook.set) { + hook.set(dom, value, me); + } else { + style[hook.name] = value; + } + if (hook.afterSet) { + hook.afterSet(dom, value, me); + } + } + } + } + + return me; + }, + + /** + * Returns the offset height of the element + * @param {Boolean} [contentHeight] true to get the height minus borders and padding + * @return {Number} The element's height + */ + getHeight: function(contentHeight) { + var dom = this.dom, + height = contentHeight ? (dom.clientHeight - this.getPadding("tb")) : dom.offsetHeight; + return height > 0 ? height: 0; + }, + + /** + * Returns the offset width of the element + * @param {Boolean} [contentWidth] true to get the width minus borders and padding + * @return {Number} The element's width + */ + getWidth: function(contentWidth) { + var dom = this.dom, + width = contentWidth ? (dom.clientWidth - this.getPadding("lr")) : dom.offsetWidth; + return width > 0 ? width: 0; + }, + + /** + * Set the width of this Element. + * @param {Number/String} 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] true for the default animation or a standard Element animation config object + * @return {Ext.dom.Element} this + */ + setWidth: function(width) { + var me = this; + me.dom.style.width = Element.addUnits(width); + return me; + }, + + /** + * 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 {Number/String} 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] true for the default animation or a standard Element animation config object + * @return {Ext.dom.Element} this + */ + setHeight: function(height) { + var me = this; + me.dom.style.height = Element.addUnits(height); + 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 **l**eft width + the border **r**ight width. + * @return {Number} The width of the sides passed added together + */ + getBorderWidth: function(side){ + return this.addStyles(side, borders); + }, + + /** + * Gets the width of the padding(s) for the specified side(s) + * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example, + * passing `'lr'` would get the padding **l**eft + the padding **r**ight. + * @return {Number} The padding of the sides passed added together + */ + getPadding: function(side){ + return this.addStyles(side, paddings); + }, + + margins : margins, + + /** + * 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.dom.Element} this + */ + applyStyles: function(styles) { + if (styles) { + var i, + len, + dom = this.dom; + + if (typeof styles == 'function') { + styles = styles.call(); + } + if (typeof styles == 'string') { + styles = Ext.util.Format.trim(styles).split(/\s*(?::|;)\s*/); + for (i = 0, len = styles.length; i < len;) { + dom.style[Element.normalize(styles[i++])] = styles[i++]; + } + } + else if (typeof styles == 'object') { + this.setStyle(styles); + } + } + }, + + /** + * Set the size of this Element. If animation is true, both width and height will be animated concurrently. + * @param {Number/String} 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 {Number/String} 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] true for the default animation or a standard Element animation config object + * @return {Ext.dom.Element} this + */ + setSize: function(width, height) { + var me = this, + style = me.dom.style; + + if (Ext.isObject(width)) { + // in case of object from getSize() + height = width.height; + width = width.width; + } + + style.width = Element.addUnits(width); + style.height = Element.addUnits(height); + return me; + }, + + /** + * Returns the dimensions of the element available to lay content out in. + * + * If the element (or any ancestor element) has CSS style `display: none`, the dimensions will be zero. + * + * Example: + * + * 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. + * + * getViewSize utilizes clientHeight/clientWidth which excludes sizing of scrollbars. + * To obtain the size including scrollbars, use getStyleSize + * + * Sizing of the document body is handled at the adapter level which handles special cases for IE and strict modes, etc. + * + * @return {Object} Object describing width and height. + * @return {Number} return.width + * @return {Number} return.height + */ + getViewSize: function() { + var doc = document, + dom = this.dom; + + if (dom == doc || dom == doc.body) { + return { + width: Element.getViewportWidth(), + height: Element.getViewportHeight() + }; + } + else { + return { + width: dom.clientWidth, + height: dom.clientHeight + }; + } + }, + + /** + * Returns the size of the element. + * @param {Boolean} [contentSize] true to get the width/size minus borders and padding + * @return {Object} An object containing the element's size: + * @return {Number} return.width + * @return {Number} return.height + */ + getSize: function(contentSize) { + var dom = this.dom; + return { + width: Math.max(0, contentSize ? (dom.clientWidth - this.getPadding("lr")) : dom.offsetWidth), + height: Math.max(0, contentSize ? (dom.clientHeight - this.getPadding("tb")) : dom.offsetHeight) + }; + }, + + /** + * Forces the browser to repaint this element + * @return {Ext.dom.Element} this + */ + repaint: function(){ + var dom = this.dom; + this.addCls(Ext.baseCSSPrefix + 'repaint'); + setTimeout(function(){ + Ext.fly(dom).removeCls(Ext.baseCSSPrefix + 'repaint'); + }, 1); + return this; + }, + + /** + * 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] Any combination of l, r, t, b to get the sum of those sides + * @return {Object/Number} + */ + getMargin: function(side){ + var me = this, + hash = {t:"top", l:"left", r:"right", b: "bottom"}, + key, + o, + margins; + + if (!side) { + margins = []; + for (key in me.margins) { + if(me.margins.hasOwnProperty(key)) { + margins.push(me.margins[key]); + } + } + o = me.getStyle(margins); + if(o && typeof o == 'object') { + //now mixin nomalized values (from hash table) + for (key in me.margins) { + if(me.margins.hasOwnProperty(key)) { + o[hash[key]] = parseFloat(o[me.margins[key]]) || 0; + } + } + } + + return o; + } else { + return me.addStyles.call(me, side, me.margins); + } + }, + + /** + * 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] A message to display in the mask + * @param {String} [msgCls] A css class to apply to the msg element + */ + mask: function(msg, msgCls, transparent) { + var me = this, + dom = me.dom, + data = (me.$cache || me.getCache()).data, + el = data.mask, + mask, + size, + cls = '', + prefix = Ext.baseCSSPrefix; + + me.addCls(prefix + 'masked'); + if (me.getStyle("position") == "static") { + me.addCls(prefix + 'masked-relative'); + } + if (el) { + el.remove(); + } + if (msgCls && typeof msgCls == 'string' ) { + cls = ' ' + msgCls; + } + else { + cls = ' ' + prefix + 'mask-gray'; + } + + mask = me.createChild({ + cls: prefix + 'mask' + ((transparent !== false) ? '' : (' ' + prefix + 'mask-gray')), + html: msg ? ('
    ' + msg + '
    ') : '' + }); + + size = me.getSize(); + + data.mask = mask; + + if (dom === document.body) { + size.height = window.innerHeight; + if (me.orientationHandler) { + Ext.EventManager.unOrientationChange(me.orientationHandler, me); + } + + me.orientationHandler = function() { + size = me.getSize(); + size.height = window.innerHeight; + mask.setSize(size); + }; + + Ext.EventManager.onOrientationChange(me.orientationHandler, me); + } + mask.setSize(size); + if (Ext.is.iPad) { + Ext.repaint(); + } + }, + + /** + * Removes a previously applied mask. + */ + unmask: function() { + var me = this, + data = (me.$cache || me.getCache()).data, + mask = data.mask, + prefix = Ext.baseCSSPrefix; + + if (mask) { + mask.remove(); + delete data.mask; + } + me.removeCls([prefix + 'masked', prefix + 'masked-relative']); + + if (me.dom === document.body) { + Ext.EventManager.unOrientationChange(me.orientationHandler, me); + delete me.orientationHandler; + } + } + }); + + /** + * Creates mappings for 'margin-before' to 'marginLeft' (etc.) given the output + * map and an ordering pair (e.g., ['left', 'right']). The ordering pair is in + * before/after order. + */ + Element.populateStyleMap = function (map, order) { + var baseStyles = ['margin-', 'padding-', 'border-width-'], + beforeAfter = ['before', 'after'], + index, style, name, i; + + for (index = baseStyles.length; index--; ) { + for (i = 2; i--; ) { + style = baseStyles[index] + beforeAfter[i]; // margin-before + // ex: maps margin-before and marginBefore to marginLeft + map[Element.normalize(style)] = map[style] = { + name: Element.normalize(baseStyles[index] + order[i]) + }; + } + } + }; + + Ext.onReady(function () { + var supports = Ext.supports, + styleHooks, + colorStyles, i, name, camel; + + function fixTransparent (dom, el, inline, style) { + var value = style[this.name] || ''; + return transparentRe.test(value) ? 'transparent' : value; + } + + function fixRightMargin (dom, el, inline, style) { + var result = style.marginRight, + domStyle, display; + + // Ignore cases when the margin is correctly reported as 0, the bug only shows + // numbers larger. + if (result != '0px') { + domStyle = dom.style; + display = domStyle.display; + domStyle.display = 'inline-block'; + result = (inline ? style : dom.ownerDocument.defaultView.getComputedStyle(dom, null)).marginRight; + domStyle.display = display; + } + + return result; + } + + function fixRightMarginAndInputFocus (dom, el, inline, style) { + var result = style.marginRight, + domStyle, cleaner, display; + + if (result != '0px') { + domStyle = dom.style; + cleaner = Element.getRightMarginFixCleaner(dom); + display = domStyle.display; + domStyle.display = 'inline-block'; + result = (inline ? style : dom.ownerDocument.defaultView.getComputedStyle(dom, '')).marginRight; + domStyle.display = display; + cleaner(); + } + + return result; + } + + styleHooks = Element.prototype.styleHooks; + + // Populate the LTR flavors of margin-before et.al. (see Ext.rtl.AbstractElement): + Element.populateStyleMap(styleHooks, ['left', 'right']); + + // Ext.supports needs to be initialized (we run very early in the onready sequence), + // but it is OK to call Ext.supports.init() more times than necessary... + if (supports.init) { + supports.init(); + } + + // Fix bug caused by this: https://bugs.webkit.org/show_bug.cgi?id=13343 + if (!supports.RightMargin) { + styleHooks.marginRight = styleHooks['margin-right'] = { + name: 'marginRight', + // TODO - Touch should use conditional compilation here or ensure that the + // underlying Ext.supports flags are set correctly... + get: (supports.DisplayChangeInputSelectionBug || supports.DisplayChangeTextAreaSelectionBug) ? + fixRightMarginAndInputFocus : fixRightMargin + }; + } + + if (!supports.TransparentColor) { + colorStyles = ['background-color', 'border-color', 'color', 'outline-color']; + for (i = colorStyles.length; i--; ) { + name = colorStyles[i]; + camel = Element.normalize(name); + + styleHooks[name] = styleHooks[camel] = { + name: camel, + get: fixTransparent + }; + } + } + }); +}()); + +/** + * @class Ext.dom.AbstractElement + */ +Ext.dom.AbstractElement.override({ + /** + * 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/String/HTMLElement/Ext.Element} [limit] + * The max depth to search as a number or an element which causes the upward traversal to stop + * and is not considered for inclusion as the result. (defaults to 50 || document.documentElement) + * @param {Boolean} [returnEl=false] 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, limit, returnEl) { + var target = this.dom, + topmost = document.documentElement, + depth = 0, + stopEl; + + limit = limit || 50; + if (isNaN(limit)) { + stopEl = Ext.getDom(limit); + limit = Number.MAX_VALUE; + } + while (target && target.nodeType == 1 && depth < limit && target != topmost && target != stopEl) { + if (Ext.DomQuery.is(target, simpleSelector)) { + return returnEl ? Ext.get(target) : target; + } + depth++; + target = target.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/String/HTMLElement/Ext.Element} [limit] + * The max depth to search as a number or an element which causes the upward traversal to stop + * and is not considered for inclusion as the result. (defaults to 50 || document.documentElement) + * @param {Boolean} [returnEl=false] 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, limit, returnEl) { + var p = Ext.fly(this.dom.parentNode, '_internal'); + return p ? p.findParent(simpleSelector, limit, 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.dom.Element. + * @param {String} selector The simple selector to test + * @param {Number/String/HTMLElement/Ext.Element} [limit] + * The max depth to search as a number or an element which causes the upward traversal to stop + * and is not considered for inclusion as the result. (defaults to 50 || document.documentElement) + * @return {Ext.Element} The matching DOM node (or null if no match was found) + */ + up: function(simpleSelector, limit) { + return this.findParentNode(simpleSelector, limit, true); + }, + + /** + * Creates a {@link Ext.CompositeElement} for child nodes based on the passed CSS selector (the selector should not contain an id). + * @param {String} selector The CSS selector + * @return {Ext.CompositeElement} The composite element + */ + select: function(selector, composite) { + return Ext.dom.Element.select(selector, this.dom, composite); + }, + + /** + * Selects child nodes based on the passed CSS selector (the selector should not contain an id). + * @param {String} selector The CSS selector + * @return {HTMLElement[]} An array of the matched nodes + */ + query: function(selector) { + return Ext.DomQuery.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=false] True to return the DOM node instead of Ext.dom.Element + * @return {HTMLElement/Ext.dom.Element} The child Ext.dom.Element (or DOM node if returnDom = true) + */ + down: function(selector, returnDom) { + var n = Ext.DomQuery.selectNode(selector, this.dom); + return returnDom ? n : Ext.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=false] True to return the DOM node instead of Ext.dom.Element. + * @return {HTMLElement/Ext.dom.Element} The child Ext.dom.Element (or DOM node if returnDom = true) + */ + child: function(selector, returnDom) { + var node, + me = this, + id; + + // Pull the ID from the DOM (Ext.id also ensures that there *is* an ID). + // If this object is a Flyweight, it will not have an ID + id = Ext.id(me.dom); + // Escape . or : + id = id.replace(/[\.:]/g, "\\$0"); + node = Ext.DomQuery.selectNode('#' + id + " > " + selector, me.dom); + return returnDom ? node : Ext.get(node); + }, + + /** + * Gets the parent node for this element, optionally chaining up trying to match a selector + * @param {String} [selector] Find a parent node that matches the passed simple selector + * @param {Boolean} [returnDom=false] True to return a raw dom node instead of an Ext.dom.Element + * @return {Ext.dom.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] Find the next sibling that matches the passed simple selector + * @param {Boolean} [returnDom=false] True to return a raw dom node instead of an Ext.dom.Element + * @return {Ext.dom.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] Find the previous sibling that matches the passed simple selector + * @param {Boolean} [returnDom=false] True to return a raw dom node instead of an Ext.dom.Element + * @return {Ext.dom.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] Find the next sibling that matches the passed simple selector + * @param {Boolean} [returnDom=false] True to return a raw dom node instead of an Ext.dom.Element + * @return {Ext.dom.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] Find the previous sibling that matches the passed simple selector + * @param {Boolean} [returnDom=false] True to return a raw dom node instead of an Ext.dom.Element + * @return {Ext.dom.Element/HTMLElement} The last child or null + */ + last: function(selector, returnDom) { + return this.matchNode('previousSibling', 'lastChild', selector, returnDom); + }, + + matchNode: function(dir, start, selector, returnDom) { + if (!this.dom) { + return null; + } + + var n = this.dom[start]; + while (n) { + if (n.nodeType == 1 && (!selector || Ext.DomQuery.is(n, selector))) { + return !returnDom ? Ext.get(n) : n; + } + n = n[dir]; + } + return null; + }, + + isAncestor: function(element) { + return this.self.isAncestor.call(this.self, this.dom, element); + } +}); + +/** + * @class Ext.dom.Helper + * @extends Ext.dom.AbstractHelper + * @alternateClassName Ext.DomHelper + * @alternateClassName Ext.core.DomHelper + * @singleton + * + * 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: + * + * - **tag** - The tag name of the element. + * - **children** or **cn** - An array of the same kind of element definition objects to be created and appended. + * These can be nested as deep as you want. + * - **cls** - The class attribute of the element. This will end up being either the "class" attribute on a HTML + * fragment or className for a DOM node, depending on whether DomHelper is using fragments or DOM. + * - **html** - The innerHTML for the element. + * + * **NOTE:** For other arbitrary attributes, the value will currently **not** be automatically HTML-escaped prior to + * building the element's HTML string. This means that if your attribute value contains special characters that would + * not normally be allowed in a double-quoted attribute value, you **must** manually HTML-encode it beforehand (see + * {@link Ext.String#htmlEncode}) or risk malformed HTML being created. This behavior may change in a future release. + * + * # Insertion methods + * + * Commonly used insertion methods: + * + * - **{@link #append}** + * - **{@link #insertBefore}** + * - **{@link #insertAfter}** + * - **{@link #overwrite}** + * - **{@link #createTemplate}** + * - **{@link #insertHtml}** + * + * # 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.edspencer.net/', "Ed'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.edspencer.net/', + * text: "Ed'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 + * + */ +(function() { + +// kill repeat to save bytes +var afterbegin = 'afterbegin', + afterend = 'afterend', + beforebegin = 'beforebegin', + beforeend = 'beforeend', + ts = '', + te = '
    ', + tbs = ts+'', + tbe = ''+te, + trs = tbs + '', + tre = ''+tbe, + detachedDiv = document.createElement('div'), + bbValues = ['BeforeBegin', 'previousSibling'], + aeValues = ['AfterEnd', 'nextSibling'], + bb_ae_PositionHash = { + beforebegin: bbValues, + afterend: aeValues + }, + fullPositionHash = { + beforebegin: bbValues, + afterend: aeValues, + afterbegin: ['AfterBegin', 'firstChild'], + beforeend: ['BeforeEnd', 'lastChild'] + }; + +Ext.define('Ext.dom.Helper', { + extend: 'Ext.dom.AbstractHelper', + + tableRe: /^table|tbody|tr|td$/i, + + tableElRe: /td|tr|tbody/i, + + /** + * @property {Boolean} useDom + * True to force the use of DOM instead of html fragments. + */ + useDom : false, + + /** + * 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: function(o, parentNode){ + var el, + doc = document, + useSet, + attr, + val, + cn, + i, l; + + if (Ext.isArray(o)) { // Allow Arrays of siblings to be inserted + el = doc.createDocumentFragment(); // in one shot using a DocumentFragment + for (i = 0, l = o.length; i < l; i++) { + this.createDom(o[i], el); + } + } else if (typeof o == 'string') { // Allow a string as a child spec. + el = doc.createTextNode(o); + } else { + el = doc.createElement(o.tag || 'div'); + useSet = !!el.setAttribute; // In IE some elements don't have setAttribute + for (attr in o) { + if (!this.confRe.test(attr)) { + val = o[attr]; + if (attr == 'cls') { + el.className = val; + } else { + if (useSet) { + el.setAttribute(attr, val); + } else { + el[attr] = val; + } + } + } + } + Ext.DomHelper.applyStyles(el, o.style); + + if ((cn = o.children || o.cn)) { + this.createDom(cn, el); + } else if (o.html) { + el.innerHTML = o.html; + } + } + if (parentNode) { + parentNode.appendChild(el); + } + return el; + }, + + ieTable: function(depth, openingTags, htmlContent, closingTags){ + detachedDiv.innerHTML = [openingTags, htmlContent, closingTags].join(''); + + var i = -1, + el = detachedDiv, + ns; + + while (++i < depth) { + el = el.firstChild; + } + // If the result is multiple siblings, then encapsulate them into one fragment. + ns = el.nextSibling; + + if (ns) { + el = document.createDocumentFragment(); + while (ns) { + el.appendChild(ns); + ns = ns.nextSibling; + } + } + return el; + }, + + /** + * @private + * Nasty code for IE's broken table implementation + */ + insertIntoTable: function(tag, where, destinationEl, html) { + var node, + before, + bb = where == beforebegin, + ab = where == afterbegin, + be = where == beforeend, + ae = where == afterend; + + if (tag == 'td' && (ab || be) || !this.tableElRe.test(tag) && (bb || ae)) { + return null; + } + before = bb ? destinationEl : + ae ? destinationEl.nextSibling : + ab ? destinationEl.firstChild : null; + + if (bb || ae) { + destinationEl = destinationEl.parentNode; + } + + if (tag == 'td' || (tag == 'tr' && (be || ab))) { + node = this.ieTable(4, trs, html, tre); + } else if ((tag == 'tbody' && (be || ab)) || + (tag == 'tr' && (bb || ae))) { + node = this.ieTable(3, tbs, html, tbe); + } else { + node = this.ieTable(2, ts, html, te); + } + destinationEl.insertBefore(node, before); + return node; + }, + + /** + * @private + * Fix for IE9 createContextualFragment missing method + */ + createContextualFragment: function(html) { + var fragment = document.createDocumentFragment(), + length, childNodes; + + detachedDiv.innerHTML = html; + childNodes = detachedDiv.childNodes; + length = childNodes.length; + + // Move nodes into fragment, don't clone: http://jsperf.com/create-fragment + while (length--) { + fragment.appendChild(childNodes[0]); + } + return fragment; + }, + + applyStyles: function(el, styles) { + if (styles) { + el = Ext.fly(el); + if (typeof styles == "function") { + styles = styles.call(); + } + if (typeof styles == "string") { + styles = Ext.dom.Element.parseStyles(styles); + } + if (typeof styles == "object") { + el.setStyle(styles); + } + } + }, + + /** + * Alias for {@link #markup}. + * @inheritdoc Ext.dom.AbstractHelper#markup + */ + createHtml: function(spec) { + return this.markup(spec); + }, + + doInsert: function(el, o, returnElement, pos, sibling, append) { + + el = el.dom || Ext.getDom(el); + + var newNode; + + if (this.useDom) { + newNode = this.createDom(o, null); + + if (append) { + el.appendChild(newNode); + } + else { + (sibling == 'firstChild' ? el : el.parentNode).insertBefore(newNode, el[sibling] || el); + } + + } else { + newNode = this.insertHtml(pos, el, this.markup(o)); + } + return returnElement ? Ext.get(newNode, true) : newNode; + }, + + /** + * Creates new DOM element(s) and overwrites the contents of el with them. + * @param {String/HTMLElement/Ext.Element} el The context element + * @param {Object/String} o The DOM object spec (and children) or raw HTML blob + * @param {Boolean} [returnElement] true to return an Ext.Element + * @return {HTMLElement/Ext.Element} The new node + */ + overwrite: function(el, html, returnElement) { + var newNode; + + el = Ext.getDom(el); + html = this.markup(html); + + // IE Inserting HTML into a table/tbody/tr requires extra processing: http://www.ericvasilik.com/2006/07/code-karma.html + if (Ext.isIE && this.tableRe.test(el.tagName)) { + // Clearing table elements requires removal of all elements. + while (el.firstChild) { + el.removeChild(el.firstChild); + } + if (html) { + newNode = this.insertHtml('afterbegin', el, html); + return returnElement ? Ext.get(newNode) : newNode; + } + return null; + } + el.innerHTML = html; + return returnElement ? Ext.get(el.firstChild) : el.firstChild; + }, + + insertHtml: function(where, el, html) { + var hashVal, + range, + rangeEl, + setStart, + frag; + + where = where.toLowerCase(); + + // Has fast HTML insertion into existing DOM: http://www.w3.org/TR/html5/apis-in-html-documents.html#insertadjacenthtml + if (el.insertAdjacentHTML) { + + // IE's incomplete table implementation: http://www.ericvasilik.com/2006/07/code-karma.html + if (Ext.isIE && this.tableRe.test(el.tagName) && (frag = this.insertIntoTable(el.tagName.toLowerCase(), where, el, html))) { + return frag; + } + + if ((hashVal = fullPositionHash[where])) { + el.insertAdjacentHTML(hashVal[0], html); + return el[hashVal[1]]; + } + // if (not IE and context element is an HTMLElement) or TextNode + } else { + // we cannot insert anything inside a textnode so... + if (el.nodeType === 3) { + where = where === 'afterbegin' ? 'beforebegin' : where; + where = where === 'beforeend' ? 'afterend' : where; + } + range = Ext.supports.CreateContextualFragment ? el.ownerDocument.createRange() : undefined; + setStart = 'setStart' + (this.endRe.test(where) ? 'After' : 'Before'); + if (bb_ae_PositionHash[where]) { + if (range) { + range[setStart](el); + frag = range.createContextualFragment(html); + } else { + frag = this.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) { + if (range) { + range[setStart](el[rangeEl]); + frag = range.createContextualFragment(html); + } else { + frag = this.createContextualFragment(html); + } + + if (where == afterbegin) { + el.insertBefore(frag, el.firstChild); + } else { + el.appendChild(frag); + } + } else { + el.innerHTML = html; + } + return el[rangeEl]; + } + } + Ext.Error.raise({ + sourceClass: 'Ext.DomHelper', + sourceMethod: 'insertHtml', + htmlToInsert: html, + targetElement: el, + msg: 'Illegal insertion point reached: "' + where + '"' + }); + }, + + /** + * 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 = this.markup(o); + return new Ext.Template(html); + } + +}, function() { + Ext.ns('Ext.core'); + Ext.DomHelper = Ext.core.DomHelper = new this; +}); + + +}()); + +/* + * This is code is also distributed under MIT license for use + * with jQuery and prototype JavaScript libraries. + */ +/** + * @class Ext.dom.Query + * @alternateClassName Ext.DomQuery + * @alternateClassName Ext.core.DomQuery + * @singleton + * + * 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][1], 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: + * + * - **`*`** any element + * - **`E`** an element with the tag E + * - **`E F`** All descendent elements of E that have the tag F + * - **`E > F`** or **E/F** all direct children elements of E that have the tag F + * - **`E + F`** all elements with the tag F that are immediately preceded by an element with the tag E + * - **`E ~ F`** all elements with the tag F that are preceded by a sibling element with the tag E + * + * ## Attribute Selectors: + * + * The use of `@` and quotes are optional. For example, `div[@foo='bar']` is also a valid attribute selector. + * + * - **`E[foo]`** has an attribute "foo" + * - **`E[foo=bar]`** has an attribute "foo" that equals "bar" + * - **`E[foo^=bar]`** has an attribute "foo" that starts with "bar" + * - **`E[foo$=bar]`** has an attribute "foo" that ends with "bar" + * - **`E[foo*=bar]`** has an attribute "foo" that contains the substring "bar" + * - **`E[foo%=2]`** has an attribute "foo" that is evenly divisible by 2 + * - **`E[foo!=bar]`** attribute "foo" does not equal "bar" + * + * ## Pseudo Classes: + * + * - **`E:first-child`** E is the first child of its parent + * - **`E:last-child`** E is the last child of its parent + * - **`E:nth-child(_n_)`** E is the _n_th child of its parent (1 based as per the spec) + * - **`E:nth-child(odd)`** E is an odd child of its parent + * - **`E:nth-child(even)`** E is an even child of its parent + * - **`E:only-child`** E is the only child of its parent + * - **`E:checked`** E is an element that is has a checked attribute that is true (e.g. a radio or checkbox) + * - **`E:first`** the first E in the resultset + * - **`E:last`** the last E in the resultset + * - **`E:nth(_n_)`** the _n_th E in the resultset (1 based) + * - **`E:odd`** shortcut for :nth-child(odd) + * - **`E:even`** shortcut for :nth-child(even) + * - **`E:contains(foo)`** E's innerHTML contains the substring "foo" + * - **`E:nodeValue(foo)`** E contains a textNode with a nodeValue that equals "foo" + * - **`E:not(S)`** an E element that does not match simple selector S + * - **`E:has(S)`** an E element that has a descendent that matches simple selector S + * - **`E:next(S)`** an E element whose next sibling matches simple selector S + * - **`E:prev(S)`** an E element whose previous sibling matches simple selector S + * - **`E:any(S1|S2|S2)`** an E element which matches any of the simple selectors S1, S2 or S3 + * + * ## CSS Value Selectors: + * + * - **`E{display=none}`** css value "display" that equals "none" + * - **`E{display^=none}`** css value "display" that starts with "none" + * - **`E{display$=none}`** css value "display" that ends with "none" + * - **`E{display*=none}`** css value "display" that contains the substring "none" + * - **`E{display%=2}`** css value "display" that is evenly divisible by 2 + * - **`E{display!=none}`** css value "display" that does not equal "none" + * + * [1]: http://www.w3.org/TR/2005/WD-css3-selectors-20051215/#selectors + */ +Ext.ns('Ext.core'); + +Ext.dom.Query = Ext.core.DomQuery = 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/, + startIdRe = /^\s*\#/, + // This is for IE MSXML which does not support expandos. + // IE runs the same speed using setAttribute, however FF slows way down + // and Safari completely fails so they need to continue to use expandos. + isIE = window.ActiveXObject ? true : false, + key = 30803, + longHex = /\\([0-9a-fA-F]{6})/g, + shortHex = /\\([0-9a-fA-F]{1,6})\s{0,1}/g, + nonHex = /\\([^0-9a-fA-F]{1})/g, + escapes = /\\/g, + num, hasEscapes, + + // replaces a long hex regex match group with the appropriate ascii value + // $args indicate regex match pos + longHexToChar = function($0, $1) { + return String.fromCharCode(parseInt($1, 16)); + }, + + // converts a shortHex regex match to the long form + shortToLongHex = function($0, $1) { + while ($1.length < 6) { + $1 = '0' + $1; + } + return '\\' + $1; + }, + + // converts a single char escape to long escape form + charToLongHex = function($0, $1) { + num = $1.charCodeAt(0).toString(16); + if (num.length === 1) { + num = '0' + num; + } + return '\\0000' + num; + }, + + // Un-escapes an input selector string. Assumes all escape sequences have been + // normalized to the css '\\0000##' 6-hex-digit style escape sequence : + // will not handle any other escape formats + unescapeCssSelector = function (selector) { + return (hasEscapes) + ? selector.replace(longHex, longHexToChar) + : selector; + }; + + // this eval is stop the compressor from + // renaming the variable to something shorter + eval("var batch = 30803;"); + + // Retrieve the child node from a particular + // parent at the specified index. + function child(parent, index){ + var i = 0, + n = parent.firstChild; + while(n){ + if(n.nodeType == 1){ + if(++i == index){ + return n; + } + } + n = n.nextSibling; + } + return null; + } + + // retrieve the next element node + function next(n){ + while((n = n.nextSibling) && n.nodeType != 1); + return n; + } + + // retrieve the previous element node + function prev(n){ + while((n = n.previousSibling) && n.nodeType != 1); + return n; + } + + // Mark each child node with a nodeIndex skipping and + // removing empty text nodes. + function children(parent){ + var n = parent.firstChild, + nodeIndex = -1, + nextNode; + while(n){ + nextNode = n.nextSibling; + // clean worthless empty nodes. + if(n.nodeType == 3 && !nonSpace.test(n.nodeValue)){ + parent.removeChild(n); + }else{ + // add an expando nodeIndex + n.nodeIndex = ++nodeIndex; + } + n = nextNode; + } + return this; + } + + // nodeSet - array of nodes + // cls - CSS Class + function byClassName(nodeSet, cls){ + cls = unescapeCssSelector(cls); + if(!cls){ + return nodeSet; + } + var result = [], ri = -1, + i, ci; + for(i = 0, ci; ci = nodeSet[i]; i++){ + if((' '+ci.className+' ').indexOf(cls) != -1){ + result[++ri] = ci; + } + } + return result; + } + + function attrValue(n, attr){ + // if its an array, use the first node. + if(!n.tagName && typeof n.length != "undefined"){ + n = n[0]; + } + if(!n){ + return null; + } + + if(attr == "for"){ + return n.htmlFor; + } + if(attr == "class" || attr == "className"){ + return n.className; + } + return n.getAttribute(attr) || n[attr]; + + } + + + // ns - nodes + // mode - false, /, >, +, ~ + // tagName - defaults to "*" + function getNodes(ns, mode, tagName){ + var result = [], ri = -1, cs, + i, ni, j, ci, cn, utag, n, cj; + if(!ns){ + return result; + } + tagName = tagName || "*"; + // convert to array + if(typeof ns.getElementsByTagName != "undefined"){ + ns = [ns]; + } + + // no mode specified, grab all elements by tagName + // at any depth + if(!mode){ + for(i = 0, ni; ni = ns[i]; i++){ + cs = ni.getElementsByTagName(tagName); + for(j = 0, ci; ci = cs[j]; j++){ + result[++ri] = ci; + } + } + // Direct Child mode (/ or >) + // E > F or E/F all direct children elements of E that have the tag + } else if(mode == "/" || mode == ">"){ + utag = tagName.toUpperCase(); + for(i = 0, ni, cn; ni = ns[i]; i++){ + cn = ni.childNodes; + for(j = 0, cj; cj = cn[j]; j++){ + if(cj.nodeName == utag || cj.nodeName == tagName || tagName == '*'){ + result[++ri] = cj; + } + } + } + // Immediately Preceding mode (+) + // E + F all elements with the tag F that are immediately preceded by an element with the tag E + }else if(mode == "+"){ + utag = tagName.toUpperCase(); + for(i = 0, n; n = ns[i]; i++){ + while((n = n.nextSibling) && n.nodeType != 1); + if(n && (n.nodeName == utag || n.nodeName == tagName || tagName == '*')){ + result[++ri] = n; + } + } + // Sibling mode (~) + // E ~ F all elements with the tag F that are preceded by a sibling element with the tag E + }else if(mode == "~"){ + utag = tagName.toUpperCase(); + for(i = 0, n; n = ns[i]; i++){ + while((n = n.nextSibling)){ + if (n.nodeName == utag || n.nodeName == tagName || tagName == '*'){ + result[++ri] = n; + } + } + } + } + return result; + } + + function concat(a, b){ + if(b.slice){ + return a.concat(b); + } + for(var i = 0, l = b.length; i < l; i++){ + a[a.length] = b[i]; + } + return a; + } + + function byTag(cs, tagName){ + if(cs.tagName || cs == document){ + cs = [cs]; + } + if(!tagName){ + return cs; + } + var result = [], ri = -1, + i, ci; + tagName = tagName.toLowerCase(); + for(i = 0, ci; ci = cs[i]; i++){ + if(ci.nodeType == 1 && ci.tagName.toLowerCase() == tagName){ + result[++ri] = ci; + } + } + return result; + } + + function byId(cs, id){ + id = unescapeCssSelector(id); + if(cs.tagName || cs == document){ + cs = [cs]; + } + if(!id){ + return cs; + } + var result = [], ri = -1, + i, ci; + for(i = 0, ci; ci = cs[i]; i++){ + if(ci && ci.id == id){ + result[++ri] = ci; + return result; + } + } + return result; + } + + // operators are =, !=, ^=, $=, *=, %=, |= and ~= + // custom can be "{" + function byAttribute(cs, attr, value, op, custom){ + var result = [], + ri = -1, + useGetStyle = custom == "{", + fn = Ext.DomQuery.operators[op], + a, + xml, + hasXml, + i, ci; + + value = unescapeCssSelector(value); + + for(i = 0, ci; ci = cs[i]; i++){ + // skip non-element nodes. + if(ci.nodeType != 1){ + continue; + } + // only need to do this for the first node + if(!hasXml){ + xml = Ext.DomQuery.isXml(ci); + hasXml = true; + } + + // we only need to change the property names if we're dealing with html nodes, not XML + 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"){ + // getAttribute href bug + // http://www.glennjones.net/Post/809/getAttributehrefbug.htm + a = ci.getAttribute("href", 2); + } else{ + a = ci.getAttribute(attr); + } + }else{ + a = ci.getAttribute(attr); + } + if((fn && fn(a, value)) || (!fn && a)){ + result[++ri] = ci; + } + } + return result; + } + + function byPseudo(cs, name, value){ + value = unescapeCssSelector(value); + return Ext.DomQuery.pseudos[name](cs, value); + } + + function nodupIEXml(cs){ + var d = ++key, + r, + i, len, c; + cs[0].setAttribute("_nodup", d); + r = [cs[0]]; + for(i = 1, len = cs.length; i < len; i++){ + c = cs[i]; + if(!c.getAttribute("_nodup") != d){ + c.setAttribute("_nodup", d); + r[r.length] = c; + } + } + for(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, d, j; + if(!len || typeof cs.nodeType != "undefined" || len == 1){ + return cs; + } + if(isIE && typeof cs[0].selectSingleNode != "undefined"){ + return nodupIEXml(cs); + } + d = ++key; + cs[0]._nodup = d; + for(i = 1; c = cs[i]; i++){ + if(c._nodup != d){ + c._nodup = d; + }else{ + r = []; + for(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 = [], + i, len; + for(i = 0, len = c1.length; i < len; i++){ + c1[i].setAttribute("_qdiff", d); + } + for(i = 0, len = c2.length; i < len; i++){ + if(c2[i].getAttribute("_qdiff") != d){ + r[r.length] = c2[i]; + } + } + for(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 = [], + i, len; + if(!len1){ + return c2; + } + if(isIE && typeof c1[0].selectSingleNode != "undefined"){ + return quickDiffIEXml(c1, c2); + } + for(i = 0; i < len1; i++){ + c1[i]._qdiff = d; + } + for(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){ + id = unescapeCssSelector(id); + var d = root.ownerDocument || root; + return d.getElementById(id); + } + ns = getNodes(ns, mode, "*"); + return byId(ns, id); + } + + return { + getStyle : function(el, name){ + return Ext.fly(el).getStyle(name); + }, + /** + * Compiles a selector/xpath query into a reusable function. The returned function + * takes one parameter "root" (optional), which is the context node from where the query should start. + * @param {String} selector The selector/xpath query + * @param {String} [type="select"] Either "select" or "simple" for a simple selector match + * @return {Function} + */ + compile : function(path, type){ + type = type || "select"; + + // setup fn preamble + var fn = ["var f = function(root){\n var mode; ++batch; var n = root || document;\n"], + mode, + lastPath, + matchers = Ext.DomQuery.matchers, + matchersLn = matchers.length, + modeMatch, + // accept leading mode switch + lmode = path.match(modeRe), + tokenMatch, matched, j, t, m; + + hasEscapes = (path.indexOf('\\') > -1); + if (hasEscapes) { + path = path + .replace(shortHex, shortToLongHex) + .replace(nonHex, charToLongHex) + .replace(escapes, '\\\\'); // double the '\' for js compilation + } + + if(lmode && lmode[1]){ + fn[fn.length] = 'mode="'+lmode[1].replace(trimRe, "")+'";'; + path = path.replace(lmode[1], ""); + } + + // strip leading slashes + while(path.substr(0, 1)=="/"){ + path = path.substr(1); + } + + while(path && lastPath != path){ + lastPath = path; + tokenMatch = path.match(tagTokenRe); + if(type == "select"){ + if(tokenMatch){ + // ID Selector + if(tokenMatch[1] == "#"){ + fn[fn.length] = 'n = quickId(n, mode, root, "'+tokenMatch[2]+'");'; + }else{ + fn[fn.length] = 'n = getNodes(n, mode, "'+tokenMatch[2]+'");'; + } + path = path.replace(tokenMatch[0], ""); + }else if(path.substr(0, 1) != '@'){ + fn[fn.length] = 'n = getNodes(n, mode, "*");'; + } + // type of "simple" + }else{ + if(tokenMatch){ + if(tokenMatch[1] == "#"){ + fn[fn.length] = 'n = byId(n, "'+tokenMatch[2]+'");'; + }else{ + fn[fn.length] = 'n = byTag(n, "'+tokenMatch[2]+'");'; + } + path = path.replace(tokenMatch[0], ""); + } + } + while(!(modeMatch = path.match(modeRe))){ + matched = false; + for(j = 0; j < matchersLn; j++){ + t = matchers[j]; + m = path.match(t.re); + if(m){ + fn[fn.length] = t.select.replace(tplRe, function(x, i){ + return m[i]; + }); + path = path.replace(m[0], ""); + matched = true; + break; + } + } + // prevent infinite loop on bad selector + if(!matched){ + Ext.Error.raise({ + sourceClass: 'Ext.DomQuery', + sourceMethod: 'compile', + msg: 'Error parsing selector. Parsing failed at "' + path + '"' + }); + } + } + if(modeMatch[1]){ + fn[fn.length] = 'mode="'+modeMatch[1].replace(trimRe, "")+'";'; + path = path.replace(modeMatch[1], ""); + } + } + // close fn out + fn[fn.length] = "return nodup(n);\n}"; + + // eval fn and return it + eval(fn.join("")); + return f; + }, + + /** + * Selects an array of DOM nodes using JavaScript-only implementation. + * + * Use {@link #select} to take advantage of browsers built-in support for CSS selectors. + * @param {String} selector The selector/xpath query (can be a comma separated list of selectors) + * @param {HTMLElement/String} [root=document] The start of the query. + * @return {HTMLElement[]} An Array of DOM elements which match the selector. If there are + * no matches, and empty Array is returned. + */ + jsSelect: function(path, root, type){ + // set root to doc if not specified. + root = root || document; + + if(typeof root == "string"){ + root = document.getElementById(root); + } + var paths = path.split(","), + results = [], + i, len, subPath, result; + + // loop over each selector + for(i = 0, len = paths.length; i < len; i++){ + subPath = paths[i].replace(trimRe, ""); + // compile and place in cache + if(!cache[subPath]){ + cache[subPath] = Ext.DomQuery.compile(subPath, type); + if(!cache[subPath]){ + Ext.Error.raise({ + sourceClass: 'Ext.DomQuery', + sourceMethod: 'jsSelect', + msg: subPath + ' is not a valid selector' + }); + } + } + result = cache[subPath](root); + if(result && result != document){ + results = results.concat(result); + } + } + + // if there were multiple selectors, make sure dups + // are eliminated + if(paths.length > 1){ + return nodup(results); + } + return results; + }, + + isXml: function(el) { + var docEl = (el ? el.ownerDocument || el : 0).documentElement; + return docEl ? docEl.nodeName !== "HTML" : false; + }, + + /** + * Selects an array of DOM nodes by CSS/XPath selector. + * + * Uses [document.querySelectorAll][0] if browser supports that, otherwise falls back to + * {@link Ext.dom.Query#jsSelect} to do the work. + * + * Aliased as {@link Ext#query}. + * + * [0]: https://developer.mozilla.org/en/DOM/document.querySelectorAll + * + * @param {String} path The selector/xpath query + * @param {HTMLElement} [root=document] The start of the query. + * @return {HTMLElement[]} An array of DOM elements (not a NodeList as returned by `querySelectorAll`). + * @param {String} [type="select"] Either "select" or "simple" for a simple selector match (only valid when + * used when the call is deferred to the jsSelect method) + * @method + */ + select : document.querySelectorAll ? function(path, root, type) { + root = root || document; + if (!Ext.DomQuery.isXml(root)) { + try { + /* + * This checking here is to "fix" the behaviour of querySelectorAll + * for non root document queries. The way qsa works is intentional, + * however it's definitely not the expected way it should work. + * When descendant selectors are used, only the lowest selector must be inside the root! + * More info: http://ejohn.org/blog/thoughts-on-queryselectorall/ + * So we create a descendant selector by prepending the root's ID, and query the parent node. + * UNLESS the root has no parent in which qsa will work perfectly. + * + * We only modify the path for single selectors (ie, no multiples), + * without a full parser it makes it difficult to do this correctly. + */ + if (root.parentNode && (root.nodeType !== 9) && path.indexOf(',') === -1 && !startIdRe.test(path)) { + path = '#' + Ext.escapeId(Ext.id(root)) + ' ' + path; + root = root.parentNode; + } + return Ext.Array.toArray(root.querySelectorAll(path)); + } + catch (e) { + } + } + return Ext.DomQuery.jsSelect.call(this, path, root, type); + } : function(path, root, type) { + return Ext.DomQuery.jsSelect.call(this, path, root, type); + }, + + /** + * Selects a single element. + * @param {String} selector The selector/xpath query + * @param {HTMLElement} [root=document] The start of the query. + * @return {HTMLElement} 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 {HTMLElement} [root=document] The start of the query. + * @param {String} [defaultValue] When specified, this is return as empty value. + * @return {String} + */ + selectValue : function(path, root, defaultValue){ + path = path.replace(trimRe, ""); + if(!valueCache[path]){ + valueCache[path] = Ext.DomQuery.compile(path, "select"); + } + var n = valueCache[path](root), v; + n = n[0] ? n[0] : n; + + // overcome a limitation of maximum textnode size + // Rumored to potentially crash IE6 but has not been confirmed. + // http://reference.sitepoint.com/javascript/Node/normalize + // https://developer.mozilla.org/En/DOM/Node.normalize + if (typeof n.normalize == 'function') { + n.normalize(); + } + + v = (n && n.firstChild ? n.firstChild.nodeValue : null); + return ((v === null||v === undefined||v==='') ? defaultValue : v); + }, + + /** + * Selects the value of a node, parsing integers and floats. + * Returns the defaultValue, or 0 if none is specified. + * @param {String} selector The selector/xpath query + * @param {HTMLElement} [root=document] The start of the query. + * @param {Number} [defaultValue] When specified, this is return as empty value. + * @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/HTMLElement[]} 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 {HTMLElement[]} 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 {HTMLElement[]} An Array of DOM elements which match the selector. If there are no matches, and empty + * Array is returned. + */ + filter : function(els, ss, nonMatches){ + ss = ss.replace(trimRe, ""); + if(!simpleCache[ss]){ + simpleCache[ss] = Ext.DomQuery.compile(ss, "simple"); + } + var result = simpleCache[ss](els); + return nonMatches ? quickDiff(result, els) : result; + }, + + /** + * Collection of matching regular expressions and code snippets. + * Each capture group within `()` will be replace the `{}` in the select + * statement as specified by their index. + */ + matchers : [{ + re: /^\.([\w\-\\]+)/, + select: 'n = byClassName(n, " {1} ");' + }, { + re: /^\:([\w\-]+)(?:\(((?:[^\s>\/]*|.*?))\))?/, + select: 'n = byPseudo(n, "{1}", "{2}");' + },{ + re: /^(?:([\[\{])(?:@)?([\w\-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]\}])/, + select: 'n = byAttribute(n, "{2}", "{4}", "{3}", "{1}");' + }, { + re: /^#([\w\-\\]+)/, + select: 'n = byId(n, "{1}");' + },{ + re: /^@([\w\-]+)/, + select: 'return {firstChild:{nodeValue:attrValue(n, "{1}")}};' + } + ], + + /** + * Collection of operator comparison functions. + * The default operators are `=`, `!=`, `^=`, `$=`, `*=`, `%=`, `|=` and `~=`. + * New operators can be added as long as the match the format *c*`=` where *c* + * is any character other than space, `>`, or `<`. + */ + 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: + * + * - **c** : Array + * An Array of DOM elements to filter. + * + * - **v** : String + * The argument (if any) supplied in the selector. + * + * 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, + i, ci; + for(i = 0; (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, + i, ci; + for(i = 0; (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, + i, n, j, cn, pn; + for(i = 0; n = c[i]; i++){ + pn = n.parentNode; + if (batch != pn._batch) { + j = 0; + for(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, + i, ci; + for(i = 0; ci = c[i]; i++){ + if(!prev(ci) && !next(ci)){ + r[++ri] = ci; + } + } + return r; + }, + + "empty" : function(c){ + var r = [], ri = -1, + i, ci, cns, j, cn, empty; + for(i = 0, ci; ci = c[i]; i++){ + cns = ci.childNodes; + j = 0; + 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, + i, ci; + for(i = 0; ci = c[i]; i++){ + if((ci.textContent||ci.innerText||ci.text||'').indexOf(v) != -1){ + r[++ri] = ci; + } + } + return r; + }, + + "nodeValue" : function(c, v){ + var r = [], ri = -1, + i, ci; + for(i = 0; ci = c[i]; i++){ + if(ci.firstChild && ci.firstChild.nodeValue == v){ + r[++ri] = ci; + } + } + return r; + }, + + "checked" : function(c){ + var r = [], ri = -1, + i, ci; + for(i = 0; 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, + i, ci, j; + for(i = 0; ci = c[i]; i++){ + for(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, + i, ci; + for(i = 0; 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, + i, ci, n; + for(i = 0; ci = c[i]; i++){ + 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, + i, ci, n; + for(i = 0; ci = c[i]; i++){ + n = prev(ci); + if(n && is(n, ss)){ + r[++ri] = ci; + } + } + return r; + } + } + }; +}()); + +/** + * Shorthand of {@link Ext.dom.Query#select} + * @member Ext + * @method query + * @inheritdoc Ext.dom.Query#select + */ +Ext.query = Ext.DomQuery.select; + + +/** + * @class Ext.dom.Element + * @alternateClassName Ext.Element + * @alternateClassName Ext.core.Element + * @extend Ext.dom.AbstractElement + * + * 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.Anim} 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. Some older browsers + * may not support the full range of events. Which events are supported is beyond the control of Ext JS. + * + * 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.Anim} animation options specific to Fx effects. The supported Element animation configuration options + * are: + * + * Option Default Description + * --------- -------- --------------------------------------------- + * {@link Ext.fx.Anim#duration duration} .35 The duration of the animation in seconds + * {@link Ext.fx.Anim#easing easing} easeOut The easing method + * {@link Ext.fx.Anim#callback callback} none A function to execute when the anim completes + * {@link Ext.fx.Anim#scope scope} this The scope (this) of the callback function + * + * Usage: + * + * // Element animation options object + * var opt = { + * {@link Ext.fx.Anim#duration duration}: 1, + * {@link Ext.fx.Anim#easing easing}: 'elasticIn', + * {@link Ext.fx.Anim#callback callback}: this.foo, + * {@link Ext.fx.Anim#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(); + * } + * + * # Composite (Collections of) Elements + * + * For working with collections of Elements, see {@link Ext.CompositeElement} + * + * @constructor + * Creates new Element directly. + * @param {String/HTMLElement} element + * @param {Boolean} [forceNew] 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). + * @return {Object} + */ +(function() { + +var HIDDEN = 'hidden', + DOC = document, + VISIBILITY = "visibility", + DISPLAY = "display", + NONE = "none", + XMASKED = Ext.baseCSSPrefix + "masked", + XMASKEDRELATIVE = Ext.baseCSSPrefix + "masked-relative", + EXTELMASKMSG = Ext.baseCSSPrefix + "mask-msg", + bodyRe = /^body/i, + visFly, + + // speedy lookup for elements never to box adjust + noBoxAdjust = Ext.isStrict ? { + select: 1 + }: { + input: 1, + select: 1, + textarea: 1 + }, + + // Pseudo for use by cacheScrollValues + isScrolled = function(c) { + var r = [], ri = -1, + i, ci; + for (i = 0; ci = c[i]; i++) { + if (ci.scrollTop > 0 || ci.scrollLeft > 0) { + r[++ri] = ci; + } + } + return r; + }, + + Element = Ext.define('Ext.dom.Element', { + + extend: 'Ext.dom.AbstractElement', + + alternateClassName: ['Ext.Element', 'Ext.core.Element'], + + addUnits: function() { + return this.self.addUnits.apply(this.self, arguments); + }, + + /** + * Tries to focus the element. Any exceptions are caught and ignored. + * @param {Number} [defer] Milliseconds to defer the focus + * @return {Ext.dom.Element} this + */ + focus: function(defer, /* private */ dom) { + var me = this, + scrollTop, + body; + + dom = dom || me.dom; + body = (dom.ownerDocument || DOC).body || DOC.body; + try { + if (Number(defer)) { + Ext.defer(me.focus, defer, me, [null, dom]); + } else { + // Focusing a large element, the browser attempts to scroll as much of it into view + // as possible. We need to override this behaviour. + if (dom.offsetHeight > Element.getViewHeight()) { + scrollTop = body.scrollTop; + } + dom.focus(); + if (scrollTop !== undefined) { + body.scrollTop = scrollTop; + } + } + } catch(e) { + } + return me; + }, + + /** + * Tries to blur the element. Any exceptions are caught and ignored. + * @return {Ext.dom.Element} this + */ + blur: function() { + try { + this.dom.blur(); + } catch(e) { + } + return this; + }, + + /** + * Tests various css rules/browsers to determine if this element uses a border box + * @return {Boolean} + */ + isBorderBox: function() { + var box = Ext.isBorderBox; + if (box) { + box = !((this.dom.tagName || "").toLowerCase() in noBoxAdjust); + } + return box; + }, + + /** + * 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] The scope (`this` reference) in which the functions are executed. Defaults + * to the Element's DOM element. + * @param {Object} [options] Options for the listener. See {@link Ext.util.Observable#addListener the + * options parameter}. + * @return {Ext.dom.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 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 + */ + getAttributeNS: function(ns, name) { + return this.getAttribute(name, ns); + }, + + getAttribute: (Ext.isIE && !(Ext.isIE9 && DOC.documentMode === 9)) ? + function(name, ns) { + var d = this.dom, + type; + if (ns) { + type = typeof d[ns + ":" + name]; + if (type != 'undefined' && type != 'unknown') { + return d[ns + ":" + name] || null; + } + return null; + } + if (name === "for") { + name = "htmlFor"; + } + return d[name] || null; + } : function(name, ns) { + var d = this.dom; + if (ns) { + return d.getAttributeNS(ns, name) || d.getAttribute(ns + ":" + name); + } + return d.getAttribute(name) || d[name] || null; + }, + + /** + * When an element is moved around in the DOM, or is hidden using `display:none`, it loses layout, and therefore + * all scroll positions of all descendant elements are lost. + * + * This function caches them, and returns a function, which when run will restore the cached positions. + * In the following example, the Panel is moved from one Container to another which will cause it to lose all scroll positions: + * + * var restoreScroll = myPanel.el.cacheScrollValues(); + * myOtherContainer.add(myPanel); + * restoreScroll(); + * + * @return {Function} A function which will restore all descentant elements of this Element to their scroll + * positions recorded when this function was executed. Be aware that the returned function is a closure which has + * captured the scope of `cacheScrollValues`, so take care to derefence it as soon as not needed - if is it is a `var` + * it will drop out of scope, and the reference will be freed. + */ + cacheScrollValues: function() { + var me = this, + scrolledDescendants, + el, i, + scrollValues = [], + result = function() { + for (i = 0; i < scrolledDescendants.length; i++) { + el = scrolledDescendants[i]; + el.scrollLeft = scrollValues[i][0]; + el.scrollTop = scrollValues[i][1]; + } + }; + + if (!Ext.DomQuery.pseudos.isScrolled) { + Ext.DomQuery.pseudos.isScrolled = isScrolled; + } + scrolledDescendants = me.query(':isScrolled'); + for (i = 0; i < scrolledDescendants.length; i++) { + el = scrolledDescendants[i]; + scrollValues[i] = [el.scrollLeft, el.scrollTop]; + } + return result; + }, + + /** + * @property {Boolean} autoBoxAdjust + * True to automatically adjust width and height settings for box-model issues. + */ + autoBoxAdjust: true, + + /** + * Checks whether the element is currently visible using both visibility and display properties. + * @param {Boolean} [deep=false] True to walk the dom and see if parent elements are hidden. + * If false, the function only checks the visibility of the element itself and it may return + * `true` even though a parent is not visible. + * @return {Boolean} `true` if the element is currently visible, else `false` + */ + isVisible : function(deep) { + var me = this, + dom = me.dom, + stopNode = dom.ownerDocument.documentElement; + + if (!visFly) { + visFly = new Element.Fly(); + } + + while (dom !== stopNode) { + // We're invisible if we hit a nonexistent parentNode or a document + // fragment or computed style visibility:hidden or display:none + if (!dom || dom.nodeType === 11 || (visFly.attach(dom)).isStyle(VISIBILITY, HIDDEN) || visFly.isStyle(DISPLAY, NONE)) { + return false; + } + // Quit now unless we are being asked to check parent nodes. + if (!deep) { + break; + } + dom = dom.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] What to set display to when visible + * @return {Ext.dom.Element} this + */ + enableDisplayMode : function(display) { + var me = this; + + me.setVisibilityMode(Element.DISPLAY); + + if (!Ext.isEmpty(display)) { + (me.$cache || me.getCache()).data.originalDisplay = display; + } + + return me; + }, + + /** + * 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] A message to display in the mask + * @param {String} [msgCls] A css class to apply to the msg element + * @return {Ext.dom.Element} The mask element + */ + mask : function(msg, msgCls /* private - passed by AbstractComponent.mask to avoid the need to interrogate the DOM to get the height*/, elHeight) { + var me = this, + dom = me.dom, + setExpression = dom.style.setExpression, + data = (me.$cache || me.getCache()).data, + maskEl = data.maskEl, + maskMsg = data.maskMsg; + + if (!(bodyRe.test(dom.tagName) && me.getStyle('position') == 'static')) { + me.addCls(XMASKEDRELATIVE); + } + + // We always needs to recreate the mask since the DOM element may have been re-created + if (maskEl) { + maskEl.remove(); + } + + if (maskMsg) { + maskMsg.remove(); + } + + Ext.DomHelper.append(dom, [{ + cls : Ext.baseCSSPrefix + "mask" + }, { + cls : msgCls ? EXTELMASKMSG + " " + msgCls : EXTELMASKMSG, + cn : { + tag: 'div', + html: msg || '' + } + }]); + + maskMsg = Ext.get(dom.lastChild); + maskEl = Ext.get(maskMsg.dom.previousSibling); + data.maskMsg = maskMsg; + data.maskEl = maskEl; + + me.addCls(XMASKED); + maskEl.setDisplayed(true); + + if (typeof msg == 'string') { + maskMsg.setDisplayed(true); + maskMsg.center(me); + } else { + maskMsg.setDisplayed(false); + } + // NOTE: CSS expressions are resource intensive and to be used only as a last resort + // These expressions are removed as soon as they are no longer necessary - in the unmask method. + // In normal use cases an element will be masked for a limited period of time. + // Fix for https://sencha.jira.com/browse/EXTJSIV-19. + // IE6 strict mode and IE6-9 quirks mode takes off left+right padding when calculating width! + if (!Ext.supports.IncludePaddingInWidthCalculation && setExpression) { + maskEl.dom.style.setExpression('width', 'this.parentNode.clientWidth + "px"'); + } + + // Some versions and modes of IE subtract top+bottom padding when calculating height. + // Different versions from those which make the same error for width! + if (!Ext.supports.IncludePaddingInHeightCalculation && setExpression) { + maskEl.dom.style.setExpression('height', 'this.parentNode.' + (dom == DOC.body ? 'scrollHeight' : 'offsetHeight') + ' + "px"'); + } + // ie will not expand full height automatically + else if (Ext.isIE && !(Ext.isIE7 && Ext.isStrict) && me.getStyle('height') == 'auto') { + maskEl.setSize(undefined, elHeight || me.getHeight()); + } + return maskEl; + }, + + /** + * Hides a previously applied mask. + */ + unmask : function() { + var me = this, + data = (me.$cache || me.getCache()).data, + maskEl = data.maskEl, + maskMsg = data.maskMsg, + style; + + if (maskEl) { + style = maskEl.dom.style; + // Remove resource-intensive CSS expressions as soon as they are not required. + if (style.clearExpression) { + style.clearExpression('width'); + style.clearExpression('height'); + } + + if (maskEl) { + maskEl.remove(); + delete data.maskEl; + } + + if (maskMsg) { + maskMsg.remove(); + delete data.maskMsg; + } + + me.removeCls([XMASKED, XMASKEDRELATIVE]); + } + }, + + /** + * Returns true if this element is masked. Also re-centers any displayed message within the mask. + * @return {Boolean} + */ + isMasked : function() { + var me = this, + data = (me.$cache || me.getCache()).data, + maskEl = data.maskEl, + maskMsg = data.maskMsg, + hasMask = false; + + if (maskEl && maskEl.isVisible()) { + if (maskMsg) { + maskMsg.center(me); + } + hasMask = true; + } + return hasMask; + }, + + /** + * Creates an iframe shim for this element to keep selects and other windowed objects from + * showing through. + * @return {Ext.dom.Element} The new shim element + */ + createShim : function() { + var el = DOC.createElement('iframe'), + shim; + + el.frameBorder = '0'; + el.className = Ext.baseCSSPrefix + 'shim'; + el.src = Ext.SSL_SECURE_URL; + shim = Ext.get(this.dom.parentNode.insertBefore(el, this.dom)); + shim.autoBoxAdjust = false; + return shim; + }, + + /** + * Convenience method for constructing a KeyMap + * @param {String/Number/Number[]/Object} 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: + * @param {Number/Array} key.key + * @param {Boolean} key.shift + * @param {Boolean} key.ctrl + * @param {Boolean} key.alt + * @param {Function} fn The function to call + * @param {Object} [scope] The scope (`this` reference) in which the specified function is executed. Defaults to this Element. + * @return {Ext.util.KeyMap} The KeyMap created + */ + addKeyListener : function(key, fn, scope){ + var config; + if(typeof key != 'object' || Ext.isArray(key)){ + config = { + target: this, + key: key, + fn: fn, + scope: scope + }; + }else{ + config = { + target: this, + key : key.key, + shift : key.shift, + ctrl : key.ctrl, + alt : key.alt, + fn: fn, + scope: scope + }; + } + return new Ext.util.KeyMap(config); + }, + + /** + * Creates a KeyMap for this element + * @param {Object} config The KeyMap config. See {@link Ext.util.KeyMap} for more details + * @return {Ext.util.KeyMap} The KeyMap created + */ + addKeyMap : function(config) { + return new Ext.util.KeyMap(Ext.apply({ + target: this + }, config)); + }, + + // 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. + */ + /** + * @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. + */ + /** + * @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. + */ + /** + * @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. + */ + /** + * @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. + */ + /** + * @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. + */ + /** + * @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. + */ + /** + * @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. + */ + /** + * @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. + */ + /** + * @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. + */ + + // 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. + */ + /** + * @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. + */ + /** + * @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. + */ + + // 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. + */ + /** + * @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. + */ + /** + * @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. + */ + /** + * @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. + */ + /** + * @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. + */ + /** + * @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. + */ + + // 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. + */ + /** + * @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. + */ + /** + * @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. + */ + /** + * @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. + */ + /** + * @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. + */ + /** + * @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. + */ + + // 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. + */ + /** + * @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. + */ + /** + * @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. + */ + + // 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. + */ + /** + * @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. + */ + /** + * @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. + */ + /** + * @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. + */ + /** + * @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. + */ + /** + * @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. + */ + /** + * @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. + */ + + /** + * Appends an event handler to this element. + * + * @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: + * + * - **evt** : EventObject + * + * The {@link Ext.EventObject EventObject} describing the event. + * + * - **el** : HtmlElement + * + * The DOM element which was the target of the event. Note that this may be filtered by using the delegate option. + * + * - **o** : Object + * + * The options object from the call that setup the listener. + * + * @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: + * + * - **scope** Object : + * + * The scope (**this** reference) in which the handler function is executed. **If omitted, defaults to this + * Element.** + * + * - **delegate** String: + * + * A simple selector to filter the target or look for a descendant of the target. See below for additional details. + * + * - **stopEvent** Boolean: + * + * True to stop the event. That is stop propagation, and prevent the default action. + * + * - **preventDefault** Boolean: + * + * True to prevent the default action + * + * - **stopPropagation** Boolean: + * + * True to prevent event propagation + * + * - **normalized** Boolean: + * + * False to pass a browser event to the handler function instead of an Ext.EventObject + * + * - **target** Ext.dom.Element: + * + * Only call the handler if the event was fired on the target Element, _not_ if the event was bubbled up from a + * child node. + * + * - **delay** Number: + * + * The number of milliseconds to delay the invocation of the handler after the event fires. + * + * - **single** Boolean: + * + * True to add a handler to handle just the next firing of the event, and then remove itself. + * + * - **buffer** Number: + * + * Causes the handler to be scheduled to run in an {@link Ext.util.DelayedTask} delayed by the specified number of + * milliseconds. If the event fires again within that time, the original handler is _not_ invoked, but the new + * handler is scheduled in its place. + * + * **Combining Options** + * + * 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: + *
    + *

    paragraph one

    + *

    paragraph two

    + *

    paragraph three

    + *
    + * + * // 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.dom.Element} this + */ + on: function(eventName, fn, scope, options) { + Ext.EventManager.on(this, eventName, fn, scope || this, options); + return this; + }, + + /** + * Removes an event handler from this element. + * + * **Note**: if a *scope* was explicitly specified when {@link #on adding} the listener, + * the same scope must be specified here. + * + * Example: + * + * el.un('click', this.handlerFn); + * // or + * el.removeListener('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 #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. + * @return {Ext.dom.Element} this + */ + un: function(eventName, fn, scope) { + Ext.EventManager.un(this, eventName, fn, scope || this); + return this; + }, + + /** + * Removes all previous added listeners from this element + * @return {Ext.dom.Element} this + */ + removeAllListeners: function() { + Ext.EventManager.removeAll(this); + return this; + }, + + /** + * Recursively removes all previous added listeners from this element and its children + * @return {Ext.dom.Element} this + */ + purgeAllListeners: function() { + Ext.EventManager.purgeElement(this); + return this; + } + +}, function() { + + var EC = Ext.cache, + El = this, + AbstractElement = Ext.dom.AbstractElement, + focusRe = /a|button|embed|iframe|img|input|object|select|textarea/i, + nonSpaceRe = /\S/, + scriptTagRe = /(?:]*)?>)((\n|\r|.)*?)(?:<\/script>)/ig, + replaceScriptTagRe = /(?:)((\n|\r|.)*?)(?:<\/script>)/ig, + srcRe = /\ssrc=([\'\"])(.*?)\1/i, + typeRe = /\stype=([\'\"])(.*?)\1/i, + useDocForId = !(Ext.isIE6 || Ext.isIE7 || Ext.isIE8); + + El.boxMarkup = '
    '; + // + + // private + // Garbage collection - uncache elements/purge listeners on orphaned elements + // so we don't hold a reference and cause the browser to retain them + function garbageCollect() { + if (!Ext.enableGarbageCollector) { + clearInterval(El.collectorThreadId); + } else { + var eid, + d, + o, + t; + + for (eid in EC) { + if (!EC.hasOwnProperty(eid)) { + continue; + } + + o = EC[eid]; + + // Skip document and window elements + if (o.skipGarbageCollection) { + continue; + } + + d = o.dom; + + // Should always have a DOM node + if (!d) { + Ext.Error.raise('Missing DOM node in element garbage collection: ' + eid); + } + + // Check that document and window elements haven't got through + if (d && (d.getElementById || d.navigator)) { + Ext.Error.raise('Unexpected document or window element in element garbage collection'); + } + + // ------------------------------------------------------- + // Determining what is 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.parentNode || (!d.offsetParent && !Ext.getElementById(eid))) { + if (d && Ext.enableListenerCollection) { + Ext.EventManager.removeAll(d); + } + delete EC[eid]; + } + } + // Cleanup IE Object leaks + if (Ext.isIE) { + t = {}; + for (eid in EC) { + if (!EC.hasOwnProperty(eid)) { + continue; + } + t[eid] = EC[eid]; + } + EC = Ext.cache = t; + } + } + } + + El.collectorThreadId = setInterval(garbageCollect, 30000); + + //Stuff from Element-more.js + El.addMethods({ + + /** + * Monitors this Element for the mouse leaving. Calls the function after the specified delay only if + * the mouse was not moved back into the Element within the delay. If the mouse *was* moved + * back in, the function is not called. + * @param {Number} delay The delay **in milliseconds** to wait for possible mouse re-entry before calling the handler function. + * @param {Function} handler The function to call if the mouse remains outside of this Element for the specified time. + * @param {Object} [scope] The scope (`this` reference) in which the handler function executes. Defaults to this Element. + * @return {Object} The listeners object which was added to this element so that monitoring can be stopped. Example usage: + * + * // Hide the menu if the mouse moves out for 250ms or more + * this.mouseLeaveMonitor = this.menuEl.monitorMouseLeave(250, this.hideMenu, this); + * + * ... + * // Remove mouseleave monitor on menu destroy + * this.menuEl.un(this.mouseLeaveMonitor); + * + */ + monitorMouseLeave: function(delay, handler, scope) { + var me = this, + timer, + listeners = { + mouseleave: function(e) { + timer = setTimeout(Ext.Function.bind(handler, scope||me, [e]), delay); + }, + mouseenter: function() { + clearTimeout(timer); + }, + freezeEvent: true + }; + + me.on(listeners); + return listeners; + }, + + /** + * Stops the specified event(s) from bubbling and optionally prevents the default action + * @param {String/String[]} eventName an event / array of events to stop from bubbling + * @param {Boolean} [preventDefault] true to prevent the default action too + * @return {Ext.dom.Element} this + */ + swallowEvent : function(eventName, preventDefault) { + var me = this, + e, eLen; + function fn(e) { + e.stopPropagation(); + if (preventDefault) { + e.preventDefault(); + } + } + + if (Ext.isArray(eventName)) { + eLen = eventName.length; + + for (e = 0; e < eLen; e++) { + me.on(eventName[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} observable 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 Empty, or whitespace filled text nodes. Combines adjacent text nodes. + * @param {Boolean} [forceReclean=false] 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, + data = (me.$cache || me.getCache()).data, + n = dom.firstChild, + ni = -1, + nx; + + if (data.isCleaned && forceReclean !== true) { + return me; + } + + while (n) { + nx = n.nextSibling; + if (n.nodeType == 3) { + // Remove empty/whitespace text nodes + if (!(nonSpaceRe.test(n.nodeValue))) { + dom.removeChild(n); + // Combine adjacent text nodes + } else if (nx && nx.nodeType == 3) { + n.appendData(Ext.String.trim(nx.data)); + dom.removeChild(nx); + nx = n.nextSibling; + n.nodeIndex = ++ni; + } + } else { + // Recursively clean + Ext.fly(n).clean(); + n.nodeIndex = ++ni; + } + n = nx; + } + + data.isCleaned = true; + return me; + }, + + /** + * Direct access to the Ext.ElementLoader {@link Ext.ElementLoader#method-load} method. The method takes the same object + * parameter as {@link Ext.ElementLoader#method-load} + * @return {Ext.dom.Element} this + */ + load : function(options) { + this.getLoader().load(options); + return this; + }, + + /** + * Gets this element's {@link Ext.ElementLoader ElementLoader} + * @return {Ext.ElementLoader} The loader + */ + getLoader : function() { + var me = this, + data = (me.$cache || me.getCache()).data, + loader = data.loader; + + if (!loader) { + data.loader = loader = new Ext.ElementLoader({ + target: me + }); + } + return loader; + }, + + /** + * Updates the innerHTML of this element, optionally searching for and processing scripts. + * @param {String} html The new HTML + * @param {Boolean} [loadScripts] True to look for and process scripts (defaults to false) + * @param {Function} [callback] For async script loading you can be notified when the update completes + * @return {Ext.dom.Element} this + */ + update : function(html, loadScripts, callback) { + var me = this, + id, + dom, + interval; + + if (!me.dom) { + return me; + } + html = html || ''; + dom = me.dom; + + if (loadScripts !== true) { + dom.innerHTML = html; + Ext.callback(callback, me); + return me; + } + + id = Ext.id(); + html += ''; + + interval = setInterval(function() { + var hd, + match, + attrs, + srcMatch, + typeMatch, + el, + s; + if (!(el = DOC.getElementById(id))) { + return false; + } + clearInterval(interval); + Ext.removeNode(el); + hd = Ext.getHead().dom; + + while ((match = scriptTagRe.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.callback(callback, me); + }, 20); + dom.innerHTML = html.replace(replaceScriptTagRe, ''); + return me; + }, + + // inherit docs, overridden so we can add removeAnchor + removeAllListeners : function() { + this.removeAnchor(); + Ext.EventManager.removeAll(this.dom); + return this; + }, + + /** + * Creates a proxy element of this element + * @param {String/Object} config The class name of the proxy element or a DomHelper config object + * @param {String/HTMLElement} [renderTo] The element or element id to render the proxy to. Defaults to: document.body. + * @param {Boolean} [matchBox=false] True to align and size the proxy to this element now. + * @return {Ext.dom.Element} The new proxy element + */ + createProxy : function(config, renderTo, matchBox) { + config = (typeof config == 'object') ? config : {tag : "div", cls: config}; + + var me = this, + proxy = renderTo ? Ext.DomHelper.append(renderTo, config, true) : + Ext.DomHelper.insertBefore(me.dom, config, true); + + proxy.setVisibilityMode(Element.DISPLAY); + proxy.hide(); + if (matchBox && me.setBox && me.getBox) { // check to make sure Element.position.js is loaded + proxy.setBox(me.getBox()); + } + return proxy; + }, + + /** + * Gets the parent node of the current element taking into account Ext.scopeResetCSS + * @protected + * @return {HTMLElement} The parent element + */ + getScopeParent: function() { + var parent = this.dom.parentNode; + return Ext.scopeResetCSS ? parent.parentNode : parent; + }, + + /** + * Returns true if this element needs an explicit tabIndex to make it focusable. Input fields, text areas, buttons + * anchors elements **with an href** etc do not need a tabIndex, but structural elements do. + */ + needsTabIndex: function() { + if (this.dom) { + if ((this.dom.nodeName === 'a') && (!this.dom.href)) { + return true; + } + return !focusRe.test(this.dom.nodeName); + } + }, + + /** + * Checks whether this element can be focused. + * @return {Boolean} True if the element is focusable + */ + focusable: function () { + var dom = this.dom, + nodeName = dom.nodeName, + canFocus = false; + + if (!dom.disabled) { + if (focusRe.test(nodeName)) { + if ((nodeName !== 'a') || dom.href) { + canFocus = true; + } + } else { + canFocus = !isNaN(dom.tabIndex); + } + } + return canFocus && this.isVisible(true); + } + }); + + if (Ext.isIE) { + El.prototype.getById = function (id, asDom) { + var dom = this.dom, + cached, el, ret; + + if (dom) { + // for normal elements getElementById is the best solution, but if the el is + // not part of the document.body, we need to use all[] + el = (useDocForId && DOC.getElementById(id)) || dom.all[id]; + if (el) { + if (asDom) { + ret = el; + } else { + // calling El.get here is a real hit (2x slower) because it has to + // redetermine that we are giving it a dom el. + cached = EC[id]; + if (cached && cached.el) { + ret = cached.el; + ret.dom = el; + } else { + ret = new Element(el); + } + } + return ret; + } + } + + return asDom ? Ext.getDom(id) : El.get(id); + }; + } + + El.createAlias({ + /** + * @method + * @inheritdoc Ext.dom.Element#on + * Shorthand for {@link #on}. + */ + addListener: 'on', + /** + * @method + * @inheritdoc Ext.dom.Element#un + * Shorthand for {@link #un}. + */ + removeListener: 'un', + /** + * @method + * @inheritdoc Ext.dom.Element#removeAllListeners + * Alias for {@link #removeAllListeners}. + */ + clearListeners: 'removeAllListeners' + }); + + El.Fly = AbstractElement.Fly = new Ext.Class({ + extend: El, + + constructor: function(dom) { + this.dom = dom; + }, + + attach: AbstractElement.Fly.prototype.attach + }); + + if (Ext.isIE) { + Ext.getElementById = function (id) { + var el = DOC.getElementById(id), + detachedBodyEl; + + if (!el && (detachedBodyEl = AbstractElement.detachedBodyEl)) { + el = detachedBodyEl.dom.all[id]; + } + + return el; + }; + } else if (!DOC.querySelector) { + Ext.getDetachedBody = Ext.getBody; + + Ext.getElementById = function (id) { + return DOC.getElementById(id); + }; + } +}); + +}()); + +/** + * @class Ext.dom.Element + */ +Ext.dom.Element.override((function() { + + var doc = document, + win = window, + alignRe = /^([a-z]+)-([a-z]+)(\?)?$/, + round = Math.round; + + return { + + /** + * Gets the x,y coordinates specified by the anchor position on the element. + * @param {String} [anchor='c'] The specified anchor position. See {@link #alignTo} + * for details on supported anchor positions. + * @param {Boolean} [local] True to get the local (element top/left-relative) anchor position instead + * of page coordinates + * @param {Object} [size] 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 {Number[]} [x, y] An array containing the element's x and y coordinates + */ + getAnchorXY: function(anchor, local, mySize) { + //Passing a different size is useful for pre-calculating anchors, + //especially for anchored animations that change the el size. + anchor = (anchor || "tl").toLowerCase(); + mySize = mySize || {}; + + var me = this, + isViewport = me.dom == doc.body || me.dom == doc, + myWidth = mySize.width || isViewport ? Ext.dom.Element.getViewWidth() : me.getWidth(), + myHeight = mySize.height || isViewport ? Ext.dom.Element.getViewHeight() : me.getHeight(), + xy, + myPos = me.getXY(), + scroll = me.getScroll(), + extraX = isViewport ? scroll.left : !local ? myPos[0] : 0, + extraY = isViewport ? scroll.top : !local ? myPos[1] : 0; + + // Calculate anchor position. + // Test most common cases for picker alignment first. + switch (anchor) { + case 'tl' : xy = [ 0, 0]; + break; + case 'bl' : xy = [ 0, myHeight]; + break; + case 'tr' : xy = [ myWidth, 0]; + break; + case 'c' : xy = [ round(myWidth * 0.5), round(myHeight * 0.5)]; + break; + case 't' : xy = [ round(myWidth * 0.5), 0]; + break; + case 'l' : xy = [ 0, round(myHeight * 0.5)]; + break; + case 'r' : xy = [ myWidth, round(myHeight * 0.5)]; + break; + case 'b' : xy = [ round(myWidth * 0.5), myHeight]; + break; + case 'br' : xy = [ myWidth, myHeight]; + } + return [xy[0] + extraX, xy[1] + extraY]; + }, + + /** + * Gets the x,y coordinates to align this element with another element. See {@link #alignTo} for more info on the + * supported position values. + * @param {String/HTMLElement/Ext.Element} element The element to align to. + * @param {String} [position="tl-bl?"] The position to align to (defaults to ) + * @param {Number[]} [offsets] Offset the positioning by [x, y] + * @return {Number[]} [x, y] + */ + getAlignToXY : function(alignToEl, posSpec, offset) { + alignToEl = Ext.get(alignToEl); + + if (!alignToEl || !alignToEl.dom) { + Ext.Error.raise({ + sourceClass: 'Ext.dom.Element', + sourceMethod: 'getAlignToXY', + msg: 'Attempted to align an element that doesn\'t exist' + }); + } + + offset = offset || [0,0]; + posSpec = (!posSpec || posSpec == "?" ? "tl-bl?" : (!(/-/).test(posSpec) && posSpec !== "" ? "tl-" + posSpec : posSpec || "tl-bl")).toLowerCase(); + + var me = this, + myPosition, + alignToElPosition, + x, + y, + myWidth, + myHeight, + alignToElRegion, + viewportWidth = Ext.dom.Element.getViewWidth() - 10, // 10px of margin for ie + viewportHeight = Ext.dom.Element.getViewHeight() - 10, // 10px of margin for ie + p1y, + p1x, + p2y, + p2x, + swapY, + swapX, + docElement = doc.documentElement, + docBody = doc.body, + scrollX = (docElement.scrollLeft || docBody.scrollLeft || 0),// + 5, WHY was 5 ever added? + scrollY = (docElement.scrollTop || docBody.scrollTop || 0),// + 5, It means align will fail if the alignTo el was at less than 5,5 + constrain, //constrain to viewport + align1, + align2, + alignMatch = posSpec.match(alignRe); + + if (!alignMatch) { + Ext.Error.raise({ + sourceClass: 'Ext.dom.Element', + sourceMethod: 'getAlignToXY', + el: alignToEl, + position: posSpec, + offset: offset, + msg: 'Attemmpted to align an element with an invalid position: "' + posSpec + '"' + }); + } + + align1 = alignMatch[1]; + align2 = alignMatch[2]; + constrain = !!alignMatch[3]; + + //Subtract the aligned el's internal xy from the target's offset xy + //plus custom offset to get this Element's new offset xy + myPosition = me.getAnchorXY(align1, true); + alignToElPosition = alignToEl.getAnchorXY(align2, false); + + x = alignToElPosition[0] - myPosition[0] + offset[0]; + y = alignToElPosition[1] - myPosition[1] + offset[1]; + + // If position spec ended with a "?", then constrain to viewport is necessary + if (constrain) { + myWidth = me.getWidth(); + myHeight = me.getHeight(); + alignToElRegion = alignToEl.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 = align1.charAt(0); + p1x = align1.charAt(align1.length - 1); + p2y = align2.charAt(0); + p2x = align2.charAt(align2.length - 1); + swapY = ((p1y == "t" && p2y == "b") || (p1y == "b" && p2y == "t")); + swapX = ((p1x == "r" && p2x == "l") || (p1x == "l" && p2x == "r")); + + if (x + myWidth > viewportWidth + scrollX) { + x = swapX ? alignToElRegion.left - myWidth : viewportWidth + scrollX - myWidth; + } + if (x < scrollX) { + x = swapX ? alignToElRegion.right : scrollX; + } + if (y + myHeight > viewportHeight + scrollY) { + y = swapY ? alignToElRegion.top - myHeight : viewportHeight + scrollY - myHeight; + } + if (y < scrollY) { + y = swapY ? alignToElRegion.bottom : scrollY; + } + } + return [x,y]; + }, + + + /** + * Anchors an element to another element and realigns it when the window is resized. + * @param {String/HTMLElement/Ext.Element} element The element to align to. + * @param {String} position The position to align to. + * @param {Number[]} [offsets] Offset the positioning by [x, y] + * @param {Boolean/Object} [animate] True for the default animation or a standard Element animation config object + * @param {Boolean/Number} [monitorScroll] True to monitor body scroll and reposition. If this parameter + * is a number, it is used as the buffer delay (defaults to 50ms). + * @param {Function} [callback] The function to call after the animation finishes + * @return {Ext.Element} this + */ + anchorTo : function(el, alignment, offsets, animate, monitorScroll, callback) { + var me = this, + dom = me.dom, + scroll = !Ext.isEmpty(monitorScroll), + action = function() { + Ext.fly(dom).alignTo(el, alignment, offsets, animate); + Ext.callback(callback, Ext.fly(dom)); + }, + anchor = this.getAnchor(); + + // previous listener anchor, remove it + this.removeAnchor(); + Ext.apply(anchor, { + fn: action, + scroll: scroll + }); + + Ext.EventManager.onWindowResize(action, null); + + if (scroll) { + Ext.EventManager.on(win, 'scroll', action, null, + {buffer: !isNaN(monitorScroll) ? monitorScroll : 50}); + } + action.call(me); // align immediately + return me; + }, + + /** + * Remove any anchor to this element. See {@link #anchorTo}. + * @return {Ext.dom.Element} this + */ + removeAnchor : function() { + var me = this, + anchor = this.getAnchor(); + + if (anchor && anchor.fn) { + Ext.EventManager.removeResizeListener(anchor.fn); + if (anchor.scroll) { + Ext.EventManager.un(win, 'scroll', anchor.fn); + } + delete anchor.fn; + } + return me; + }, + + getAlignVector: function(el, spec, offset) { + var me = this, + myPos = me.getXY(), + alignedPos = me.getAlignToXY(el, spec, offset); + + el = Ext.get(el); + if (!el || !el.dom) { + Ext.Error.raise({ + sourceClass: 'Ext.dom.Element', + sourceMethod: 'getAlignVector', + msg: 'Attempted to align an element that doesn\'t exist' + }); + } + + alignedPos[0] -= myPos[0]; + alignedPos[1] -= myPos[1]; + return alignedPos; + }, + + /** + * 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 {String/HTMLElement/Ext.Element} element The element to align to. + * @param {String} [position="tl-bl?"] The position to align to + * @param {Number[]} [offsets] Offset the positioning by [x, y] + * @param {Boolean/Object} [animate] 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.anim && !!animate ? me.anim(animate) : false); + }, + + /** + * Returns the `[X, Y]` vector by which this element must be translated to make a best attempt + * to constrain within the passed constraint. Returns `false` is this element does not need to be moved. + * + * Priority is given to constraining the top and left within the constraint. + * + * The constraint may either be an existing element into which this element is to be constrained, or + * an {@link Ext.util.Region Region} into which this element is to be constrained. + * + * @param {Ext.Element/Ext.util.Region} constrainTo The Element or Region into which this element is to be constrained. + * @param {Number[]} proposedPosition A proposed `[X, Y]` position to test for validity and to produce a vector for instead + * of using this Element's current position; + * @returns {Number[]/Boolean} **If** this element *needs* to be translated, an `[X, Y]` + * vector by which this element must be translated. Otherwise, `false`. + */ + getConstrainVector: function(constrainTo, proposedPosition) { + if (!(constrainTo instanceof Ext.util.Region)) { + constrainTo = Ext.get(constrainTo).getViewRegion(); + } + var thisRegion = this.getRegion(), + vector = [0, 0], + shadowSize = this.shadow && this.shadow.offset, + overflowed = false; + + // Shift this region to occupy the proposed position + if (proposedPosition) { + thisRegion.translateBy(proposedPosition[0] - thisRegion.x, proposedPosition[1] - thisRegion.y); + } + + // Reduce the constrain region to allow for shadow + // TODO: Rewrite the Shadow class. When that's done, get the extra for each side from the Shadow. + if (shadowSize) { + constrainTo.adjust(0, -shadowSize, -shadowSize, shadowSize); + } + + // Constrain the X coordinate by however much this Element overflows + if (thisRegion.right > constrainTo.right) { + overflowed = true; + vector[0] = (constrainTo.right - thisRegion.right); // overflowed the right + } + if (thisRegion.left + vector[0] < constrainTo.left) { + overflowed = true; + vector[0] = (constrainTo.left - thisRegion.left); // overflowed the left + } + + // Constrain the Y coordinate by however much this Element overflows + if (thisRegion.bottom > constrainTo.bottom) { + overflowed = true; + vector[1] = (constrainTo.bottom - thisRegion.bottom); // overflowed the bottom + } + if (thisRegion.top + vector[1] < constrainTo.top) { + overflowed = true; + vector[1] = (constrainTo.top - thisRegion.top); // overflowed the top + } + return overflowed ? vector : false; + }, + + /** + * Calculates the x, y to center this element on the screen + * @return {Number[]} The x, y values [x, y] + */ + getCenterXY : function(){ + return this.getAlignToXY(doc, 'c-c'); + }, + + /** + * Centers the Element in either the viewport, or another Element. + * @param {String/HTMLElement/Ext.Element} [centerIn] The element in which to center the element. + */ + center : function(centerIn){ + return this.alignTo(centerIn || doc, 'c-c'); + } + }; +}())); +/** + * @class Ext.dom.Element + */ +/* ================================ + * A Note About Wrapped Animations + * ================================ + * A few of the effects below implement two different animations per effect, one wrapping + * animation that performs the visual effect and a "no-op" animation on this Element where + * no attributes of the element itself actually change. The purpose for this is that the + * wrapper is required for the effect to work and so it does the actual animation work, but + * we always animate `this` so that the element's events and callbacks work as expected to + * the callers of this API. + * + * Because of this, we always want each wrap animation to complete first (we don't want to + * cut off the visual effect early). To ensure that, we arbitrarily increase the duration of + * the element's no-op animation, also ensuring that it has a decent minimum value -- on slow + * systems, too-low durations can cause race conditions between the wrap animation and the + * element animation being removed out of order. Note that in each wrap's `afteranimate` + * callback it will explicitly terminate the element animation as soon as the wrap is complete, + * so there's no real danger in making the duration too long. + * + * This applies to all effects that get wrapped, including slideIn, slideOut, switchOff and frame. + */ + +Ext.dom.Element.override({ + // @private override base Ext.util.Animate mixin for animate for backwards compatibility + animate: function(config) { + var me = this, + listeners, + anim, + animId = me.dom.id || Ext.id(me.dom); + + if (!Ext.fx.Manager.hasFxBlock(animId)) { + // Bit of gymnastics here to ensure our internal listeners get bound first + if (config.listeners) { + listeners = config.listeners; + delete config.listeners; + } + if (config.internalListeners) { + config.listeners = config.internalListeners; + delete config.internalListeners; + } + anim = new Ext.fx.Anim(me.anim(config)); + if (listeners) { + anim.on(listeners); + } + Ext.fx.Manager.queueFx(anim); + } + return me; + }, + + // @private override base Ext.util.Animate mixin for animate for backwards compatibility + anim: function(config) { + if (!Ext.isObject(config)) { + return (config) ? {} : false; + } + + var me = this, + duration = config.duration || Ext.fx.Anim.prototype.duration, + easing = config.easing || 'ease', + animConfig; + + if (config.stopAnimation) { + me.stopAnimation(); + } + + Ext.applyIf(config, Ext.fx.Manager.getFxDefaults(me.id)); + + // Clear any 'paused' defaults. + Ext.fx.Manager.setFxDefaults(me.id, { + delay: 0 + }); + + animConfig = { + // Pass the DOM reference. That's tested first so will be converted to an Ext.fx.Target fastest. + target: me.dom, + remove: config.remove, + alternate: config.alternate || false, + duration: duration, + easing: easing, + callback: config.callback, + listeners: config.listeners, + iterations: config.iterations || 1, + scope: config.scope, + block: config.block, + concurrent: config.concurrent, + delay: config.delay || 0, + paused: true, + keyframes: config.keyframes, + from: config.from || {}, + to: Ext.apply({}, config) + }; + Ext.apply(animConfig.to, config.to); + + // Anim API properties - backward compat + delete animConfig.to.to; + delete animConfig.to.from; + delete animConfig.to.remove; + delete animConfig.to.alternate; + delete animConfig.to.keyframes; + delete animConfig.to.iterations; + delete animConfig.to.listeners; + delete animConfig.to.target; + delete animConfig.to.paused; + delete animConfig.to.callback; + delete animConfig.to.scope; + delete animConfig.to.duration; + delete animConfig.to.easing; + delete animConfig.to.concurrent; + delete animConfig.to.block; + delete animConfig.to.stopAnimation; + delete animConfig.to.delay; + return animConfig; + }, + + /** + * 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: 2000 }); + * + * // common config options shown with default values + * el.slideIn('t', { + * easing: 'easeOut', + * duration: 500 + * }); + * + * @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 + * @param {Boolean} options.preserveScroll Set to true if preservation of any descendant elements' + * `scrollTop` values is required. By default the DOM wrapping operation performed by `slideIn` and + * `slideOut` causes the browser to lose all scroll positions. + * @return {Ext.dom.Element} The Element + */ + slideIn: function(anchor, obj, slideOut) { + var me = this, + elStyle = me.dom.style, + beforeAnim, + wrapAnim, + restoreScroll, + wrapDomParentNode; + + anchor = anchor || "t"; + obj = obj || {}; + + beforeAnim = function() { + var animScope = this, + listeners = obj.listeners, + box, originalStyles, anim, wrap; + + if (!slideOut) { + me.fixDisplay(); + } + + box = me.getBox(); + if ((anchor == 't' || anchor == 'b') && box.height === 0) { + box.height = me.dom.scrollHeight; + } + else if ((anchor == 'l' || anchor == 'r') && box.width === 0) { + box.width = me.dom.scrollWidth; + } + + originalStyles = me.getStyles('width', 'height', 'left', 'right', 'top', 'bottom', 'position', 'z-index', true); + me.setSize(box.width, box.height); + + // Cache all descendants' scrollTop & scrollLeft values if configured to preserve scroll. + if (obj.preserveScroll) { + restoreScroll = me.cacheScrollValues(); + } + + wrap = me.wrap({ + id: Ext.id() + '-anim-wrap-for-' + me.id, + style: { + visibility: slideOut ? 'visible' : 'hidden' + } + }); + wrapDomParentNode = wrap.dom.parentNode; + wrap.setPositioning(me.getPositioning()); + if (wrap.isStyle('position', 'static')) { + wrap.position('relative'); + } + me.clearPositioning('auto'); + wrap.clip(); + + // The wrap will have reset all descendant scrollTops. Restore them if we cached them. + if (restoreScroll) { + restoreScroll(); + } + + // This element is temporarily positioned absolute within its wrapper. + // Restore to its default, CSS-inherited visibility setting. + // We cannot explicitly poke visibility:visible into its style because that overrides the visibility of the wrap. + me.setStyle({ + visibility: '', + position: 'absolute' + }); + if (slideOut) { + wrap.setSize(box.width, box.height); + } + + switch (anchor) { + case 't': + anim = { + from: { + width: box.width + 'px', + height: '0px' + }, + to: { + width: box.width + 'px', + height: box.height + 'px' + } + }; + elStyle.bottom = '0px'; + break; + case 'l': + anim = { + from: { + width: '0px', + height: box.height + 'px' + }, + to: { + width: box.width + 'px', + height: box.height + 'px' + } + }; + elStyle.right = '0px'; + break; + case 'r': + anim = { + from: { + x: box.x + box.width, + width: '0px', + height: box.height + 'px' + }, + to: { + x: box.x, + width: box.width + 'px', + height: box.height + 'px' + } + }; + break; + case 'b': + anim = { + from: { + y: box.y + box.height, + width: box.width + 'px', + height: '0px' + }, + to: { + y: box.y, + width: box.width + 'px', + height: box.height + 'px' + } + }; + break; + case 'tl': + anim = { + from: { + x: box.x, + y: box.y, + width: '0px', + height: '0px' + }, + to: { + width: box.width + 'px', + height: box.height + 'px' + } + }; + elStyle.bottom = '0px'; + elStyle.right = '0px'; + break; + case 'bl': + anim = { + from: { + x: box.x + box.width, + width: '0px', + height: '0px' + }, + to: { + x: box.x, + width: box.width + 'px', + height: box.height + 'px' + } + }; + elStyle.right = '0px'; + break; + case 'br': + anim = { + from: { + x: box.x + box.width, + y: box.y + box.height, + width: '0px', + height: '0px' + }, + to: { + x: box.x, + y: box.y, + width: box.width + 'px', + height: box.height + 'px' + } + }; + break; + case 'tr': + anim = { + from: { + y: box.y + box.height, + width: '0px', + height: '0px' + }, + to: { + y: box.y, + width: box.width + 'px', + height: box.height + 'px' + } + }; + elStyle.bottom = '0px'; + break; + } + + wrap.show(); + wrapAnim = Ext.apply({}, obj); + delete wrapAnim.listeners; + wrapAnim = new Ext.fx.Anim(Ext.applyIf(wrapAnim, { + target: wrap, + duration: 500, + easing: 'ease-out', + from: slideOut ? anim.to : anim.from, + to: slideOut ? anim.from : anim.to + })); + + // In the absence of a callback, this listener MUST be added first + wrapAnim.on('afteranimate', function() { + me.setStyle(originalStyles); + if (slideOut) { + if (obj.useDisplay) { + me.setDisplayed(false); + } else { + me.hide(); + } + } + if (wrap.dom) { + if (wrap.dom.parentNode) { + wrap.dom.parentNode.insertBefore(me.dom, wrap.dom); + } else { + wrapDomParentNode.appendChild(me.dom); + } + wrap.remove(); + } + // The unwrap will have reset all descendant scrollTops. Restore them if we cached them. + if (restoreScroll) { + restoreScroll(); + } + // kill the no-op element animation created below + animScope.end(); + }); + // Add configured listeners after + if (listeners) { + wrapAnim.on(listeners); + } + }; + + me.animate({ + // See "A Note About Wrapped Animations" at the top of this class: + duration: obj.duration ? Math.max(obj.duration, 500) * 2 : 1000, + listeners: { + beforeanimate: beforeAnim // kick off the wrap animation + } + }); + 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: 2000 }); + * + * // common config options shown with default values + * el.slideOut('t', { + * easing: 'easeOut', + * duration: 500, + * 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.dom.Element} The Element + */ + slideOut: function(anchor, o) { + return this.slideIn(anchor, o, true); + }, + + /** + * 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. Usage: + * + * // default + * el.puff(); + * + * // common config options shown with default values + * el.puff({ + * easing: 'easeOut', + * duration: 500, + * useDisplay: false + * }); + * + * @param {Object} options (optional) Object literal with any of the Fx config options + * @return {Ext.dom.Element} The Element + */ + puff: function(obj) { + var me = this, + beforeAnim, + box = me.getBox(), + originalStyles = me.getStyles('width', 'height', 'left', 'right', 'top', 'bottom', 'position', 'z-index', 'font-size', 'opacity', true); + + obj = Ext.applyIf(obj || {}, { + easing: 'ease-out', + duration: 500, + useDisplay: false + }); + + beforeAnim = function() { + me.clearOpacity(); + me.show(); + this.to = { + width: box.width * 2, + height: box.height * 2, + x: box.x - (box.width / 2), + y: box.y - (box.height /2), + opacity: 0, + fontSize: '200%' + }; + this.on('afteranimate',function() { + if (me.dom) { + if (obj.useDisplay) { + me.setDisplayed(false); + } else { + me.hide(); + } + me.setStyle(originalStyles); + obj.callback.call(obj.scope); + } + }); + }; + + me.animate({ + duration: obj.duration, + easing: obj.easing, + listeners: { + beforeanimate: { + fn: beforeAnim + } + } + }); + 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.dom.Element} The Element + */ + switchOff: function(obj) { + var me = this, + beforeAnim; + + obj = Ext.applyIf(obj || {}, { + easing: 'ease-in', + duration: 500, + remove: false, + useDisplay: false + }); + + beforeAnim = function() { + var animScope = this, + size = me.getSize(), + xy = me.getXY(), + keyframe, position; + me.clearOpacity(); + me.clip(); + position = me.getPositioning(); + + keyframe = new Ext.fx.Animator({ + target: me, + duration: obj.duration, + easing: obj.easing, + keyframes: { + 33: { + opacity: 0.3 + }, + 66: { + height: 1, + y: xy[1] + size.height / 2 + }, + 100: { + width: 1, + x: xy[0] + size.width / 2 + } + } + }); + keyframe.on('afteranimate', function() { + if (obj.useDisplay) { + me.setDisplayed(false); + } else { + me.hide(); + } + me.clearOpacity(); + me.setPositioning(position); + me.setSize(size); + // kill the no-op element animation created below + animScope.end(); + }); + }; + + me.animate({ + // See "A Note About Wrapped Animations" at the top of this class: + duration: (Math.max(obj.duration, 500) * 2), + listeners: { + beforeanimate: { + fn: beforeAnim + } + } + }); + 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.dom.Element} The Element + */ + frame : function(color, count, obj){ + var me = this, + beforeAnim; + + color = color || '#C3DAF9'; + count = count || 1; + obj = obj || {}; + + beforeAnim = function() { + me.show(); + var animScope = this, + box = me.getBox(), + proxy = Ext.getBody().createChild({ + id: me.id + '-anim-proxy', + style: { + position : 'absolute', + 'pointer-events': 'none', + 'z-index': 35000, + border : '0px solid ' + color + } + }), + proxyAnim; + proxyAnim = new Ext.fx.Anim({ + target: proxy, + duration: obj.duration || 1000, + iterations: count, + from: { + top: box.y, + left: box.x, + borderWidth: 0, + opacity: 1, + height: box.height, + width: box.width + }, + to: { + top: box.y - 20, + left: box.x - 20, + borderWidth: 10, + opacity: 0, + height: box.height + 40, + width: box.width + 40 + } + }); + proxyAnim.on('afteranimate', function() { + proxy.remove(); + // kill the no-op element animation created below + animScope.end(); + }); + }; + + me.animate({ + // See "A Note About Wrapped Animations" at the top of this class: + duration: (Math.max(obj.duration, 500) * 2) || 2000, + listeners: { + beforeanimate: { + fn: beforeAnim + } + } + }); + return me; + }, + + /** + * 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: 2000 }); + * + * // common config options shown with default values + * el.ghost('b', { + * easing: 'easeOut', + * duration: 500 + * }); + * + * @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.dom.Element} The Element + */ + ghost: function(anchor, obj) { + var me = this, + beforeAnim; + + anchor = anchor || "b"; + beforeAnim = function() { + var width = me.getWidth(), + height = me.getHeight(), + xy = me.getXY(), + position = me.getPositioning(), + to = { + opacity: 0 + }; + switch (anchor) { + case 't': + to.y = xy[1] - height; + break; + case 'l': + to.x = xy[0] - width; + break; + case 'r': + to.x = xy[0] + width; + break; + case 'b': + to.y = xy[1] + height; + break; + case 'tl': + to.x = xy[0] - width; + to.y = xy[1] - height; + break; + case 'bl': + to.x = xy[0] - width; + to.y = xy[1] + height; + break; + case 'br': + to.x = xy[0] + width; + to.y = xy[1] + height; + break; + case 'tr': + to.x = xy[0] + width; + to.y = xy[1] - height; + break; + } + this.to = to; + this.on('afteranimate', function () { + if (me.dom) { + me.hide(); + me.clearOpacity(); + me.setPositioning(position); + } + }); + }; + + me.animate(Ext.applyIf(obj || {}, { + duration: 500, + easing: 'ease-out', + listeners: { + beforeanimate: { + fn: beforeAnim + } + } + })); + 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: 2000 }); + * + * // common config options shown with default values + * el.highlight("ffff9c", { + * attr: "backgroundColor", //can be any valid CSS property (attribute) that supports a color value + * endColor: (current color) or "ffffff", + * easing: 'easeIn', + * duration: 1000 + * }); + * + * @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.dom.Element} The Element + */ + highlight: function(color, o) { + var me = this, + dom = me.dom, + from = {}, + restore, to, attr, lns, event, fn; + + o = o || {}; + lns = o.listeners || {}; + attr = o.attr || 'backgroundColor'; + from[attr] = color || 'ffff9c'; + + if (!o.to) { + to = {}; + to[attr] = o.endColor || me.getColor(attr, 'ffffff', ''); + } + else { + to = o.to; + } + + // Don't apply directly on lns, since we reference it in our own callbacks below + o.listeners = Ext.apply(Ext.apply({}, lns), { + beforeanimate: function() { + restore = dom.style[attr]; + me.clearOpacity(); + me.show(); + + event = lns.beforeanimate; + if (event) { + fn = event.fn || event; + return fn.apply(event.scope || lns.scope || window, arguments); + } + }, + afteranimate: function() { + if (dom) { + dom.style[attr] = restore; + } + + event = lns.afteranimate; + if (event) { + fn = event.fn || event; + fn.apply(event.scope || lns.scope || window, arguments); + } + } + }); + + me.animate(Ext.apply({}, o, { + duration: 1000, + easing: 'ease-in', + from: from, + to: to + })); + return me; + }, + + /** + * @deprecated 4.0 + * 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(ms) { + var me = this; + Ext.fx.Manager.setFxDefaults(me.id, { + delay: ms + }); + return me; + }, + + /** + * Fade an element in (from transparent to opaque). The ending opacity can be specified using the `opacity` + * 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({ opacity: .75, duration: 2000}); + * + * // common config options shown with default values + * el.fadeIn({ + * opacity: 1, //can be any value between 0 and 1 (e.g. .5) + * easing: 'easeOut', + * duration: 500 + * }); + * + * @param {Object} options (optional) Object literal with any of the Fx config options + * @return {Ext.Element} The Element + */ + fadeIn: function(o) { + var me = this; + me.animate(Ext.apply({}, o, { + opacity: 1, + internalListeners: { + beforeanimate: function(anim){ + // restore any visibility/display that may have + // been applied by a fadeout animation + if (me.isStyle('display', 'none')) { + me.setDisplayed(''); + } else { + me.show(); + } + } + } + })); + return this; + }, + + /** + * Fade an element out (from opaque to transparent). The ending opacity can be specified using the `opacity` + * config option. Note that IE may require `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({ opacity: .25, duration: 2000}); + * + * // common config options shown with default values + * el.fadeOut({ + * opacity: 0, //can be any value between 0 and 1 (e.g. .5) + * easing: 'easeOut', + * duration: 500, + * 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) { + var me = this; + o = Ext.apply({ + opacity: 0, + internalListeners: { + afteranimate: function(anim){ + var dom = me.dom; + if (dom && anim.to.opacity === 0) { + if (o.useDisplay) { + me.setDisplayed(false); + } else { + me.hide(); + } + } + } + } + }, o); + me.animate(o); + return me; + }, + + /** + * @deprecated 4.0 + * 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.animate(Ext.apply({}, o, { + width: w, + height: h + })); + return this; + }, + + /** + * @deprecated 4.0 + * 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(config) { + this.animate(config); + return this; + } +}); + +/** + * @class Ext.dom.Element + */ +Ext.dom.Element.override({ + /** + * Initializes a {@link Ext.dd.DD} drag drop object for this element. + * @param {String} group The group the DD object is member of + * @param {Object} config The DD config object + * @param {Object} overrides An object containing methods to override/implement on the DD object + * @return {Ext.dd.DD} The DD object + */ + initDD : function(group, config, overrides){ + var dd = new Ext.dd.DD(Ext.id(this.dom), group, config); + return Ext.apply(dd, overrides); + }, + + /** + * Initializes a {@link Ext.dd.DDProxy} object for this element. + * @param {String} group The group the DDProxy object is member of + * @param {Object} config The DDProxy config object + * @param {Object} overrides An object containing methods to override/implement on the DDProxy object + * @return {Ext.dd.DDProxy} The DDProxy object + */ + initDDProxy : function(group, config, overrides){ + var dd = new Ext.dd.DDProxy(Ext.id(this.dom), group, config); + return Ext.apply(dd, overrides); + }, + + /** + * Initializes a {@link Ext.dd.DDTarget} object for this element. + * @param {String} group The group the DDTarget object is member of + * @param {Object} config The DDTarget config object + * @param {Object} overrides An object containing methods to override/implement on the DDTarget object + * @return {Ext.dd.DDTarget} The DDTarget object + */ + initDDTarget : function(group, config, overrides){ + var dd = new Ext.dd.DDTarget(Ext.id(this.dom), group, config); + return Ext.apply(dd, overrides); + } +}); + +/** + * @class Ext.dom.Element + */ +(function() { + +var Element = Ext.dom.Element, + VISIBILITY = "visibility", + DISPLAY = "display", + NONE = "none", + HIDDEN = 'hidden', + VISIBLE = 'visible', + OFFSETS = "offsets", + ASCLASS = "asclass", + NOSIZE = 'nosize', + ORIGINALDISPLAY = 'originalDisplay', + VISMODE = 'visibilityMode', + ISVISIBLE = 'isVisible', + OFFSETCLASS = Ext.baseCSSPrefix + 'hide-offsets', + getDisplay = function(el) { + var data = (el.$cache || el.getCache()).data, + display = data[ORIGINALDISPLAY]; + + if (display === undefined) { + data[ORIGINALDISPLAY] = display = ''; + } + return display; + }, + getVisMode = function(el){ + var data = (el.$cache || el.getCache()).data, + visMode = data[VISMODE]; + + if (visMode === undefined) { + data[VISMODE] = visMode = Element.VISIBILITY; + } + return visMode; + }; + +Element.override({ + /** + * The element's default display mode. + */ + originalDisplay : "", + visibilityMode : 1, + + /** + * 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] True for the default animation, or a standard Element animation config object + * @return {Ext.dom.Element} this + */ + setVisible : function(visible, animate) { + var me = this, + dom = me.dom, + visMode = getVisMode(me); + + // hideMode string override + if (typeof animate == 'string') { + switch (animate) { + case DISPLAY: + visMode = Element.DISPLAY; + break; + case VISIBILITY: + visMode = Element.VISIBILITY; + break; + case OFFSETS: + visMode = Element.OFFSETS; + break; + case NOSIZE: + case ASCLASS: + visMode = Element.ASCLASS; + break; + } + me.setVisibilityMode(visMode); + animate = false; + } + + if (!animate || !me.anim) { + if (visMode == Element.DISPLAY) { + return me.setDisplayed(visible); + } else if (visMode == Element.OFFSETS) { + me[visible?'removeCls':'addCls'](OFFSETCLASS); + } else if (visMode == Element.VISIBILITY) { + me.fixDisplay(); + // Show by clearing visibility style. Explicitly setting to "visible" overrides parent visibility setting + dom.style.visibility = visible ? '' : HIDDEN; + } else if (visMode == Element.ASCLASS) { + me[visible?'removeCls':'addCls'](me.visibilityCls || Element.visibilityCls); + } + } else { + // closure for composites + if (visible) { + me.setOpacity(0.01); + me.setVisible(true); + } + if (!Ext.isObject(animate)) { + animate = { + duration: 350, + easing: 'ease-in' + }; + } + me.animate(Ext.applyIf({ + callback: function() { + if (!visible) { + me.setVisible(false).setOpacity(1); + } + }, + to: { + opacity: (visible) ? 1 : 0 + } + }, animate)); + } + (me.$cache || me.getCache()).data[ISVISIBLE] = visible; + return me; + }, + + /** + * @private + * Determine if the Element has a relevant height and width available based + * upon current logical visibility state + */ + hasMetrics : function(){ + var visMode = getVisMode(this); + return this.isVisible() || (visMode == Element.OFFSETS) || (visMode == Element.VISIBILITY); + }, + + /** + * Toggles the element's visibility or display, depending on visibility mode. + * @param {Boolean/Object} [animate] True for the default animation, or a standard Element animation config object + * @return {Ext.dom.Element} this + */ + toggle : function(animate){ + var me = this; + me.setVisible(!me.isVisible(), me.anim(animate)); + return me; + }, + + /** + * Sets the CSS display property. Uses originalDisplay if the specified value is a boolean true. + * @param {Boolean/String} value Boolean value to display the element using its default display, or a string to set the display directly. + * @return {Ext.dom.Element} this + */ + setDisplayed : function(value) { + if(typeof value == "boolean"){ + value = value ? getDisplay(this) : 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(me)); // 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] true for the default animation or a standard Element animation config object + * @return {Ext.dom.Element} this + */ + hide : function(animate){ + // hideMode override + if (typeof animate == 'string'){ + this.setVisible(false, animate); + return this; + } + this.setVisible(false, this.anim(animate)); + return this; + }, + + /** + * Show this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}. + * @param {Boolean/Object} [animate] true for the default animation or a standard Element animation config object + * @return {Ext.dom.Element} this + */ + show : function(animate){ + // hideMode override + if (typeof animate == 'string'){ + this.setVisible(true, animate); + return this; + } + this.setVisible(true, this.anim(animate)); + return this; + } +}); + +}()); + +/** + * @class Ext.dom.Element + */ +(function() { + +var Element = Ext.dom.Element, + LEFT = "left", + RIGHT = "right", + TOP = "top", + BOTTOM = "bottom", + POSITION = "position", + STATIC = "static", + RELATIVE = "relative", + AUTO = "auto", + ZINDEX = "z-index", + BODY = 'BODY', + + PADDING = 'padding', + BORDER = 'border', + SLEFT = '-left', + SRIGHT = '-right', + STOP = '-top', + SBOTTOM = '-bottom', + SWIDTH = '-width', + // special markup used throughout Ext when box wrapping elements + borders = {l: BORDER + SLEFT + SWIDTH, r: BORDER + SRIGHT + SWIDTH, t: BORDER + STOP + SWIDTH, b: BORDER + SBOTTOM + SWIDTH}, + paddings = {l: PADDING + SLEFT, r: PADDING + SRIGHT, t: PADDING + STOP, b: PADDING + SBOTTOM}, + paddingsTLRB = [paddings.l, paddings.r, paddings.t, paddings.b], + bordersTLRB = [borders.l, borders.r, borders.t, borders.b], + positionTopLeft = ['position', 'top', 'left']; + +Element.override({ + + getX: function() { + return Element.getX(this.dom); + }, + + getY: function() { + return Element.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 {Number[]} The XY position of the element + */ + getXY: function() { + return Element.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 {String/HTMLElement/Ext.Element} element The element to get the offsets from. + * @return {Number[]} 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]]; + }, + + setX: function(x, animate) { + return this.setXY([x, this.getY()], animate); + }, + + setY: function(y, animate) { + return this.setXY([this.getX(), y], animate); + }, + + setLeft: function(left) { + this.setStyle(LEFT, this.addUnits(left)); + return this; + }, + + setTop: function(top) { + this.setStyle(TOP, this.addUnits(top)); + return this; + }, + + setRight: function(right) { + this.setStyle(RIGHT, this.addUnits(right)); + return 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 {Number[]} pos Contains X & Y [x, y] values for new position (coordinates are page-based) + * @param {Boolean/Object} [animate] 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) { + Element.setXY(me.dom, pos); + } + else { + if (!Ext.isObject(animate)) { + animate = {}; + } + me.animate(Ext.applyIf({ to: { x: pos[0], y: pos[1] } }, animate)); + } + return me; + }, + + getLeft: function(local) { + return !local ? this.getX() : parseFloat(this.getStyle(LEFT)) || 0; + }, + + getRight: function(local) { + var me = this; + return !local ? me.getX() + me.getWidth() : (me.getLeft(true) + me.getWidth()) || 0; + }, + + getTop: function(local) { + return !local ? this.getY() : parseFloat(this.getStyle(TOP)) || 0; + }, + + getBottom: function(local) { + var me = this; + return !local ? me.getY() + me.getHeight() : (me.getTop(true) + me.getHeight()) || 0; + }, + + translatePoints: function(x, y) { + var me = this, + styles = me.getStyle(positionTopLeft), + relative = styles.position == 'relative', + left = parseFloat(styles.left), + top = parseFloat(styles.top), + xy = me.getXY(); + + if (Ext.isArray(x)) { + y = x[1]; + x = x[0]; + } + if (isNaN(left)) { + left = relative ? 0 : me.dom.offsetLeft; + } + if (isNaN(top)) { + top = relative ? 0 : me.dom.offsetTop; + } + left = (typeof x == 'number') ? x - xy[0] + left : undefined; + top = (typeof y == 'number') ? y - xy[1] + top : undefined; + return { + left: left, + top: top + }; + + }, + + 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, animate); + return me; + }, + + getBox: function(contentBox, local) { + var me = this, + xy, + left, + top, + paddingWidth, + bordersWidth, + l, r, t, b, w, h, bx; + + if (!local) { + xy = me.getXY(); + } else { + xy = me.getStyle([LEFT, TOP]); + xy = [ parseFloat(xy.left) || 0, parseFloat(xy.top) || 0]; + } + w = me.getWidth(); + h = me.getHeight(); + if (!contentBox) { + bx = { + x: xy[0], + y: xy[1], + 0: xy[0], + 1: xy[1], + width: w, + height: h + }; + } else { + paddingWidth = me.getStyle(paddingsTLRB); + bordersWidth = me.getStyle(bordersTLRB); + + l = (parseFloat(bordersWidth[borders.l]) || 0) + (parseFloat(paddingWidth[paddings.l]) || 0); + r = (parseFloat(bordersWidth[borders.r]) || 0) + (parseFloat(paddingWidth[paddings.r]) || 0); + t = (parseFloat(bordersWidth[borders.t]) || 0) + (parseFloat(paddingWidth[paddings.t]) || 0); + b = (parseFloat(bordersWidth[borders.b]) || 0) + (parseFloat(paddingWidth[paddings.b]) || 0); + + 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; + }, + + getPageBox: function(getRegion) { + var me = this, + el = me.dom, + isDoc = el.nodeName == BODY, + w = isDoc ? Ext.dom.AbstractElement.getViewWidth() : el.offsetWidth, + h = isDoc ? Ext.dom.AbstractElement.getViewHeight() : el.offsetHeight, + xy = me.getXY(), + t = xy[1], + r = xy[0] + w, + b = xy[1] + h, + l = xy[0]; + + if (getRegion) { + return new Ext.util.Region(t, r, b, l); + } + else { + return { + left: l, + top: t, + width: w, + height: h, + right: r, + bottom: b + }; + } + }, + + /** + * 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] True for the default animation, or a standard Element + * animation config object + * @return {Ext.dom.AbstractElement} this + */ + setLocation : function(x, y, animate) { + return this.setXY([x, y], animate); + }, + + /** + * 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] True for the default animation, or a standard Element + * animation config object + * @return {Ext.dom.AbstractElement} this + */ + moveTo : function(x, y, animate) { + return this.setXY([x, y], animate); + }, + + /** + * 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] Positioning to use "relative", "absolute" or "fixed" + * @param {Number} [zIndex] The zIndex to apply + * @param {Number} [x] Set the page X position + * @param {Number} [y] 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]); + } + }, + + /** + * Clears positioning back to the default when the document was loaded. + * @param {String} [value=''] The value to use for the left, right, top, bottom. You could use 'auto'. + * @return {Ext.dom.AbstractElement} 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 styles = this.getStyle([LEFT, TOP, POSITION, RIGHT, BOTTOM, ZINDEX]); + styles[RIGHT] = styles[LEFT] ? '' : styles[RIGHT]; + styles[BOTTOM] = styles[TOP] ? '' : styles[BOTTOM]; + return styles; + }, + + /** + * Set positioning with an object returned by #getPositioning. + * @param {Object} posCfg + * @return {Ext.dom.AbstractElement} 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; + }, + + /** + * 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] true for the default animation or a standard Element + * animation config object + */ + 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], animate); + }, + + /** + * Conveniently sets left and top adding default units. + * @param {String} left The left CSS property value + * @param {String} top The top CSS property value + * @return {Ext.dom.Element} this + */ + setLeftTop: function(left, top) { + var style = this.dom.style; + + style.left = Element.addUnits(left); + style.top = Element.addUnits(top); + + return this; + }, + + /** + * Returns the region of this element. + * The element must be part of the DOM tree to have a region + * (display:none or elements not appended return false). + * @return {Ext.util.Region} A Region containing "top, left, bottom, right" member data. + */ + getRegion: function() { + return this.getPageBox(true); + }, + + /** + * Returns the **content** region of this element. That is the region within the borders and padding. + * @return {Ext.util.Region} A Region containing "top, left, bottom, right" member data. + */ + getViewRegion: function() { + var me = this, + isBody = me.dom.nodeName == BODY, + scroll, pos, top, left, width, height; + + // For the body we want to do some special logic + if (isBody) { + scroll = me.getScroll(); + left = scroll.left; + top = scroll.top; + width = Ext.dom.AbstractElement.getViewportWidth(); + height = Ext.dom.AbstractElement.getViewportHeight(); + } + else { + pos = me.getXY(); + left = pos[0] + me.getBorderWidth('l') + me.getPadding('l'); + top = pos[1] + me.getBorderWidth('t') + me.getPadding('t'); + width = me.getWidth(true); + height = me.getHeight(true); + } + + return new Ext.util.Region(top, left + width, top + height, left); + }, + + /** + * 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 {Number/String} 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 {Number/String} 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] true for the default animation or a standard Element + * animation config object + * + * @return {Ext.dom.AbstractElement} this + */ + setBounds: function(x, y, width, height, animate) { + var me = this; + if (!animate || !me.anim) { + me.setSize(width, height); + me.setLocation(x, y); + } else { + if (!Ext.isObject(animate)) { + animate = {}; + } + me.animate(Ext.applyIf({ + to: { + x: x, + y: y, + width: me.adjustWidth(width), + height: me.adjustHeight(height) + } + }, animate)); + } + 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.util.Region} region The region to fill + * @param {Boolean/Object} [animate] true for the default animation or a standard Element + * animation config object + * @return {Ext.dom.AbstractElement} this + */ + setRegion: function(region, animate) { + return this.setBounds(region.left, region.top, region.right - region.left, region.bottom - region.top, animate); + } +}); + +}()); + + +/** + * @class Ext.dom.Element + */ +Ext.dom.Element.override({ + /** + * Returns true if this element is scrollable. + * @return {Boolean} + */ + isScrollable: function() { + var dom = this.dom; + return dom.scrollHeight > dom.clientHeight || dom.scrollWidth > dom.clientWidth; + }, + + /** + * 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; + }, + + /** + * Scrolls this element by the passed delta values, optionally animating. + * + * All of the following are equivalent: + * + * el.scrollBy(10, 10, true); + * el.scrollBy([10, 10], true); + * el.scrollBy({ x: 10, y: 10 }, true); + * + * @param {Number/Number[]/Object} deltaX Either the x delta, an Array specifying x and y deltas or + * an object with "x" and "y" properties. + * @param {Number/Boolean/Object} deltaY Either the y delta, or an animate flag or config object. + * @param {Boolean/Object} animate Animate flag/config object if the delta values were passed separately. + * @return {Ext.Element} this + */ + scrollBy: function(deltaX, deltaY, animate) { + var me = this, + dom = me.dom; + + // Extract args if deltas were passed as an Array. + if (deltaX.length) { + animate = deltaY; + deltaY = deltaX[1]; + deltaX = deltaX[0]; + } else if (typeof deltaX != 'number') { // or an object + animate = deltaY; + deltaY = deltaX.y; + deltaX = deltaX.x; + } + + if (deltaX) { + me.scrollTo('left', Math.max(Math.min(dom.scrollLeft + deltaX, dom.scrollWidth - dom.clientWidth), 0), animate); + } + if (deltaY) { + me.scrollTo('top', Math.max(Math.min(dom.scrollTop + deltaY, dom.scrollHeight - dom.clientHeight), 0), animate); + } + + return me; + }, + + /** + * 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] true for the default animation or a standard Element + * animation config object + * @return {Ext.Element} this + */ + scrollTo: function(side, value, animate) { + //check if we're scrolling top or left + var top = /top/i.test(side), + me = this, + dom = me.dom, + obj = {}, + prop; + + if (!animate || !me.anim) { + // just setting the value, so grab the direction + prop = 'scroll' + (top ? 'Top' : 'Left'); + dom[prop] = value; + } + else { + if (!Ext.isObject(animate)) { + animate = {}; + } + obj['scroll' + (top ? 'Top' : 'Left')] = value; + me.animate(Ext.applyIf({ + to: obj + }, animate)); + } + return me; + }, + + /** + * Scrolls this element into view within the passed container. + * @param {String/HTMLElement/Ext.Element} [container=document.body] The container element + * to scroll. Should be a string (id), dom node, or Ext.Element. + * @param {Boolean} [hscroll=true] False to disable horizontal scroll. + * @return {Ext.dom.Element} this + */ + scrollIntoView: function(container, hscroll) { + container = Ext.getDom(container) || Ext.getBody().dom; + var el = this.dom, + offsets = this.getOffsetsTo(container), + // el's box + left = offsets[0] + container.scrollLeft, + top = offsets[1] + container.scrollTop, + bottom = top + el.offsetHeight, + right = left + el.offsetWidth, + // ct's box + ctClientHeight = container.clientHeight, + ctScrollTop = parseInt(container.scrollTop, 10), + ctScrollLeft = parseInt(container.scrollLeft, 10), + ctBottom = ctScrollTop + ctClientHeight, + ctRight = ctScrollLeft + container.clientWidth; + + if (el.offsetHeight > ctClientHeight || top < ctScrollTop) { + container.scrollTop = top; + } else if (bottom > ctBottom) { + container.scrollTop = bottom - ctClientHeight; + } + // corrects IE, other browsers will ignore + container.scrollTop = container.scrollTop; + + if (hscroll !== false) { + if (el.offsetWidth > container.clientWidth || left < ctScrollLeft) { + container.scrollLeft = left; + } + else if (right > ctRight) { + container.scrollLeft = right - container.clientWidth; + } + container.scrollLeft = container.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] 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 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.anim(animate)); + } + return scrolled; + } +}); + +/** + * @class Ext.dom.Element + */ +(function() { + +var Element = Ext.dom.Element, + view = document.defaultView, + adjustDirect2DTableRe = /table-row|table-.*-group/, + INTERNAL = '_internal', + HIDDEN = 'hidden', + HEIGHT = 'height', + WIDTH = 'width', + ISCLIPPED = 'isClipped', + OVERFLOW = 'overflow', + OVERFLOWX = 'overflow-x', + OVERFLOWY = 'overflow-y', + ORIGINALCLIP = 'originalClip', + DOCORBODYRE = /#document|body/i, + // This reduces the lookup of 'me.styleHooks' by one hop in the prototype chain. It is + // the same object. + styleHooks, + edges, k, edge, borderWidth; + +if (!view || !view.getComputedStyle) { + Element.prototype.getStyle = function (property, inline) { + var me = this, + dom = me.dom, + multiple = typeof property != 'string', + hooks = me.styleHooks, + prop = property, + props = prop, + len = 1, + isInline = inline, + camel, domStyle, values, hook, out, style, i; + + if (multiple) { + values = {}; + prop = props[0]; + i = 0; + if (!(len = props.length)) { + return values; + } + } + + if (!dom || dom.documentElement) { + return values || ''; + } + + domStyle = dom.style; + + if (inline) { + style = domStyle; + } else { + style = dom.currentStyle; + + // fallback to inline style if rendering context not available + if (!style) { + isInline = true; + style = domStyle; + } + } + + do { + hook = hooks[prop]; + + if (!hook) { + hooks[prop] = hook = { name: Element.normalize(prop) }; + } + + if (hook.get) { + out = hook.get(dom, me, isInline, style); + } else { + camel = hook.name; + + // In some cases, IE6 will throw Invalid Argument exceptions for properties + // like fontSize (/examples/tabs/tabs.html in 4.0 used to exhibit this but + // no longer does due to font style changes). There is a real cost to a try + // block, so we avoid it where possible... + if (hook.canThrow) { + try { + out = style[camel]; + } catch (e) { + out = ''; + } + } else { + // EXTJSIV-5657 - In IE9 quirks mode there is a chance that VML root element + // has neither `currentStyle` nor `style`. Return '' this case. + out = style ? style[camel] : ''; + } + } + + if (!multiple) { + return out; + } + + values[prop] = out; + prop = props[++i]; + } while (i < len); + + return values; + }; +} + +Element.override({ + getHeight: function(contentHeight, preciseHeight) { + var me = this, + dom = me.dom, + hidden = me.isStyle('display', 'none'), + height, + floating; + + if (hidden) { + return 0; + } + + height = Math.max(dom.offsetHeight, dom.clientHeight) || 0; + + // IE9 Direct2D dimension rounding bug + if (Ext.supports.Direct2DBug) { + floating = me.adjustDirect2DDimension(HEIGHT); + if (preciseHeight) { + height += floating; + } + else if (floating > 0 && floating < 0.5) { + height++; + } + } + + if (contentHeight) { + height -= me.getBorderWidth("tb") + me.getPadding("tb"); + } + + return (height < 0) ? 0 : height; + }, + + getWidth: function(contentWidth, preciseWidth) { + var me = this, + dom = me.dom, + hidden = me.isStyle('display', 'none'), + rect, width, floating; + + if (hidden) { + return 0; + } + + // Gecko will in some cases report an offsetWidth that is actually less than the width of the + // text contents, because it measures fonts with sub-pixel precision but rounds the calculated + // value down. Using getBoundingClientRect instead of offsetWidth allows us to get the precise + // subpixel measurements so we can force them to always be rounded up. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=458617 + // Rounding up ensures that the width includes the full width of the text contents. + if (Ext.supports.BoundingClientRect) { + rect = dom.getBoundingClientRect(); + width = rect.right - rect.left; + width = preciseWidth ? width : Math.ceil(width); + } else { + width = dom.offsetWidth; + } + + width = Math.max(width, dom.clientWidth) || 0; + + // IE9 Direct2D dimension rounding bug + if (Ext.supports.Direct2DBug) { + // get the fractional portion of the sub-pixel precision width of the element's text contents + floating = me.adjustDirect2DDimension(WIDTH); + if (preciseWidth) { + width += floating; + } + // IE9 also measures fonts with sub-pixel precision, but unlike Gecko, instead of rounding the offsetWidth down, + // it rounds to the nearest integer. This means that in order to ensure that the width includes the full + // width of the text contents we need to increment the width by 1 only if the fractional portion is less than 0.5 + else if (floating > 0 && floating < 0.5) { + width++; + } + } + + if (contentWidth) { + width -= me.getBorderWidth("lr") + me.getPadding("lr"); + } + + return (width < 0) ? 0 : width; + }, + + setWidth: function(width, animate) { + var me = this; + width = me.adjustWidth(width); + if (!animate || !me.anim) { + me.dom.style.width = me.addUnits(width); + } + else { + if (!Ext.isObject(animate)) { + animate = {}; + } + me.animate(Ext.applyIf({ + to: { + width: width + } + }, animate)); + } + return me; + }, + + setHeight : function(height, animate) { + var me = this; + + height = me.adjustHeight(height); + if (!animate || !me.anim) { + me.dom.style.height = me.addUnits(height); + } + else { + if (!Ext.isObject(animate)) { + animate = {}; + } + me.animate(Ext.applyIf({ + to: { + height: height + } + }, animate)); + } + + return me; + }, + + applyStyles: function(style) { + Ext.DomHelper.applyStyles(this.dom, style); + return this; + }, + + setSize: function(width, height, animate) { + var me = this; + + if (Ext.isObject(width)) { // in case of object from getSize() + animate = height; + 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 { + if (animate === true) { + animate = {}; + } + me.animate(Ext.applyIf({ + to: { + width: width, + height: height + } + }, animate)); + } + + return me; + }, + + getViewSize : function() { + var me = this, + dom = me.dom, + isDoc = DOCORBODYRE.test(dom.nodeName), + ret; + + // If the body, use static methods + if (isDoc) { + ret = { + width : Element.getViewWidth(), + height : Element.getViewHeight() + }; + } else { + ret = { + width : dom.clientWidth, + height : dom.clientHeight + }; + } + + return ret; + }, + + getSize: function(contentSize) { + return {width: this.getWidth(contentSize), height: this.getHeight(contentSize)}; + }, + + // TODO: Look at this + + // private ==> used by Fx + adjustWidth : function(width) { + var me = this, + isNum = (typeof width == 'number'); + + if (isNum && me.autoBoxAdjust && !me.isBorderBox()) { + width -= (me.getBorderWidth("lr") + me.getPadding("lr")); + } + return (isNum && width < 0) ? 0 : width; + }, + + // private ==> used by Fx + adjustHeight : function(height) { + var me = this, + isNum = (typeof height == "number"); + + if (isNum && me.autoBoxAdjust && !me.isBorderBox()) { + height -= (me.getBorderWidth("tb") + me.getPadding("tb")); + } + return (isNum && height < 0) ? 0 : height; + }, + + /** + * 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] defaults to #. Use an empty string when working with + * color anims. + */ + getColor : function(attr, defaultValue, prefix) { + var v = this.getStyle(attr), + color = prefix || prefix === '' ? prefix : '#', + h, len, i=0; + + if (!v || (/transparent|inherit/.test(v))) { + return defaultValue; + } + if (/^r/.test(v)) { + v = v.slice(4, v.length - 1).split(','); + len = v.length; + for (; i 5 ? color.toLowerCase() : defaultValue); + }, + + /** + * Set the opacity of the element + * @param {Number} opacity The new opacity. 0 = transparent, .5 = 50% visibile, 1 = fully visible, etc + * @param {Boolean/Object} [animate] a standard Element animation config object or `true` for + * the default animation (`{duration: .35, easing: 'easeIn'}`) + * @return {Ext.dom.Element} this + */ + setOpacity: function(opacity, animate) { + var me = this; + + if (!me.dom) { + return me; + } + + if (!animate || !me.anim) { + me.setStyle('opacity', opacity); + } + else { + if (typeof animate != 'object') { + animate = { + duration: 350, + easing: 'ease-in' + }; + } + + me.animate(Ext.applyIf({ + to: { + opacity: opacity + } + }, animate)); + } + return me; + }, + + /** + * Clears any opacity settings from this element. Required in some cases for IE. + * @return {Ext.dom.Element} this + */ + clearOpacity : function() { + return this.setOpacity(''); + }, + + /** + * @private + * Returns 1 if the browser returns the subpixel dimension rounded to the lowest pixel. + * @return {Number} 0 or 1 + */ + adjustDirect2DDimension: function(dimension) { + var me = this, + dom = me.dom, + display = me.getStyle('display'), + inlineDisplay = dom.style.display, + inlinePosition = dom.style.position, + originIndex = dimension === WIDTH ? 0 : 1, + currentStyle = dom.currentStyle, + floating; + + if (display === 'inline') { + dom.style.display = 'inline-block'; + } + + dom.style.position = display.match(adjustDirect2DTableRe) ? 'absolute' : 'static'; + + // floating will contain digits that appears after the decimal point + // if height or width are set to auto we fallback to msTransformOrigin calculation + + // Use currentStyle here instead of getStyle. In some difficult to reproduce + // instances it resets the scrollWidth of the element + floating = (parseFloat(currentStyle[dimension]) || parseFloat(currentStyle.msTransformOrigin.split(' ')[originIndex]) * 2) % 1; + + dom.style.position = inlinePosition; + + if (display === 'inline') { + dom.style.display = inlineDisplay; + } + + return floating; + }, + + /** + * Store the current overflow setting and clip overflow on the element - use {@link #unclip} to remove + * @return {Ext.dom.Element} this + */ + clip : function() { + var me = this, + data = (me.$cache || me.getCache()).data, + style; + + if (!data[ISCLIPPED]) { + data[ISCLIPPED] = true; + style = me.getStyle([OVERFLOW, OVERFLOWX, OVERFLOWY]); + data[ORIGINALCLIP] = { + o: style[OVERFLOW], + x: style[OVERFLOWX], + y: style[OVERFLOWY] + }; + me.setStyle(OVERFLOW, HIDDEN); + me.setStyle(OVERFLOWX, HIDDEN); + me.setStyle(OVERFLOWY, HIDDEN); + } + return me; + }, + + /** + * Return clipping (overflow) to original clipping before {@link #clip} was called + * @return {Ext.dom.Element} this + */ + unclip : function() { + var me = this, + data = (me.$cache || me.getCache()).data, + clip; + + if (data[ISCLIPPED]) { + data[ISCLIPPED] = false; + clip = data[ORIGINALCLIP]; + if (clip.o) { + me.setStyle(OVERFLOW, clip.o); + } + if (clip.x) { + me.setStyle(OVERFLOWX, clip.x); + } + if (clip.y) { + me.setStyle(OVERFLOWY, clip.y); + } + } + return me; + }, + + /** + * 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.Button}, + * {@link Ext.panel.Panel} when {@link Ext.panel.Panel#frame frame=true}, {@link Ext.window.Window}). + * The markup is of this form: + * + * Ext.dom.Element.boxMarkup = + * '
    + *
    + *
    '; + * + * 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().addCls("x-box-blue"); + * + * @param {String} [class='x-box'] A base CSS class to apply to the containing wrapper element. + * 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.dom.Element} The outermost wrapping element of the created box structure. + */ + boxWrap : function(cls) { + cls = cls || Ext.baseCSSPrefix + 'box'; + var el = Ext.get(this.insertHtml("beforeBegin", "
    " + Ext.String.format(Element.boxMarkup, cls) + "
    ")); + Ext.DomQuery.selectNode('.' + cls + '-mc', el.dom).appendChild(this.dom); + return el; + }, + + /** + * Returns either the offsetHeight or the height of this element based on CSS height adjusted by padding or borders + * when needed to simulate offsetHeight when offsets aren't available. This may not work on display:none elements + * if a height has not been set using CSS. + * @return {Number} + */ + getComputedHeight : function() { + var me = this, + h = Math.max(me.dom.offsetHeight, me.dom.clientHeight); + if (!h) { + h = parseFloat(me.getStyle(HEIGHT)) || 0; + if (!me.isBorderBox()) { + h += me.getFrameWidth('tb'); + } + } + return h; + }, + + /** + * Returns either the offsetWidth or the width of this element based on CSS width adjusted by padding or borders + * when needed to simulate offsetWidth when offsets aren't available. This may not work on display:none elements + * if a width has not been set using CSS. + * @return {Number} + */ + getComputedWidth : function() { + var me = this, + w = Math.max(me.dom.offsetWidth, me.dom.clientWidth); + + if (!w) { + w = parseFloat(me.getStyle(WIDTH)) || 0; + if (!me.isBorderBox()) { + w += me.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 The class to add + * @param {Function} [testFn] A test function to execute before adding the class. The passed parameter + * will be the Element instance. If this functions returns false, the class will not be added. + * @param {Object} [scope] The scope to execute the testFn in. + * @return {Ext.dom.Element} this + */ + addClsOnOver : function(className, testFn, scope) { + var me = this, + dom = me.dom, + hasTest = Ext.isFunction(testFn); + + me.hover( + function() { + if (hasTest && testFn.call(scope || me, me) === false) { + return; + } + Ext.fly(dom, INTERNAL).addCls(className); + }, + function() { + Ext.fly(dom, INTERNAL).removeCls(className); + } + ); + return me; + }, + + /** + * Sets up event handlers to add and remove a css class when this element has the focus + * @param {String} className The class to add + * @param {Function} [testFn] A test function to execute before adding the class. The passed parameter + * will be the Element instance. If this functions returns false, the class will not be added. + * @param {Object} [scope] The scope to execute the testFn in. + * @return {Ext.dom.Element} this + */ + addClsOnFocus : function(className, testFn, scope) { + var me = this, + dom = me.dom, + hasTest = Ext.isFunction(testFn); + + me.on("focus", function() { + if (hasTest && testFn.call(scope || me, me) === false) { + return false; + } + Ext.fly(dom, INTERNAL).addCls(className); + }); + me.on("blur", function() { + Ext.fly(dom, INTERNAL).removeCls(className); + }); + return me; + }, + + /** + * 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 The class to add + * @param {Function} [testFn] A test function to execute before adding the class. The passed parameter + * will be the Element instance. If this functions returns false, the class will not be added. + * @param {Object} [scope] The scope to execute the testFn in. + * @return {Ext.dom.Element} this + */ + addClsOnClick : function(className, testFn, scope) { + var me = this, + dom = me.dom, + hasTest = Ext.isFunction(testFn); + + me.on("mousedown", function() { + if (hasTest && testFn.call(scope || me, me) === false) { + return false; + } + Ext.fly(dom, INTERNAL).addCls(className); + var d = Ext.getDoc(), + fn = function() { + Ext.fly(dom, INTERNAL).removeCls(className); + d.removeListener("mouseup", fn); + }; + d.on("mouseup", fn); + }); + return me; + }, + + /** + * Returns the dimensions of the element available to lay content out in. + * + * getStyleSize utilizes prefers style sizing if present, otherwise it chooses the larger of offsetHeight/clientHeight and + * offsetWidth/clientWidth. To obtain the size excluding scrollbars, use getViewSize. + * + * Sizing of the document body is handled at the adapter level which handles special cases for IE and strict modes, etc. + * + * @return {Object} Object describing width and height. + * @return {Number} return.width + * @return {Number} return.height + */ + getStyleSize : function() { + var me = this, + d = this.dom, + isDoc = DOCORBODYRE.test(d.nodeName), + s , + w, h; + + // If the body, use static methods + if (isDoc) { + return { + width : Element.getViewWidth(), + height : Element.getViewHeight() + }; + } + + s = me.getStyle([HEIGHT, WIDTH], true); //seek inline + // Use Styles if they are set + if (s.width && s.width != 'auto') { + w = parseFloat(s.width); + if (me.isBorderBox()) { + w -= me.getFrameWidth('lr'); + } + } + // Use Styles if they are set + if (s.height && s.height != 'auto') { + h = parseFloat(s.height); + if (me.isBorderBox()) { + h -= me.getFrameWidth('tb'); + } + } + // Use getWidth/getHeight if style not set. + return {width: w || me.getWidth(true), height: h || me.getHeight(true)}; + }, + + /** + * Enable text selection for this element (normalized across browsers) + * @return {Ext.Element} this + */ + selectable : function() { + var me = this; + me.dom.unselectable = "off"; + // Prevent it from bubles up and enables it to be selectable + me.on('selectstart', function (e) { + e.stopPropagation(); + return true; + }); + me.applyStyles("-moz-user-select: text; -khtml-user-select: text;"); + me.removeCls(Ext.baseCSSPrefix + 'unselectable'); + return me; + }, + + /** + * Disables text selection for this element (normalized across browsers) + * @return {Ext.dom.Element} this + */ + unselectable : function() { + var me = this; + me.dom.unselectable = "on"; + + me.swallowEvent("selectstart", true); + me.applyStyles("-moz-user-select:-moz-none;-khtml-user-select:none;"); + me.addCls(Ext.baseCSSPrefix + 'unselectable'); + + return me; + } +}); + +Element.prototype.styleHooks = styleHooks = Ext.dom.AbstractElement.prototype.styleHooks; + +if (Ext.isIE6) { + styleHooks.fontSize = styleHooks['font-size'] = { + name: 'fontSize', + canThrow: true + }; +} + +// override getStyle for border-*-width +if (Ext.isIEQuirks || Ext.isIE && Ext.ieVersion <= 8) { + function getBorderWidth (dom, el, inline, style) { + if (style[this.styleName] == 'none') { + return '0px'; + } + return style[this.name]; + } + + edges = ['Top','Right','Bottom','Left']; + k = edges.length; + + while (k--) { + edge = edges[k]; + borderWidth = 'border' + edge + 'Width'; + + styleHooks['border-'+edge.toLowerCase()+'-width'] = styleHooks[borderWidth] = { + name: borderWidth, + styleName: 'border' + edge + 'Style', + get: getBorderWidth + }; + } +} + +}()); + +Ext.onReady(function () { + var opacityRe = /alpha\(opacity=(.*)\)/i, + trimRe = /^\s+|\s+$/g, + hooks = Ext.dom.Element.prototype.styleHooks; + + // Ext.supports flags are not populated until onReady... + hooks.opacity = { + name: 'opacity', + afterSet: function(dom, value, el) { + if (el.isLayer) { + el.onOpacitySet(value); + } + } + }; + if (!Ext.supports.Opacity && Ext.isIE) { + Ext.apply(hooks.opacity, { + get: function (dom) { + var filter = dom.style.filter, + match, opacity; + if (filter.match) { + match = filter.match(opacityRe); + if (match) { + opacity = parseFloat(match[1]); + if (!isNaN(opacity)) { + return opacity ? opacity / 100 : 0; + } + } + } + return 1; + }, + set: function (dom, value) { + var style = dom.style, + val = style.filter.replace(opacityRe, '').replace(trimRe, ''); + + style.zoom = 1; // ensure dom.hasLayout + + // value can be a number or '' or null... so treat falsey as no opacity + if (typeof(value) == 'number' && value >= 0 && value < 1) { + value *= 100; + style.filter = val + (val.length ? ' ' : '') + 'alpha(opacity='+value+')'; + } else { + style.filter = val; + } + } + }); + } + // else there is no work around for the lack of opacity support. Should not be a + // problem given that this has been supported for a long time now... +}); + +/** + * @class Ext.dom.Element + */ +Ext.dom.Element.override({ + select: function(selector) { + return Ext.dom.Element.select(selector, false, this.dom); + } +}); + +/** + * 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.dom.Element} and + * {@link Ext.fx.Anim}. 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.define('Ext.dom.CompositeElementLite', { + alternateClassName: 'Ext.CompositeElementLite', + + requires: ['Ext.dom.Element'], + + statics: { + /** + * @private + * Copies all of the functions from Ext.dom.Element's prototype onto CompositeElementLite's prototype. + * This is called twice - once immediately below, and once again after additional Ext.dom.Element + * are added in Ext JS + */ + importElementMethods: function() { + var name, + elementPrototype = Ext.dom.Element.prototype, + prototype = this.prototype; + + for (name in elementPrototype) { + if (typeof elementPrototype[name] == 'function'){ + (function(key) { + prototype[key] = prototype[key] || function() { + return this.invoke(key, arguments); + }; + }).call(prototype, name); + + } + } + } + }, + + constructor: function(elements, root) { + /** + * @property {HTMLElement[]} elements + * The Array of DOM elements which this CompositeElement encapsulates. + * + * 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.dom.CompositeElementLite, { + * nextAll: function() { + * var elements = this.elements, i, l = elements.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 = elements[i].nextSibling; n; n = n.nextSibling) { + * r[++ri] = n; + * } + * } + * + * // Add all found siblings to this Composite + * return this.add(r); + * } + * }); + * + * @readonly + */ + this.elements = []; + this.add(elements, root); + this.el = new Ext.dom.AbstractElement.Fly(); + }, + + /** + * @property {Boolean} isComposite + * `true` in this class to identify an object as an instantiated CompositeElement, or subclass thereof. + */ + isComposite: true, + + // private + getElement: function(el) { + // Set the shared flyweight dom property to the current element + return this.el.attach(el); + }, + + // private + transformElement: function(el) { + return Ext.getDom(el); + }, + + /** + * Returns the number of elements in this Composite. + * @return {Number} + */ + getCount: function() { + return this.elements.length; + }, + + /** + * Adds elements to this Composite object. + * @param {HTMLElement[]/Ext.dom.CompositeElement} els Either an Array of DOM elements to add, or another Composite + * object who's elements should be added. + * @return {Ext.dom.CompositeElement} This Composite object. + */ + add: function(els, root) { + var elements = this.elements, + i, ln; + + if (!els) { + return this; + } + + if (typeof els == "string") { + els = Ext.dom.Element.selectorFunction(els, root); + } + else if (els.isComposite) { + els = els.elements; + } + else if (!Ext.isIterable(els)) { + els = [els]; + } + + for (i = 0, ln = els.length; i < ln; ++i) { + elements.push(this.transformElement(els[i])); + } + + return this; + }, + + invoke: function(fn, args) { + var elements = this.elements, + ln = elements.length, + element, + i; + + fn = Ext.dom.Element.prototype[fn]; + for (i = 0; i < ln; i++) { + element = elements[i]; + + if (element) { + fn.apply(this.getElement(element), args); + } + } + return this; + }, + + /** + * Returns a flyweight Element of the dom element object at the specified index + * @param {Number} index + * @return {Ext.dom.Element} + */ + item: function(index) { + var el = this.elements[index], + out = null; + + if (el) { + out = this.getElement(el); + } + + return out; + }, + + // fixes scope with flyweight + addListener: function(eventName, handler, scope, opt) { + var els = this.elements, + len = els.length, + i, e; + + for (i = 0; i < len; i++) { + e = els[i]; + if (e) { + Ext.EventManager.on(e, eventName, handler, scope || e, opt); + } + } + return this; + }, + /** + * Calls the passed function for each element in this composite. + * @param {Function} fn The function to call. + * @param {Ext.dom.Element} fn.el The current Element in the iteration. **This is the flyweight + * (shared) Ext.dom.Element instance, so if you require a a reference to the dom node, use el.dom.** + * @param {Ext.dom.CompositeElement} fn.c This Composite object. + * @param {Number} fn.index The zero-based index in the iteration. + * @param {Object} [scope] The scope (this reference) in which the function is executed. + * Defaults to the Element. + * @return {Ext.dom.CompositeElement} this + */ + each: function(fn, scope) { + var me = this, + els = me.elements, + len = els.length, + i, e; + + for (i = 0; i < len; i++) { + e = els[i]; + if (e) { + e = this.getElement(e); + if (fn.call(scope || e, e, me, i) === false) { + break; + } + } + } + return me; + }, + + /** + * Clears this Composite and adds the elements passed. + * @param {HTMLElement[]/Ext.dom.CompositeElement} els Either an array of DOM elements, or another Composite from which + * to fill this Composite. + * @return {Ext.dom.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: + * @param {Ext.dom.Element} selector.el The current DOM element. + * @param {Number} selector.index The current index within the collection. + * @return {Ext.dom.CompositeElement} this + */ + filter: function(selector) { + var me = this, + els = me.elements, + len = els.length, + out = [], + i = 0, + isFunc = typeof selector == 'function', + add, + el; + + for (; i < len; i++) { + el = els[i]; + add = false; + if (el) { + el = me.getElement(el); + + if (isFunc) { + add = selector.call(el, el, me, i) !== false; + } else { + add = el.is(selector); + } + + if (add) { + out.push(me.transformElement(el)); + } + } + } + + me.elements = out; + return me; + }, + + /** + * Find the index of the passed element within the composite collection. + * @param {String/HTMLElement/Ext.Element/Number} el The id of an element, or an Ext.dom.Element, or an HtmlElement + * to find within the composite collection. + * @return {Number} The index of the passed Ext.dom.Element in the composite collection, or -1 if not found. + */ + indexOf: function(el) { + return Ext.Array.indexOf(this.elements, this.transformElement(el)); + }, + + /** + * Replaces the specified element with the passed element. + * @param {String/HTMLElement/Ext.Element/Number} el The id of an element, the Element itself, the index of the + * element in this composite to replace. + * @param {String/Ext.Element} replacement The id of an element or the Element itself. + * @param {Boolean} [domReplace] True to remove and replace the element in the document too. + * @return {Ext.dom.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); + } + Ext.Array.splice(this.elements, index, 1, replacement); + } + return this; + }, + + /** + * Removes all elements. + */ + clear: function() { + this.elements = []; + }, + + addElements: function(els, root) { + if (!els) { + return this; + } + + if (typeof els == "string") { + els = Ext.dom.Element.selectorFunction(els, root); + } + + var yels = this.elements, + eLen = els.length, + e; + + for (e = 0; e < eLen; e++) { + yels.push(Ext.get(els[e])); + } + + return this; + }, + + /** + * Returns the first Element + * @return {Ext.dom.Element} + */ + first: function() { + return this.item(0); + }, + + /** + * Returns the last Element + * @return {Ext.dom.Element} + */ + last: function() { + return this.item(this.getCount() - 1); + }, + + /** + * Returns true if this composite contains the passed element + * @param {String/HTMLElement/Ext.Element/Number} el 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 {String/HTMLElement/Ext.Element/Number} 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] True to also remove the element from the document + * @return {Ext.dom.CompositeElement} this + */ + removeElement: function(keys, removeDom) { + keys = [].concat(keys); + + var me = this, + elements = me.elements, + kLen = keys.length, + val, el, k; + + for (k = 0; k < kLen; k++) { + val = keys[k]; + + if ((el = (elements[val] || elements[val = me.indexOf(val)]))) { + if (removeDom) { + if (el.dom) { + el.remove(); + } else { + Ext.removeNode(el); + } + } + Ext.Array.erase(elements, val, 1); + } + } + + return me; + } + +}, function() { + this.importElementMethods(); + + this.prototype.on = this.prototype.addListener; + + if (Ext.DomQuery){ + Ext.dom.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.dom.CompositeElement CompositeElement} or + * {@link Ext.dom.CompositeElementLite CompositeElementLite} object. + * @param {String/HTMLElement[]} selector The CSS selector or an array of elements + * @param {HTMLElement/String} [root] The root element of the query or id of the root + * @return {Ext.dom.CompositeElementLite/Ext.dom.CompositeElement} + * @member Ext.dom.Element + * @method select + * @static + */ + Ext.dom.Element.select = function(selector, root) { + var elements; + + if (typeof selector == "string") { + elements = Ext.dom.Element.selectorFunction(selector, root); + } + else if (selector.length !== undefined) { + elements = selector; + } + else { + throw new Error("[Ext.select] Invalid selector specified: " + selector); + } + + return new Ext.CompositeElementLite(elements); + }; + + /** + * @member Ext + * @method select + * @inheritdoc Ext.dom.Element#select + */ + Ext.select = function() { + return Ext.dom.Element.select.apply(Ext.dom.Element, arguments); + }; +}); + +/** + * @class Ext.dom.CompositeElement + *

    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.dom.Element} and + * {@link Ext.fx.Anim}. The methods from these classes will be performed on all the elements in this collection.

    + *

    All methods return this and can be chained.

    + * Usage: +
    
    + 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.define('Ext.dom.CompositeElement', { + alternateClassName: 'Ext.CompositeElement', + + extend: 'Ext.dom.CompositeElementLite', + + // private + getElement: function(el) { + // In this case just return it, since we already have a reference to it + return el; + }, + + // private + transformElement: function(el) { + return Ext.get(el); + } + +}, function() { + /** + * 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/HTMLElement[]} selector The CSS selector or an array of elements + * @param {Boolean} [unique] true to create a unique Ext.Element for each element (defaults to a shared flyweight object) + * @param {HTMLElement/String} [root] The root element of the query or id of the root + * @return {Ext.CompositeElementLite/Ext.CompositeElement} + * @member Ext.dom.Element + * @method select + * @static + */ + + Ext.dom.Element.select = function(selector, unique, root) { + var elements; + + if (typeof selector == "string") { + elements = Ext.dom.Element.selectorFunction(selector, root); + } + else if (selector.length !== undefined) { + elements = selector; + } + else { + throw new Error("[Ext.select] Invalid selector specified: " + selector); + } + return (unique === true) ? new Ext.CompositeElement(elements) : new Ext.CompositeElementLite(elements); + }; +}); + +/** + * Shorthand of {@link Ext.Element#method-select}. + * @member Ext + * @method select + * @inheritdoc Ext.Element#select + */ +Ext.select = Ext.Element.select; + + +this.ExtBootstrapData = { + "nameToAliasesMap":{ + "Ext.AbstractComponent":[], + "Ext.AbstractManager":[], + "Ext.AbstractPlugin":[], + "Ext.Ajax":[], + "Ext.ComponentLoader":[], + "Ext.ComponentManager":[], + "Ext.ComponentQuery":[], + "Ext.ElementLoader":[], + "Ext.ModelManager":[], + "Ext.PluginManager":[], + "Ext.Template":[], + "Ext.XTemplate":[], + "Ext.XTemplateCompiler":[], + "Ext.XTemplateParser":[], + "Ext.app.Application":[], + "Ext.app.Controller":[], + "Ext.app.EventBus":[], + "Ext.chart.Callout":[], + "Ext.chart.Chart":["widget.chart" + ], + "Ext.chart.Highlight":[], + "Ext.chart.Label":[], + "Ext.chart.Legend":[], + "Ext.chart.LegendItem":[], + "Ext.chart.Mask":[], + "Ext.chart.MaskLayer":[], + "Ext.chart.Navigation":[], + "Ext.chart.Shape":[], + "Ext.chart.Tip":[], + "Ext.chart.TipSurface":[], + "Ext.chart.axis.Abstract":[], + "Ext.chart.axis.Axis":[], + "Ext.chart.axis.Category":["axis.category" + ], + "Ext.chart.axis.Gauge":["axis.gauge" + ], + "Ext.chart.axis.Numeric":["axis.numeric" + ], + "Ext.chart.axis.Radial":["axis.radial" + ], + "Ext.chart.axis.Time":["axis.time" + ], + "Ext.chart.series.Area":["series.area" + ], + "Ext.chart.series.Bar":["series.bar" + ], + "Ext.chart.series.Cartesian":[], + "Ext.chart.series.Column":["series.column" + ], + "Ext.chart.series.Gauge":["series.gauge" + ], + "Ext.chart.series.Line":["series.line" + ], + "Ext.chart.series.Pie":["series.pie" + ], + "Ext.chart.series.Radar":["series.radar" + ], + "Ext.chart.series.Scatter":["series.scatter" + ], + "Ext.chart.series.Series":[], + "Ext.chart.theme.Base":[], + "Ext.chart.theme.Theme":[], + "Ext.container.AbstractContainer":[], + "Ext.container.DockingContainer":[], + "Ext.data.AbstractStore":[], + "Ext.data.ArrayStore":["store.array" + ], + "Ext.data.Batch":[], + "Ext.data.BufferStore":["store.buffer" + ], + "Ext.data.Connection":[], + "Ext.data.DirectStore":["store.direct" + ], + "Ext.data.Errors":[], + "Ext.data.Field":["data.field" + ], + "Ext.data.IdGenerator":[], + "Ext.data.JsonP":[], + "Ext.data.JsonPStore":["store.jsonp" + ], + "Ext.data.JsonStore":["store.json" + ], + "Ext.data.Model":[], + "Ext.data.NodeInterface":[], + "Ext.data.NodeStore":["store.node" + ], + "Ext.data.Operation":[], + "Ext.data.Request":[], + "Ext.data.ResultSet":[], + "Ext.data.SequentialIdGenerator":["idgen.sequential" + ], + "Ext.data.SortTypes":[], + "Ext.data.Store":["store.store" + ], + "Ext.data.StoreManager":[], + "Ext.data.Tree":["data.tree" + ], + "Ext.data.TreeStore":["store.tree" + ], + "Ext.data.Types":[], + "Ext.data.UuidGenerator":[], + "Ext.data.validations":[], + "Ext.data.XmlStore":["store.xml" + ], + "Ext.data.association.Association":[], + "Ext.data.association.BelongsTo":["association.belongsto" + ], + "Ext.data.association.HasMany":["association.hasmany" + ], + "Ext.data.association.HasOne":["association.hasone" + ], + "Ext.data.proxy.Ajax":["proxy.ajax" + ], + "Ext.data.proxy.Client":[], + "Ext.data.proxy.Direct":["proxy.direct" + ], + "Ext.data.proxy.JsonP":["proxy.jsonp", + "proxy.scripttag" + ], + "Ext.data.proxy.LocalStorage":["proxy.localstorage" + ], + "Ext.data.proxy.Memory":["proxy.memory" + ], + "Ext.data.proxy.Proxy":["proxy.proxy" + ], + "Ext.data.proxy.Rest":["proxy.rest" + ], + "Ext.data.proxy.Server":["proxy.server" + ], + "Ext.data.proxy.SessionStorage":["proxy.sessionstorage" + ], + "Ext.data.proxy.WebStorage":[], + "Ext.data.reader.Array":["reader.array" + ], + "Ext.data.reader.Json":["reader.json" + ], + "Ext.data.reader.Reader":[], + "Ext.data.reader.Xml":["reader.xml" + ], + "Ext.data.writer.Json":["writer.json" + ], + "Ext.data.writer.Writer":["writer.base" + ], + "Ext.data.writer.Xml":["writer.xml" + ], + "Ext.direct.Event":["direct.event" + ], + "Ext.direct.ExceptionEvent":["direct.exception" + ], + "Ext.direct.JsonProvider":["direct.jsonprovider" + ], + "Ext.direct.Manager":[], + "Ext.direct.PollingProvider":["direct.pollingprovider" + ], + "Ext.direct.Provider":["direct.provider" + ], + "Ext.direct.RemotingEvent":["direct.rpc" + ], + "Ext.direct.RemotingMethod":[], + "Ext.direct.RemotingProvider":["direct.remotingprovider" + ], + "Ext.direct.Transaction":["direct.transaction" + ], + "Ext.draw.Color":[], + "Ext.draw.Component":["widget.draw" + ], + "Ext.draw.CompositeSprite":[], + "Ext.draw.Draw":[], + "Ext.draw.Matrix":[], + "Ext.draw.Sprite":[], + "Ext.draw.SpriteDD":[], + "Ext.draw.Surface":[], + "Ext.draw.Text":["widget.text" + ], + "Ext.draw.engine.ImageExporter":[], + "Ext.draw.engine.Svg":[], + "Ext.draw.engine.SvgExporter":[], + "Ext.draw.engine.Vml":[], + "Ext.fx.Anim":[], + "Ext.fx.Animator":[], + "Ext.fx.CubicBezier":[], + "Ext.fx.Manager":[], + "Ext.fx.PropertyHandler":[], + "Ext.fx.Queue":[], + "Ext.fx.target.Component":[], + "Ext.fx.target.CompositeElement":[], + "Ext.fx.target.CompositeElementCSS":[], + "Ext.fx.target.CompositeSprite":[], + "Ext.fx.target.Element":[], + "Ext.fx.target.ElementCSS":[], + "Ext.fx.target.Sprite":[], + "Ext.fx.target.Target":[], + "Ext.layout.ClassList":[], + "Ext.layout.Context":[], + "Ext.layout.ContextItem":[], + "Ext.layout.Layout":[], + "Ext.layout.component.Auto":["layout.autocomponent" + ], + "Ext.layout.component.Component":[], + "Ext.layout.component.Draw":["layout.draw" + ], + "Ext.layout.container.Auto":["layout.auto", + "layout.autocontainer" + ], + "Ext.panel.AbstractPanel":[], + "Ext.selection.DataViewModel":[], + "Ext.selection.Model":[], + "Ext.state.CookieProvider":[], + "Ext.state.LocalStorageProvider":["state.localstorage" + ], + "Ext.state.Manager":[], + "Ext.state.Provider":[], + "Ext.state.Stateful":[], + "Ext.util.AbstractMixedCollection":[], + "Ext.util.Bindable":[], + "Ext.util.ElementContainer":[], + "Ext.util.Filter":[], + "Ext.util.Grouper":[], + "Ext.util.HashMap":[], + "Ext.util.Inflector":[], + "Ext.util.LruCache":[], + "Ext.util.Memento":[], + "Ext.util.MixedCollection":[], + "Ext.util.Observable":[], + "Ext.util.Offset":[], + "Ext.util.Point":[], + "Ext.util.ProtoElement":[], + "Ext.util.Queue":[], + "Ext.util.Region":[], + "Ext.util.Renderable":[], + "Ext.util.Sortable":[], + "Ext.util.Sorter":[], + "Ext.view.AbstractView":[], + "Ext.Action":[], + "Ext.Component":["widget.component", + "widget.box" + ], + "Ext.Editor":["widget.editor" + ], + "Ext.FocusManager":[], + "Ext.Img":["widget.image", + "widget.imagecomponent" + ], + "Ext.Layer":[], + "Ext.LoadMask":["widget.loadmask" + ], + "Ext.ProgressBar":["widget.progressbar" + ], + "Ext.Shadow":[], + "Ext.ShadowPool":[], + "Ext.ZIndexManager":[], + "Ext.button.Button":["widget.button" + ], + "Ext.button.Cycle":["widget.cycle" + ], + "Ext.button.Split":["widget.splitbutton" + ], + "Ext.container.ButtonGroup":["widget.buttongroup" + ], + "Ext.container.Container":["widget.container" + ], + "Ext.container.Viewport":["widget.viewport" + ], + "Ext.dd.DD":[], + "Ext.dd.DDProxy":[], + "Ext.dd.DDTarget":[], + "Ext.dd.DragDrop":[], + "Ext.dd.DragDropManager":[], + "Ext.dd.DragSource":[], + "Ext.dd.DragTracker":[], + "Ext.dd.DragZone":[], + "Ext.dd.DropTarget":[], + "Ext.dd.DropZone":[], + "Ext.dd.Registry":[], + "Ext.dd.ScrollManager":[], + "Ext.dd.StatusProxy":[], + "Ext.dom.Element":[], + "Ext.dom.Helper":[], + "Ext.flash.Component":["widget.flash" + ], + "Ext.form.Basic":[], + "Ext.form.CheckboxGroup":["widget.checkboxgroup" + ], + "Ext.form.CheckboxManager":[], + "Ext.form.FieldAncestor":[], + "Ext.form.FieldContainer":["widget.fieldcontainer" + ], + "Ext.form.FieldSet":["widget.fieldset" + ], + "Ext.form.Label":["widget.label" + ], + "Ext.form.Labelable":[], + "Ext.form.Panel":["widget.form" + ], + "Ext.form.RadioGroup":["widget.radiogroup" + ], + "Ext.form.RadioManager":[], + "Ext.form.action.Action":[], + "Ext.form.action.DirectLoad":["formaction.directload" + ], + "Ext.form.action.DirectSubmit":["formaction.directsubmit" + ], + "Ext.form.action.Load":["formaction.load" + ], + "Ext.form.action.StandardSubmit":["formaction.standardsubmit" + ], + "Ext.form.action.Submit":["formaction.submit" + ], + "Ext.form.field.Base":["widget.field" + ], + "Ext.form.field.Checkbox":["widget.checkboxfield", + "widget.checkbox" + ], + "Ext.form.field.ComboBox":["widget.combobox", + "widget.combo" + ], + "Ext.form.field.Date":["widget.datefield" + ], + "Ext.form.field.Display":["widget.displayfield" + ], + "Ext.form.field.Field":[], + "Ext.form.field.File":["widget.filefield", + "widget.fileuploadfield" + ], + "Ext.form.field.Hidden":["widget.hiddenfield", + "widget.hidden" + ], + "Ext.form.field.HtmlEditor":["widget.htmleditor" + ], + "Ext.form.field.Number":["widget.numberfield" + ], + "Ext.form.field.Picker":["widget.pickerfield" + ], + "Ext.form.field.Radio":["widget.radiofield", + "widget.radio" + ], + "Ext.form.field.Spinner":["widget.spinnerfield" + ], + "Ext.form.field.Text":["widget.textfield" + ], + "Ext.form.field.TextArea":["widget.textareafield", + "widget.textarea" + ], + "Ext.form.field.Time":["widget.timefield" + ], + "Ext.form.field.Trigger":["widget.triggerfield", + "widget.trigger" + ], + "Ext.form.field.VTypes":[], + "Ext.grid.CellEditor":[], + "Ext.grid.ColumnComponentLayout":["layout.columncomponent" + ], + "Ext.grid.ColumnLayout":["layout.gridcolumn" + ], + "Ext.grid.Lockable":[], + "Ext.grid.LockingView":[], + "Ext.grid.PagingScroller":[], + "Ext.grid.Panel":["widget.gridpanel", + "widget.grid" + ], + "Ext.grid.RowEditor":[], + "Ext.grid.RowNumberer":["widget.rownumberer" + ], + "Ext.grid.Scroller":[], + "Ext.grid.View":["widget.gridview" + ], + "Ext.grid.ViewDropZone":[], + "Ext.grid.column.Action":["widget.actioncolumn" + ], + "Ext.grid.column.Boolean":["widget.booleancolumn" + ], + "Ext.grid.column.Column":["widget.gridcolumn" + ], + "Ext.grid.column.Date":["widget.datecolumn" + ], + "Ext.grid.column.Number":["widget.numbercolumn" + ], + "Ext.grid.column.Template":["widget.templatecolumn" + ], + "Ext.grid.feature.AbstractSummary":["feature.abstractsummary" + ], + "Ext.grid.feature.Chunking":["feature.chunking" + ], + "Ext.grid.feature.Feature":["feature.feature" + ], + "Ext.grid.feature.Grouping":["feature.grouping" + ], + "Ext.grid.feature.GroupingSummary":["feature.groupingsummary" + ], + "Ext.grid.feature.RowBody":["feature.rowbody" + ], + "Ext.grid.feature.RowWrap":["feature.rowwrap" + ], + "Ext.grid.feature.Summary":["feature.summary" + ], + "Ext.grid.header.Container":["widget.headercontainer" + ], + "Ext.grid.header.DragZone":[], + "Ext.grid.header.DropZone":[], + "Ext.grid.plugin.CellEditing":["plugin.cellediting" + ], + "Ext.grid.plugin.DragDrop":["plugin.gridviewdragdrop" + ], + "Ext.grid.plugin.Editing":["editing.editing" + ], + "Ext.grid.plugin.HeaderReorderer":["plugin.gridheaderreorderer" + ], + "Ext.grid.plugin.HeaderResizer":["plugin.gridheaderresizer" + ], + "Ext.grid.plugin.RowEditing":["plugin.rowediting" + ], + "Ext.grid.property.Grid":["widget.propertygrid" + ], + "Ext.grid.property.HeaderContainer":[], + "Ext.grid.property.Property":[], + "Ext.grid.property.Store":[], + "Ext.layout.component.Body":["layout.body" + ], + "Ext.layout.component.BoundList":["layout.boundlist" + ], + "Ext.layout.component.Button":["layout.button" + ], + "Ext.layout.component.Dock":["layout.dock" + ], + "Ext.layout.component.FieldSet":["layout.fieldset" + ], + "Ext.layout.component.ProgressBar":["layout.progressbar" + ], + "Ext.layout.component.Tab":["layout.tab" + ], + "Ext.layout.component.field.ComboBox":["layout.combobox" + ], + "Ext.layout.component.field.Field":["layout.field" + ], + "Ext.layout.component.field.FieldContainer":["layout.fieldcontainer" + ], + "Ext.layout.component.field.HtmlEditor":["layout.htmleditor" + ], + "Ext.layout.component.field.Slider":["layout.sliderfield" + ], + "Ext.layout.component.field.Text":["layout.textfield" + ], + "Ext.layout.component.field.TextArea":["layout.textareafield" + ], + "Ext.layout.component.field.Trigger":["layout.triggerfield" + ], + "Ext.layout.container.Absolute":["layout.absolute" + ], + "Ext.layout.container.Accordion":["layout.accordion" + ], + "Ext.layout.container.Anchor":["layout.anchor" + ], + "Ext.layout.container.Border":["layout.border" + ], + "Ext.layout.container.Box":["layout.box" + ], + "Ext.layout.container.Card":["layout.card" + ], + "Ext.layout.container.CheckboxGroup":["layout.checkboxgroup" + ], + "Ext.layout.container.Column":["layout.column" + ], + "Ext.layout.container.Container":[], + "Ext.layout.container.Editor":["layout.editor" + ], + "Ext.layout.container.Fit":["layout.fit" + ], + "Ext.layout.container.Form":["layout.form" + ], + "Ext.layout.container.HBox":["layout.hbox" + ], + "Ext.layout.container.Table":["layout.table" + ], + "Ext.layout.container.VBox":["layout.vbox" + ], + "Ext.layout.container.boxOverflow.Menu":[], + "Ext.layout.container.boxOverflow.None":[], + "Ext.layout.container.boxOverflow.Scroller":[], + "Ext.menu.CheckItem":["widget.menucheckitem" + ], + "Ext.menu.ColorPicker":["widget.colormenu" + ], + "Ext.menu.DatePicker":["widget.datemenu" + ], + "Ext.menu.Item":["widget.menuitem" + ], + "Ext.menu.KeyNav":[], + "Ext.menu.Manager":[], + "Ext.menu.Menu":["widget.menu" + ], + "Ext.menu.Separator":["widget.menuseparator" + ], + "Ext.panel.DD":[], + "Ext.panel.Header":["widget.header" + ], + "Ext.panel.Panel":["widget.panel" + ], + "Ext.panel.Proxy":[], + "Ext.panel.Table":["widget.tablepanel" + ], + "Ext.panel.Tool":["widget.tool" + ], + "Ext.picker.Color":["widget.colorpicker" + ], + "Ext.picker.Date":["widget.datepicker" + ], + "Ext.picker.Month":["widget.monthpicker" + ], + "Ext.picker.Time":["widget.timepicker" + ], + "Ext.resizer.BorderSplitter":["widget.bordersplitter" + ], + "Ext.resizer.BorderSplitterTracker":[], + "Ext.resizer.Handle":[], + "Ext.resizer.Resizer":[], + "Ext.resizer.ResizeTracker":[], + "Ext.resizer.Splitter":["widget.splitter" + ], + "Ext.resizer.SplitterTracker":[], + "Ext.selection.CellModel":["selection.cellmodel" + ], + "Ext.selection.CheckboxModel":["selection.checkboxmodel" + ], + "Ext.selection.RowModel":["selection.rowmodel" + ], + "Ext.selection.TreeModel":["selection.treemodel" + ], + "Ext.slider.Multi":["widget.multislider" + ], + "Ext.slider.Single":["widget.slider", + "widget.sliderfield" + ], + "Ext.slider.Thumb":[], + "Ext.slider.Tip":["widget.slidertip" + ], + "Ext.tab.Bar":["widget.tabbar" + ], + "Ext.tab.Panel":["widget.tabpanel" + ], + "Ext.tab.Tab":["widget.tab" + ], + "Ext.tip.QuickTip":["widget.quicktip" + ], + "Ext.tip.QuickTipManager":[], + "Ext.tip.Tip":[], + "Ext.tip.ToolTip":["widget.tooltip" + ], + "Ext.toolbar.Fill":["widget.tbfill" + ], + "Ext.toolbar.Item":["widget.tbitem" + ], + "Ext.toolbar.Paging":["widget.pagingtoolbar" + ], + "Ext.toolbar.Separator":["widget.tbseparator" + ], + "Ext.toolbar.Spacer":["widget.tbspacer" + ], + "Ext.toolbar.TextItem":["widget.tbtext" + ], + "Ext.toolbar.Toolbar":["widget.toolbar" + ], + "Ext.tree.Column":["widget.treecolumn" + ], + "Ext.tree.Panel":["widget.treepanel" + ], + "Ext.tree.View":["widget.treeview" + ], + "Ext.tree.ViewDragZone":[], + "Ext.tree.ViewDropZone":[], + "Ext.tree.plugin.TreeViewDragDrop":["plugin.treeviewdragdrop" + ], + "Ext.util.Animate":[], + "Ext.util.ClickRepeater":[], + "Ext.util.ComponentDragger":[], + "Ext.util.Cookies":[], + "Ext.util.CSS":[], + "Ext.util.Floating":[], + "Ext.util.History":[], + "Ext.util.KeyMap":[], + "Ext.util.KeyNav":[], + "Ext.util.TextMetrics":[], + "Ext.view.BoundList":["widget.boundlist" + ], + "Ext.view.BoundListKeyNav":[], + "Ext.view.DragZone":[], + "Ext.view.DropZone":[], + "Ext.view.Table":["widget.tableview" + ], + "Ext.view.TableChunker":[], + "Ext.view.View":["widget.dataview" + ], + "Ext.window.MessageBox":["widget.messagebox" + ], + "Ext.window.Window":["widget.window" + ] + }, + "alternateToNameMap":{ + "Ext.ComponentMgr":"Ext.ComponentManager", + "Ext.ModelMgr":"Ext.ModelManager", + "Ext.PluginMgr":"Ext.PluginManager", + "Ext.chart.Axis":"Ext.chart.axis.Axis", + "Ext.chart.CategoryAxis":"Ext.chart.axis.Category", + "Ext.chart.NumericAxis":"Ext.chart.axis.Numeric", + "Ext.chart.TimeAxis":"Ext.chart.axis.Time", + "Ext.chart.BarSeries":"Ext.chart.series.Bar", + "Ext.chart.BarChart":"Ext.chart.series.Bar", + "Ext.chart.StackedBarChart":"Ext.chart.series.Bar", + "Ext.chart.CartesianSeries":"Ext.chart.series.Cartesian", + "Ext.chart.CartesianChart":"Ext.chart.series.Cartesian", + "Ext.chart.ColumnSeries":"Ext.chart.series.Column", + "Ext.chart.ColumnChart":"Ext.chart.series.Column", + "Ext.chart.StackedColumnChart":"Ext.chart.series.Column", + "Ext.chart.LineSeries":"Ext.chart.series.Line", + "Ext.chart.LineChart":"Ext.chart.series.Line", + "Ext.chart.PieSeries":"Ext.chart.series.Pie", + "Ext.chart.PieChart":"Ext.chart.series.Pie", + "Ext.data.Record":"Ext.data.Model", + "Ext.StoreMgr":"Ext.data.StoreManager", + "Ext.data.StoreMgr":"Ext.data.StoreManager", + "Ext.StoreManager":"Ext.data.StoreManager", + "Ext.data.Association":"Ext.data.association.Association", + "Ext.data.BelongsToAssociation":"Ext.data.association.BelongsTo", + "Ext.data.HasManyAssociation":"Ext.data.association.HasMany", + "Ext.data.HasOneAssociation":"Ext.data.association.HasOne", + "Ext.data.HttpProxy":"Ext.data.proxy.Ajax", + "Ext.data.AjaxProxy":"Ext.data.proxy.Ajax", + "Ext.data.ClientProxy":"Ext.data.proxy.Client", + "Ext.data.DirectProxy":"Ext.data.proxy.Direct", + "Ext.data.ScriptTagProxy":"Ext.data.proxy.JsonP", + "Ext.data.LocalStorageProxy":"Ext.data.proxy.LocalStorage", + "Ext.data.MemoryProxy":"Ext.data.proxy.Memory", + "Ext.data.DataProxy":"Ext.data.proxy.Proxy", + "Ext.data.Proxy":"Ext.data.proxy.Proxy", + "Ext.data.RestProxy":"Ext.data.proxy.Rest", + "Ext.data.ServerProxy":"Ext.data.proxy.Server", + "Ext.data.SessionStorageProxy":"Ext.data.proxy.SessionStorage", + "Ext.data.WebStorageProxy":"Ext.data.proxy.WebStorage", + "Ext.data.ArrayReader":"Ext.data.reader.Array", + "Ext.data.JsonReader":"Ext.data.reader.Json", + "Ext.data.Reader":"Ext.data.reader.Reader", + "Ext.data.DataReader":"Ext.data.reader.Reader", + "Ext.data.XmlReader":"Ext.data.reader.Xml", + "Ext.data.JsonWriter":"Ext.data.writer.Json", + "Ext.data.DataWriter":"Ext.data.writer.Writer", + "Ext.data.Writer":"Ext.data.writer.Writer", + "Ext.data.XmlWriter":"Ext.data.writer.Xml", + "Ext.Direct.Transaction":"Ext.direct.Transaction", + "Ext.AbstractSelectionModel":"Ext.selection.Model", + "Ext.FocusMgr":"Ext.FocusManager", + "Ext.WindowGroup":"Ext.ZIndexManager", + "Ext.Button":"Ext.button.Button", + "Ext.CycleButton":"Ext.button.Cycle", + "Ext.SplitButton":"Ext.button.Split", + "Ext.ButtonGroup":"Ext.container.ButtonGroup", + "Ext.Container":"Ext.container.Container", + "Ext.Viewport":"Ext.container.Viewport", + "Ext.dd.DragDropMgr":"Ext.dd.DragDropManager", + "Ext.dd.DDM":"Ext.dd.DragDropManager", + "Ext.Element":"Ext.dom.Element", + "Ext.core.Element":"Ext.dom.Element", + "Ext.FlashComponent":"Ext.flash.Component", + "Ext.form.BasicForm":"Ext.form.Basic", + "Ext.FormPanel":"Ext.form.Panel", + "Ext.form.FormPanel":"Ext.form.Panel", + "Ext.form.Action":"Ext.form.action.Action", + "Ext.form.Action.DirectLoad":"Ext.form.action.DirectLoad", + "Ext.form.Action.DirectSubmit":"Ext.form.action.DirectSubmit", + "Ext.form.Action.Load":"Ext.form.action.Load", + "Ext.form.Action.Submit":"Ext.form.action.Submit", + "Ext.form.Field":"Ext.form.field.Base", + "Ext.form.BaseField":"Ext.form.field.Base", + "Ext.form.Checkbox":"Ext.form.field.Checkbox", + "Ext.form.ComboBox":"Ext.form.field.ComboBox", + "Ext.form.DateField":"Ext.form.field.Date", + "Ext.form.Date":"Ext.form.field.Date", + "Ext.form.DisplayField":"Ext.form.field.Display", + "Ext.form.Display":"Ext.form.field.Display", + "Ext.form.FileUploadField":"Ext.form.field.File", + "Ext.ux.form.FileUploadField":"Ext.form.field.File", + "Ext.form.File":"Ext.form.field.File", + "Ext.form.Hidden":"Ext.form.field.Hidden", + "Ext.form.HtmlEditor":"Ext.form.field.HtmlEditor", + "Ext.form.NumberField":"Ext.form.field.Number", + "Ext.form.Number":"Ext.form.field.Number", + "Ext.form.Picker":"Ext.form.field.Picker", + "Ext.form.Radio":"Ext.form.field.Radio", + "Ext.form.Spinner":"Ext.form.field.Spinner", + "Ext.form.TextField":"Ext.form.field.Text", + "Ext.form.Text":"Ext.form.field.Text", + "Ext.form.TextArea":"Ext.form.field.TextArea", + "Ext.form.TimeField":"Ext.form.field.Time", + "Ext.form.Time":"Ext.form.field.Time", + "Ext.form.TriggerField":"Ext.form.field.Trigger", + "Ext.form.TwinTriggerField":"Ext.form.field.Trigger", + "Ext.form.Trigger":"Ext.form.field.Trigger", + "Ext.list.ListView":"Ext.grid.Panel", + "Ext.ListView":"Ext.grid.Panel", + "Ext.grid.GridPanel":"Ext.grid.Panel", + "Ext.grid.ActionColumn":"Ext.grid.column.Action", + "Ext.grid.BooleanColumn":"Ext.grid.column.Boolean", + "Ext.grid.Column":"Ext.grid.column.Column", + "Ext.grid.DateColumn":"Ext.grid.column.Date", + "Ext.grid.NumberColumn":"Ext.grid.column.Number", + "Ext.grid.TemplateColumn":"Ext.grid.column.Template", + "Ext.grid.PropertyGrid":"Ext.grid.property.Grid", + "Ext.grid.PropertyColumnModel":"Ext.grid.property.HeaderContainer", + "Ext.PropGridProperty":"Ext.grid.property.Property", + "Ext.grid.PropertyStore":"Ext.grid.property.Store", + "Ext.layout.component.AbstractDock":"Ext.layout.component.Dock", + "Ext.layout.AbsoluteLayout":"Ext.layout.container.Absolute", + "Ext.layout.AccordionLayout":"Ext.layout.container.Accordion", + "Ext.layout.AnchorLayout":"Ext.layout.container.Anchor", + "Ext.layout.BorderLayout":"Ext.layout.container.Border", + "Ext.layout.BoxLayout":"Ext.layout.container.Box", + "Ext.layout.CardLayout":"Ext.layout.container.Card", + "Ext.layout.ColumnLayout":"Ext.layout.container.Column", + "Ext.layout.ContainerLayout":"Ext.layout.container.Container", + "Ext.layout.FitLayout":"Ext.layout.container.Fit", + "Ext.layout.FormLayout":"Ext.layout.container.Form", + "Ext.layout.HBoxLayout":"Ext.layout.container.HBox", + "Ext.layout.TableLayout":"Ext.layout.container.Table", + "Ext.layout.VBoxLayout":"Ext.layout.container.VBox", + "Ext.layout.boxOverflow.Menu":"Ext.layout.container.boxOverflow.Menu", + "Ext.layout.boxOverflow.None":"Ext.layout.container.boxOverflow.None", + "Ext.layout.boxOverflow.Scroller":"Ext.layout.container.boxOverflow.Scroller", + "Ext.menu.TextItem":"Ext.menu.Item", + "Ext.menu.MenuMgr":"Ext.menu.Manager", + "Ext.Panel":"Ext.panel.Panel", + "Ext.dd.PanelProxy":"Ext.panel.Proxy", + "Ext.ColorPalette":"Ext.picker.Color", + "Ext.DatePicker":"Ext.picker.Date", + "Ext.MonthPicker":"Ext.picker.Month", + "Ext.Resizable":"Ext.resizer.Resizer", + "Ext.slider.MultiSlider":"Ext.slider.Multi", + "Ext.Slider":"Ext.slider.Single", + "Ext.form.SliderField":"Ext.slider.Single", + "Ext.slider.SingleSlider":"Ext.slider.Single", + "Ext.slider.Slider":"Ext.slider.Single", + "Ext.TabPanel":"Ext.tab.Panel", + "Ext.QuickTip":"Ext.tip.QuickTip", + "Ext.Tip":"Ext.tip.Tip", + "Ext.ToolTip":"Ext.tip.ToolTip", + "Ext.Toolbar.Fill":"Ext.toolbar.Fill", + "Ext.Toolbar.Item":"Ext.toolbar.Item", + "Ext.PagingToolbar":"Ext.toolbar.Paging", + "Ext.Toolbar.Separator":"Ext.toolbar.Separator", + "Ext.Toolbar.Spacer":"Ext.toolbar.Spacer", + "Ext.Toolbar.TextItem":"Ext.toolbar.TextItem", + "Ext.Toolbar":"Ext.toolbar.Toolbar", + "Ext.tree.TreePanel":"Ext.tree.Panel", + "Ext.TreePanel":"Ext.tree.Panel", + "Ext.History":"Ext.util.History", + "Ext.KeyMap":"Ext.util.KeyMap", + "Ext.KeyNav":"Ext.util.KeyNav", + "Ext.BoundList":"Ext.view.BoundList", + "Ext.DataView":"Ext.view.View", + "Ext.Window":"Ext.window.Window" + } +}; + +(function() { + var scripts = document.getElementsByTagName('script'), + currentScript = scripts[scripts.length - 1], + src = currentScript.src, + path = src.substring(0, src.lastIndexOf('/') + 1), + Loader = Ext.Loader, + ClassManager = Ext.ClassManager, + data = this.ExtBootstrapData, + nameToAliasesMap = data.nameToAliasesMap, + alternateToNameMap = data.alternateToNameMap, + i, ln, name, aliases; + + if (nameToAliasesMap) { + for (name in nameToAliasesMap) { + if (nameToAliasesMap.hasOwnProperty(name)) { + aliases = nameToAliasesMap[name]; + + if (aliases.length > 0) { + for (i = 0,ln = aliases.length; i < ln; i++) { + ClassManager.setAlias(name, aliases[i]); + } + } + else { + ClassManager.setAlias(name, null); + } + } + } + } + + if (alternateToNameMap) { + Ext.merge(ClassManager.maps.alternateToName, alternateToNameMap); + } + + Loader.setConfig({ + enabled: true, + disableCaching: true, + paths: { + 'Ext': path + 'src' + } + }); + + try { + delete this.ExtBootstrapData; + } catch (e) { + this.ExtBootstrapData = null; + } +})(); + + +/* + * This file represents the very last stage of the Ext definition process and is ensured + * to be included at the end of the build via the 'tail' package of extjs.jsb3. + * + */ + +Ext._endTime = new Date().getTime(); +if (Ext._beforereadyhandler){ + Ext._beforereadyhandler(); +} + + diff --git a/test/testcase/ext.js b/test/testcase/ext.js new file mode 100644 index 0000000..792282d --- /dev/null +++ b/test/testcase/ext.js @@ -0,0 +1,21 @@ +/* +This file is part of Ext JS 4.1 + +Copyright (c) 2011-2012 Sencha Inc + +Contact: http://www.sencha.com/contact + +GNU General Public License Usage +This file may be used under the terms of the GNU General Public License version 3.0 as +published by the Free Software Foundation and appearing in the file LICENSE included in the +packaging of this file. + +Please review the following information to ensure the GNU General Public License version 3.0 +requirements will be met: http://www.gnu.org/copyleft/gpl.html. + +If you are unsure which license is appropriate for your use, please contact the sales department +at http://www.sencha.com/contact. + +Build date: 2012-04-20 14:10:47 (19f55ab932145a3443b228045fa80950dfeaf9cc) +*/ +var Ext=Ext||{};Ext._startTime=new Date().getTime();(function(){var h=this,a=Object.prototype,j=a.toString,b=true,g={toString:1},e=function(){},d=function(){var i=d.caller.caller;return i.$owner.prototype[i.$name].apply(this,arguments)},c;Ext.global=h;for(c in g){b=null}if(b){b=["hasOwnProperty","valueOf","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","constructor"]}Ext.enumerables=b;Ext.apply=function(o,n,q){if(q){Ext.apply(o,q)}if(o&&n&&typeof n==="object"){var p,m,l;for(p in n){o[p]=n[p]}if(b){for(m=b.length;m--;){l=b[m];if(n.hasOwnProperty(l)){o[l]=n[l]}}}}return o};Ext.buildSettings=Ext.apply({baseCSSPrefix:"x-",scopeResetCSS:false},Ext.buildSettings||{});Ext.apply(Ext,{name:Ext.sandboxName||"Ext",emptyFn:e,emptyString:new String(),baseCSSPrefix:Ext.buildSettings.baseCSSPrefix,applyIf:function(k,i){var l;if(k){for(l in i){if(k[l]===undefined){k[l]=i[l]}}}return k},iterate:function(i,l,k){if(Ext.isEmpty(i)){return}if(k===undefined){k=i}if(Ext.isIterable(i)){Ext.Array.each.call(Ext.Array,i,l,k)}else{Ext.Object.each.call(Ext.Object,i,l,k)}}});Ext.apply(Ext,{extend:(function(){var i=a.constructor,k=function(n){for(var l in n){if(!n.hasOwnProperty(l)){continue}this[l]=n[l]}};return function(l,q,o){if(Ext.isObject(q)){o=q;q=l;l=o.constructor!==i?o.constructor:function(){q.apply(this,arguments)}}var n=function(){},m,p=q.prototype;n.prototype=p;m=l.prototype=new n();m.constructor=l;l.superclass=p;if(p.constructor===i){p.constructor=q}l.override=function(r){Ext.override(l,r)};m.override=k;m.proto=m;l.override(o);l.extend=function(r){return Ext.extend(l,r)};return l}}()),override:function(m,n){if(m.$isClass){m.override(n)}else{if(typeof m=="function"){Ext.apply(m.prototype,n)}else{var i=m.self,k,l;if(i&&i.$isClass){for(k in n){if(n.hasOwnProperty(k)){l=n[k];if(typeof l=="function"){l.$name=k;l.$owner=i;l.$previous=m.hasOwnProperty(k)?m[k]:d}m[k]=l}}}else{Ext.apply(m,n)}}}return m}});Ext.apply(Ext,{valueFrom:function(l,i,k){return Ext.isEmpty(l,k)?i:l},typeOf:function(k){var i,l;if(k===null){return"null"}i=typeof k;if(i==="undefined"||i==="string"||i==="number"||i==="boolean"){return i}l=j.call(k);switch(l){case"[object Array]":return"array";case"[object Date]":return"date";case"[object Boolean]":return"boolean";case"[object Number]":return"number";case"[object RegExp]":return"regexp"}if(i==="function"){return"function"}if(i==="object"){if(k.nodeType!==undefined){if(k.nodeType===3){return(/\S/).test(k.nodeValue)?"textnode":"whitespace"}else{return"element"}}return"object"}},isEmpty:function(i,k){return(i===null)||(i===undefined)||(!k?i==="":false)||(Ext.isArray(i)&&i.length===0)},isArray:("isArray" in Array)?Array.isArray:function(i){return j.call(i)==="[object Array]"},isDate:function(i){return j.call(i)==="[object Date]"},isObject:(j.call(null)==="[object Object]")?function(i){return i!==null&&i!==undefined&&j.call(i)==="[object Object]"&&i.ownerDocument===undefined}:function(i){return j.call(i)==="[object Object]"},isSimpleObject:function(i){return i instanceof Object&&i.constructor===Object},isPrimitive:function(k){var i=typeof k;return i==="string"||i==="number"||i==="boolean"},isFunction:(typeof document!=="undefined"&&typeof document.getElementsByTagName("body")==="function")?function(i){return j.call(i)==="[object Function]"}:function(i){return typeof i==="function"},isNumber:function(i){return typeof i==="number"&&isFinite(i)},isNumeric:function(i){return !isNaN(parseFloat(i))&&isFinite(i)},isString:function(i){return typeof i==="string"},isBoolean:function(i){return typeof i==="boolean"},isElement:function(i){return i?i.nodeType===1:false},isTextNode:function(i){return i?i.nodeName==="#text":false},isDefined:function(i){return typeof i!=="undefined"},isIterable:function(k){var i=typeof k,l=false;if(k&&i!="string"){if(i=="function"){if(Ext.isSafari){l=k instanceof NodeList||k instanceof HTMLCollection}}else{l=true}}return l?k.length!==undefined:false}});Ext.apply(Ext,{clone:function(q){var p,o,m,l,r,n;if(q===null||q===undefined){return q}if(q.nodeType&&q.cloneNode){return q.cloneNode(true)}p=j.call(q);if(p==="[object Date]"){return new Date(q.getTime())}if(p==="[object Array]"){o=q.length;r=[];while(o--){r[o]=Ext.clone(q[o])}}else{if(p==="[object Object]"&&q.constructor===Object){r={};for(n in q){r[n]=Ext.clone(q[n])}if(b){for(m=b.length;m--;){l=b[m];r[l]=q[l]}}}}return r||q},getUniqueGlobalNamespace:function(){var l=this.uniqueGlobalNamespace,k;if(l===undefined){k=0;do{l="ExtBox"+(++k)}while(Ext.global[l]!==undefined);Ext.global[l]=Ext;this.uniqueGlobalNamespace=l}return l},functionFactoryCache:{},cacheableFunctionFactory:function(){var o=this,l=Array.prototype.slice.call(arguments),k=o.functionFactoryCache,i,m,n;if(Ext.isSandboxed){n=l.length;if(n>0){n--;l[n]="var Ext=window."+Ext.name+";"+l[n]}}i=l.join("");m=k[i];if(!m){m=Function.prototype.constructor.apply(Function.prototype,l);k[i]=m}return m},functionFactory:function(){var l=this,i=Array.prototype.slice.call(arguments),k;if(Ext.isSandboxed){k=i.length;if(k>0){k--;i[k]="var Ext=window."+Ext.name+";"+i[k]}}return Function.prototype.constructor.apply(Function.prototype,i)},Logger:{verbose:e,log:e,info:e,warn:e,error:function(i){throw new Error(i)},deprecate:e}});Ext.type=Ext.typeOf}());Ext.globalEval=Ext.global.execScript?function(a){execScript(a)}:function($$code){(function(){eval($$code)}())};(function(){var a="4.1.0",b;Ext.Version=b=Ext.extend(Object,{constructor:function(c){var e,d;if(c instanceof b){return c}this.version=this.shortVersion=String(c).toLowerCase().replace(/_/g,".").replace(/[\-+]/g,"");d=this.version.search(/([^\d\.])/);if(d!==-1){this.release=this.version.substr(d,c.length);this.shortVersion=this.version.substr(0,d)}this.shortVersion=this.shortVersion.replace(/[^\d]/g,"");e=this.version.split(".");this.major=parseInt(e.shift()||0,10);this.minor=parseInt(e.shift()||0,10);this.patch=parseInt(e.shift()||0,10);this.build=parseInt(e.shift()||0,10);return this},toString:function(){return this.version},valueOf:function(){return this.version},getMajor:function(){return this.major||0},getMinor:function(){return this.minor||0},getPatch:function(){return this.patch||0},getBuild:function(){return this.build||0},getRelease:function(){return this.release||""},isGreaterThan:function(c){return b.compare(this.version,c)===1},isGreaterThanOrEqual:function(c){return b.compare(this.version,c)>=0},isLessThan:function(c){return b.compare(this.version,c)===-1},isLessThanOrEqual:function(c){return b.compare(this.version,c)<=0},equals:function(c){return b.compare(this.version,c)===0},match:function(c){c=String(c);return this.version.substr(0,c.length)===c},toArray:function(){return[this.getMajor(),this.getMinor(),this.getPatch(),this.getBuild(),this.getRelease()]},getShortVersion:function(){return this.shortVersion},gt:function(){return this.isGreaterThan.apply(this,arguments)},lt:function(){return this.isLessThan.apply(this,arguments)},gtEq:function(){return this.isGreaterThanOrEqual.apply(this,arguments)},ltEq:function(){return this.isLessThanOrEqual.apply(this,arguments)}});Ext.apply(b,{releaseValueMap:{dev:-6,alpha:-5,a:-5,beta:-4,b:-4,rc:-3,"#":-2,p:-1,pl:-1},getComponentValue:function(c){return !c?0:(isNaN(c)?this.releaseValueMap[c]||c:parseInt(c,10))},compare:function(h,g){var d,e,c;h=new b(h).toArray();g=new b(g).toArray();for(c=0;ce){return 1}}}return 0}});Ext.apply(Ext,{versions:{},lastRegisteredVersion:null,setVersion:function(d,c){Ext.versions[d]=new b(c);Ext.lastRegisteredVersion=Ext.versions[d];return this},getVersion:function(c){if(c===undefined){return Ext.lastRegisteredVersion}return Ext.versions[c]},deprecate:function(c,e,g,d){if(b.compare(Ext.getVersion(c),e)<1){g.call(d)}}});Ext.setVersion("core",a)}());Ext.String=(function(){var i=/^[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+|[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+$/g,m=/('|\\)/g,h=/\{(\d+)\}/g,b=/([-.*+?\^${}()|\[\]\/\\])/g,n=/^\s+|\s+$/g,j=/\s+/,l=/(^[^a-z]*|[^\w])/gi,d,a,g,c,e=function(p,o){return d[o]},k=function(p,o){return(o in a)?a[o]:String.fromCharCode(parseInt(o.substr(2),10))};return{createVarName:function(o){return o.replace(l,"")},htmlEncode:function(o){return(!o)?o:String(o).replace(g,e)},htmlDecode:function(o){return(!o)?o:String(o).replace(c,k)},addCharacterEntities:function(p){var o=[],s=[],q,r;for(q in p){r=p[q];a[q]=r;d[r]=q;o.push(r);s.push(q)}g=new RegExp("("+o.join("|")+")","g");c=new RegExp("("+s.join("|")+"|&#[0-9]{1,5};)","g")},resetCharacterEntities:function(){d={};a={};this.addCharacterEntities({"&":"&",">":">","<":"<",""":'"',"'":"'"})},urlAppend:function(p,o){if(!Ext.isEmpty(o)){return p+(p.indexOf("?")===-1?"?":"&")+o}return p},trim:function(o){return o.replace(i,"")},capitalize:function(o){return o.charAt(0).toUpperCase()+o.substr(1)},uncapitalize:function(o){return o.charAt(0).toLowerCase()+o.substr(1)},ellipsis:function(q,o,r){if(q&&q.length>o){if(r){var s=q.substr(0,o-2),p=Math.max(s.lastIndexOf(" "),s.lastIndexOf("."),s.lastIndexOf("!"),s.lastIndexOf("?"));if(p!==-1&&p>=(o-15)){return s.substr(0,p)+"..."}}return q.substr(0,o-3)+"..."}return q},escapeRegex:function(o){return o.replace(b,"\\$1")},escape:function(o){return o.replace(m,"\\$1")},toggle:function(p,q,o){return p===q?o:q},leftPad:function(p,q,r){var o=String(p);r=r||" ";while(o.lengthe)?e:d)},snap:function(h,e,g,i){var d;if(h===undefined||h=e){h+=e}else{if(d*2<-e){h-=e}}}}return b.constrain(h,g,i)},snapInRange:function(h,d,g,i){var e;g=(g||0);if(h===undefined||h=d){h+=d}}if(i!==undefined){if(h>(i=b.snapInRange(i,d,g))){h=i}}return h},toFixed:c?function(g,d){d=d||0;var e=a.pow(10,d);return(a.round(g*e)/e).toFixed(d)}:function(e,d){return e.toFixed(d)},from:function(e,d){if(isFinite(e)){e=parseFloat(e)}return !isNaN(e)?e:d},randomInt:function(e,d){return a.floor(a.random()*(d-e+1)+e)}});Ext.num=function(){return b.from.apply(this,arguments)}};(function(){var g=Array.prototype,o=g.slice,q=(function(){var A=[],e,z=20;if(!A.splice){return false}while(z--){A.push("A")}A.splice(15,0,"F","F","F","F","F","F","F","F","F","F","F","F","F","F","F","F","F","F","F","F","F");e=A.length;A.splice(13,0,"XXX");if(e+1!=A.length){return false}return true}()),j="forEach" in g,u="map" in g,p="indexOf" in g,y="every" in g,c="some" in g,d="filter" in g,n=(function(){var e=[1,2,3,4,5].sort(function(){return 0});return e[0]===1&&e[1]===2&&e[2]===3&&e[3]===4&&e[4]===5}()),k=true,a,w,t,v;try{if(typeof document!=="undefined"){o.call(document.getElementsByTagName("body"))}}catch(s){k=false}function m(z,e){return(e<0)?Math.max(0,z.length+e):Math.min(z.length,e)}function x(G,F,z,J){var K=J?J.length:0,B=G.length,H=m(G,F),E,I,A,e,C,D;if(H===B){if(K){G.push.apply(G,J)}}else{E=Math.min(z,B-H);I=H+E;A=I+K-E;e=B-I;C=B-E;if(AI){for(D=e;D--;){G[A+D]=G[I+D]}}}if(K&&H===C){G.length=C;G.push.apply(G,J)}else{G.length=C+K;for(D=0;D-1;z--){if(B.call(A||D[z],D[z],z,D)===false){return z}}}return true},forEach:j?function(A,z,e){return A.forEach(z,e)}:function(C,A,z){var e=0,B=C.length;for(;ee){e=A}}}return e},mean:function(e){return e.length>0?a.sum(e)/e.length:undefined},sum:function(C){var z=0,e,B,A;for(e=0,B=C.length;e0){return setTimeout(Ext.supports.TimeoutActualLateness?function(){e()}:e,c)}e();return 0},createSequence:function(b,c,a){if(!c){return b}else{return function(){var d=b.apply(this,arguments);c.apply(a||this,arguments);return d}}},createBuffered:function(e,b,d,c){var a;return function(){var h=c||Array.prototype.slice.call(arguments,0),g=d||this;if(a){clearTimeout(a)}a=setTimeout(function(){e.apply(g,h)},b)}},createThrottled:function(e,b,d){var g,a,c,i,h=function(){e.apply(d||this,c);g=new Date().getTime()};return function(){a=new Date().getTime()-g;c=arguments;clearTimeout(i);if(!g||(a>=b)){h()}else{i=setTimeout(h,b-a)}}},interceptBefore:function(b,a,d,c){var e=b[a]||Ext.emptyFn;return(b[a]=function(){var g=d.apply(c||this,arguments);e.apply(this,arguments);return g})},interceptAfter:function(b,a,d,c){var e=b[a]||Ext.emptyFn;return(b[a]=function(){e.apply(this,arguments);return d.apply(c||this,arguments)})}};Ext.defer=Ext.Function.alias(Ext.Function,"defer");Ext.pass=Ext.Function.alias(Ext.Function,"pass");Ext.bind=Ext.Function.alias(Ext.Function,"bind");(function(){var a=function(){},b=Ext.Object={chain:function(d){a.prototype=d;var c=new a();a.prototype=null;return c},toQueryObjects:function(e,k,d){var c=b.toQueryObjects,j=[],g,h;if(Ext.isArray(k)){for(g=0,h=k.length;g0){k=o.split("=");w=decodeURIComponent(k[0]);n=(k[1]!==undefined)?decodeURIComponent(k[1]):"";if(!r){if(u.hasOwnProperty(w)){if(!Ext.isArray(u[w])){u[w]=[u[w]]}u[w].push(n)}else{u[w]=n}}else{h=w.match(/(\[):?([^\]]*)\]/g);t=w.match(/^([^\[]+)/);w=t[0];l=[];if(h===null){u[w]=n;continue}for(p=0,c=h.length;p 0 ? +1 : (Ext.Date.getWeekOfYear(this) >= 52 && this.getMonth() < 11 ? -1 : 0)))",Y:"Ext.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:"Ext.String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0')",H:"Ext.String.leftPad(this.getHours(), 2, '0')",i:"Ext.String.leftPad(this.getMinutes(), 2, '0')",s:"Ext.String.leftPad(this.getSeconds(), 2, '0')",u:"Ext.String.leftPad(this.getMilliseconds(), 3, '0')",O:"Ext.Date.getGMTOffset(this)",P:"Ext.Date.getGMTOffset(this, true)",T:"Ext.Date.getTimezone(this)",Z:"(this.getTimezoneOffset() * -60)",c:function(){var k,h,g,d,j;for(k="Y-m-dTH:i:sP",h=[],g=0,d=k.length;g= 0 && y >= 0){","v = Ext.Date.add(new Date(y < 100 ? 100 : y, 0, 1, h, i, s, ms), Ext.Date.YEAR, y < 100 ? y - 100 : 0);","v = !strict? v : (strict === true && (z <= 364 || (Ext.Date.isLeapYear(v) && z <= 365))? Ext.Date.add(v, Ext.Date.DAY, z) : null);","}else if(strict === true && !Ext.Date.isValid(y, m + 1, d, h, i, s, ms)){","v = null;","}else{","v = Ext.Date.add(new Date(y < 100 ? 100 : y, m, d, h, i, s, ms), Ext.Date.YEAR, y < 100 ? y - 100 : 0);","}","}","}","if(v){","if(zz != null){","v = Ext.Date.add(v, Ext.Date.SECOND, -v.getTimezoneOffset() * 60 - zz);","}else if(o){","v = Ext.Date.add(v, Ext.Date.MINUTE, -v.getTimezoneOffset() + (sn == '+'? -1 : 1) * (hr * 60 + mn));","}","}","return v;"].join("\n");return function(o){var e=a.parseRegexes.length,p=1,g=[],n=[],l=false,d="",j=0,k=o.length,m=[],h;for(;j Ext.Date.y2kYear ? 1900 + ty : 2000 + ty;\n",s:"(\\d{1,2})"},a:{g:1,c:"if (/(am)/i.test(results[{0}])) {\nif (!h || h == 12) { h = 0; }\n} else { if (!h || h < 12) { h = (h || 0) + 12; }}",s:"(am|pm|AM|PM)",calcAtEnd:true},A:{g:1,c:"if (/(am)/i.test(results[{0}])) {\nif (!h || h == 12) { h = 0; }\n} else { if (!h || h < 12) { h = (h || 0) + 12; }}",s:"(AM|PM|am|pm)",calcAtEnd:true},g:{g:1,c:"h = parseInt(results[{0}], 10);\n",s:"(1[0-2]|[0-9])"},G:{g:1,c:"h = parseInt(results[{0}], 10);\n",s:"(2[0-3]|1[0-9]|[0-9])"},h:{g:1,c:"h = parseInt(results[{0}], 10);\n",s:"(1[0-2]|0[1-9])"},H:{g:1,c:"h = parseInt(results[{0}], 10);\n",s:"(2[0-3]|[0-1][0-9])"},i:{g:1,c:"i = parseInt(results[{0}], 10);\n",s:"([0-5][0-9])"},s:{g:1,c:"s = parseInt(results[{0}], 10);\n",s:"([0-5][0-9])"},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 + Ext.String.leftPad(hr, 2, '0') + Ext.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 + Ext.String.leftPad(hr, 2, '0') + Ext.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;\nzz = (-43200 <= zz && zz <= 50400)? zz : null;\n",s:"([+-]?\\d{1,5})"},c:function(){var e=[],c=[a.formatCodeToRegex("Y",1),a.formatCodeToRegex("m",2),a.formatCodeToRegex("d",3),a.formatCodeToRegex("H",4),a.formatCodeToRegex("i",5),a.formatCodeToRegex("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){",a.formatCodeToRegex("P",8).c,"}else{",a.formatCodeToRegex("O",8).c,"}","}"].join("\n")}],g,d;for(g=0,d=c.length;g0?"-":"+")+Ext.String.leftPad(Math.floor(Math.abs(e)/60),2,"0")+(d?":":"")+Ext.String.leftPad(Math.abs(e%60),2,"0")},getDayOfYear:function(g){var e=0,j=Ext.Date.clone(g),c=g.getMonth(),h;for(h=0,j.setDate(1),j.setMonth(0);h28){e=Math.min(e,Ext.Date.getLastDateOfMonth(Ext.Date.add(Ext.Date.getFirstDateOfMonth(h),Ext.Date.MONTH,i)).getDate())}j.setDate(e);j.setMonth(h.getMonth()+i);break;case Ext.Date.YEAR:e=h.getDate();if(e>28){e=Math.min(e,Ext.Date.getLastDateOfMonth(Ext.Date.add(Ext.Date.getFirstDateOfMonth(h),Ext.Date.YEAR,i)).getDate())}j.setDate(e);j.setFullYear(h.getFullYear()+i);break}return j},between:function(d,g,c){var e=d.getTime();return g.getTime()<=e&&e<=c.getTime()},compat:function(){var d=window.Date,c,l,j=["useStrict","formatCodeToRegex","parseFunctions","parseRegexes","formatFunctions","y2kYear","MILLI","SECOND","MINUTE","HOUR","DAY","MONTH","YEAR","defaults","dayNames","monthNames","monthNumbers","getShortMonthName","getShortDayName","getMonthNumber","formatCodes","isValid","parseDate","getFormatCode","createFormat","createParser","parseCodes"],h=["dateFormat","format","getTimezone","getGMTOffset","getDayOfYear","getWeekOfYear","isLeapYear","getFirstDayOfMonth","getLastDayOfMonth","getDaysInMonth","getSuffix","clone","isDST","clearTime","add","between"],i=j.length,e=h.length,g,k,m;for(m=0;m0){for(d=0;d0){if(x===w){return z[x]}y=z[x];w=w.substring(x.length+1)}if(y.length>0){y+="/"}return y.replace(c,"/")+w.replace(g,"/")+".js"},getPrefix:function(x){var z=j.config.paths,y,w="";if(z.hasOwnProperty(x)){return x}for(y in z){if(z.hasOwnProperty(y)&&y+"."===x.substring(0,y.length+1)){if(y.length>w.length){w=y}}}return w},isAClassNameWithAKnownPrefix:function(w){var x=j.getPrefix(w);return x!==""&&x!==w},require:function(y,x,w,z){if(x){x.call(w)}},syncRequire:function(){},exclude:function(w){return{require:function(z,y,x){return j.require(z,y,x,w)},syncRequire:function(z,y,x){return j.syncRequire(z,y,x,w)}}},onReady:function(z,y,A,w){var x;if(A!==false&&Ext.onDocumentReady){x=z;z=function(){Ext.onDocumentReady(x,y,w)}}z.call(y)}});var o=[],p={},s={},q={},n={},u=[],v=[],i={};Ext.apply(j,{documentHead:typeof document!="undefined"&&(document.head||document.getElementsByTagName("head")[0]),isLoading:false,queue:o,isClassFileLoaded:p,isFileLoaded:s,readyListeners:u,optionalRequires:v,requiresMap:i,numPendingFiles:0,numLoadedFiles:0,hasFileLoadError:false,classNameToFilePathMap:q,scriptsLoading:0,syncModeEnabled:false,scriptElements:n,refreshQueue:function(){var A=o.length,x,z,w,y;if(!A&&!j.scriptsLoading){return j.triggerReady()}for(x=0;xj.numLoadedFiles){continue}for(w=0;w=200&&A<300)||(A===304)){Ext.globalEval(F.responseText+"\n//@ sourceURL="+x);D.call(G)}else{}}F=null}},syncRequire:function(){var w=j.syncModeEnabled;if(!w){j.syncModeEnabled=true}j.require.apply(j,arguments);if(!w){j.syncModeEnabled=false}j.refreshQueue()},require:function(O,F,z,B){var H={},y={},E=[],Q=[],N=[],x=[],D,P,J,I,w,C,M,L,K,G,A;if(B){B=(typeof B==="string")?[B]:B;for(L=0,G=B.length;L0){E=b.getNamesByExpression(w);for(K=0,A=E.length;K0){D=function(){var S=[],R,T;for(R=0,T=x.length;R0){Q=b.getNamesByExpression(I);A=Q.length;for(K=0;K0){if(!j.config.enabled){throw new Error("Ext.Loader is not enabled, so dependencies cannot be resolved dynamically. Missing required class"+((N.length>1)?"es":"")+": "+N.join(", "))}}else{D.call(z);return j}P=j.syncModeEnabled;if(!P){o.push({requires:N.slice(),callback:D,scope:z})}G=N.length;for(L=0;Lwindow.innerWidth?"portrait":"landscape"},destroy:function(){var c=arguments.length,b,a;for(b=0;b]+>/gi,c=/(?:)((\n|\r|.)*?)(?:<\/script>)/ig,b=/\r?\n/g,d=/[^\d\.]/g,a;Ext.apply(g,{thousandSeparator:",",decimalSeparator:".",currencyPrecision:2,currencySign:"$",currencyAtEnd:false,undef:function(h){return h!==undefined?h:""},defaultValue:function(i,h){return i!==undefined&&i!==""?i:h},substr:"ab".substr(-1)!="b"?function(i,k,h){var j=String(i);return(k<0)?j.substr(Math.max(j.length+k,0),h):j.substr(k,h)}:function(i,j,h){return String(i).substr(j,h)},lowercase:function(h){return String(h).toLowerCase()},uppercase:function(h){return String(h).toUpperCase()},usMoney:function(h){return g.currency(h,"$",2)},currency:function(k,m,j,h){var o="",n=",0",l=0;k=k-0;if(k<0){k=-k;o="-"}j=Ext.isDefined(j)?j:g.currencyPrecision;n+=n+(j>0?".":"");for(;l2){}else{if(h.length>1){y=Ext.Number.toFixed(y,h[1].length)}else{y=Ext.Number.toFixed(y,0)}}x=y.toString();h=x.split(".");if(k){w=h[0];p=[];t=w.length;o=Math.floor(t/3);l=w.length%3||3;for(u=0;u")},capitalize:Ext.String.capitalize,ellipsis:Ext.String.ellipsis,format:Ext.String.format,htmlDecode:Ext.String.htmlDecode,htmlEncode:Ext.String.htmlEncode,leftPad:Ext.String.leftPad,trim:Ext.String.trim,parseBox:function(i){i=Ext.isEmpty(i)?"":i;if(Ext.isNumber(i)){i=i.toString()}var j=i.split(" "),h=j.length;if(h==1){j[1]=j[2]=j[3]=j[0]}else{if(h==2){j[2]=j[0];j[3]=j[1]}else{if(h==3){j[3]=j[1]}}}return{top:parseInt(j[0],10)||0,right:parseInt(j[1],10)||0,bottom:parseInt(j[2],10)||0,left:parseInt(j[3],10)||0}},escapeRegex:function(h){return h.replace(/([\-.*+?\^${}()|\[\]\/\\])/g,"\\$1")}})}());Ext.define("Ext.util.TaskRunner",{interval:10,timerId:null,constructor:function(a){var b=this;if(typeof a=="number"){b.interval=a}else{if(a){Ext.apply(b,a)}}b.tasks=[];b.timerFn=Ext.Function.bind(b.onTick,b)},newTask:function(b){var a=new Ext.util.TaskRunner.Task(b);a.manager=this;return a},start:function(a){var c=this,b=new Date().getTime();if(!a.pending){c.tasks.push(a);a.pending=true}a.stopped=false;a.taskStartTime=b;a.taskRunTime=a.fireOnStart!==false?0:a.taskStartTime;a.taskRunCount=0;if(!c.firing){if(a.fireOnStart!==false){c.startTimer(0,b)}else{c.startTimer(a.interval,b)}}return a},stop:function(a){if(!a.stopped){a.stopped=true;if(a.onStop){a.onStop.call(a.scope||a,a)}}return a},stopAll:function(){Ext.each(this.tasks,this.stop,this)},firing:false,nextExpires:1e+99,onTick:function(){var m=this,e=m.tasks,a=new Date().getTime(),n=1e+99,k=e.length,c,o,h,b,d,g;m.timerId=null;m.firing=true;for(h=0;hc){n=c}}}if(o){m.tasks=o}m.firing=false;if(m.tasks.length){m.startTimer(n-a,new Date().getTime())}},startTimer:function(e,c){var d=this,b=c+e,a=d.timerId;if(a&&d.nextExpires-b>d.interval){clearTimeout(a);a=null}if(!a){if(e',''," ({childCount} children)","",''," ({depth} deep)","",'',", {type}: {[this.time(values.sum)]} msec (","avg={[this.time(values.sum / parent.count)]}",")","",""].join(""),{time:function(n){return Math.round(n*100)/100}})}var m=this.getData(l);m.name=this.name;m.pure.type="Pure";m.total.type="Total";m.times=[m.pure,m.total];return d.apply(m)},getData:function(l){var m=this;return{count:m.count,childCount:m.childCount,depth:m.maxDepth,pure:g(m.count,m.childCount,l,m.pure),total:g(m.count,m.childCount,l,m.total)}},enter:function(){var l=this,m={accum:l,leave:e,childTime:0,parent:c};++l.depth;if(l.maxDepth','
    ',"
    ",'
    ','
    ',"
    ",'
    ','
    '].join("");e.body.appendChild(h)}while(i--){g=c[i];if(h||g.early){d[g.identity]=g.fn.call(d,e,h)}else{b.push(g)}}if(h){e.body.removeChild(h)}d.tests=b},PointerEvents:"pointerEvents" in document.documentElement.style,CSS3BoxShadow:"boxShadow" in document.documentElement.style||"WebkitBoxShadow" in document.documentElement.style||"MozBoxShadow" in document.documentElement.style,ClassList:!!document.documentElement.classList,OrientationChange:((typeof window.orientation!="undefined")&&("onorientationchange" in window)),DeviceMotion:("ondevicemotion" in window),Touch:("ontouchstart" in window)&&(!Ext.is.Desktop),TimeoutActualLateness:(function(){setTimeout(function(){Ext.supports.TimeoutActualLateness=arguments.length!==0},0)}()),tests:[{identity:"Transitions",fn:function(h,k){var g=["webkit","Moz","o","ms","khtml"],j="TransitionEnd",b=[g[0]+j,"transitionend",g[2]+j,g[3]+j,g[4]+j],e=g.length,d=0,c=false;for(;d

    ";return(c.childNodes.length==2)}},{identity:"Float",fn:function(b,c){return !!c.lastChild.style.cssFloat}},{identity:"AudioTag",fn:function(b){return !!b.createElement("audio").canPlayType}},{identity:"History",fn:function(){var b=window.history;return !!(b&&b.pushState)}},{identity:"CSS3DTransform",fn:function(){return(typeof WebKitCSSMatrix!="undefined"&&new WebKitCSSMatrix().hasOwnProperty("m41"))}},{identity:"CSS3LinearGradient",fn:function(h,j){var g="background-image:",d="-webkit-gradient(linear, left top, right bottom, from(black), to(white))",i="linear-gradient(left top, black, white)",e="-moz-"+i,b="-o-"+i,c=[g+d,g+i,g+e,g+b];j.style.cssText=c.join(";");return(""+j.style.backgroundImage).indexOf("gradient")!==-1}},{identity:"CSS3BorderRadius",fn:function(e,g){var c=["borderRadius","BorderRadius","MozBorderRadius","WebkitBorderRadius","OBorderRadius","KhtmlBorderRadius"],d=false,b;for(b=0;b=534.16}},{identity:"TextAreaMaxLength",fn:function(){var b=document.createElement("textarea");return("maxlength" in b)}},{identity:"GetPositionPercentage",fn:function(b,c){return a(c.childNodes[2],"left")=="10%"}}]}}());Ext.supports.init();Ext.util.DelayedTask=function(d,c,a){var e=this,g,b=function(){clearInterval(g);g=null;d.apply(c,a||[])};this.delay=function(i,k,j,h){e.cancel();d=k||d;c=j||c;a=h||a;g=setInterval(b,i)};this.cancel=function(){if(g){clearInterval(g);g=null}}};Ext.require("Ext.util.DelayedTask",function(){Ext.util.Event=Ext.extend(Object,(function(){function c(g,h,i,e){return function(){if(i.target===arguments[0]){g.apply(e,arguments)}}}function b(g,h,i,e){h.task=new Ext.util.DelayedTask();return function(){h.task.delay(i.buffer,g,e,Ext.Array.toArray(arguments))}}function a(g,h,i,e){return function(){var j=new Ext.util.DelayedTask();if(!h.tasks){h.tasks=[]}h.tasks.push(j);j.delay(i.delay||10,g,e,Ext.Array.toArray(arguments))}}function d(g,h,i,e){return function(){var j=h.ev;if(j.removeListener(h.fn,e)&&j.observable){j.observable.hasListeners[j.name]--}return g.apply(e,arguments)}}return{isEvent:true,constructor:function(g,e){this.name=e;this.observable=g;this.listeners=[]},addListener:function(h,g,e){var i=this,j;g=g||i.observable;if(!i.isListening(h,g)){j=i.createListener(h,g,e);if(i.firing){i.listeners=i.listeners.slice(0)}i.listeners.push(j)}},createListener:function(h,g,j){j=j||{};g=g||this.observable;var i={fn:h,scope:g,o:j,ev:this},e=h;if(j.single){e=d(e,i,j,g)}if(j.target){e=c(e,i,j,g)}if(j.delay){e=a(e,i,j,g)}if(j.buffer){e=b(e,i,j,g)}i.fireFn=e;return i},findListener:function(k,j){var h=this.listeners,e=h.length,l,g;while(e--){l=h[e];if(l){g=l.scope;if(l.fn==k&&(g==j||g==this.observable)){return e}}}return -1},isListening:function(g,e){return this.findListener(g,e)!==-1},removeListener:function(i,h){var j=this,g,l,e;g=j.findListener(i,h);if(g!=-1){l=j.listeners[g];if(j.firing){j.listeners=j.listeners.slice(0)}if(l.task){l.task.cancel();delete l.task}e=l.tasks&&l.tasks.length;if(e){while(e--){l.tasks[e].cancel()}delete l.tasks}Ext.Array.erase(j.listeners,g,1);return true}return false},clearListeners:function(){var g=this.listeners,e=g.length;while(e--){this.removeListener(g[e].fn,g[e].scope)}},fire:function(){var k=this,h=k.listeners,j=h.length,g,e,l;if(j>0){k.firing=true;for(g=0;g111&&g.keyCode<124){g.keyCode=-1}}catch(h){}}},getRelatedTarget:function(e){e=e.browserEvent||e;var g=e.relatedTarget;if(!g){if(a.mouseLeaveRe.test(e.type)){g=e.toElement}else{if(a.mouseEnterRe.test(e.type)){g=e.fromElement}}}return a.resolveTextNode(g)},getPageX:function(e){return a.getPageXY(e)[0]},getPageY:function(e){return a.getPageXY(e)[1]},getPageXY:function(h){h=h.browserEvent||h;var g=h.pageX,j=h.pageY,i=d.documentElement,e=d.body;if(!g&&g!==0){g=h.clientX+(i&&i.scrollLeft||e&&e.scrollLeft||0)-(i&&i.clientLeft||e&&e.clientLeft||0);j=h.clientY+(i&&i.scrollTop||e&&e.scrollTop||0)-(i&&i.clientTop||e&&e.clientTop||0)}return[g,j]},getTarget:function(e){e=e.browserEvent||e;return a.resolveTextNode(e.target||e.srcElement)},resolveTextNode:Ext.isGecko?function(g){if(!g){return}var e=HTMLElement.prototype.toString.call(g);if(e=="[xpconnect wrapped native prototype]"||e=="[object XULElement]"){return}return g.nodeType==3?g.parentNode:g}:function(e){return e&&e.nodeType==3?e.parentNode:e},curWidth:0,curHeight:0,onWindowResize:function(i,h,g){var e=a.resizeEvent;if(!e){a.resizeEvent=e=new Ext.util.Event();a.on(c,"resize",a.fireResize,null,{buffer:100})}e.addListener(i,h,g)},fireResize:function(){var e=Ext.Element.getViewWidth(),g=Ext.Element.getViewHeight();if(a.curHeight!=g||a.curWidth!=e){a.curHeight=g;a.curWidth=e;a.resizeEvent.fire(e,g)}},removeResizeListener:function(h,g){var e=a.resizeEvent;if(e){e.removeListener(h,g)}},onWindowUnload:function(i,h,g){var e=a.unloadEvent;if(!e){a.unloadEvent=e=new Ext.util.Event();a.addListener(c,"unload",a.fireUnload)}if(i){e.addListener(i,h,g)}},fireUnload:function(){try{d=c=undefined;var m,h,k,j,g;a.unloadEvent.fire();if(Ext.isGecko3){m=Ext.ComponentQuery.query("gridview");h=0;k=m.length;for(;h=525:!((Ext.isGecko&&!Ext.isWindows)||Ext.isOpera),getKeyEvent:function(){return a.useKeyDown?"keydown":"keypress"}});if(!("addEventListener" in document)&&document.attachEvent){Ext.apply(a,{pollScroll:function(){var g=true;try{document.documentElement.doScroll("left")}catch(h){g=false}if(g){a.onReadyEvent({type:"doScroll"})}else{a.scrollTimeout=setTimeout(a.pollScroll,20)}return g},scrollTimeout:null,readyStatesRe:/complete/i,checkReadyState:function(){var e=document.readyState;if(a.readyStatesRe.test(e)){a.onReadyEvent({type:e})}},bindReadyEvent:function(){var g=true;if(a.hasBoundOnReady){return}try{g=!window.frameElement}catch(h){}if(!g||!d.documentElement.doScroll){a.pollScroll=Ext.emptyFn}if(a.pollScroll()===true){return}if(d.readyState=="complete"){a.onReadyEvent({type:"already "+(d.readyState||"body")})}else{d.attachEvent("onreadystatechange",a.checkReadyState);window.attachEvent("onload",a.onReadyEvent);a.hasBoundOnReady=true}},onReadyEvent:function(g){if(g&&g.type){a.onReadyChain.push(g.type)}if(a.hasBoundOnReady){document.detachEvent("onreadystatechange",a.checkReadyState);window.detachEvent("onload",a.onReadyEvent)}if(Ext.isNumber(a.scrollTimeout)){clearTimeout(a.scrollTimeout);delete a.scrollTimeout}if(!Ext.isReady){a.fireDocReady()}},onReadyChain:[]})}Ext.onReady=function(h,g,e){Ext.Loader.onReady(h,g,true,e)};Ext.onDocumentReady=a.onDocumentReady;a.on=a.addListener;a.un=a.removeListener;Ext.onReady(b)};Ext.define("Ext.EventObjectImpl",{uses:["Ext.util.Point"],BACKSPACE:8,TAB:9,NUM_CENTER:12,ENTER:13,RETURN:13,SHIFT:16,CTRL:17,ALT:18,PAUSE:19,CAPS_LOCK:20,ESC:27,SPACE:32,PAGE_UP:33,PAGE_DOWN: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,WHEEL_SCALE:(function(){var a;if(Ext.isGecko){a=3}else{if(Ext.isMac){if(Ext.isSafari&&Ext.webKitVersion>=532){a=120}else{a=12}a*=3}else{a=120}}return a}()),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},constructor:function(a,b){if(a){this.setEvent(a.browserEvent||a,b)}},setEvent:function(d,e){var c=this,b,a;if(d==c||(d&&d.browserEvent)){return d}c.browserEvent=d;if(d){b=d.button?c.btnMap[d.button]:(d.which?d.which-1:-1);if(c.clickRe.test(d.type)&&b==-1){b=0}a={type:d.type,button:b,shiftKey:d.shiftKey,ctrlKey:d.ctrlKey||d.metaKey||false,altKey:d.altKey,keyCode:d.keyCode,charCode:d.charCode,target:Ext.EventManager.getTarget(d),relatedTarget:Ext.EventManager.getRelatedTarget(d),currentTarget:d.currentTarget,xy:(e?c.getXY():null)}}else{a={button:-1,shiftKey:false,ctrlKey:false,altKey:false,keyCode:0,charCode:0,target:null,xy:[0,0]}}Ext.apply(c,a);return c},stopEvent:function(){this.stopPropagation();this.preventDefault()},preventDefault:function(){if(this.browserEvent){Ext.EventManager.preventDefault(this.browserEvent)}},stopPropagation:function(){var a=this.browserEvent;if(a){if(a.type=="mousedown"){Ext.EventManager.stoppedMouseDownEvent.fire(this)}Ext.EventManager.stopPropagation(a)}},getCharCode:function(){return this.charCode||this.keyCode},getKey:function(){return this.normalizeKey(this.keyCode||this.charCode)},normalizeKey:function(a){return Ext.isWebKit?(this.safariKeys[a]||a):a},getPageX:function(){return this.getX()},getPageY:function(){return this.getY()},getX:function(){return this.getXY()[0]},getY:function(){return this.getXY()[1]},getXY:function(){if(!this.xy){this.xy=Ext.EventManager.getPageXY(this.browserEvent)}return this.xy},getTarget:function(b,c,a){if(b){return Ext.fly(this.target).findParent(b,c,a)}return a?Ext.get(this.target):this.target},getRelatedTarget:function(b,c,a){if(b){return Ext.fly(this.relatedTarget).findParent(b,c,a)}return a?Ext.get(this.relatedTarget):this.relatedTarget},correctWheelDelta:function(c){var b=this.WHEEL_SCALE,a=Math.round(c/b);if(!a&&c){a=(c<0)?-1:1}return a},getWheelDeltas:function(){var d=this,c=d.browserEvent,b=0,a=0;if(Ext.isDefined(c.wheelDeltaX)){b=c.wheelDeltaX;a=c.wheelDeltaY}else{if(c.wheelDelta){a=c.wheelDelta}else{if(c.detail){a=-c.detail;if(a>100){a=3}else{if(a<-100){a=-3}}if(Ext.isDefined(c.axis)&&c.axis===c.HORIZONTAL_AXIS){b=a;a=0}}}}return{x:d.correctWheelDelta(b),y:d.correctWheelDelta(a)}},getWheelDelta:function(){var a=this.getWheelDeltas();return a.y},within:function(d,e,b){if(d){var c=e?this.getRelatedTarget():this.getTarget(),a;if(c){a=Ext.fly(d).contains(c);if(!a&&b){a=c==Ext.getDom(d)}return a}}return false},isNavKeyPress:function(){var b=this,a=this.normalizeKey(b.keyCode);return(a>=33&&a<=40)||a==b.RETURN||a==b.TAB||a==b.ESC},isSpecialKey:function(){var a=this.normalizeKey(this.keyCode);return(this.type=="keypress"&&this.ctrlKey)||this.isNavKeyPress()||(a==this.BACKSPACE)||(a>=16&&a<=20)||(a>=44&&a<=46)},getPoint:function(){var a=this.getXY();return new Ext.util.Point(a[0],a[1])},hasModifier:function(){return this.ctrlKey||this.altKey||this.shiftKey||this.metaKey},injectEvent:(function(){var d,e={},c;if(!Ext.isIE&&document.createEvent){d={createHtmlEvent:function(k,i,h,g){var j=k.createEvent("HTMLEvents");j.initEvent(i,h,g);return j},createMouseEvent:function(u,s,m,l,o,k,i,j,g,r,q,n,p){var h=u.createEvent("MouseEvents"),t=u.defaultView||window;if(h.initMouseEvent){h.initMouseEvent(s,m,l,t,o,k,i,k,i,j,g,r,q,n,p)}else{h=u.createEvent("UIEvents");h.initEvent(s,m,l);h.view=t;h.detail=o;h.screenX=k;h.screenY=i;h.clientX=k;h.clientY=i;h.ctrlKey=j;h.altKey=g;h.metaKey=q;h.shiftKey=r;h.button=n;h.relatedTarget=p}return h},createUIEvent:function(m,k,i,h,j){var l=m.createEvent("UIEvents"),g=m.defaultView||window;l.initUIEvent(k,i,h,g,j);return l},fireEvent:function(i,g,h){i.dispatchEvent(h)},fixTarget:function(g){if(g==window&&!g.dispatchEvent){return document}return g}}}else{if(document.createEventObject){c={0:1,1:4,2:2};d={createHtmlEvent:function(k,i,h,g){var j=k.createEventObject();j.bubbles=h;j.cancelable=g;return j},createMouseEvent:function(t,s,m,l,o,k,i,j,g,r,q,n,p){var h=t.createEventObject();h.bubbles=m;h.cancelable=l;h.detail=o;h.screenX=k;h.screenY=i;h.clientX=k;h.clientY=i;h.ctrlKey=j;h.altKey=g;h.shiftKey=r;h.metaKey=q;h.button=c[n]||n;h.relatedTarget=p;return h},createUIEvent:function(l,j,h,g,i){var k=l.createEventObject();k.bubbles=h;k.cancelable=g;return k},fireEvent:function(i,g,h){i.fireEvent("on"+g,h)},fixTarget:function(g){if(g==document){return document.documentElement}return g}}}}Ext.Object.each({load:[false,false],unload:[false,false],select:[true,false],change:[true,false],submit:[true,true],reset:[true,false],resize:[true,false],scroll:[true,false]},function(i,j){var h=j[0],g=j[1];e[i]=function(m,k){var l=d.createHtmlEvent(i,h,g);d.fireEvent(m,i,l)}});function b(i,h){var g=(i!="mousemove");return function(m,j){var l=j.getXY(),k=d.createMouseEvent(m.ownerDocument,i,true,g,h,l[0],l[1],j.ctrlKey,j.altKey,j.shiftKey,j.metaKey,j.button,j.relatedTarget);d.fireEvent(m,i,k)}}Ext.each(["click","dblclick","mousedown","mouseup","mouseover","mousemove","mouseout"],function(g){e[g]=b(g,1)});Ext.Object.each({focusin:[true,false],focusout:[true,false],activate:[true,true],focus:[false,false],blur:[false,false]},function(i,j){var h=j[0],g=j[1];e[i]=function(m,k){var l=d.createUIEvent(m.ownerDocument,i,h,g,1);d.fireEvent(m,i,l)}});if(!d){e={};d={fixTarget:function(g){return g}}}function a(h,g){}return function(j){var i=this,h=e[i.type]||a,g=j?(j.dom||j):i.getTarget();g=d.fixTarget(g);h(g,i)}}())},function(){Ext.EventObject=new Ext.EventObjectImpl()});Ext.define("Ext.dom.AbstractQuery",{select:function(k,b){var h=[],d,g,e,c,a;b=b||document;if(typeof b=="string"){b=document.getElementById(b)}k=k.split(",");for(g=0,c=k.length;g")}else{c.push(">");if((j=d.tpl)){j.applyOut(d.tplData,c)}if((j=d.html)){c.push(j)}if((j=d.cn||d.children)){h.generateMarkup(j,c)}g=h.closeTags;c.push(g[a]||(g[a]=""))}}}return c},generateStyles:function(e,c){var b=c||[],d;for(d in e){if(e.hasOwnProperty(d)){b.push(this.decamelizeName(d),":",e[d],";")}}return c||b.join("")},markup:function(a){if(typeof a=="string"){return a}var b=this.generateMarkup(a,[]);return b.join("")},applyStyles:function(d,e){if(e){var b=0,a,c;d=Ext.fly(d);if(typeof e=="function"){e=e.call()}if(typeof e=="string"){e=Ext.util.Format.trim(e).split(/\s*(?::|;)\s*/);for(a=e.length;b "'+g+'"'},insertBefore:function(a,c,b){return this.doInsert(a,c,b,"beforebegin")},insertAfter:function(a,c,b){return this.doInsert(a,c,b,"afterend","nextSibling")},insertFirst:function(a,c,b){return this.doInsert(a,c,b,"afterbegin","firstChild")},append:function(a,c,b){return this.doInsert(a,c,b,"beforeend","",true)},overwrite:function(a,c,b){a=Ext.getDom(a);a.innerHTML=this.markup(c);return b?Ext.get(a.firstChild):a.firstChild},doInsert:function(d,g,e,h,c,a){var b=this.insertHtml(h,Ext.getDom(d),this.markup(g));return e?Ext.get(b,true):b}});(function(){var a=window.document,b=/^\s+|\s+$/g,c=/\s/;if(!Ext.cache){Ext.cache={}}Ext.define("Ext.dom.AbstractElement",{inheritableStatics:{get:function(e){var g=this,h=Ext.dom.Element,d,j,i,k;if(!e){return null}if(typeof e=="string"){if(e==Ext.windowId){return h.get(window)}else{if(e==Ext.documentId){return h.get(a)}}d=Ext.cache[e];if(d&&d.skipGarbageCollection){j=d.el;return j}if(!(i=a.getElementById(e))){return null}if(d&&d.el){j=d.el;j.dom=i}else{j=new h(i,!!d)}return j}else{if(e.tagName){if(!(k=e.id)){k=Ext.id(e)}d=Ext.cache[k];if(d&&d.el){j=Ext.cache[k].el;j.dom=e}else{j=new h(e,!!d)}return j}else{if(e instanceof g){if(e!=g.docEl&&e!=g.winEl){e.dom=a.getElementById(e.id)||e.dom}return e}else{if(e.isComposite){return e}else{if(Ext.isArray(e)){return g.select(e)}else{if(e===a){if(!g.docEl){g.docEl=Ext.Object.chain(h.prototype);g.docEl.dom=a;g.docEl.id=Ext.id(a);g.addToCache(g.docEl)}return g.docEl}else{if(e===window){if(!g.winEl){g.winEl=Ext.Object.chain(h.prototype);g.winEl.dom=window;g.winEl.id=Ext.id(window);g.addToCache(g.winEl)}return g.winEl}}}}}}}return null},addToCache:function(d,e){if(d){Ext.addCacheEntry(e,d)}return d},addMethods:function(){this.override.apply(this,arguments)},mergeClsList:function(){var n,m={},k,d,g,l,e,o=[],h=false;for(k=0,d=arguments.length;kwindow.innerWidth)?"portrait":"landscape"},fromPoint:function(a,b){return Ext.get(document.elementFromPoint(a,b))},parseStyles:function(c){var a={},b=this.cssRe,d;if(c){b.lastIndex=0;while((d=b.exec(c))){a[d[1]]=d[2]}}return a}});(function(){var g=document,a=Ext.dom.AbstractElement,e=null,d=g.compatMode=="CSS1Compat",c,b=function(i){if(!c){c=new a.Fly()}c.attach(i);return c};if(!("activeElement" in g)&&g.addEventListener){g.addEventListener("focus",function(i){if(i&&i.target){e=(i.target==g)?null:i.target}},true)}function h(j,k,i){return function(){j.selectionStart=k;j.selectionEnd=i}}a.addInheritableStatics({getActiveElement:function(){return g.activeElement||e},getRightMarginFixCleaner:function(n){var k=Ext.supports,l=k.DisplayChangeInputSelectionBug,m=k.DisplayChangeTextAreaSelectionBug,o,i,p,j;if(l||m){o=g.activeElement||e;i=o&&o.tagName;if((m&&i=="TEXTAREA")||(l&&i=="INPUT"&&o.type=="text")){if(Ext.dom.Element.isAncestor(n,o)){p=o.selectionStart;j=o.selectionEnd;if(Ext.isNumber(p)&&Ext.isNumber(j)){return h(o,p,j)}}}}return Ext.emptyFn},getViewWidth:function(i){return i?Ext.dom.Element.getDocumentWidth():Ext.dom.Element.getViewportWidth()},getViewHeight:function(i){return i?Ext.dom.Element.getDocumentHeight():Ext.dom.Element.getViewportHeight()},getDocumentHeight:function(){return Math.max(!d?g.body.scrollHeight:g.documentElement.scrollHeight,Ext.dom.Element.getViewportHeight())},getDocumentWidth:function(){return Math.max(!d?g.body.scrollWidth:g.documentElement.scrollWidth,Ext.dom.Element.getViewportWidth())},getViewportHeight:function(){return Ext.isIE?(Ext.isStrict?g.documentElement.clientHeight:g.body.clientHeight):self.innerHeight},getViewportWidth:function(){return(!Ext.isStrict&&!Ext.isOpera)?g.body.clientWidth:Ext.isIE?g.documentElement.clientWidth:self.innerWidth},getY:function(i){return Ext.dom.Element.getXY(i)[1]},getX:function(i){return Ext.dom.Element.getXY(i)[0]},getXY:function(k){var n=g.body,j=g.documentElement,i=0,l=0,o=[0,0],r=Math.round,m,q;k=Ext.getDom(k);if(k!=g&&k!=n){if(Ext.isIE){try{m=k.getBoundingClientRect();l=j.clientTop||n.clientTop;i=j.clientLeft||n.clientLeft}catch(p){m={left:0,top:0}}}else{m=k.getBoundingClientRect()}q=b(document).getScroll();o=[r(m.left+q.left-i),r(m.top+q.top-l)]}return o},setXY:function(j,k){(j=Ext.fly(j,"_setXY")).position();var l=j.translatePoints(k),i=j.dom.style,m;for(m in l){if(!isNaN(l[m])){i[m]=l[m]+"px"}}},setX:function(j,i){Ext.dom.Element.setXY(j,[i,false])},setY:function(i,j){Ext.dom.Element.setXY(i,[false,j])},serializeForm:function(k){var l=k.elements||(document.forms[k]||Ext.getDom(k)).elements,v=false,u=encodeURIComponent,p="",n=l.length,q,i,t,x,w,r,m,s,j;for(r=0;rn){m=q?h.left-r:n-r}if(m<0){m=q?h.right:0}if(l+p>u){l=o?h.top-p:u-p}if(l<0){l=o?h.bottom:0}}return[m,l]},getAnchor:function(){var b=(this.$cache||this.getCache()).data,a;if(!this.dom){return}a=b._anchor;if(!a){a=b._anchor={}}return a},adjustForConstraints:function(c,b){var a=this.getConstrainVector(b,c);if(a){c[0]+=a[0];c[1]+=a[1]}return c}});Ext.dom.AbstractElement.addMethods({appendChild:function(a){return Ext.get(a).appendTo(this)},appendTo:function(a){Ext.getDom(a).appendChild(this.dom);return this},insertBefore:function(a){a=Ext.getDom(a);a.parentNode.insertBefore(this.dom,a);return this},insertAfter:function(a){a=Ext.getDom(a);a.parentNode.insertBefore(this.dom,a.nextSibling);return this},insertFirst:function(b,a){b=b||{};if(b.nodeType||b.dom||typeof b=="string"){b=Ext.getDom(b);this.dom.insertBefore(b,this.dom.firstChild);return !a?Ext.get(b):b}else{return this.createChild(b,this.dom.firstChild,a)}},insertSibling:function(b,g,j){var i=this,k=(g||"before").toLowerCase()=="after",d,a,c,h;if(Ext.isArray(b)){a=i;c=b.length;for(h=0;h1){g=[g,arguments[1]]}e=c.translatePoints(g);b=c.dom.style;for(d in e){if(!e.hasOwnProperty(d)){continue}if(!isNaN(e[d])){b[d]=e[d]+"px"}}return c},getLeft:function(b){return parseInt(this.getStyle("left"),10)||0},getRight:function(b){return parseInt(this.getStyle("right"),10)||0},getTop:function(b){return parseInt(this.getStyle("top"),10)||0},getBottom:function(b){return parseInt(this.getStyle("bottom"),10)||0},translatePoints:function(b,i){i=isNaN(b[1])?i:b[1];b=isNaN(b[0])?b:b[0];var e=this,g=e.isStyle("position","relative"),h=e.getXY(),c=parseInt(e.getStyle("left"),10),d=parseInt(e.getStyle("top"),10);c=!isNaN(c)?c:(g?0:e.dom.offsetLeft);d=!isNaN(d)?d:(g?0:e.dom.offsetTop);return{left:(b-h[0]+c),top:(i-h[1]+d)}},setBox:function(e){var d=this,c=e.width,b=e.height,h=e.top,g=e.left;if(g!==undefined){d.setLeft(g)}if(h!==undefined){d.setTop(h)}if(c!==undefined){d.setWidth(c)}if(b!==undefined){d.setHeight(b)}return this},getBox:function(i,m){var j=this,g=j.dom,d=g.offsetWidth,n=g.offsetHeight,p,h,e,c,o,k;if(!m){p=j.getXY()}else{if(i){p=[0,0]}else{p=[parseInt(j.getStyle("left"),10)||0,parseInt(j.getStyle("top"),10)||0]}}if(!i){h={x:p[0],y:p[1],0:p[0],1:p[1],width:d,height:n}}else{e=j.getBorderWidth.call(j,"l")+j.getPadding.call(j,"l");c=j.getBorderWidth.call(j,"r")+j.getPadding.call(j,"r");o=j.getBorderWidth.call(j,"t")+j.getPadding.call(j,"t");k=j.getBorderWidth.call(j,"b")+j.getPadding.call(j,"b");h={x:p[0]+e,y:p[1]+o,0:p[0]+e,1:p[1]+o,width:d-(e+c),height:n-(o+k)}}h.left=h.x;h.top=h.y;h.right=h.x+h.width;h.bottom=h.y+h.height;return h},getPageBox:function(g){var j=this,d=j.dom,m=d.offsetWidth,i=d.offsetHeight,o=j.getXY(),n=o[1],c=o[0]+m,k=o[1]+i,e=o[0];if(!d){return new Ext.util.Region()}if(g){return new Ext.util.Region(n,c,k,e)}else{return{left:e,top:n,width:m,height:i,right:c,bottom:k}}}})}());(function(){var q=Ext.dom.AbstractElement,o=document.defaultView,n=Ext.Array,m=/^\s+|\s+$/g,b=/\w/g,p=/\s+/,t=/^(?:transparent|(?:rgba[(](?:\s*\d+\s*[,]){3}\s*0\s*[)]))$/i,h=Ext.supports.ClassList,e="padding",d="margin",s="border",k="-left",r="-right",l="-top",c="-bottom",i="-width",j={l:s+k+i,r:s+r+i,t:s+l+i,b:s+c+i},g={l:e+k,r:e+r,t:e+l,b:e+c},a={l:d+k,r:d+r,t:d+l,b:d+c};q.override({styleHooks:{},addStyles:function(B,A){var w=0,z=(B||"").match(b),y,u=z.length,x,v=[];if(u==1){w=Math.abs(parseFloat(this.getStyle(A[z[0]]))||0)}else{if(u){for(y=0;y0?u:0},getWidth:function(u){var w=this.dom,v=u?(w.clientWidth-this.getPadding("lr")):w.offsetWidth;return v>0?v:0},setWidth:function(u){var v=this;v.dom.style.width=q.addUnits(u);return v},setHeight:function(u){var v=this;v.dom.style.height=q.addUnits(u);return v},getBorderWidth:function(u){return this.addStyles(u,j)},getPadding:function(u){return this.addStyles(u,g)},margins:a,applyStyles:function(w){if(w){var v,u,x=this.dom;if(typeof w=="function"){w=w.call()}if(typeof w=="string"){w=Ext.util.Format.trim(w).split(/\s*(?::|;)\s*/);for(v=0,u=w.length;v'+v+""):""});C=A.getSize();x.mask=E;if(w===document.body){C.height=window.innerHeight;if(A.orientationHandler){Ext.EventManager.unOrientationChange(A.orientationHandler,A)}A.orientationHandler=function(){C=A.getSize();C.height=window.innerHeight;E.setSize(C)};Ext.EventManager.onOrientationChange(A.orientationHandler,A)}E.setSize(C);if(Ext.is.iPad){Ext.repaint()}},unmask:function(){var v=this,x=(v.$cache||v.getCache()).data,u=x.mask,w=Ext.baseCSSPrefix;if(u){u.remove();delete x.mask}v.removeCls([w+"masked",w+"masked-relative"]);if(v.dom===document.body){Ext.EventManager.unOrientationChange(v.orientationHandler,v);delete v.orientationHandler}}});q.populateStyleMap=function(B,u){var A=["margin-","padding-","border-width-"],z=["before","after"],w,y,v,x;for(w=A.length;w--;){for(x=2;x--;){y=A[w]+z[x];B[q.normalize(y)]=B[y]={name:q.normalize(A[w]+u[x])}}}};Ext.onReady(function(){var C=Ext.supports,u,A,y,v,B;function z(H,E,G,D){var F=D[this.name]||"";return t.test(F)?"transparent":F}function x(J,G,I,F){var D=F.marginRight,E,H;if(D!="0px"){E=J.style;H=E.display;E.display="inline-block";D=(I?F:J.ownerDocument.defaultView.getComputedStyle(J,null)).marginRight;E.display=H}return D}function w(K,H,J,G){var D=G.marginRight,F,E,I;if(D!="0px"){F=K.style;E=q.getRightMarginFixCleaner(K);I=F.display;F.display="inline-block";D=(J?G:K.ownerDocument.defaultView.getComputedStyle(K,"")).marginRight;F.display=I;E()}return D}u=q.prototype.styleHooks;q.populateStyleMap(u,["left","right"]);if(C.init){C.init()}if(!C.RightMargin){u.marginRight=u["margin-right"]={name:"marginRight",get:(C.DisplayChangeInputSelectionBug||C.DisplayChangeTextAreaSelectionBug)?w:x}}if(!C.TransparentColor){A=["background-color","border-color","color","outline-color"];for(y=A.length;y--;){v=A[y];B=q.normalize(v);u[v]=u[B]={name:B,get:z}}}})}());Ext.dom.AbstractElement.override({findParent:function(h,b,a){var e=this.dom,c=document.documentElement,g=0,d;b=b||50;if(isNaN(b)){d=Ext.getDom(b);b=Number.MAX_VALUE}while(e&&e.nodeType==1&&g "+a,c.dom);return b?d:Ext.get(d)},parent:function(a,b){return this.matchNode("parentNode","parentNode",a,b)},next:function(a,b){return this.matchNode("nextSibling","nextSibling",a,b)},prev:function(a,b){return this.matchNode("previousSibling","previousSibling",a,b)},first:function(a,b){return this.matchNode("nextSibling","firstChild",a,b)},last:function(a,b){return this.matchNode("previousSibling","lastChild",a,b)},matchNode:function(b,e,a,c){if(!this.dom){return null}var d=this.dom[e];while(d){if(d.nodeType==1&&(!a||Ext.DomQuery.is(d,a))){return !c?Ext.get(d):d}d=d[b]}return null},isAncestor:function(a){return this.self.isAncestor.call(this.self,this.dom,a)}});(function(){var b="afterbegin",i="afterend",a="beforebegin",o="beforeend",l="",h="
    ",c=l+"",n=""+h,k=c+"",e=""+n,p=document.createElement("div"),m=["BeforeBegin","previousSibling"],j=["AfterEnd","nextSibling"],d={beforebegin:m,afterend:j},g={beforebegin:m,afterend:j,afterbegin:["AfterBegin","firstChild"],beforeend:["BeforeEnd","lastChild"]};Ext.define("Ext.dom.Helper",{extend:"Ext.dom.AbstractHelper",tableRe:/^table|tbody|tr|td$/i,tableElRe:/td|tr|tbody/i,useDom:false,createDom:function(q,w){var r,z=document,u,x,s,y,v,t;if(Ext.isArray(q)){r=z.createDocumentFragment();for(v=0,t=q.length;v+~]\s?|\s|$)/,tagTokenRe=/^(#)?([\w\-\*\\]+)/,nthRe=/(\d*)n\+?(\d*)/,nthRe2=/\D/,startIdRe=/^\s*\#/,isIE=window.ActiveXObject?true:false,key=30803,longHex=/\\([0-9a-fA-F]{6})/g,shortHex=/\\([0-9a-fA-F]{1,6})\s{0,1}/g,nonHex=/\\([^0-9a-fA-F]{1})/g,escapes=/\\/g,num,hasEscapes,longHexToChar=function($0,$1){return String.fromCharCode(parseInt($1,16))},shortToLongHex=function($0,$1){while($1.length<6){$1="0"+$1}return"\\"+$1},charToLongHex=function($0,$1){num=$1.charCodeAt(0).toString(16);if(num.length===1){num="0"+num}return"\\0000"+num},unescapeCssSelector=function(selector){return(hasEscapes)?selector.replace(longHex,longHexToChar):selector};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}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(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}function byClassName(nodeSet,cls){cls=unescapeCssSelector(cls);if(!cls){return nodeSet}var result=[],ri=-1,i,ci;for(i=0,ci;ci=nodeSet[i];i++){if((" "+ci.className+" ").indexOf(cls)!=-1){result[++ri]=ci}}return result}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,i,ni,j,ci,cn,utag,n,cj;if(!ns){return result}tagName=tagName||"*";if(typeof ns.getElementsByTagName!="undefined"){ns=[ns]}if(!mode){for(i=0,ni;ni=ns[i];i++){cs=ni.getElementsByTagName(tagName);for(j=0,ci;ci=cs[j];j++){result[++ri]=ci}}}else{if(mode=="/"||mode==">"){utag=tagName.toUpperCase();for(i=0,ni,cn;ni=ns[i];i++){cn=ni.childNodes;for(j=0,cj;cj=cn[j];j++){if(cj.nodeName==utag||cj.nodeName==tagName||tagName=="*"){result[++ri]=cj}}}}else{if(mode=="+"){utag=tagName.toUpperCase();for(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=="~"){utag=tagName.toUpperCase();for(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-1);if(hasEscapes){path=path.replace(shortHex,shortToLongHex).replace(nonHex,charToLongHex).replace(escapes,"\\\\")}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;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))){matched=false;for(j=0;j1){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{if(root.parentNode&&(root.nodeType!==9)&&path.indexOf(",")===-1&&!startIdRe.test(path)){path="#"+Ext.escapeId(Ext.id(root))+" "+path;root=root.parentNode}return Ext.Array.toArray(root.querySelectorAll(path))}catch(e){}}return Ext.DomQuery.jsSelect.call(this,path,root,type)}:function(path,root,type){return Ext.DomQuery.jsSelect.call(this,path,root,type)},selectNode:function(path,root){return Ext.DomQuery.select(path,root)[0]},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)},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)}var isArray=Ext.isArray(el),result=Ext.DomQuery.filter(isArray?el:[el],ss);return isArray?(result.length==el.length):(result.length>0)},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},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}")}};'}],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,i,ci;for(i=0;(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,i,ci;for(i=0;(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,i,n,j,cn,pn;for(i=0;n=c[i];i++){pn=n.parentNode;if(batch!=pn._batch){j=0;for(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,i,ci;for(i=0;ci=c[i];i++){if(!prev(ci)&&!next(ci)){r[++ri]=ci}}return r},empty:function(c){var r=[],ri=-1,i,ci,cns,j,cn,empty;for(i=0,ci;ci=c[i];i++){cns=ci.childNodes;j=0;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,i,ci;for(i=0;ci=c[i];i++){if((ci.textContent||ci.innerText||ci.text||"").indexOf(v)!=-1){r[++ri]=ci}}return r},nodeValue:function(c,v){var r=[],ri=-1,i,ci;for(i=0;ci=c[i];i++){if(ci.firstChild&&ci.firstChild.nodeValue==v){r[++ri]=ci}}return r},checked:function(c){var r=[],ri=-1,i,ci;for(i=0;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,i,ci,j;for(i=0;ci=c[i];i++){for(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,i,ci;for(i=0;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,i,ci,n;for(i=0;ci=c[i];i++){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,i,ci,n;for(i=0;ci=c[i];i++){n=prev(ci);if(n&&is(n,ss)){r[++ri]=ci}}return r}}}}());Ext.query=Ext.DomQuery.select;(function(){var HIDDEN="hidden",DOC=document,VISIBILITY="visibility",DISPLAY="display",NONE="none",XMASKED=Ext.baseCSSPrefix+"masked",XMASKEDRELATIVE=Ext.baseCSSPrefix+"masked-relative",EXTELMASKMSG=Ext.baseCSSPrefix+"mask-msg",bodyRe=/^body/i,visFly,noBoxAdjust=Ext.isStrict?{select:1}:{input:1,select:1,textarea:1},isScrolled=function(c){var r=[],ri=-1,i,ci;for(i=0;ci=c[i];i++){if(ci.scrollTop>0||ci.scrollLeft>0){r[++ri]=ci}}return r},Element=Ext.define("Ext.dom.Element",{extend:"Ext.dom.AbstractElement",alternateClassName:["Ext.Element","Ext.core.Element"],addUnits:function(){return this.self.addUnits.apply(this.self,arguments)},focus:function(defer,dom){var me=this,scrollTop,body;dom=dom||me.dom;body=(dom.ownerDocument||DOC).body||DOC.body;try{if(Number(defer)){Ext.defer(me.focus,defer,me,[null,dom])}else{if(dom.offsetHeight>Element.getViewHeight()){scrollTop=body.scrollTop}dom.focus();if(scrollTop!==undefined){body.scrollTop=scrollTop}}}catch(e){}return me},blur:function(){try{this.dom.blur()}catch(e){}return this},isBorderBox:function(){var box=Ext.isBorderBox;if(box){box=!((this.dom.tagName||"").toLowerCase() in noBoxAdjust)}return box},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},getAttributeNS:function(ns,name){return this.getAttribute(name,ns)},getAttribute:(Ext.isIE&&!(Ext.isIE9&&DOC.documentMode===9))?function(name,ns){var d=this.dom,type;if(ns){type=typeof d[ns+":"+name];if(type!="undefined"&&type!="unknown"){return d[ns+":"+name]||null}return null}if(name==="for"){name="htmlFor"}return d[name]||null}:function(name,ns){var d=this.dom;if(ns){return d.getAttributeNS(ns,name)||d.getAttribute(ns+":"+name)}return d.getAttribute(name)||d[name]||null},cacheScrollValues:function(){var me=this,scrolledDescendants,el,i,scrollValues=[],result=function(){for(i=0;i]*)?>)((\n|\r|.)*?)(?:<\/script>)/ig,replaceScriptTagRe=/(?:)((\n|\r|.)*?)(?:<\/script>)/ig,srcRe=/\ssrc=([\'\"])(.*?)\1/i,typeRe=/\stype=([\'\"])(.*?)\1/i,useDocForId=!(Ext.isIE6||Ext.isIE7||Ext.isIE8);El.boxMarkup='
    ';function garbageCollect(){if(!Ext.enableGarbageCollector){clearInterval(El.collectorThreadId)}else{var eid,d,o,t;for(eid in EC){if(!EC.hasOwnProperty(eid)){continue}o=EC[eid];if(o.skipGarbageCollection){continue}d=o.dom;if(!d.parentNode||(!d.offsetParent&&!Ext.getElementById(eid))){if(d&&Ext.enableListenerCollection){Ext.EventManager.removeAll(d)}delete EC[eid]}}if(Ext.isIE){t={};for(eid in EC){if(!EC.hasOwnProperty(eid)){continue}t[eid]=EC[eid]}EC=Ext.cache=t}}}El.collectorThreadId=setInterval(garbageCollect,30000);El.addMethods({monitorMouseLeave:function(delay,handler,scope){var me=this,timer,listeners={mouseleave:function(e){timer=setTimeout(Ext.Function.bind(handler,scope||me,[e]),delay)},mouseenter:function(){clearTimeout(timer)},freezeEvent:true};me.on(listeners);return listeners},swallowEvent:function(eventName,preventDefault){var me=this,e,eLen;function fn(e){e.stopPropagation();if(preventDefault){e.preventDefault()}}if(Ext.isArray(eventName)){eLen=eventName.length;for(e=0;e';interval=setInterval(function(){var hd,match,attrs,srcMatch,typeMatch,el,s;if(!(el=DOC.getElementById(id))){return false}clearInterval(interval);Ext.removeNode(el);hd=Ext.getHead().dom;while((match=scriptTagRe.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.callback(callback,me)},20);dom.innerHTML=html.replace(replaceScriptTagRe,"");return me},removeAllListeners:function(){this.removeAnchor();Ext.EventManager.removeAll(this.dom);return this},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);proxy.setVisibilityMode(Element.DISPLAY);proxy.hide();if(matchBox&&me.setBox&&me.getBox){proxy.setBox(me.getBox())}return proxy},getScopeParent:function(){var parent=this.dom.parentNode;return Ext.scopeResetCSS?parent.parentNode:parent},needsTabIndex:function(){if(this.dom){if((this.dom.nodeName==="a")&&(!this.dom.href)){return true}return !focusRe.test(this.dom.nodeName)}},focusable:function(){var dom=this.dom,nodeName=dom.nodeName,canFocus=false;if(!dom.disabled){if(focusRe.test(nodeName)){if((nodeName!=="a")||dom.href){canFocus=true}}else{canFocus=!isNaN(dom.tabIndex)}}return canFocus&&this.isVisible(true)}});if(Ext.isIE){El.prototype.getById=function(id,asDom){var dom=this.dom,cached,el,ret;if(dom){el=(useDocForId&&DOC.getElementById(id))||dom.all[id];if(el){if(asDom){ret=el}else{cached=EC[id];if(cached&&cached.el){ret=cached.el;ret.dom=el}else{ret=new Element(el)}}return ret}}return asDom?Ext.getDom(id):El.get(id)}}El.createAlias({addListener:"on",removeListener:"un",clearListeners:"removeAllListeners"});El.Fly=AbstractElement.Fly=new Ext.Class({extend:El,constructor:function(dom){this.dom=dom},attach:AbstractElement.Fly.prototype.attach});if(Ext.isIE){Ext.getElementById=function(id){var el=DOC.getElementById(id),detachedBodyEl;if(!el&&(detachedBodyEl=AbstractElement.detachedBodyEl)){el=detachedBodyEl.dom.all[id]}return el}}else{if(!DOC.querySelector){Ext.getDetachedBody=Ext.getBody;Ext.getElementById=function(id){return DOC.getElementById(id)}}}})}());Ext.dom.Element.override((function(){var d=document,c=window,a=/^([a-z]+)-([a-z]+)(\?)?$/,b=Math.round;return{getAnchorXY:function(j,o,h){j=(j||"tl").toLowerCase();h=h||{};var m=this,i=m.dom==d.body||m.dom==d,e=h.width||i?Ext.dom.Element.getViewWidth():m.getWidth(),g=h.height||i?Ext.dom.Element.getViewHeight():m.getHeight(),q,n=m.getXY(),p=m.getScroll(),l=i?p.left:!o?n[0]:0,k=i?p.top:!o?n[1]:0;switch(j){case"tl":q=[0,0];break;case"bl":q=[0,g];break;case"tr":q=[e,0];break;case"c":q=[b(e*0.5),b(g*0.5)];break;case"t":q=[b(e*0.5),0];break;case"l":q=[0,b(g*0.5)];break;case"r":q=[e,b(g*0.5)];break;case"b":q=[b(e*0.5),g];break;case"br":q=[e,g]}return[q[0]+l,q[1]+k]},getAlignToXY:function(m,G,j){m=Ext.get(m);if(!m||!m.dom){}j=j||[0,0];G=(!G||G=="?"?"tl-bl?":(!(/-/).test(G)&&G!==""?"tl-"+G:G||"tl-bl")).toLowerCase();var H=this,l,w,q,o,k,z,A,E=Ext.dom.Element.getViewWidth()-10,i=Ext.dom.Element.getViewHeight()-10,g,h,n,p,u,v,F=d.documentElement,s=d.body,D=(F.scrollLeft||s.scrollLeft||0),B=(F.scrollTop||s.scrollTop||0),C,t,r,e=G.match(a);t=e[1];r=e[2];C=!!e[3];l=H.getAnchorXY(t,true);w=m.getAnchorXY(r,false);q=w[0]-l[0]+j[0];o=w[1]-l[1]+j[1];if(C){k=H.getWidth();z=H.getHeight();A=m.getRegion();g=t.charAt(0);h=t.charAt(t.length-1);n=r.charAt(0);p=r.charAt(r.length-1);u=((g=="t"&&n=="b")||(g=="b"&&n=="t"));v=((h=="r"&&p=="l")||(h=="l"&&p=="r"));if(q+k>E+D){q=v?A.left-k:E+D-k}if(qi+B){o=u?A.top-z:i+B-z}if(oi.right){h=true;e[0]=(i.right-k.right)}if(k.left+e[0]i.bottom){h=true;e[1]=(i.bottom-k.bottom)}if(k.top+e[1]a.clientHeight||a.scrollWidth>a.clientWidth},getScroll:function(){var i=this.dom,h=document,a=h.body,c=h.documentElement,b,g,e;if(i==h||i==a){if(Ext.isIE&&Ext.isStrict){b=c.scrollLeft;g=c.scrollTop}else{b=window.pageXOffset;g=window.pageYOffset}e={left:b||(a?a.scrollLeft:0),top:g||(a?a.scrollTop:0)}}else{e={left:i.scrollLeft,top:i.scrollTop}}return e},scrollBy:function(b,a,c){var d=this,e=d.dom;if(b.length){c=a;a=b[1];b=b[0]}else{if(typeof b!="number"){c=a;a=b.y;b=b.x}}if(b){d.scrollTo("left",Math.max(Math.min(e.scrollLeft+b,e.scrollWidth-e.clientWidth),0),c)}if(a){d.scrollTo("top",Math.max(Math.min(e.scrollTop+a,e.scrollHeight-e.clientHeight),0),c)}return d},scrollTo:function(b,d,a){var g=/top/i.test(b),c=this,h=c.dom,e={},i;if(!a||!c.anim){i="scroll"+(g?"Top":"Left");h[i]=d}else{if(!Ext.isObject(a)){a={}}e["scroll"+(g?"Top":"Left")]=d;c.animate(Ext.applyIf({to:e},a))}return c},scrollIntoView:function(b,e){b=Ext.getDom(b)||Ext.getBody().dom;var c=this.dom,h=this.getOffsetsTo(b),g=h[0]+b.scrollLeft,j=h[1]+b.scrollTop,a=j+c.offsetHeight,k=g+c.offsetWidth,n=b.clientHeight,m=parseInt(b.scrollTop,10),d=parseInt(b.scrollLeft,10),i=m+n,l=d+b.clientWidth;if(c.offsetHeight>n||ji){b.scrollTop=a-n}}b.scrollTop=b.scrollTop;if(e!==false){if(c.offsetWidth>b.clientWidth||gl){b.scrollLeft=k-b.clientWidth}}b.scrollLeft=b.scrollLeft}return this},scrollChildIntoView:function(b,a){Ext.fly(b,"_scrollChildIntoView").scrollIntoView(this,a)},scroll:function(m,b,d){if(!this.isScrollable()){return false}var e=this.dom,g=e.scrollLeft,p=e.scrollTop,n=e.scrollWidth,k=e.scrollHeight,i=e.clientWidth,a=e.clientHeight,c=false,o,j={l:Math.min(g+b,n-i),r:o=Math.max(g-b,0),t:Math.max(p-b,0),b:Math.min(p+b,k-a)};j.d=j.b;j.u=j.t;m=m.substr(0,1);if((o=j[m])>-1){c=true;this.scrollTo(m=="l"||m=="r"?"left":"top",o,this.anim(d))}return c}});(function(){var p=Ext.dom.Element,m=document.defaultView,n=/table-row|table-.*-group/,a="_internal",r="hidden",o="height",g="width",e="isClipped",i="overflow",l="overflow-x",j="overflow-y",s="originalClip",b=/#document|body/i,t,d,q,h,u;if(!m||!m.getComputedStyle){p.prototype.getStyle=function(z,y){var L=this,G=L.dom,J=typeof z!="string",k=L.styleHooks,w=z,x=w,F=1,B=y,K,C,v,A,E,H,D;if(J){v={};w=x[0];D=0;if(!(F=x.length)){return v}}if(!G||G.documentElement){return v||""}C=G.style;if(y){H=C}else{H=G.currentStyle;if(!H){B=true;H=C}}do{A=k[w];if(!A){k[w]=A={name:p.normalize(w)}}if(A.get){E=A.get(G,L,B,H)}else{K=A.name;if(A.canThrow){try{E=H[K]}catch(I){E=""}}else{E=H?H[K]:""}}if(!J){return E}v[w]=E;w=x[++D]}while(D0&&A<0.5){k++}}}if(x){k-=w.getBorderWidth("tb")+w.getPadding("tb")}return(k<0)?0:k},getWidth:function(k,z){var x=this,A=x.dom,y=x.isStyle("display","none"),w,v,B;if(y){return 0}if(Ext.supports.BoundingClientRect){w=A.getBoundingClientRect();v=w.right-w.left;v=z?v:Math.ceil(v)}else{v=A.offsetWidth}v=Math.max(v,A.clientWidth)||0;if(Ext.supports.Direct2DBug){B=x.adjustDirect2DDimension(g);if(z){v+=B}else{if(B>0&&B<0.5){v++}}}if(k){v-=x.getBorderWidth("lr")+x.getPadding("lr")}return(v<0)?0:v},setWidth:function(v,k){var w=this;v=w.adjustWidth(v);if(!k||!w.anim){w.dom.style.width=w.addUnits(v)}else{if(!Ext.isObject(k)){k={}}w.animate(Ext.applyIf({to:{width:v}},k))}return w},setHeight:function(k,v){var w=this;k=w.adjustHeight(k);if(!v||!w.anim){w.dom.style.height=w.addUnits(k)}else{if(!Ext.isObject(v)){v={}}w.animate(Ext.applyIf({to:{height:k}},v))}return w},applyStyles:function(k){Ext.DomHelper.applyStyles(this.dom,k);return this},setSize:function(w,k,v){var x=this;if(Ext.isObject(w)){v=k;k=w.height;w=w.width}w=x.adjustWidth(w);k=x.adjustHeight(k);if(!v||!x.anim){x.dom.style.width=x.addUnits(w);x.dom.style.height=x.addUnits(k)}else{if(v===true){v={}}x.animate(Ext.applyIf({to:{width:w,height:k}},v))}return x},getViewSize:function(){var w=this,x=w.dom,v=b.test(x.nodeName),k;if(v){k={width:p.getViewWidth(),height:p.getViewHeight()}}else{k={width:x.clientWidth,height:x.clientHeight}}return k},getSize:function(k){return{width:this.getWidth(k),height:this.getHeight(k)}},adjustWidth:function(k){var v=this,w=(typeof k=="number");if(w&&v.autoBoxAdjust&&!v.isBorderBox()){k-=(v.getBorderWidth("lr")+v.getPadding("lr"))}return(w&&k<0)?0:k},adjustHeight:function(k){var v=this,w=(typeof k=="number");if(w&&v.autoBoxAdjust&&!v.isBorderBox()){k-=(v.getBorderWidth("tb")+v.getPadding("tb"))}return(w&&k<0)?0:k},getColor:function(w,x,C){var z=this.getStyle(w),y=C||C===""?C:"#",B,k,A=0;if(!z||(/transparent|inherit/.test(z))){return x}if(/^r/.test(z)){z=z.slice(4,z.length-1).split(",");k=z.length;for(;A5?y.toLowerCase():x)},setOpacity:function(v,k){var w=this;if(!w.dom){return w}if(!k||!w.anim){w.setStyle("opacity",v)}else{if(typeof k!="object"){k={duration:350,easing:"ease-in"}}w.animate(Ext.applyIf({to:{opacity:v}},k))}return w},clearOpacity:function(){return this.setOpacity("")},adjustDirect2DDimension:function(w){var B=this,v=B.dom,z=B.getStyle("display"),y=v.style.display,C=v.style.position,A=w===g?0:1,k=v.currentStyle,x;if(z==="inline"){v.style.display="inline-block"}v.style.position=z.match(n)?"absolute":"static";x=(parseFloat(k[w])||parseFloat(k.msTransformOrigin.split(" ")[A])*2)%1;v.style.position=C;if(z==="inline"){v.style.display=y}return x},clip:function(){var v=this,w=(v.$cache||v.getCache()).data,k;if(!w[e]){w[e]=true;k=v.getStyle([i,l,j]);w[s]={o:k[i],x:k[l],y:k[j]};v.setStyle(i,r);v.setStyle(l,r);v.setStyle(j,r)}return v},unclip:function(){var v=this,w=(v.$cache||v.getCache()).data,k;if(w[e]){w[e]=false;k=w[s];if(k.o){v.setStyle(i,k.o)}if(k.x){v.setStyle(l,k.x)}if(k.y){v.setStyle(j,k.y)}}return v},boxWrap:function(k){k=k||Ext.baseCSSPrefix+"box";var v=Ext.get(this.insertHtml("beforeBegin","
    "+Ext.String.format(p.boxMarkup,k)+"
    "));Ext.DomQuery.selectNode("."+k+"-mc",v.dom).appendChild(this.dom);return v},getComputedHeight:function(){var v=this,k=Math.max(v.dom.offsetHeight,v.dom.clientHeight);if(!k){k=parseFloat(v.getStyle(o))||0;if(!v.isBorderBox()){k+=v.getFrameWidth("tb")}}return k},getComputedWidth:function(){var v=this,k=Math.max(v.dom.offsetWidth,v.dom.clientWidth);if(!k){k=parseFloat(v.getStyle(g))||0;if(!v.isBorderBox()){k+=v.getFrameWidth("lr")}}return k},getFrameWidth:function(v,k){return(k&&this.isBorderBox())?0:(this.getPadding(v)+this.getBorderWidth(v))},addClsOnOver:function(w,z,v){var x=this,y=x.dom,k=Ext.isFunction(z);x.hover(function(){if(k&&z.call(v||x,x)===false){return}Ext.fly(y,a).addCls(w)},function(){Ext.fly(y,a).removeCls(w)});return x},addClsOnFocus:function(w,z,v){var x=this,y=x.dom,k=Ext.isFunction(z);x.on("focus",function(){if(k&&z.call(v||x,x)===false){return false}Ext.fly(y,a).addCls(w)});x.on("blur",function(){Ext.fly(y,a).removeCls(w)});return x},addClsOnClick:function(w,z,v){var x=this,y=x.dom,k=Ext.isFunction(z);x.on("mousedown",function(){if(k&&z.call(v||x,x)===false){return false}Ext.fly(y,a).addCls(w);var B=Ext.getDoc(),A=function(){Ext.fly(y,a).removeCls(w);B.removeListener("mouseup",A)};B.on("mouseup",A)});return x},getStyleSize:function(){var z=this,A=this.dom,v=b.test(A.nodeName),y,k,x;if(v){return{width:p.getViewWidth(),height:p.getViewHeight()}}y=z.getStyle([o,g],true);if(y.width&&y.width!="auto"){k=parseFloat(y.width);if(z.isBorderBox()){k-=z.getFrameWidth("lr")}}if(y.height&&y.height!="auto"){x=parseFloat(y.height);if(z.isBorderBox()){x-=z.getFrameWidth("tb")}}return{width:k||z.getWidth(true),height:x||z.getHeight(true)}},selectable:function(){var k=this;k.dom.unselectable="off";k.on("selectstart",function(v){v.stopPropagation();return true});k.applyStyles("-moz-user-select: text; -khtml-user-select: text;");k.removeCls(Ext.baseCSSPrefix+"unselectable");return k},unselectable:function(){var k=this;k.dom.unselectable="on";k.swallowEvent("selectstart",true);k.applyStyles("-moz-user-select:-moz-none;-khtml-user-select:none;");k.addCls(Ext.baseCSSPrefix+"unselectable");return k}});p.prototype.styleHooks=t=Ext.dom.AbstractElement.prototype.styleHooks;if(Ext.isIE6){t.fontSize=t["font-size"]={name:"fontSize",canThrow:true}}if(Ext.isIEQuirks||Ext.isIE&&Ext.ieVersion<=8){function c(x,v,w,k){if(k[this.styleName]=="none"){return"0px"}return k[this.name]}d=["Top","Right","Bottom","Left"];q=d.length;while(q--){h=d[q];u="border"+h+"Width";t["border-"+h.toLowerCase()+"-width"]=t[u]={name:u,styleName:"border"+h+"Style",get:c}}}}());Ext.onReady(function(){var c=/alpha\(opacity=(.*)\)/i,b=/^\s+|\s+$/g,a=Ext.dom.Element.prototype.styleHooks;a.opacity={name:"opacity",afterSet:function(g,e,d){if(d.isLayer){d.onOpacitySet(e)}}};if(!Ext.supports.Opacity&&Ext.isIE){Ext.apply(a.opacity,{get:function(h){var g=h.style.filter,e,d;if(g.match){e=g.match(c);if(e){d=parseFloat(e[1]);if(!isNaN(d)){return d?d/100:0}}}return 1},set:function(h,e){var d=h.style,g=d.filter.replace(c,"").replace(b,"");d.zoom=1;if(typeof(e)=="number"&&e>=0&&e<1){e*=100;d.filter=g+(g.length?" ":"")+"alpha(opacity="+e+")"}else{d.filter=g}}})}});Ext.dom.Element.override({select:function(a){return Ext.dom.Element.select(a,false,this.dom)}});Ext.define("Ext.dom.CompositeElementLite",{alternateClassName:"Ext.CompositeElementLite",requires:["Ext.dom.Element"],statics:{importElementMethods:function(){var b,c=Ext.dom.Element.prototype,a=this.prototype;for(b in c){if(typeof c[b]=="function"){(function(d){a[d]=a[d]||function(){return this.invoke(d,arguments)}}).call(a,b)}}}},constructor:function(b,a){this.elements=[];this.add(b,a);this.el=new Ext.dom.AbstractElement.Fly()},isComposite:true,getElement:function(a){return this.el.attach(a)},transformElement:function(a){return Ext.getDom(a)},getCount:function(){return this.elements.length},add:function(c,a){var e=this.elements,b,d;if(!c){return this}if(typeof c=="string"){c=Ext.dom.Element.selectorFunction(c,a)}else{if(c.isComposite){c=c.elements}else{if(!Ext.isIterable(c)){c=[c]}}}for(b=0,d=c.length;b-1){c=Ext.getDom(c);if(a){g=this.elements[b];g.parentNode.insertBefore(c,g);Ext.removeNode(g)}Ext.Array.splice(this.elements,b,1,c)}return this},clear:function(){this.elements=[]},addElements:function(d,b){if(!d){return this}if(typeof d=="string"){d=Ext.dom.Element.selectorFunction(d,b)}var c=this.elements,a=d.length,g;for(g=0;g0){for(k=0,o=d.length;k to avoid XSS via location.hash (#9521) + quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, + + // Check if a string has a non-whitespace character in it + rnotwhite = /\S/, + + // Used for trimming whitespace + trimLeft = /^\s+/, + trimRight = /\s+$/, + + // Match a standalone tag + rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, + + // JSON RegExp + rvalidchars = /^[\],:{}\s]*$/, + rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, + rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, + rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, + + // Useragent RegExp + rwebkit = /(webkit)[ \/]([\w.]+)/, + ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/, + rmsie = /(msie) ([\w.]+)/, + rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, + + // Matches dashed string for camelizing + rdashAlpha = /-([a-z]|[0-9])/ig, + rmsPrefix = /^-ms-/, + + // Used by jQuery.camelCase as callback to replace() + fcamelCase = function( all, letter ) { + return ( letter + "" ).toUpperCase(); + }, + + // Keep a UserAgent string for use with jQuery.browser + userAgent = navigator.userAgent, + + // For matching the engine and version of the browser + browserMatch, + + // The deferred used on DOM ready + readyList, + + // The ready event handler + DOMContentLoaded, + + // Save a reference to some core methods + toString = Object.prototype.toString, + hasOwn = Object.prototype.hasOwnProperty, + push = Array.prototype.push, + slice = Array.prototype.slice, + trim = String.prototype.trim, + indexOf = Array.prototype.indexOf, + + // [[Class]] -> type pairs + class2type = {}; + +jQuery.fn = jQuery.prototype = { + constructor: jQuery, + init: function( selector, context, rootjQuery ) { + var match, elem, ret, doc; + + // Handle $(""), $(null), or $(undefined) + if ( !selector ) { + return this; + } + + // Handle $(DOMElement) + if ( selector.nodeType ) { + this.context = this[0] = selector; + this.length = 1; + return this; + } + + // The body element only exists once, optimize finding it + if ( selector === "body" && !context && document.body ) { + this.context = document; + this[0] = document.body; + this.selector = selector; + this.length = 1; + return this; + } + + // Handle HTML strings + if ( typeof selector === "string" ) { + // Are we dealing with HTML string or an ID? + if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { + // Assume that strings that start and end with <> are HTML and skip the regex check + match = [ null, selector, null ]; + + } else { + match = quickExpr.exec( selector ); + } + + // Verify a match, and that no context was specified for #id + if ( match && (match[1] || !context) ) { + + // HANDLE: $(html) -> $(array) + if ( match[1] ) { + context = context instanceof jQuery ? context[0] : context; + doc = ( context ? context.ownerDocument || context : document ); + + // If a single string is passed in and it's a single tag + // just do a createElement and skip the rest + ret = rsingleTag.exec( selector ); + + if ( ret ) { + if ( jQuery.isPlainObject( context ) ) { + selector = [ document.createElement( ret[1] ) ]; + jQuery.fn.attr.call( selector, context, true ); + + } else { + selector = [ doc.createElement( ret[1] ) ]; + } + + } else { + ret = jQuery.buildFragment( [ match[1] ], [ doc ] ); + selector = ( ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment ).childNodes; + } + + return jQuery.merge( this, selector ); + + // HANDLE: $("#id") + } else { + elem = document.getElementById( match[2] ); + + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE and Opera return items + // by name instead of ID + if ( elem.id !== match[2] ) { + return rootjQuery.find( selector ); + } + + // Otherwise, we inject the element directly into the jQuery object + this.length = 1; + this[0] = elem; + } + + this.context = document; + this.selector = selector; + return this; + } + + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return ( context || rootjQuery ).find( selector ); + + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return this.constructor( context ).find( selector ); + } + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( jQuery.isFunction( selector ) ) { + return rootjQuery.ready( selector ); + } + + if ( selector.selector !== undefined ) { + this.selector = selector.selector; + this.context = selector.context; + } + + return jQuery.makeArray( selector, this ); + }, + + // Start with an empty selector + selector: "", + + // The current version of jQuery being used + jquery: "1.7.1", + + // The default length of a jQuery object is 0 + length: 0, + + // The number of elements contained in the matched element set + size: function() { + return this.length; + }, + + toArray: function() { + return slice.call( this, 0 ); + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + return num == null ? + + // Return a 'clean' array + this.toArray() : + + // Return just the object + ( num < 0 ? this[ this.length + num ] : this[ num ] ); + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems, name, selector ) { + // Build a new jQuery matched element set + var ret = this.constructor(); + + if ( jQuery.isArray( elems ) ) { + push.apply( ret, elems ); + + } else { + jQuery.merge( ret, elems ); + } + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + + ret.context = this.context; + + if ( name === "find" ) { + ret.selector = this.selector + ( this.selector ? " " : "" ) + selector; + } else if ( name ) { + ret.selector = this.selector + "." + name + "(" + selector + ")"; + } + + // Return the newly-formed element set + return ret; + }, + + // Execute a callback for every element in the matched set. + // (You can seed the arguments with an array of args, but this is + // only used internally.) + each: function( callback, args ) { + return jQuery.each( this, callback, args ); + }, + + ready: function( fn ) { + // Attach the listeners + jQuery.bindReady(); + + // Add the callback + readyList.add( fn ); + + return this; + }, + + eq: function( i ) { + i = +i; + return i === -1 ? + this.slice( i ) : + this.slice( i, i + 1 ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + slice: function() { + return this.pushStack( slice.apply( this, arguments ), + "slice", slice.call(arguments).join(",") ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map(this, function( elem, i ) { + return callback.call( elem, i, elem ); + })); + }, + + end: function() { + return this.prevObject || this.constructor(null); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: push, + sort: [].sort, + splice: [].splice +}; + +// Give the init function the jQuery prototype for later instantiation +jQuery.fn.init.prototype = jQuery.fn; + +jQuery.extend = jQuery.fn.extend = function() { + var options, name, src, copy, copyIsArray, clone, + target = arguments[0] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !jQuery.isFunction(target) ) { + target = {}; + } + + // extend jQuery itself if only one argument is passed + if ( length === i ) { + target = this; + --i; + } + + for ( ; i < length; i++ ) { + // Only deal with non-null/undefined values + if ( (options = arguments[ i ]) != null ) { + // Extend the base object + for ( name in options ) { + src = target[ name ]; + copy = options[ name ]; + + // Prevent never-ending loop + if ( target === copy ) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { + if ( copyIsArray ) { + copyIsArray = false; + clone = src && jQuery.isArray(src) ? src : []; + + } else { + clone = src && jQuery.isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +jQuery.extend({ + noConflict: function( deep ) { + if ( window.$ === jQuery ) { + window.$ = _$; + } + + if ( deep && window.jQuery === jQuery ) { + window.jQuery = _jQuery; + } + + return jQuery; + }, + + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, + + // A counter to track how many items to wait for before + // the ready event fires. See #6781 + readyWait: 1, + + // Hold (or release) the ready event + holdReady: function( hold ) { + if ( hold ) { + jQuery.readyWait++; + } else { + jQuery.ready( true ); + } + }, + + // Handle when the DOM is ready + ready: function( wait ) { + // Either a released hold or an DOMready/load event and not yet ready + if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) { + // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). + if ( !document.body ) { + return setTimeout( jQuery.ready, 1 ); + } + + // Remember that the DOM is ready + jQuery.isReady = true; + + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } + + // If there are functions bound, to execute + readyList.fireWith( document, [ jQuery ] ); + + // Trigger any bound ready events + if ( jQuery.fn.trigger ) { + jQuery( document ).trigger( "ready" ).off( "ready" ); + } + } + }, + + bindReady: function() { + if ( readyList ) { + return; + } + + readyList = jQuery.Callbacks( "once memory" ); + + // Catch cases where $(document).ready() is called after the + // browser event has already occurred. + if ( document.readyState === "complete" ) { + // Handle it asynchronously to allow scripts the opportunity to delay ready + return setTimeout( jQuery.ready, 1 ); + } + + // Mozilla, Opera and webkit nightlies currently support this event + if ( document.addEventListener ) { + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", jQuery.ready, false ); + + // If IE event model is used + } else if ( document.attachEvent ) { + // ensure firing before onload, + // maybe late but safe also for iframes + document.attachEvent( "onreadystatechange", DOMContentLoaded ); + + // A fallback to window.onload, that will always work + window.attachEvent( "onload", jQuery.ready ); + + // If IE and not a frame + // continually check to see if the document is ready + var toplevel = false; + + try { + toplevel = window.frameElement == null; + } catch(e) {} + + if ( document.documentElement.doScroll && toplevel ) { + doScrollCheck(); + } + } + }, + + // See test/unit/core.js for details concerning isFunction. + // Since version 1.3, DOM methods and functions like alert + // aren't supported. They return false on IE (#2968). + isFunction: function( obj ) { + return jQuery.type(obj) === "function"; + }, + + isArray: Array.isArray || function( obj ) { + return jQuery.type(obj) === "array"; + }, + + // A crude way of determining if an object is a window + isWindow: function( obj ) { + return obj && typeof obj === "object" && "setInterval" in obj; + }, + + isNumeric: function( obj ) { + return !isNaN( parseFloat(obj) ) && isFinite( obj ); + }, + + type: function( obj ) { + return obj == null ? + String( obj ) : + class2type[ toString.call(obj) ] || "object"; + }, + + isPlainObject: function( obj ) { + // Must be an Object. + // Because of IE, we also have to check the presence of the constructor property. + // Make sure that DOM nodes and window objects don't pass through, as well + if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { + return false; + } + + try { + // Not own constructor property must be Object + if ( obj.constructor && + !hasOwn.call(obj, "constructor") && + !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { + return false; + } + } catch ( e ) { + // IE8,9 Will throw exceptions on certain host objects #9897 + return false; + } + + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + + var key; + for ( key in obj ) {} + + return key === undefined || hasOwn.call( obj, key ); + }, + + isEmptyObject: function( obj ) { + for ( var name in obj ) { + return false; + } + return true; + }, + + error: function( msg ) { + throw new Error( msg ); + }, + + parseJSON: function( data ) { + if ( typeof data !== "string" || !data ) { + return null; + } + + // Make sure leading/trailing whitespace is removed (IE can't handle it) + data = jQuery.trim( data ); + + // Attempt to parse using the native JSON parser first + if ( window.JSON && window.JSON.parse ) { + return window.JSON.parse( data ); + } + + // Make sure the incoming data is actual JSON + // Logic borrowed from http://json.org/json2.js + if ( rvalidchars.test( data.replace( rvalidescape, "@" ) + .replace( rvalidtokens, "]" ) + .replace( rvalidbraces, "")) ) { + + return ( new Function( "return " + data ) )(); + + } + jQuery.error( "Invalid JSON: " + data ); + }, + + // Cross-browser xml parsing + parseXML: function( data ) { + var xml, tmp; + try { + if ( window.DOMParser ) { // Standard + tmp = new DOMParser(); + xml = tmp.parseFromString( data , "text/xml" ); + } else { // IE + xml = new ActiveXObject( "Microsoft.XMLDOM" ); + xml.async = "false"; + xml.loadXML( data ); + } + } catch( e ) { + xml = undefined; + } + if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { + jQuery.error( "Invalid XML: " + data ); + } + return xml; + }, + + noop: function() {}, + + // Evaluates a script in a global context + // Workarounds based on findings by Jim Driscoll + // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context + globalEval: function( data ) { + if ( data && rnotwhite.test( data ) ) { + // We use execScript on Internet Explorer + // We use an anonymous function so that context is window + // rather than jQuery in Firefox + ( window.execScript || function( data ) { + window[ "eval" ].call( window, data ); + } )( data ); + } + }, + + // Convert dashed to camelCase; used by the css and data modules + // Microsoft forgot to hump their vendor prefix (#9572) + camelCase: function( string ) { + return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); + }, + + nodeName: function( elem, name ) { + return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); + }, + + // args is for internal usage only + each: function( object, callback, args ) { + var name, i = 0, + length = object.length, + isObj = length === undefined || jQuery.isFunction( object ); + + if ( args ) { + if ( isObj ) { + for ( name in object ) { + if ( callback.apply( object[ name ], args ) === false ) { + break; + } + } + } else { + for ( ; i < length; ) { + if ( callback.apply( object[ i++ ], args ) === false ) { + break; + } + } + } + + // A special, fast, case for the most common use of each + } else { + if ( isObj ) { + for ( name in object ) { + if ( callback.call( object[ name ], name, object[ name ] ) === false ) { + break; + } + } + } else { + for ( ; i < length; ) { + if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) { + break; + } + } + } + } + + return object; + }, + + // Use native String.trim function wherever possible + trim: trim ? + function( text ) { + return text == null ? + "" : + trim.call( text ); + } : + + // Otherwise use our own trimming functionality + function( text ) { + return text == null ? + "" : + text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); + }, + + // results is for internal usage only + makeArray: function( array, results ) { + var ret = results || []; + + if ( array != null ) { + // The window, strings (and functions) also have 'length' + // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 + var type = jQuery.type( array ); + + if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) { + push.call( ret, array ); + } else { + jQuery.merge( ret, array ); + } + } + + return ret; + }, + + inArray: function( elem, array, i ) { + var len; + + if ( array ) { + if ( indexOf ) { + return indexOf.call( array, elem, i ); + } + + len = array.length; + i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; + + for ( ; i < len; i++ ) { + // Skip accessing in sparse arrays + if ( i in array && array[ i ] === elem ) { + return i; + } + } + } + + return -1; + }, + + merge: function( first, second ) { + var i = first.length, + j = 0; + + if ( typeof second.length === "number" ) { + for ( var l = second.length; j < l; j++ ) { + first[ i++ ] = second[ j ]; + } + + } else { + while ( second[j] !== undefined ) { + first[ i++ ] = second[ j++ ]; + } + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, inv ) { + var ret = [], retVal; + inv = !!inv; + + // Go through the array, only saving the items + // that pass the validator function + for ( var i = 0, length = elems.length; i < length; i++ ) { + retVal = !!callback( elems[ i ], i ); + if ( inv !== retVal ) { + ret.push( elems[ i ] ); + } + } + + return ret; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var value, key, ret = [], + i = 0, + length = elems.length, + // jquery objects are treated as arrays + isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; + + // Go through the array, translating each of the items to their + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret[ ret.length ] = value; + } + } + + // Go through every key on the object, + } else { + for ( key in elems ) { + value = callback( elems[ key ], key, arg ); + + if ( value != null ) { + ret[ ret.length ] = value; + } + } + } + + // Flatten any nested arrays + return ret.concat.apply( [], ret ); + }, + + // A global GUID counter for objects + guid: 1, + + // Bind a function to a context, optionally partially applying any + // arguments. + proxy: function( fn, context ) { + if ( typeof context === "string" ) { + var tmp = fn[ context ]; + context = fn; + fn = tmp; + } + + // Quick check to determine if target is callable, in the spec + // this throws a TypeError, but we will just return undefined. + if ( !jQuery.isFunction( fn ) ) { + return undefined; + } + + // Simulated bind + var args = slice.call( arguments, 2 ), + proxy = function() { + return fn.apply( context, args.concat( slice.call( arguments ) ) ); + }; + + // Set the guid of unique handler to the same of original handler, so it can be removed + proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; + + return proxy; + }, + + // Mutifunctional method to get and set values to a collection + // The value/s can optionally be executed if it's a function + access: function( elems, key, value, exec, fn, pass ) { + var length = elems.length; + + // Setting many attributes + if ( typeof key === "object" ) { + for ( var k in key ) { + jQuery.access( elems, k, key[k], exec, fn, value ); + } + return elems; + } + + // Setting one attribute + if ( value !== undefined ) { + // Optionally, function values get executed if exec is true + exec = !pass && exec && jQuery.isFunction(value); + + for ( var i = 0; i < length; i++ ) { + fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); + } + + return elems; + } + + // Getting an attribute + return length ? fn( elems[0], key ) : undefined; + }, + + now: function() { + return ( new Date() ).getTime(); + }, + + // Use of jQuery.browser is frowned upon. + // More details: http://docs.jquery.com/Utilities/jQuery.browser + uaMatch: function( ua ) { + ua = ua.toLowerCase(); + + var match = rwebkit.exec( ua ) || + ropera.exec( ua ) || + rmsie.exec( ua ) || + ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || + []; + + return { browser: match[1] || "", version: match[2] || "0" }; + }, + + sub: function() { + function jQuerySub( selector, context ) { + return new jQuerySub.fn.init( selector, context ); + } + jQuery.extend( true, jQuerySub, this ); + jQuerySub.superclass = this; + jQuerySub.fn = jQuerySub.prototype = this(); + jQuerySub.fn.constructor = jQuerySub; + jQuerySub.sub = this.sub; + jQuerySub.fn.init = function init( selector, context ) { + if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { + context = jQuerySub( context ); + } + + return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); + }; + jQuerySub.fn.init.prototype = jQuerySub.fn; + var rootjQuerySub = jQuerySub(document); + return jQuerySub; + }, + + browser: {} +}); + +// Populate the class2type map +jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); +}); + +browserMatch = jQuery.uaMatch( userAgent ); +if ( browserMatch.browser ) { + jQuery.browser[ browserMatch.browser ] = true; + jQuery.browser.version = browserMatch.version; +} + +// Deprecated, use jQuery.browser.webkit instead +if ( jQuery.browser.webkit ) { + jQuery.browser.safari = true; +} + +// IE doesn't match non-breaking spaces with \s +if ( rnotwhite.test( "\xA0" ) ) { + trimLeft = /^[\s\xA0]+/; + trimRight = /[\s\xA0]+$/; +} + +// All jQuery objects should point back to these +rootjQuery = jQuery(document); + +// Cleanup functions for the document ready method +if ( document.addEventListener ) { + DOMContentLoaded = function() { + document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); + jQuery.ready(); + }; + +} else if ( document.attachEvent ) { + DOMContentLoaded = function() { + // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). + if ( document.readyState === "complete" ) { + document.detachEvent( "onreadystatechange", DOMContentLoaded ); + jQuery.ready(); + } + }; +} + +// The DOM ready check for Internet Explorer +function doScrollCheck() { + if ( jQuery.isReady ) { + return; + } + + try { + // If IE is used, use the trick by Diego Perini + // http://javascript.nwbox.com/IEContentLoaded/ + document.documentElement.doScroll("left"); + } catch(e) { + setTimeout( doScrollCheck, 1 ); + return; + } + + // and execute any waiting functions + jQuery.ready(); +} + +return jQuery; + +})(); + + +// String to Object flags format cache +var flagsCache = {}; + +// Convert String-formatted flags into Object-formatted ones and store in cache +function createFlags( flags ) { + var object = flagsCache[ flags ] = {}, + i, length; + flags = flags.split( /\s+/ ); + for ( i = 0, length = flags.length; i < length; i++ ) { + object[ flags[i] ] = true; + } + return object; +} + +/* + * Create a callback list using the following parameters: + * + * flags: an optional list of space-separated flags that will change how + * the callback list behaves + * + * By default a callback list will act like an event callback list and can be + * "fired" multiple times. + * + * Possible flags: + * + * once: will ensure the callback list can only be fired once (like a Deferred) + * + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) + * + * unique: will ensure a callback can only be added once (no duplicate in the list) + * + * stopOnFalse: interrupt callings when a callback returns false + * + */ +jQuery.Callbacks = function( flags ) { + + // Convert flags from String-formatted to Object-formatted + // (we check in cache first) + flags = flags ? ( flagsCache[ flags ] || createFlags( flags ) ) : {}; + + var // Actual callback list + list = [], + // Stack of fire calls for repeatable lists + stack = [], + // Last fire value (for non-forgettable lists) + memory, + // Flag to know if list is currently firing + firing, + // First callback to fire (used internally by add and fireWith) + firingStart, + // End of the loop when firing + firingLength, + // Index of currently firing callback (modified by remove if needed) + firingIndex, + // Add one or several callbacks to the list + add = function( args ) { + var i, + length, + elem, + type, + actual; + for ( i = 0, length = args.length; i < length; i++ ) { + elem = args[ i ]; + type = jQuery.type( elem ); + if ( type === "array" ) { + // Inspect recursively + add( elem ); + } else if ( type === "function" ) { + // Add if not in unique mode and callback is not in + if ( !flags.unique || !self.has( elem ) ) { + list.push( elem ); + } + } + } + }, + // Fire callbacks + fire = function( context, args ) { + args = args || []; + memory = !flags.memory || [ context, args ]; + firing = true; + firingIndex = firingStart || 0; + firingStart = 0; + firingLength = list.length; + for ( ; list && firingIndex < firingLength; firingIndex++ ) { + if ( list[ firingIndex ].apply( context, args ) === false && flags.stopOnFalse ) { + memory = true; // Mark as halted + break; + } + } + firing = false; + if ( list ) { + if ( !flags.once ) { + if ( stack && stack.length ) { + memory = stack.shift(); + self.fireWith( memory[ 0 ], memory[ 1 ] ); + } + } else if ( memory === true ) { + self.disable(); + } else { + list = []; + } + } + }, + // Actual Callbacks object + self = { + // Add a callback or a collection of callbacks to the list + add: function() { + if ( list ) { + var length = list.length; + add( arguments ); + // Do we need to add the callbacks to the + // current firing batch? + if ( firing ) { + firingLength = list.length; + // With memory, if we're not firing then + // we should call right away, unless previous + // firing was halted (stopOnFalse) + } else if ( memory && memory !== true ) { + firingStart = length; + fire( memory[ 0 ], memory[ 1 ] ); + } + } + return this; + }, + // Remove a callback from the list + remove: function() { + if ( list ) { + var args = arguments, + argIndex = 0, + argLength = args.length; + for ( ; argIndex < argLength ; argIndex++ ) { + for ( var i = 0; i < list.length; i++ ) { + if ( args[ argIndex ] === list[ i ] ) { + // Handle firingIndex and firingLength + if ( firing ) { + if ( i <= firingLength ) { + firingLength--; + if ( i <= firingIndex ) { + firingIndex--; + } + } + } + // Remove the element + list.splice( i--, 1 ); + // If we have some unicity property then + // we only need to do this once + if ( flags.unique ) { + break; + } + } + } + } + } + return this; + }, + // Control if a given callback is in the list + has: function( fn ) { + if ( list ) { + var i = 0, + length = list.length; + for ( ; i < length; i++ ) { + if ( fn === list[ i ] ) { + return true; + } + } + } + return false; + }, + // Remove all callbacks from the list + empty: function() { + list = []; + return this; + }, + // Have the list do nothing anymore + disable: function() { + list = stack = memory = undefined; + return this; + }, + // Is it disabled? + disabled: function() { + return !list; + }, + // Lock the list in its current state + lock: function() { + stack = undefined; + if ( !memory || memory === true ) { + self.disable(); + } + return this; + }, + // Is it locked? + locked: function() { + return !stack; + }, + // Call all callbacks with the given context and arguments + fireWith: function( context, args ) { + if ( stack ) { + if ( firing ) { + if ( !flags.once ) { + stack.push( [ context, args ] ); + } + } else if ( !( flags.once && memory ) ) { + fire( context, args ); + } + } + return this; + }, + // Call all the callbacks with the given arguments + fire: function() { + self.fireWith( this, arguments ); + return this; + }, + // To know if the callbacks have already been called at least once + fired: function() { + return !!memory; + } + }; + + return self; +}; + + + + +var // Static reference to slice + sliceDeferred = [].slice; + +jQuery.extend({ + + Deferred: function( func ) { + var doneList = jQuery.Callbacks( "once memory" ), + failList = jQuery.Callbacks( "once memory" ), + progressList = jQuery.Callbacks( "memory" ), + state = "pending", + lists = { + resolve: doneList, + reject: failList, + notify: progressList + }, + promise = { + done: doneList.add, + fail: failList.add, + progress: progressList.add, + + state: function() { + return state; + }, + + // Deprecated + isResolved: doneList.fired, + isRejected: failList.fired, + + then: function( doneCallbacks, failCallbacks, progressCallbacks ) { + deferred.done( doneCallbacks ).fail( failCallbacks ).progress( progressCallbacks ); + return this; + }, + always: function() { + deferred.done.apply( deferred, arguments ).fail.apply( deferred, arguments ); + return this; + }, + pipe: function( fnDone, fnFail, fnProgress ) { + return jQuery.Deferred(function( newDefer ) { + jQuery.each( { + done: [ fnDone, "resolve" ], + fail: [ fnFail, "reject" ], + progress: [ fnProgress, "notify" ] + }, function( handler, data ) { + var fn = data[ 0 ], + action = data[ 1 ], + returned; + if ( jQuery.isFunction( fn ) ) { + deferred[ handler ](function() { + returned = fn.apply( this, arguments ); + if ( returned && jQuery.isFunction( returned.promise ) ) { + returned.promise().then( newDefer.resolve, newDefer.reject, newDefer.notify ); + } else { + newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] ); + } + }); + } else { + deferred[ handler ]( newDefer[ action ] ); + } + }); + }).promise(); + }, + // Get a promise for this deferred + // If obj is provided, the promise aspect is added to the object + promise: function( obj ) { + if ( obj == null ) { + obj = promise; + } else { + for ( var key in promise ) { + obj[ key ] = promise[ key ]; + } + } + return obj; + } + }, + deferred = promise.promise({}), + key; + + for ( key in lists ) { + deferred[ key ] = lists[ key ].fire; + deferred[ key + "With" ] = lists[ key ].fireWith; + } + + // Handle state + deferred.done( function() { + state = "resolved"; + }, failList.disable, progressList.lock ).fail( function() { + state = "rejected"; + }, doneList.disable, progressList.lock ); + + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); + } + + // All done! + return deferred; + }, + + // Deferred helper + when: function( firstParam ) { + var args = sliceDeferred.call( arguments, 0 ), + i = 0, + length = args.length, + pValues = new Array( length ), + count = length, + pCount = length, + deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ? + firstParam : + jQuery.Deferred(), + promise = deferred.promise(); + function resolveFunc( i ) { + return function( value ) { + args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; + if ( !( --count ) ) { + deferred.resolveWith( deferred, args ); + } + }; + } + function progressFunc( i ) { + return function( value ) { + pValues[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; + deferred.notifyWith( promise, pValues ); + }; + } + if ( length > 1 ) { + for ( ; i < length; i++ ) { + if ( args[ i ] && args[ i ].promise && jQuery.isFunction( args[ i ].promise ) ) { + args[ i ].promise().then( resolveFunc(i), deferred.reject, progressFunc(i) ); + } else { + --count; + } + } + if ( !count ) { + deferred.resolveWith( deferred, args ); + } + } else if ( deferred !== firstParam ) { + deferred.resolveWith( deferred, length ? [ firstParam ] : [] ); + } + return promise; + } +}); + + + + +jQuery.support = (function() { + + var support, + all, + a, + select, + opt, + input, + marginDiv, + fragment, + tds, + events, + eventName, + i, + isSupported, + div = document.createElement( "div" ), + documentElement = document.documentElement; + + // Preliminary tests + div.setAttribute("className", "t"); + div.innerHTML = "
    a"; + + all = div.getElementsByTagName( "*" ); + a = div.getElementsByTagName( "a" )[ 0 ]; + + // Can't get basic test support + if ( !all || !all.length || !a ) { + return {}; + } + + // First batch of supports tests + select = document.createElement( "select" ); + opt = select.appendChild( document.createElement("option") ); + input = div.getElementsByTagName( "input" )[ 0 ]; + + support = { + // IE strips leading whitespace when .innerHTML is used + leadingWhitespace: ( div.firstChild.nodeType === 3 ), + + // Make sure that tbody elements aren't automatically inserted + // IE will insert them into empty tables + tbody: !div.getElementsByTagName("tbody").length, + + // Make sure that link elements get serialized correctly by innerHTML + // This requires a wrapper element in IE + htmlSerialize: !!div.getElementsByTagName("link").length, + + // Get the style information from getAttribute + // (IE uses .cssText instead) + style: /top/.test( a.getAttribute("style") ), + + // Make sure that URLs aren't manipulated + // (IE normalizes it by default) + hrefNormalized: ( a.getAttribute("href") === "/a" ), + + // Make sure that element opacity exists + // (IE uses filter instead) + // Use a regex to work around a WebKit issue. See #5145 + opacity: /^0.55/.test( a.style.opacity ), + + // Verify style float existence + // (IE uses styleFloat instead of cssFloat) + cssFloat: !!a.style.cssFloat, + + // Make sure that if no value is specified for a checkbox + // that it defaults to "on". + // (WebKit defaults to "" instead) + checkOn: ( input.value === "on" ), + + // Make sure that a selected-by-default option has a working selected property. + // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) + optSelected: opt.selected, + + // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) + getSetAttribute: div.className !== "t", + + // Tests for enctype support on a form(#6743) + enctype: !!document.createElement("form").enctype, + + // Makes sure cloning an html5 element does not cause problems + // Where outerHTML is undefined, this still works + html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav>", + + // Will be defined later + submitBubbles: true, + changeBubbles: true, + focusinBubbles: false, + deleteExpando: true, + noCloneEvent: true, + inlineBlockNeedsLayout: false, + shrinkWrapBlocks: false, + reliableMarginRight: true + }; + + // Make sure checked status is properly cloned + input.checked = true; + support.noCloneChecked = input.cloneNode( true ).checked; + + // Make sure that the options inside disabled selects aren't marked as disabled + // (WebKit marks them as disabled) + select.disabled = true; + support.optDisabled = !opt.disabled; + + // Test to see if it's possible to delete an expando from an element + // Fails in Internet Explorer + try { + delete div.test; + } catch( e ) { + support.deleteExpando = false; + } + + if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { + div.attachEvent( "onclick", function() { + // Cloning a node shouldn't copy over any + // bound event handlers (IE does this) + support.noCloneEvent = false; + }); + div.cloneNode( true ).fireEvent( "onclick" ); + } + + // Check if a radio maintains its value + // after being appended to the DOM + input = document.createElement("input"); + input.value = "t"; + input.setAttribute("type", "radio"); + support.radioValue = input.value === "t"; + + input.setAttribute("checked", "checked"); + div.appendChild( input ); + fragment = document.createDocumentFragment(); + fragment.appendChild( div.lastChild ); + + // WebKit doesn't clone checked state correctly in fragments + support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; + + // Check if a disconnected checkbox will retain its checked + // value of true after appended to the DOM (IE6/7) + support.appendChecked = input.checked; + + fragment.removeChild( input ); + fragment.appendChild( div ); + + div.innerHTML = ""; + + // Check if div with explicit width and no margin-right incorrectly + // gets computed margin-right based on width of container. For more + // info see bug #3333 + // Fails in WebKit before Feb 2011 nightlies + // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right + if ( window.getComputedStyle ) { + marginDiv = document.createElement( "div" ); + marginDiv.style.width = "0"; + marginDiv.style.marginRight = "0"; + div.style.width = "2px"; + div.appendChild( marginDiv ); + support.reliableMarginRight = + ( parseInt( ( window.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0; + } + + // Technique from Juriy Zaytsev + // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/ + // We only care about the case where non-standard event systems + // are used, namely in IE. Short-circuiting here helps us to + // avoid an eval call (in setAttribute) which can cause CSP + // to go haywire. See: https://developer.mozilla.org/en/Security/CSP + if ( div.attachEvent ) { + for( i in { + submit: 1, + change: 1, + focusin: 1 + }) { + eventName = "on" + i; + isSupported = ( eventName in div ); + if ( !isSupported ) { + div.setAttribute( eventName, "return;" ); + isSupported = ( typeof div[ eventName ] === "function" ); + } + support[ i + "Bubbles" ] = isSupported; + } + } + + fragment.removeChild( div ); + + // Null elements to avoid leaks in IE + fragment = select = opt = marginDiv = div = input = null; + + // Run tests that need a body at doc ready + jQuery(function() { + var container, outer, inner, table, td, offsetSupport, + conMarginTop, ptlm, vb, style, html, + body = document.getElementsByTagName("body")[0]; + + if ( !body ) { + // Return for frameset docs that don't have a body + return; + } + + conMarginTop = 1; + ptlm = "position:absolute;top:0;left:0;width:1px;height:1px;margin:0;"; + vb = "visibility:hidden;border:0;"; + style = "style='" + ptlm + "border:5px solid #000;padding:0;'"; + html = "
    " + + "" + + "
    "; + + container = document.createElement("div"); + container.style.cssText = vb + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px"; + body.insertBefore( container, body.firstChild ); + + // Construct the test element + div = document.createElement("div"); + container.appendChild( div ); + + // Check if table cells still have offsetWidth/Height when they are set + // to display:none and there are still other visible table cells in a + // table row; if so, offsetWidth/Height are not reliable for use when + // determining if an element has been hidden directly using + // display:none (it is still safe to use offsets if a parent element is + // hidden; don safety goggles and see bug #4512 for more information). + // (only IE 8 fails this test) + div.innerHTML = "
    t
    "; + tds = div.getElementsByTagName( "td" ); + isSupported = ( tds[ 0 ].offsetHeight === 0 ); + + tds[ 0 ].style.display = ""; + tds[ 1 ].style.display = "none"; + + // Check if empty table cells still have offsetWidth/Height + // (IE <= 8 fail this test) + support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); + + // Figure out if the W3C box model works as expected + div.innerHTML = ""; + div.style.width = div.style.paddingLeft = "1px"; + jQuery.boxModel = support.boxModel = div.offsetWidth === 2; + + if ( typeof div.style.zoom !== "undefined" ) { + // Check if natively block-level elements act like inline-block + // elements when setting their display to 'inline' and giving + // them layout + // (IE < 8 does this) + div.style.display = "inline"; + div.style.zoom = 1; + support.inlineBlockNeedsLayout = ( div.offsetWidth === 2 ); + + // Check if elements with layout shrink-wrap their children + // (IE 6 does this) + div.style.display = ""; + div.innerHTML = "
    "; + support.shrinkWrapBlocks = ( div.offsetWidth !== 2 ); + } + + div.style.cssText = ptlm + vb; + div.innerHTML = html; + + outer = div.firstChild; + inner = outer.firstChild; + td = outer.nextSibling.firstChild.firstChild; + + offsetSupport = { + doesNotAddBorder: ( inner.offsetTop !== 5 ), + doesAddBorderForTableAndCells: ( td.offsetTop === 5 ) + }; + + inner.style.position = "fixed"; + inner.style.top = "20px"; + + // safari subtracts parent border width here which is 5px + offsetSupport.fixedPosition = ( inner.offsetTop === 20 || inner.offsetTop === 15 ); + inner.style.position = inner.style.top = ""; + + outer.style.overflow = "hidden"; + outer.style.position = "relative"; + + offsetSupport.subtractsBorderForOverflowNotVisible = ( inner.offsetTop === -5 ); + offsetSupport.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== conMarginTop ); + + body.removeChild( container ); + div = container = null; + + jQuery.extend( support, offsetSupport ); + }); + + return support; +})(); + + + + +var rbrace = /^(?:\{.*\}|\[.*\])$/, + rmultiDash = /([A-Z])/g; + +jQuery.extend({ + cache: {}, + + // Please use with caution + uuid: 0, + + // Unique for each copy of jQuery on the page + // Non-digits removed to match rinlinejQuery + expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), + + // The following elements throw uncatchable exceptions if you + // attempt to add expando properties to them. + noData: { + "embed": true, + // Ban all objects except for Flash (which handle expandos) + "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", + "applet": true + }, + + hasData: function( elem ) { + elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; + return !!elem && !isEmptyDataObject( elem ); + }, + + data: function( elem, name, data, pvt /* Internal Use Only */ ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var privateCache, thisCache, ret, + internalKey = jQuery.expando, + getByName = typeof name === "string", + + // We have to handle DOM nodes and JS objects differently because IE6-7 + // can't GC object references properly across the DOM-JS boundary + isNode = elem.nodeType, + + // Only DOM nodes need the global jQuery cache; JS object data is + // attached directly to the object so GC can occur automatically + cache = isNode ? jQuery.cache : elem, + + // Only defining an ID for JS objects if its cache already exists allows + // the code to shortcut on the same path as a DOM node with no cache + id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey, + isEvents = name === "events"; + + // Avoid doing any more work than we need to when trying to get data on an + // object that has no data at all + if ( (!id || !cache[id] || (!isEvents && !pvt && !cache[id].data)) && getByName && data === undefined ) { + return; + } + + if ( !id ) { + // Only DOM nodes need a new unique ID for each element since their data + // ends up in the global cache + if ( isNode ) { + elem[ internalKey ] = id = ++jQuery.uuid; + } else { + id = internalKey; + } + } + + if ( !cache[ id ] ) { + cache[ id ] = {}; + + // Avoids exposing jQuery metadata on plain JS objects when the object + // is serialized using JSON.stringify + if ( !isNode ) { + cache[ id ].toJSON = jQuery.noop; + } + } + + // An object can be passed to jQuery.data instead of a key/value pair; this gets + // shallow copied over onto the existing cache + if ( typeof name === "object" || typeof name === "function" ) { + if ( pvt ) { + cache[ id ] = jQuery.extend( cache[ id ], name ); + } else { + cache[ id ].data = jQuery.extend( cache[ id ].data, name ); + } + } + + privateCache = thisCache = cache[ id ]; + + // jQuery data() is stored in a separate object inside the object's internal data + // cache in order to avoid key collisions between internal data and user-defined + // data. + if ( !pvt ) { + if ( !thisCache.data ) { + thisCache.data = {}; + } + + thisCache = thisCache.data; + } + + if ( data !== undefined ) { + thisCache[ jQuery.camelCase( name ) ] = data; + } + + // Users should not attempt to inspect the internal events object using jQuery.data, + // it is undocumented and subject to change. But does anyone listen? No. + if ( isEvents && !thisCache[ name ] ) { + return privateCache.events; + } + + // Check for both converted-to-camel and non-converted data property names + // If a data property was specified + if ( getByName ) { + + // First Try to find as-is property data + ret = thisCache[ name ]; + + // Test for null|undefined property data + if ( ret == null ) { + + // Try to find the camelCased property + ret = thisCache[ jQuery.camelCase( name ) ]; + } + } else { + ret = thisCache; + } + + return ret; + }, + + removeData: function( elem, name, pvt /* Internal Use Only */ ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var thisCache, i, l, + + // Reference to internal data cache key + internalKey = jQuery.expando, + + isNode = elem.nodeType, + + // See jQuery.data for more information + cache = isNode ? jQuery.cache : elem, + + // See jQuery.data for more information + id = isNode ? elem[ internalKey ] : internalKey; + + // If there is already no cache entry for this object, there is no + // purpose in continuing + if ( !cache[ id ] ) { + return; + } + + if ( name ) { + + thisCache = pvt ? cache[ id ] : cache[ id ].data; + + if ( thisCache ) { + + // Support array or space separated string names for data keys + if ( !jQuery.isArray( name ) ) { + + // try the string as a key before any manipulation + if ( name in thisCache ) { + name = [ name ]; + } else { + + // split the camel cased version by spaces unless a key with the spaces exists + name = jQuery.camelCase( name ); + if ( name in thisCache ) { + name = [ name ]; + } else { + name = name.split( " " ); + } + } + } + + for ( i = 0, l = name.length; i < l; i++ ) { + delete thisCache[ name[i] ]; + } + + // If there is no data left in the cache, we want to continue + // and let the cache object itself get destroyed + if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { + return; + } + } + } + + // See jQuery.data for more information + if ( !pvt ) { + delete cache[ id ].data; + + // Don't destroy the parent cache unless the internal data object + // had been the only thing left in it + if ( !isEmptyDataObject(cache[ id ]) ) { + return; + } + } + + // Browsers that fail expando deletion also refuse to delete expandos on + // the window, but it will allow it on all other JS objects; other browsers + // don't care + // Ensure that `cache` is not a window object #10080 + if ( jQuery.support.deleteExpando || !cache.setInterval ) { + delete cache[ id ]; + } else { + cache[ id ] = null; + } + + // We destroyed the cache and need to eliminate the expando on the node to avoid + // false lookups in the cache for entries that no longer exist + if ( isNode ) { + // IE does not allow us to delete expando properties from nodes, + // nor does it have a removeAttribute function on Document nodes; + // we must handle all of these cases + if ( jQuery.support.deleteExpando ) { + delete elem[ internalKey ]; + } else if ( elem.removeAttribute ) { + elem.removeAttribute( internalKey ); + } else { + elem[ internalKey ] = null; + } + } + }, + + // For internal use only. + _data: function( elem, name, data ) { + return jQuery.data( elem, name, data, true ); + }, + + // A method for determining if a DOM node can handle the data expando + acceptData: function( elem ) { + if ( elem.nodeName ) { + var match = jQuery.noData[ elem.nodeName.toLowerCase() ]; + + if ( match ) { + return !(match === true || elem.getAttribute("classid") !== match); + } + } + + return true; + } +}); + +jQuery.fn.extend({ + data: function( key, value ) { + var parts, attr, name, + data = null; + + if ( typeof key === "undefined" ) { + if ( this.length ) { + data = jQuery.data( this[0] ); + + if ( this[0].nodeType === 1 && !jQuery._data( this[0], "parsedAttrs" ) ) { + attr = this[0].attributes; + for ( var i = 0, l = attr.length; i < l; i++ ) { + name = attr[i].name; + + if ( name.indexOf( "data-" ) === 0 ) { + name = jQuery.camelCase( name.substring(5) ); + + dataAttr( this[0], name, data[ name ] ); + } + } + jQuery._data( this[0], "parsedAttrs", true ); + } + } + + return data; + + } else if ( typeof key === "object" ) { + return this.each(function() { + jQuery.data( this, key ); + }); + } + + parts = key.split("."); + parts[1] = parts[1] ? "." + parts[1] : ""; + + if ( value === undefined ) { + data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); + + // Try to fetch any internally stored data first + if ( data === undefined && this.length ) { + data = jQuery.data( this[0], key ); + data = dataAttr( this[0], key, data ); + } + + return data === undefined && parts[1] ? + this.data( parts[0] ) : + data; + + } else { + return this.each(function() { + var self = jQuery( this ), + args = [ parts[0], value ]; + + self.triggerHandler( "setData" + parts[1] + "!", args ); + jQuery.data( this, key, value ); + self.triggerHandler( "changeData" + parts[1] + "!", args ); + }); + } + }, + + removeData: function( key ) { + return this.each(function() { + jQuery.removeData( this, key ); + }); + } +}); + +function dataAttr( elem, key, data ) { + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { + + var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); + + data = elem.getAttribute( name ); + + if ( typeof data === "string" ) { + try { + data = data === "true" ? true : + data === "false" ? false : + data === "null" ? null : + jQuery.isNumeric( data ) ? parseFloat( data ) : + rbrace.test( data ) ? jQuery.parseJSON( data ) : + data; + } catch( e ) {} + + // Make sure we set the data so it isn't changed later + jQuery.data( elem, key, data ); + + } else { + data = undefined; + } + } + + return data; +} + +// checks a cache object for emptiness +function isEmptyDataObject( obj ) { + for ( var name in obj ) { + + // if the public data object is empty, the private is still empty + if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { + continue; + } + if ( name !== "toJSON" ) { + return false; + } + } + + return true; +} + + + + +function handleQueueMarkDefer( elem, type, src ) { + var deferDataKey = type + "defer", + queueDataKey = type + "queue", + markDataKey = type + "mark", + defer = jQuery._data( elem, deferDataKey ); + if ( defer && + ( src === "queue" || !jQuery._data(elem, queueDataKey) ) && + ( src === "mark" || !jQuery._data(elem, markDataKey) ) ) { + // Give room for hard-coded callbacks to fire first + // and eventually mark/queue something else on the element + setTimeout( function() { + if ( !jQuery._data( elem, queueDataKey ) && + !jQuery._data( elem, markDataKey ) ) { + jQuery.removeData( elem, deferDataKey, true ); + defer.fire(); + } + }, 0 ); + } +} + +jQuery.extend({ + + _mark: function( elem, type ) { + if ( elem ) { + type = ( type || "fx" ) + "mark"; + jQuery._data( elem, type, (jQuery._data( elem, type ) || 0) + 1 ); + } + }, + + _unmark: function( force, elem, type ) { + if ( force !== true ) { + type = elem; + elem = force; + force = false; + } + if ( elem ) { + type = type || "fx"; + var key = type + "mark", + count = force ? 0 : ( (jQuery._data( elem, key ) || 1) - 1 ); + if ( count ) { + jQuery._data( elem, key, count ); + } else { + jQuery.removeData( elem, key, true ); + handleQueueMarkDefer( elem, type, "mark" ); + } + } + }, + + queue: function( elem, type, data ) { + var q; + if ( elem ) { + type = ( type || "fx" ) + "queue"; + q = jQuery._data( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( data ) { + if ( !q || jQuery.isArray(data) ) { + q = jQuery._data( elem, type, jQuery.makeArray(data) ); + } else { + q.push( data ); + } + } + return q || []; + } + }, + + dequeue: function( elem, type ) { + type = type || "fx"; + + var queue = jQuery.queue( elem, type ), + fn = queue.shift(), + hooks = {}; + + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + } + + if ( fn ) { + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift( "inprogress" ); + } + + jQuery._data( elem, type + ".run", hooks ); + fn.call( elem, function() { + jQuery.dequeue( elem, type ); + }, hooks ); + } + + if ( !queue.length ) { + jQuery.removeData( elem, type + "queue " + type + ".run", true ); + handleQueueMarkDefer( elem, type, "queue" ); + } + } +}); + +jQuery.fn.extend({ + queue: function( type, data ) { + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + } + + if ( data === undefined ) { + return jQuery.queue( this[0], type ); + } + return this.each(function() { + var queue = jQuery.queue( this, type, data ); + + if ( type === "fx" && queue[0] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + }); + }, + dequeue: function( type ) { + return this.each(function() { + jQuery.dequeue( this, type ); + }); + }, + // Based off of the plugin by Clint Helfers, with permission. + // http://blindsignals.com/index.php/2009/07/jquery-delay/ + delay: function( time, type ) { + time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; + type = type || "fx"; + + return this.queue( type, function( next, hooks ) { + var timeout = setTimeout( next, time ); + hooks.stop = function() { + clearTimeout( timeout ); + }; + }); + }, + clearQueue: function( type ) { + return this.queue( type || "fx", [] ); + }, + // Get a promise resolved when queues of a certain type + // are emptied (fx is the type by default) + promise: function( type, object ) { + if ( typeof type !== "string" ) { + object = type; + type = undefined; + } + type = type || "fx"; + var defer = jQuery.Deferred(), + elements = this, + i = elements.length, + count = 1, + deferDataKey = type + "defer", + queueDataKey = type + "queue", + markDataKey = type + "mark", + tmp; + function resolve() { + if ( !( --count ) ) { + defer.resolveWith( elements, [ elements ] ); + } + } + while( i-- ) { + if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) || + ( jQuery.data( elements[ i ], queueDataKey, undefined, true ) || + jQuery.data( elements[ i ], markDataKey, undefined, true ) ) && + jQuery.data( elements[ i ], deferDataKey, jQuery.Callbacks( "once memory" ), true ) )) { + count++; + tmp.add( resolve ); + } + } + resolve(); + return defer.promise(); + } +}); + + + + +var rclass = /[\n\t\r]/g, + rspace = /\s+/, + rreturn = /\r/g, + rtype = /^(?:button|input)$/i, + rfocusable = /^(?:button|input|object|select|textarea)$/i, + rclickable = /^a(?:rea)?$/i, + rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, + getSetAttribute = jQuery.support.getSetAttribute, + nodeHook, boolHook, fixSpecified; + +jQuery.fn.extend({ + attr: function( name, value ) { + return jQuery.access( this, name, value, true, jQuery.attr ); + }, + + removeAttr: function( name ) { + return this.each(function() { + jQuery.removeAttr( this, name ); + }); + }, + + prop: function( name, value ) { + return jQuery.access( this, name, value, true, jQuery.prop ); + }, + + removeProp: function( name ) { + name = jQuery.propFix[ name ] || name; + return this.each(function() { + // try/catch handles cases where IE balks (such as removing a property on window) + try { + this[ name ] = undefined; + delete this[ name ]; + } catch( e ) {} + }); + }, + + addClass: function( value ) { + var classNames, i, l, elem, + setClass, c, cl; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( j ) { + jQuery( this ).addClass( value.call(this, j, this.className) ); + }); + } + + if ( value && typeof value === "string" ) { + classNames = value.split( rspace ); + + for ( i = 0, l = this.length; i < l; i++ ) { + elem = this[ i ]; + + if ( elem.nodeType === 1 ) { + if ( !elem.className && classNames.length === 1 ) { + elem.className = value; + + } else { + setClass = " " + elem.className + " "; + + for ( c = 0, cl = classNames.length; c < cl; c++ ) { + if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) { + setClass += classNames[ c ] + " "; + } + } + elem.className = jQuery.trim( setClass ); + } + } + } + } + + return this; + }, + + removeClass: function( value ) { + var classNames, i, l, elem, className, c, cl; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( j ) { + jQuery( this ).removeClass( value.call(this, j, this.className) ); + }); + } + + if ( (value && typeof value === "string") || value === undefined ) { + classNames = ( value || "" ).split( rspace ); + + for ( i = 0, l = this.length; i < l; i++ ) { + elem = this[ i ]; + + if ( elem.nodeType === 1 && elem.className ) { + if ( value ) { + className = (" " + elem.className + " ").replace( rclass, " " ); + for ( c = 0, cl = classNames.length; c < cl; c++ ) { + className = className.replace(" " + classNames[ c ] + " ", " "); + } + elem.className = jQuery.trim( className ); + + } else { + elem.className = ""; + } + } + } + } + + return this; + }, + + toggleClass: function( value, stateVal ) { + var type = typeof value, + isBool = typeof stateVal === "boolean"; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( i ) { + jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); + }); + } + + return this.each(function() { + if ( type === "string" ) { + // toggle individual class names + var className, + i = 0, + self = jQuery( this ), + state = stateVal, + classNames = value.split( rspace ); + + while ( (className = classNames[ i++ ]) ) { + // check each className given, space seperated list + state = isBool ? state : !self.hasClass( className ); + self[ state ? "addClass" : "removeClass" ]( className ); + } + + } else if ( type === "undefined" || type === "boolean" ) { + if ( this.className ) { + // store className if set + jQuery._data( this, "__className__", this.className ); + } + + // toggle whole className + this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; + } + }); + }, + + hasClass: function( selector ) { + var className = " " + selector + " ", + i = 0, + l = this.length; + for ( ; i < l; i++ ) { + if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { + return true; + } + } + + return false; + }, + + val: function( value ) { + var hooks, ret, isFunction, + elem = this[0]; + + if ( !arguments.length ) { + if ( elem ) { + hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ]; + + if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { + return ret; + } + + ret = elem.value; + + return typeof ret === "string" ? + // handle most common string cases + ret.replace(rreturn, "") : + // handle cases where value is null/undef or number + ret == null ? "" : ret; + } + + return; + } + + isFunction = jQuery.isFunction( value ); + + return this.each(function( i ) { + var self = jQuery(this), val; + + if ( this.nodeType !== 1 ) { + return; + } + + if ( isFunction ) { + val = value.call( this, i, self.val() ); + } else { + val = value; + } + + // Treat null/undefined as ""; convert numbers to string + if ( val == null ) { + val = ""; + } else if ( typeof val === "number" ) { + val += ""; + } else if ( jQuery.isArray( val ) ) { + val = jQuery.map(val, function ( value ) { + return value == null ? "" : value + ""; + }); + } + + hooks = jQuery.valHooks[ this.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ]; + + // If set returns undefined, fall back to normal setting + if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { + this.value = val; + } + }); + } +}); + +jQuery.extend({ + valHooks: { + option: { + get: function( elem ) { + // attributes.value is undefined in Blackberry 4.7 but + // uses .value. See #6932 + var val = elem.attributes.value; + return !val || val.specified ? elem.value : elem.text; + } + }, + select: { + get: function( elem ) { + var value, i, max, option, + index = elem.selectedIndex, + values = [], + options = elem.options, + one = elem.type === "select-one"; + + // Nothing was selected + if ( index < 0 ) { + return null; + } + + // Loop through all the selected options + i = one ? index : 0; + max = one ? index + 1 : options.length; + for ( ; i < max; i++ ) { + option = options[ i ]; + + // Don't return options that are disabled or in a disabled optgroup + if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && + (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) { + + // Get the specific value for the option + value = jQuery( option ).val(); + + // We don't need an array for one selects + if ( one ) { + return value; + } + + // Multi-Selects return an array + values.push( value ); + } + } + + // Fixes Bug #2551 -- select.val() broken in IE after form.reset() + if ( one && !values.length && options.length ) { + return jQuery( options[ index ] ).val(); + } + + return values; + }, + + set: function( elem, value ) { + var values = jQuery.makeArray( value ); + + jQuery(elem).find("option").each(function() { + this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; + }); + + if ( !values.length ) { + elem.selectedIndex = -1; + } + return values; + } + } + }, + + attrFn: { + val: true, + css: true, + html: true, + text: true, + data: true, + width: true, + height: true, + offset: true + }, + + attr: function( elem, name, value, pass ) { + var ret, hooks, notxml, + nType = elem.nodeType; + + // don't get/set attributes on text, comment and attribute nodes + if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + if ( pass && name in jQuery.attrFn ) { + return jQuery( elem )[ name ]( value ); + } + + // Fallback to prop when attributes are not supported + if ( typeof elem.getAttribute === "undefined" ) { + return jQuery.prop( elem, name, value ); + } + + notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); + + // All attributes are lowercase + // Grab necessary hook if one is defined + if ( notxml ) { + name = name.toLowerCase(); + hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); + } + + if ( value !== undefined ) { + + if ( value === null ) { + jQuery.removeAttr( elem, name ); + return; + + } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { + return ret; + + } else { + elem.setAttribute( name, "" + value ); + return value; + } + + } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { + return ret; + + } else { + + ret = elem.getAttribute( name ); + + // Non-existent attributes return null, we normalize to undefined + return ret === null ? + undefined : + ret; + } + }, + + removeAttr: function( elem, value ) { + var propName, attrNames, name, l, + i = 0; + + if ( value && elem.nodeType === 1 ) { + attrNames = value.toLowerCase().split( rspace ); + l = attrNames.length; + + for ( ; i < l; i++ ) { + name = attrNames[ i ]; + + if ( name ) { + propName = jQuery.propFix[ name ] || name; + + // See #9699 for explanation of this approach (setting first, then removal) + jQuery.attr( elem, name, "" ); + elem.removeAttribute( getSetAttribute ? name : propName ); + + // Set corresponding property to false for boolean attributes + if ( rboolean.test( name ) && propName in elem ) { + elem[ propName ] = false; + } + } + } + } + }, + + attrHooks: { + type: { + set: function( elem, value ) { + // We can't allow the type property to be changed (since it causes problems in IE) + if ( rtype.test( elem.nodeName ) && elem.parentNode ) { + jQuery.error( "type property can't be changed" ); + } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { + // Setting the type on a radio button after the value resets the value in IE6-9 + // Reset value to it's default in case type is set after value + // This is for element creation + var val = elem.value; + elem.setAttribute( "type", value ); + if ( val ) { + elem.value = val; + } + return value; + } + } + }, + // Use the value property for back compat + // Use the nodeHook for button elements in IE6/7 (#1954) + value: { + get: function( elem, name ) { + if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { + return nodeHook.get( elem, name ); + } + return name in elem ? + elem.value : + null; + }, + set: function( elem, value, name ) { + if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { + return nodeHook.set( elem, value, name ); + } + // Does not return so that setAttribute is also used + elem.value = value; + } + } + }, + + propFix: { + tabindex: "tabIndex", + readonly: "readOnly", + "for": "htmlFor", + "class": "className", + maxlength: "maxLength", + cellspacing: "cellSpacing", + cellpadding: "cellPadding", + rowspan: "rowSpan", + colspan: "colSpan", + usemap: "useMap", + frameborder: "frameBorder", + contenteditable: "contentEditable" + }, + + prop: function( elem, name, value ) { + var ret, hooks, notxml, + nType = elem.nodeType; + + // don't get/set properties on text, comment and attribute nodes + if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); + + if ( notxml ) { + // Fix name and attach hooks + name = jQuery.propFix[ name ] || name; + hooks = jQuery.propHooks[ name ]; + } + + if ( value !== undefined ) { + if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { + return ret; + + } else { + return ( elem[ name ] = value ); + } + + } else { + if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { + return ret; + + } else { + return elem[ name ]; + } + } + }, + + propHooks: { + tabIndex: { + get: function( elem ) { + // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set + // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ + var attributeNode = elem.getAttributeNode("tabindex"); + + return attributeNode && attributeNode.specified ? + parseInt( attributeNode.value, 10 ) : + rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? + 0 : + undefined; + } + } + } +}); + +// Add the tabIndex propHook to attrHooks for back-compat (different case is intentional) +jQuery.attrHooks.tabindex = jQuery.propHooks.tabIndex; + +// Hook for boolean attributes +boolHook = { + get: function( elem, name ) { + // Align boolean attributes with corresponding properties + // Fall back to attribute presence where some booleans are not supported + var attrNode, + property = jQuery.prop( elem, name ); + return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ? + name.toLowerCase() : + undefined; + }, + set: function( elem, value, name ) { + var propName; + if ( value === false ) { + // Remove boolean attributes when set to false + jQuery.removeAttr( elem, name ); + } else { + // value is true since we know at this point it's type boolean and not false + // Set boolean attributes to the same name and set the DOM property + propName = jQuery.propFix[ name ] || name; + if ( propName in elem ) { + // Only set the IDL specifically if it already exists on the element + elem[ propName ] = true; + } + + elem.setAttribute( name, name.toLowerCase() ); + } + return name; + } +}; + +// IE6/7 do not support getting/setting some attributes with get/setAttribute +if ( !getSetAttribute ) { + + fixSpecified = { + name: true, + id: true + }; + + // Use this for any attribute in IE6/7 + // This fixes almost every IE6/7 issue + nodeHook = jQuery.valHooks.button = { + get: function( elem, name ) { + var ret; + ret = elem.getAttributeNode( name ); + return ret && ( fixSpecified[ name ] ? ret.nodeValue !== "" : ret.specified ) ? + ret.nodeValue : + undefined; + }, + set: function( elem, value, name ) { + // Set the existing or create a new attribute node + var ret = elem.getAttributeNode( name ); + if ( !ret ) { + ret = document.createAttribute( name ); + elem.setAttributeNode( ret ); + } + return ( ret.nodeValue = value + "" ); + } + }; + + // Apply the nodeHook to tabindex + jQuery.attrHooks.tabindex.set = nodeHook.set; + + // Set width and height to auto instead of 0 on empty string( Bug #8150 ) + // This is for removals + jQuery.each([ "width", "height" ], function( i, name ) { + jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { + set: function( elem, value ) { + if ( value === "" ) { + elem.setAttribute( name, "auto" ); + return value; + } + } + }); + }); + + // Set contenteditable to false on removals(#10429) + // Setting to empty string throws an error as an invalid value + jQuery.attrHooks.contenteditable = { + get: nodeHook.get, + set: function( elem, value, name ) { + if ( value === "" ) { + value = "false"; + } + nodeHook.set( elem, value, name ); + } + }; +} + + +// Some attributes require a special call on IE +if ( !jQuery.support.hrefNormalized ) { + jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { + jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { + get: function( elem ) { + var ret = elem.getAttribute( name, 2 ); + return ret === null ? undefined : ret; + } + }); + }); +} + +if ( !jQuery.support.style ) { + jQuery.attrHooks.style = { + get: function( elem ) { + // Return undefined in the case of empty string + // Normalize to lowercase since IE uppercases css property names + return elem.style.cssText.toLowerCase() || undefined; + }, + set: function( elem, value ) { + return ( elem.style.cssText = "" + value ); + } + }; +} + +// Safari mis-reports the default selected property of an option +// Accessing the parent's selectedIndex property fixes it +if ( !jQuery.support.optSelected ) { + jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { + get: function( elem ) { + var parent = elem.parentNode; + + if ( parent ) { + parent.selectedIndex; + + // Make sure that it also works with optgroups, see #5701 + if ( parent.parentNode ) { + parent.parentNode.selectedIndex; + } + } + return null; + } + }); +} + +// IE6/7 call enctype encoding +if ( !jQuery.support.enctype ) { + jQuery.propFix.enctype = "encoding"; +} + +// Radios and checkboxes getter/setter +if ( !jQuery.support.checkOn ) { + jQuery.each([ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = { + get: function( elem ) { + // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified + return elem.getAttribute("value") === null ? "on" : elem.value; + } + }; + }); +} +jQuery.each([ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { + set: function( elem, value ) { + if ( jQuery.isArray( value ) ) { + return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); + } + } + }); +}); + + + + +var rformElems = /^(?:textarea|input|select)$/i, + rtypenamespace = /^([^\.]*)?(?:\.(.+))?$/, + rhoverHack = /\bhover(\.\S+)?\b/, + rkeyEvent = /^key/, + rmouseEvent = /^(?:mouse|contextmenu)|click/, + rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, + rquickIs = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/, + quickParse = function( selector ) { + var quick = rquickIs.exec( selector ); + if ( quick ) { + // 0 1 2 3 + // [ _, tag, id, class ] + quick[1] = ( quick[1] || "" ).toLowerCase(); + quick[3] = quick[3] && new RegExp( "(?:^|\\s)" + quick[3] + "(?:\\s|$)" ); + } + return quick; + }, + quickIs = function( elem, m ) { + var attrs = elem.attributes || {}; + return ( + (!m[1] || elem.nodeName.toLowerCase() === m[1]) && + (!m[2] || (attrs.id || {}).value === m[2]) && + (!m[3] || m[3].test( (attrs[ "class" ] || {}).value )) + ); + }, + hoverHack = function( events ) { + return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); + }; + +/* + * Helper functions for managing events -- not part of the public interface. + * Props to Dean Edwards' addEvent library for many of the ideas. + */ +jQuery.event = { + + add: function( elem, types, handler, data, selector ) { + + var elemData, eventHandle, events, + t, tns, type, namespaces, handleObj, + handleObjIn, quick, handlers, special; + + // Don't attach events to noData or text/comment nodes (allow plain objects tho) + if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) { + return; + } + + // Caller can pass in an object of custom data in lieu of the handler + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + } + + // Make sure that the handler has a unique ID, used to find/remove it later + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } + + // Init the element's event structure and main handler, if this is the first + events = elemData.events; + if ( !events ) { + elemData.events = events = {}; + } + eventHandle = elemData.handle; + if ( !eventHandle ) { + elemData.handle = eventHandle = function( e ) { + // Discard the second event of a jQuery.event.trigger() and + // when an event is called after a page has unloaded + return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? + jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : + undefined; + }; + // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events + eventHandle.elem = elem; + } + + // Handle multiple events separated by a space + // jQuery(...).bind("mouseover mouseout", fn); + types = jQuery.trim( hoverHack(types) ).split( " " ); + for ( t = 0; t < types.length; t++ ) { + + tns = rtypenamespace.exec( types[t] ) || []; + type = tns[1]; + namespaces = ( tns[2] || "" ).split( "." ).sort(); + + // If event changes its type, use the special event handlers for the changed type + special = jQuery.event.special[ type ] || {}; + + // If selector defined, determine special event api type, otherwise given type + type = ( selector ? special.delegateType : special.bindType ) || type; + + // Update special based on newly reset type + special = jQuery.event.special[ type ] || {}; + + // handleObj is passed to all event handlers + handleObj = jQuery.extend({ + type: type, + origType: tns[1], + data: data, + handler: handler, + guid: handler.guid, + selector: selector, + quick: quickParse( selector ), + namespace: namespaces.join(".") + }, handleObjIn ); + + // Init the event handler queue if we're the first + handlers = events[ type ]; + if ( !handlers ) { + handlers = events[ type ] = []; + handlers.delegateCount = 0; + + // Only use addEventListener/attachEvent if the special events handler returns false + if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + // Bind the global event handler to the element + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle, false ); + + } else if ( elem.attachEvent ) { + elem.attachEvent( "on" + type, eventHandle ); + } + } + } + + if ( special.add ) { + special.add.call( elem, handleObj ); + + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; + } + } + + // Add to the element's handler list, delegates in front + if ( selector ) { + handlers.splice( handlers.delegateCount++, 0, handleObj ); + } else { + handlers.push( handleObj ); + } + + // Keep track of which events have ever been used, for event optimization + jQuery.event.global[ type ] = true; + } + + // Nullify elem to prevent memory leaks in IE + elem = null; + }, + + global: {}, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, selector, mappedTypes ) { + + var elemData = jQuery.hasData( elem ) && jQuery._data( elem ), + t, tns, type, origType, namespaces, origCount, + j, events, special, handle, eventType, handleObj; + + if ( !elemData || !(events = elemData.events) ) { + return; + } + + // Once for each type.namespace in types; type may be omitted + types = jQuery.trim( hoverHack( types || "" ) ).split(" "); + for ( t = 0; t < types.length; t++ ) { + tns = rtypenamespace.exec( types[t] ) || []; + type = origType = tns[1]; + namespaces = tns[2]; + + // Unbind all events (on this namespace, if provided) for the element + if ( !type ) { + for ( type in events ) { + jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); + } + continue; + } + + special = jQuery.event.special[ type ] || {}; + type = ( selector? special.delegateType : special.bindType ) || type; + eventType = events[ type ] || []; + origCount = eventType.length; + namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.)?") + "(\\.|$)") : null; + + // Remove matching events + for ( j = 0; j < eventType.length; j++ ) { + handleObj = eventType[ j ]; + + if ( ( mappedTypes || origType === handleObj.origType ) && + ( !handler || handler.guid === handleObj.guid ) && + ( !namespaces || namespaces.test( handleObj.namespace ) ) && + ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { + eventType.splice( j--, 1 ); + + if ( handleObj.selector ) { + eventType.delegateCount--; + } + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + } + + // Remove generic event handler if we removed something and no more handlers exist + // (avoids potential for endless recursion during removal of special event handlers) + if ( eventType.length === 0 && origCount !== eventType.length ) { + if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { + jQuery.removeEvent( elem, type, elemData.handle ); + } + + delete events[ type ]; + } + } + + // Remove the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + handle = elemData.handle; + if ( handle ) { + handle.elem = null; + } + + // removeData also checks for emptiness and clears the expando if empty + // so use it instead of delete + jQuery.removeData( elem, [ "events", "handle" ], true ); + } + }, + + // Events that are safe to short-circuit if no handlers are attached. + // Native DOM events should not be added, they may have inline handlers. + customEvent: { + "getData": true, + "setData": true, + "changeData": true + }, + + trigger: function( event, data, elem, onlyHandlers ) { + // Don't do events on text and comment nodes + if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) { + return; + } + + // Event object or event type + var type = event.type || event, + namespaces = [], + cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType; + + // focus/blur morphs to focusin/out; ensure we're not firing them right now + if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { + return; + } + + if ( type.indexOf( "!" ) >= 0 ) { + // Exclusive events trigger only for the exact event (no namespaces) + type = type.slice(0, -1); + exclusive = true; + } + + if ( type.indexOf( "." ) >= 0 ) { + // Namespaced trigger; create a regexp to match event type in handle() + namespaces = type.split("."); + type = namespaces.shift(); + namespaces.sort(); + } + + if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { + // No jQuery handlers for this event type, and it can't have inline handlers + return; + } + + // Caller can pass in an Event, Object, or just an event type string + event = typeof event === "object" ? + // jQuery.Event object + event[ jQuery.expando ] ? event : + // Object literal + new jQuery.Event( type, event ) : + // Just the event type (string) + new jQuery.Event( type ); + + event.type = type; + event.isTrigger = true; + event.exclusive = exclusive; + event.namespace = namespaces.join( "." ); + event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)") : null; + ontype = type.indexOf( ":" ) < 0 ? "on" + type : ""; + + // Handle a global trigger + if ( !elem ) { + + // TODO: Stop taunting the data cache; remove global events and always attach to document + cache = jQuery.cache; + for ( i in cache ) { + if ( cache[ i ].events && cache[ i ].events[ type ] ) { + jQuery.event.trigger( event, data, cache[ i ].handle.elem, true ); + } + } + return; + } + + // Clean up the event in case it is being reused + event.result = undefined; + if ( !event.target ) { + event.target = elem; + } + + // Clone any incoming data and prepend the event, creating the handler arg list + data = data != null ? jQuery.makeArray( data ) : []; + data.unshift( event ); + + // Allow special events to draw outside the lines + special = jQuery.event.special[ type ] || {}; + if ( special.trigger && special.trigger.apply( elem, data ) === false ) { + return; + } + + // Determine event propagation path in advance, per W3C events spec (#9951) + // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) + eventPath = [[ elem, special.bindType || type ]]; + if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { + + bubbleType = special.delegateType || type; + cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode; + old = null; + for ( ; cur; cur = cur.parentNode ) { + eventPath.push([ cur, bubbleType ]); + old = cur; + } + + // Only add window if we got to document (e.g., not plain obj or detached DOM) + if ( old && old === elem.ownerDocument ) { + eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]); + } + } + + // Fire handlers on the event path + for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) { + + cur = eventPath[i][0]; + event.type = eventPath[i][1]; + + handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); + if ( handle ) { + handle.apply( cur, data ); + } + // Note that this is a bare JS function and not a jQuery handler + handle = ontype && cur[ ontype ]; + if ( handle && jQuery.acceptData( cur ) && handle.apply( cur, data ) === false ) { + event.preventDefault(); + } + } + event.type = type; + + // If nobody prevented the default action, do it now + if ( !onlyHandlers && !event.isDefaultPrevented() ) { + + if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && + !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { + + // Call a native DOM method on the target with the same name name as the event. + // Can't use an .isFunction() check here because IE6/7 fails that test. + // Don't do default actions on window, that's where global variables be (#6170) + // IE<9 dies on focus/blur to hidden element (#1486) + if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) { + + // Don't re-trigger an onFOO event when we call its FOO() method + old = elem[ ontype ]; + + if ( old ) { + elem[ ontype ] = null; + } + + // Prevent re-triggering of the same event, since we already bubbled it above + jQuery.event.triggered = type; + elem[ type ](); + jQuery.event.triggered = undefined; + + if ( old ) { + elem[ ontype ] = old; + } + } + } + } + + return event.result; + }, + + dispatch: function( event ) { + + // Make a writable jQuery.Event from the native event object + event = jQuery.event.fix( event || window.event ); + + var handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), + delegateCount = handlers.delegateCount, + args = [].slice.call( arguments, 0 ), + run_all = !event.exclusive && !event.namespace, + handlerQueue = [], + i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related; + + // Use the fix-ed jQuery.Event rather than the (read-only) native event + args[0] = event; + event.delegateTarget = this; + + // Determine handlers that should run if there are delegated events + // Avoid disabled elements in IE (#6911) and non-left-click bubbling in Firefox (#3861) + if ( delegateCount && !event.target.disabled && !(event.button && event.type === "click") ) { + + // Pregenerate a single jQuery object for reuse with .is() + jqcur = jQuery(this); + jqcur.context = this.ownerDocument || this; + + for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { + selMatch = {}; + matches = []; + jqcur[0] = cur; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; + sel = handleObj.selector; + + if ( selMatch[ sel ] === undefined ) { + selMatch[ sel ] = ( + handleObj.quick ? quickIs( cur, handleObj.quick ) : jqcur.is( sel ) + ); + } + if ( selMatch[ sel ] ) { + matches.push( handleObj ); + } + } + if ( matches.length ) { + handlerQueue.push({ elem: cur, matches: matches }); + } + } + } + + // Add the remaining (directly-bound) handlers + if ( handlers.length > delegateCount ) { + handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) }); + } + + // Run delegates first; they may want to stop propagation beneath us + for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) { + matched = handlerQueue[ i ]; + event.currentTarget = matched.elem; + + for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) { + handleObj = matched.matches[ j ]; + + // Triggered event must either 1) be non-exclusive and have no namespace, or + // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). + if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) { + + event.data = handleObj.data; + event.handleObj = handleObj; + + ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) + .apply( matched.elem, args ); + + if ( ret !== undefined ) { + event.result = ret; + if ( ret === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + } + } + } + + return event.result; + }, + + // Includes some event props shared by KeyEvent and MouseEvent + // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 *** + props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), + + fixHooks: {}, + + keyHooks: { + props: "char charCode key keyCode".split(" "), + filter: function( event, original ) { + + // Add which for key events + if ( event.which == null ) { + event.which = original.charCode != null ? original.charCode : original.keyCode; + } + + return event; + } + }, + + mouseHooks: { + props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), + filter: function( event, original ) { + var eventDoc, doc, body, + button = original.button, + fromElement = original.fromElement; + + // Calculate pageX/Y if missing and clientX/Y available + if ( event.pageX == null && original.clientX != null ) { + eventDoc = event.target.ownerDocument || document; + doc = eventDoc.documentElement; + body = eventDoc.body; + + event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); + event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); + } + + // Add relatedTarget, if necessary + if ( !event.relatedTarget && fromElement ) { + event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; + } + + // Add which for click: 1 === left; 2 === middle; 3 === right + // Note: button is not normalized, so don't use it + if ( !event.which && button !== undefined ) { + event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); + } + + return event; + } + }, + + fix: function( event ) { + if ( event[ jQuery.expando ] ) { + return event; + } + + // Create a writable copy of the event object and normalize some properties + var i, prop, + originalEvent = event, + fixHook = jQuery.event.fixHooks[ event.type ] || {}, + copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; + + event = jQuery.Event( originalEvent ); + + for ( i = copy.length; i; ) { + prop = copy[ --i ]; + event[ prop ] = originalEvent[ prop ]; + } + + // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2) + if ( !event.target ) { + event.target = originalEvent.srcElement || document; + } + + // Target should not be a text node (#504, Safari) + if ( event.target.nodeType === 3 ) { + event.target = event.target.parentNode; + } + + // For mouse/key events; add metaKey if it's not there (#3368, IE6/7/8) + if ( event.metaKey === undefined ) { + event.metaKey = event.ctrlKey; + } + + return fixHook.filter? fixHook.filter( event, originalEvent ) : event; + }, + + special: { + ready: { + // Make sure the ready event is setup + setup: jQuery.bindReady + }, + + load: { + // Prevent triggered image.load events from bubbling to window.load + noBubble: true + }, + + focus: { + delegateType: "focusin" + }, + blur: { + delegateType: "focusout" + }, + + beforeunload: { + setup: function( data, namespaces, eventHandle ) { + // We only want to do this special case on windows + if ( jQuery.isWindow( this ) ) { + this.onbeforeunload = eventHandle; + } + }, + + teardown: function( namespaces, eventHandle ) { + if ( this.onbeforeunload === eventHandle ) { + this.onbeforeunload = null; + } + } + } + }, + + simulate: function( type, elem, event, bubble ) { + // Piggyback on a donor event to simulate a different one. + // Fake originalEvent to avoid donor's stopPropagation, but if the + // simulated event prevents default then we do the same on the donor. + var e = jQuery.extend( + new jQuery.Event(), + event, + { type: type, + isSimulated: true, + originalEvent: {} + } + ); + if ( bubble ) { + jQuery.event.trigger( e, null, elem ); + } else { + jQuery.event.dispatch.call( elem, e ); + } + if ( e.isDefaultPrevented() ) { + event.preventDefault(); + } + } +}; + +// Some plugins are using, but it's undocumented/deprecated and will be removed. +// The 1.7 special event interface should provide all the hooks needed now. +jQuery.event.handle = jQuery.event.dispatch; + +jQuery.removeEvent = document.removeEventListener ? + function( elem, type, handle ) { + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle, false ); + } + } : + function( elem, type, handle ) { + if ( elem.detachEvent ) { + elem.detachEvent( "on" + type, handle ); + } + }; + +jQuery.Event = function( src, props ) { + // Allow instantiation without the 'new' keyword + if ( !(this instanceof jQuery.Event) ) { + return new jQuery.Event( src, props ); + } + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || + src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; + + // Event type + } else { + this.type = src; + } + + // Put explicitly provided properties onto the event object + if ( props ) { + jQuery.extend( this, props ); + } + + // Create a timestamp if incoming event doesn't have one + this.timeStamp = src && src.timeStamp || jQuery.now(); + + // Mark it as fixed + this[ jQuery.expando ] = true; +}; + +function returnFalse() { + return false; +} +function returnTrue() { + return true; +} + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + preventDefault: function() { + this.isDefaultPrevented = returnTrue; + + var e = this.originalEvent; + if ( !e ) { + return; + } + + // if preventDefault exists run it on the original event + if ( e.preventDefault ) { + e.preventDefault(); + + // otherwise set the returnValue property of the original event to false (IE) + } else { + e.returnValue = false; + } + }, + stopPropagation: function() { + this.isPropagationStopped = returnTrue; + + var e = this.originalEvent; + if ( !e ) { + return; + } + // if stopPropagation exists run it on the original event + if ( e.stopPropagation ) { + e.stopPropagation(); + } + // otherwise set the cancelBubble property of the original event to true (IE) + e.cancelBubble = true; + }, + stopImmediatePropagation: function() { + this.isImmediatePropagationStopped = returnTrue; + this.stopPropagation(); + }, + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse +}; + +// Create mouseenter/leave events using mouseover/out and event-time checks +jQuery.each({ + mouseenter: "mouseover", + mouseleave: "mouseout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = { + delegateType: fix, + bindType: fix, + + handle: function( event ) { + var target = this, + related = event.relatedTarget, + handleObj = event.handleObj, + selector = handleObj.selector, + ret; + + // For mousenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if ( !related || (related !== target && !jQuery.contains( target, related )) ) { + event.type = handleObj.origType; + ret = handleObj.handler.apply( this, arguments ); + event.type = fix; + } + return ret; + } + }; +}); + +// IE submit delegation +if ( !jQuery.support.submitBubbles ) { + + jQuery.event.special.submit = { + setup: function() { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } + + // Lazy-add a submit handler when a descendant form may potentially be submitted + jQuery.event.add( this, "click._submit keypress._submit", function( e ) { + // Node name check avoids a VML-related crash in IE (#9807) + var elem = e.target, + form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; + if ( form && !form._submit_attached ) { + jQuery.event.add( form, "submit._submit", function( event ) { + // If form was submitted by the user, bubble the event up the tree + if ( this.parentNode && !event.isTrigger ) { + jQuery.event.simulate( "submit", this.parentNode, event, true ); + } + }); + form._submit_attached = true; + } + }); + // return undefined since we don't need an event listener + }, + + teardown: function() { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } + + // Remove delegated handlers; cleanData eventually reaps submit handlers attached above + jQuery.event.remove( this, "._submit" ); + } + }; +} + +// IE change delegation and checkbox/radio fix +if ( !jQuery.support.changeBubbles ) { + + jQuery.event.special.change = { + + setup: function() { + + if ( rformElems.test( this.nodeName ) ) { + // IE doesn't fire change on a check/radio until blur; trigger it on click + // after a propertychange. Eat the blur-change in special.change.handle. + // This still fires onchange a second time for check/radio after blur. + if ( this.type === "checkbox" || this.type === "radio" ) { + jQuery.event.add( this, "propertychange._change", function( event ) { + if ( event.originalEvent.propertyName === "checked" ) { + this._just_changed = true; + } + }); + jQuery.event.add( this, "click._change", function( event ) { + if ( this._just_changed && !event.isTrigger ) { + this._just_changed = false; + jQuery.event.simulate( "change", this, event, true ); + } + }); + } + return false; + } + // Delegated event; lazy-add a change handler on descendant inputs + jQuery.event.add( this, "beforeactivate._change", function( e ) { + var elem = e.target; + + if ( rformElems.test( elem.nodeName ) && !elem._change_attached ) { + jQuery.event.add( elem, "change._change", function( event ) { + if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { + jQuery.event.simulate( "change", this.parentNode, event, true ); + } + }); + elem._change_attached = true; + } + }); + }, + + handle: function( event ) { + var elem = event.target; + + // Swallow native change events from checkbox/radio, we already triggered them above + if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { + return event.handleObj.handler.apply( this, arguments ); + } + }, + + teardown: function() { + jQuery.event.remove( this, "._change" ); + + return rformElems.test( this.nodeName ); + } + }; +} + +// Create "bubbling" focus and blur events +if ( !jQuery.support.focusinBubbles ) { + jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { + + // Attach a single capturing handler while someone wants focusin/focusout + var attaches = 0, + handler = function( event ) { + jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); + }; + + jQuery.event.special[ fix ] = { + setup: function() { + if ( attaches++ === 0 ) { + document.addEventListener( orig, handler, true ); + } + }, + teardown: function() { + if ( --attaches === 0 ) { + document.removeEventListener( orig, handler, true ); + } + } + }; + }); +} + +jQuery.fn.extend({ + + on: function( types, selector, data, fn, /*INTERNAL*/ one ) { + var origFn, type; + + // Types can be a map of types/handlers + if ( typeof types === "object" ) { + // ( types-Object, selector, data ) + if ( typeof selector !== "string" ) { + // ( types-Object, data ) + data = selector; + selector = undefined; + } + for ( type in types ) { + this.on( type, selector, data, types[ type ], one ); + } + return this; + } + + if ( data == null && fn == null ) { + // ( types, fn ) + fn = selector; + data = selector = undefined; + } else if ( fn == null ) { + if ( typeof selector === "string" ) { + // ( types, selector, fn ) + fn = data; + data = undefined; + } else { + // ( types, data, fn ) + fn = data; + data = selector; + selector = undefined; + } + } + if ( fn === false ) { + fn = returnFalse; + } else if ( !fn ) { + return this; + } + + if ( one === 1 ) { + origFn = fn; + fn = function( event ) { + // Can use an empty set, since event contains the info + jQuery().off( event ); + return origFn.apply( this, arguments ); + }; + // Use same guid so caller can remove using origFn + fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); + } + return this.each( function() { + jQuery.event.add( this, types, fn, data, selector ); + }); + }, + one: function( types, selector, data, fn ) { + return this.on.call( this, types, selector, data, fn, 1 ); + }, + off: function( types, selector, fn ) { + if ( types && types.preventDefault && types.handleObj ) { + // ( event ) dispatched jQuery.Event + var handleObj = types.handleObj; + jQuery( types.delegateTarget ).off( + handleObj.namespace? handleObj.type + "." + handleObj.namespace : handleObj.type, + handleObj.selector, + handleObj.handler + ); + return this; + } + if ( typeof types === "object" ) { + // ( types-object [, selector] ) + for ( var type in types ) { + this.off( type, selector, types[ type ] ); + } + return this; + } + if ( selector === false || typeof selector === "function" ) { + // ( types [, fn] ) + fn = selector; + selector = undefined; + } + if ( fn === false ) { + fn = returnFalse; + } + return this.each(function() { + jQuery.event.remove( this, types, fn, selector ); + }); + }, + + bind: function( types, data, fn ) { + return this.on( types, null, data, fn ); + }, + unbind: function( types, fn ) { + return this.off( types, null, fn ); + }, + + live: function( types, data, fn ) { + jQuery( this.context ).on( types, this.selector, data, fn ); + return this; + }, + die: function( types, fn ) { + jQuery( this.context ).off( types, this.selector || "**", fn ); + return this; + }, + + delegate: function( selector, types, data, fn ) { + return this.on( types, selector, data, fn ); + }, + undelegate: function( selector, types, fn ) { + // ( namespace ) or ( selector, types [, fn] ) + return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector, fn ); + }, + + trigger: function( type, data ) { + return this.each(function() { + jQuery.event.trigger( type, data, this ); + }); + }, + triggerHandler: function( type, data ) { + if ( this[0] ) { + return jQuery.event.trigger( type, data, this[0], true ); + } + }, + + toggle: function( fn ) { + // Save reference to arguments for access in closure + var args = arguments, + guid = fn.guid || jQuery.guid++, + i = 0, + toggler = function( event ) { + // Figure out which function to execute + var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; + jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); + + // Make sure that clicks stop + event.preventDefault(); + + // and execute the function + return args[ lastToggle ].apply( this, arguments ) || false; + }; + + // link all the functions, so any of them can unbind this click handler + toggler.guid = guid; + while ( i < args.length ) { + args[ i++ ].guid = guid; + } + + return this.click( toggler ); + }, + + hover: function( fnOver, fnOut ) { + return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); + } +}); + +jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { + + // Handle event binding + jQuery.fn[ name ] = function( data, fn ) { + if ( fn == null ) { + fn = data; + data = null; + } + + return arguments.length > 0 ? + this.on( name, null, data, fn ) : + this.trigger( name ); + }; + + if ( jQuery.attrFn ) { + jQuery.attrFn[ name ] = true; + } + + if ( rkeyEvent.test( name ) ) { + jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; + } + + if ( rmouseEvent.test( name ) ) { + jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; + } +}); + + + +/*! + * Sizzle CSS Selector Engine + * Copyright 2011, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * More information: http://sizzlejs.com/ + */ +(function(){ + +var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, + expando = "sizcache" + (Math.random() + '').replace('.', ''), + done = 0, + toString = Object.prototype.toString, + hasDuplicate = false, + baseHasDuplicate = true, + rBackslash = /\\/g, + rReturn = /\r\n/g, + rNonWord = /\W/; + +// Here we check if the JavaScript engine is using some sort of +// optimization where it does not always call our comparision +// function. If that is the case, discard the hasDuplicate value. +// Thus far that includes Google Chrome. +[0, 0].sort(function() { + baseHasDuplicate = false; + return 0; +}); + +var Sizzle = function( selector, context, results, seed ) { + results = results || []; + context = context || document; + + var origContext = context; + + if ( context.nodeType !== 1 && context.nodeType !== 9 ) { + return []; + } + + if ( !selector || typeof selector !== "string" ) { + return results; + } + + var m, set, checkSet, extra, ret, cur, pop, i, + prune = true, + contextXML = Sizzle.isXML( context ), + parts = [], + soFar = selector; + + // Reset the position of the chunker regexp (start from head) + do { + chunker.exec( "" ); + m = chunker.exec( soFar ); + + if ( m ) { + soFar = m[3]; + + parts.push( m[1] ); + + if ( m[2] ) { + extra = m[3]; + break; + } + } + } while ( m ); + + if ( parts.length > 1 && origPOS.exec( selector ) ) { + + if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { + set = posProcess( parts[0] + parts[1], context, seed ); + + } else { + set = Expr.relative[ parts[0] ] ? + [ context ] : + Sizzle( parts.shift(), context ); + + while ( parts.length ) { + selector = parts.shift(); + + if ( Expr.relative[ selector ] ) { + selector += parts.shift(); + } + + set = posProcess( selector, set, seed ); + } + } + + } else { + // Take a shortcut and set the context if the root selector is an ID + // (but not if it'll be faster if the inner selector is an ID) + if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && + Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { + + ret = Sizzle.find( parts.shift(), context, contextXML ); + context = ret.expr ? + Sizzle.filter( ret.expr, ret.set )[0] : + ret.set[0]; + } + + if ( context ) { + ret = seed ? + { expr: parts.pop(), set: makeArray(seed) } : + Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); + + set = ret.expr ? + Sizzle.filter( ret.expr, ret.set ) : + ret.set; + + if ( parts.length > 0 ) { + checkSet = makeArray( set ); + + } else { + prune = false; + } + + while ( parts.length ) { + cur = parts.pop(); + pop = cur; + + if ( !Expr.relative[ cur ] ) { + cur = ""; + } else { + pop = parts.pop(); + } + + if ( pop == null ) { + pop = context; + } + + Expr.relative[ cur ]( checkSet, pop, contextXML ); + } + + } else { + checkSet = parts = []; + } + } + + if ( !checkSet ) { + checkSet = set; + } + + if ( !checkSet ) { + Sizzle.error( cur || selector ); + } + + if ( toString.call(checkSet) === "[object Array]" ) { + if ( !prune ) { + results.push.apply( results, checkSet ); + + } else if ( context && context.nodeType === 1 ) { + for ( i = 0; checkSet[i] != null; i++ ) { + if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { + results.push( set[i] ); + } + } + + } else { + for ( i = 0; checkSet[i] != null; i++ ) { + if ( checkSet[i] && checkSet[i].nodeType === 1 ) { + results.push( set[i] ); + } + } + } + + } else { + makeArray( checkSet, results ); + } + + if ( extra ) { + Sizzle( extra, origContext, results, seed ); + Sizzle.uniqueSort( results ); + } + + return results; +}; + +Sizzle.uniqueSort = function( results ) { + if ( sortOrder ) { + hasDuplicate = baseHasDuplicate; + results.sort( sortOrder ); + + if ( hasDuplicate ) { + for ( var i = 1; i < results.length; i++ ) { + if ( results[i] === results[ i - 1 ] ) { + results.splice( i--, 1 ); + } + } + } + } + + return results; +}; + +Sizzle.matches = function( expr, set ) { + return Sizzle( expr, null, null, set ); +}; + +Sizzle.matchesSelector = function( node, expr ) { + return Sizzle( expr, null, null, [node] ).length > 0; +}; + +Sizzle.find = function( expr, context, isXML ) { + var set, i, len, match, type, left; + + if ( !expr ) { + return []; + } + + for ( i = 0, len = Expr.order.length; i < len; i++ ) { + type = Expr.order[i]; + + if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { + left = match[1]; + match.splice( 1, 1 ); + + if ( left.substr( left.length - 1 ) !== "\\" ) { + match[1] = (match[1] || "").replace( rBackslash, "" ); + set = Expr.find[ type ]( match, context, isXML ); + + if ( set != null ) { + expr = expr.replace( Expr.match[ type ], "" ); + break; + } + } + } + } + + if ( !set ) { + set = typeof context.getElementsByTagName !== "undefined" ? + context.getElementsByTagName( "*" ) : + []; + } + + return { set: set, expr: expr }; +}; + +Sizzle.filter = function( expr, set, inplace, not ) { + var match, anyFound, + type, found, item, filter, left, + i, pass, + old = expr, + result = [], + curLoop = set, + isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); + + while ( expr && set.length ) { + for ( type in Expr.filter ) { + if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { + filter = Expr.filter[ type ]; + left = match[1]; + + anyFound = false; + + match.splice(1,1); + + if ( left.substr( left.length - 1 ) === "\\" ) { + continue; + } + + if ( curLoop === result ) { + result = []; + } + + if ( Expr.preFilter[ type ] ) { + match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); + + if ( !match ) { + anyFound = found = true; + + } else if ( match === true ) { + continue; + } + } + + if ( match ) { + for ( i = 0; (item = curLoop[i]) != null; i++ ) { + if ( item ) { + found = filter( item, match, i, curLoop ); + pass = not ^ found; + + if ( inplace && found != null ) { + if ( pass ) { + anyFound = true; + + } else { + curLoop[i] = false; + } + + } else if ( pass ) { + result.push( item ); + anyFound = true; + } + } + } + } + + if ( found !== undefined ) { + if ( !inplace ) { + curLoop = result; + } + + expr = expr.replace( Expr.match[ type ], "" ); + + if ( !anyFound ) { + return []; + } + + break; + } + } + } + + // Improper expression + if ( expr === old ) { + if ( anyFound == null ) { + Sizzle.error( expr ); + + } else { + break; + } + } + + old = expr; + } + + return curLoop; +}; + +Sizzle.error = function( msg ) { + throw new Error( "Syntax error, unrecognized expression: " + msg ); +}; + +/** + * Utility function for retreiving the text value of an array of DOM nodes + * @param {Array|Element} elem + */ +var getText = Sizzle.getText = function( elem ) { + var i, node, + nodeType = elem.nodeType, + ret = ""; + + if ( nodeType ) { + if ( nodeType === 1 || nodeType === 9 ) { + // Use textContent || innerText for elements + if ( typeof elem.textContent === 'string' ) { + return elem.textContent; + } else if ( typeof elem.innerText === 'string' ) { + // Replace IE's carriage returns + return elem.innerText.replace( rReturn, '' ); + } else { + // Traverse it's children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling) { + ret += getText( elem ); + } + } + } else if ( nodeType === 3 || nodeType === 4 ) { + return elem.nodeValue; + } + } else { + + // If no nodeType, this is expected to be an array + for ( i = 0; (node = elem[i]); i++ ) { + // Do not traverse comment nodes + if ( node.nodeType !== 8 ) { + ret += getText( node ); + } + } + } + return ret; +}; + +var Expr = Sizzle.selectors = { + order: [ "ID", "NAME", "TAG" ], + + match: { + ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, + CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, + NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, + ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, + TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, + CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, + POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, + PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ + }, + + leftMatch: {}, + + attrMap: { + "class": "className", + "for": "htmlFor" + }, + + attrHandle: { + href: function( elem ) { + return elem.getAttribute( "href" ); + }, + type: function( elem ) { + return elem.getAttribute( "type" ); + } + }, + + relative: { + "+": function(checkSet, part){ + var isPartStr = typeof part === "string", + isTag = isPartStr && !rNonWord.test( part ), + isPartStrNotTag = isPartStr && !isTag; + + if ( isTag ) { + part = part.toLowerCase(); + } + + for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { + if ( (elem = checkSet[i]) ) { + while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} + + checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? + elem || false : + elem === part; + } + } + + if ( isPartStrNotTag ) { + Sizzle.filter( part, checkSet, true ); + } + }, + + ">": function( checkSet, part ) { + var elem, + isPartStr = typeof part === "string", + i = 0, + l = checkSet.length; + + if ( isPartStr && !rNonWord.test( part ) ) { + part = part.toLowerCase(); + + for ( ; i < l; i++ ) { + elem = checkSet[i]; + + if ( elem ) { + var parent = elem.parentNode; + checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; + } + } + + } else { + for ( ; i < l; i++ ) { + elem = checkSet[i]; + + if ( elem ) { + checkSet[i] = isPartStr ? + elem.parentNode : + elem.parentNode === part; + } + } + + if ( isPartStr ) { + Sizzle.filter( part, checkSet, true ); + } + } + }, + + "": function(checkSet, part, isXML){ + var nodeCheck, + doneName = done++, + checkFn = dirCheck; + + if ( typeof part === "string" && !rNonWord.test( part ) ) { + part = part.toLowerCase(); + nodeCheck = part; + checkFn = dirNodeCheck; + } + + checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); + }, + + "~": function( checkSet, part, isXML ) { + var nodeCheck, + doneName = done++, + checkFn = dirCheck; + + if ( typeof part === "string" && !rNonWord.test( part ) ) { + part = part.toLowerCase(); + nodeCheck = part; + checkFn = dirNodeCheck; + } + + checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); + } + }, + + find: { + ID: function( match, context, isXML ) { + if ( typeof context.getElementById !== "undefined" && !isXML ) { + var m = context.getElementById(match[1]); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + return m && m.parentNode ? [m] : []; + } + }, + + NAME: function( match, context ) { + if ( typeof context.getElementsByName !== "undefined" ) { + var ret = [], + results = context.getElementsByName( match[1] ); + + for ( var i = 0, l = results.length; i < l; i++ ) { + if ( results[i].getAttribute("name") === match[1] ) { + ret.push( results[i] ); + } + } + + return ret.length === 0 ? null : ret; + } + }, + + TAG: function( match, context ) { + if ( typeof context.getElementsByTagName !== "undefined" ) { + return context.getElementsByTagName( match[1] ); + } + } + }, + preFilter: { + CLASS: function( match, curLoop, inplace, result, not, isXML ) { + match = " " + match[1].replace( rBackslash, "" ) + " "; + + if ( isXML ) { + return match; + } + + for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { + if ( elem ) { + if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) { + if ( !inplace ) { + result.push( elem ); + } + + } else if ( inplace ) { + curLoop[i] = false; + } + } + } + + return false; + }, + + ID: function( match ) { + return match[1].replace( rBackslash, "" ); + }, + + TAG: function( match, curLoop ) { + return match[1].replace( rBackslash, "" ).toLowerCase(); + }, + + CHILD: function( match ) { + if ( match[1] === "nth" ) { + if ( !match[2] ) { + Sizzle.error( match[0] ); + } + + match[2] = match[2].replace(/^\+|\s*/g, ''); + + // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' + var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( + match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || + !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); + + // calculate the numbers (first)n+(last) including if they are negative + match[2] = (test[1] + (test[2] || 1)) - 0; + match[3] = test[3] - 0; + } + else if ( match[2] ) { + Sizzle.error( match[0] ); + } + + // TODO: Move to normal caching system + match[0] = done++; + + return match; + }, + + ATTR: function( match, curLoop, inplace, result, not, isXML ) { + var name = match[1] = match[1].replace( rBackslash, "" ); + + if ( !isXML && Expr.attrMap[name] ) { + match[1] = Expr.attrMap[name]; + } + + // Handle if an un-quoted value was used + match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" ); + + if ( match[2] === "~=" ) { + match[4] = " " + match[4] + " "; + } + + return match; + }, + + PSEUDO: function( match, curLoop, inplace, result, not ) { + if ( match[1] === "not" ) { + // If we're dealing with a complex expression, or a simple one + if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { + match[3] = Sizzle(match[3], null, null, curLoop); + + } else { + var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); + + if ( !inplace ) { + result.push.apply( result, ret ); + } + + return false; + } + + } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { + return true; + } + + return match; + }, + + POS: function( match ) { + match.unshift( true ); + + return match; + } + }, + + filters: { + enabled: function( elem ) { + return elem.disabled === false && elem.type !== "hidden"; + }, + + disabled: function( elem ) { + return elem.disabled === true; + }, + + checked: function( elem ) { + return elem.checked === true; + }, + + selected: function( elem ) { + // Accessing this property makes selected-by-default + // options in Safari work properly + if ( elem.parentNode ) { + elem.parentNode.selectedIndex; + } + + return elem.selected === true; + }, + + parent: function( elem ) { + return !!elem.firstChild; + }, + + empty: function( elem ) { + return !elem.firstChild; + }, + + has: function( elem, i, match ) { + return !!Sizzle( match[3], elem ).length; + }, + + header: function( elem ) { + return (/h\d/i).test( elem.nodeName ); + }, + + text: function( elem ) { + var attr = elem.getAttribute( "type" ), type = elem.type; + // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) + // use getAttribute instead to test this case + return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null ); + }, + + radio: function( elem ) { + return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type; + }, + + checkbox: function( elem ) { + return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type; + }, + + file: function( elem ) { + return elem.nodeName.toLowerCase() === "input" && "file" === elem.type; + }, + + password: function( elem ) { + return elem.nodeName.toLowerCase() === "input" && "password" === elem.type; + }, + + submit: function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && "submit" === elem.type; + }, + + image: function( elem ) { + return elem.nodeName.toLowerCase() === "input" && "image" === elem.type; + }, + + reset: function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && "reset" === elem.type; + }, + + button: function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && "button" === elem.type || name === "button"; + }, + + input: function( elem ) { + return (/input|select|textarea|button/i).test( elem.nodeName ); + }, + + focus: function( elem ) { + return elem === elem.ownerDocument.activeElement; + } + }, + setFilters: { + first: function( elem, i ) { + return i === 0; + }, + + last: function( elem, i, match, array ) { + return i === array.length - 1; + }, + + even: function( elem, i ) { + return i % 2 === 0; + }, + + odd: function( elem, i ) { + return i % 2 === 1; + }, + + lt: function( elem, i, match ) { + return i < match[3] - 0; + }, + + gt: function( elem, i, match ) { + return i > match[3] - 0; + }, + + nth: function( elem, i, match ) { + return match[3] - 0 === i; + }, + + eq: function( elem, i, match ) { + return match[3] - 0 === i; + } + }, + filter: { + PSEUDO: function( elem, match, i, array ) { + var name = match[1], + filter = Expr.filters[ name ]; + + if ( filter ) { + return filter( elem, i, match, array ); + + } else if ( name === "contains" ) { + return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0; + + } else if ( name === "not" ) { + var not = match[3]; + + for ( var j = 0, l = not.length; j < l; j++ ) { + if ( not[j] === elem ) { + return false; + } + } + + return true; + + } else { + Sizzle.error( name ); + } + }, + + CHILD: function( elem, match ) { + var first, last, + doneName, parent, cache, + count, diff, + type = match[1], + node = elem; + + switch ( type ) { + case "only": + case "first": + while ( (node = node.previousSibling) ) { + if ( node.nodeType === 1 ) { + return false; + } + } + + if ( type === "first" ) { + return true; + } + + node = elem; + + case "last": + while ( (node = node.nextSibling) ) { + if ( node.nodeType === 1 ) { + return false; + } + } + + return true; + + case "nth": + first = match[2]; + last = match[3]; + + if ( first === 1 && last === 0 ) { + return true; + } + + doneName = match[0]; + parent = elem.parentNode; + + if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) { + count = 0; + + for ( node = parent.firstChild; node; node = node.nextSibling ) { + if ( node.nodeType === 1 ) { + node.nodeIndex = ++count; + } + } + + parent[ expando ] = doneName; + } + + diff = elem.nodeIndex - last; + + if ( first === 0 ) { + return diff === 0; + + } else { + return ( diff % first === 0 && diff / first >= 0 ); + } + } + }, + + ID: function( elem, match ) { + return elem.nodeType === 1 && elem.getAttribute("id") === match; + }, + + TAG: function( elem, match ) { + return (match === "*" && elem.nodeType === 1) || !!elem.nodeName && elem.nodeName.toLowerCase() === match; + }, + + CLASS: function( elem, match ) { + return (" " + (elem.className || elem.getAttribute("class")) + " ") + .indexOf( match ) > -1; + }, + + ATTR: function( elem, match ) { + var name = match[1], + result = Sizzle.attr ? + Sizzle.attr( elem, name ) : + Expr.attrHandle[ name ] ? + Expr.attrHandle[ name ]( elem ) : + elem[ name ] != null ? + elem[ name ] : + elem.getAttribute( name ), + value = result + "", + type = match[2], + check = match[4]; + + return result == null ? + type === "!=" : + !type && Sizzle.attr ? + result != null : + type === "=" ? + value === check : + type === "*=" ? + value.indexOf(check) >= 0 : + type === "~=" ? + (" " + value + " ").indexOf(check) >= 0 : + !check ? + value && result !== false : + type === "!=" ? + value !== check : + type === "^=" ? + value.indexOf(check) === 0 : + type === "$=" ? + value.substr(value.length - check.length) === check : + type === "|=" ? + value === check || value.substr(0, check.length + 1) === check + "-" : + false; + }, + + POS: function( elem, match, i, array ) { + var name = match[2], + filter = Expr.setFilters[ name ]; + + if ( filter ) { + return filter( elem, i, match, array ); + } + } + } +}; + +var origPOS = Expr.match.POS, + fescape = function(all, num){ + return "\\" + (num - 0 + 1); + }; + +for ( var type in Expr.match ) { + Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); + Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); +} + +var makeArray = function( array, results ) { + array = Array.prototype.slice.call( array, 0 ); + + if ( results ) { + results.push.apply( results, array ); + return results; + } + + return array; +}; + +// Perform a simple check to determine if the browser is capable of +// converting a NodeList to an array using builtin methods. +// Also verifies that the returned array holds DOM nodes +// (which is not the case in the Blackberry browser) +try { + Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; + +// Provide a fallback method if it does not work +} catch( e ) { + makeArray = function( array, results ) { + var i = 0, + ret = results || []; + + if ( toString.call(array) === "[object Array]" ) { + Array.prototype.push.apply( ret, array ); + + } else { + if ( typeof array.length === "number" ) { + for ( var l = array.length; i < l; i++ ) { + ret.push( array[i] ); + } + + } else { + for ( ; array[i]; i++ ) { + ret.push( array[i] ); + } + } + } + + return ret; + }; +} + +var sortOrder, siblingCheck; + +if ( document.documentElement.compareDocumentPosition ) { + sortOrder = function( a, b ) { + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { + return a.compareDocumentPosition ? -1 : 1; + } + + return a.compareDocumentPosition(b) & 4 ? -1 : 1; + }; + +} else { + sortOrder = function( a, b ) { + // The nodes are identical, we can exit early + if ( a === b ) { + hasDuplicate = true; + return 0; + + // Fallback to using sourceIndex (in IE) if it's available on both nodes + } else if ( a.sourceIndex && b.sourceIndex ) { + return a.sourceIndex - b.sourceIndex; + } + + var al, bl, + ap = [], + bp = [], + aup = a.parentNode, + bup = b.parentNode, + cur = aup; + + // If the nodes are siblings (or identical) we can do a quick check + if ( aup === bup ) { + return siblingCheck( a, b ); + + // If no parents were found then the nodes are disconnected + } else if ( !aup ) { + return -1; + + } else if ( !bup ) { + return 1; + } + + // Otherwise they're somewhere else in the tree so we need + // to build up a full list of the parentNodes for comparison + while ( cur ) { + ap.unshift( cur ); + cur = cur.parentNode; + } + + cur = bup; + + while ( cur ) { + bp.unshift( cur ); + cur = cur.parentNode; + } + + al = ap.length; + bl = bp.length; + + // Start walking down the tree looking for a discrepancy + for ( var i = 0; i < al && i < bl; i++ ) { + if ( ap[i] !== bp[i] ) { + return siblingCheck( ap[i], bp[i] ); + } + } + + // We ended someplace up the tree so do a sibling check + return i === al ? + siblingCheck( a, bp[i], -1 ) : + siblingCheck( ap[i], b, 1 ); + }; + + siblingCheck = function( a, b, ret ) { + if ( a === b ) { + return ret; + } + + var cur = a.nextSibling; + + while ( cur ) { + if ( cur === b ) { + return -1; + } + + cur = cur.nextSibling; + } + + return 1; + }; +} + +// Check to see if the browser returns elements by name when +// querying by getElementById (and provide a workaround) +(function(){ + // We're going to inject a fake input element with a specified name + var form = document.createElement("div"), + id = "script" + (new Date()).getTime(), + root = document.documentElement; + + form.innerHTML = ""; + + // Inject it into the root element, check its status, and remove it quickly + root.insertBefore( form, root.firstChild ); + + // The workaround has to do additional checks after a getElementById + // Which slows things down for other browsers (hence the branching) + if ( document.getElementById( id ) ) { + Expr.find.ID = function( match, context, isXML ) { + if ( typeof context.getElementById !== "undefined" && !isXML ) { + var m = context.getElementById(match[1]); + + return m ? + m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? + [m] : + undefined : + []; + } + }; + + Expr.filter.ID = function( elem, match ) { + var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); + + return elem.nodeType === 1 && node && node.nodeValue === match; + }; + } + + root.removeChild( form ); + + // release memory in IE + root = form = null; +})(); + +(function(){ + // Check to see if the browser returns only elements + // when doing getElementsByTagName("*") + + // Create a fake element + var div = document.createElement("div"); + div.appendChild( document.createComment("") ); + + // Make sure no comments are found + if ( div.getElementsByTagName("*").length > 0 ) { + Expr.find.TAG = function( match, context ) { + var results = context.getElementsByTagName( match[1] ); + + // Filter out possible comments + if ( match[1] === "*" ) { + var tmp = []; + + for ( var i = 0; results[i]; i++ ) { + if ( results[i].nodeType === 1 ) { + tmp.push( results[i] ); + } + } + + results = tmp; + } + + return results; + }; + } + + // Check to see if an attribute returns normalized href attributes + div.innerHTML = ""; + + if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && + div.firstChild.getAttribute("href") !== "#" ) { + + Expr.attrHandle.href = function( elem ) { + return elem.getAttribute( "href", 2 ); + }; + } + + // release memory in IE + div = null; +})(); + +if ( document.querySelectorAll ) { + (function(){ + var oldSizzle = Sizzle, + div = document.createElement("div"), + id = "__sizzle__"; + + div.innerHTML = "

    "; + + // Safari can't handle uppercase or unicode characters when + // in quirks mode. + if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { + return; + } + + Sizzle = function( query, context, extra, seed ) { + context = context || document; + + // Only use querySelectorAll on non-XML documents + // (ID selectors don't work in non-HTML documents) + if ( !seed && !Sizzle.isXML(context) ) { + // See if we find a selector to speed up + var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query ); + + if ( match && (context.nodeType === 1 || context.nodeType === 9) ) { + // Speed-up: Sizzle("TAG") + if ( match[1] ) { + return makeArray( context.getElementsByTagName( query ), extra ); + + // Speed-up: Sizzle(".CLASS") + } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) { + return makeArray( context.getElementsByClassName( match[2] ), extra ); + } + } + + if ( context.nodeType === 9 ) { + // Speed-up: Sizzle("body") + // The body element only exists once, optimize finding it + if ( query === "body" && context.body ) { + return makeArray( [ context.body ], extra ); + + // Speed-up: Sizzle("#ID") + } else if ( match && match[3] ) { + var elem = context.getElementById( match[3] ); + + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE and Opera return items + // by name instead of ID + if ( elem.id === match[3] ) { + return makeArray( [ elem ], extra ); + } + + } else { + return makeArray( [], extra ); + } + } + + try { + return makeArray( context.querySelectorAll(query), extra ); + } catch(qsaError) {} + + // qSA works strangely on Element-rooted queries + // We can work around this by specifying an extra ID on the root + // and working up from there (Thanks to Andrew Dupont for the technique) + // IE 8 doesn't work on object elements + } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { + var oldContext = context, + old = context.getAttribute( "id" ), + nid = old || id, + hasParent = context.parentNode, + relativeHierarchySelector = /^\s*[+~]/.test( query ); + + if ( !old ) { + context.setAttribute( "id", nid ); + } else { + nid = nid.replace( /'/g, "\\$&" ); + } + if ( relativeHierarchySelector && hasParent ) { + context = context.parentNode; + } + + try { + if ( !relativeHierarchySelector || hasParent ) { + return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); + } + + } catch(pseudoError) { + } finally { + if ( !old ) { + oldContext.removeAttribute( "id" ); + } + } + } + } + + return oldSizzle(query, context, extra, seed); + }; + + for ( var prop in oldSizzle ) { + Sizzle[ prop ] = oldSizzle[ prop ]; + } + + // release memory in IE + div = null; + })(); +} + +(function(){ + var html = document.documentElement, + matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector; + + if ( matches ) { + // Check to see if it's possible to do matchesSelector + // on a disconnected node (IE 9 fails this) + var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ), + pseudoWorks = false; + + try { + // This should fail with an exception + // Gecko does not error, returns false instead + matches.call( document.documentElement, "[test!='']:sizzle" ); + + } catch( pseudoError ) { + pseudoWorks = true; + } + + Sizzle.matchesSelector = function( node, expr ) { + // Make sure that attribute selectors are quoted + expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); + + if ( !Sizzle.isXML( node ) ) { + try { + if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { + var ret = matches.call( node, expr ); + + // IE 9's matchesSelector returns false on disconnected nodes + if ( ret || !disconnectedMatch || + // As well, disconnected nodes are said to be in a document + // fragment in IE 9, so check for that + node.document && node.document.nodeType !== 11 ) { + return ret; + } + } + } catch(e) {} + } + + return Sizzle(expr, null, null, [node]).length > 0; + }; + } +})(); + +(function(){ + var div = document.createElement("div"); + + div.innerHTML = "
    "; + + // Opera can't find a second classname (in 9.6) + // Also, make sure that getElementsByClassName actually exists + if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { + return; + } + + // Safari caches class attributes, doesn't catch changes (in 3.2) + div.lastChild.className = "e"; + + if ( div.getElementsByClassName("e").length === 1 ) { + return; + } + + Expr.order.splice(1, 0, "CLASS"); + Expr.find.CLASS = function( match, context, isXML ) { + if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { + return context.getElementsByClassName(match[1]); + } + }; + + // release memory in IE + div = null; +})(); + +function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { + for ( var i = 0, l = checkSet.length; i < l; i++ ) { + var elem = checkSet[i]; + + if ( elem ) { + var match = false; + + elem = elem[dir]; + + while ( elem ) { + if ( elem[ expando ] === doneName ) { + match = checkSet[elem.sizset]; + break; + } + + if ( elem.nodeType === 1 && !isXML ){ + elem[ expando ] = doneName; + elem.sizset = i; + } + + if ( elem.nodeName.toLowerCase() === cur ) { + match = elem; + break; + } + + elem = elem[dir]; + } + + checkSet[i] = match; + } + } +} + +function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { + for ( var i = 0, l = checkSet.length; i < l; i++ ) { + var elem = checkSet[i]; + + if ( elem ) { + var match = false; + + elem = elem[dir]; + + while ( elem ) { + if ( elem[ expando ] === doneName ) { + match = checkSet[elem.sizset]; + break; + } + + if ( elem.nodeType === 1 ) { + if ( !isXML ) { + elem[ expando ] = doneName; + elem.sizset = i; + } + + if ( typeof cur !== "string" ) { + if ( elem === cur ) { + match = true; + break; + } + + } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { + match = elem; + break; + } + } + + elem = elem[dir]; + } + + checkSet[i] = match; + } + } +} + +if ( document.documentElement.contains ) { + Sizzle.contains = function( a, b ) { + return a !== b && (a.contains ? a.contains(b) : true); + }; + +} else if ( document.documentElement.compareDocumentPosition ) { + Sizzle.contains = function( a, b ) { + return !!(a.compareDocumentPosition(b) & 16); + }; + +} else { + Sizzle.contains = function() { + return false; + }; +} + +Sizzle.isXML = function( elem ) { + // documentElement is verified for cases where it doesn't yet exist + // (such as loading iframes in IE - #4833) + var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; + + return documentElement ? documentElement.nodeName !== "HTML" : false; +}; + +var posProcess = function( selector, context, seed ) { + var match, + tmpSet = [], + later = "", + root = context.nodeType ? [context] : context; + + // Position selectors must be done after the filter + // And so must :not(positional) so we move all PSEUDOs to the end + while ( (match = Expr.match.PSEUDO.exec( selector )) ) { + later += match[0]; + selector = selector.replace( Expr.match.PSEUDO, "" ); + } + + selector = Expr.relative[selector] ? selector + "*" : selector; + + for ( var i = 0, l = root.length; i < l; i++ ) { + Sizzle( selector, root[i], tmpSet, seed ); + } + + return Sizzle.filter( later, tmpSet ); +}; + +// EXPOSE +// Override sizzle attribute retrieval +Sizzle.attr = jQuery.attr; +Sizzle.selectors.attrMap = {}; +jQuery.find = Sizzle; +jQuery.expr = Sizzle.selectors; +jQuery.expr[":"] = jQuery.expr.filters; +jQuery.unique = Sizzle.uniqueSort; +jQuery.text = Sizzle.getText; +jQuery.isXMLDoc = Sizzle.isXML; +jQuery.contains = Sizzle.contains; + + +})(); + + +var runtil = /Until$/, + rparentsprev = /^(?:parents|prevUntil|prevAll)/, + // Note: This RegExp should be improved, or likely pulled from Sizzle + rmultiselector = /,/, + isSimple = /^.[^:#\[\.,]*$/, + slice = Array.prototype.slice, + POS = jQuery.expr.match.POS, + // methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true + }; + +jQuery.fn.extend({ + find: function( selector ) { + var self = this, + i, l; + + if ( typeof selector !== "string" ) { + return jQuery( selector ).filter(function() { + for ( i = 0, l = self.length; i < l; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } + } + }); + } + + var ret = this.pushStack( "", "find", selector ), + length, n, r; + + for ( i = 0, l = this.length; i < l; i++ ) { + length = ret.length; + jQuery.find( selector, this[i], ret ); + + if ( i > 0 ) { + // Make sure that the results are unique + for ( n = length; n < ret.length; n++ ) { + for ( r = 0; r < length; r++ ) { + if ( ret[r] === ret[n] ) { + ret.splice(n--, 1); + break; + } + } + } + } + } + + return ret; + }, + + has: function( target ) { + var targets = jQuery( target ); + return this.filter(function() { + for ( var i = 0, l = targets.length; i < l; i++ ) { + if ( jQuery.contains( this, targets[i] ) ) { + return true; + } + } + }); + }, + + not: function( selector ) { + return this.pushStack( winnow(this, selector, false), "not", selector); + }, + + filter: function( selector ) { + return this.pushStack( winnow(this, selector, true), "filter", selector ); + }, + + is: function( selector ) { + return !!selector && ( + typeof selector === "string" ? + // If this is a positional selector, check membership in the returned set + // so $("p:first").is("p:last") won't return true for a doc with two "p". + POS.test( selector ) ? + jQuery( selector, this.context ).index( this[0] ) >= 0 : + jQuery.filter( selector, this ).length > 0 : + this.filter( selector ).length > 0 ); + }, + + closest: function( selectors, context ) { + var ret = [], i, l, cur = this[0]; + + // Array (deprecated as of jQuery 1.7) + if ( jQuery.isArray( selectors ) ) { + var level = 1; + + while ( cur && cur.ownerDocument && cur !== context ) { + for ( i = 0; i < selectors.length; i++ ) { + + if ( jQuery( cur ).is( selectors[ i ] ) ) { + ret.push({ selector: selectors[ i ], elem: cur, level: level }); + } + } + + cur = cur.parentNode; + level++; + } + + return ret; + } + + // String + var pos = POS.test( selectors ) || typeof selectors !== "string" ? + jQuery( selectors, context || this.context ) : + 0; + + for ( i = 0, l = this.length; i < l; i++ ) { + cur = this[i]; + + while ( cur ) { + if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { + ret.push( cur ); + break; + + } else { + cur = cur.parentNode; + if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) { + break; + } + } + } + } + + ret = ret.length > 1 ? jQuery.unique( ret ) : ret; + + return this.pushStack( ret, "closest", selectors ); + }, + + // Determine the position of an element within + // the matched set of elements + index: function( elem ) { + + // No argument, return index in parent + if ( !elem ) { + return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1; + } + + // index in selector + if ( typeof elem === "string" ) { + return jQuery.inArray( this[0], jQuery( elem ) ); + } + + // Locate the position of the desired element + return jQuery.inArray( + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[0] : elem, this ); + }, + + add: function( selector, context ) { + var set = typeof selector === "string" ? + jQuery( selector, context ) : + jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), + all = jQuery.merge( this.get(), set ); + + return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? + all : + jQuery.unique( all ) ); + }, + + andSelf: function() { + return this.add( this.prevObject ); + } +}); + +// A painfully simple check to see if an element is disconnected +// from a document (should be improved, where feasible). +function isDisconnected( node ) { + return !node || !node.parentNode || node.parentNode.nodeType === 11; +} + +jQuery.each({ + parent: function( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents: function( elem ) { + return jQuery.dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, i, until ) { + return jQuery.dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return jQuery.nth( elem, 2, "nextSibling" ); + }, + prev: function( elem ) { + return jQuery.nth( elem, 2, "previousSibling" ); + }, + nextAll: function( elem ) { + return jQuery.dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return jQuery.dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, i, until ) { + return jQuery.dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, i, until ) { + return jQuery.dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return jQuery.sibling( elem.parentNode.firstChild, elem ); + }, + children: function( elem ) { + return jQuery.sibling( elem.firstChild ); + }, + contents: function( elem ) { + return jQuery.nodeName( elem, "iframe" ) ? + elem.contentDocument || elem.contentWindow.document : + jQuery.makeArray( elem.childNodes ); + } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var ret = jQuery.map( this, fn, until ); + + if ( !runtil.test( name ) ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + ret = jQuery.filter( selector, ret ); + } + + ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; + + if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { + ret = ret.reverse(); + } + + return this.pushStack( ret, name, slice.call( arguments ).join(",") ); + }; +}); + +jQuery.extend({ + filter: function( expr, elems, not ) { + if ( not ) { + expr = ":not(" + expr + ")"; + } + + return elems.length === 1 ? + jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : + jQuery.find.matches(expr, elems); + }, + + dir: function( elem, dir, until ) { + var matched = [], + cur = elem[ dir ]; + + while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { + if ( cur.nodeType === 1 ) { + matched.push( cur ); + } + cur = cur[dir]; + } + return matched; + }, + + nth: function( cur, result, dir, elem ) { + result = result || 1; + var num = 0; + + for ( ; cur; cur = cur[dir] ) { + if ( cur.nodeType === 1 && ++num === result ) { + break; + } + } + + return cur; + }, + + sibling: function( n, elem ) { + var r = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + r.push( n ); + } + } + + return r; + } +}); + +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, keep ) { + + // Can't pass null or undefined to indexOf in Firefox 4 + // Set to 0 to skip string check + qualifier = qualifier || 0; + + if ( jQuery.isFunction( qualifier ) ) { + return jQuery.grep(elements, function( elem, i ) { + var retVal = !!qualifier.call( elem, i, elem ); + return retVal === keep; + }); + + } else if ( qualifier.nodeType ) { + return jQuery.grep(elements, function( elem, i ) { + return ( elem === qualifier ) === keep; + }); + + } else if ( typeof qualifier === "string" ) { + var filtered = jQuery.grep(elements, function( elem ) { + return elem.nodeType === 1; + }); + + if ( isSimple.test( qualifier ) ) { + return jQuery.filter(qualifier, filtered, !keep); + } else { + qualifier = jQuery.filter( qualifier, filtered ); + } + } + + return jQuery.grep(elements, function( elem, i ) { + return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; + }); +} + + + + +function createSafeFragment( document ) { + var list = nodeNames.split( "|" ), + safeFrag = document.createDocumentFragment(); + + if ( safeFrag.createElement ) { + while ( list.length ) { + safeFrag.createElement( + list.pop() + ); + } + } + return safeFrag; +} + +var nodeNames = "abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|" + + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", + rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, + rleadingWhitespace = /^\s+/, + rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, + rtagName = /<([\w:]+)/, + rtbody = /", "" ], + legend: [ 1, "
    ", "
    " ], + thead: [ 1, "", "
    " ], + tr: [ 2, "", "
    " ], + td: [ 3, "", "
    " ], + col: [ 2, "", "
    " ], + area: [ 1, "", "" ], + _default: [ 0, "", "" ] + }, + safeFragment = createSafeFragment( document ); + +wrapMap.optgroup = wrapMap.option; +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + +// IE can't serialize and