4 * Copyright(c) 2006-2007, Ext JS, LLC.
6 * Originally Released Under LGPL - original licence link has changed is not relivant.
9 * <script type="text/javascript">
17 window["undefined"] = window["undefined"];
21 * Roo core utilities and functions.
26 * Copies all the properties of config to obj.
27 * @param {Object} obj The receiver of the properties
28 * @param {Object} config The source of the properties
29 * @param {Object} defaults A different object that will also be applied for default values
30 * @return {Object} returns obj
35 Roo.apply = function(o, c, defaults){
37 // no "this" reference for friendly out of scope calls
38 Roo.apply(o, defaults);
40 if(o && c && typeof c == 'object'){
51 var ua = navigator.userAgent.toLowerCase();
53 var isStrict = document.compatMode == "CSS1Compat",
54 isOpera = ua.indexOf("opera") > -1,
55 isSafari = (/webkit|khtml/).test(ua),
56 isIE = ua.indexOf("msie") > -1,
57 isIE7 = ua.indexOf("msie 7") > -1,
58 isGecko = !isSafari && ua.indexOf("gecko") > -1,
59 isBorderBox = isIE && !isStrict,
60 isWindows = (ua.indexOf("windows") != -1 || ua.indexOf("win32") != -1),
61 isMac = (ua.indexOf("macintosh") != -1 || ua.indexOf("mac os x") != -1),
62 isLinux = (ua.indexOf("linux") != -1),
63 isSecure = window.location.href.toLowerCase().indexOf("https") === 0,
64 isTouch = 'ontouchstart' in window || window.DocumentTouch && document instanceof DocumentTouch;
65 // remove css image flicker
68 document.execCommand("BackgroundImageCache", false, true);
74 * True if the browser is in strict mode
79 * True if the page is running over SSL
84 * True when the document is fully initialized and ready for action
89 * Turn on debugging output (currently only the factory uses this)
96 * True to automatically uncache orphaned Roo.Elements periodically (defaults to true)
99 enableGarbageCollector : true,
102 * True to automatically purge event listeners after uncaching an element (defaults to false).
103 * Note: this only happens if enableGarbageCollector is true.
106 enableListenerCollection:false,
109 * URL to a blank file used by Roo when in secure mode for iframe src and onReady src to prevent
110 * the IE insecure content warning (defaults to javascript:false).
113 SSL_SECURE_URL : "javascript:false",
116 * URL to a 1x1 transparent gif image used by Roo to create inline icons with CSS background images. (Defaults to
117 * "http://Roojs.com/s.gif" and you should change this to a URL on your server).
120 BLANK_IMAGE_URL : "http:/"+"/localhost/s.gif",
122 emptyFn : function(){},
125 * Copies all the properties of config to obj if they don't already exist.
126 * @param {Object} obj The receiver of the properties
127 * @param {Object} config The source of the properties
128 * @return {Object} returns obj
130 applyIf : function(o, c){
133 if(typeof o[p] == "undefined"){ o[p] = c[p]; }
140 * Applies event listeners to elements by selectors when the document is ready.
141 * The event name is specified with an @ suffix.
144 // add a listener for click on all anchors in element with id foo
145 '#foo a@click' : function(e, t){
149 // add the same listener to multiple selectors (separated by comma BEFORE the @)
150 '#foo a, #bar span.some-class@mouseover' : function(){
155 * @param {Object} obj The list of behaviors to apply
157 addBehaviors : function(o){
159 Roo.onReady(function(){
164 var cache = {}; // simple cache for applying multiple behaviors to same selector does query multiple times
166 var parts = b.split('@');
167 if(parts[1]){ // for Object prototype breakers
170 cache[s] = Roo.select(s);
172 cache[s].on(parts[1], o[b]);
179 * Generates unique ids. If the element already has an id, it is unchanged
180 * @param {String/HTMLElement/Element} el (optional) The element to generate an id for
181 * @param {String} prefix (optional) Id prefix (defaults "Roo-gen")
182 * @return {String} The generated Id.
184 id : function(el, prefix){
185 prefix = prefix || "roo-gen";
187 var id = prefix + (++idSeed);
188 return el ? (el.id ? el.id : (el.id = id)) : id;
193 * Extends one class with another class and optionally overrides members with the passed literal. This class
194 * also adds the function "override()" to the class that can be used to override
195 * members on an instance.
196 * @param {Object} subclass The class inheriting the functionality
197 * @param {Object} superclass The class being extended
198 * @param {Object} overrides (optional) A literal with members
203 var io = function(o){
208 return function(sb, sp, overrides){
209 if(typeof sp == 'object'){ // eg. prototype, rather than function constructor..
212 sb = function(){sp.apply(this, arguments);};
214 var F = function(){}, sbp, spp = sp.prototype;
216 sbp = sb.prototype = new F();
220 if(spp.constructor == Object.prototype.constructor){
225 sb.override = function(o){
229 Roo.override(sb, overrides);
235 * Adds a list of functions to the prototype of an existing class, overwriting any existing methods with the same name.
237 Roo.override(MyClass, {
238 newMethod1: function(){
241 newMethod2: function(foo){
246 * @param {Object} origclass The class to override
247 * @param {Object} overrides The list of functions to add to origClass. This should be specified as an object literal
248 * containing one or more methods.
251 override : function(origclass, overrides){
253 var p = origclass.prototype;
254 for(var method in overrides){
255 p[method] = overrides[method];
260 * Creates namespaces to be used for scoping variables and classes so that they are not global. Usage:
262 Roo.namespace('Company', 'Company.data');
263 Company.Widget = function() { ... }
264 Company.data.CustomStore = function(config) { ... }
266 * @param {String} namespace1
267 * @param {String} namespace2
268 * @param {String} etc
271 namespace : function(){
272 var a=arguments, o=null, i, j, d, rt;
273 for (i=0; i<a.length; ++i) {
277 eval('if (typeof ' + rt + ' == "undefined"){' + rt + ' = {};} o = ' + rt + ';');
278 for (j=1; j<d.length; ++j) {
279 o[d[j]]=o[d[j]] || {};
285 * Creates namespaces to be used for scoping variables and classes so that they are not global. Usage:
287 Roo.factory({ xns: Roo.data, xtype : 'Store', .....});
288 Roo.factory(conf, Roo.data);
290 * @param {String} classname
291 * @param {String} namespace (optional)
295 factory : function(c, ns)
297 // no xtype, no ns or c.xns - or forced off by c.xns
298 if (!c.xtype || (!ns && !c.xns) || (c.xns === false)) { // not enough info...
301 ns = c.xns ? c.xns : ns; // if c.xns is set, then use that..
302 if (c.constructor == ns[c.xtype]) {// already created...
306 if (Roo.debug) Roo.log("Roo.Factory(" + c.xtype + ")");
307 var ret = new ns[c.xtype](c);
311 c.xns = false; // prevent recursion..
315 * Logs to console if it can.
317 * @param {String|Object} string
322 if ((typeof(console) == 'undefined') || (typeof(console.log) == 'undefined')) {
329 * Takes an object and converts it to an encoded URL. e.g. Roo.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.
333 urlEncode : function(o){
339 var ov = o[key], k = Roo.encodeURIComponent(key);
340 var type = typeof ov;
341 if(type == 'undefined'){
343 }else if(type != "function" && type != "object"){
344 buf.push(k, "=", Roo.encodeURIComponent(ov), "&");
345 }else if(ov instanceof Array){
347 for(var i = 0, len = ov.length; i < len; i++) {
348 buf.push(k, "=", Roo.encodeURIComponent(ov[i] === undefined ? '' : ov[i]), "&");
359 * Safe version of encodeURIComponent
360 * @param {String} data
364 encodeURIComponent : function (data)
367 return encodeURIComponent(data);
368 } catch(e) {} // should be an uri encode error.
370 if (data == '' || data == null){
373 // http://stackoverflow.com/questions/2596483/unicode-and-uri-encoding-decoding-and-escaping-in-javascript
374 function nibble_to_hex(nibble){
375 var chars = '0123456789ABCDEF';
376 return chars.charAt(nibble);
378 data = data.toString();
380 for(var i=0; i<data.length; i++){
381 var c = data.charCodeAt(i);
382 var bs = new Array();
385 bs[0] = 0xF0 | ((c & 0x1C0000) >>> 18);
386 bs[1] = 0x80 | ((c & 0x3F000) >>> 12);
387 bs[2] = 0x80 | ((c & 0xFC0) >>> 6);
388 bs[3] = 0x80 | (c & 0x3F);
389 }else if (c > 0x800){
391 bs[0] = 0xE0 | ((c & 0xF000) >>> 12);
392 bs[1] = 0x80 | ((c & 0xFC0) >>> 6);
393 bs[2] = 0x80 | (c & 0x3F);
396 bs[0] = 0xC0 | ((c & 0x7C0) >>> 6);
397 bs[1] = 0x80 | (c & 0x3F);
402 for(var j=0; j<bs.length; j++){
404 var hex = nibble_to_hex((b & 0xF0) >>> 4)
405 + nibble_to_hex(b &0x0F);
414 * Takes an encoded URL and and converts it to an object. e.g. Roo.urlDecode("foo=1&bar=2"); would return {foo: 1, bar: 2} or Roo.urlDecode("foo=1&bar=2&bar=3&bar=4", true); would return {foo: 1, bar: [2, 3, 4]}.
415 * @param {String} string
416 * @param {Boolean} overwrite (optional) Items of the same name will overwrite previous values instead of creating an an array (Defaults to false).
417 * @return {Object} A literal with members
419 urlDecode : function(string, overwrite){
420 if(!string || !string.length){
424 var pairs = string.split('&');
425 var pair, name, value;
426 for(var i = 0, len = pairs.length; i < len; i++){
427 pair = pairs[i].split('=');
428 name = decodeURIComponent(pair[0]);
429 value = decodeURIComponent(pair[1]);
430 if(overwrite !== true){
431 if(typeof obj[name] == "undefined"){
433 }else if(typeof obj[name] == "string"){
434 obj[name] = [obj[name]];
435 obj[name].push(value);
437 obj[name].push(value);
447 * Iterates an array calling the passed function with each item, stopping if your function returns false. If the
448 * passed array is not really an array, your function is called once with it.
449 * The supplied function is called with (Object item, Number index, Array allItems).
450 * @param {Array/NodeList/Mixed} array
451 * @param {Function} fn
452 * @param {Object} scope
454 each : function(array, fn, scope){
455 if(typeof array.length == "undefined" || typeof array == "string"){
458 for(var i = 0, len = array.length; i < len; i++){
459 if(fn.call(scope || array[i], array[i], i, array) === false){ return i; };
464 combine : function(){
465 var as = arguments, l = as.length, r = [];
466 for(var i = 0; i < l; i++){
468 if(a instanceof Array){
470 }else if(a.length !== undefined && !a.substr){
471 r = r.concat(Array.prototype.slice.call(a, 0));
480 * Escapes the passed string for use in a regular expression
481 * @param {String} str
484 escapeRe : function(s) {
485 return s.replace(/([.*+?^${}()|[\]\/\\])/g, "\\$1");
489 callback : function(cb, scope, args, delay){
490 if(typeof cb == "function"){
492 cb.defer(delay, scope, args || []);
494 cb.apply(scope, args || []);
500 * Return the dom node for the passed string (id), dom node, or Roo.Element
501 * @param {String/HTMLElement/Roo.Element} el
502 * @return HTMLElement
504 getDom : function(el){
508 return el.dom ? el.dom : (typeof el == 'string' ? document.getElementById(el) : el);
512 * Shorthand for {@link Roo.ComponentMgr#get}
514 * @return Roo.Component
516 getCmp : function(id){
517 return Roo.ComponentMgr.get(id);
520 num : function(v, defaultValue){
521 if(typeof v != 'number'){
527 destroy : function(){
528 for(var i = 0, a = arguments, len = a.length; i < len; i++) {
532 as.removeAllListeners();
536 if(typeof as.purgeListeners == 'function'){
539 if(typeof as.destroy == 'function'){
546 // inpired by a similar function in mootools library
548 * Returns the type of object that is passed in. If the object passed in is null or undefined it
549 * return false otherwise it returns one of the following values:<ul>
550 * <li><b>string</b>: If the object passed is a string</li>
551 * <li><b>number</b>: If the object passed is a number</li>
552 * <li><b>boolean</b>: If the object passed is a boolean value</li>
553 * <li><b>function</b>: If the object passed is a function reference</li>
554 * <li><b>object</b>: If the object passed is an object</li>
555 * <li><b>array</b>: If the object passed is an array</li>
556 * <li><b>regexp</b>: If the object passed is a regular expression</li>
557 * <li><b>element</b>: If the object passed is a DOM Element</li>
558 * <li><b>nodelist</b>: If the object passed is a DOM NodeList</li>
559 * <li><b>textnode</b>: If the object passed is a DOM text node and contains something other than whitespace</li>
560 * <li><b>whitespace</b>: If the object passed is a DOM text node and contains only whitespace</li>
561 * @param {Mixed} object
565 if(o === undefined || o === null){
572 if(t == 'object' && o.nodeName) {
574 case 1: return 'element';
575 case 3: return (/\S/).test(o.nodeValue) ? 'textnode' : 'whitespace';
578 if(t == 'object' || t == 'function') {
579 switch(o.constructor) {
580 case Array: return 'array';
581 case RegExp: return 'regexp';
583 if(typeof o.length == 'number' && typeof o.item == 'function') {
591 * Returns true if the passed value is null, undefined or an empty string (optional).
592 * @param {Mixed} value The value to test
593 * @param {Boolean} allowBlank (optional) Pass true if an empty string is not considered empty
596 isEmpty : function(v, allowBlank){
597 return v === null || v === undefined || (!allowBlank ? v === '' : false);
611 isBorderBox : isBorderBox,
613 isWindows : isWindows,
622 * By default, Ext intelligently decides whether floating elements should be shimmed. If you are using flash,
623 * you may want to set this to true.
626 useShims : ((isIE && !isIE7) || (isGecko && isMac)),
631 * Selects a single element as a Roo Element
632 * This is about as close as you can get to jQuery's $('do crazy stuff')
633 * @param {String} selector The selector/xpath query
634 * @param {Node} root (optional) The start of the query (defaults to document).
635 * @return {Roo.Element}
637 selectNode : function(selector, root)
639 var node = Roo.DomQuery.selectNode(selector,root);
640 return node ? Roo.get(node) : new Roo.Element(false);
648 Roo.namespace("Roo", "Roo.util", "Roo.grid", "Roo.dd", "Roo.tree", "Roo.data",
649 "Roo.form", "Roo.menu", "Roo.state", "Roo.lib", "Roo.layout", "Roo.app", "Roo.ux");
652 * Ext JS Library 1.1.1
653 * Copyright(c) 2006-2007, Ext JS, LLC.
655 * Originally Released Under LGPL - original licence link has changed is not relivant.
658 * <script type="text/javascript">
662 // wrappedn so fnCleanup is not in global scope...
664 function fnCleanUp() {
665 var p = Function.prototype;
666 delete p.createSequence;
668 delete p.createDelegate;
669 delete p.createCallback;
670 delete p.createInterceptor;
672 window.detachEvent("onunload", fnCleanUp);
674 window.attachEvent("onunload", fnCleanUp);
681 * These functions are available on every Function object (any JavaScript function).
683 Roo.apply(Function.prototype, {
685 * Creates a callback that passes arguments[0], arguments[1], arguments[2], ...
686 * Call directly on any function. Example: <code>myFunction.createCallback(myarg, myarg2)</code>
687 * Will create a function that is bound to those 2 args.
688 * @return {Function} The new function
690 createCallback : function(/*args...*/){
691 // make args available, in function below
692 var args = arguments;
695 return method.apply(window, args);
700 * Creates a delegate (callback) that sets the scope to obj.
701 * Call directly on any function. Example: <code>this.myFunction.createDelegate(this)</code>
702 * Will create a function that is automatically scoped to this.
703 * @param {Object} obj (optional) The object for which the scope is set
704 * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
705 * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
706 * if a number the args are inserted at the specified position
707 * @return {Function} The new function
709 createDelegate : function(obj, args, appendArgs){
712 var callArgs = args || arguments;
713 if(appendArgs === true){
714 callArgs = Array.prototype.slice.call(arguments, 0);
715 callArgs = callArgs.concat(args);
716 }else if(typeof appendArgs == "number"){
717 callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first
718 var applyArgs = [appendArgs, 0].concat(args); // create method call params
719 Array.prototype.splice.apply(callArgs, applyArgs); // splice them in
721 return method.apply(obj || window, callArgs);
726 * Calls this function after the number of millseconds specified.
727 * @param {Number} millis The number of milliseconds for the setTimeout call (if 0 the function is executed immediately)
728 * @param {Object} obj (optional) The object for which the scope is set
729 * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
730 * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
731 * if a number the args are inserted at the specified position
732 * @return {Number} The timeout id that can be used with clearTimeout
734 defer : function(millis, obj, args, appendArgs){
735 var fn = this.createDelegate(obj, args, appendArgs);
737 return setTimeout(fn, millis);
743 * Create a combined function call sequence of the original function + the passed function.
744 * The resulting function returns the results of the original function.
745 * The passed fcn is called with the parameters of the original function
746 * @param {Function} fcn The function to sequence
747 * @param {Object} scope (optional) The scope of the passed fcn (Defaults to scope of original function or window)
748 * @return {Function} The new function
750 createSequence : function(fcn, scope){
751 if(typeof fcn != "function"){
756 var retval = method.apply(this || window, arguments);
757 fcn.apply(scope || this || window, arguments);
763 * Creates an interceptor function. The passed fcn is called before the original one. If it returns false, the original one is not called.
764 * The resulting function returns the results of the original function.
765 * The passed fcn is called with the parameters of the original function.
767 * @param {Function} fcn The function to call before the original
768 * @param {Object} scope (optional) The scope of the passed fcn (Defaults to scope of original function or window)
769 * @return {Function} The new function
771 createInterceptor : function(fcn, scope){
772 if(typeof fcn != "function"){
779 if(fcn.apply(scope || this || window, arguments) === false){
782 return method.apply(this || window, arguments);
788 * Ext JS Library 1.1.1
789 * Copyright(c) 2006-2007, Ext JS, LLC.
791 * Originally Released Under LGPL - original licence link has changed is not relivant.
794 * <script type="text/javascript">
797 Roo.applyIf(String, {
802 * Escapes the passed string for ' and \
803 * @param {String} string The string to escape
804 * @return {String} The escaped string
807 escape : function(string) {
808 return string.replace(/('|\\)/g, "\\$1");
812 * Pads the left side of a string with a specified character. This is especially useful
813 * for normalizing number and date strings. Example usage:
815 var s = String.leftPad('123', 5, '0');
816 // s now contains the string: '00123'
818 * @param {String} string The original string
819 * @param {Number} size The total length of the output string
820 * @param {String} char (optional) The character with which to pad the original string (defaults to empty string " ")
821 * @return {String} The padded string
824 leftPad : function (val, size, ch) {
825 var result = new String(val);
826 if(ch === null || ch === undefined || ch === '') {
829 while (result.length < size) {
830 result = ch + result;
836 * Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens. Each
837 * token must be unique, and must increment in the format {0}, {1}, etc. Example usage:
839 var cls = 'my-class', text = 'Some text';
840 var s = String.format('<div class="{0}">{1}</div>', cls, text);
841 // s now contains the string: '<div class="my-class">Some text</div>'
843 * @param {String} string The tokenized string to be formatted
844 * @param {String} value1 The value to replace token {0}
845 * @param {String} value2 Etc...
846 * @return {String} The formatted string
849 format : function(format){
850 var args = Array.prototype.slice.call(arguments, 1);
851 return format.replace(/\{(\d+)\}/g, function(m, i){
852 return Roo.util.Format.htmlEncode(args[i]);
858 * Utility function that allows you to easily switch a string between two alternating values. The passed value
859 * is compared to the current string, and if they are equal, the other value that was passed in is returned. If
860 * they are already different, the first value passed in is returned. Note that this method returns the new value
861 * but does not change the current string.
863 // alternate sort directions
864 sort = sort.toggle('ASC', 'DESC');
866 // instead of conditional logic:
867 sort = (sort == 'ASC' ? 'DESC' : 'ASC');
869 * @param {String} value The value to compare to the current string
870 * @param {String} other The new value to use if the string already equals the first value passed in
871 * @return {String} The new value
874 String.prototype.toggle = function(value, other){
875 return this == value ? other : value;
878 * Ext JS Library 1.1.1
879 * Copyright(c) 2006-2007, Ext JS, LLC.
881 * Originally Released Under LGPL - original licence link has changed is not relivant.
884 * <script type="text/javascript">
890 Roo.applyIf(Number.prototype, {
892 * Checks whether or not the current number is within a desired range. If the number is already within the
893 * range it is returned, otherwise the min or max value is returned depending on which side of the range is
894 * exceeded. Note that this method returns the constrained value but does not change the current number.
895 * @param {Number} min The minimum number in the range
896 * @param {Number} max The maximum number in the range
897 * @return {Number} The constrained value if outside the range, otherwise the current value
899 constrain : function(min, max){
900 return Math.min(Math.max(this, min), max);
904 * Ext JS Library 1.1.1
905 * Copyright(c) 2006-2007, Ext JS, LLC.
907 * Originally Released Under LGPL - original licence link has changed is not relivant.
910 * <script type="text/javascript">
915 Roo.applyIf(Array.prototype, {
917 * Checks whether or not the specified object exists in the array.
918 * @param {Object} o The object to check for
919 * @return {Number} The index of o in the array (or -1 if it is not found)
921 indexOf : function(o){
922 for (var i = 0, len = this.length; i < len; i++){
923 if(this[i] == o) return i;
929 * Removes the specified object from the array. If the object is not found nothing happens.
930 * @param {Object} o The object to remove
932 remove : function(o){
933 var index = this.indexOf(o);
935 this.splice(index, 1);
939 * Map (JS 1.6 compatibility)
940 * @param {Function} function to call
944 var len = this.length >>> 0;
945 if (typeof fun != "function")
946 throw new TypeError();
948 var res = new Array(len);
949 var thisp = arguments[1];
950 for (var i = 0; i < len; i++)
953 res[i] = fun.call(thisp, this[i], i, this);
964 * Ext JS Library 1.1.1
965 * Copyright(c) 2006-2007, Ext JS, LLC.
967 * Originally Released Under LGPL - original licence link has changed is not relivant.
970 * <script type="text/javascript">
976 * The date parsing and format syntax is a subset of
977 * <a href="http://www.php.net/date">PHP's date() function</a>, and the formats that are
978 * supported will provide results equivalent to their PHP versions.
980 * Following is the list of all currently supported formats:
983 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'
985 Format Output Description
986 ------ ---------- --------------------------------------------------------------
987 d 10 Day of the month, 2 digits with leading zeros
988 D Wed A textual representation of a day, three letters
989 j 10 Day of the month without leading zeros
990 l Wednesday A full textual representation of the day of the week
991 S th English ordinal day of month suffix, 2 chars (use with j)
992 w 3 Numeric representation of the day of the week
993 z 9 The julian date, or day of the year (0-365)
994 W 01 ISO-8601 2-digit week number of year, weeks starting on Monday (00-52)
995 F January A full textual representation of the month
996 m 01 Numeric representation of a month, with leading zeros
997 M Jan Month name abbreviation, three letters
998 n 1 Numeric representation of a month, without leading zeros
999 t 31 Number of days in the given month
1000 L 0 Whether it's a leap year (1 if it is a leap year, else 0)
1001 Y 2007 A full numeric representation of a year, 4 digits
1002 y 07 A two digit representation of a year
1003 a pm Lowercase Ante meridiem and Post meridiem
1004 A PM Uppercase Ante meridiem and Post meridiem
1005 g 3 12-hour format of an hour without leading zeros
1006 G 15 24-hour format of an hour without leading zeros
1007 h 03 12-hour format of an hour with leading zeros
1008 H 15 24-hour format of an hour with leading zeros
1009 i 05 Minutes with leading zeros
1010 s 01 Seconds, with leading zeros
1011 O -0600 Difference to Greenwich time (GMT) in hours (Allows +08, without minutes)
1012 P -06:00 Difference to Greenwich time (GMT) with colon between hours and minutes
1013 T CST Timezone setting of the machine running the code
1014 Z -21600 Timezone offset in seconds (negative if west of UTC, positive if east)
1017 * Example usage (note that you must escape format specifiers with '\\' to render them as character literals):
1019 var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
1020 document.write(dt.format('Y-m-d')); //2007-01-10
1021 document.write(dt.format('F j, Y, g:i a')); //January 10, 2007, 3:05 pm
1022 document.write(dt.format('l, \\t\\he dS of F Y h:i:s A')); //Wednesday, the 10th of January 2007 03:05:01 PM
1025 * Here are some standard date/time patterns that you might find helpful. They
1026 * are not part of the source of Date.js, but to use them you can simply copy this
1027 * block of code into any script that is included after Date.js and they will also become
1028 * globally available on the Date object. Feel free to add or remove patterns as needed in your code.
1031 ISO8601Long:"Y-m-d H:i:s",
1032 ISO8601Short:"Y-m-d",
1034 LongDate: "l, F d, Y",
1035 FullDateTime: "l, F d, Y g:i:s A",
1038 LongTime: "g:i:s A",
1039 SortableDateTime: "Y-m-d\\TH:i:s",
1040 UniversalSortableDateTime: "Y-m-d H:i:sO",
1047 var dt = new Date();
1048 document.write(dt.format(Date.patterns.ShortDate));
1053 * Most of the date-formatting functions below are the excellent work of Baron Schwartz.
1054 * They generate precompiled functions from date formats instead of parsing and
1055 * processing the pattern every time you format a date. These functions are available
1056 * on every Date object (any javascript function).
1058 * The original article and download are here:
1059 * http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/
1066 Returns the number of milliseconds between this date and date
1067 @param {Date} date (optional) Defaults to now
1068 @return {Number} The diff in milliseconds
1069 @member Date getElapsed
1071 Date.prototype.getElapsed = function(date) {
1072 return Math.abs((date || new Date()).getTime()-this.getTime());
1074 // was in date file..
1078 Date.parseFunctions = {count:0};
1080 Date.parseRegexes = [];
1082 Date.formatFunctions = {count:0};
1085 Date.prototype.dateFormat = function(format) {
1086 if (Date.formatFunctions[format] == null) {
1087 Date.createNewFormat(format);
1089 var func = Date.formatFunctions[format];
1090 return this[func]();
1095 * Formats a date given the supplied format string
1096 * @param {String} format The format string
1097 * @return {String} The formatted date
1100 Date.prototype.format = Date.prototype.dateFormat;
1103 Date.createNewFormat = function(format) {
1104 var funcName = "format" + Date.formatFunctions.count++;
1105 Date.formatFunctions[format] = funcName;
1106 var code = "Date.prototype." + funcName + " = function(){return ";
1107 var special = false;
1109 for (var i = 0; i < format.length; ++i) {
1110 ch = format.charAt(i);
1111 if (!special && ch == "\\") {
1116 code += "'" + String.escape(ch) + "' + ";
1119 code += Date.getFormatCode(ch);
1122 /** eval:var:zzzzzzzzzzzzz */
1123 eval(code.substring(0, code.length - 3) + ";}");
1127 Date.getFormatCode = function(character) {
1128 switch (character) {
1130 return "String.leftPad(this.getDate(), 2, '0') + ";
1132 return "Date.dayNames[this.getDay()].substring(0, 3) + ";
1134 return "this.getDate() + ";
1136 return "Date.dayNames[this.getDay()] + ";
1138 return "this.getSuffix() + ";
1140 return "this.getDay() + ";
1142 return "this.getDayOfYear() + ";
1144 return "this.getWeekOfYear() + ";
1146 return "Date.monthNames[this.getMonth()] + ";
1148 return "String.leftPad(this.getMonth() + 1, 2, '0') + ";
1150 return "Date.monthNames[this.getMonth()].substring(0, 3) + ";
1152 return "(this.getMonth() + 1) + ";
1154 return "this.getDaysInMonth() + ";
1156 return "(this.isLeapYear() ? 1 : 0) + ";
1158 return "this.getFullYear() + ";
1160 return "('' + this.getFullYear()).substring(2, 4) + ";
1162 return "(this.getHours() < 12 ? 'am' : 'pm') + ";
1164 return "(this.getHours() < 12 ? 'AM' : 'PM') + ";
1166 return "((this.getHours() % 12) ? this.getHours() % 12 : 12) + ";
1168 return "this.getHours() + ";
1170 return "String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0') + ";
1172 return "String.leftPad(this.getHours(), 2, '0') + ";
1174 return "String.leftPad(this.getMinutes(), 2, '0') + ";
1176 return "String.leftPad(this.getSeconds(), 2, '0') + ";
1178 return "this.getGMTOffset() + ";
1180 return "this.getGMTColonOffset() + ";
1182 return "this.getTimezone() + ";
1184 return "(this.getTimezoneOffset() * -60) + ";
1186 return "'" + String.escape(character) + "' + ";
1191 * Parses the passed string using the specified format. Note that this function expects dates in normal calendar
1192 * format, meaning that months are 1-based (1 = January) and not zero-based like in JavaScript dates. Any part of
1193 * the date format that is not specified will default to the current date value for that part. Time parts can also
1194 * be specified, but default to 0. Keep in mind that the input date string must precisely match the specified format
1195 * string or the parse operation will fail.
1198 //dt = Fri May 25 2007 (current date)
1199 var dt = new Date();
1201 //dt = Thu May 25 2006 (today's month/day in 2006)
1202 dt = Date.parseDate("2006", "Y");
1204 //dt = Sun Jan 15 2006 (all date parts specified)
1205 dt = Date.parseDate("2006-1-15", "Y-m-d");
1207 //dt = Sun Jan 15 2006 15:20:01 GMT-0600 (CST)
1208 dt = Date.parseDate("2006-1-15 3:20:01 PM", "Y-m-d h:i:s A" );
1210 * @param {String} input The unparsed date as a string
1211 * @param {String} format The format the date is in
1212 * @return {Date} The parsed date
1215 Date.parseDate = function(input, format) {
1216 if (Date.parseFunctions[format] == null) {
1217 Date.createParser(format);
1219 var func = Date.parseFunctions[format];
1220 return Date[func](input);
1225 Date.createParser = function(format) {
1226 var funcName = "parse" + Date.parseFunctions.count++;
1227 var regexNum = Date.parseRegexes.length;
1228 var currentGroup = 1;
1229 Date.parseFunctions[format] = funcName;
1231 var code = "Date." + funcName + " = function(input){\n"
1232 + "var y = -1, m = -1, d = -1, h = -1, i = -1, s = -1, o, z, v;\n"
1233 + "var d = new Date();\n"
1234 + "y = d.getFullYear();\n"
1235 + "m = d.getMonth();\n"
1236 + "d = d.getDate();\n"
1237 + "var results = input.match(Date.parseRegexes[" + regexNum + "]);\n"
1238 + "if (results && results.length > 0) {";
1241 var special = false;
1243 for (var i = 0; i < format.length; ++i) {
1244 ch = format.charAt(i);
1245 if (!special && ch == "\\") {
1250 regex += String.escape(ch);
1253 var obj = Date.formatCodeToRegex(ch, currentGroup);
1254 currentGroup += obj.g;
1256 if (obj.g && obj.c) {
1262 code += "if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0)\n"
1263 + "{v = new Date(y, m, d, h, i, s);}\n"
1264 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0)\n"
1265 + "{v = new Date(y, m, d, h, i);}\n"
1266 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0)\n"
1267 + "{v = new Date(y, m, d, h);}\n"
1268 + "else if (y >= 0 && m >= 0 && d > 0)\n"
1269 + "{v = new Date(y, m, d);}\n"
1270 + "else if (y >= 0 && m >= 0)\n"
1271 + "{v = new Date(y, m);}\n"
1272 + "else if (y >= 0)\n"
1273 + "{v = new Date(y);}\n"
1274 + "}return (v && (z || o))?\n" // favour UTC offset over GMT offset
1275 + " ((z)? v.add(Date.SECOND, (v.getTimezoneOffset() * 60) + (z*1)) :\n" // reset to UTC, then add offset
1276 + " v.add(Date.HOUR, (v.getGMTOffset() / 100) + (o / -100))) : v\n" // reset to GMT, then add offset
1279 Date.parseRegexes[regexNum] = new RegExp("^" + regex + "$");
1280 /** eval:var:zzzzzzzzzzzzz */
1285 Date.formatCodeToRegex = function(character, currentGroup) {
1286 switch (character) {
1290 s:"(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)"};
1293 c:"d = parseInt(results[" + currentGroup + "], 10);\n",
1294 s:"(\\d{1,2})"}; // day of month without leading zeroes
1297 c:"d = parseInt(results[" + currentGroup + "], 10);\n",
1298 s:"(\\d{2})"}; // day of month with leading zeroes
1302 s:"(?:" + Date.dayNames.join("|") + ")"};
1306 s:"(?:st|nd|rd|th)"};
1321 c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "].substring(0, 3)], 10);\n",
1322 s:"(" + Date.monthNames.join("|") + ")"};
1325 c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "]], 10);\n",
1326 s:"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)"};
1329 c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
1330 s:"(\\d{1,2})"}; // Numeric representation of a month, without leading zeros
1333 c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
1334 s:"(\\d{2})"}; // Numeric representation of a month, with leading zeros
1345 c:"y = parseInt(results[" + currentGroup + "], 10);\n",
1349 c:"var ty = parseInt(results[" + currentGroup + "], 10);\n"
1350 + "y = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n",
1354 c:"if (results[" + currentGroup + "] == 'am') {\n"
1355 + "if (h == 12) { h = 0; }\n"
1356 + "} else { if (h < 12) { h += 12; }}",
1360 c:"if (results[" + currentGroup + "] == 'AM') {\n"
1361 + "if (h == 12) { h = 0; }\n"
1362 + "} else { if (h < 12) { h += 12; }}",
1367 c:"h = parseInt(results[" + currentGroup + "], 10);\n",
1368 s:"(\\d{1,2})"}; // 12/24-hr format format of an hour without leading zeroes
1372 c:"h = parseInt(results[" + currentGroup + "], 10);\n",
1373 s:"(\\d{2})"}; // 12/24-hr format format of an hour with leading zeroes
1376 c:"i = parseInt(results[" + currentGroup + "], 10);\n",
1380 c:"s = parseInt(results[" + currentGroup + "], 10);\n",
1385 "o = results[", currentGroup, "];\n",
1386 "var sn = o.substring(0,1);\n", // get + / - sign
1387 "var hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60);\n", // get hours (performs minutes-to-hour conversion also)
1388 "var mn = o.substring(3,5) % 60;\n", // get minutes
1389 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n", // -12hrs <= GMT offset <= 14hrs
1390 " (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"
1392 s:"([+\-]\\d{2,4})"};
1398 "o = results[", currentGroup, "];\n",
1399 "var sn = o.substring(0,1);\n",
1400 "var hr = o.substring(1,3)*1 + Math.floor(o.substring(4,6) / 60);\n",
1401 "var mn = o.substring(4,6) % 60;\n",
1402 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n",
1403 " (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"
1409 s:"[A-Z]{1,4}"}; // timezone abbrev. may be between 1 - 4 chars
1412 c:"z = results[" + currentGroup + "];\n" // -43200 <= UTC offset <= 50400
1413 + "z = (-43200 <= z*1 && z*1 <= 50400)? z : null;\n",
1414 s:"([+\-]?\\d{1,5})"}; // leading '+' sign is optional for UTC offset
1418 s:String.escape(character)};
1423 * Get the timezone abbreviation of the current date (equivalent to the format specifier 'T').
1424 * @return {String} The abbreviated timezone name (e.g. 'CST')
1426 Date.prototype.getTimezone = function() {
1427 return this.toString().replace(/^.*? ([A-Z]{1,4})[\-+][0-9]{4} .*$/, "$1");
1431 * Get the offset from GMT of the current date (equivalent to the format specifier 'O').
1432 * @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600')
1434 Date.prototype.getGMTOffset = function() {
1435 return (this.getTimezoneOffset() > 0 ? "-" : "+")
1436 + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
1437 + String.leftPad(this.getTimezoneOffset() % 60, 2, "0");
1441 * Get the offset from GMT of the current date (equivalent to the format specifier 'P').
1442 * @return {String} 2-characters representing hours and 2-characters representing minutes
1443 * seperated by a colon and prefixed with + or - (e.g. '-06:00')
1445 Date.prototype.getGMTColonOffset = function() {
1446 return (this.getTimezoneOffset() > 0 ? "-" : "+")
1447 + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
1449 + String.leftPad(this.getTimezoneOffset() %60, 2, "0");
1453 * Get the numeric day number of the year, adjusted for leap year.
1454 * @return {Number} 0 through 364 (365 in leap years)
1456 Date.prototype.getDayOfYear = function() {
1458 Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
1459 for (var i = 0; i < this.getMonth(); ++i) {
1460 num += Date.daysInMonth[i];
1462 return num + this.getDate() - 1;
1466 * Get the string representation of the numeric week number of the year
1467 * (equivalent to the format specifier 'W').
1468 * @return {String} '00' through '52'
1470 Date.prototype.getWeekOfYear = function() {
1471 // Skip to Thursday of this week
1472 var now = this.getDayOfYear() + (4 - this.getDay());
1473 // Find the first Thursday of the year
1474 var jan1 = new Date(this.getFullYear(), 0, 1);
1475 var then = (7 - jan1.getDay() + 4);
1476 return String.leftPad(((now - then) / 7) + 1, 2, "0");
1480 * Whether or not the current date is in a leap year.
1481 * @return {Boolean} True if the current date is in a leap year, else false
1483 Date.prototype.isLeapYear = function() {
1484 var year = this.getFullYear();
1485 return ((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
1489 * Get the first day of the current month, adjusted for leap year. The returned value
1490 * is the numeric day index within the week (0-6) which can be used in conjunction with
1491 * the {@link #monthNames} array to retrieve the textual day name.
1494 var dt = new Date('1/10/2007');
1495 document.write(Date.dayNames[dt.getFirstDayOfMonth()]); //output: 'Monday'
1497 * @return {Number} The day number (0-6)
1499 Date.prototype.getFirstDayOfMonth = function() {
1500 var day = (this.getDay() - (this.getDate() - 1)) % 7;
1501 return (day < 0) ? (day + 7) : day;
1505 * Get the last day of the current month, adjusted for leap year. The returned value
1506 * is the numeric day index within the week (0-6) which can be used in conjunction with
1507 * the {@link #monthNames} array to retrieve the textual day name.
1510 var dt = new Date('1/10/2007');
1511 document.write(Date.dayNames[dt.getLastDayOfMonth()]); //output: 'Wednesday'
1513 * @return {Number} The day number (0-6)
1515 Date.prototype.getLastDayOfMonth = function() {
1516 var day = (this.getDay() + (Date.daysInMonth[this.getMonth()] - this.getDate())) % 7;
1517 return (day < 0) ? (day + 7) : day;
1522 * Get the first date of this date's month
1525 Date.prototype.getFirstDateOfMonth = function() {
1526 return new Date(this.getFullYear(), this.getMonth(), 1);
1530 * Get the last date of this date's month
1533 Date.prototype.getLastDateOfMonth = function() {
1534 return new Date(this.getFullYear(), this.getMonth(), this.getDaysInMonth());
1537 * Get the number of days in the current month, adjusted for leap year.
1538 * @return {Number} The number of days in the month
1540 Date.prototype.getDaysInMonth = function() {
1541 Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
1542 return Date.daysInMonth[this.getMonth()];
1546 * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S').
1547 * @return {String} 'st, 'nd', 'rd' or 'th'
1549 Date.prototype.getSuffix = function() {
1550 switch (this.getDate()) {
1567 Date.daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
1570 * An array of textual month names.
1571 * Override these values for international dates, for example...
1572 * Date.monthNames = ['JanInYourLang', 'FebInYourLang', ...];
1591 * An array of textual day names.
1592 * Override these values for international dates, for example...
1593 * Date.dayNames = ['SundayInYourLang', 'MondayInYourLang', ...];
1609 Date.monthNumbers = {
1624 * Creates and returns a new Date instance with the exact same date value as the called instance.
1625 * Dates are copied and passed by reference, so if a copied date variable is modified later, the original
1626 * variable will also be changed. When the intention is to create a new variable that will not
1627 * modify the original instance, you should create a clone.
1629 * Example of correctly cloning a date:
1632 var orig = new Date('10/1/2006');
1635 document.write(orig); //returns 'Thu Oct 05 2006'!
1638 var orig = new Date('10/1/2006');
1639 var copy = orig.clone();
1641 document.write(orig); //returns 'Thu Oct 01 2006'
1643 * @return {Date} The new Date instance
1645 Date.prototype.clone = function() {
1646 return new Date(this.getTime());
1650 * Clears any time information from this date
1651 @param {Boolean} clone true to create a clone of this date, clear the time and return it
1652 @return {Date} this or the clone
1654 Date.prototype.clearTime = function(clone){
1656 return this.clone().clearTime();
1661 this.setMilliseconds(0);
1666 // safari setMonth is broken
1668 Date.brokenSetMonth = Date.prototype.setMonth;
1669 Date.prototype.setMonth = function(num){
1671 var n = Math.ceil(-num);
1672 var back_year = Math.ceil(n/12);
1673 var month = (n % 12) ? 12 - n % 12 : 0 ;
1674 this.setFullYear(this.getFullYear() - back_year);
1675 return Date.brokenSetMonth.call(this, month);
1677 return Date.brokenSetMonth.apply(this, arguments);
1682 /** Date interval constant
1686 /** Date interval constant
1690 /** Date interval constant
1694 /** Date interval constant
1698 /** Date interval constant
1702 /** Date interval constant
1706 /** Date interval constant
1712 * Provides a convenient method of performing basic date arithmetic. This method
1713 * does not modify the Date instance being called - it creates and returns
1714 * a new Date instance containing the resulting date value.
1719 var dt = new Date('10/29/2006').add(Date.DAY, 5);
1720 document.write(dt); //returns 'Fri Oct 06 2006 00:00:00'
1722 //Negative values will subtract correctly:
1723 var dt2 = new Date('10/1/2006').add(Date.DAY, -5);
1724 document.write(dt2); //returns 'Tue Sep 26 2006 00:00:00'
1726 //You can even chain several calls together in one line!
1727 var dt3 = new Date('10/1/2006').add(Date.DAY, 5).add(Date.HOUR, 8).add(Date.MINUTE, -30);
1728 document.write(dt3); //returns 'Fri Oct 06 2006 07:30:00'
1731 * @param {String} interval A valid date interval enum value
1732 * @param {Number} value The amount to add to the current date
1733 * @return {Date} The new Date instance
1735 Date.prototype.add = function(interval, value){
1736 var d = this.clone();
1737 if (!interval || value === 0) return d;
1738 switch(interval.toLowerCase()){
1740 d.setMilliseconds(this.getMilliseconds() + value);
1743 d.setSeconds(this.getSeconds() + value);
1746 d.setMinutes(this.getMinutes() + value);
1749 d.setHours(this.getHours() + value);
1752 d.setDate(this.getDate() + value);
1755 var day = this.getDate();
1757 day = Math.min(day, this.getFirstDateOfMonth().add('mo', value).getLastDateOfMonth().getDate());
1760 d.setMonth(this.getMonth() + value);
1763 d.setFullYear(this.getFullYear() + value);
1770 * Ext JS Library 1.1.1
1771 * Copyright(c) 2006-2007, Ext JS, LLC.
1773 * Originally Released Under LGPL - original licence link has changed is not relivant.
1776 * <script type="text/javascript">
1780 * @class Roo.lib.Dom
1783 * Dom utils (from YIU afaik)
1788 * Get the view width
1789 * @param {Boolean} full True will get the full document, otherwise it's the view width
1790 * @return {Number} The width
1793 getViewWidth : function(full) {
1794 return full ? this.getDocumentWidth() : this.getViewportWidth();
1797 * Get the view height
1798 * @param {Boolean} full True will get the full document, otherwise it's the view height
1799 * @return {Number} The height
1801 getViewHeight : function(full) {
1802 return full ? this.getDocumentHeight() : this.getViewportHeight();
1805 getDocumentHeight: function() {
1806 var scrollHeight = (document.compatMode != "CSS1Compat") ? document.body.scrollHeight : document.documentElement.scrollHeight;
1807 return Math.max(scrollHeight, this.getViewportHeight());
1810 getDocumentWidth: function() {
1811 var scrollWidth = (document.compatMode != "CSS1Compat") ? document.body.scrollWidth : document.documentElement.scrollWidth;
1812 return Math.max(scrollWidth, this.getViewportWidth());
1815 getViewportHeight: function() {
1816 var height = self.innerHeight;
1817 var mode = document.compatMode;
1819 if ((mode || Roo.isIE) && !Roo.isOpera) {
1820 height = (mode == "CSS1Compat") ?
1821 document.documentElement.clientHeight :
1822 document.body.clientHeight;
1828 getViewportWidth: function() {
1829 var width = self.innerWidth;
1830 var mode = document.compatMode;
1832 if (mode || Roo.isIE) {
1833 width = (mode == "CSS1Compat") ?
1834 document.documentElement.clientWidth :
1835 document.body.clientWidth;
1840 isAncestor : function(p, c) {
1847 if (p.contains && !Roo.isSafari) {
1848 return p.contains(c);
1849 } else if (p.compareDocumentPosition) {
1850 return !!(p.compareDocumentPosition(c) & 16);
1852 var parent = c.parentNode;
1857 else if (!parent.tagName || parent.tagName.toUpperCase() == "HTML") {
1860 parent = parent.parentNode;
1866 getRegion : function(el) {
1867 return Roo.lib.Region.getRegion(el);
1870 getY : function(el) {
1871 return this.getXY(el)[1];
1874 getX : function(el) {
1875 return this.getXY(el)[0];
1878 getXY : function(el) {
1879 var p, pe, b, scroll, bd = document.body;
1880 el = Roo.getDom(el);
1881 var fly = Roo.lib.AnimBase.fly;
1882 if (el.getBoundingClientRect) {
1883 b = el.getBoundingClientRect();
1884 scroll = fly(document).getScroll();
1885 return [b.left + scroll.left, b.top + scroll.top];
1891 var hasAbsolute = fly(el).getStyle("position") == "absolute";
1898 if (!hasAbsolute && fly(p).getStyle("position") == "absolute") {
1905 var bt = parseInt(pe.getStyle("borderTopWidth"), 10) || 0;
1906 var bl = parseInt(pe.getStyle("borderLeftWidth"), 10) || 0;
1913 if (p != el && pe.getStyle('overflow') != 'visible') {
1921 if (Roo.isSafari && hasAbsolute) {
1926 if (Roo.isGecko && !hasAbsolute) {
1928 x += parseInt(dbd.getStyle("borderLeftWidth"), 10) || 0;
1929 y += parseInt(dbd.getStyle("borderTopWidth"), 10) || 0;
1933 while (p && p != bd) {
1934 if (!Roo.isOpera || (p.tagName != 'TR' && fly(p).getStyle("display") != "inline")) {
1946 setXY : function(el, xy) {
1947 el = Roo.fly(el, '_setXY');
1949 var pts = el.translatePoints(xy);
1950 if (xy[0] !== false) {
1951 el.dom.style.left = pts.left + "px";
1953 if (xy[1] !== false) {
1954 el.dom.style.top = pts.top + "px";
1958 setX : function(el, x) {
1959 this.setXY(el, [x, false]);
1962 setY : function(el, y) {
1963 this.setXY(el, [false, y]);
1967 * Portions of this file are based on pieces of Yahoo User Interface Library
1968 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
1969 * YUI licensed under the BSD License:
1970 * http://developer.yahoo.net/yui/license.txt
1971 * <script type="text/javascript">
1975 Roo.lib.Event = function() {
1976 var loadComplete = false;
1978 var unloadListeners = [];
1980 var onAvailStack = [];
1982 var lastError = null;
1995 startInterval: function() {
1996 if (!this._interval) {
1998 var callback = function() {
1999 self._tryPreloadAttach();
2001 this._interval = setInterval(callback, this.POLL_INTERVAL);
2006 onAvailable: function(p_id, p_fn, p_obj, p_override) {
2007 onAvailStack.push({ id: p_id,
2010 override: p_override,
2011 checkReady: false });
2013 retryCount = this.POLL_RETRYS;
2014 this.startInterval();
2018 addListener: function(el, eventName, fn) {
2019 el = Roo.getDom(el);
2024 if ("unload" == eventName) {
2025 unloadListeners[unloadListeners.length] =
2026 [el, eventName, fn];
2030 var wrappedFn = function(e) {
2031 return fn(Roo.lib.Event.getEvent(e));
2034 var li = [el, eventName, fn, wrappedFn];
2036 var index = listeners.length;
2037 listeners[index] = li;
2039 this.doAdd(el, eventName, wrappedFn, false);
2045 removeListener: function(el, eventName, fn) {
2048 el = Roo.getDom(el);
2051 return this.purgeElement(el, false, eventName);
2055 if ("unload" == eventName) {
2057 for (i = 0,len = unloadListeners.length; i < len; i++) {
2058 var li = unloadListeners[i];
2061 li[1] == eventName &&
2063 unloadListeners.splice(i, 1);
2071 var cacheItem = null;
2074 var index = arguments[3];
2076 if ("undefined" == typeof index) {
2077 index = this._getCacheIndex(el, eventName, fn);
2081 cacheItem = listeners[index];
2084 if (!el || !cacheItem) {
2088 this.doRemove(el, eventName, cacheItem[this.WFN], false);
2090 delete listeners[index][this.WFN];
2091 delete listeners[index][this.FN];
2092 listeners.splice(index, 1);
2099 getTarget: function(ev, resolveTextNode) {
2100 ev = ev.browserEvent || ev;
2101 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2102 var t = ev.target || ev.srcElement;
2103 return this.resolveTextNode(t);
2107 resolveTextNode: function(node) {
2108 if (Roo.isSafari && node && 3 == node.nodeType) {
2109 return node.parentNode;
2116 getPageX: function(ev) {
2117 ev = ev.browserEvent || ev;
2118 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2120 if (!x && 0 !== x) {
2121 x = ev.clientX || 0;
2124 x += this.getScroll()[1];
2132 getPageY: function(ev) {
2133 ev = ev.browserEvent || ev;
2134 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2136 if (!y && 0 !== y) {
2137 y = ev.clientY || 0;
2140 y += this.getScroll()[0];
2149 getXY: function(ev) {
2150 ev = ev.browserEvent || ev;
2151 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2152 return [this.getPageX(ev), this.getPageY(ev)];
2156 getRelatedTarget: function(ev) {
2157 ev = ev.browserEvent || ev;
2158 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2159 var t = ev.relatedTarget;
2161 if (ev.type == "mouseout") {
2163 } else if (ev.type == "mouseover") {
2168 return this.resolveTextNode(t);
2172 getTime: function(ev) {
2173 ev = ev.browserEvent || ev;
2174 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2176 var t = new Date().getTime();
2180 this.lastError = ex;
2189 stopEvent: function(ev) {
2190 this.stopPropagation(ev);
2191 this.preventDefault(ev);
2195 stopPropagation: function(ev) {
2196 ev = ev.browserEvent || ev;
2197 if (ev.stopPropagation) {
2198 ev.stopPropagation();
2200 ev.cancelBubble = true;
2205 preventDefault: function(ev) {
2206 ev = ev.browserEvent || ev;
2207 if(ev.preventDefault) {
2208 ev.preventDefault();
2210 ev.returnValue = false;
2215 getEvent: function(e) {
2216 var ev = e || window.event;
2218 var c = this.getEvent.caller;
2220 ev = c.arguments[0];
2221 if (ev && Event == ev.constructor) {
2231 getCharCode: function(ev) {
2232 ev = ev.browserEvent || ev;
2233 return ev.charCode || ev.keyCode || 0;
2237 _getCacheIndex: function(el, eventName, fn) {
2238 for (var i = 0,len = listeners.length; i < len; ++i) {
2239 var li = listeners[i];
2241 li[this.FN] == fn &&
2242 li[this.EL] == el &&
2243 li[this.TYPE] == eventName) {
2255 getEl: function(id) {
2256 return document.getElementById(id);
2260 clearCache: function() {
2264 _load: function(e) {
2265 loadComplete = true;
2266 var EU = Roo.lib.Event;
2270 EU.doRemove(window, "load", EU._load);
2275 _tryPreloadAttach: function() {
2284 var tryAgain = !loadComplete;
2286 tryAgain = (retryCount > 0);
2291 for (var i = 0,len = onAvailStack.length; i < len; ++i) {
2292 var item = onAvailStack[i];
2294 var el = this.getEl(item.id);
2297 if (!item.checkReady ||
2300 (document && document.body)) {
2303 if (item.override) {
2304 if (item.override === true) {
2307 scope = item.override;
2310 item.fn.call(scope, item.obj);
2311 onAvailStack[i] = null;
2314 notAvail.push(item);
2319 retryCount = (notAvail.length === 0) ? 0 : retryCount - 1;
2323 this.startInterval();
2325 clearInterval(this._interval);
2326 this._interval = null;
2329 this.locked = false;
2336 purgeElement: function(el, recurse, eventName) {
2337 var elListeners = this.getListeners(el, eventName);
2339 for (var i = 0,len = elListeners.length; i < len; ++i) {
2340 var l = elListeners[i];
2341 this.removeListener(el, l.type, l.fn);
2345 if (recurse && el && el.childNodes) {
2346 for (i = 0,len = el.childNodes.length; i < len; ++i) {
2347 this.purgeElement(el.childNodes[i], recurse, eventName);
2353 getListeners: function(el, eventName) {
2354 var results = [], searchLists;
2356 searchLists = [listeners, unloadListeners];
2357 } else if (eventName == "unload") {
2358 searchLists = [unloadListeners];
2360 searchLists = [listeners];
2363 for (var j = 0; j < searchLists.length; ++j) {
2364 var searchList = searchLists[j];
2365 if (searchList && searchList.length > 0) {
2366 for (var i = 0,len = searchList.length; i < len; ++i) {
2367 var l = searchList[i];
2368 if (l && l[this.EL] === el &&
2369 (!eventName || eventName === l[this.TYPE])) {
2374 adjust: l[this.ADJ_SCOPE],
2382 return (results.length) ? results : null;
2386 _unload: function(e) {
2388 var EU = Roo.lib.Event, i, j, l, len, index;
2390 for (i = 0,len = unloadListeners.length; i < len; ++i) {
2391 l = unloadListeners[i];
2394 if (l[EU.ADJ_SCOPE]) {
2395 if (l[EU.ADJ_SCOPE] === true) {
2398 scope = l[EU.ADJ_SCOPE];
2401 l[EU.FN].call(scope, EU.getEvent(e), l[EU.OBJ]);
2402 unloadListeners[i] = null;
2408 unloadListeners = null;
2410 if (listeners && listeners.length > 0) {
2411 j = listeners.length;
2414 l = listeners[index];
2416 EU.removeListener(l[EU.EL], l[EU.TYPE],
2426 EU.doRemove(window, "unload", EU._unload);
2431 getScroll: function() {
2432 var dd = document.documentElement, db = document.body;
2433 if (dd && (dd.scrollTop || dd.scrollLeft)) {
2434 return [dd.scrollTop, dd.scrollLeft];
2436 return [db.scrollTop, db.scrollLeft];
2443 doAdd: function () {
2444 if (window.addEventListener) {
2445 return function(el, eventName, fn, capture) {
2446 el.addEventListener(eventName, fn, (capture));
2448 } else if (window.attachEvent) {
2449 return function(el, eventName, fn, capture) {
2450 el.attachEvent("on" + eventName, fn);
2459 doRemove: function() {
2460 if (window.removeEventListener) {
2461 return function (el, eventName, fn, capture) {
2462 el.removeEventListener(eventName, fn, (capture));
2464 } else if (window.detachEvent) {
2465 return function (el, eventName, fn) {
2466 el.detachEvent("on" + eventName, fn);
2478 var E = Roo.lib.Event;
2479 E.on = E.addListener;
2480 E.un = E.removeListener;
2482 if (document && document.body) {
2485 E.doAdd(window, "load", E._load);
2487 E.doAdd(window, "unload", E._unload);
2488 E._tryPreloadAttach();
2492 * Portions of this file are based on pieces of Yahoo User Interface Library
2493 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
2494 * YUI licensed under the BSD License:
2495 * http://developer.yahoo.net/yui/license.txt
2496 * <script type="text/javascript">
2502 * @class Roo.lib.Ajax
2509 request : function(method, uri, cb, data, options) {
2511 var hs = options.headers;
2514 if(hs.hasOwnProperty(h)){
2515 this.initHeader(h, hs[h], false);
2519 if(options.xmlData){
2520 this.initHeader('Content-Type', 'text/xml', false);
2522 data = options.xmlData;
2526 return this.asyncRequest(method, uri, cb, data);
2529 serializeForm : function(form) {
2530 if(typeof form == 'string') {
2531 form = (document.getElementById(form) || document.forms[form]);
2534 var el, name, val, disabled, data = '', hasSubmit = false;
2535 for (var i = 0; i < form.elements.length; i++) {
2536 el = form.elements[i];
2537 disabled = form.elements[i].disabled;
2538 name = form.elements[i].name;
2539 val = form.elements[i].value;
2541 if (!disabled && name){
2545 case 'select-multiple':
2546 for (var j = 0; j < el.options.length; j++) {
2547 if (el.options[j].selected) {
2549 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(el.options[j].attributes['value'].specified ? el.options[j].value : el.options[j].text) + '&';
2552 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(el.options[j].hasAttribute('value') ? el.options[j].value : el.options[j].text) + '&';
2560 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2573 if(hasSubmit == false) {
2574 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2579 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2584 data = data.substr(0, data.length - 1);
2592 useDefaultHeader:true,
2594 defaultPostHeader:'application/x-www-form-urlencoded',
2596 useDefaultXhrHeader:true,
2598 defaultXhrHeader:'XMLHttpRequest',
2600 hasDefaultHeaders:true,
2612 setProgId:function(id)
2614 this.activeX.unshift(id);
2617 setDefaultPostHeader:function(b)
2619 this.useDefaultHeader = b;
2622 setDefaultXhrHeader:function(b)
2624 this.useDefaultXhrHeader = b;
2627 setPollingInterval:function(i)
2629 if (typeof i == 'number' && isFinite(i)) {
2630 this.pollInterval = i;
2634 createXhrObject:function(transactionId)
2640 http = new XMLHttpRequest();
2642 obj = { conn:http, tId:transactionId };
2646 for (var i = 0; i < this.activeX.length; ++i) {
2650 http = new ActiveXObject(this.activeX[i]);
2652 obj = { conn:http, tId:transactionId };
2665 getConnectionObject:function()
2668 var tId = this.transactionId;
2672 o = this.createXhrObject(tId);
2674 this.transactionId++;
2685 asyncRequest:function(method, uri, callback, postData)
2687 var o = this.getConnectionObject();
2693 o.conn.open(method, uri, true);
2695 if (this.useDefaultXhrHeader) {
2696 if (!this.defaultHeaders['X-Requested-With']) {
2697 this.initHeader('X-Requested-With', this.defaultXhrHeader, true);
2701 if(postData && this.useDefaultHeader){
2702 this.initHeader('Content-Type', this.defaultPostHeader);
2705 if (this.hasDefaultHeaders || this.hasHeaders) {
2709 this.handleReadyState(o, callback);
2710 o.conn.send(postData || null);
2716 handleReadyState:function(o, callback)
2720 if (callback && callback.timeout) {
2722 this.timeout[o.tId] = window.setTimeout(function() {
2723 oConn.abort(o, callback, true);
2724 }, callback.timeout);
2727 this.poll[o.tId] = window.setInterval(
2729 if (o.conn && o.conn.readyState == 4) {
2730 window.clearInterval(oConn.poll[o.tId]);
2731 delete oConn.poll[o.tId];
2733 if(callback && callback.timeout) {
2734 window.clearTimeout(oConn.timeout[o.tId]);
2735 delete oConn.timeout[o.tId];
2738 oConn.handleTransactionResponse(o, callback);
2741 , this.pollInterval);
2744 handleTransactionResponse:function(o, callback, isAbort)
2748 this.releaseObject(o);
2752 var httpStatus, responseObject;
2756 if (o.conn.status !== undefined && o.conn.status != 0) {
2757 httpStatus = o.conn.status;
2769 if (httpStatus >= 200 && httpStatus < 300) {
2770 responseObject = this.createResponseObject(o, callback.argument);
2771 if (callback.success) {
2772 if (!callback.scope) {
2773 callback.success(responseObject);
2778 callback.success.apply(callback.scope, [responseObject]);
2783 switch (httpStatus) {
2791 responseObject = this.createExceptionObject(o.tId, callback.argument, (isAbort ? isAbort : false));
2792 if (callback.failure) {
2793 if (!callback.scope) {
2794 callback.failure(responseObject);
2797 callback.failure.apply(callback.scope, [responseObject]);
2802 responseObject = this.createResponseObject(o, callback.argument);
2803 if (callback.failure) {
2804 if (!callback.scope) {
2805 callback.failure(responseObject);
2808 callback.failure.apply(callback.scope, [responseObject]);
2814 this.releaseObject(o);
2815 responseObject = null;
2818 createResponseObject:function(o, callbackArg)
2825 var headerStr = o.conn.getAllResponseHeaders();
2826 var header = headerStr.split('\n');
2827 for (var i = 0; i < header.length; i++) {
2828 var delimitPos = header[i].indexOf(':');
2829 if (delimitPos != -1) {
2830 headerObj[header[i].substring(0, delimitPos)] = header[i].substring(delimitPos + 2);
2838 obj.status = o.conn.status;
2839 obj.statusText = o.conn.statusText;
2840 obj.getResponseHeader = headerObj;
2841 obj.getAllResponseHeaders = headerStr;
2842 obj.responseText = o.conn.responseText;
2843 obj.responseXML = o.conn.responseXML;
2845 if (typeof callbackArg !== undefined) {
2846 obj.argument = callbackArg;
2852 createExceptionObject:function(tId, callbackArg, isAbort)
2855 var COMM_ERROR = 'communication failure';
2856 var ABORT_CODE = -1;
2857 var ABORT_ERROR = 'transaction aborted';
2863 obj.status = ABORT_CODE;
2864 obj.statusText = ABORT_ERROR;
2867 obj.status = COMM_CODE;
2868 obj.statusText = COMM_ERROR;
2872 obj.argument = callbackArg;
2878 initHeader:function(label, value, isDefault)
2880 var headerObj = (isDefault) ? this.defaultHeaders : this.headers;
2882 if (headerObj[label] === undefined) {
2883 headerObj[label] = value;
2888 headerObj[label] = value + "," + headerObj[label];
2892 this.hasDefaultHeaders = true;
2895 this.hasHeaders = true;
2900 setHeader:function(o)
2902 if (this.hasDefaultHeaders) {
2903 for (var prop in this.defaultHeaders) {
2904 if (this.defaultHeaders.hasOwnProperty(prop)) {
2905 o.conn.setRequestHeader(prop, this.defaultHeaders[prop]);
2910 if (this.hasHeaders) {
2911 for (var prop in this.headers) {
2912 if (this.headers.hasOwnProperty(prop)) {
2913 o.conn.setRequestHeader(prop, this.headers[prop]);
2917 this.hasHeaders = false;
2921 resetDefaultHeaders:function() {
2922 delete this.defaultHeaders;
2923 this.defaultHeaders = {};
2924 this.hasDefaultHeaders = false;
2927 abort:function(o, callback, isTimeout)
2929 if(this.isCallInProgress(o)) {
2931 window.clearInterval(this.poll[o.tId]);
2932 delete this.poll[o.tId];
2934 delete this.timeout[o.tId];
2937 this.handleTransactionResponse(o, callback, true);
2947 isCallInProgress:function(o)
2950 return o.conn.readyState != 4 && o.conn.readyState != 0;
2959 releaseObject:function(o)
2968 'MSXML2.XMLHTTP.3.0',
2976 * Portions of this file are based on pieces of Yahoo User Interface Library
2977 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
2978 * YUI licensed under the BSD License:
2979 * http://developer.yahoo.net/yui/license.txt
2980 * <script type="text/javascript">
2984 Roo.lib.Region = function(t, r, b, l) {
2994 Roo.lib.Region.prototype = {
2995 contains : function(region) {
2996 return ( region.left >= this.left &&
2997 region.right <= this.right &&
2998 region.top >= this.top &&
2999 region.bottom <= this.bottom );
3003 getArea : function() {
3004 return ( (this.bottom - this.top) * (this.right - this.left) );
3007 intersect : function(region) {
3008 var t = Math.max(this.top, region.top);
3009 var r = Math.min(this.right, region.right);
3010 var b = Math.min(this.bottom, region.bottom);
3011 var l = Math.max(this.left, region.left);
3013 if (b >= t && r >= l) {
3014 return new Roo.lib.Region(t, r, b, l);
3019 union : function(region) {
3020 var t = Math.min(this.top, region.top);
3021 var r = Math.max(this.right, region.right);
3022 var b = Math.max(this.bottom, region.bottom);
3023 var l = Math.min(this.left, region.left);
3025 return new Roo.lib.Region(t, r, b, l);
3028 adjust : function(t, l, b, r) {
3037 Roo.lib.Region.getRegion = function(el) {
3038 var p = Roo.lib.Dom.getXY(el);
3041 var r = p[0] + el.offsetWidth;
3042 var b = p[1] + el.offsetHeight;
3045 return new Roo.lib.Region(t, r, b, l);
3048 * Portions of this file are based on pieces of Yahoo User Interface Library
3049 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3050 * YUI licensed under the BSD License:
3051 * http://developer.yahoo.net/yui/license.txt
3052 * <script type="text/javascript">
3055 //@@dep Roo.lib.Region
3058 Roo.lib.Point = function(x, y) {
3059 if (x instanceof Array) {
3063 this.x = this.right = this.left = this[0] = x;
3064 this.y = this.top = this.bottom = this[1] = y;
3067 Roo.lib.Point.prototype = new Roo.lib.Region();
3069 * Portions of this file are based on pieces of Yahoo User Interface Library
3070 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3071 * YUI licensed under the BSD License:
3072 * http://developer.yahoo.net/yui/license.txt
3073 * <script type="text/javascript">
3080 scroll : function(el, args, duration, easing, cb, scope) {
3081 this.run(el, args, duration, easing, cb, scope, Roo.lib.Scroll);
3084 motion : function(el, args, duration, easing, cb, scope) {
3085 this.run(el, args, duration, easing, cb, scope, Roo.lib.Motion);
3088 color : function(el, args, duration, easing, cb, scope) {
3089 this.run(el, args, duration, easing, cb, scope, Roo.lib.ColorAnim);
3092 run : function(el, args, duration, easing, cb, scope, type) {
3093 type = type || Roo.lib.AnimBase;
3094 if (typeof easing == "string") {
3095 easing = Roo.lib.Easing[easing];
3097 var anim = new type(el, args, duration, easing);
3098 anim.animateX(function() {
3099 Roo.callback(cb, scope);
3105 * Portions of this file are based on pieces of Yahoo User Interface Library
3106 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3107 * YUI licensed under the BSD License:
3108 * http://developer.yahoo.net/yui/license.txt
3109 * <script type="text/javascript">
3117 if (!libFlyweight) {
3118 libFlyweight = new Roo.Element.Flyweight();
3120 libFlyweight.dom = el;
3121 return libFlyweight;
3124 // since this uses fly! - it cant be in DOM (which does not have fly yet..)
3128 Roo.lib.AnimBase = function(el, attributes, duration, method) {
3130 this.init(el, attributes, duration, method);
3134 Roo.lib.AnimBase.fly = fly;
3138 Roo.lib.AnimBase.prototype = {
3140 toString: function() {
3141 var el = this.getEl();
3142 var id = el.id || el.tagName;
3143 return ("Anim " + id);
3147 noNegatives: /width|height|opacity|padding/i,
3148 offsetAttribute: /^((width|height)|(top|left))$/,
3149 defaultUnit: /width|height|top$|bottom$|left$|right$/i,
3150 offsetUnit: /\d+(em|%|en|ex|pt|in|cm|mm|pc)$/i
3154 doMethod: function(attr, start, end) {
3155 return this.method(this.currentFrame, start, end - start, this.totalFrames);
3159 setAttribute: function(attr, val, unit) {
3160 if (this.patterns.noNegatives.test(attr)) {
3161 val = (val > 0) ? val : 0;
3164 Roo.fly(this.getEl(), '_anim').setStyle(attr, val + unit);
3168 getAttribute: function(attr) {
3169 var el = this.getEl();
3170 var val = fly(el).getStyle(attr);
3172 if (val !== 'auto' && !this.patterns.offsetUnit.test(val)) {
3173 return parseFloat(val);
3176 var a = this.patterns.offsetAttribute.exec(attr) || [];
3177 var pos = !!( a[3] );
3178 var box = !!( a[2] );
3181 if (box || (fly(el).getStyle('position') == 'absolute' && pos)) {
3182 val = el['offset' + a[0].charAt(0).toUpperCase() + a[0].substr(1)];
3191 getDefaultUnit: function(attr) {
3192 if (this.patterns.defaultUnit.test(attr)) {
3199 animateX : function(callback, scope) {
3200 var f = function() {
3201 this.onComplete.removeListener(f);
3202 if (typeof callback == "function") {
3203 callback.call(scope || this, this);
3206 this.onComplete.addListener(f, this);
3211 setRuntimeAttribute: function(attr) {
3214 var attributes = this.attributes;
3216 this.runtimeAttributes[attr] = {};
3218 var isset = function(prop) {
3219 return (typeof prop !== 'undefined');
3222 if (!isset(attributes[attr]['to']) && !isset(attributes[attr]['by'])) {
3226 start = ( isset(attributes[attr]['from']) ) ? attributes[attr]['from'] : this.getAttribute(attr);
3229 if (isset(attributes[attr]['to'])) {
3230 end = attributes[attr]['to'];
3231 } else if (isset(attributes[attr]['by'])) {
3232 if (start.constructor == Array) {
3234 for (var i = 0, len = start.length; i < len; ++i) {
3235 end[i] = start[i] + attributes[attr]['by'][i];
3238 end = start + attributes[attr]['by'];
3242 this.runtimeAttributes[attr].start = start;
3243 this.runtimeAttributes[attr].end = end;
3246 this.runtimeAttributes[attr].unit = ( isset(attributes[attr].unit) ) ? attributes[attr]['unit'] : this.getDefaultUnit(attr);
3250 init: function(el, attributes, duration, method) {
3252 var isAnimated = false;
3255 var startTime = null;
3258 var actualFrames = 0;
3261 el = Roo.getDom(el);
3264 this.attributes = attributes || {};
3267 this.duration = duration || 1;
3270 this.method = method || Roo.lib.Easing.easeNone;
3273 this.useSeconds = true;
3276 this.currentFrame = 0;
3279 this.totalFrames = Roo.lib.AnimMgr.fps;
3282 this.getEl = function() {
3287 this.isAnimated = function() {
3292 this.getStartTime = function() {
3296 this.runtimeAttributes = {};
3299 this.animate = function() {
3300 if (this.isAnimated()) {
3304 this.currentFrame = 0;
3306 this.totalFrames = ( this.useSeconds ) ? Math.ceil(Roo.lib.AnimMgr.fps * this.duration) : this.duration;
3308 Roo.lib.AnimMgr.registerElement(this);
3312 this.stop = function(finish) {
3314 this.currentFrame = this.totalFrames;
3315 this._onTween.fire();
3317 Roo.lib.AnimMgr.stop(this);
3320 var onStart = function() {
3321 this.onStart.fire();
3323 this.runtimeAttributes = {};
3324 for (var attr in this.attributes) {
3325 this.setRuntimeAttribute(attr);
3330 startTime = new Date();
3334 var onTween = function() {
3336 duration: new Date() - this.getStartTime(),
3337 currentFrame: this.currentFrame
3340 data.toString = function() {
3342 'duration: ' + data.duration +
3343 ', currentFrame: ' + data.currentFrame
3347 this.onTween.fire(data);
3349 var runtimeAttributes = this.runtimeAttributes;
3351 for (var attr in runtimeAttributes) {
3352 this.setAttribute(attr, this.doMethod(attr, runtimeAttributes[attr].start, runtimeAttributes[attr].end), runtimeAttributes[attr].unit);
3358 var onComplete = function() {
3359 var actual_duration = (new Date() - startTime) / 1000 ;
3362 duration: actual_duration,
3363 frames: actualFrames,
3364 fps: actualFrames / actual_duration
3367 data.toString = function() {
3369 'duration: ' + data.duration +
3370 ', frames: ' + data.frames +
3371 ', fps: ' + data.fps
3377 this.onComplete.fire(data);
3381 this._onStart = new Roo.util.Event(this);
3382 this.onStart = new Roo.util.Event(this);
3383 this.onTween = new Roo.util.Event(this);
3384 this._onTween = new Roo.util.Event(this);
3385 this.onComplete = new Roo.util.Event(this);
3386 this._onComplete = new Roo.util.Event(this);
3387 this._onStart.addListener(onStart);
3388 this._onTween.addListener(onTween);
3389 this._onComplete.addListener(onComplete);
3394 * Portions of this file are based on pieces of Yahoo User Interface Library
3395 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3396 * YUI licensed under the BSD License:
3397 * http://developer.yahoo.net/yui/license.txt
3398 * <script type="text/javascript">
3402 Roo.lib.AnimMgr = new function() {
3419 this.registerElement = function(tween) {
3420 queue[queue.length] = tween;
3422 tween._onStart.fire();
3427 this.unRegister = function(tween, index) {
3428 tween._onComplete.fire();
3429 index = index || getIndex(tween);
3431 queue.splice(index, 1);
3435 if (tweenCount <= 0) {
3441 this.start = function() {
3442 if (thread === null) {
3443 thread = setInterval(this.run, this.delay);
3448 this.stop = function(tween) {
3450 clearInterval(thread);
3452 for (var i = 0, len = queue.length; i < len; ++i) {
3453 if (queue[0].isAnimated()) {
3454 this.unRegister(queue[0], 0);
3463 this.unRegister(tween);
3468 this.run = function() {
3469 for (var i = 0, len = queue.length; i < len; ++i) {
3470 var tween = queue[i];
3471 if (!tween || !tween.isAnimated()) {
3475 if (tween.currentFrame < tween.totalFrames || tween.totalFrames === null)
3477 tween.currentFrame += 1;
3479 if (tween.useSeconds) {
3480 correctFrame(tween);
3482 tween._onTween.fire();
3485 Roo.lib.AnimMgr.stop(tween, i);
3490 var getIndex = function(anim) {
3491 for (var i = 0, len = queue.length; i < len; ++i) {
3492 if (queue[i] == anim) {
3500 var correctFrame = function(tween) {
3501 var frames = tween.totalFrames;
3502 var frame = tween.currentFrame;
3503 var expected = (tween.currentFrame * tween.duration * 1000 / tween.totalFrames);
3504 var elapsed = (new Date() - tween.getStartTime());
3507 if (elapsed < tween.duration * 1000) {
3508 tweak = Math.round((elapsed / expected - 1) * tween.currentFrame);
3510 tweak = frames - (frame + 1);
3512 if (tweak > 0 && isFinite(tweak)) {
3513 if (tween.currentFrame + tweak >= frames) {
3514 tweak = frames - (frame + 1);
3517 tween.currentFrame += tweak;
3523 * Portions of this file are based on pieces of Yahoo User Interface Library
3524 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3525 * YUI licensed under the BSD License:
3526 * http://developer.yahoo.net/yui/license.txt
3527 * <script type="text/javascript">
3530 Roo.lib.Bezier = new function() {
3532 this.getPosition = function(points, t) {
3533 var n = points.length;
3536 for (var i = 0; i < n; ++i) {
3537 tmp[i] = [points[i][0], points[i][1]];
3540 for (var j = 1; j < n; ++j) {
3541 for (i = 0; i < n - j; ++i) {
3542 tmp[i][0] = (1 - t) * tmp[i][0] + t * tmp[parseInt(i + 1, 10)][0];
3543 tmp[i][1] = (1 - t) * tmp[i][1] + t * tmp[parseInt(i + 1, 10)][1];
3547 return [ tmp[0][0], tmp[0][1] ];
3551 * Portions of this file are based on pieces of Yahoo User Interface Library
3552 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3553 * YUI licensed under the BSD License:
3554 * http://developer.yahoo.net/yui/license.txt
3555 * <script type="text/javascript">
3560 Roo.lib.ColorAnim = function(el, attributes, duration, method) {
3561 Roo.lib.ColorAnim.superclass.constructor.call(this, el, attributes, duration, method);
3564 Roo.extend(Roo.lib.ColorAnim, Roo.lib.AnimBase);
3566 var fly = Roo.lib.AnimBase.fly;
3568 var superclass = Y.ColorAnim.superclass;
3569 var proto = Y.ColorAnim.prototype;
3571 proto.toString = function() {
3572 var el = this.getEl();
3573 var id = el.id || el.tagName;
3574 return ("ColorAnim " + id);
3577 proto.patterns.color = /color$/i;
3578 proto.patterns.rgb = /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i;
3579 proto.patterns.hex = /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i;
3580 proto.patterns.hex3 = /^#?([0-9A-F]{1})([0-9A-F]{1})([0-9A-F]{1})$/i;
3581 proto.patterns.transparent = /^transparent|rgba\(0, 0, 0, 0\)$/;
3584 proto.parseColor = function(s) {
3585 if (s.length == 3) {
3589 var c = this.patterns.hex.exec(s);
3590 if (c && c.length == 4) {
3591 return [ parseInt(c[1], 16), parseInt(c[2], 16), parseInt(c[3], 16) ];
3594 c = this.patterns.rgb.exec(s);
3595 if (c && c.length == 4) {
3596 return [ parseInt(c[1], 10), parseInt(c[2], 10), parseInt(c[3], 10) ];
3599 c = this.patterns.hex3.exec(s);
3600 if (c && c.length == 4) {
3601 return [ parseInt(c[1] + c[1], 16), parseInt(c[2] + c[2], 16), parseInt(c[3] + c[3], 16) ];
3606 // since this uses fly! - it cant be in ColorAnim (which does not have fly yet..)
3607 proto.getAttribute = function(attr) {
3608 var el = this.getEl();
3609 if (this.patterns.color.test(attr)) {
3610 var val = fly(el).getStyle(attr);
3612 if (this.patterns.transparent.test(val)) {
3613 var parent = el.parentNode;
3614 val = fly(parent).getStyle(attr);
3616 while (parent && this.patterns.transparent.test(val)) {
3617 parent = parent.parentNode;
3618 val = fly(parent).getStyle(attr);
3619 if (parent.tagName.toUpperCase() == 'HTML') {
3625 val = superclass.getAttribute.call(this, attr);
3630 proto.getAttribute = function(attr) {
3631 var el = this.getEl();
3632 if (this.patterns.color.test(attr)) {
3633 var val = fly(el).getStyle(attr);
3635 if (this.patterns.transparent.test(val)) {
3636 var parent = el.parentNode;
3637 val = fly(parent).getStyle(attr);
3639 while (parent && this.patterns.transparent.test(val)) {
3640 parent = parent.parentNode;
3641 val = fly(parent).getStyle(attr);
3642 if (parent.tagName.toUpperCase() == 'HTML') {
3648 val = superclass.getAttribute.call(this, attr);
3654 proto.doMethod = function(attr, start, end) {
3657 if (this.patterns.color.test(attr)) {
3659 for (var i = 0, len = start.length; i < len; ++i) {
3660 val[i] = superclass.doMethod.call(this, attr, start[i], end[i]);
3663 val = 'rgb(' + Math.floor(val[0]) + ',' + Math.floor(val[1]) + ',' + Math.floor(val[2]) + ')';
3666 val = superclass.doMethod.call(this, attr, start, end);
3672 proto.setRuntimeAttribute = function(attr) {
3673 superclass.setRuntimeAttribute.call(this, attr);
3675 if (this.patterns.color.test(attr)) {
3676 var attributes = this.attributes;
3677 var start = this.parseColor(this.runtimeAttributes[attr].start);
3678 var end = this.parseColor(this.runtimeAttributes[attr].end);
3680 if (typeof attributes[attr]['to'] === 'undefined' && typeof attributes[attr]['by'] !== 'undefined') {
3681 end = this.parseColor(attributes[attr].by);
3683 for (var i = 0, len = start.length; i < len; ++i) {
3684 end[i] = start[i] + end[i];
3688 this.runtimeAttributes[attr].start = start;
3689 this.runtimeAttributes[attr].end = end;
3695 * Portions of this file are based on pieces of Yahoo User Interface Library
3696 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3697 * YUI licensed under the BSD License:
3698 * http://developer.yahoo.net/yui/license.txt
3699 * <script type="text/javascript">
3705 easeNone: function (t, b, c, d) {
3706 return c * t / d + b;
3710 easeIn: function (t, b, c, d) {
3711 return c * (t /= d) * t + b;
3715 easeOut: function (t, b, c, d) {
3716 return -c * (t /= d) * (t - 2) + b;
3720 easeBoth: function (t, b, c, d) {
3721 if ((t /= d / 2) < 1) {
3722 return c / 2 * t * t + b;
3725 return -c / 2 * ((--t) * (t - 2) - 1) + b;
3729 easeInStrong: function (t, b, c, d) {
3730 return c * (t /= d) * t * t * t + b;
3734 easeOutStrong: function (t, b, c, d) {
3735 return -c * ((t = t / d - 1) * t * t * t - 1) + b;
3739 easeBothStrong: function (t, b, c, d) {
3740 if ((t /= d / 2) < 1) {
3741 return c / 2 * t * t * t * t + b;
3744 return -c / 2 * ((t -= 2) * t * t * t - 2) + b;
3749 elasticIn: function (t, b, c, d, a, p) {
3753 if ((t /= d) == 1) {
3760 if (!a || a < Math.abs(c)) {
3765 var s = p / (2 * Math.PI) * Math.asin(c / a);
3768 return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
3772 elasticOut: function (t, b, c, d, a, p) {
3776 if ((t /= d) == 1) {
3783 if (!a || a < Math.abs(c)) {
3788 var s = p / (2 * Math.PI) * Math.asin(c / a);
3791 return a * Math.pow(2, -10 * t) * Math.sin((t * d - s) * (2 * Math.PI) / p) + c + b;
3795 elasticBoth: function (t, b, c, d, a, p) {
3800 if ((t /= d / 2) == 2) {
3808 if (!a || a < Math.abs(c)) {
3813 var s = p / (2 * Math.PI) * Math.asin(c / a);
3817 return -.5 * (a * Math.pow(2, 10 * (t -= 1)) *
3818 Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
3820 return a * Math.pow(2, -10 * (t -= 1)) *
3821 Math.sin((t * d - s) * (2 * Math.PI) / p) * .5 + c + b;
3826 backIn: function (t, b, c, d, s) {
3827 if (typeof s == 'undefined') {
3830 return c * (t /= d) * t * ((s + 1) * t - s) + b;
3834 backOut: function (t, b, c, d, s) {
3835 if (typeof s == 'undefined') {
3838 return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
3842 backBoth: function (t, b, c, d, s) {
3843 if (typeof s == 'undefined') {
3847 if ((t /= d / 2 ) < 1) {
3848 return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b;
3850 return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;
3854 bounceIn: function (t, b, c, d) {
3855 return c - Roo.lib.Easing.bounceOut(d - t, 0, c, d) + b;
3859 bounceOut: function (t, b, c, d) {
3860 if ((t /= d) < (1 / 2.75)) {
3861 return c * (7.5625 * t * t) + b;
3862 } else if (t < (2 / 2.75)) {
3863 return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b;
3864 } else if (t < (2.5 / 2.75)) {
3865 return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b;
3867 return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b;
3871 bounceBoth: function (t, b, c, d) {
3873 return Roo.lib.Easing.bounceIn(t * 2, 0, c, d) * .5 + b;
3875 return Roo.lib.Easing.bounceOut(t * 2 - d, 0, c, d) * .5 + c * .5 + b;
3878 * Portions of this file are based on pieces of Yahoo User Interface Library
3879 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3880 * YUI licensed under the BSD License:
3881 * http://developer.yahoo.net/yui/license.txt
3882 * <script type="text/javascript">
3886 Roo.lib.Motion = function(el, attributes, duration, method) {
3888 Roo.lib.Motion.superclass.constructor.call(this, el, attributes, duration, method);
3892 Roo.extend(Roo.lib.Motion, Roo.lib.ColorAnim);
3896 var superclass = Y.Motion.superclass;
3897 var proto = Y.Motion.prototype;
3899 proto.toString = function() {
3900 var el = this.getEl();
3901 var id = el.id || el.tagName;
3902 return ("Motion " + id);
3905 proto.patterns.points = /^points$/i;
3907 proto.setAttribute = function(attr, val, unit) {
3908 if (this.patterns.points.test(attr)) {
3909 unit = unit || 'px';
3910 superclass.setAttribute.call(this, 'left', val[0], unit);
3911 superclass.setAttribute.call(this, 'top', val[1], unit);
3913 superclass.setAttribute.call(this, attr, val, unit);
3917 proto.getAttribute = function(attr) {
3918 if (this.patterns.points.test(attr)) {
3920 superclass.getAttribute.call(this, 'left'),
3921 superclass.getAttribute.call(this, 'top')
3924 val = superclass.getAttribute.call(this, attr);
3930 proto.doMethod = function(attr, start, end) {
3933 if (this.patterns.points.test(attr)) {
3934 var t = this.method(this.currentFrame, 0, 100, this.totalFrames) / 100;
3935 val = Y.Bezier.getPosition(this.runtimeAttributes[attr], t);
3937 val = superclass.doMethod.call(this, attr, start, end);
3942 proto.setRuntimeAttribute = function(attr) {
3943 if (this.patterns.points.test(attr)) {
3944 var el = this.getEl();
3945 var attributes = this.attributes;
3947 var control = attributes['points']['control'] || [];
3951 if (control.length > 0 && !(control[0] instanceof Array)) {
3952 control = [control];
3955 for (i = 0,len = control.length; i < len; ++i) {
3956 tmp[i] = control[i];
3961 Roo.fly(el).position();
3963 if (isset(attributes['points']['from'])) {
3964 Roo.lib.Dom.setXY(el, attributes['points']['from']);
3967 Roo.lib.Dom.setXY(el, Roo.lib.Dom.getXY(el));
3970 start = this.getAttribute('points');
3973 if (isset(attributes['points']['to'])) {
3974 end = translateValues.call(this, attributes['points']['to'], start);
3976 var pageXY = Roo.lib.Dom.getXY(this.getEl());
3977 for (i = 0,len = control.length; i < len; ++i) {
3978 control[i] = translateValues.call(this, control[i], start);
3982 } else if (isset(attributes['points']['by'])) {
3983 end = [ start[0] + attributes['points']['by'][0], start[1] + attributes['points']['by'][1] ];
3985 for (i = 0,len = control.length; i < len; ++i) {
3986 control[i] = [ start[0] + control[i][0], start[1] + control[i][1] ];
3990 this.runtimeAttributes[attr] = [start];
3992 if (control.length > 0) {
3993 this.runtimeAttributes[attr] = this.runtimeAttributes[attr].concat(control);
3996 this.runtimeAttributes[attr][this.runtimeAttributes[attr].length] = end;
3999 superclass.setRuntimeAttribute.call(this, attr);
4003 var translateValues = function(val, start) {
4004 var pageXY = Roo.lib.Dom.getXY(this.getEl());
4005 val = [ val[0] - pageXY[0] + start[0], val[1] - pageXY[1] + start[1] ];
4010 var isset = function(prop) {
4011 return (typeof prop !== 'undefined');
4015 * Portions of this file are based on pieces of Yahoo User Interface Library
4016 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
4017 * YUI licensed under the BSD License:
4018 * http://developer.yahoo.net/yui/license.txt
4019 * <script type="text/javascript">
4023 Roo.lib.Scroll = function(el, attributes, duration, method) {
4025 Roo.lib.Scroll.superclass.constructor.call(this, el, attributes, duration, method);
4029 Roo.extend(Roo.lib.Scroll, Roo.lib.ColorAnim);
4033 var superclass = Y.Scroll.superclass;
4034 var proto = Y.Scroll.prototype;
4036 proto.toString = function() {
4037 var el = this.getEl();
4038 var id = el.id || el.tagName;
4039 return ("Scroll " + id);
4042 proto.doMethod = function(attr, start, end) {
4045 if (attr == 'scroll') {
4047 this.method(this.currentFrame, start[0], end[0] - start[0], this.totalFrames),
4048 this.method(this.currentFrame, start[1], end[1] - start[1], this.totalFrames)
4052 val = superclass.doMethod.call(this, attr, start, end);
4057 proto.getAttribute = function(attr) {
4059 var el = this.getEl();
4061 if (attr == 'scroll') {
4062 val = [ el.scrollLeft, el.scrollTop ];
4064 val = superclass.getAttribute.call(this, attr);
4070 proto.setAttribute = function(attr, val, unit) {
4071 var el = this.getEl();
4073 if (attr == 'scroll') {
4074 el.scrollLeft = val[0];
4075 el.scrollTop = val[1];
4077 superclass.setAttribute.call(this, attr, val, unit);
4083 * Ext JS Library 1.1.1
4084 * Copyright(c) 2006-2007, Ext JS, LLC.
4086 * Originally Released Under LGPL - original licence link has changed is not relivant.
4089 * <script type="text/javascript">
4093 // nasty IE9 hack - what a pile of crap that is..
4095 if (typeof Range != "undefined" && typeof Range.prototype.createContextualFragment == "undefined") {
4096 Range.prototype.createContextualFragment = function (html) {
4097 var doc = window.document;
4098 var container = doc.createElement("div");
4099 container.innerHTML = html;
4100 var frag = doc.createDocumentFragment(), n;
4101 while ((n = container.firstChild)) {
4102 frag.appendChild(n);
4109 * @class Roo.DomHelper
4110 * Utility class for working with DOM and/or Templates. It transparently supports using HTML fragments or DOM.
4111 * For more information see <a href="http://web.archive.org/web/20071221063734/http://www.jackslocum.com/blog/2006/10/06/domhelper-create-elements-using-dom-html-fragments-or-templates/">this blog post with examples</a>.
4114 Roo.DomHelper = function(){
4115 var tempTableEl = null;
4116 var emptyTags = /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i;
4117 var tableRe = /^table|tbody|tr|td$/i;
4119 // build as innerHTML where available
4121 var createHtml = function(o){
4122 if(typeof o == 'string'){
4131 if(attr == "tag" || attr == "children" || attr == "cn" || attr == "html" || typeof o[attr] == "function") continue;
4132 if(attr == "style"){
4134 if(typeof s == "function"){
4137 if(typeof s == "string"){
4138 b += ' style="' + s + '"';
4139 }else if(typeof s == "object"){
4142 if(typeof s[key] != "function"){
4143 b += key + ":" + s[key] + ";";
4150 b += ' class="' + o["cls"] + '"';
4151 }else if(attr == "htmlFor"){
4152 b += ' for="' + o["htmlFor"] + '"';
4154 b += " " + attr + '="' + o[attr] + '"';
4158 if(emptyTags.test(o.tag)){
4162 var cn = o.children || o.cn;
4164 //http://bugs.kde.org/show_bug.cgi?id=71506
4165 if((cn instanceof Array) || (Roo.isSafari && typeof(cn.join) == "function")){
4166 for(var i = 0, len = cn.length; i < len; i++) {
4167 b += createHtml(cn[i], b);
4170 b += createHtml(cn, b);
4176 b += "</" + o.tag + ">";
4183 var createDom = function(o, parentNode){
4185 // defininition craeted..
4187 if (o.ns && o.ns != 'html') {
4189 if (o.xmlns && typeof(xmlns[o.ns]) == 'undefined') {
4190 xmlns[o.ns] = o.xmlns;
4193 if (typeof(xmlns[o.ns]) == 'undefined') {
4194 console.log("Trying to create namespace element " + o.ns + ", however no xmlns was sent to builder previously");
4200 if (typeof(o) == 'string') {
4201 return parentNode.appendChild(document.createTextNode(o));
4203 o.tag = o.tag || div;
4204 if (o.ns && Roo.isIE) {
4206 o.tag = o.ns + ':' + o.tag;
4209 var el = ns ? document.createElementNS( ns, o.tag||'div') : document.createElement(o.tag||'div');
4210 var useSet = el.setAttribute ? true : false; // In IE some elements don't have setAttribute
4213 if(attr == "tag" || attr == "ns" ||attr == "xmlns" ||attr == "children" || attr == "cn" || attr == "html" ||
4214 attr == "style" || typeof o[attr] == "function") continue;
4216 if(attr=="cls" && Roo.isIE){
4217 el.className = o["cls"];
4219 if(useSet) el.setAttribute(attr=="cls" ? 'class' : attr, o[attr]);
4220 else el[attr] = o[attr];
4223 Roo.DomHelper.applyStyles(el, o.style);
4224 var cn = o.children || o.cn;
4226 //http://bugs.kde.org/show_bug.cgi?id=71506
4227 if((cn instanceof Array) || (Roo.isSafari && typeof(cn.join) == "function")){
4228 for(var i = 0, len = cn.length; i < len; i++) {
4229 createDom(cn[i], el);
4236 el.innerHTML = o.html;
4239 parentNode.appendChild(el);
4244 var ieTable = function(depth, s, h, e){
4245 tempTableEl.innerHTML = [s, h, e].join('');
4246 var i = -1, el = tempTableEl;
4253 // kill repeat to save bytes
4257 tbe = '</tbody>'+te,
4263 * Nasty code for IE's broken table implementation
4265 var insertIntoTable = function(tag, where, el, html){
4267 tempTableEl = document.createElement('div');
4272 if(where == 'afterbegin' || where == 'beforeend'){ // INTO a TD
4275 if(where == 'beforebegin'){
4279 before = el.nextSibling;
4282 node = ieTable(4, trs, html, tre);
4284 else if(tag == 'tr'){
4285 if(where == 'beforebegin'){
4288 node = ieTable(3, tbs, html, tbe);
4289 } else if(where == 'afterend'){
4290 before = el.nextSibling;
4292 node = ieTable(3, tbs, html, tbe);
4293 } else{ // INTO a TR
4294 if(where == 'afterbegin'){
4295 before = el.firstChild;
4297 node = ieTable(4, trs, html, tre);
4299 } else if(tag == 'tbody'){
4300 if(where == 'beforebegin'){
4303 node = ieTable(2, ts, html, te);
4304 } else if(where == 'afterend'){
4305 before = el.nextSibling;
4307 node = ieTable(2, ts, html, te);
4309 if(where == 'afterbegin'){
4310 before = el.firstChild;
4312 node = ieTable(3, tbs, html, tbe);
4315 if(where == 'beforebegin' || where == 'afterend'){ // OUTSIDE the table
4318 if(where == 'afterbegin'){
4319 before = el.firstChild;
4321 node = ieTable(2, ts, html, te);
4323 el.insertBefore(node, before);
4328 /** True to force the use of DOM instead of html fragments @type Boolean */
4332 * Returns the markup for the passed Element(s) config
4333 * @param {Object} o The Dom object spec (and children)
4336 markup : function(o){
4337 return createHtml(o);
4341 * Applies a style specification to an element
4342 * @param {String/HTMLElement} el The element to apply styles to
4343 * @param {String/Object/Function} styles A style specification string eg "width:100px", or object in the form {width:"100px"}, or
4344 * a function which returns such a specification.
4346 applyStyles : function(el, styles){
4349 if(typeof styles == "string"){
4350 var re = /\s?([a-z\-]*)\:\s?([^;]*);?/gi;
4352 while ((matches = re.exec(styles)) != null){
4353 el.setStyle(matches[1], matches[2]);
4355 }else if (typeof styles == "object"){
4356 for (var style in styles){
4357 el.setStyle(style, styles[style]);
4359 }else if (typeof styles == "function"){
4360 Roo.DomHelper.applyStyles(el, styles.call());
4366 * Inserts an HTML fragment into the Dom
4367 * @param {String} where Where to insert the html in relation to el - beforeBegin, afterBegin, beforeEnd, afterEnd.
4368 * @param {HTMLElement} el The context element
4369 * @param {String} html The HTML fragmenet
4370 * @return {HTMLElement} The new node
4372 insertHtml : function(where, el, html){
4373 where = where.toLowerCase();
4374 if(el.insertAdjacentHTML){
4375 if(tableRe.test(el.tagName)){
4377 if(rs = insertIntoTable(el.tagName.toLowerCase(), where, el, html)){
4383 el.insertAdjacentHTML('BeforeBegin', html);
4384 return el.previousSibling;
4386 el.insertAdjacentHTML('AfterBegin', html);
4387 return el.firstChild;
4389 el.insertAdjacentHTML('BeforeEnd', html);
4390 return el.lastChild;
4392 el.insertAdjacentHTML('AfterEnd', html);
4393 return el.nextSibling;
4395 throw 'Illegal insertion point -> "' + where + '"';
4397 var range = el.ownerDocument.createRange();
4401 range.setStartBefore(el);
4402 frag = range.createContextualFragment(html);
4403 el.parentNode.insertBefore(frag, el);
4404 return el.previousSibling;
4407 range.setStartBefore(el.firstChild);
4408 frag = range.createContextualFragment(html);
4409 el.insertBefore(frag, el.firstChild);
4410 return el.firstChild;
4412 el.innerHTML = html;
4413 return el.firstChild;
4417 range.setStartAfter(el.lastChild);
4418 frag = range.createContextualFragment(html);
4419 el.appendChild(frag);
4420 return el.lastChild;
4422 el.innerHTML = html;
4423 return el.lastChild;
4426 range.setStartAfter(el);
4427 frag = range.createContextualFragment(html);
4428 el.parentNode.insertBefore(frag, el.nextSibling);
4429 return el.nextSibling;
4431 throw 'Illegal insertion point -> "' + where + '"';
4435 * Creates new Dom element(s) and inserts them before el
4436 * @param {String/HTMLElement/Element} el The context element
4437 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
4438 * @param {Boolean} returnElement (optional) true to return a Roo.Element
4439 * @return {HTMLElement/Roo.Element} The new node
4441 insertBefore : function(el, o, returnElement){
4442 return this.doInsert(el, o, returnElement, "beforeBegin");
4446 * Creates new Dom element(s) and inserts them after el
4447 * @param {String/HTMLElement/Element} el The context element
4448 * @param {Object} o The Dom object spec (and children)
4449 * @param {Boolean} returnElement (optional) true to return a Roo.Element
4450 * @return {HTMLElement/Roo.Element} The new node
4452 insertAfter : function(el, o, returnElement){
4453 return this.doInsert(el, o, returnElement, "afterEnd", "nextSibling");
4457 * Creates new Dom element(s) and inserts them as the first child of el
4458 * @param {String/HTMLElement/Element} el The context element
4459 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
4460 * @param {Boolean} returnElement (optional) true to return a Roo.Element
4461 * @return {HTMLElement/Roo.Element} The new node
4463 insertFirst : function(el, o, returnElement){
4464 return this.doInsert(el, o, returnElement, "afterBegin");
4468 doInsert : function(el, o, returnElement, pos, sibling){
4469 el = Roo.getDom(el);
4471 if(this.useDom || o.ns){
4472 newNode = createDom(o, null);
4473 el.parentNode.insertBefore(newNode, sibling ? el[sibling] : el);
4475 var html = createHtml(o);
4476 newNode = this.insertHtml(pos, el, html);
4478 return returnElement ? Roo.get(newNode, true) : newNode;
4482 * Creates new Dom element(s) and appends them to el
4483 * @param {String/HTMLElement/Element} el The context element
4484 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
4485 * @param {Boolean} returnElement (optional) true to return a Roo.Element
4486 * @return {HTMLElement/Roo.Element} The new node
4488 append : function(el, o, returnElement){
4489 el = Roo.getDom(el);
4491 if(this.useDom || o.ns){
4492 newNode = createDom(o, null);
4493 el.appendChild(newNode);
4495 var html = createHtml(o);
4496 newNode = this.insertHtml("beforeEnd", el, html);
4498 return returnElement ? Roo.get(newNode, true) : newNode;
4502 * Creates new Dom element(s) and overwrites the contents of el with them
4503 * @param {String/HTMLElement/Element} el The context element
4504 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
4505 * @param {Boolean} returnElement (optional) true to return a Roo.Element
4506 * @return {HTMLElement/Roo.Element} The new node
4508 overwrite : function(el, o, returnElement){
4509 el = Roo.getDom(el);
4512 while (el.childNodes.length) {
4513 el.removeChild(el.firstChild);
4517 el.innerHTML = createHtml(o);
4520 return returnElement ? Roo.get(el.firstChild, true) : el.firstChild;
4524 * Creates a new Roo.DomHelper.Template from the Dom object spec
4525 * @param {Object} o The Dom object spec (and children)
4526 * @return {Roo.DomHelper.Template} The new template
4528 createTemplate : function(o){
4529 var html = createHtml(o);
4530 return new Roo.Template(html);
4536 * Ext JS Library 1.1.1
4537 * Copyright(c) 2006-2007, Ext JS, LLC.
4539 * Originally Released Under LGPL - original licence link has changed is not relivant.
4542 * <script type="text/javascript">
4546 * @class Roo.Template
4547 * Represents an HTML fragment template. Templates can be precompiled for greater performance.
4548 * For a list of available format functions, see {@link Roo.util.Format}.<br />
4551 var t = new Roo.Template({
4552 html : '<div name="{id}">' +
4553 '<span class="{cls}">{name:trim} {someval:this.myformat}{value:ellipsis(10)}</span>' +
4555 myformat: function (value, allValues) {
4556 return 'XX' + value;
4559 t.append('some-element', {id: 'myid', cls: 'myclass', name: 'foo', value: 'bar'});
4561 * For more information see this blog post with examples:
4562 * <a href="http://www.cnitblog.com/seeyeah/archive/2011/12/30/38728.html/">DomHelper
4563 - Create Elements using DOM, HTML fragments and Templates</a>.
4565 * @param {Object} cfg - Configuration object.
4567 Roo.Template = function(cfg){
4569 if(cfg instanceof Array){
4571 }else if(arguments.length > 1){
4572 cfg = Array.prototype.join.call(arguments, "");
4576 if (typeof(cfg) == 'object') {
4587 Roo.Template.prototype = {
4590 * @cfg {String} url The Url to load the template from. beware if you are loading from a url, the data may not be ready if you use it instantly..
4591 * it should be fixed so that template is observable...
4595 * @cfg {String} html The HTML fragment or an array of fragments to join("") or multiple arguments to join("")
4599 * Returns an HTML fragment of this template with the specified values applied.
4600 * @param {Object} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'})
4601 * @return {String} The HTML fragment
4603 applyTemplate : function(values){
4607 return this.compiled(values);
4609 var useF = this.disableFormats !== true;
4610 var fm = Roo.util.Format, tpl = this;
4611 var fn = function(m, name, format, args){
4613 if(format.substr(0, 5) == "this."){
4614 return tpl.call(format.substr(5), values[name], values);
4617 // quoted values are required for strings in compiled templates,
4618 // but for non compiled we need to strip them
4619 // quoted reversed for jsmin
4620 var re = /^\s*['"](.*)["']\s*$/;
4621 args = args.split(',');
4622 for(var i = 0, len = args.length; i < len; i++){
4623 args[i] = args[i].replace(re, "$1");
4625 args = [values[name]].concat(args);
4627 args = [values[name]];
4629 return fm[format].apply(fm, args);
4632 return values[name] !== undefined ? values[name] : "";
4635 return this.html.replace(this.re, fn);
4653 this.loading = true;
4654 this.compiled = false;
4656 var cx = new Roo.data.Connection();
4660 success : function (response) {
4662 _t.html = response.responseText;
4666 failure : function(response) {
4667 Roo.log("Template failed to load from " + _t.url);
4674 * Sets the HTML used as the template and optionally compiles it.
4675 * @param {String} html
4676 * @param {Boolean} compile (optional) True to compile the template (defaults to undefined)
4677 * @return {Roo.Template} this
4679 set : function(html, compile){
4681 this.compiled = null;
4689 * True to disable format functions (defaults to false)
4692 disableFormats : false,
4695 * The regular expression used to match template variables
4699 re : /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
4702 * Compiles the template into an internal function, eliminating the RegEx overhead.
4703 * @return {Roo.Template} this
4705 compile : function(){
4706 var fm = Roo.util.Format;
4707 var useF = this.disableFormats !== true;
4708 var sep = Roo.isGecko ? "+" : ",";
4709 var fn = function(m, name, format, args){
4711 args = args ? ',' + args : "";
4712 if(format.substr(0, 5) != "this."){
4713 format = "fm." + format + '(';
4715 format = 'this.call("'+ format.substr(5) + '", ';
4719 args= ''; format = "(values['" + name + "'] == undefined ? '' : ";
4721 return "'"+ sep + format + "values['" + name + "']" + args + ")"+sep+"'";
4724 // branched to use + in gecko and [].join() in others
4726 body = "this.compiled = function(values){ return '" +
4727 this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
4730 body = ["this.compiled = function(values){ return ['"];
4731 body.push(this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn));
4732 body.push("'].join('');};");
4733 body = body.join('');
4743 // private function used to call members
4744 call : function(fnName, value, allValues){
4745 return this[fnName](value, allValues);
4749 * Applies the supplied values to the template and inserts the new node(s) as the first child of el.
4750 * @param {String/HTMLElement/Roo.Element} el The context element
4751 * @param {Object} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'})
4752 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
4753 * @return {HTMLElement/Roo.Element} The new node or Element
4755 insertFirst: function(el, values, returnElement){
4756 return this.doInsert('afterBegin', el, values, returnElement);
4760 * Applies the supplied values to the template and inserts the new node(s) before el.
4761 * @param {String/HTMLElement/Roo.Element} el The context element
4762 * @param {Object} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'})
4763 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
4764 * @return {HTMLElement/Roo.Element} The new node or Element
4766 insertBefore: function(el, values, returnElement){
4767 return this.doInsert('beforeBegin', el, values, returnElement);
4771 * Applies the supplied values to the template and inserts the new node(s) after el.
4772 * @param {String/HTMLElement/Roo.Element} el The context element
4773 * @param {Object} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'})
4774 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
4775 * @return {HTMLElement/Roo.Element} The new node or Element
4777 insertAfter : function(el, values, returnElement){
4778 return this.doInsert('afterEnd', el, values, returnElement);
4782 * Applies the supplied values to the template and appends the new node(s) to el.
4783 * @param {String/HTMLElement/Roo.Element} el The context element
4784 * @param {Object} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'})
4785 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
4786 * @return {HTMLElement/Roo.Element} The new node or Element
4788 append : function(el, values, returnElement){
4789 return this.doInsert('beforeEnd', el, values, returnElement);
4792 doInsert : function(where, el, values, returnEl){
4793 el = Roo.getDom(el);
4794 var newNode = Roo.DomHelper.insertHtml(where, el, this.applyTemplate(values));
4795 return returnEl ? Roo.get(newNode, true) : newNode;
4799 * Applies the supplied values to the template and overwrites the content of el with the new node(s).
4800 * @param {String/HTMLElement/Roo.Element} el The context element
4801 * @param {Object} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'})
4802 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
4803 * @return {HTMLElement/Roo.Element} The new node or Element
4805 overwrite : function(el, values, returnElement){
4806 el = Roo.getDom(el);
4807 el.innerHTML = this.applyTemplate(values);
4808 return returnElement ? Roo.get(el.firstChild, true) : el.firstChild;
4812 * Alias for {@link #applyTemplate}
4815 Roo.Template.prototype.apply = Roo.Template.prototype.applyTemplate;
4818 Roo.DomHelper.Template = Roo.Template;
4821 * Creates a template from the passed element's value (<i>display:none</i> textarea, preferred) or innerHTML.
4822 * @param {String/HTMLElement} el A DOM element or its id
4823 * @returns {Roo.Template} The created template
4826 Roo.Template.from = function(el){
4827 el = Roo.getDom(el);
4828 return new Roo.Template(el.value || el.innerHTML);
4831 * Ext JS Library 1.1.1
4832 * Copyright(c) 2006-2007, Ext JS, LLC.
4834 * Originally Released Under LGPL - original licence link has changed is not relivant.
4837 * <script type="text/javascript">
4842 * This is code is also distributed under MIT license for use
4843 * with jQuery and prototype JavaScript libraries.
4846 * @class Roo.DomQuery
4847 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).
4849 DomQuery supports most of the <a href="http://www.w3.org/TR/2005/WD-css3-selectors-20051215/">CSS3 selectors spec</a>, along with some custom selectors and basic XPath.</p>
4852 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.
4854 <h4>Element Selectors:</h4>
4856 <li> <b>*</b> any element</li>
4857 <li> <b>E</b> an element with the tag E</li>
4858 <li> <b>E F</b> All descendent elements of E that have the tag F</li>
4859 <li> <b>E > F</b> or <b>E/F</b> all direct children elements of E that have the tag F</li>
4860 <li> <b>E + F</b> all elements with the tag F that are immediately preceded by an element with the tag E</li>
4861 <li> <b>E ~ F</b> all elements with the tag F that are preceded by a sibling element with the tag E</li>
4863 <h4>Attribute Selectors:</h4>
4864 <p>The use of @ and quotes are optional. For example, div[@foo='bar'] is also a valid attribute selector.</p>
4866 <li> <b>E[foo]</b> has an attribute "foo"</li>
4867 <li> <b>E[foo=bar]</b> has an attribute "foo" that equals "bar"</li>
4868 <li> <b>E[foo^=bar]</b> has an attribute "foo" that starts with "bar"</li>
4869 <li> <b>E[foo$=bar]</b> has an attribute "foo" that ends with "bar"</li>
4870 <li> <b>E[foo*=bar]</b> has an attribute "foo" that contains the substring "bar"</li>
4871 <li> <b>E[foo%=2]</b> has an attribute "foo" that is evenly divisible by 2</li>
4872 <li> <b>E[foo!=bar]</b> has an attribute "foo" that does not equal "bar"</li>
4874 <h4>Pseudo Classes:</h4>
4876 <li> <b>E:first-child</b> E is the first child of its parent</li>
4877 <li> <b>E:last-child</b> E is the last child of its parent</li>
4878 <li> <b>E:nth-child(<i>n</i>)</b> E is the <i>n</i>th child of its parent (1 based as per the spec)</li>
4879 <li> <b>E:nth-child(odd)</b> E is an odd child of its parent</li>
4880 <li> <b>E:nth-child(even)</b> E is an even child of its parent</li>
4881 <li> <b>E:only-child</b> E is the only child of its parent</li>
4882 <li> <b>E:checked</b> E is an element that is has a checked attribute that is true (e.g. a radio or checkbox) </li>
4883 <li> <b>E:first</b> the first E in the resultset</li>
4884 <li> <b>E:last</b> the last E in the resultset</li>
4885 <li> <b>E:nth(<i>n</i>)</b> the <i>n</i>th E in the resultset (1 based)</li>
4886 <li> <b>E:odd</b> shortcut for :nth-child(odd)</li>
4887 <li> <b>E:even</b> shortcut for :nth-child(even)</li>
4888 <li> <b>E:contains(foo)</b> E's innerHTML contains the substring "foo"</li>
4889 <li> <b>E:nodeValue(foo)</b> E contains a textNode with a nodeValue that equals "foo"</li>
4890 <li> <b>E:not(S)</b> an E element that does not match simple selector S</li>
4891 <li> <b>E:has(S)</b> an E element that has a descendent that matches simple selector S</li>
4892 <li> <b>E:next(S)</b> an E element whose next sibling matches simple selector S</li>
4893 <li> <b>E:prev(S)</b> an E element whose previous sibling matches simple selector S</li>
4895 <h4>CSS Value Selectors:</h4>
4897 <li> <b>E{display=none}</b> css value "display" that equals "none"</li>
4898 <li> <b>E{display^=none}</b> css value "display" that starts with "none"</li>
4899 <li> <b>E{display$=none}</b> css value "display" that ends with "none"</li>
4900 <li> <b>E{display*=none}</b> css value "display" that contains the substring "none"</li>
4901 <li> <b>E{display%=2}</b> css value "display" that is evenly divisible by 2</li>
4902 <li> <b>E{display!=none}</b> css value "display" that does not equal "none"</li>
4906 Roo.DomQuery = function(){
4907 var cache = {}, simpleCache = {}, valueCache = {};
4908 var nonSpace = /\S/;
4909 var trimRe = /^\s+|\s+$/g;
4910 var tplRe = /\{(\d+)\}/g;
4911 var modeRe = /^(\s?[\/>+~]\s?|\s|$)/;
4912 var tagTokenRe = /^(#)?([\w-\*]+)/;
4913 var nthRe = /(\d*)n\+?(\d*)/, nthRe2 = /\D/;
4915 function child(p, index){
4917 var n = p.firstChild;
4919 if(n.nodeType == 1){
4930 while((n = n.nextSibling) && n.nodeType != 1);
4935 while((n = n.previousSibling) && n.nodeType != 1);
4939 function children(d){
4940 var n = d.firstChild, ni = -1;
4942 var nx = n.nextSibling;
4943 if(n.nodeType == 3 && !nonSpace.test(n.nodeValue)){
4953 function byClassName(c, a, v){
4957 var r = [], ri = -1, cn;
4958 for(var i = 0, ci; ci = c[i]; i++){
4959 if((' '+ci.className+' ').indexOf(v) != -1){
4966 function attrValue(n, attr){
4967 if(!n.tagName && typeof n.length != "undefined"){
4976 if(attr == "class" || attr == "className"){
4979 return n.getAttribute(attr) || n[attr];
4983 function getNodes(ns, mode, tagName){
4984 var result = [], ri = -1, cs;
4988 tagName = tagName || "*";
4989 if(typeof ns.getElementsByTagName != "undefined"){
4993 for(var i = 0, ni; ni = ns[i]; i++){
4994 cs = ni.getElementsByTagName(tagName);
4995 for(var j = 0, ci; ci = cs[j]; j++){
4999 }else if(mode == "/" || mode == ">"){
5000 var utag = tagName.toUpperCase();
5001 for(var i = 0, ni, cn; ni = ns[i]; i++){
5002 cn = ni.children || ni.childNodes;
5003 for(var j = 0, cj; cj = cn[j]; j++){
5004 if(cj.nodeName == utag || cj.nodeName == tagName || tagName == '*'){
5009 }else if(mode == "+"){
5010 var utag = tagName.toUpperCase();
5011 for(var i = 0, n; n = ns[i]; i++){
5012 while((n = n.nextSibling) && n.nodeType != 1);
5013 if(n && (n.nodeName == utag || n.nodeName == tagName || tagName == '*')){
5017 }else if(mode == "~"){
5018 for(var i = 0, n; n = ns[i]; i++){
5019 while((n = n.nextSibling) && (n.nodeType != 1 || (tagName == '*' || n.tagName.toLowerCase()!=tagName)));
5028 function concat(a, b){
5032 for(var i = 0, l = b.length; i < l; i++){
5038 function byTag(cs, tagName){
5039 if(cs.tagName || cs == document){
5045 var r = [], ri = -1;
5046 tagName = tagName.toLowerCase();
5047 for(var i = 0, ci; ci = cs[i]; i++){
5048 if(ci.nodeType == 1 && ci.tagName.toLowerCase()==tagName){
5055 function byId(cs, attr, id){
5056 if(cs.tagName || cs == document){
5062 var r = [], ri = -1;
5063 for(var i = 0,ci; ci = cs[i]; i++){
5064 if(ci && ci.id == id){
5072 function byAttribute(cs, attr, value, op, custom){
5073 var r = [], ri = -1, st = custom=="{";
5074 var f = Roo.DomQuery.operators[op];
5075 for(var i = 0, ci; ci = cs[i]; i++){
5078 a = Roo.DomQuery.getStyle(ci, attr);
5080 else if(attr == "class" || attr == "className"){
5082 }else if(attr == "for"){
5084 }else if(attr == "href"){
5085 a = ci.getAttribute("href", 2);
5087 a = ci.getAttribute(attr);
5089 if((f && f(a, value)) || (!f && a)){
5096 function byPseudo(cs, name, value){
5097 return Roo.DomQuery.pseudos[name](cs, value);
5100 // This is for IE MSXML which does not support expandos.
5101 // IE runs the same speed using setAttribute, however FF slows way down
5102 // and Safari completely fails so they need to continue to use expandos.
5103 var isIE = window.ActiveXObject ? true : false;
5105 // this eval is stop the compressor from
5106 // renaming the variable to something shorter
5108 /** eval:var:batch */
5113 function nodupIEXml(cs){
5115 cs[0].setAttribute("_nodup", d);
5117 for(var i = 1, len = cs.length; i < len; i++){
5119 if(!c.getAttribute("_nodup") != d){
5120 c.setAttribute("_nodup", d);
5124 for(var i = 0, len = cs.length; i < len; i++){
5125 cs[i].removeAttribute("_nodup");
5134 var len = cs.length, c, i, r = cs, cj, ri = -1;
5135 if(!len || typeof cs.nodeType != "undefined" || len == 1){
5138 if(isIE && typeof cs[0].selectSingleNode != "undefined"){
5139 return nodupIEXml(cs);
5143 for(i = 1; c = cs[i]; i++){
5148 for(var j = 0; j < i; j++){
5151 for(j = i+1; cj = cs[j]; j++){
5163 function quickDiffIEXml(c1, c2){
5165 for(var i = 0, len = c1.length; i < len; i++){
5166 c1[i].setAttribute("_qdiff", d);
5169 for(var i = 0, len = c2.length; i < len; i++){
5170 if(c2[i].getAttribute("_qdiff") != d){
5171 r[r.length] = c2[i];
5174 for(var i = 0, len = c1.length; i < len; i++){
5175 c1[i].removeAttribute("_qdiff");
5180 function quickDiff(c1, c2){
5181 var len1 = c1.length;
5185 if(isIE && c1[0].selectSingleNode){
5186 return quickDiffIEXml(c1, c2);
5189 for(var i = 0; i < len1; i++){
5193 for(var i = 0, len = c2.length; i < len; i++){
5194 if(c2[i]._qdiff != d){
5195 r[r.length] = c2[i];
5201 function quickId(ns, mode, root, id){
5203 var d = root.ownerDocument || root;
5204 return d.getElementById(id);
5206 ns = getNodes(ns, mode, "*");
5207 return byId(ns, null, id);
5211 getStyle : function(el, name){
5212 return Roo.fly(el).getStyle(name);
5215 * Compiles a selector/xpath query into a reusable function. The returned function
5216 * takes one parameter "root" (optional), which is the context node from where the query should start.
5217 * @param {String} selector The selector/xpath query
5218 * @param {String} type (optional) Either "select" (the default) or "simple" for a simple selector match
5219 * @return {Function}
5221 compile : function(path, type){
5222 type = type || "select";
5224 var fn = ["var f = function(root){\n var mode; ++batch; var n = root || document;\n"];
5225 var q = path, mode, lq;
5226 var tk = Roo.DomQuery.matchers;
5227 var tklen = tk.length;
5232 Roo.log('compile!!!');
5234 // accept leading mode switch
5237 var lmode = q.match(modeRe);
5242 if(lmode && lmode[1]){
5243 fn[fn.length] = 'mode="'+lmode[1].replace(trimRe, "")+'";';
5244 q = q.replace(lmode[1], "");
5246 // strip leading slashes
5247 while(path.substr(0, 1)=="/"){
5248 path = path.substr(1);
5252 while(q && lq != q){
5254 var tm = q.match(tagTokenRe);
5257 if(type == "select"){
5260 fn[fn.length] = 'n = quickId(n, mode, root, "'+tm[2]+'");';
5262 fn[fn.length] = 'n = getNodes(n, mode, "'+tm[2]+'");';
5264 q = q.replace(tm[0], "");
5265 }else if(q.substr(0, 1) != '@'){
5266 fn[fn.length] = 'n = getNodes(n, mode, "*");';
5271 fn[fn.length] = 'n = byId(n, null, "'+tm[2]+'");';
5273 fn[fn.length] = 'n = byTag(n, "'+tm[2]+'");';
5275 q = q.replace(tm[0], "");
5278 while(!(mm = q.match(modeRe))){
5279 var matched = false;
5280 for(var j = 0; j < tklen; j++){
5282 var m = q.match(t.re);
5284 fn[fn.length] = t.select.replace(tplRe, function(x, i){
5287 q = q.replace(m[0], "");
5292 // prevent infinite loop on bad selector
5294 throw 'Error parsing selector, parsing failed at "' + q + '"';
5298 fn[fn.length] = 'mode="'+mm[1].replace(trimRe, "")+'";';
5299 q = q.replace(mm[1], "");
5302 fn[fn.length] = "return nodup(n);\n}";
5305 * list of variables that need from compression as they are used by eval.
5315 * eval:var:byClassName
5317 * eval:var:byAttribute
5318 * eval:var:attrValue
5326 * Selects a group of elements.
5327 * @param {String} selector The selector/xpath query (can be a comma separated list of selectors)
5328 * @param {Node} root (optional) The start of the query (defaults to document).
5331 select : function(path, root, type){
5332 if(!root || root == document){
5335 if(typeof root == "string"){
5336 root = document.getElementById(root);
5338 var paths = path.split(",");
5340 for(var i = 0, len = paths.length; i < len; i++){
5341 var p = paths[i].replace(trimRe, "");
5345 cache[p] = Roo.DomQuery.compile(p);
5347 throw p + " is not a valid selector";
5350 var result = cache[p](root);
5351 if(result && result != document){
5352 results = results.concat(result);
5355 if(paths.length > 1){
5356 return nodup(results);
5362 * Selects a single element.
5363 * @param {String} selector The selector/xpath query
5364 * @param {Node} root (optional) The start of the query (defaults to document).
5367 selectNode : function(path, root){
5368 return Roo.DomQuery.select(path, root)[0];
5372 * Selects the value of a node, optionally replacing null with the defaultValue.
5373 * @param {String} selector The selector/xpath query
5374 * @param {Node} root (optional) The start of the query (defaults to document).
5375 * @param {String} defaultValue
5377 selectValue : function(path, root, defaultValue){
5378 path = path.replace(trimRe, "");
5379 if(!valueCache[path]){
5380 valueCache[path] = Roo.DomQuery.compile(path, "select");
5382 var n = valueCache[path](root);
5383 n = n[0] ? n[0] : n;
5384 var v = (n && n.firstChild ? n.firstChild.nodeValue : null);
5385 return ((v === null||v === undefined||v==='') ? defaultValue : v);
5389 * Selects the value of a node, parsing integers and floats.
5390 * @param {String} selector The selector/xpath query
5391 * @param {Node} root (optional) The start of the query (defaults to document).
5392 * @param {Number} defaultValue
5395 selectNumber : function(path, root, defaultValue){
5396 var v = Roo.DomQuery.selectValue(path, root, defaultValue || 0);
5397 return parseFloat(v);
5401 * Returns true if the passed element(s) match the passed simple selector (e.g. div.some-class or span:first-child)
5402 * @param {String/HTMLElement/Array} el An element id, element or array of elements
5403 * @param {String} selector The simple selector to test
5406 is : function(el, ss){
5407 if(typeof el == "string"){
5408 el = document.getElementById(el);
5410 var isArray = (el instanceof Array);
5411 var result = Roo.DomQuery.filter(isArray ? el : [el], ss);
5412 return isArray ? (result.length == el.length) : (result.length > 0);
5416 * Filters an array of elements to only include matches of a simple selector (e.g. div.some-class or span:first-child)
5417 * @param {Array} el An array of elements to filter
5418 * @param {String} selector The simple selector to test
5419 * @param {Boolean} nonMatches If true, it returns the elements that DON'T match
5420 * the selector instead of the ones that match
5423 filter : function(els, ss, nonMatches){
5424 ss = ss.replace(trimRe, "");
5425 if(!simpleCache[ss]){
5426 simpleCache[ss] = Roo.DomQuery.compile(ss, "simple");
5428 var result = simpleCache[ss](els);
5429 return nonMatches ? quickDiff(result, els) : result;
5433 * Collection of matching regular expressions and code snippets.
5437 select: 'n = byClassName(n, null, " {1} ");'
5439 re: /^\:([\w-]+)(?:\(((?:[^\s>\/]*|.*?))\))?/,
5440 select: 'n = byPseudo(n, "{1}", "{2}");'
5442 re: /^(?:([\[\{])(?:@)?([\w-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]\}])/,
5443 select: 'n = byAttribute(n, "{2}", "{4}", "{3}", "{1}");'
5446 select: 'n = byId(n, null, "{1}");'
5449 select: 'return {firstChild:{nodeValue:attrValue(n, "{1}")}};'
5454 * Collection of operator comparison functions. The default operators are =, !=, ^=, $=, *=, %=, |= and ~=.
5455 * New operators can be added as long as the match the format <i>c</i>= where <i>c</i> is any character other than space, > <.
5458 "=" : function(a, v){
5461 "!=" : function(a, v){
5464 "^=" : function(a, v){
5465 return a && a.substr(0, v.length) == v;
5467 "$=" : function(a, v){
5468 return a && a.substr(a.length-v.length) == v;
5470 "*=" : function(a, v){
5471 return a && a.indexOf(v) !== -1;
5473 "%=" : function(a, v){
5474 return (a % v) == 0;
5476 "|=" : function(a, v){
5477 return a && (a == v || a.substr(0, v.length+1) == v+'-');
5479 "~=" : function(a, v){
5480 return a && (' '+a+' ').indexOf(' '+v+' ') != -1;
5485 * Collection of "pseudo class" processors. Each processor is passed the current nodeset (array)
5486 * and the argument (if any) supplied in the selector.
5489 "first-child" : function(c){
5490 var r = [], ri = -1, n;
5491 for(var i = 0, ci; ci = n = c[i]; i++){
5492 while((n = n.previousSibling) && n.nodeType != 1);
5500 "last-child" : function(c){
5501 var r = [], ri = -1, n;
5502 for(var i = 0, ci; ci = n = c[i]; i++){
5503 while((n = n.nextSibling) && n.nodeType != 1);
5511 "nth-child" : function(c, a) {
5512 var r = [], ri = -1;
5513 var m = nthRe.exec(a == "even" && "2n" || a == "odd" && "2n+1" || !nthRe2.test(a) && "n+" + a || a);
5514 var f = (m[1] || 1) - 0, l = m[2] - 0;
5515 for(var i = 0, n; n = c[i]; i++){
5516 var pn = n.parentNode;
5517 if (batch != pn._batch) {
5519 for(var cn = pn.firstChild; cn; cn = cn.nextSibling){
5520 if(cn.nodeType == 1){
5527 if (l == 0 || n.nodeIndex == l){
5530 } else if ((n.nodeIndex + l) % f == 0){
5538 "only-child" : function(c){
5539 var r = [], ri = -1;;
5540 for(var i = 0, ci; ci = c[i]; i++){
5541 if(!prev(ci) && !next(ci)){
5548 "empty" : function(c){
5549 var r = [], ri = -1;
5550 for(var i = 0, ci; ci = c[i]; i++){
5551 var cns = ci.childNodes, j = 0, cn, empty = true;
5554 if(cn.nodeType == 1 || cn.nodeType == 3){
5566 "contains" : function(c, v){
5567 var r = [], ri = -1;
5568 for(var i = 0, ci; ci = c[i]; i++){
5569 if((ci.textContent||ci.innerText||'').indexOf(v) != -1){
5576 "nodeValue" : function(c, v){
5577 var r = [], ri = -1;
5578 for(var i = 0, ci; ci = c[i]; i++){
5579 if(ci.firstChild && ci.firstChild.nodeValue == v){
5586 "checked" : function(c){
5587 var r = [], ri = -1;
5588 for(var i = 0, ci; ci = c[i]; i++){
5589 if(ci.checked == true){
5596 "not" : function(c, ss){
5597 return Roo.DomQuery.filter(c, ss, true);
5600 "odd" : function(c){
5601 return this["nth-child"](c, "odd");
5604 "even" : function(c){
5605 return this["nth-child"](c, "even");
5608 "nth" : function(c, a){
5609 return c[a-1] || [];
5612 "first" : function(c){
5616 "last" : function(c){
5617 return c[c.length-1] || [];
5620 "has" : function(c, ss){
5621 var s = Roo.DomQuery.select;
5622 var r = [], ri = -1;
5623 for(var i = 0, ci; ci = c[i]; i++){
5624 if(s(ss, ci).length > 0){
5631 "next" : function(c, ss){
5632 var is = Roo.DomQuery.is;
5633 var r = [], ri = -1;
5634 for(var i = 0, ci; ci = c[i]; i++){
5643 "prev" : function(c, ss){
5644 var is = Roo.DomQuery.is;
5645 var r = [], ri = -1;
5646 for(var i = 0, ci; ci = c[i]; i++){
5659 * Selects an array of DOM nodes by CSS/XPath selector. Shorthand of {@link Roo.DomQuery#select}
5660 * @param {String} path The selector/xpath query
5661 * @param {Node} root (optional) The start of the query (defaults to document).
5666 Roo.query = Roo.DomQuery.select;
5669 * Ext JS Library 1.1.1
5670 * Copyright(c) 2006-2007, Ext JS, LLC.
5672 * Originally Released Under LGPL - original licence link has changed is not relivant.
5675 * <script type="text/javascript">
5679 * @class Roo.util.Observable
5680 * Base class that provides a common interface for publishing events. Subclasses are expected to
5681 * to have a property "events" with all the events defined.<br>
5684 Employee = function(name){
5691 Roo.extend(Employee, Roo.util.Observable);
5693 * @param {Object} config properties to use (incuding events / listeners)
5696 Roo.util.Observable = function(cfg){
5699 this.addEvents(cfg.events || {});
5701 delete cfg.events; // make sure
5704 Roo.apply(this, cfg);
5707 this.on(this.listeners);
5708 delete this.listeners;
5711 Roo.util.Observable.prototype = {
5713 * @cfg {Object} listeners list of events and functions to call for this object,
5717 'click' : function(e) {
5727 * Fires the specified event with the passed parameters (minus the event name).
5728 * @param {String} eventName
5729 * @param {Object...} args Variable number of parameters are passed to handlers
5730 * @return {Boolean} returns false if any of the handlers return false otherwise it returns true
5732 fireEvent : function(){
5733 var ce = this.events[arguments[0].toLowerCase()];
5734 if(typeof ce == "object"){
5735 return ce.fire.apply(ce, Array.prototype.slice.call(arguments, 1));
5742 filterOptRe : /^(?:scope|delay|buffer|single)$/,
5745 * Appends an event handler to this component
5746 * @param {String} eventName The type of event to listen for
5747 * @param {Function} handler The method the event invokes
5748 * @param {Object} scope (optional) The scope in which to execute the handler
5749 * function. The handler function's "this" context.
5750 * @param {Object} options (optional) An object containing handler configuration
5751 * properties. This may contain any of the following properties:<ul>
5752 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
5753 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
5754 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
5755 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
5756 * by the specified number of milliseconds. If the event fires again within that time, the original
5757 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
5760 * <b>Combining Options</b><br>
5761 * Using the options argument, it is possible to combine different types of listeners:<br>
5763 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)
5765 el.on('click', this.onClick, this, {
5772 * <b>Attaching multiple handlers in 1 call</b><br>
5773 * The method also allows for a single argument to be passed which is a config object containing properties
5774 * which specify multiple handlers.
5783 fn: this.onMouseOver,
5787 fn: this.onMouseOut,
5793 * Or a shorthand syntax which passes the same scope object to all handlers:
5796 'click': this.onClick,
5797 'mouseover': this.onMouseOver,
5798 'mouseout': this.onMouseOut,
5803 addListener : function(eventName, fn, scope, o){
5804 if(typeof eventName == "object"){
5807 if(this.filterOptRe.test(e)){
5810 if(typeof o[e] == "function"){
5812 this.addListener(e, o[e], o.scope, o);
5814 // individual options
5815 this.addListener(e, o[e].fn, o[e].scope, o[e]);
5820 o = (!o || typeof o == "boolean") ? {} : o;
5821 eventName = eventName.toLowerCase();
5822 var ce = this.events[eventName] || true;
5823 if(typeof ce == "boolean"){
5824 ce = new Roo.util.Event(this, eventName);
5825 this.events[eventName] = ce;
5827 ce.addListener(fn, scope, o);
5831 * Removes a listener
5832 * @param {String} eventName The type of event to listen for
5833 * @param {Function} handler The handler to remove
5834 * @param {Object} scope (optional) The scope (this object) for the handler
5836 removeListener : function(eventName, fn, scope){
5837 var ce = this.events[eventName.toLowerCase()];
5838 if(typeof ce == "object"){
5839 ce.removeListener(fn, scope);
5844 * Removes all listeners for this object
5846 purgeListeners : function(){
5847 for(var evt in this.events){
5848 if(typeof this.events[evt] == "object"){
5849 this.events[evt].clearListeners();
5854 relayEvents : function(o, events){
5855 var createHandler = function(ename){
5857 return this.fireEvent.apply(this, Roo.combine(ename, Array.prototype.slice.call(arguments, 0)));
5860 for(var i = 0, len = events.length; i < len; i++){
5861 var ename = events[i];
5862 if(!this.events[ename]){ this.events[ename] = true; };
5863 o.on(ename, createHandler(ename), this);
5868 * Used to define events on this Observable
5869 * @param {Object} object The object with the events defined
5871 addEvents : function(o){
5875 Roo.applyIf(this.events, o);
5879 * Checks to see if this object has any listeners for a specified event
5880 * @param {String} eventName The name of the event to check for
5881 * @return {Boolean} True if the event is being listened for, else false
5883 hasListener : function(eventName){
5884 var e = this.events[eventName];
5885 return typeof e == "object" && e.listeners.length > 0;
5889 * Appends an event handler to this element (shorthand for addListener)
5890 * @param {String} eventName The type of event to listen for
5891 * @param {Function} handler The method the event invokes
5892 * @param {Object} scope (optional) The scope in which to execute the handler
5893 * function. The handler function's "this" context.
5894 * @param {Object} options (optional)
5897 Roo.util.Observable.prototype.on = Roo.util.Observable.prototype.addListener;
5899 * Removes a listener (shorthand for removeListener)
5900 * @param {String} eventName The type of event to listen for
5901 * @param {Function} handler The handler to remove
5902 * @param {Object} scope (optional) The scope (this object) for the handler
5905 Roo.util.Observable.prototype.un = Roo.util.Observable.prototype.removeListener;
5908 * Starts capture on the specified Observable. All events will be passed
5909 * to the supplied function with the event name + standard signature of the event
5910 * <b>before</b> the event is fired. If the supplied function returns false,
5911 * the event will not fire.
5912 * @param {Observable} o The Observable to capture
5913 * @param {Function} fn The function to call
5914 * @param {Object} scope (optional) The scope (this object) for the fn
5917 Roo.util.Observable.capture = function(o, fn, scope){
5918 o.fireEvent = o.fireEvent.createInterceptor(fn, scope);
5922 * Removes <b>all</b> added captures from the Observable.
5923 * @param {Observable} o The Observable to release
5926 Roo.util.Observable.releaseCapture = function(o){
5927 o.fireEvent = Roo.util.Observable.prototype.fireEvent;
5932 var createBuffered = function(h, o, scope){
5933 var task = new Roo.util.DelayedTask();
5935 task.delay(o.buffer, h, scope, Array.prototype.slice.call(arguments, 0));
5939 var createSingle = function(h, e, fn, scope){
5941 e.removeListener(fn, scope);
5942 return h.apply(scope, arguments);
5946 var createDelayed = function(h, o, scope){
5948 var args = Array.prototype.slice.call(arguments, 0);
5949 setTimeout(function(){
5950 h.apply(scope, args);
5955 Roo.util.Event = function(obj, name){
5958 this.listeners = [];
5961 Roo.util.Event.prototype = {
5962 addListener : function(fn, scope, options){
5963 var o = options || {};
5964 scope = scope || this.obj;
5965 if(!this.isListening(fn, scope)){
5966 var l = {fn: fn, scope: scope, options: o};
5969 h = createDelayed(h, o, scope);
5972 h = createSingle(h, this, fn, scope);
5975 h = createBuffered(h, o, scope);
5978 if(!this.firing){ // if we are currently firing this event, don't disturb the listener loop
5979 this.listeners.push(l);
5981 this.listeners = this.listeners.slice(0);
5982 this.listeners.push(l);
5987 findListener : function(fn, scope){
5988 scope = scope || this.obj;
5989 var ls = this.listeners;
5990 for(var i = 0, len = ls.length; i < len; i++){
5992 if(l.fn == fn && l.scope == scope){
5999 isListening : function(fn, scope){
6000 return this.findListener(fn, scope) != -1;
6003 removeListener : function(fn, scope){
6005 if((index = this.findListener(fn, scope)) != -1){
6007 this.listeners.splice(index, 1);
6009 this.listeners = this.listeners.slice(0);
6010 this.listeners.splice(index, 1);
6017 clearListeners : function(){
6018 this.listeners = [];
6022 var ls = this.listeners, scope, len = ls.length;
6025 var args = Array.prototype.slice.call(arguments, 0);
6026 for(var i = 0; i < len; i++){
6028 if(l.fireFn.apply(l.scope||this.obj||window, arguments) === false){
6029 this.firing = false;
6033 this.firing = false;
6040 * Ext JS Library 1.1.1
6041 * Copyright(c) 2006-2007, Ext JS, LLC.
6043 * Originally Released Under LGPL - original licence link has changed is not relivant.
6046 * <script type="text/javascript">
6050 * @class Roo.EventManager
6051 * Registers event handlers that want to receive a normalized EventObject instead of the standard browser event and provides
6052 * several useful events directly.
6053 * See {@link Roo.EventObject} for more details on normalized event objects.
6056 Roo.EventManager = function(){
6057 var docReadyEvent, docReadyProcId, docReadyState = false;
6058 var resizeEvent, resizeTask, textEvent, textSize;
6059 var E = Roo.lib.Event;
6060 var D = Roo.lib.Dom;
6063 var fireDocReady = function(){
6065 docReadyState = true;
6068 clearInterval(docReadyProcId);
6070 if(Roo.isGecko || Roo.isOpera) {
6071 document.removeEventListener("DOMContentLoaded", fireDocReady, false);
6074 var defer = document.getElementById("ie-deferred-loader");
6076 defer.onreadystatechange = null;
6077 defer.parentNode.removeChild(defer);
6081 docReadyEvent.fire();
6082 docReadyEvent.clearListeners();
6087 var initDocReady = function(){
6088 docReadyEvent = new Roo.util.Event();
6089 if(Roo.isGecko || Roo.isOpera) {
6090 document.addEventListener("DOMContentLoaded", fireDocReady, false);
6092 document.write("<s"+'cript id="ie-deferred-loader" defer="defer" src="/'+'/:"></s'+"cript>");
6093 var defer = document.getElementById("ie-deferred-loader");
6094 defer.onreadystatechange = function(){
6095 if(this.readyState == "complete"){
6099 }else if(Roo.isSafari){
6100 docReadyProcId = setInterval(function(){
6101 var rs = document.readyState;
6102 if(rs == "complete") {
6107 // no matter what, make sure it fires on load
6108 E.on(window, "load", fireDocReady);
6111 var createBuffered = function(h, o){
6112 var task = new Roo.util.DelayedTask(h);
6114 // create new event object impl so new events don't wipe out properties
6115 e = new Roo.EventObjectImpl(e);
6116 task.delay(o.buffer, h, null, [e]);
6120 var createSingle = function(h, el, ename, fn){
6122 Roo.EventManager.removeListener(el, ename, fn);
6127 var createDelayed = function(h, o){
6129 // create new event object impl so new events don't wipe out properties
6130 e = new Roo.EventObjectImpl(e);
6131 setTimeout(function(){
6137 var listen = function(element, ename, opt, fn, scope){
6138 var o = (!opt || typeof opt == "boolean") ? {} : opt;
6139 fn = fn || o.fn; scope = scope || o.scope;
6140 var el = Roo.getDom(element);
6142 throw "Error listening for \"" + ename + '\". Element "' + element + '" doesn\'t exist.';
6144 var h = function(e){
6145 e = Roo.EventObject.setEvent(e);
6148 t = e.getTarget(o.delegate, el);
6155 if(o.stopEvent === true){
6158 if(o.preventDefault === true){
6161 if(o.stopPropagation === true){
6162 e.stopPropagation();
6165 if(o.normalized === false){
6169 fn.call(scope || el, e, t, o);
6172 h = createDelayed(h, o);
6175 h = createSingle(h, el, ename, fn);
6178 h = createBuffered(h, o);
6180 fn._handlers = fn._handlers || [];
6181 fn._handlers.push([Roo.id(el), ename, h]);
6184 if(ename == "mousewheel" && el.addEventListener){ // workaround for jQuery
6185 el.addEventListener("DOMMouseScroll", h, false);
6186 E.on(window, 'unload', function(){
6187 el.removeEventListener("DOMMouseScroll", h, false);
6190 if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
6191 Roo.EventManager.stoppedMouseDownEvent.addListener(h);
6196 var stopListening = function(el, ename, fn){
6197 var id = Roo.id(el), hds = fn._handlers, hd = fn;
6199 for(var i = 0, len = hds.length; i < len; i++){
6201 if(h[0] == id && h[1] == ename){
6208 E.un(el, ename, hd);
6209 el = Roo.getDom(el);
6210 if(ename == "mousewheel" && el.addEventListener){
6211 el.removeEventListener("DOMMouseScroll", hd, false);
6213 if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
6214 Roo.EventManager.stoppedMouseDownEvent.removeListener(hd);
6218 var propRe = /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/;
6225 * @scope Roo.EventManager
6230 * This is no longer needed and is deprecated. Places a simple wrapper around an event handler to override the browser event
6231 * object with a Roo.EventObject
6232 * @param {Function} fn The method the event invokes
6233 * @param {Object} scope An object that becomes the scope of the handler
6234 * @param {boolean} override If true, the obj passed in becomes
6235 * the execution scope of the listener
6236 * @return {Function} The wrapped function
6239 wrap : function(fn, scope, override){
6241 Roo.EventObject.setEvent(e);
6242 fn.call(override ? scope || window : window, Roo.EventObject, scope);
6247 * Appends an event handler to an element (shorthand for addListener)
6248 * @param {String/HTMLElement} element The html element or id to assign the
6249 * @param {String} eventName The type of event to listen for
6250 * @param {Function} handler The method the event invokes
6251 * @param {Object} scope (optional) The scope in which to execute the handler
6252 * function. The handler function's "this" context.
6253 * @param {Object} options (optional) An object containing handler configuration
6254 * properties. This may contain any of the following properties:<ul>
6255 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
6256 * <li>delegate {String} A simple selector to filter the target or look for a descendant of the target</li>
6257 * <li>stopEvent {Boolean} True to stop the event. That is stop propagation, and prevent the default action.</li>
6258 * <li>preventDefault {Boolean} True to prevent the default action</li>
6259 * <li>stopPropagation {Boolean} True to prevent event propagation</li>
6260 * <li>normalized {Boolean} False to pass a browser event to the handler function instead of an Roo.EventObject</li>
6261 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
6262 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
6263 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
6264 * by the specified number of milliseconds. If the event fires again within that time, the original
6265 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
6268 * <b>Combining Options</b><br>
6269 * Using the options argument, it is possible to combine different types of listeners:<br>
6271 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)<div style="margin: 5px 20px 20px;">
6273 el.on('click', this.onClick, this, {
6280 * <b>Attaching multiple handlers in 1 call</b><br>
6281 * The method also allows for a single argument to be passed which is a config object containing properties
6282 * which specify multiple handlers.
6292 fn: this.onMouseOver
6301 * Or a shorthand syntax:<br>
6304 'click' : this.onClick,
6305 'mouseover' : this.onMouseOver,
6306 'mouseout' : this.onMouseOut
6310 addListener : function(element, eventName, fn, scope, options){
6311 if(typeof eventName == "object"){
6317 if(typeof o[e] == "function"){
6319 listen(element, e, o, o[e], o.scope);
6321 // individual options
6322 listen(element, e, o[e]);
6327 return listen(element, eventName, options, fn, scope);
6331 * Removes an event handler
6333 * @param {String/HTMLElement} element The id or html element to remove the
6335 * @param {String} eventName The type of event
6336 * @param {Function} fn
6337 * @return {Boolean} True if a listener was actually removed
6339 removeListener : function(element, eventName, fn){
6340 return stopListening(element, eventName, fn);
6344 * Fires when the document is ready (before onload and before images are loaded). Can be
6345 * accessed shorthanded Roo.onReady().
6346 * @param {Function} fn The method the event invokes
6347 * @param {Object} scope An object that becomes the scope of the handler
6348 * @param {boolean} options
6350 onDocumentReady : function(fn, scope, options){
6351 if(docReadyState){ // if it already fired
6352 docReadyEvent.addListener(fn, scope, options);
6353 docReadyEvent.fire();
6354 docReadyEvent.clearListeners();
6360 docReadyEvent.addListener(fn, scope, options);
6364 * Fires when the window is resized and provides resize event buffering (50 milliseconds), passes new viewport width and height to handlers.
6365 * @param {Function} fn The method the event invokes
6366 * @param {Object} scope An object that becomes the scope of the handler
6367 * @param {boolean} options
6369 onWindowResize : function(fn, scope, options){
6371 resizeEvent = new Roo.util.Event();
6372 resizeTask = new Roo.util.DelayedTask(function(){
6373 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
6375 E.on(window, "resize", function(){
6377 resizeTask.delay(50);
6379 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
6383 resizeEvent.addListener(fn, scope, options);
6387 * Fires when the user changes the active text size. Handler gets called with 2 params, the old size and the new size.
6388 * @param {Function} fn The method the event invokes
6389 * @param {Object} scope An object that becomes the scope of the handler
6390 * @param {boolean} options
6392 onTextResize : function(fn, scope, options){
6394 textEvent = new Roo.util.Event();
6395 var textEl = new Roo.Element(document.createElement('div'));
6396 textEl.dom.className = 'x-text-resize';
6397 textEl.dom.innerHTML = 'X';
6398 textEl.appendTo(document.body);
6399 textSize = textEl.dom.offsetHeight;
6400 setInterval(function(){
6401 if(textEl.dom.offsetHeight != textSize){
6402 textEvent.fire(textSize, textSize = textEl.dom.offsetHeight);
6404 }, this.textResizeInterval);
6406 textEvent.addListener(fn, scope, options);
6410 * Removes the passed window resize listener.
6411 * @param {Function} fn The method the event invokes
6412 * @param {Object} scope The scope of handler
6414 removeResizeListener : function(fn, scope){
6416 resizeEvent.removeListener(fn, scope);
6421 fireResize : function(){
6423 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
6427 * Url used for onDocumentReady with using SSL (defaults to Roo.SSL_SECURE_URL)
6431 * The frequency, in milliseconds, to check for text resize events (defaults to 50)
6433 textResizeInterval : 50
6438 * @scopeAlias pub=Roo.EventManager
6442 * Appends an event handler to an element (shorthand for addListener)
6443 * @param {String/HTMLElement} element The html element or id to assign the
6444 * @param {String} eventName The type of event to listen for
6445 * @param {Function} handler The method the event invokes
6446 * @param {Object} scope (optional) The scope in which to execute the handler
6447 * function. The handler function's "this" context.
6448 * @param {Object} options (optional) An object containing handler configuration
6449 * properties. This may contain any of the following properties:<ul>
6450 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
6451 * <li>delegate {String} A simple selector to filter the target or look for a descendant of the target</li>
6452 * <li>stopEvent {Boolean} True to stop the event. That is stop propagation, and prevent the default action.</li>
6453 * <li>preventDefault {Boolean} True to prevent the default action</li>
6454 * <li>stopPropagation {Boolean} True to prevent event propagation</li>
6455 * <li>normalized {Boolean} False to pass a browser event to the handler function instead of an Roo.EventObject</li>
6456 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
6457 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
6458 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
6459 * by the specified number of milliseconds. If the event fires again within that time, the original
6460 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
6463 * <b>Combining Options</b><br>
6464 * Using the options argument, it is possible to combine different types of listeners:<br>
6466 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)<div style="margin: 5px 20px 20px;">
6468 el.on('click', this.onClick, this, {
6475 * <b>Attaching multiple handlers in 1 call</b><br>
6476 * The method also allows for a single argument to be passed which is a config object containing properties
6477 * which specify multiple handlers.
6487 fn: this.onMouseOver
6496 * Or a shorthand syntax:<br>
6499 'click' : this.onClick,
6500 'mouseover' : this.onMouseOver,
6501 'mouseout' : this.onMouseOut
6505 pub.on = pub.addListener;
6506 pub.un = pub.removeListener;
6508 pub.stoppedMouseDownEvent = new Roo.util.Event();
6512 * Fires when the document is ready (before onload and before images are loaded). Shorthand of {@link Roo.EventManager#onDocumentReady}.
6513 * @param {Function} fn The method the event invokes
6514 * @param {Object} scope An object that becomes the scope of the handler
6515 * @param {boolean} override If true, the obj passed in becomes
6516 * the execution scope of the listener
6520 Roo.onReady = Roo.EventManager.onDocumentReady;
6522 Roo.onReady(function(){
6523 var bd = Roo.get(document.body);
6528 : Roo.isGecko ? "roo-gecko"
6529 : Roo.isOpera ? "roo-opera"
6530 : Roo.isSafari ? "roo-safari" : ""];
6533 cls.push("roo-mac");
6536 cls.push("roo-linux");
6538 if(Roo.isBorderBox){
6539 cls.push('roo-border-box');
6541 if(Roo.isStrict){ // add to the parent to allow for selectors like ".ext-strict .ext-ie"
6542 var p = bd.dom.parentNode;
6544 p.className += ' roo-strict';
6547 bd.addClass(cls.join(' '));
6551 * @class Roo.EventObject
6552 * EventObject exposes the Yahoo! UI Event functionality directly on the object
6553 * passed to your event handler. It exists mostly for convenience. It also fixes the annoying null checks automatically to cleanup your code
6556 function handleClick(e){ // e is not a standard event object, it is a Roo.EventObject
6558 var target = e.getTarget();
6561 var myDiv = Roo.get("myDiv");
6562 myDiv.on("click", handleClick);
6564 Roo.EventManager.on("myDiv", 'click', handleClick);
6565 Roo.EventManager.addListener("myDiv", 'click', handleClick);
6569 Roo.EventObject = function(){
6571 var E = Roo.lib.Event;
6573 // safari keypress events for special keys return bad keycodes
6576 63235 : 39, // right
6579 63276 : 33, // page up
6580 63277 : 34, // page down
6581 63272 : 46, // delete
6586 // normalize button clicks
6587 var btnMap = Roo.isIE ? {1:0,4:1,2:2} :
6588 (Roo.isSafari ? {1:0,2:1,3:2} : {0:0,1:1,2:2});
6590 Roo.EventObjectImpl = function(e){
6592 this.setEvent(e.browserEvent || e);
6595 Roo.EventObjectImpl.prototype = {
6597 * Used to fix doc tools.
6598 * @scope Roo.EventObject.prototype
6604 /** The normal browser event */
6605 browserEvent : null,
6606 /** The button pressed in a mouse event */
6608 /** True if the shift key was down during the event */
6610 /** True if the control key was down during the event */
6612 /** True if the alt key was down during the event */
6671 setEvent : function(e){
6672 if(e == this || (e && e.browserEvent)){ // already wrapped
6675 this.browserEvent = e;
6677 // normalize buttons
6678 this.button = e.button ? btnMap[e.button] : (e.which ? e.which-1 : -1);
6679 if(e.type == 'click' && this.button == -1){
6683 this.shiftKey = e.shiftKey;
6684 // mac metaKey behaves like ctrlKey
6685 this.ctrlKey = e.ctrlKey || e.metaKey;
6686 this.altKey = e.altKey;
6687 // in getKey these will be normalized for the mac
6688 this.keyCode = e.keyCode;
6689 // keyup warnings on firefox.
6690 this.charCode = (e.type == 'keyup' || e.type == 'keydown') ? 0 : e.charCode;
6691 // cache the target for the delayed and or buffered events
6692 this.target = E.getTarget(e);
6694 this.xy = E.getXY(e);
6697 this.shiftKey = false;
6698 this.ctrlKey = false;
6699 this.altKey = false;
6709 * Stop the event (preventDefault and stopPropagation)
6711 stopEvent : function(){
6712 if(this.browserEvent){
6713 if(this.browserEvent.type == 'mousedown'){
6714 Roo.EventManager.stoppedMouseDownEvent.fire(this);
6716 E.stopEvent(this.browserEvent);
6721 * Prevents the browsers default handling of the event.
6723 preventDefault : function(){
6724 if(this.browserEvent){
6725 E.preventDefault(this.browserEvent);
6730 isNavKeyPress : function(){
6731 var k = this.keyCode;
6732 k = Roo.isSafari ? (safariKeys[k] || k) : k;
6733 return (k >= 33 && k <= 40) || k == this.RETURN || k == this.TAB || k == this.ESC;
6736 isSpecialKey : function(){
6737 var k = this.keyCode;
6738 return (this.type == 'keypress' && this.ctrlKey) || k == 9 || k == 13 || k == 40 || k == 27 ||
6739 (k == 16) || (k == 17) ||
6740 (k >= 18 && k <= 20) ||
6741 (k >= 33 && k <= 35) ||
6742 (k >= 36 && k <= 39) ||
6743 (k >= 44 && k <= 45);
6746 * Cancels bubbling of the event.
6748 stopPropagation : function(){
6749 if(this.browserEvent){
6750 if(this.type == 'mousedown'){
6751 Roo.EventManager.stoppedMouseDownEvent.fire(this);
6753 E.stopPropagation(this.browserEvent);
6758 * Gets the key code for the event.
6761 getCharCode : function(){
6762 return this.charCode || this.keyCode;
6766 * Returns a normalized keyCode for the event.
6767 * @return {Number} The key code
6769 getKey : function(){
6770 var k = this.keyCode || this.charCode;
6771 return Roo.isSafari ? (safariKeys[k] || k) : k;
6775 * Gets the x coordinate of the event.
6778 getPageX : function(){
6783 * Gets the y coordinate of the event.
6786 getPageY : function(){
6791 * Gets the time of the event.
6794 getTime : function(){
6795 if(this.browserEvent){
6796 return E.getTime(this.browserEvent);
6802 * Gets the page coordinates of the event.
6803 * @return {Array} The xy values like [x, y]
6810 * Gets the target for the event.
6811 * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target
6812 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
6813 search as a number or element (defaults to 10 || document.body)
6814 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
6815 * @return {HTMLelement}
6817 getTarget : function(selector, maxDepth, returnEl){
6818 return selector ? Roo.fly(this.target).findParent(selector, maxDepth, returnEl) : this.target;
6821 * Gets the related target.
6822 * @return {HTMLElement}
6824 getRelatedTarget : function(){
6825 if(this.browserEvent){
6826 return E.getRelatedTarget(this.browserEvent);
6832 * Normalizes mouse wheel delta across browsers
6833 * @return {Number} The delta
6835 getWheelDelta : function(){
6836 var e = this.browserEvent;
6838 if(e.wheelDelta){ /* IE/Opera. */
6839 delta = e.wheelDelta/120;
6840 }else if(e.detail){ /* Mozilla case. */
6841 delta = -e.detail/3;
6847 * Returns true if the control, meta, shift or alt key was pressed during this event.
6850 hasModifier : function(){
6851 return !!((this.ctrlKey || this.altKey) || this.shiftKey);
6855 * Returns true if the target of this event equals el or is a child of el
6856 * @param {String/HTMLElement/Element} el
6857 * @param {Boolean} related (optional) true to test if the related target is within el instead of the target
6860 within : function(el, related){
6861 var t = this[related ? "getRelatedTarget" : "getTarget"]();
6862 return t && Roo.fly(el).contains(t);
6865 getPoint : function(){
6866 return new Roo.lib.Point(this.xy[0], this.xy[1]);
6870 return new Roo.EventObjectImpl();
6875 * Ext JS Library 1.1.1
6876 * Copyright(c) 2006-2007, Ext JS, LLC.
6878 * Originally Released Under LGPL - original licence link has changed is not relivant.
6881 * <script type="text/javascript">
6885 // was in Composite Element!??!?!
6888 var D = Roo.lib.Dom;
6889 var E = Roo.lib.Event;
6890 var A = Roo.lib.Anim;
6892 // local style camelizing for speed
6894 var camelRe = /(-[a-z])/gi;
6895 var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); };
6896 var view = document.defaultView;
6899 * @class Roo.Element
6900 * Represents an Element in the DOM.<br><br>
6903 var el = Roo.get("my-div");
6906 var el = getEl("my-div");
6908 // or with a DOM element
6909 var el = Roo.get(myDivElement);
6911 * Using Roo.get() or getEl() instead of calling the constructor directly ensures you get the same object
6912 * each call instead of constructing a new one.<br><br>
6913 * <b>Animations</b><br />
6914 * Many of the functions for manipulating an element have an optional "animate" parameter. The animate parameter
6915 * should either be a boolean (true) or an object literal with animation options. The animation options are:
6917 Option Default Description
6918 --------- -------- ---------------------------------------------
6919 duration .35 The duration of the animation in seconds
6920 easing easeOut The YUI easing method
6921 callback none A function to execute when the anim completes
6922 scope this The scope (this) of the callback function
6924 * Also, the Anim object being used for the animation will be set on your options object as "anim", which allows you to stop or
6925 * manipulate the animation. Here's an example:
6927 var el = Roo.get("my-div");
6932 // default animation
6933 el.setWidth(100, true);
6935 // animation with some options set
6942 // using the "anim" property to get the Anim object
6948 el.setWidth(100, opt);
6950 if(opt.anim.isAnimated()){
6954 * <b> Composite (Collections of) Elements</b><br />
6955 * For working with collections of Elements, see <a href="Roo.CompositeElement.html">Roo.CompositeElement</a>
6956 * @constructor Create a new Element directly.
6957 * @param {String/HTMLElement} element
6958 * @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).
6960 Roo.Element = function(element, forceNew){
6961 var dom = typeof element == "string" ?
6962 document.getElementById(element) : element;
6963 if(!dom){ // invalid id/element
6967 if(forceNew !== true && id && Roo.Element.cache[id]){ // element object already exists
6968 return Roo.Element.cache[id];
6978 * The DOM element ID
6981 this.id = id || Roo.id(dom);
6984 var El = Roo.Element;
6988 * The element's default display mode (defaults to "")
6991 originalDisplay : "",
6995 * The default unit to append to CSS values where a unit isn't provided (defaults to px).
7000 * Sets the element's visibility mode. When setVisible() is called it
7001 * will use this to determine whether to set the visibility or the display property.
7002 * @param visMode Element.VISIBILITY or Element.DISPLAY
7003 * @return {Roo.Element} this
7005 setVisibilityMode : function(visMode){
7006 this.visibilityMode = visMode;
7010 * Convenience method for setVisibilityMode(Element.DISPLAY)
7011 * @param {String} display (optional) What to set display to when visible
7012 * @return {Roo.Element} this
7014 enableDisplayMode : function(display){
7015 this.setVisibilityMode(El.DISPLAY);
7016 if(typeof display != "undefined") this.originalDisplay = display;
7021 * 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)
7022 * @param {String} selector The simple selector to test
7023 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
7024 search as a number or element (defaults to 10 || document.body)
7025 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
7026 * @return {HTMLElement} The matching DOM node (or null if no match was found)
7028 findParent : function(simpleSelector, maxDepth, returnEl){
7029 var p = this.dom, b = document.body, depth = 0, dq = Roo.DomQuery, stopEl;
7030 maxDepth = maxDepth || 50;
7031 if(typeof maxDepth != "number"){
7032 stopEl = Roo.getDom(maxDepth);
7035 while(p && p.nodeType == 1 && depth < maxDepth && p != b && p != stopEl){
7036 if(dq.is(p, simpleSelector)){
7037 return returnEl ? Roo.get(p) : p;
7047 * Looks at parent nodes for a match of the passed simple selector (e.g. div.some-class or span:first-child)
7048 * @param {String} selector The simple selector to test
7049 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
7050 search as a number or element (defaults to 10 || document.body)
7051 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
7052 * @return {HTMLElement} The matching DOM node (or null if no match was found)
7054 findParentNode : function(simpleSelector, maxDepth, returnEl){
7055 var p = Roo.fly(this.dom.parentNode, '_internal');
7056 return p ? p.findParent(simpleSelector, maxDepth, returnEl) : null;
7060 * Walks up the dom looking for a parent node that matches the passed simple selector (e.g. div.some-class or span:first-child).
7061 * This is a shortcut for findParentNode() that always returns an Roo.Element.
7062 * @param {String} selector The simple selector to test
7063 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
7064 search as a number or element (defaults to 10 || document.body)
7065 * @return {Roo.Element} The matching DOM node (or null if no match was found)
7067 up : function(simpleSelector, maxDepth){
7068 return this.findParentNode(simpleSelector, maxDepth, true);
7074 * Returns true if this element matches the passed simple selector (e.g. div.some-class or span:first-child)
7075 * @param {String} selector The simple selector to test
7076 * @return {Boolean} True if this element matches the selector, else false
7078 is : function(simpleSelector){
7079 return Roo.DomQuery.is(this.dom, simpleSelector);
7083 * Perform animation on this element.
7084 * @param {Object} args The YUI animation control args
7085 * @param {Float} duration (optional) How long the animation lasts in seconds (defaults to .35)
7086 * @param {Function} onComplete (optional) Function to call when animation completes
7087 * @param {String} easing (optional) Easing method to use (defaults to 'easeOut')
7088 * @param {String} animType (optional) 'run' is the default. Can also be 'color', 'motion', or 'scroll'
7089 * @return {Roo.Element} this
7091 animate : function(args, duration, onComplete, easing, animType){
7092 this.anim(args, {duration: duration, callback: onComplete, easing: easing}, animType);
7097 * @private Internal animation call
7099 anim : function(args, opt, animType, defaultDur, defaultEase, cb){
7100 animType = animType || 'run';
7102 var anim = Roo.lib.Anim[animType](
7104 (opt.duration || defaultDur) || .35,
7105 (opt.easing || defaultEase) || 'easeOut',
7107 Roo.callback(cb, this);
7108 Roo.callback(opt.callback, opt.scope || this, [this, opt]);
7116 // private legacy anim prep
7117 preanim : function(a, i){
7118 return !a[i] ? false : (typeof a[i] == "object" ? a[i]: {duration: a[i+1], callback: a[i+2], easing: a[i+3]});
7122 * Removes worthless text nodes
7123 * @param {Boolean} forceReclean (optional) By default the element
7124 * keeps track if it has been cleaned already so
7125 * you can call this over and over. However, if you update the element and
7126 * need to force a reclean, you can pass true.
7128 clean : function(forceReclean){
7129 if(this.isCleaned && forceReclean !== true){
7133 var d = this.dom, n = d.firstChild, ni = -1;
7135 var nx = n.nextSibling;
7136 if(n.nodeType == 3 && !ns.test(n.nodeValue)){
7143 this.isCleaned = true;
7148 calcOffsetsTo : function(el){
7151 var restorePos = false;
7152 if(el.getStyle('position') == 'static'){
7153 el.position('relative');
7158 while(op && op != d && op.tagName != 'HTML'){
7161 op = op.offsetParent;
7164 el.position('static');
7170 * Scrolls this element into view within the passed container.
7171 * @param {String/HTMLElement/Element} container (optional) The container element to scroll (defaults to document.body)
7172 * @param {Boolean} hscroll (optional) False to disable horizontal scroll (defaults to true)
7173 * @return {Roo.Element} this
7175 scrollIntoView : function(container, hscroll){
7176 var c = Roo.getDom(container) || document.body;
7179 var o = this.calcOffsetsTo(c),
7182 b = t+el.offsetHeight,
7183 r = l+el.offsetWidth;
7185 var ch = c.clientHeight;
7186 var ct = parseInt(c.scrollTop, 10);
7187 var cl = parseInt(c.scrollLeft, 10);
7189 var cr = cl + c.clientWidth;
7197 if(hscroll !== false){
7201 c.scrollLeft = r-c.clientWidth;
7208 scrollChildIntoView : function(child, hscroll){
7209 Roo.fly(child, '_scrollChildIntoView').scrollIntoView(this, hscroll);
7213 * Measures the element's content height and updates height to match. Note: this function uses setTimeout so
7214 * the new height may not be available immediately.
7215 * @param {Boolean} animate (optional) Animate the transition (defaults to false)
7216 * @param {Float} duration (optional) Length of the animation in seconds (defaults to .35)
7217 * @param {Function} onComplete (optional) Function to call when animation completes
7218 * @param {String} easing (optional) Easing method to use (defaults to easeOut)
7219 * @return {Roo.Element} this
7221 autoHeight : function(animate, duration, onComplete, easing){
7222 var oldHeight = this.getHeight();
7224 this.setHeight(1); // force clipping
7225 setTimeout(function(){
7226 var height = parseInt(this.dom.scrollHeight, 10); // parseInt for Safari
7228 this.setHeight(height);
7230 if(typeof onComplete == "function"){
7234 this.setHeight(oldHeight); // restore original height
7235 this.setHeight(height, animate, duration, function(){
7237 if(typeof onComplete == "function") onComplete();
7238 }.createDelegate(this), easing);
7240 }.createDelegate(this), 0);
7245 * Returns true if this element is an ancestor of the passed element
7246 * @param {HTMLElement/String} el The element to check
7247 * @return {Boolean} True if this element is an ancestor of el, else false
7249 contains : function(el){
7250 if(!el){return false;}
7251 return D.isAncestor(this.dom, el.dom ? el.dom : el);
7255 * Checks whether the element is currently visible using both visibility and display properties.
7256 * @param {Boolean} deep (optional) True to walk the dom and see if parent elements are hidden (defaults to false)
7257 * @return {Boolean} True if the element is currently visible, else false
7259 isVisible : function(deep) {
7260 var vis = !(this.getStyle("visibility") == "hidden" || this.getStyle("display") == "none");
7261 if(deep !== true || !vis){
7264 var p = this.dom.parentNode;
7265 while(p && p.tagName.toLowerCase() != "body"){
7266 if(!Roo.fly(p, '_isVisible').isVisible()){
7275 * Creates a {@link Roo.CompositeElement} for child nodes based on the passed CSS selector (the selector should not contain an id).
7276 * @param {String} selector The CSS selector
7277 * @param {Boolean} unique (optional) True to create a unique Roo.Element for each child (defaults to false, which creates a single shared flyweight object)
7278 * @return {CompositeElement/CompositeElementLite} The composite element
7280 select : function(selector, unique){
7281 return El.select(selector, unique, this.dom);
7285 * Selects child nodes based on the passed CSS selector (the selector should not contain an id).
7286 * @param {String} selector The CSS selector
7287 * @return {Array} An array of the matched nodes
7289 query : function(selector, unique){
7290 return Roo.DomQuery.select(selector, this.dom);
7294 * Selects a single child at any depth below this element based on the passed CSS selector (the selector should not contain an id).
7295 * @param {String} selector The CSS selector
7296 * @param {Boolean} returnDom (optional) True to return the DOM node instead of Roo.Element (defaults to false)
7297 * @return {HTMLElement/Roo.Element} The child Roo.Element (or DOM node if returnDom = true)
7299 child : function(selector, returnDom){
7300 var n = Roo.DomQuery.selectNode(selector, this.dom);
7301 return returnDom ? n : Roo.get(n);
7305 * Selects a single *direct* child based on the passed CSS selector (the selector should not contain an id).
7306 * @param {String} selector The CSS selector
7307 * @param {Boolean} returnDom (optional) True to return the DOM node instead of Roo.Element (defaults to false)
7308 * @return {HTMLElement/Roo.Element} The child Roo.Element (or DOM node if returnDom = true)
7310 down : function(selector, returnDom){
7311 var n = Roo.DomQuery.selectNode(" > " + selector, this.dom);
7312 return returnDom ? n : Roo.get(n);
7316 * Initializes a {@link Roo.dd.DD} drag drop object for this element.
7317 * @param {String} group The group the DD object is member of
7318 * @param {Object} config The DD config object
7319 * @param {Object} overrides An object containing methods to override/implement on the DD object
7320 * @return {Roo.dd.DD} The DD object
7322 initDD : function(group, config, overrides){
7323 var dd = new Roo.dd.DD(Roo.id(this.dom), group, config);
7324 return Roo.apply(dd, overrides);
7328 * Initializes a {@link Roo.dd.DDProxy} object for this element.
7329 * @param {String} group The group the DDProxy object is member of
7330 * @param {Object} config The DDProxy config object
7331 * @param {Object} overrides An object containing methods to override/implement on the DDProxy object
7332 * @return {Roo.dd.DDProxy} The DDProxy object
7334 initDDProxy : function(group, config, overrides){
7335 var dd = new Roo.dd.DDProxy(Roo.id(this.dom), group, config);
7336 return Roo.apply(dd, overrides);
7340 * Initializes a {@link Roo.dd.DDTarget} object for this element.
7341 * @param {String} group The group the DDTarget object is member of
7342 * @param {Object} config The DDTarget config object
7343 * @param {Object} overrides An object containing methods to override/implement on the DDTarget object
7344 * @return {Roo.dd.DDTarget} The DDTarget object
7346 initDDTarget : function(group, config, overrides){
7347 var dd = new Roo.dd.DDTarget(Roo.id(this.dom), group, config);
7348 return Roo.apply(dd, overrides);
7352 * Sets the visibility of the element (see details). If the visibilityMode is set to Element.DISPLAY, it will use
7353 * the display property to hide the element, otherwise it uses visibility. The default is to hide and show using the visibility property.
7354 * @param {Boolean} visible Whether the element is visible
7355 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7356 * @return {Roo.Element} this
7358 setVisible : function(visible, animate){
7360 if(this.visibilityMode == El.DISPLAY){
7361 this.setDisplayed(visible);
7364 this.dom.style.visibility = visible ? "visible" : "hidden";
7367 // closure for composites
7369 var visMode = this.visibilityMode;
7371 this.setOpacity(.01);
7372 this.setVisible(true);
7374 this.anim({opacity: { to: (visible?1:0) }},
7375 this.preanim(arguments, 1),
7376 null, .35, 'easeIn', function(){
7378 if(visMode == El.DISPLAY){
7379 dom.style.display = "none";
7381 dom.style.visibility = "hidden";
7383 Roo.get(dom).setOpacity(1);
7391 * Returns true if display is not "none"
7394 isDisplayed : function() {
7395 return this.getStyle("display") != "none";
7399 * Toggles the element's visibility or display, depending on visibility mode.
7400 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7401 * @return {Roo.Element} this
7403 toggle : function(animate){
7404 this.setVisible(!this.isVisible(), this.preanim(arguments, 0));
7409 * Sets the CSS display property. Uses originalDisplay if the specified value is a boolean true.
7410 * @param {Boolean} value Boolean value to display the element using its default display, or a string to set the display directly
7411 * @return {Roo.Element} this
7413 setDisplayed : function(value) {
7414 if(typeof value == "boolean"){
7415 value = value ? this.originalDisplay : "none";
7417 this.setStyle("display", value);
7422 * Tries to focus the element. Any exceptions are caught and ignored.
7423 * @return {Roo.Element} this
7425 focus : function() {
7433 * Tries to blur the element. Any exceptions are caught and ignored.
7434 * @return {Roo.Element} this
7444 * Adds one or more CSS classes to the element. Duplicate classes are automatically filtered out.
7445 * @param {String/Array} className The CSS class to add, or an array of classes
7446 * @return {Roo.Element} this
7448 addClass : function(className){
7449 if(className instanceof Array){
7450 for(var i = 0, len = className.length; i < len; i++) {
7451 this.addClass(className[i]);
7454 if(className && !this.hasClass(className)){
7455 this.dom.className = this.dom.className + " " + className;
7462 * Adds one or more CSS classes to this element and removes the same class(es) from all siblings.
7463 * @param {String/Array} className The CSS class to add, or an array of classes
7464 * @return {Roo.Element} this
7466 radioClass : function(className){
7467 var siblings = this.dom.parentNode.childNodes;
7468 for(var i = 0; i < siblings.length; i++) {
7469 var s = siblings[i];
7470 if(s.nodeType == 1){
7471 Roo.get(s).removeClass(className);
7474 this.addClass(className);
7479 * Removes one or more CSS classes from the element.
7480 * @param {String/Array} className The CSS class to remove, or an array of classes
7481 * @return {Roo.Element} this
7483 removeClass : function(className){
7484 if(!className || !this.dom.className){
7487 if(className instanceof Array){
7488 for(var i = 0, len = className.length; i < len; i++) {
7489 this.removeClass(className[i]);
7492 if(this.hasClass(className)){
7493 var re = this.classReCache[className];
7495 re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)', "g");
7496 this.classReCache[className] = re;
7498 this.dom.className =
7499 this.dom.className.replace(re, " ");
7509 * Toggles the specified CSS class on this element (removes it if it already exists, otherwise adds it).
7510 * @param {String} className The CSS class to toggle
7511 * @return {Roo.Element} this
7513 toggleClass : function(className){
7514 if(this.hasClass(className)){
7515 this.removeClass(className);
7517 this.addClass(className);
7523 * Checks if the specified CSS class exists on this element's DOM node.
7524 * @param {String} className The CSS class to check for
7525 * @return {Boolean} True if the class exists, else false
7527 hasClass : function(className){
7528 return className && (' '+this.dom.className+' ').indexOf(' '+className+' ') != -1;
7532 * Replaces a CSS class on the element with another. If the old name does not exist, the new name will simply be added.
7533 * @param {String} oldClassName The CSS class to replace
7534 * @param {String} newClassName The replacement CSS class
7535 * @return {Roo.Element} this
7537 replaceClass : function(oldClassName, newClassName){
7538 this.removeClass(oldClassName);
7539 this.addClass(newClassName);
7544 * Returns an object with properties matching the styles requested.
7545 * For example, el.getStyles('color', 'font-size', 'width') might return
7546 * {'color': '#FFFFFF', 'font-size': '13px', 'width': '100px'}.
7547 * @param {String} style1 A style name
7548 * @param {String} style2 A style name
7549 * @param {String} etc.
7550 * @return {Object} The style object
7552 getStyles : function(){
7553 var a = arguments, len = a.length, r = {};
7554 for(var i = 0; i < len; i++){
7555 r[a[i]] = this.getStyle(a[i]);
7561 * Normalizes currentStyle and computedStyle. This is not YUI getStyle, it is an optimised version.
7562 * @param {String} property The style property whose value is returned.
7563 * @return {String} The current value of the style property for this element.
7565 getStyle : function(){
7566 return view && view.getComputedStyle ?
7568 var el = this.dom, v, cs, camel;
7569 if(prop == 'float'){
7572 if(el.style && (v = el.style[prop])){
7575 if(cs = view.getComputedStyle(el, "")){
7576 if(!(camel = propCache[prop])){
7577 camel = propCache[prop] = prop.replace(camelRe, camelFn);
7584 var el = this.dom, v, cs, camel;
7585 if(prop == 'opacity'){
7586 if(typeof el.style.filter == 'string'){
7587 var m = el.style.filter.match(/alpha\(opacity=(.*)\)/i);
7589 var fv = parseFloat(m[1]);
7591 return fv ? fv / 100 : 0;
7596 }else if(prop == 'float'){
7597 prop = "styleFloat";
7599 if(!(camel = propCache[prop])){
7600 camel = propCache[prop] = prop.replace(camelRe, camelFn);
7602 if(v = el.style[camel]){
7605 if(cs = el.currentStyle){
7613 * Wrapper for setting style properties, also takes single object parameter of multiple styles.
7614 * @param {String/Object} property The style property to be set, or an object of multiple styles.
7615 * @param {String} value (optional) The value to apply to the given property, or null if an object was passed.
7616 * @return {Roo.Element} this
7618 setStyle : function(prop, value){
7619 if(typeof prop == "string"){
7621 if (prop == 'float') {
7622 this.setStyle(Roo.isIE ? 'styleFloat' : 'cssFloat', value);
7627 if(!(camel = propCache[prop])){
7628 camel = propCache[prop] = prop.replace(camelRe, camelFn);
7631 if(camel == 'opacity') {
7632 this.setOpacity(value);
7634 this.dom.style[camel] = value;
7637 for(var style in prop){
7638 if(typeof prop[style] != "function"){
7639 this.setStyle(style, prop[style]);
7647 * More flexible version of {@link #setStyle} for setting style properties.
7648 * @param {String/Object/Function} styles A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
7649 * a function which returns such a specification.
7650 * @return {Roo.Element} this
7652 applyStyles : function(style){
7653 Roo.DomHelper.applyStyles(this.dom, style);
7658 * 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).
7659 * @return {Number} The X position of the element
7662 return D.getX(this.dom);
7666 * 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).
7667 * @return {Number} The Y position of the element
7670 return D.getY(this.dom);
7674 * 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).
7675 * @return {Array} The XY position of the element
7678 return D.getXY(this.dom);
7682 * 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).
7683 * @param {Number} The X position of the element
7684 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7685 * @return {Roo.Element} this
7687 setX : function(x, animate){
7689 D.setX(this.dom, x);
7691 this.setXY([x, this.getY()], this.preanim(arguments, 1));
7697 * 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).
7698 * @param {Number} The Y position of the element
7699 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7700 * @return {Roo.Element} this
7702 setY : function(y, animate){
7704 D.setY(this.dom, y);
7706 this.setXY([this.getX(), y], this.preanim(arguments, 1));
7712 * Sets the element's left position directly using CSS style (instead of {@link #setX}).
7713 * @param {String} left The left CSS property value
7714 * @return {Roo.Element} this
7716 setLeft : function(left){
7717 this.setStyle("left", this.addUnits(left));
7722 * Sets the element's top position directly using CSS style (instead of {@link #setY}).
7723 * @param {String} top The top CSS property value
7724 * @return {Roo.Element} this
7726 setTop : function(top){
7727 this.setStyle("top", this.addUnits(top));
7732 * Sets the element's CSS right style.
7733 * @param {String} right The right CSS property value
7734 * @return {Roo.Element} this
7736 setRight : function(right){
7737 this.setStyle("right", this.addUnits(right));
7742 * Sets the element's CSS bottom style.
7743 * @param {String} bottom The bottom CSS property value
7744 * @return {Roo.Element} this
7746 setBottom : function(bottom){
7747 this.setStyle("bottom", this.addUnits(bottom));
7752 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
7753 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
7754 * @param {Array} pos Contains X & Y [x, y] values for new position (coordinates are page-based)
7755 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7756 * @return {Roo.Element} this
7758 setXY : function(pos, animate){
7760 D.setXY(this.dom, pos);
7762 this.anim({points: {to: pos}}, this.preanim(arguments, 1), 'motion');
7768 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
7769 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
7770 * @param {Number} x X value for new position (coordinates are page-based)
7771 * @param {Number} y Y value for new position (coordinates are page-based)
7772 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7773 * @return {Roo.Element} this
7775 setLocation : function(x, y, animate){
7776 this.setXY([x, y], this.preanim(arguments, 2));
7781 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
7782 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
7783 * @param {Number} x X value for new position (coordinates are page-based)
7784 * @param {Number} y Y value for new position (coordinates are page-based)
7785 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7786 * @return {Roo.Element} this
7788 moveTo : function(x, y, animate){
7789 this.setXY([x, y], this.preanim(arguments, 2));
7794 * Returns the region of the given element.
7795 * The element must be part of the DOM tree to have a region (display:none or elements not appended return false).
7796 * @return {Region} A Roo.lib.Region containing "top, left, bottom, right" member data.
7798 getRegion : function(){
7799 return D.getRegion(this.dom);
7803 * Returns the offset height of the element
7804 * @param {Boolean} contentHeight (optional) true to get the height minus borders and padding
7805 * @return {Number} The element's height
7807 getHeight : function(contentHeight){
7808 var h = this.dom.offsetHeight || 0;
7809 return contentHeight !== true ? h : h-this.getBorderWidth("tb")-this.getPadding("tb");
7813 * Returns the offset width of the element
7814 * @param {Boolean} contentWidth (optional) true to get the width minus borders and padding
7815 * @return {Number} The element's width
7817 getWidth : function(contentWidth){
7818 var w = this.dom.offsetWidth || 0;
7819 return contentWidth !== true ? w : w-this.getBorderWidth("lr")-this.getPadding("lr");
7823 * Returns either the offsetHeight or the height of this element based on CSS height adjusted by padding or borders
7824 * when needed to simulate offsetHeight when offsets aren't available. This may not work on display:none elements
7825 * if a height has not been set using CSS.
7828 getComputedHeight : function(){
7829 var h = Math.max(this.dom.offsetHeight, this.dom.clientHeight);
7831 h = parseInt(this.getStyle('height'), 10) || 0;
7832 if(!this.isBorderBox()){
7833 h += this.getFrameWidth('tb');
7840 * Returns either the offsetWidth or the width of this element based on CSS width adjusted by padding or borders
7841 * when needed to simulate offsetWidth when offsets aren't available. This may not work on display:none elements
7842 * if a width has not been set using CSS.
7845 getComputedWidth : function(){
7846 var w = Math.max(this.dom.offsetWidth, this.dom.clientWidth);
7848 w = parseInt(this.getStyle('width'), 10) || 0;
7849 if(!this.isBorderBox()){
7850 w += this.getFrameWidth('lr');
7857 * Returns the size of the element.
7858 * @param {Boolean} contentSize (optional) true to get the width/size minus borders and padding
7859 * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
7861 getSize : function(contentSize){
7862 return {width: this.getWidth(contentSize), height: this.getHeight(contentSize)};
7866 * Returns the width and height of the viewport.
7867 * @return {Object} An object containing the viewport's size {width: (viewport width), height: (viewport height)}
7869 getViewSize : function(){
7870 var d = this.dom, doc = document, aw = 0, ah = 0;
7871 if(d == doc || d == doc.body){
7872 return {width : D.getViewWidth(), height: D.getViewHeight()};
7875 width : d.clientWidth,
7876 height: d.clientHeight
7882 * Returns the value of the "value" attribute
7883 * @param {Boolean} asNumber true to parse the value as a number
7884 * @return {String/Number}
7886 getValue : function(asNumber){
7887 return asNumber ? parseInt(this.dom.value, 10) : this.dom.value;
7891 adjustWidth : function(width){
7892 if(typeof width == "number"){
7893 if(this.autoBoxAdjust && !this.isBorderBox()){
7894 width -= (this.getBorderWidth("lr") + this.getPadding("lr"));
7904 adjustHeight : function(height){
7905 if(typeof height == "number"){
7906 if(this.autoBoxAdjust && !this.isBorderBox()){
7907 height -= (this.getBorderWidth("tb") + this.getPadding("tb"));
7917 * Set the width of the element
7918 * @param {Number} width The new width
7919 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
7920 * @return {Roo.Element} this
7922 setWidth : function(width, animate){
7923 width = this.adjustWidth(width);
7925 this.dom.style.width = this.addUnits(width);
7927 this.anim({width: {to: width}}, this.preanim(arguments, 1));
7933 * Set the height of the element
7934 * @param {Number} height The new height
7935 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
7936 * @return {Roo.Element} this
7938 setHeight : function(height, animate){
7939 height = this.adjustHeight(height);
7941 this.dom.style.height = this.addUnits(height);
7943 this.anim({height: {to: height}}, this.preanim(arguments, 1));
7949 * Set the size of the element. If animation is true, both width an height will be animated concurrently.
7950 * @param {Number} width The new width
7951 * @param {Number} height The new height
7952 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
7953 * @return {Roo.Element} this
7955 setSize : function(width, height, animate){
7956 if(typeof width == "object"){ // in case of object from getSize()
7957 height = width.height; width = width.width;
7959 width = this.adjustWidth(width); height = this.adjustHeight(height);
7961 this.dom.style.width = this.addUnits(width);
7962 this.dom.style.height = this.addUnits(height);
7964 this.anim({width: {to: width}, height: {to: height}}, this.preanim(arguments, 2));
7970 * Sets the element's position and size in one shot. If animation is true then width, height, x and y will be animated concurrently.
7971 * @param {Number} x X value for new position (coordinates are page-based)
7972 * @param {Number} y Y value for new position (coordinates are page-based)
7973 * @param {Number} width The new width
7974 * @param {Number} height The new height
7975 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
7976 * @return {Roo.Element} this
7978 setBounds : function(x, y, width, height, animate){
7980 this.setSize(width, height);
7981 this.setLocation(x, y);
7983 width = this.adjustWidth(width); height = this.adjustHeight(height);
7984 this.anim({points: {to: [x, y]}, width: {to: width}, height: {to: height}},
7985 this.preanim(arguments, 4), 'motion');
7991 * Sets the element's position and size the the specified region. If animation is true then width, height, x and y will be animated concurrently.
7992 * @param {Roo.lib.Region} region The region to fill
7993 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
7994 * @return {Roo.Element} this
7996 setRegion : function(region, animate){
7997 this.setBounds(region.left, region.top, region.right-region.left, region.bottom-region.top, this.preanim(arguments, 1));
8002 * Appends an event handler
8004 * @param {String} eventName The type of event to append
8005 * @param {Function} fn The method the event invokes
8006 * @param {Object} scope (optional) The scope (this object) of the fn
8007 * @param {Object} options (optional)An object with standard {@link Roo.EventManager#addListener} options
8009 addListener : function(eventName, fn, scope, options){
8011 Roo.EventManager.on(this.dom, eventName, fn, scope || this, options);
8016 * Removes an event handler from this element
8017 * @param {String} eventName the type of event to remove
8018 * @param {Function} fn the method the event invokes
8019 * @return {Roo.Element} this
8021 removeListener : function(eventName, fn){
8022 Roo.EventManager.removeListener(this.dom, eventName, fn);
8027 * Removes all previous added listeners from this element
8028 * @return {Roo.Element} this
8030 removeAllListeners : function(){
8031 E.purgeElement(this.dom);
8035 relayEvent : function(eventName, observable){
8036 this.on(eventName, function(e){
8037 observable.fireEvent(eventName, e);
8042 * Set the opacity of the element
8043 * @param {Float} opacity The new opacity. 0 = transparent, .5 = 50% visibile, 1 = fully visible, etc
8044 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8045 * @return {Roo.Element} this
8047 setOpacity : function(opacity, animate){
8049 var s = this.dom.style;
8052 s.filter = (s.filter || '').replace(/alpha\([^\)]*\)/gi,"") +
8053 (opacity == 1 ? "" : "alpha(opacity=" + opacity * 100 + ")");
8055 s.opacity = opacity;
8058 this.anim({opacity: {to: opacity}}, this.preanim(arguments, 1), null, .35, 'easeIn');
8064 * Gets the left X coordinate
8065 * @param {Boolean} local True to get the local css position instead of page coordinate
8068 getLeft : function(local){
8072 return parseInt(this.getStyle("left"), 10) || 0;
8077 * Gets the right X coordinate of the element (element X position + element width)
8078 * @param {Boolean} local True to get the local css position instead of page coordinate
8081 getRight : function(local){
8083 return this.getX() + this.getWidth();
8085 return (this.getLeft(true) + this.getWidth()) || 0;
8090 * Gets the top Y coordinate
8091 * @param {Boolean} local True to get the local css position instead of page coordinate
8094 getTop : function(local) {
8098 return parseInt(this.getStyle("top"), 10) || 0;
8103 * Gets the bottom Y coordinate of the element (element Y position + element height)
8104 * @param {Boolean} local True to get the local css position instead of page coordinate
8107 getBottom : function(local){
8109 return this.getY() + this.getHeight();
8111 return (this.getTop(true) + this.getHeight()) || 0;
8116 * Initializes positioning on this element. If a desired position is not passed, it will make the
8117 * the element positioned relative IF it is not already positioned.
8118 * @param {String} pos (optional) Positioning to use "relative", "absolute" or "fixed"
8119 * @param {Number} zIndex (optional) The zIndex to apply
8120 * @param {Number} x (optional) Set the page X position
8121 * @param {Number} y (optional) Set the page Y position
8123 position : function(pos, zIndex, x, y){
8125 if(this.getStyle('position') == 'static'){
8126 this.setStyle('position', 'relative');
8129 this.setStyle("position", pos);
8132 this.setStyle("z-index", zIndex);
8134 if(x !== undefined && y !== undefined){
8136 }else if(x !== undefined){
8138 }else if(y !== undefined){
8144 * Clear positioning back to the default when the document was loaded
8145 * @param {String} value (optional) The value to use for the left,right,top,bottom, defaults to '' (empty string). You could use 'auto'.
8146 * @return {Roo.Element} this
8148 clearPositioning : function(value){
8156 "position" : "static"
8162 * Gets an object with all CSS positioning properties. Useful along with setPostioning to get
8163 * snapshot before performing an update and then restoring the element.
8166 getPositioning : function(){
8167 var l = this.getStyle("left");
8168 var t = this.getStyle("top");
8170 "position" : this.getStyle("position"),
8172 "right" : l ? "" : this.getStyle("right"),
8174 "bottom" : t ? "" : this.getStyle("bottom"),
8175 "z-index" : this.getStyle("z-index")
8180 * Gets the width of the border(s) for the specified side(s)
8181 * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
8182 * passing lr would get the border (l)eft width + the border (r)ight width.
8183 * @return {Number} The width of the sides passed added together
8185 getBorderWidth : function(side){
8186 return this.addStyles(side, El.borders);
8190 * Gets the width of the padding(s) for the specified side(s)
8191 * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
8192 * passing lr would get the padding (l)eft + the padding (r)ight.
8193 * @return {Number} The padding of the sides passed added together
8195 getPadding : function(side){
8196 return this.addStyles(side, El.paddings);
8200 * Set positioning with an object returned by getPositioning().
8201 * @param {Object} posCfg
8202 * @return {Roo.Element} this
8204 setPositioning : function(pc){
8205 this.applyStyles(pc);
8206 if(pc.right == "auto"){
8207 this.dom.style.right = "";
8209 if(pc.bottom == "auto"){
8210 this.dom.style.bottom = "";
8216 fixDisplay : function(){
8217 if(this.getStyle("display") == "none"){
8218 this.setStyle("visibility", "hidden");
8219 this.setStyle("display", this.originalDisplay); // first try reverting to default
8220 if(this.getStyle("display") == "none"){ // if that fails, default to block
8221 this.setStyle("display", "block");
8227 * Quick set left and top adding default units
8228 * @param {String} left The left CSS property value
8229 * @param {String} top The top CSS property value
8230 * @return {Roo.Element} this
8232 setLeftTop : function(left, top){
8233 this.dom.style.left = this.addUnits(left);
8234 this.dom.style.top = this.addUnits(top);
8239 * Move this element relative to its current position.
8240 * @param {String} direction Possible values are: "l","left" - "r","right" - "t","top","up" - "b","bottom","down".
8241 * @param {Number} distance How far to move the element in pixels
8242 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8243 * @return {Roo.Element} this
8245 move : function(direction, distance, animate){
8246 var xy = this.getXY();
8247 direction = direction.toLowerCase();
8251 this.moveTo(xy[0]-distance, xy[1], this.preanim(arguments, 2));
8255 this.moveTo(xy[0]+distance, xy[1], this.preanim(arguments, 2));
8260 this.moveTo(xy[0], xy[1]-distance, this.preanim(arguments, 2));
8265 this.moveTo(xy[0], xy[1]+distance, this.preanim(arguments, 2));
8272 * Store the current overflow setting and clip overflow on the element - use {@link #unclip} to remove
8273 * @return {Roo.Element} this
8276 if(!this.isClipped){
8277 this.isClipped = true;
8278 this.originalClip = {
8279 "o": this.getStyle("overflow"),
8280 "x": this.getStyle("overflow-x"),
8281 "y": this.getStyle("overflow-y")
8283 this.setStyle("overflow", "hidden");
8284 this.setStyle("overflow-x", "hidden");
8285 this.setStyle("overflow-y", "hidden");
8291 * Return clipping (overflow) to original clipping before clip() was called
8292 * @return {Roo.Element} this
8294 unclip : function(){
8296 this.isClipped = false;
8297 var o = this.originalClip;
8298 if(o.o){this.setStyle("overflow", o.o);}
8299 if(o.x){this.setStyle("overflow-x", o.x);}
8300 if(o.y){this.setStyle("overflow-y", o.y);}
8307 * Gets the x,y coordinates specified by the anchor position on the element.
8308 * @param {String} anchor (optional) The specified anchor position (defaults to "c"). See {@link #alignTo} for details on supported anchor positions.
8309 * @param {Object} size (optional) An object containing the size to use for calculating anchor position
8310 * {width: (target width), height: (target height)} (defaults to the element's current size)
8311 * @param {Boolean} local (optional) True to get the local (element top/left-relative) anchor position instead of page coordinates
8312 * @return {Array} [x, y] An array containing the element's x and y coordinates
8314 getAnchorXY : function(anchor, local, s){
8315 //Passing a different size is useful for pre-calculating anchors,
8316 //especially for anchored animations that change the el size.
8318 var w, h, vp = false;
8321 if(d == document.body || d == document){
8323 w = D.getViewWidth(); h = D.getViewHeight();
8325 w = this.getWidth(); h = this.getHeight();
8328 w = s.width; h = s.height;
8330 var x = 0, y = 0, r = Math.round;
8331 switch((anchor || "tl").toLowerCase()){
8373 var sc = this.getScroll();
8374 return [x + sc.left, y + sc.top];
8376 //Add the element's offset xy
8377 var o = this.getXY();
8378 return [x+o[0], y+o[1]];
8382 * Gets the x,y coordinates to align this element with another element. See {@link #alignTo} for more info on the
8383 * supported position values.
8384 * @param {String/HTMLElement/Roo.Element} element The element to align to.
8385 * @param {String} position The position to align to.
8386 * @param {Array} offsets (optional) Offset the positioning by [x, y]
8387 * @return {Array} [x, y]
8389 getAlignToXY : function(el, p, o){
8393 throw "Element.alignTo with an element that doesn't exist";
8395 var c = false; //constrain to viewport
8396 var p1 = "", p2 = "";
8403 }else if(p.indexOf("-") == -1){
8406 p = p.toLowerCase();
8407 var m = p.match(/^([a-z]+)-([a-z]+)(\?)?$/);
8409 throw "Element.alignTo with an invalid alignment " + p;
8411 p1 = m[1]; p2 = m[2]; c = !!m[3];
8413 //Subtract the aligned el's internal xy from the target's offset xy
8414 //plus custom offset to get the aligned el's new offset xy
8415 var a1 = this.getAnchorXY(p1, true);
8416 var a2 = el.getAnchorXY(p2, false);
8417 var x = a2[0] - a1[0] + o[0];
8418 var y = a2[1] - a1[1] + o[1];
8420 //constrain the aligned el to viewport if necessary
8421 var w = this.getWidth(), h = this.getHeight(), r = el.getRegion();
8422 // 5px of margin for ie
8423 var dw = D.getViewWidth()-5, dh = D.getViewHeight()-5;
8425 //If we are at a viewport boundary and the aligned el is anchored on a target border that is
8426 //perpendicular to the vp border, allow the aligned el to slide on that border,
8427 //otherwise swap the aligned el to the opposite border of the target.
8428 var p1y = p1.charAt(0), p1x = p1.charAt(p1.length-1);
8429 var p2y = p2.charAt(0), p2x = p2.charAt(p2.length-1);
8430 var swapY = ((p1y=="t" && p2y=="b") || (p1y=="b" && p2y=="t"));
8431 var swapX = ((p1x=="r" && p2x=="l") || (p1x=="l" && p2x=="r"));
8434 var scrollX = (doc.documentElement.scrollLeft || doc.body.scrollLeft || 0)+5;
8435 var scrollY = (doc.documentElement.scrollTop || doc.body.scrollTop || 0)+5;
8437 if((x+w) > dw + scrollX){
8438 x = swapX ? r.left-w : dw+scrollX-w;
8441 x = swapX ? r.right : scrollX;
8443 if((y+h) > dh + scrollY){
8444 y = swapY ? r.top-h : dh+scrollY-h;
8447 y = swapY ? r.bottom : scrollY;
8454 getConstrainToXY : function(){
8455 var os = {top:0, left:0, bottom:0, right: 0};
8457 return function(el, local, offsets, proposedXY){
8459 offsets = offsets ? Roo.applyIf(offsets, os) : os;
8461 var vw, vh, vx = 0, vy = 0;
8462 if(el.dom == document.body || el.dom == document){
8463 vw = Roo.lib.Dom.getViewWidth();
8464 vh = Roo.lib.Dom.getViewHeight();
8466 vw = el.dom.clientWidth;
8467 vh = el.dom.clientHeight;
8469 var vxy = el.getXY();
8475 var s = el.getScroll();
8477 vx += offsets.left + s.left;
8478 vy += offsets.top + s.top;
8480 vw -= offsets.right;
8481 vh -= offsets.bottom;
8486 var xy = proposedXY || (!local ? this.getXY() : [this.getLeft(true), this.getTop(true)]);
8487 var x = xy[0], y = xy[1];
8488 var w = this.dom.offsetWidth, h = this.dom.offsetHeight;
8490 // only move it if it needs it
8493 // first validate right/bottom
8502 // then make sure top/left isn't negative
8511 return moved ? [x, y] : false;
8516 adjustForConstraints : function(xy, parent, offsets){
8517 return this.getConstrainToXY(parent || document, false, offsets, xy) || xy;
8521 * Aligns this element with another element relative to the specified anchor points. If the other element is the
8522 * document it aligns it to the viewport.
8523 * The position parameter is optional, and can be specified in any one of the following formats:
8525 * <li><b>Blank</b>: Defaults to aligning the element's top-left corner to the target's bottom-left corner ("tl-bl").</li>
8526 * <li><b>One anchor (deprecated)</b>: The passed anchor position is used as the target element's anchor point.
8527 * The element being aligned will position its top-left corner (tl) to that point. <i>This method has been
8528 * deprecated in favor of the newer two anchor syntax below</i>.</li>
8529 * <li><b>Two anchors</b>: If two values from the table below are passed separated by a dash, the first value is used as the
8530 * element's anchor point, and the second value is used as the target's anchor point.</li>
8532 * In addition to the anchor points, the position parameter also supports the "?" character. If "?" is passed at the end of
8533 * the position string, the element will attempt to align as specified, but the position will be adjusted to constrain to
8534 * the viewport if necessary. Note that the element being aligned might be swapped to align to a different position than
8535 * that specified in order to enforce the viewport constraints.
8536 * Following are all of the supported anchor positions:
8539 ----- -----------------------------
8540 tl The top left corner (default)
8541 t The center of the top edge
8542 tr The top right corner
8543 l The center of the left edge
8544 c In the center of the element
8545 r The center of the right edge
8546 bl The bottom left corner
8547 b The center of the bottom edge
8548 br The bottom right corner
8552 // align el to other-el using the default positioning ("tl-bl", non-constrained)
8553 el.alignTo("other-el");
8555 // align the top left corner of el with the top right corner of other-el (constrained to viewport)
8556 el.alignTo("other-el", "tr?");
8558 // align the bottom right corner of el with the center left edge of other-el
8559 el.alignTo("other-el", "br-l?");
8561 // align the center of el with the bottom left corner of other-el and
8562 // adjust the x position by -6 pixels (and the y position by 0)
8563 el.alignTo("other-el", "c-bl", [-6, 0]);
8565 * @param {String/HTMLElement/Roo.Element} element The element to align to.
8566 * @param {String} position The position to align to.
8567 * @param {Array} offsets (optional) Offset the positioning by [x, y]
8568 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8569 * @return {Roo.Element} this
8571 alignTo : function(element, position, offsets, animate){
8572 var xy = this.getAlignToXY(element, position, offsets);
8573 this.setXY(xy, this.preanim(arguments, 3));
8578 * Anchors an element to another element and realigns it when the window is resized.
8579 * @param {String/HTMLElement/Roo.Element} element The element to align to.
8580 * @param {String} position The position to align to.
8581 * @param {Array} offsets (optional) Offset the positioning by [x, y]
8582 * @param {Boolean/Object} animate (optional) True for the default animation or a standard Element animation config object
8583 * @param {Boolean/Number} monitorScroll (optional) True to monitor body scroll and reposition. If this parameter
8584 * is a number, it is used as the buffer delay (defaults to 50ms).
8585 * @param {Function} callback The function to call after the animation finishes
8586 * @return {Roo.Element} this
8588 anchorTo : function(el, alignment, offsets, animate, monitorScroll, callback){
8589 var action = function(){
8590 this.alignTo(el, alignment, offsets, animate);
8591 Roo.callback(callback, this);
8593 Roo.EventManager.onWindowResize(action, this);
8594 var tm = typeof monitorScroll;
8595 if(tm != 'undefined'){
8596 Roo.EventManager.on(window, 'scroll', action, this,
8597 {buffer: tm == 'number' ? monitorScroll : 50});
8599 action.call(this); // align immediately
8603 * Clears any opacity settings from this element. Required in some cases for IE.
8604 * @return {Roo.Element} this
8606 clearOpacity : function(){
8607 if (window.ActiveXObject) {
8608 if(typeof this.dom.style.filter == 'string' && (/alpha/i).test(this.dom.style.filter)){
8609 this.dom.style.filter = "";
8612 this.dom.style.opacity = "";
8613 this.dom.style["-moz-opacity"] = "";
8614 this.dom.style["-khtml-opacity"] = "";
8620 * Hide this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
8621 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8622 * @return {Roo.Element} this
8624 hide : function(animate){
8625 this.setVisible(false, this.preanim(arguments, 0));
8630 * Show this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
8631 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8632 * @return {Roo.Element} this
8634 show : function(animate){
8635 this.setVisible(true, this.preanim(arguments, 0));
8640 * @private Test if size has a unit, otherwise appends the default
8642 addUnits : function(size){
8643 return Roo.Element.addUnits(size, this.defaultUnit);
8647 * Temporarily enables offsets (width,height,x,y) for an element with display:none, use endMeasure() when done.
8648 * @return {Roo.Element} this
8650 beginMeasure : function(){
8652 if(el.offsetWidth || el.offsetHeight){
8653 return this; // offsets work already
8656 var p = this.dom, b = document.body; // start with this element
8657 while((!el.offsetWidth && !el.offsetHeight) && p && p.tagName && p != b){
8658 var pe = Roo.get(p);
8659 if(pe.getStyle('display') == 'none'){
8660 changed.push({el: p, visibility: pe.getStyle("visibility")});
8661 p.style.visibility = "hidden";
8662 p.style.display = "block";
8666 this._measureChanged = changed;
8672 * Restores displays to before beginMeasure was called
8673 * @return {Roo.Element} this
8675 endMeasure : function(){
8676 var changed = this._measureChanged;
8678 for(var i = 0, len = changed.length; i < len; i++) {
8680 r.el.style.visibility = r.visibility;
8681 r.el.style.display = "none";
8683 this._measureChanged = null;
8689 * Update the innerHTML of this element, optionally searching for and processing scripts
8690 * @param {String} html The new HTML
8691 * @param {Boolean} loadScripts (optional) true to look for and process scripts
8692 * @param {Function} callback For async script loading you can be noticed when the update completes
8693 * @return {Roo.Element} this
8695 update : function(html, loadScripts, callback){
8696 if(typeof html == "undefined"){
8699 if(loadScripts !== true){
8700 this.dom.innerHTML = html;
8701 if(typeof callback == "function"){
8709 html += '<span id="' + id + '"></span>';
8711 E.onAvailable(id, function(){
8712 var hd = document.getElementsByTagName("head")[0];
8713 var re = /(?:<script([^>]*)?>)((\n|\r|.)*?)(?:<\/script>)/ig;
8714 var srcRe = /\ssrc=([\'\"])(.*?)\1/i;
8715 var typeRe = /\stype=([\'\"])(.*?)\1/i;
8718 while(match = re.exec(html)){
8719 var attrs = match[1];
8720 var srcMatch = attrs ? attrs.match(srcRe) : false;
8721 if(srcMatch && srcMatch[2]){
8722 var s = document.createElement("script");
8723 s.src = srcMatch[2];
8724 var typeMatch = attrs.match(typeRe);
8725 if(typeMatch && typeMatch[2]){
8726 s.type = typeMatch[2];
8729 }else if(match[2] && match[2].length > 0){
8730 if(window.execScript) {
8731 window.execScript(match[2]);
8739 window.eval(match[2]);
8743 var el = document.getElementById(id);
8744 if(el){el.parentNode.removeChild(el);}
8745 if(typeof callback == "function"){
8749 dom.innerHTML = html.replace(/(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig, "");
8754 * Direct access to the UpdateManager update() method (takes the same parameters).
8755 * @param {String/Function} url The url for this request or a function to call to get the url
8756 * @param {String/Object} params (optional) The parameters to pass as either a url encoded string "param1=1&param2=2" or an object {param1: 1, param2: 2}
8757 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
8758 * @param {Boolean} discardUrl (optional) By default when you execute an update the defaultUrl is changed to the last used url. If true, it will not store the url.
8759 * @return {Roo.Element} this
8762 var um = this.getUpdateManager();
8763 um.update.apply(um, arguments);
8768 * Gets this element's UpdateManager
8769 * @return {Roo.UpdateManager} The UpdateManager
8771 getUpdateManager : function(){
8772 if(!this.updateManager){
8773 this.updateManager = new Roo.UpdateManager(this);
8775 return this.updateManager;
8779 * Disables text selection for this element (normalized across browsers)
8780 * @return {Roo.Element} this
8782 unselectable : function(){
8783 this.dom.unselectable = "on";
8784 this.swallowEvent("selectstart", true);
8785 this.applyStyles("-moz-user-select:none;-khtml-user-select:none;");
8786 this.addClass("x-unselectable");
8791 * Calculates the x, y to center this element on the screen
8792 * @return {Array} The x, y values [x, y]
8794 getCenterXY : function(){
8795 return this.getAlignToXY(document, 'c-c');
8799 * Centers the Element in either the viewport, or another Element.
8800 * @param {String/HTMLElement/Roo.Element} centerIn (optional) The element in which to center the element.
8802 center : function(centerIn){
8803 this.alignTo(centerIn || document, 'c-c');
8808 * Tests various css rules/browsers to determine if this element uses a border box
8811 isBorderBox : function(){
8812 return noBoxAdjust[this.dom.tagName.toLowerCase()] || Roo.isBorderBox;
8816 * Return a box {x, y, width, height} that can be used to set another elements
8817 * size/location to match this element.
8818 * @param {Boolean} contentBox (optional) If true a box for the content of the element is returned.
8819 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page x/y.
8820 * @return {Object} box An object in the format {x, y, width, height}
8822 getBox : function(contentBox, local){
8827 var left = parseInt(this.getStyle("left"), 10) || 0;
8828 var top = parseInt(this.getStyle("top"), 10) || 0;
8831 var el = this.dom, w = el.offsetWidth, h = el.offsetHeight, bx;
8833 bx = {x: xy[0], y: xy[1], 0: xy[0], 1: xy[1], width: w, height: h};
8835 var l = this.getBorderWidth("l")+this.getPadding("l");
8836 var r = this.getBorderWidth("r")+this.getPadding("r");
8837 var t = this.getBorderWidth("t")+this.getPadding("t");
8838 var b = this.getBorderWidth("b")+this.getPadding("b");
8839 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)};
8841 bx.right = bx.x + bx.width;
8842 bx.bottom = bx.y + bx.height;
8847 * Returns the sum width of the padding and borders for the passed "sides". See getBorderWidth()
8848 for more information about the sides.
8849 * @param {String} sides
8852 getFrameWidth : function(sides, onlyContentBox){
8853 return onlyContentBox && Roo.isBorderBox ? 0 : (this.getPadding(sides) + this.getBorderWidth(sides));
8857 * 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.
8858 * @param {Object} box The box to fill {x, y, width, height}
8859 * @param {Boolean} adjust (optional) Whether to adjust for box-model issues automatically
8860 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8861 * @return {Roo.Element} this
8863 setBox : function(box, adjust, animate){
8864 var w = box.width, h = box.height;
8865 if((adjust && !this.autoBoxAdjust) && !this.isBorderBox()){
8866 w -= (this.getBorderWidth("lr") + this.getPadding("lr"));
8867 h -= (this.getBorderWidth("tb") + this.getPadding("tb"));
8869 this.setBounds(box.x, box.y, w, h, this.preanim(arguments, 2));
8874 * Forces the browser to repaint this element
8875 * @return {Roo.Element} this
8877 repaint : function(){
8879 this.addClass("x-repaint");
8880 setTimeout(function(){
8881 Roo.get(dom).removeClass("x-repaint");
8887 * Returns an object with properties top, left, right and bottom representing the margins of this element unless sides is passed,
8888 * then it returns the calculated width of the sides (see getPadding)
8889 * @param {String} sides (optional) Any combination of l, r, t, b to get the sum of those sides
8890 * @return {Object/Number}
8892 getMargins : function(side){
8895 top: parseInt(this.getStyle("margin-top"), 10) || 0,
8896 left: parseInt(this.getStyle("margin-left"), 10) || 0,
8897 bottom: parseInt(this.getStyle("margin-bottom"), 10) || 0,
8898 right: parseInt(this.getStyle("margin-right"), 10) || 0
8901 return this.addStyles(side, El.margins);
8906 addStyles : function(sides, styles){
8908 for(var i = 0, len = sides.length; i < len; i++){
8909 v = this.getStyle(styles[sides.charAt(i)]);
8911 w = parseInt(v, 10);
8919 * Creates a proxy element of this element
8920 * @param {String/Object} config The class name of the proxy element or a DomHelper config object
8921 * @param {String/HTMLElement} renderTo (optional) The element or element id to render the proxy to (defaults to document.body)
8922 * @param {Boolean} matchBox (optional) True to align and size the proxy to this element now (defaults to false)
8923 * @return {Roo.Element} The new proxy element
8925 createProxy : function(config, renderTo, matchBox){
8927 renderTo = Roo.getDom(renderTo);
8929 renderTo = document.body;
8931 config = typeof config == "object" ?
8932 config : {tag : "div", cls: config};
8933 var proxy = Roo.DomHelper.append(renderTo, config, true);
8935 proxy.setBox(this.getBox());
8941 * Puts a mask over this element to disable user interaction. Requires core.css.
8942 * This method can only be applied to elements which accept child nodes.
8943 * @param {String} msg (optional) A message to display in the mask
8944 * @param {String} msgCls (optional) A css class to apply to the msg element
8945 * @return {Element} The mask element
8947 mask : function(msg, msgCls)
8949 if(this.getStyle("position") == "static"){
8950 this.setStyle("position", "relative");
8953 this._mask = Roo.DomHelper.append(this.dom, {cls:"roo-el-mask"}, true);
8955 this.addClass("x-masked");
8956 this._mask.setDisplayed(true);
8961 while (dom && dom.style) {
8962 if (!isNaN(parseInt(dom.style.zIndex))) {
8963 z = Math.max(z, parseInt(dom.style.zIndex));
8965 dom = dom.parentNode;
8967 // if we are masking the body - then it hides everything..
8968 if (this.dom == document.body) {
8970 this._mask.setWidth(Roo.lib.Dom.getDocumentWidth());
8971 this._mask.setHeight(Roo.lib.Dom.getDocumentHeight());
8974 if(typeof msg == 'string'){
8976 this._maskMsg = Roo.DomHelper.append(this.dom, {cls:"roo-el-mask-msg", cn:{tag:'div'}}, true);
8978 var mm = this._maskMsg;
8979 mm.dom.className = msgCls ? "roo-el-mask-msg " + msgCls : "roo-el-mask-msg";
8980 mm.dom.firstChild.innerHTML = msg;
8981 mm.setDisplayed(true);
8983 mm.setStyle('z-index', z + 102);
8985 if(Roo.isIE && !(Roo.isIE7 && Roo.isStrict) && this.getStyle('height') == 'auto'){ // ie will not expand full height automatically
8986 this._mask.setHeight(this.getHeight());
8988 this._mask.setStyle('z-index', z + 100);
8994 * Removes a previously applied mask. If removeEl is true the mask overlay is destroyed, otherwise
8995 * it is cached for reuse.
8997 unmask : function(removeEl){
8999 if(removeEl === true){
9000 this._mask.remove();
9003 this._maskMsg.remove();
9004 delete this._maskMsg;
9007 this._mask.setDisplayed(false);
9009 this._maskMsg.setDisplayed(false);
9013 this.removeClass("x-masked");
9017 * Returns true if this element is masked
9020 isMasked : function(){
9021 return this._mask && this._mask.isVisible();
9025 * Creates an iframe shim for this element to keep selects and other windowed objects from
9027 * @return {Roo.Element} The new shim element
9029 createShim : function(){
9030 var el = document.createElement('iframe');
9031 el.frameBorder = 'no';
9032 el.className = 'roo-shim';
9033 if(Roo.isIE && Roo.isSecure){
9034 el.src = Roo.SSL_SECURE_URL;
9036 var shim = Roo.get(this.dom.parentNode.insertBefore(el, this.dom));
9037 shim.autoBoxAdjust = false;
9042 * Removes this element from the DOM and deletes it from the cache
9044 remove : function(){
9045 if(this.dom.parentNode){
9046 this.dom.parentNode.removeChild(this.dom);
9048 delete El.cache[this.dom.id];
9052 * Sets up event handlers to add and remove a css class when the mouse is over this element
9053 * @param {String} className
9054 * @param {Boolean} preventFlicker (optional) If set to true, it prevents flickering by filtering
9055 * mouseout events for children elements
9056 * @return {Roo.Element} this
9058 addClassOnOver : function(className, preventFlicker){
9059 this.on("mouseover", function(){
9060 Roo.fly(this, '_internal').addClass(className);
9062 var removeFn = function(e){
9063 if(preventFlicker !== true || !e.within(this, true)){
9064 Roo.fly(this, '_internal').removeClass(className);
9067 this.on("mouseout", removeFn, this.dom);
9072 * Sets up event handlers to add and remove a css class when this element has the focus
9073 * @param {String} className
9074 * @return {Roo.Element} this
9076 addClassOnFocus : function(className){
9077 this.on("focus", function(){
9078 Roo.fly(this, '_internal').addClass(className);
9080 this.on("blur", function(){
9081 Roo.fly(this, '_internal').removeClass(className);
9086 * 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)
9087 * @param {String} className
9088 * @return {Roo.Element} this
9090 addClassOnClick : function(className){
9092 this.on("mousedown", function(){
9093 Roo.fly(dom, '_internal').addClass(className);
9094 var d = Roo.get(document);
9095 var fn = function(){
9096 Roo.fly(dom, '_internal').removeClass(className);
9097 d.removeListener("mouseup", fn);
9099 d.on("mouseup", fn);
9105 * Stops the specified event from bubbling and optionally prevents the default action
9106 * @param {String} eventName
9107 * @param {Boolean} preventDefault (optional) true to prevent the default action too
9108 * @return {Roo.Element} this
9110 swallowEvent : function(eventName, preventDefault){
9111 var fn = function(e){
9112 e.stopPropagation();
9117 if(eventName instanceof Array){
9118 for(var i = 0, len = eventName.length; i < len; i++){
9119 this.on(eventName[i], fn);
9123 this.on(eventName, fn);
9130 fitToParentDelegate : Roo.emptyFn, // keep a reference to the fitToParent delegate
9133 * Sizes this element to its parent element's dimensions performing
9134 * neccessary box adjustments.
9135 * @param {Boolean} monitorResize (optional) If true maintains the fit when the browser window is resized.
9136 * @param {String/HTMLElment/Element} targetParent (optional) The target parent, default to the parentNode.
9137 * @return {Roo.Element} this
9139 fitToParent : function(monitorResize, targetParent) {
9140 Roo.EventManager.removeResizeListener(this.fitToParentDelegate); // always remove previous fitToParent delegate from onWindowResize
9141 this.fitToParentDelegate = Roo.emptyFn; // remove reference to previous delegate
9142 if (monitorResize === true && !this.dom.parentNode) { // check if this Element still exists
9145 var p = Roo.get(targetParent || this.dom.parentNode);
9146 this.setSize(p.getComputedWidth() - p.getFrameWidth('lr'), p.getComputedHeight() - p.getFrameWidth('tb'));
9147 if (monitorResize === true) {
9148 this.fitToParentDelegate = this.fitToParent.createDelegate(this, [true, targetParent]);
9149 Roo.EventManager.onWindowResize(this.fitToParentDelegate);
9155 * Gets the next sibling, skipping text nodes
9156 * @return {HTMLElement} The next sibling or null
9158 getNextSibling : function(){
9159 var n = this.dom.nextSibling;
9160 while(n && n.nodeType != 1){
9167 * Gets the previous sibling, skipping text nodes
9168 * @return {HTMLElement} The previous sibling or null
9170 getPrevSibling : function(){
9171 var n = this.dom.previousSibling;
9172 while(n && n.nodeType != 1){
9173 n = n.previousSibling;
9180 * Appends the passed element(s) to this element
9181 * @param {String/HTMLElement/Array/Element/CompositeElement} el
9182 * @return {Roo.Element} this
9184 appendChild: function(el){
9191 * Creates the passed DomHelper config and appends it to this element or optionally inserts it before the passed child element.
9192 * @param {Object} config DomHelper element config object. If no tag is specified (e.g., {tag:'input'}) then a div will be
9193 * automatically generated with the specified attributes.
9194 * @param {HTMLElement} insertBefore (optional) a child element of this element
9195 * @param {Boolean} returnDom (optional) true to return the dom node instead of creating an Element
9196 * @return {Roo.Element} The new child element
9198 createChild: function(config, insertBefore, returnDom){
9199 config = config || {tag:'div'};
9201 return Roo.DomHelper.insertBefore(insertBefore, config, returnDom !== true);
9203 return Roo.DomHelper[!this.dom.firstChild ? 'overwrite' : 'append'](this.dom, config, returnDom !== true);
9207 * Appends this element to the passed element
9208 * @param {String/HTMLElement/Element} el The new parent element
9209 * @return {Roo.Element} this
9211 appendTo: function(el){
9212 el = Roo.getDom(el);
9213 el.appendChild(this.dom);
9218 * Inserts this element before the passed element in the DOM
9219 * @param {String/HTMLElement/Element} el The element to insert before
9220 * @return {Roo.Element} this
9222 insertBefore: function(el){
9223 el = Roo.getDom(el);
9224 el.parentNode.insertBefore(this.dom, el);
9229 * Inserts this element after the passed element in the DOM
9230 * @param {String/HTMLElement/Element} el The element to insert after
9231 * @return {Roo.Element} this
9233 insertAfter: function(el){
9234 el = Roo.getDom(el);
9235 el.parentNode.insertBefore(this.dom, el.nextSibling);
9240 * Inserts (or creates) an element (or DomHelper config) as the first child of the this element
9241 * @param {String/HTMLElement/Element/Object} el The id or element to insert or a DomHelper config to create and insert
9242 * @return {Roo.Element} The new child
9244 insertFirst: function(el, returnDom){
9246 if(typeof el == 'object' && !el.nodeType){ // dh config
9247 return this.createChild(el, this.dom.firstChild, returnDom);
9249 el = Roo.getDom(el);
9250 this.dom.insertBefore(el, this.dom.firstChild);
9251 return !returnDom ? Roo.get(el) : el;
9256 * Inserts (or creates) the passed element (or DomHelper config) as a sibling of this element
9257 * @param {String/HTMLElement/Element/Object} el The id or element to insert or a DomHelper config to create and insert
9258 * @param {String} where (optional) 'before' or 'after' defaults to before
9259 * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Roo.Element
9260 * @return {Roo.Element} the inserted Element
9262 insertSibling: function(el, where, returnDom){
9263 where = where ? where.toLowerCase() : 'before';
9265 var rt, refNode = where == 'before' ? this.dom : this.dom.nextSibling;
9267 if(typeof el == 'object' && !el.nodeType){ // dh config
9268 if(where == 'after' && !this.dom.nextSibling){
9269 rt = Roo.DomHelper.append(this.dom.parentNode, el, !returnDom);
9271 rt = Roo.DomHelper[where == 'after' ? 'insertAfter' : 'insertBefore'](this.dom, el, !returnDom);
9275 rt = this.dom.parentNode.insertBefore(Roo.getDom(el),
9276 where == 'before' ? this.dom : this.dom.nextSibling);
9285 * Creates and wraps this element with another element
9286 * @param {Object} config (optional) DomHelper element config object for the wrapper element or null for an empty div
9287 * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Roo.Element
9288 * @return {HTMLElement/Element} The newly created wrapper element
9290 wrap: function(config, returnDom){
9292 config = {tag: "div"};
9294 var newEl = Roo.DomHelper.insertBefore(this.dom, config, !returnDom);
9295 newEl.dom ? newEl.dom.appendChild(this.dom) : newEl.appendChild(this.dom);
9300 * Replaces the passed element with this element
9301 * @param {String/HTMLElement/Element} el The element to replace
9302 * @return {Roo.Element} this
9304 replace: function(el){
9306 this.insertBefore(el);
9312 * Inserts an html fragment into this element
9313 * @param {String} where Where to insert the html in relation to the this element - beforeBegin, afterBegin, beforeEnd, afterEnd.
9314 * @param {String} html The HTML fragment
9315 * @param {Boolean} returnEl True to return an Roo.Element
9316 * @return {HTMLElement/Roo.Element} The inserted node (or nearest related if more than 1 inserted)
9318 insertHtml : function(where, html, returnEl){
9319 var el = Roo.DomHelper.insertHtml(where, this.dom, html);
9320 return returnEl ? Roo.get(el) : el;
9324 * Sets the passed attributes as attributes of this element (a style attribute can be a string, object or function)
9325 * @param {Object} o The object with the attributes
9326 * @param {Boolean} useSet (optional) false to override the default setAttribute to use expandos.
9327 * @return {Roo.Element} this
9329 set : function(o, useSet){
9331 useSet = typeof useSet == 'undefined' ? (el.setAttribute ? true : false) : useSet;
9333 if(attr == "style" || typeof o[attr] == "function") continue;
9335 el.className = o["cls"];
9337 if(useSet) el.setAttribute(attr, o[attr]);
9338 else el[attr] = o[attr];
9342 Roo.DomHelper.applyStyles(el, o.style);
9348 * Convenience method for constructing a KeyMap
9349 * @param {Number/Array/Object/String} key Either a string with the keys to listen for, the numeric key code, array of key codes or an object with the following options:
9350 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
9351 * @param {Function} fn The function to call
9352 * @param {Object} scope (optional) The scope of the function
9353 * @return {Roo.KeyMap} The KeyMap created
9355 addKeyListener : function(key, fn, scope){
9357 if(typeof key != "object" || key instanceof Array){
9373 return new Roo.KeyMap(this, config);
9377 * Creates a KeyMap for this element
9378 * @param {Object} config The KeyMap config. See {@link Roo.KeyMap} for more details
9379 * @return {Roo.KeyMap} The KeyMap created
9381 addKeyMap : function(config){
9382 return new Roo.KeyMap(this, config);
9386 * Returns true if this element is scrollable.
9389 isScrollable : function(){
9391 return dom.scrollHeight > dom.clientHeight || dom.scrollWidth > dom.clientWidth;
9395 * 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().
9396 * @param {String} side Either "left" for scrollLeft values or "top" for scrollTop values.
9397 * @param {Number} value The new scroll value
9398 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9399 * @return {Element} this
9402 scrollTo : function(side, value, animate){
9403 var prop = side.toLowerCase() == "left" ? "scrollLeft" : "scrollTop";
9405 this.dom[prop] = value;
9407 var to = prop == "scrollLeft" ? [value, this.dom.scrollTop] : [this.dom.scrollLeft, value];
9408 this.anim({scroll: {"to": to}}, this.preanim(arguments, 2), 'scroll');
9414 * Scrolls this element the specified direction. Does bounds checking to make sure the scroll is
9415 * within this element's scrollable range.
9416 * @param {String} direction Possible values are: "l","left" - "r","right" - "t","top","up" - "b","bottom","down".
9417 * @param {Number} distance How far to scroll the element in pixels
9418 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9419 * @return {Boolean} Returns true if a scroll was triggered or false if the element
9420 * was scrolled as far as it could go.
9422 scroll : function(direction, distance, animate){
9423 if(!this.isScrollable()){
9427 var l = el.scrollLeft, t = el.scrollTop;
9428 var w = el.scrollWidth, h = el.scrollHeight;
9429 var cw = el.clientWidth, ch = el.clientHeight;
9430 direction = direction.toLowerCase();
9431 var scrolled = false;
9432 var a = this.preanim(arguments, 2);
9437 var v = Math.min(l + distance, w-cw);
9438 this.scrollTo("left", v, a);
9445 var v = Math.max(l - distance, 0);
9446 this.scrollTo("left", v, a);
9454 var v = Math.max(t - distance, 0);
9455 this.scrollTo("top", v, a);
9463 var v = Math.min(t + distance, h-ch);
9464 this.scrollTo("top", v, a);
9473 * Translates the passed page coordinates into left/top css values for this element
9474 * @param {Number/Array} x The page x or an array containing [x, y]
9475 * @param {Number} y The page y
9476 * @return {Object} An object with left and top properties. e.g. {left: (value), top: (value)}
9478 translatePoints : function(x, y){
9479 if(typeof x == 'object' || x instanceof Array){
9482 var p = this.getStyle('position');
9483 var o = this.getXY();
9485 var l = parseInt(this.getStyle('left'), 10);
9486 var t = parseInt(this.getStyle('top'), 10);
9489 l = (p == "relative") ? 0 : this.dom.offsetLeft;
9492 t = (p == "relative") ? 0 : this.dom.offsetTop;
9495 return {left: (x - o[0] + l), top: (y - o[1] + t)};
9499 * Returns the current scroll position of the element.
9500 * @return {Object} An object containing the scroll position in the format {left: (scrollLeft), top: (scrollTop)}
9502 getScroll : function(){
9503 var d = this.dom, doc = document;
9504 if(d == doc || d == doc.body){
9505 var l = window.pageXOffset || doc.documentElement.scrollLeft || doc.body.scrollLeft || 0;
9506 var t = window.pageYOffset || doc.documentElement.scrollTop || doc.body.scrollTop || 0;
9507 return {left: l, top: t};
9509 return {left: d.scrollLeft, top: d.scrollTop};
9514 * Return the CSS color for the specified CSS attribute. rgb, 3 digit (like #fff) and valid values
9515 * are convert to standard 6 digit hex color.
9516 * @param {String} attr The css attribute
9517 * @param {String} defaultValue The default value to use when a valid color isn't found
9518 * @param {String} prefix (optional) defaults to #. Use an empty string when working with
9521 getColor : function(attr, defaultValue, prefix){
9522 var v = this.getStyle(attr);
9523 if(!v || v == "transparent" || v == "inherit") {
9524 return defaultValue;
9526 var color = typeof prefix == "undefined" ? "#" : prefix;
9527 if(v.substr(0, 4) == "rgb("){
9528 var rvs = v.slice(4, v.length -1).split(",");
9529 for(var i = 0; i < 3; i++){
9530 var h = parseInt(rvs[i]).toString(16);
9537 if(v.substr(0, 1) == "#"){
9539 for(var i = 1; i < 4; i++){
9540 var c = v.charAt(i);
9543 }else if(v.length == 7){
9544 color += v.substr(1);
9548 return(color.length > 5 ? color.toLowerCase() : defaultValue);
9552 * Wraps the specified element with a special markup/CSS block that renders by default as a gray container with a
9553 * gradient background, rounded corners and a 4-way shadow.
9554 * @param {String} class (optional) A base CSS class to apply to the containing wrapper element (defaults to 'x-box').
9555 * Note that there are a number of CSS rules that are dependent on this name to make the overall effect work,
9556 * so if you supply an alternate base class, make sure you also supply all of the necessary rules.
9557 * @return {Roo.Element} this
9559 boxWrap : function(cls){
9560 cls = cls || 'x-box';
9561 var el = Roo.get(this.insertHtml('beforeBegin', String.format('<div class="{0}">'+El.boxMarkup+'</div>', cls)));
9562 el.child('.'+cls+'-mc').dom.appendChild(this.dom);
9567 * Returns the value of a namespaced attribute from the element's underlying DOM node.
9568 * @param {String} namespace The namespace in which to look for the attribute
9569 * @param {String} name The attribute name
9570 * @return {String} The attribute value
9572 getAttributeNS : Roo.isIE ? function(ns, name){
9574 var type = typeof d[ns+":"+name];
9575 if(type != 'undefined' && type != 'unknown'){
9576 return d[ns+":"+name];
9579 } : function(ns, name){
9581 return d.getAttributeNS(ns, name) || d.getAttribute(ns+":"+name) || d.getAttribute(name) || d[name];
9586 * Sets or Returns the value the dom attribute value
9587 * @param {String} name The attribute name
9588 * @param {String} value (optional) The value to set the attribute to
9589 * @return {String} The attribute value
9591 attr : function(name){
9592 if (arguments.length > 1) {
9593 this.dom.setAttribute(name, arguments[1]);
9594 return arguments[1];
9596 if (!this.dom.hasAttribute(name)) {
9599 return this.dom.getAttribute(name);
9606 var ep = El.prototype;
9609 * Appends an event handler (Shorthand for addListener)
9610 * @param {String} eventName The type of event to append
9611 * @param {Function} fn The method the event invokes
9612 * @param {Object} scope (optional) The scope (this object) of the fn
9613 * @param {Object} options (optional)An object with standard {@link Roo.EventManager#addListener} options
9616 ep.on = ep.addListener;
9618 ep.mon = ep.addListener;
9621 * Removes an event handler from this element (shorthand for removeListener)
9622 * @param {String} eventName the type of event to remove
9623 * @param {Function} fn the method the event invokes
9624 * @return {Roo.Element} this
9627 ep.un = ep.removeListener;
9630 * true to automatically adjust width and height settings for box-model issues (default to true)
9632 ep.autoBoxAdjust = true;
9635 El.unitPattern = /\d+(px|em|%|en|ex|pt|in|cm|mm|pc)$/i;
9638 El.addUnits = function(v, defaultUnit){
9639 if(v === "" || v == "auto"){
9642 if(v === undefined){
9645 if(typeof v == "number" || !El.unitPattern.test(v)){
9646 return v + (defaultUnit || 'px');
9651 // special markup used throughout Roo when box wrapping elements
9652 El.boxMarkup = '<div class="{0}-tl"><div class="{0}-tr"><div class="{0}-tc"></div></div></div><div class="{0}-ml"><div class="{0}-mr"><div class="{0}-mc"></div></div></div><div class="{0}-bl"><div class="{0}-br"><div class="{0}-bc"></div></div></div>';
9654 * Visibility mode constant - Use visibility to hide element
9660 * Visibility mode constant - Use display to hide element
9666 El.borders = {l: "border-left-width", r: "border-right-width", t: "border-top-width", b: "border-bottom-width"};
9667 El.paddings = {l: "padding-left", r: "padding-right", t: "padding-top", b: "padding-bottom"};
9668 El.margins = {l: "margin-left", r: "margin-right", t: "margin-top", b: "margin-bottom"};
9680 * Static method to retrieve Element objects. Uses simple caching to consistently return the same object.
9681 * Automatically fixes if an object was recreated with the same id via AJAX or DOM.
9682 * @param {String/HTMLElement/Element} el The id of the node, a DOM Node or an existing Element.
9683 * @return {Element} The Element object
9686 El.get = function(el){
9688 if(!el){ return null; }
9689 if(typeof el == "string"){ // element id
9690 if(!(elm = document.getElementById(el))){
9693 if(ex = El.cache[el]){
9696 ex = El.cache[el] = new El(elm);
9699 }else if(el.tagName){ // dom element
9703 if(ex = El.cache[id]){
9706 ex = El.cache[id] = new El(el);
9709 }else if(el instanceof El){
9711 el.dom = document.getElementById(el.id) || el.dom; // refresh dom element in case no longer valid,
9712 // catch case where it hasn't been appended
9713 El.cache[el.id] = el; // in case it was created directly with Element(), let's cache it
9716 }else if(el.isComposite){
9718 }else if(el instanceof Array){
9719 return El.select(el);
9720 }else if(el == document){
9721 // create a bogus element object representing the document object
9723 var f = function(){};
9724 f.prototype = El.prototype;
9726 docEl.dom = document;
9734 El.uncache = function(el){
9735 for(var i = 0, a = arguments, len = a.length; i < len; i++) {
9737 delete El.cache[a[i].id || a[i]];
9743 // Garbage collection - uncache elements/purge listeners on orphaned elements
9744 // so we don't hold a reference and cause the browser to retain them
9745 El.garbageCollect = function(){
9746 if(!Roo.enableGarbageCollector){
9747 clearInterval(El.collectorThread);
9750 for(var eid in El.cache){
9751 var el = El.cache[eid], d = el.dom;
9752 // -------------------------------------------------------
9753 // Determining what is garbage:
9754 // -------------------------------------------------------
9756 // dom node is null, definitely garbage
9757 // -------------------------------------------------------
9759 // no parentNode == direct orphan, definitely garbage
9760 // -------------------------------------------------------
9761 // !d.offsetParent && !document.getElementById(eid)
9762 // display none elements have no offsetParent so we will
9763 // also try to look it up by it's id. However, check
9764 // offsetParent first so we don't do unneeded lookups.
9765 // This enables collection of elements that are not orphans
9766 // directly, but somewhere up the line they have an orphan
9768 // -------------------------------------------------------
9769 if(!d || !d.parentNode || (!d.offsetParent && !document.getElementById(eid))){
9770 delete El.cache[eid];
9771 if(d && Roo.enableListenerCollection){
9777 El.collectorThreadId = setInterval(El.garbageCollect, 30000);
9781 El.Flyweight = function(dom){
9784 El.Flyweight.prototype = El.prototype;
9786 El._flyweights = {};
9788 * Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
9789 * the dom node can be overwritten by other code.
9790 * @param {String/HTMLElement} el The dom node or id
9791 * @param {String} named (optional) Allows for creation of named reusable flyweights to
9792 * prevent conflicts (e.g. internally Roo uses "_internal")
9794 * @return {Element} The shared Element object
9796 El.fly = function(el, named){
9797 named = named || '_global';
9798 el = Roo.getDom(el);
9802 if(!El._flyweights[named]){
9803 El._flyweights[named] = new El.Flyweight();
9805 El._flyweights[named].dom = el;
9806 return El._flyweights[named];
9810 * Static method to retrieve Element objects. Uses simple caching to consistently return the same object.
9811 * Automatically fixes if an object was recreated with the same id via AJAX or DOM.
9812 * Shorthand of {@link Roo.Element#get}
9813 * @param {String/HTMLElement/Element} el The id of the node, a DOM Node or an existing Element.
9814 * @return {Element} The Element object
9820 * Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
9821 * the dom node can be overwritten by other code.
9822 * Shorthand of {@link Roo.Element#fly}
9823 * @param {String/HTMLElement} el The dom node or id
9824 * @param {String} named (optional) Allows for creation of named reusable flyweights to
9825 * prevent conflicts (e.g. internally Roo uses "_internal")
9827 * @return {Element} The shared Element object
9833 // speedy lookup for elements never to box adjust
9834 var noBoxAdjust = Roo.isStrict ? {
9837 input:1, select:1, textarea:1
9839 if(Roo.isIE || Roo.isGecko){
9840 noBoxAdjust['button'] = 1;
9844 Roo.EventManager.on(window, 'unload', function(){
9846 delete El._flyweights;
9854 Roo.Element.selectorFunction = Roo.DomQuery.select;
9857 Roo.Element.select = function(selector, unique, root){
9859 if(typeof selector == "string"){
9860 els = Roo.Element.selectorFunction(selector, root);
9861 }else if(selector.length !== undefined){
9864 throw "Invalid selector";
9866 if(unique === true){
9867 return new Roo.CompositeElement(els);
9869 return new Roo.CompositeElementLite(els);
9873 * Selects elements based on the passed CSS selector to enable working on them as 1.
9874 * @param {String/Array} selector The CSS selector or an array of elements
9875 * @param {Boolean} unique (optional) true to create a unique Roo.Element for each element (defaults to a shared flyweight object)
9876 * @param {HTMLElement/String} root (optional) The root element of the query or id of the root
9877 * @return {CompositeElementLite/CompositeElement}
9881 Roo.select = Roo.Element.select;
9898 * Ext JS Library 1.1.1
9899 * Copyright(c) 2006-2007, Ext JS, LLC.
9901 * Originally Released Under LGPL - original licence link has changed is not relivant.
9904 * <script type="text/javascript">
9909 //Notifies Element that fx methods are available
9910 Roo.enableFx = true;
9914 * <p>A class to provide basic animation and visual effects support. <b>Note:</b> This class is automatically applied
9915 * to the {@link Roo.Element} interface when included, so all effects calls should be performed via Element.
9916 * Conversely, since the effects are not actually defined in Element, Roo.Fx <b>must</b> be included in order for the
9917 * Element effects to work.</p><br/>
9919 * <p>It is important to note that although the Fx methods and many non-Fx Element methods support "method chaining" in that
9920 * they return the Element object itself as the method return value, it is not always possible to mix the two in a single
9921 * method chain. The Fx methods use an internal effects queue so that each effect can be properly timed and sequenced.
9922 * Non-Fx methods, on the other hand, have no such internal queueing and will always execute immediately. For this reason,
9923 * while it may be possible to mix certain Fx and non-Fx method calls in a single chain, it may not always provide the
9924 * expected results and should be done with care.</p><br/>
9926 * <p>Motion effects support 8-way anchoring, meaning that you can choose one of 8 different anchor points on the Element
9927 * that will serve as either the start or end point of the animation. Following are all of the supported anchor positions:</p>
9930 ----- -----------------------------
9931 tl The top left corner
9932 t The center of the top edge
9933 tr The top right corner
9934 l The center of the left edge
9935 r The center of the right edge
9936 bl The bottom left corner
9937 b The center of the bottom edge
9938 br The bottom right corner
9940 * <b>Although some Fx methods accept specific custom config parameters, the ones shown in the Config Options section
9941 * below are common options that can be passed to any Fx method.</b>
9942 * @cfg {Function} callback A function called when the effect is finished
9943 * @cfg {Object} scope The scope of the effect function
9944 * @cfg {String} easing A valid Easing value for the effect
9945 * @cfg {String} afterCls A css class to apply after the effect
9946 * @cfg {Number} duration The length of time (in seconds) that the effect should last
9947 * @cfg {Boolean} remove Whether the Element should be removed from the DOM and destroyed after the effect finishes
9948 * @cfg {Boolean} useDisplay Whether to use the <i>display</i> CSS property instead of <i>visibility</i> when hiding Elements (only applies to
9949 * effects that end with the element being visually hidden, ignored otherwise)
9950 * @cfg {String/Object/Function} afterStyle A style specification string, e.g. "width:100px", or an object in the form {width:"100px"}, or
9951 * a function which returns such a specification that will be applied to the Element after the effect finishes
9952 * @cfg {Boolean} block Whether the effect should block other effects from queueing while it runs
9953 * @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
9954 * @cfg {Boolean} stopFx Whether subsequent effects should be stopped and removed after the current effect finishes
9958 * Slides the element into view. An anchor point can be optionally passed to set the point of
9959 * origin for the slide effect. This function automatically handles wrapping the element with
9960 * a fixed-size container if needed. See the Fx class overview for valid anchor point options.
9963 // default: slide the element in from the top
9966 // custom: slide the element in from the right with a 2-second duration
9967 el.slideIn('r', { duration: 2 });
9969 // common config options shown with default values
9975 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to top: 't')
9976 * @param {Object} options (optional) Object literal with any of the Fx config options
9977 * @return {Roo.Element} The Element
9979 slideIn : function(anchor, o){
9980 var el = this.getFxEl();
9983 el.queueFx(o, function(){
9985 anchor = anchor || "t";
9987 // fix display to visibility
9990 // restore values after effect
9991 var r = this.getFxRestore();
9992 var b = this.getBox();
9993 // fixed size for slide
9997 var wrap = this.fxWrap(r.pos, o, "hidden");
9999 var st = this.dom.style;
10000 st.visibility = "visible";
10001 st.position = "absolute";
10003 // clear out temp styles after slide and unwrap
10004 var after = function(){
10005 el.fxUnwrap(wrap, r.pos, o);
10006 st.width = r.width;
10007 st.height = r.height;
10010 // time to calc the positions
10011 var a, pt = {to: [b.x, b.y]}, bw = {to: b.width}, bh = {to: b.height};
10013 switch(anchor.toLowerCase()){
10015 wrap.setSize(b.width, 0);
10016 st.left = st.bottom = "0";
10020 wrap.setSize(0, b.height);
10021 st.right = st.top = "0";
10025 wrap.setSize(0, b.height);
10026 wrap.setX(b.right);
10027 st.left = st.top = "0";
10028 a = {width: bw, points: pt};
10031 wrap.setSize(b.width, 0);
10032 wrap.setY(b.bottom);
10033 st.left = st.top = "0";
10034 a = {height: bh, points: pt};
10037 wrap.setSize(0, 0);
10038 st.right = st.bottom = "0";
10039 a = {width: bw, height: bh};
10042 wrap.setSize(0, 0);
10043 wrap.setY(b.y+b.height);
10044 st.right = st.top = "0";
10045 a = {width: bw, height: bh, points: pt};
10048 wrap.setSize(0, 0);
10049 wrap.setXY([b.right, b.bottom]);
10050 st.left = st.top = "0";
10051 a = {width: bw, height: bh, points: pt};
10054 wrap.setSize(0, 0);
10055 wrap.setX(b.x+b.width);
10056 st.left = st.bottom = "0";
10057 a = {width: bw, height: bh, points: pt};
10060 this.dom.style.visibility = "visible";
10063 arguments.callee.anim = wrap.fxanim(a,
10073 * Slides the element out of view. An anchor point can be optionally passed to set the end point
10074 * for the slide effect. When the effect is completed, the element will be hidden (visibility =
10075 * 'hidden') but block elements will still take up space in the document. The element must be removed
10076 * from the DOM using the 'remove' config option if desired. This function automatically handles
10077 * wrapping the element with a fixed-size container if needed. See the Fx class overview for valid anchor point options.
10080 // default: slide the element out to the top
10083 // custom: slide the element out to the right with a 2-second duration
10084 el.slideOut('r', { duration: 2 });
10086 // common config options shown with default values
10094 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to top: 't')
10095 * @param {Object} options (optional) Object literal with any of the Fx config options
10096 * @return {Roo.Element} The Element
10098 slideOut : function(anchor, o){
10099 var el = this.getFxEl();
10102 el.queueFx(o, function(){
10104 anchor = anchor || "t";
10106 // restore values after effect
10107 var r = this.getFxRestore();
10109 var b = this.getBox();
10110 // fixed size for slide
10114 var wrap = this.fxWrap(r.pos, o, "visible");
10116 var st = this.dom.style;
10117 st.visibility = "visible";
10118 st.position = "absolute";
10122 var after = function(){
10124 el.setDisplayed(false);
10129 el.fxUnwrap(wrap, r.pos, o);
10131 st.width = r.width;
10132 st.height = r.height;
10137 var a, zero = {to: 0};
10138 switch(anchor.toLowerCase()){
10140 st.left = st.bottom = "0";
10141 a = {height: zero};
10144 st.right = st.top = "0";
10148 st.left = st.top = "0";
10149 a = {width: zero, points: {to:[b.right, b.y]}};
10152 st.left = st.top = "0";
10153 a = {height: zero, points: {to:[b.x, b.bottom]}};
10156 st.right = st.bottom = "0";
10157 a = {width: zero, height: zero};
10160 st.right = st.top = "0";
10161 a = {width: zero, height: zero, points: {to:[b.x, b.bottom]}};
10164 st.left = st.top = "0";
10165 a = {width: zero, height: zero, points: {to:[b.x+b.width, b.bottom]}};
10168 st.left = st.bottom = "0";
10169 a = {width: zero, height: zero, points: {to:[b.right, b.y]}};
10173 arguments.callee.anim = wrap.fxanim(a,
10183 * Fades the element out while slowly expanding it in all directions. When the effect is completed, the
10184 * element will be hidden (visibility = 'hidden') but block elements will still take up space in the document.
10185 * The element must be removed from the DOM using the 'remove' config option if desired.
10191 // common config options shown with default values
10199 * @param {Object} options (optional) Object literal with any of the Fx config options
10200 * @return {Roo.Element} The Element
10202 puff : function(o){
10203 var el = this.getFxEl();
10206 el.queueFx(o, function(){
10207 this.clearOpacity();
10210 // restore values after effect
10211 var r = this.getFxRestore();
10212 var st = this.dom.style;
10214 var after = function(){
10216 el.setDisplayed(false);
10223 el.setPositioning(r.pos);
10224 st.width = r.width;
10225 st.height = r.height;
10230 var width = this.getWidth();
10231 var height = this.getHeight();
10233 arguments.callee.anim = this.fxanim({
10234 width : {to: this.adjustWidth(width * 2)},
10235 height : {to: this.adjustHeight(height * 2)},
10236 points : {by: [-(width * .5), -(height * .5)]},
10238 fontSize: {to:200, unit: "%"}
10249 * Blinks the element as if it was clicked and then collapses on its center (similar to switching off a television).
10250 * When the effect is completed, the element will be hidden (visibility = 'hidden') but block elements will still
10251 * take up space in the document. The element must be removed from the DOM using the 'remove' config option if desired.
10257 // all config options shown with default values
10265 * @param {Object} options (optional) Object literal with any of the Fx config options
10266 * @return {Roo.Element} The Element
10268 switchOff : function(o){
10269 var el = this.getFxEl();
10272 el.queueFx(o, function(){
10273 this.clearOpacity();
10276 // restore values after effect
10277 var r = this.getFxRestore();
10278 var st = this.dom.style;
10280 var after = function(){
10282 el.setDisplayed(false);
10288 el.setPositioning(r.pos);
10289 st.width = r.width;
10290 st.height = r.height;
10295 this.fxanim({opacity:{to:0.3}}, null, null, .1, null, function(){
10296 this.clearOpacity();
10300 points:{by:[0, this.getHeight() * .5]}
10301 }, o, 'motion', 0.3, 'easeIn', after);
10302 }).defer(100, this);
10309 * Highlights the Element by setting a color (applies to the background-color by default, but can be
10310 * changed using the "attr" config option) and then fading back to the original color. If no original
10311 * color is available, you should provide the "endColor" config option which will be cleared after the animation.
10314 // default: highlight background to yellow
10317 // custom: highlight foreground text to blue for 2 seconds
10318 el.highlight("0000ff", { attr: 'color', duration: 2 });
10320 // common config options shown with default values
10321 el.highlight("ffff9c", {
10322 attr: "background-color", //can be any valid CSS property (attribute) that supports a color value
10323 endColor: (current color) or "ffffff",
10328 * @param {String} color (optional) The highlight color. Should be a 6 char hex color without the leading # (defaults to yellow: 'ffff9c')
10329 * @param {Object} options (optional) Object literal with any of the Fx config options
10330 * @return {Roo.Element} The Element
10332 highlight : function(color, o){
10333 var el = this.getFxEl();
10336 el.queueFx(o, function(){
10337 color = color || "ffff9c";
10338 attr = o.attr || "backgroundColor";
10340 this.clearOpacity();
10343 var origColor = this.getColor(attr);
10344 var restoreColor = this.dom.style[attr];
10345 endColor = (o.endColor || origColor) || "ffffff";
10347 var after = function(){
10348 el.dom.style[attr] = restoreColor;
10353 a[attr] = {from: color, to: endColor};
10354 arguments.callee.anim = this.fxanim(a,
10364 * Shows a ripple of exploding, attenuating borders to draw attention to an Element.
10367 // default: a single light blue ripple
10370 // custom: 3 red ripples lasting 3 seconds total
10371 el.frame("ff0000", 3, { duration: 3 });
10373 // common config options shown with default values
10374 el.frame("C3DAF9", 1, {
10375 duration: 1 //duration of entire animation (not each individual ripple)
10376 // Note: Easing is not configurable and will be ignored if included
10379 * @param {String} color (optional) The color of the border. Should be a 6 char hex color without the leading # (defaults to light blue: 'C3DAF9').
10380 * @param {Number} count (optional) The number of ripples to display (defaults to 1)
10381 * @param {Object} options (optional) Object literal with any of the Fx config options
10382 * @return {Roo.Element} The Element
10384 frame : function(color, count, o){
10385 var el = this.getFxEl();
10388 el.queueFx(o, function(){
10389 color = color || "#C3DAF9";
10390 if(color.length == 6){
10391 color = "#" + color;
10393 count = count || 1;
10394 duration = o.duration || 1;
10397 var b = this.getBox();
10398 var animFn = function(){
10399 var proxy = this.createProxy({
10402 visbility:"hidden",
10403 position:"absolute",
10404 "z-index":"35000", // yee haw
10405 border:"0px solid " + color
10408 var scale = Roo.isBorderBox ? 2 : 1;
10410 top:{from:b.y, to:b.y - 20},
10411 left:{from:b.x, to:b.x - 20},
10412 borderWidth:{from:0, to:10},
10413 opacity:{from:1, to:0},
10414 height:{from:b.height, to:(b.height + (20*scale))},
10415 width:{from:b.width, to:(b.width + (20*scale))}
10416 }, duration, function(){
10420 animFn.defer((duration/2)*1000, this);
10431 * Creates a pause before any subsequent queued effects begin. If there are
10432 * no effects queued after the pause it will have no effect.
10437 * @param {Number} seconds The length of time to pause (in seconds)
10438 * @return {Roo.Element} The Element
10440 pause : function(seconds){
10441 var el = this.getFxEl();
10444 el.queueFx(o, function(){
10445 setTimeout(function(){
10447 }, seconds * 1000);
10453 * Fade an element in (from transparent to opaque). The ending opacity can be specified
10454 * using the "endOpacity" config option.
10457 // default: fade in from opacity 0 to 100%
10460 // custom: fade in from opacity 0 to 75% over 2 seconds
10461 el.fadeIn({ endOpacity: .75, duration: 2});
10463 // common config options shown with default values
10465 endOpacity: 1, //can be any value between 0 and 1 (e.g. .5)
10470 * @param {Object} options (optional) Object literal with any of the Fx config options
10471 * @return {Roo.Element} The Element
10473 fadeIn : function(o){
10474 var el = this.getFxEl();
10476 el.queueFx(o, function(){
10477 this.setOpacity(0);
10479 this.dom.style.visibility = 'visible';
10480 var to = o.endOpacity || 1;
10481 arguments.callee.anim = this.fxanim({opacity:{to:to}},
10482 o, null, .5, "easeOut", function(){
10484 this.clearOpacity();
10493 * Fade an element out (from opaque to transparent). The ending opacity can be specified
10494 * using the "endOpacity" config option.
10497 // default: fade out from the element's current opacity to 0
10500 // custom: fade out from the element's current opacity to 25% over 2 seconds
10501 el.fadeOut({ endOpacity: .25, duration: 2});
10503 // common config options shown with default values
10505 endOpacity: 0, //can be any value between 0 and 1 (e.g. .5)
10512 * @param {Object} options (optional) Object literal with any of the Fx config options
10513 * @return {Roo.Element} The Element
10515 fadeOut : function(o){
10516 var el = this.getFxEl();
10518 el.queueFx(o, function(){
10519 arguments.callee.anim = this.fxanim({opacity:{to:o.endOpacity || 0}},
10520 o, null, .5, "easeOut", function(){
10521 if(this.visibilityMode == Roo.Element.DISPLAY || o.useDisplay){
10522 this.dom.style.display = "none";
10524 this.dom.style.visibility = "hidden";
10526 this.clearOpacity();
10534 * Animates the transition of an element's dimensions from a starting height/width
10535 * to an ending height/width.
10538 // change height and width to 100x100 pixels
10539 el.scale(100, 100);
10541 // common config options shown with default values. The height and width will default to
10542 // the element's existing values if passed as null.
10545 [element's height], {
10550 * @param {Number} width The new width (pass undefined to keep the original width)
10551 * @param {Number} height The new height (pass undefined to keep the original height)
10552 * @param {Object} options (optional) Object literal with any of the Fx config options
10553 * @return {Roo.Element} The Element
10555 scale : function(w, h, o){
10556 this.shift(Roo.apply({}, o, {
10564 * Animates the transition of any combination of an element's dimensions, xy position and/or opacity.
10565 * Any of these properties not specified in the config object will not be changed. This effect
10566 * requires that at least one new dimension, position or opacity setting must be passed in on
10567 * the config object in order for the function to have any effect.
10570 // slide the element horizontally to x position 200 while changing the height and opacity
10571 el.shift({ x: 200, height: 50, opacity: .8 });
10573 // common config options shown with default values.
10575 width: [element's width],
10576 height: [element's height],
10577 x: [element's x position],
10578 y: [element's y position],
10579 opacity: [element's opacity],
10584 * @param {Object} options Object literal with any of the Fx config options
10585 * @return {Roo.Element} The Element
10587 shift : function(o){
10588 var el = this.getFxEl();
10590 el.queueFx(o, function(){
10591 var a = {}, w = o.width, h = o.height, x = o.x, y = o.y, op = o.opacity;
10592 if(w !== undefined){
10593 a.width = {to: this.adjustWidth(w)};
10595 if(h !== undefined){
10596 a.height = {to: this.adjustHeight(h)};
10598 if(x !== undefined || y !== undefined){
10600 x !== undefined ? x : this.getX(),
10601 y !== undefined ? y : this.getY()
10604 if(op !== undefined){
10605 a.opacity = {to: op};
10607 if(o.xy !== undefined){
10608 a.points = {to: o.xy};
10610 arguments.callee.anim = this.fxanim(a,
10611 o, 'motion', .35, "easeOut", function(){
10619 * Slides the element while fading it out of view. An anchor point can be optionally passed to set the
10620 * ending point of the effect.
10623 // default: slide the element downward while fading out
10626 // custom: slide the element out to the right with a 2-second duration
10627 el.ghost('r', { duration: 2 });
10629 // common config options shown with default values
10637 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to bottom: 'b')
10638 * @param {Object} options (optional) Object literal with any of the Fx config options
10639 * @return {Roo.Element} The Element
10641 ghost : function(anchor, o){
10642 var el = this.getFxEl();
10645 el.queueFx(o, function(){
10646 anchor = anchor || "b";
10648 // restore values after effect
10649 var r = this.getFxRestore();
10650 var w = this.getWidth(),
10651 h = this.getHeight();
10653 var st = this.dom.style;
10655 var after = function(){
10657 el.setDisplayed(false);
10663 el.setPositioning(r.pos);
10664 st.width = r.width;
10665 st.height = r.height;
10670 var a = {opacity: {to: 0}, points: {}}, pt = a.points;
10671 switch(anchor.toLowerCase()){
10698 arguments.callee.anim = this.fxanim(a,
10708 * Ensures that all effects queued after syncFx is called on the element are
10709 * run concurrently. This is the opposite of {@link #sequenceFx}.
10710 * @return {Roo.Element} The Element
10712 syncFx : function(){
10713 this.fxDefaults = Roo.apply(this.fxDefaults || {}, {
10722 * Ensures that all effects queued after sequenceFx is called on the element are
10723 * run in sequence. This is the opposite of {@link #syncFx}.
10724 * @return {Roo.Element} The Element
10726 sequenceFx : function(){
10727 this.fxDefaults = Roo.apply(this.fxDefaults || {}, {
10729 concurrent : false,
10736 nextFx : function(){
10737 var ef = this.fxQueue[0];
10744 * Returns true if the element has any effects actively running or queued, else returns false.
10745 * @return {Boolean} True if element has active effects, else false
10747 hasActiveFx : function(){
10748 return this.fxQueue && this.fxQueue[0];
10752 * Stops any running effects and clears the element's internal effects queue if it contains
10753 * any additional effects that haven't started yet.
10754 * @return {Roo.Element} The Element
10756 stopFx : function(){
10757 if(this.hasActiveFx()){
10758 var cur = this.fxQueue[0];
10759 if(cur && cur.anim && cur.anim.isAnimated()){
10760 this.fxQueue = [cur]; // clear out others
10761 cur.anim.stop(true);
10768 beforeFx : function(o){
10769 if(this.hasActiveFx() && !o.concurrent){
10780 * Returns true if the element is currently blocking so that no other effect can be queued
10781 * until this effect is finished, else returns false if blocking is not set. This is commonly
10782 * used to ensure that an effect initiated by a user action runs to completion prior to the
10783 * same effect being restarted (e.g., firing only one effect even if the user clicks several times).
10784 * @return {Boolean} True if blocking, else false
10786 hasFxBlock : function(){
10787 var q = this.fxQueue;
10788 return q && q[0] && q[0].block;
10792 queueFx : function(o, fn){
10796 if(!this.hasFxBlock()){
10797 Roo.applyIf(o, this.fxDefaults);
10799 var run = this.beforeFx(o);
10800 fn.block = o.block;
10801 this.fxQueue.push(fn);
10813 fxWrap : function(pos, o, vis){
10815 if(!o.wrap || !(wrap = Roo.get(o.wrap))){
10818 wrapXY = this.getXY();
10820 var div = document.createElement("div");
10821 div.style.visibility = vis;
10822 wrap = Roo.get(this.dom.parentNode.insertBefore(div, this.dom));
10823 wrap.setPositioning(pos);
10824 if(wrap.getStyle("position") == "static"){
10825 wrap.position("relative");
10827 this.clearPositioning('auto');
10829 wrap.dom.appendChild(this.dom);
10831 wrap.setXY(wrapXY);
10838 fxUnwrap : function(wrap, pos, o){
10839 this.clearPositioning();
10840 this.setPositioning(pos);
10842 wrap.dom.parentNode.insertBefore(this.dom, wrap.dom);
10848 getFxRestore : function(){
10849 var st = this.dom.style;
10850 return {pos: this.getPositioning(), width: st.width, height : st.height};
10854 afterFx : function(o){
10856 this.applyStyles(o.afterStyle);
10859 this.addClass(o.afterCls);
10861 if(o.remove === true){
10864 Roo.callback(o.callback, o.scope, [this]);
10866 this.fxQueue.shift();
10872 getFxEl : function(){ // support for composite element fx
10873 return Roo.get(this.dom);
10877 fxanim : function(args, opt, animType, defaultDur, defaultEase, cb){
10878 animType = animType || 'run';
10880 var anim = Roo.lib.Anim[animType](
10882 (opt.duration || defaultDur) || .35,
10883 (opt.easing || defaultEase) || 'easeOut',
10885 Roo.callback(cb, this);
10894 // backwords compat
10895 Roo.Fx.resize = Roo.Fx.scale;
10897 //When included, Roo.Fx is automatically applied to Element so that all basic
10898 //effects are available directly via the Element API
10899 Roo.apply(Roo.Element.prototype, Roo.Fx);/*
10901 * Ext JS Library 1.1.1
10902 * Copyright(c) 2006-2007, Ext JS, LLC.
10904 * Originally Released Under LGPL - original licence link has changed is not relivant.
10907 * <script type="text/javascript">
10912 * @class Roo.CompositeElement
10913 * Standard composite class. Creates a Roo.Element for every element in the collection.
10915 * <b>NOTE: Although they are not listed, this class supports all of the set/update methods of Roo.Element. All Roo.Element
10916 * actions will be performed on all the elements in this collection.</b>
10918 * All methods return <i>this</i> and can be chained.
10920 var els = Roo.select("#some-el div.some-class", true);
10921 // or select directly from an existing element
10922 var el = Roo.get('some-el');
10923 el.select('div.some-class', true);
10925 els.setWidth(100); // all elements become 100 width
10926 els.hide(true); // all elements fade out and hide
10928 els.setWidth(100).hide(true);
10931 Roo.CompositeElement = function(els){
10932 this.elements = [];
10933 this.addElements(els);
10935 Roo.CompositeElement.prototype = {
10937 addElements : function(els){
10938 if(!els) return this;
10939 if(typeof els == "string"){
10940 els = Roo.Element.selectorFunction(els);
10942 var yels = this.elements;
10943 var index = yels.length-1;
10944 for(var i = 0, len = els.length; i < len; i++) {
10945 yels[++index] = Roo.get(els[i]);
10951 * Clears this composite and adds the elements returned by the passed selector.
10952 * @param {String/Array} els A string CSS selector, an array of elements or an element
10953 * @return {CompositeElement} this
10955 fill : function(els){
10956 this.elements = [];
10962 * Filters this composite to only elements that match the passed selector.
10963 * @param {String} selector A string CSS selector
10964 * @return {CompositeElement} this
10966 filter : function(selector){
10968 this.each(function(el){
10969 if(el.is(selector)){
10970 els[els.length] = el.dom;
10977 invoke : function(fn, args){
10978 var els = this.elements;
10979 for(var i = 0, len = els.length; i < len; i++) {
10980 Roo.Element.prototype[fn].apply(els[i], args);
10985 * Adds elements to this composite.
10986 * @param {String/Array} els A string CSS selector, an array of elements or an element
10987 * @return {CompositeElement} this
10989 add : function(els){
10990 if(typeof els == "string"){
10991 this.addElements(Roo.Element.selectorFunction(els));
10992 }else if(els.length !== undefined){
10993 this.addElements(els);
10995 this.addElements([els]);
11000 * Calls the passed function passing (el, this, index) for each element in this composite.
11001 * @param {Function} fn The function to call
11002 * @param {Object} scope (optional) The <i>this</i> object (defaults to the element)
11003 * @return {CompositeElement} this
11005 each : function(fn, scope){
11006 var els = this.elements;
11007 for(var i = 0, len = els.length; i < len; i++){
11008 if(fn.call(scope || els[i], els[i], this, i) === false) {
11016 * Returns the Element object at the specified index
11017 * @param {Number} index
11018 * @return {Roo.Element}
11020 item : function(index){
11021 return this.elements[index] || null;
11025 * Returns the first Element
11026 * @return {Roo.Element}
11028 first : function(){
11029 return this.item(0);
11033 * Returns the last Element
11034 * @return {Roo.Element}
11037 return this.item(this.elements.length-1);
11041 * Returns the number of elements in this composite
11044 getCount : function(){
11045 return this.elements.length;
11049 * Returns true if this composite contains the passed element
11052 contains : function(el){
11053 return this.indexOf(el) !== -1;
11057 * Returns true if this composite contains the passed element
11060 indexOf : function(el){
11061 return this.elements.indexOf(Roo.get(el));
11066 * Removes the specified element(s).
11067 * @param {Mixed} el The id of an element, the Element itself, the index of the element in this composite
11068 * or an array of any of those.
11069 * @param {Boolean} removeDom (optional) True to also remove the element from the document
11070 * @return {CompositeElement} this
11072 removeElement : function(el, removeDom){
11073 if(el instanceof Array){
11074 for(var i = 0, len = el.length; i < len; i++){
11075 this.removeElement(el[i]);
11079 var index = typeof el == 'number' ? el : this.indexOf(el);
11082 var d = this.elements[index];
11086 d.parentNode.removeChild(d);
11089 this.elements.splice(index, 1);
11095 * Replaces the specified element with the passed element.
11096 * @param {String/HTMLElement/Element/Number} el The id of an element, the Element itself, the index of the element in this composite
11098 * @param {String/HTMLElement/Element} replacement The id of an element or the Element itself.
11099 * @param {Boolean} domReplace (Optional) True to remove and replace the element in the document too.
11100 * @return {CompositeElement} this
11102 replaceElement : function(el, replacement, domReplace){
11103 var index = typeof el == 'number' ? el : this.indexOf(el);
11106 this.elements[index].replaceWith(replacement);
11108 this.elements.splice(index, 1, Roo.get(replacement))
11115 * Removes all elements.
11117 clear : function(){
11118 this.elements = [];
11122 Roo.CompositeElement.createCall = function(proto, fnName){
11123 if(!proto[fnName]){
11124 proto[fnName] = function(){
11125 return this.invoke(fnName, arguments);
11129 for(var fnName in Roo.Element.prototype){
11130 if(typeof Roo.Element.prototype[fnName] == "function"){
11131 Roo.CompositeElement.createCall(Roo.CompositeElement.prototype, fnName);
11137 * Ext JS Library 1.1.1
11138 * Copyright(c) 2006-2007, Ext JS, LLC.
11140 * Originally Released Under LGPL - original licence link has changed is not relivant.
11143 * <script type="text/javascript">
11147 * @class Roo.CompositeElementLite
11148 * @extends Roo.CompositeElement
11149 * Flyweight composite class. Reuses the same Roo.Element for element operations.
11151 var els = Roo.select("#some-el div.some-class");
11152 // or select directly from an existing element
11153 var el = Roo.get('some-el');
11154 el.select('div.some-class');
11156 els.setWidth(100); // all elements become 100 width
11157 els.hide(true); // all elements fade out and hide
11159 els.setWidth(100).hide(true);
11160 </code></pre><br><br>
11161 * <b>NOTE: Although they are not listed, this class supports all of the set/update methods of Roo.Element. All Roo.Element
11162 * actions will be performed on all the elements in this collection.</b>
11164 Roo.CompositeElementLite = function(els){
11165 Roo.CompositeElementLite.superclass.constructor.call(this, els);
11166 this.el = new Roo.Element.Flyweight();
11168 Roo.extend(Roo.CompositeElementLite, Roo.CompositeElement, {
11169 addElements : function(els){
11171 if(els instanceof Array){
11172 this.elements = this.elements.concat(els);
11174 var yels = this.elements;
11175 var index = yels.length-1;
11176 for(var i = 0, len = els.length; i < len; i++) {
11177 yels[++index] = els[i];
11183 invoke : function(fn, args){
11184 var els = this.elements;
11186 for(var i = 0, len = els.length; i < len; i++) {
11188 Roo.Element.prototype[fn].apply(el, args);
11193 * Returns a flyweight Element of the dom element object at the specified index
11194 * @param {Number} index
11195 * @return {Roo.Element}
11197 item : function(index){
11198 if(!this.elements[index]){
11201 this.el.dom = this.elements[index];
11205 // fixes scope with flyweight
11206 addListener : function(eventName, handler, scope, opt){
11207 var els = this.elements;
11208 for(var i = 0, len = els.length; i < len; i++) {
11209 Roo.EventManager.on(els[i], eventName, handler, scope || els[i], opt);
11215 * Calls the passed function passing (el, this, index) for each element in this composite. <b>The element
11216 * passed is the flyweight (shared) Roo.Element instance, so if you require a
11217 * a reference to the dom node, use el.dom.</b>
11218 * @param {Function} fn The function to call
11219 * @param {Object} scope (optional) The <i>this</i> object (defaults to the element)
11220 * @return {CompositeElement} this
11222 each : function(fn, scope){
11223 var els = this.elements;
11225 for(var i = 0, len = els.length; i < len; i++){
11227 if(fn.call(scope || el, el, this, i) === false){
11234 indexOf : function(el){
11235 return this.elements.indexOf(Roo.getDom(el));
11238 replaceElement : function(el, replacement, domReplace){
11239 var index = typeof el == 'number' ? el : this.indexOf(el);
11241 replacement = Roo.getDom(replacement);
11243 var d = this.elements[index];
11244 d.parentNode.insertBefore(replacement, d);
11245 d.parentNode.removeChild(d);
11247 this.elements.splice(index, 1, replacement);
11252 Roo.CompositeElementLite.prototype.on = Roo.CompositeElementLite.prototype.addListener;
11256 * Ext JS Library 1.1.1
11257 * Copyright(c) 2006-2007, Ext JS, LLC.
11259 * Originally Released Under LGPL - original licence link has changed is not relivant.
11262 * <script type="text/javascript">
11268 * @class Roo.data.Connection
11269 * @extends Roo.util.Observable
11270 * The class encapsulates a connection to the page's originating domain, allowing requests to be made
11271 * either to a configured URL, or to a URL specified at request time.<br><br>
11273 * Requests made by this class are asynchronous, and will return immediately. No data from
11274 * the server will be available to the statement immediately following the {@link #request} call.
11275 * To process returned data, use a callback in the request options object, or an event listener.</p><br>
11277 * Note: If you are doing a file upload, you will not get a normal response object sent back to
11278 * your callback or event handler. Since the upload is handled via in IFRAME, there is no XMLHttpRequest.
11279 * The response object is created using the innerHTML of the IFRAME's document as the responseText
11280 * property and, if present, the IFRAME's XML document as the responseXML property.</p><br>
11281 * This means that a valid XML or HTML document must be returned. If JSON data is required, it is suggested
11282 * that it be placed either inside a <textarea> in an HTML document and retrieved from the responseText
11283 * using a regex, or inside a CDATA section in an XML document and retrieved from the responseXML using
11284 * standard DOM methods.
11286 * @param {Object} config a configuration object.
11288 Roo.data.Connection = function(config){
11289 Roo.apply(this, config);
11292 * @event beforerequest
11293 * Fires before a network request is made to retrieve a data object.
11294 * @param {Connection} conn This Connection object.
11295 * @param {Object} options The options config object passed to the {@link #request} method.
11297 "beforerequest" : true,
11299 * @event requestcomplete
11300 * Fires if the request was successfully completed.
11301 * @param {Connection} conn This Connection object.
11302 * @param {Object} response The XHR object containing the response data.
11303 * See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
11304 * @param {Object} options The options config object passed to the {@link #request} method.
11306 "requestcomplete" : true,
11308 * @event requestexception
11309 * Fires if an error HTTP status was returned from the server.
11310 * See {@link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html} for details of HTTP status codes.
11311 * @param {Connection} conn This Connection object.
11312 * @param {Object} response The XHR object containing the response data.
11313 * See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
11314 * @param {Object} options The options config object passed to the {@link #request} method.
11316 "requestexception" : true
11318 Roo.data.Connection.superclass.constructor.call(this);
11321 Roo.extend(Roo.data.Connection, Roo.util.Observable, {
11323 * @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
11326 * @cfg {Object} extraParams (Optional) An object containing properties which are used as
11327 * extra parameters to each request made by this object. (defaults to undefined)
11330 * @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
11331 * to each request made by this object. (defaults to undefined)
11334 * @cfg {String} method (Optional) The default HTTP method to be used for requests. (defaults to undefined; if not set but parms are present will use POST, otherwise GET)
11337 * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
11341 * @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
11347 * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
11350 disableCaching: true,
11353 * Sends an HTTP request to a remote server.
11354 * @param {Object} options An object which may contain the following properties:<ul>
11355 * <li><b>url</b> {String} (Optional) The URL to which to send the request. Defaults to configured URL</li>
11356 * <li><b>params</b> {Object/String/Function} (Optional) An object containing properties which are used as parameters to the
11357 * request, a url encoded string or a function to call to get either.</li>
11358 * <li><b>method</b> {String} (Optional) The HTTP method to use for the request. Defaults to the configured method, or
11359 * if no method was configured, "GET" if no parameters are being sent, and "POST" if parameters are being sent.</li>
11360 * <li><b>callback</b> {Function} (Optional) The function to be called upon receipt of the HTTP response.
11361 * The callback is called regardless of success or failure and is passed the following parameters:<ul>
11362 * <li>options {Object} The parameter to the request call.</li>
11363 * <li>success {Boolean} True if the request succeeded.</li>
11364 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
11366 * <li><b>success</b> {Function} (Optional) The function to be called upon success of the request.
11367 * The callback is passed the following parameters:<ul>
11368 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
11369 * <li>options {Object} The parameter to the request call.</li>
11371 * <li><b>failure</b> {Function} (Optional) The function to be called upon failure of the request.
11372 * The callback is passed the following parameters:<ul>
11373 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
11374 * <li>options {Object} The parameter to the request call.</li>
11376 * <li><b>scope</b> {Object} (Optional) The scope in which to execute the callbacks: The "this" object
11377 * for the callback function. Defaults to the browser window.</li>
11378 * <li><b>form</b> {Object/String} (Optional) A form object or id to pull parameters from.</li>
11379 * <li><b>isUpload</b> {Boolean} (Optional) True if the form object is a file upload (will usually be automatically detected).</li>
11380 * <li><b>headers</b> {Object} (Optional) Request headers to set for the request.</li>
11381 * <li><b>xmlData</b> {Object} (Optional) XML document to use for the post. Note: This will be used instead of
11382 * params for the post data. Any params will be appended to the URL.</li>
11383 * <li><b>disableCaching</b> {Boolean} (Optional) True to add a unique cache-buster param to GET requests.</li>
11385 * @return {Number} transactionId
11387 request : function(o){
11388 if(this.fireEvent("beforerequest", this, o) !== false){
11391 if(typeof p == "function"){
11392 p = p.call(o.scope||window, o);
11394 if(typeof p == "object"){
11395 p = Roo.urlEncode(o.params);
11397 if(this.extraParams){
11398 var extras = Roo.urlEncode(this.extraParams);
11399 p = p ? (p + '&' + extras) : extras;
11402 var url = o.url || this.url;
11403 if(typeof url == 'function'){
11404 url = url.call(o.scope||window, o);
11408 var form = Roo.getDom(o.form);
11409 url = url || form.action;
11411 var enctype = form.getAttribute("enctype");
11412 if(o.isUpload || (enctype && enctype.toLowerCase() == 'multipart/form-data')){
11413 return this.doFormUpload(o, p, url);
11415 var f = Roo.lib.Ajax.serializeForm(form);
11416 p = p ? (p + '&' + f) : f;
11419 var hs = o.headers;
11420 if(this.defaultHeaders){
11421 hs = Roo.apply(hs || {}, this.defaultHeaders);
11428 success: this.handleResponse,
11429 failure: this.handleFailure,
11431 argument: {options: o},
11432 timeout : o.timeout || this.timeout
11435 var method = o.method||this.method||(p ? "POST" : "GET");
11437 if(method == 'GET' && (this.disableCaching && o.disableCaching !== false) || o.disableCaching === true){
11438 url += (url.indexOf('?') != -1 ? '&' : '?') + '_dc=' + (new Date().getTime());
11441 if(typeof o.autoAbort == 'boolean'){ // options gets top priority
11445 }else if(this.autoAbort !== false){
11449 if((method == 'GET' && p) || o.xmlData){
11450 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
11453 this.transId = Roo.lib.Ajax.request(method, url, cb, p, o);
11454 return this.transId;
11456 Roo.callback(o.callback, o.scope, [o, null, null]);
11462 * Determine whether this object has a request outstanding.
11463 * @param {Number} transactionId (Optional) defaults to the last transaction
11464 * @return {Boolean} True if there is an outstanding request.
11466 isLoading : function(transId){
11468 return Roo.lib.Ajax.isCallInProgress(transId);
11470 return this.transId ? true : false;
11475 * Aborts any outstanding request.
11476 * @param {Number} transactionId (Optional) defaults to the last transaction
11478 abort : function(transId){
11479 if(transId || this.isLoading()){
11480 Roo.lib.Ajax.abort(transId || this.transId);
11485 handleResponse : function(response){
11486 this.transId = false;
11487 var options = response.argument.options;
11488 response.argument = options ? options.argument : null;
11489 this.fireEvent("requestcomplete", this, response, options);
11490 Roo.callback(options.success, options.scope, [response, options]);
11491 Roo.callback(options.callback, options.scope, [options, true, response]);
11495 handleFailure : function(response, e){
11496 this.transId = false;
11497 var options = response.argument.options;
11498 response.argument = options ? options.argument : null;
11499 this.fireEvent("requestexception", this, response, options, e);
11500 Roo.callback(options.failure, options.scope, [response, options]);
11501 Roo.callback(options.callback, options.scope, [options, false, response]);
11505 doFormUpload : function(o, ps, url){
11507 var frame = document.createElement('iframe');
11510 frame.className = 'x-hidden';
11512 frame.src = Roo.SSL_SECURE_URL;
11514 document.body.appendChild(frame);
11517 document.frames[id].name = id;
11520 var form = Roo.getDom(o.form);
11522 form.method = 'POST';
11523 form.enctype = form.encoding = 'multipart/form-data';
11529 if(ps){ // add dynamic params
11531 ps = Roo.urlDecode(ps, false);
11533 if(ps.hasOwnProperty(k)){
11534 hd = document.createElement('input');
11535 hd.type = 'hidden';
11538 form.appendChild(hd);
11545 var r = { // bogus response object
11550 r.argument = o ? o.argument : null;
11555 doc = frame.contentWindow.document;
11557 doc = (frame.contentDocument || window.frames[id].document);
11559 if(doc && doc.body){
11560 r.responseText = doc.body.innerHTML;
11562 if(doc && doc.XMLDocument){
11563 r.responseXML = doc.XMLDocument;
11565 r.responseXML = doc;
11572 Roo.EventManager.removeListener(frame, 'load', cb, this);
11574 this.fireEvent("requestcomplete", this, r, o);
11575 Roo.callback(o.success, o.scope, [r, o]);
11576 Roo.callback(o.callback, o.scope, [o, true, r]);
11578 setTimeout(function(){document.body.removeChild(frame);}, 100);
11581 Roo.EventManager.on(frame, 'load', cb, this);
11584 if(hiddens){ // remove dynamic params
11585 for(var i = 0, len = hiddens.length; i < len; i++){
11586 form.removeChild(hiddens[i]);
11593 * Ext JS Library 1.1.1
11594 * Copyright(c) 2006-2007, Ext JS, LLC.
11596 * Originally Released Under LGPL - original licence link has changed is not relivant.
11599 * <script type="text/javascript">
11603 * Global Ajax request class.
11606 * @extends Roo.data.Connection
11609 * @cfg {String} url The default URL to be used for requests to the server. (defaults to undefined)
11610 * @cfg {Object} extraParams An object containing properties which are used as extra parameters to each request made by this object. (defaults to undefined)
11611 * @cfg {Object} defaultHeaders An object containing request headers which are added to each request made by this object. (defaults to undefined)
11612 * @cfg {String} method (Optional) The default HTTP method to be used for requests. (defaults to undefined; if not set but parms are present will use POST, otherwise GET)
11613 * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
11614 * @cfg {Boolean} autoAbort (Optional) Whether a new request should abort any pending requests. (defaults to false)
11615 * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
11617 Roo.Ajax = new Roo.data.Connection({
11626 * Serialize the passed form into a url encoded string
11628 * @param {String/HTMLElement} form
11631 serializeForm : function(form){
11632 return Roo.lib.Ajax.serializeForm(form);
11636 * Ext JS Library 1.1.1
11637 * Copyright(c) 2006-2007, Ext JS, LLC.
11639 * Originally Released Under LGPL - original licence link has changed is not relivant.
11642 * <script type="text/javascript">
11647 * @class Roo.UpdateManager
11648 * @extends Roo.util.Observable
11649 * Provides AJAX-style update for Element object.<br><br>
11652 * // Get it from a Roo.Element object
11653 * var el = Roo.get("foo");
11654 * var mgr = el.getUpdateManager();
11655 * mgr.update("http://myserver.com/index.php", "param1=1&param2=2");
11657 * mgr.formUpdate("myFormId", "http://myserver.com/index.php");
11659 * // or directly (returns the same UpdateManager instance)
11660 * var mgr = new Roo.UpdateManager("myElementId");
11661 * mgr.startAutoRefresh(60, "http://myserver.com/index.php");
11662 * mgr.on("update", myFcnNeedsToKnow);
11664 // short handed call directly from the element object
11665 Roo.get("foo").load({
11669 text: "Loading Foo..."
11673 * Create new UpdateManager directly.
11674 * @param {String/HTMLElement/Roo.Element} el The element to update
11675 * @param {Boolean} forceNew (optional) By default the constructor checks to see if the passed element already has an UpdateManager and if it does it returns the same instance. This will skip that check (useful for extending this class).
11677 Roo.UpdateManager = function(el, forceNew){
11679 if(!forceNew && el.updateManager){
11680 return el.updateManager;
11683 * The Element object
11684 * @type Roo.Element
11688 * Cached url to use for refreshes. Overwritten every time update() is called unless "discardUrl" param is set to true.
11691 this.defaultUrl = null;
11695 * @event beforeupdate
11696 * Fired before an update is made, return false from your handler and the update is cancelled.
11697 * @param {Roo.Element} el
11698 * @param {String/Object/Function} url
11699 * @param {String/Object} params
11701 "beforeupdate": true,
11704 * Fired after successful update is made.
11705 * @param {Roo.Element} el
11706 * @param {Object} oResponseObject The response Object
11711 * Fired on update failure.
11712 * @param {Roo.Element} el
11713 * @param {Object} oResponseObject The response Object
11717 var d = Roo.UpdateManager.defaults;
11719 * Blank page URL to use with SSL file uploads (Defaults to Roo.UpdateManager.defaults.sslBlankUrl or "about:blank").
11722 this.sslBlankUrl = d.sslBlankUrl;
11724 * Whether to append unique parameter on get request to disable caching (Defaults to Roo.UpdateManager.defaults.disableCaching or false).
11727 this.disableCaching = d.disableCaching;
11729 * Text for loading indicator (Defaults to Roo.UpdateManager.defaults.indicatorText or '<div class="loading-indicator">Loading...</div>').
11732 this.indicatorText = d.indicatorText;
11734 * Whether to show indicatorText when loading (Defaults to Roo.UpdateManager.defaults.showLoadIndicator or true).
11737 this.showLoadIndicator = d.showLoadIndicator;
11739 * Timeout for requests or form posts in seconds (Defaults to Roo.UpdateManager.defaults.timeout or 30 seconds).
11742 this.timeout = d.timeout;
11745 * True to process scripts in the output (Defaults to Roo.UpdateManager.defaults.loadScripts (false)).
11748 this.loadScripts = d.loadScripts;
11751 * Transaction object of current executing transaction
11753 this.transaction = null;
11758 this.autoRefreshProcId = null;
11760 * Delegate for refresh() prebound to "this", use myUpdater.refreshDelegate.createCallback(arg1, arg2) to bind arguments
11763 this.refreshDelegate = this.refresh.createDelegate(this);
11765 * Delegate for update() prebound to "this", use myUpdater.updateDelegate.createCallback(arg1, arg2) to bind arguments
11768 this.updateDelegate = this.update.createDelegate(this);
11770 * Delegate for formUpdate() prebound to "this", use myUpdater.formUpdateDelegate.createCallback(arg1, arg2) to bind arguments
11773 this.formUpdateDelegate = this.formUpdate.createDelegate(this);
11777 this.successDelegate = this.processSuccess.createDelegate(this);
11781 this.failureDelegate = this.processFailure.createDelegate(this);
11783 if(!this.renderer){
11785 * The renderer for this UpdateManager. Defaults to {@link Roo.UpdateManager.BasicRenderer}.
11787 this.renderer = new Roo.UpdateManager.BasicRenderer();
11790 Roo.UpdateManager.superclass.constructor.call(this);
11793 Roo.extend(Roo.UpdateManager, Roo.util.Observable, {
11795 * Get the Element this UpdateManager is bound to
11796 * @return {Roo.Element} The element
11798 getEl : function(){
11802 * Performs an async request, updating this element with the response. If params are specified it uses POST, otherwise it uses GET.
11803 * @param {Object/String/Function} url The url for this request or a function to call to get the url or a config object containing any of the following options:
11806 url: "your-url.php",<br/>
11807 params: {param1: "foo", param2: "bar"}, // or a URL encoded string<br/>
11808 callback: yourFunction,<br/>
11809 scope: yourObject, //(optional scope) <br/>
11810 discardUrl: false, <br/>
11811 nocache: false,<br/>
11812 text: "Loading...",<br/>
11814 scripts: false<br/>
11817 * The only required property is url. The optional properties nocache, text and scripts
11818 * are shorthand for disableCaching, indicatorText and loadScripts and are used to set their associated property on this UpdateManager instance.
11819 * @param {String/Object} params (optional) The parameters to pass as either a url encoded string "param1=1&param2=2" or an object {param1: 1, param2: 2}
11820 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess, oResponse)
11821 * @param {Boolean} discardUrl (optional) By default when you execute an update the defaultUrl is changed to the last used url. If true, it will not store the url.
11823 update : function(url, params, callback, discardUrl){
11824 if(this.fireEvent("beforeupdate", this.el, url, params) !== false){
11825 var method = this.method,
11827 if(typeof url == "object"){ // must be config object
11830 params = params || cfg.params;
11831 callback = callback || cfg.callback;
11832 discardUrl = discardUrl || cfg.discardUrl;
11833 if(callback && cfg.scope){
11834 callback = callback.createDelegate(cfg.scope);
11836 if(typeof cfg.method != "undefined"){method = cfg.method;};
11837 if(typeof cfg.nocache != "undefined"){this.disableCaching = cfg.nocache;};
11838 if(typeof cfg.text != "undefined"){this.indicatorText = '<div class="loading-indicator">'+cfg.text+"</div>";};
11839 if(typeof cfg.scripts != "undefined"){this.loadScripts = cfg.scripts;};
11840 if(typeof cfg.timeout != "undefined"){this.timeout = cfg.timeout;};
11842 this.showLoading();
11844 this.defaultUrl = url;
11846 if(typeof url == "function"){
11847 url = url.call(this);
11850 method = method || (params ? "POST" : "GET");
11851 if(method == "GET"){
11852 url = this.prepareUrl(url);
11855 var o = Roo.apply(cfg ||{}, {
11858 success: this.successDelegate,
11859 failure: this.failureDelegate,
11860 callback: undefined,
11861 timeout: (this.timeout*1000),
11862 argument: {"url": url, "form": null, "callback": callback, "params": params}
11864 Roo.log("updated manager called with timeout of " + o.timeout);
11865 this.transaction = Roo.Ajax.request(o);
11870 * Performs an async form post, updating this element with the response. If the form has the attribute enctype="multipart/form-data", it assumes it's a file upload.
11871 * Uses this.sslBlankUrl for SSL file uploads to prevent IE security warning.
11872 * @param {String/HTMLElement} form The form Id or form element
11873 * @param {String} url (optional) The url to pass the form to. If omitted the action attribute on the form will be used.
11874 * @param {Boolean} reset (optional) Whether to try to reset the form after the update
11875 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess, oResponse)
11877 formUpdate : function(form, url, reset, callback){
11878 if(this.fireEvent("beforeupdate", this.el, form, url) !== false){
11879 if(typeof url == "function"){
11880 url = url.call(this);
11882 form = Roo.getDom(form);
11883 this.transaction = Roo.Ajax.request({
11886 success: this.successDelegate,
11887 failure: this.failureDelegate,
11888 timeout: (this.timeout*1000),
11889 argument: {"url": url, "form": form, "callback": callback, "reset": reset}
11891 this.showLoading.defer(1, this);
11896 * Refresh the element with the last used url or defaultUrl. If there is no url, it returns immediately
11897 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
11899 refresh : function(callback){
11900 if(this.defaultUrl == null){
11903 this.update(this.defaultUrl, null, callback, true);
11907 * Set this element to auto refresh.
11908 * @param {Number} interval How often to update (in seconds).
11909 * @param {String/Function} url (optional) The url for this request or a function to call to get the url (Defaults to the last used url)
11910 * @param {String/Object} params (optional) The parameters to pass as either a url encoded string "¶m1=1¶m2=2" or as an object {param1: 1, param2: 2}
11911 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
11912 * @param {Boolean} refreshNow (optional) Whether to execute the refresh now, or wait the interval
11914 startAutoRefresh : function(interval, url, params, callback, refreshNow){
11916 this.update(url || this.defaultUrl, params, callback, true);
11918 if(this.autoRefreshProcId){
11919 clearInterval(this.autoRefreshProcId);
11921 this.autoRefreshProcId = setInterval(this.update.createDelegate(this, [url || this.defaultUrl, params, callback, true]), interval*1000);
11925 * Stop auto refresh on this element.
11927 stopAutoRefresh : function(){
11928 if(this.autoRefreshProcId){
11929 clearInterval(this.autoRefreshProcId);
11930 delete this.autoRefreshProcId;
11934 isAutoRefreshing : function(){
11935 return this.autoRefreshProcId ? true : false;
11938 * Called to update the element to "Loading" state. Override to perform custom action.
11940 showLoading : function(){
11941 if(this.showLoadIndicator){
11942 this.el.update(this.indicatorText);
11947 * Adds unique parameter to query string if disableCaching = true
11950 prepareUrl : function(url){
11951 if(this.disableCaching){
11952 var append = "_dc=" + (new Date().getTime());
11953 if(url.indexOf("?") !== -1){
11954 url += "&" + append;
11956 url += "?" + append;
11965 processSuccess : function(response){
11966 this.transaction = null;
11967 if(response.argument.form && response.argument.reset){
11968 try{ // put in try/catch since some older FF releases had problems with this
11969 response.argument.form.reset();
11972 if(this.loadScripts){
11973 this.renderer.render(this.el, response, this,
11974 this.updateComplete.createDelegate(this, [response]));
11976 this.renderer.render(this.el, response, this);
11977 this.updateComplete(response);
11981 updateComplete : function(response){
11982 this.fireEvent("update", this.el, response);
11983 if(typeof response.argument.callback == "function"){
11984 response.argument.callback(this.el, true, response);
11991 processFailure : function(response){
11992 this.transaction = null;
11993 this.fireEvent("failure", this.el, response);
11994 if(typeof response.argument.callback == "function"){
11995 response.argument.callback(this.el, false, response);
12000 * Set the content renderer for this UpdateManager. See {@link Roo.UpdateManager.BasicRenderer#render} for more details.
12001 * @param {Object} renderer The object implementing the render() method
12003 setRenderer : function(renderer){
12004 this.renderer = renderer;
12007 getRenderer : function(){
12008 return this.renderer;
12012 * Set the defaultUrl used for updates
12013 * @param {String/Function} defaultUrl The url or a function to call to get the url
12015 setDefaultUrl : function(defaultUrl){
12016 this.defaultUrl = defaultUrl;
12020 * Aborts the executing transaction
12022 abort : function(){
12023 if(this.transaction){
12024 Roo.Ajax.abort(this.transaction);
12029 * Returns true if an update is in progress
12030 * @return {Boolean}
12032 isUpdating : function(){
12033 if(this.transaction){
12034 return Roo.Ajax.isLoading(this.transaction);
12041 * @class Roo.UpdateManager.defaults
12042 * @static (not really - but it helps the doc tool)
12043 * The defaults collection enables customizing the default properties of UpdateManager
12045 Roo.UpdateManager.defaults = {
12047 * Timeout for requests or form posts in seconds (Defaults 30 seconds).
12053 * True to process scripts by default (Defaults to false).
12056 loadScripts : false,
12059 * Blank page URL to use with SSL file uploads (Defaults to "javascript:false").
12062 sslBlankUrl : (Roo.SSL_SECURE_URL || "javascript:false"),
12064 * Whether to append unique parameter on get request to disable caching (Defaults to false).
12067 disableCaching : false,
12069 * Whether to show indicatorText when loading (Defaults to true).
12072 showLoadIndicator : true,
12074 * Text for loading indicator (Defaults to '<div class="loading-indicator">Loading...</div>').
12077 indicatorText : '<div class="loading-indicator">Loading...</div>'
12081 * Static convenience method. This method is deprecated in favor of el.load({url:'foo.php', ...}).
12083 * <pre><code>Roo.UpdateManager.updateElement("my-div", "stuff.php");</code></pre>
12084 * @param {String/HTMLElement/Roo.Element} el The element to update
12085 * @param {String} url The url
12086 * @param {String/Object} params (optional) Url encoded param string or an object of name/value pairs
12087 * @param {Object} options (optional) A config object with any of the UpdateManager properties you want to set - for example: {disableCaching:true, indicatorText: "Loading data..."}
12090 * @member Roo.UpdateManager
12092 Roo.UpdateManager.updateElement = function(el, url, params, options){
12093 var um = Roo.get(el, true).getUpdateManager();
12094 Roo.apply(um, options);
12095 um.update(url, params, options ? options.callback : null);
12097 // alias for backwards compat
12098 Roo.UpdateManager.update = Roo.UpdateManager.updateElement;
12100 * @class Roo.UpdateManager.BasicRenderer
12101 * Default Content renderer. Updates the elements innerHTML with the responseText.
12103 Roo.UpdateManager.BasicRenderer = function(){};
12105 Roo.UpdateManager.BasicRenderer.prototype = {
12107 * This is called when the transaction is completed and it's time to update the element - The BasicRenderer
12108 * updates the elements innerHTML with the responseText - To perform a custom render (i.e. XML or JSON processing),
12109 * create an object with a "render(el, response)" method and pass it to setRenderer on the UpdateManager.
12110 * @param {Roo.Element} el The element being rendered
12111 * @param {Object} response The YUI Connect response object
12112 * @param {UpdateManager} updateManager The calling update manager
12113 * @param {Function} callback A callback that will need to be called if loadScripts is true on the UpdateManager
12115 render : function(el, response, updateManager, callback){
12116 el.update(response.responseText, updateManager.loadScripts, callback);
12122 * (c)) Alan Knowles
12128 * @class Roo.DomTemplate
12129 * @extends Roo.Template
12130 * An effort at a dom based template engine..
12132 * Similar to XTemplate, except it uses dom parsing to create the template..
12134 * Supported features:
12139 {a_variable} - output encoded.
12140 {a_variable.format:("Y-m-d")} - call a method on the variable
12141 {a_variable:raw} - unencoded output
12142 {a_variable:toFixed(1,2)} - Roo.util.Format."toFixed"
12143 {a_variable:this.method_on_template(...)} - call a method on the template object.
12148 <div roo-for="a_variable or condition.."></div>
12149 <div roo-if="a_variable or condition"></div>
12150 <div roo-exec="some javascript"></div>
12151 <div roo-name="named_template"></div>
12156 Roo.DomTemplate = function()
12158 Roo.DomTemplate.superclass.constructor.apply(this, arguments);
12165 Roo.extend(Roo.DomTemplate, Roo.Template, {
12167 * id counter for sub templates.
12171 * flag to indicate if dom parser is inside a pre,
12172 * it will strip whitespace if not.
12177 * The various sub templates
12185 * basic tag replacing syntax
12188 * // you can fake an object call by doing this
12192 re : /(\{|\%7B)([\w-\.]+)(?:\:([\w\.]*)(?:\(([^)]*?)?\))?)?(\}|\%7D)/g,
12193 //re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
12195 iterChild : function (node, method) {
12197 var oldPre = this.inPre;
12198 if (node.tagName == 'PRE') {
12201 for( var i = 0; i < node.childNodes.length; i++) {
12202 method.call(this, node.childNodes[i]);
12204 this.inPre = oldPre;
12210 * compile the template
12212 * This is not recursive, so I'm not sure how nested templates are really going to be handled..
12215 compile: function()
12219 // covert the html into DOM...
12223 doc = document.implementation.createHTMLDocument("");
12224 doc.documentElement.innerHTML = this.html ;
12225 div = doc.documentElement;
12227 // old IE... - nasty -- it causes all sorts of issues.. with
12228 // images getting pulled from server..
12229 div = document.createElement('div');
12230 div.innerHTML = this.html;
12232 //doc.documentElement.innerHTML = htmlBody
12238 this.iterChild(div, function(n) {_t.compileNode(n, true); });
12240 var tpls = this.tpls;
12242 // create a top level template from the snippet..
12244 //Roo.log(div.innerHTML);
12251 body : div.innerHTML,
12264 Roo.each(tpls, function(tp){
12265 this.compileTpl(tp);
12266 this.tpls[tp.id] = tp;
12269 this.master = tpls[0];
12275 compileNode : function(node, istop) {
12280 // skip anything not a tag..
12281 if (node.nodeType != 1) {
12282 if (node.nodeType == 3 && !this.inPre) {
12283 // reduce white space..
12284 node.nodeValue = node.nodeValue.replace(/\s+/g, ' ');
12307 case (node.hasAttribute('roo-for')): tpl.attr = 'for'; break;
12308 case (node.hasAttribute('roo-if')): tpl.attr = 'if'; break;
12309 case (node.hasAttribute('roo-name')): tpl.attr = 'name'; break;
12310 case (node.hasAttribute('roo-exec')): tpl.attr = 'exec'; break;
12316 // just itterate children..
12317 this.iterChild(node,this.compileNode);
12320 tpl.uid = this.id++;
12321 tpl.value = node.getAttribute('roo-' + tpl.attr);
12322 node.removeAttribute('roo-'+ tpl.attr);
12323 if (tpl.attr != 'name') {
12324 var placeholder = document.createTextNode('{domtpl' + tpl.uid + '}');
12325 node.parentNode.replaceChild(placeholder, node);
12328 var placeholder = document.createElement('span');
12329 placeholder.className = 'roo-tpl-' + tpl.value;
12330 node.parentNode.replaceChild(placeholder, node);
12333 // parent now sees '{domtplXXXX}
12334 this.iterChild(node,this.compileNode);
12336 // we should now have node body...
12337 var div = document.createElement('div');
12338 div.appendChild(node);
12340 // this has the unfortunate side effect of converting tagged attributes
12341 // eg. href="{...}" into %7C...%7D
12342 // this has been fixed by searching for those combo's although it's a bit hacky..
12345 tpl.body = div.innerHTML;
12352 switch (tpl.value) {
12353 case '.': tpl.forCall = new Function('values', 'parent', 'with(values){ return values; }'); break;
12354 case '..': tpl.forCall= new Function('values', 'parent', 'with(values){ return parent; }'); break;
12355 default: tpl.forCall= new Function('values', 'parent', 'with(values){ return '+tpl.value+'; }');
12360 tpl.execCall = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
12364 tpl.ifCall = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
12368 tpl.id = tpl.value; // replace non characters???
12374 this.tpls.push(tpl);
12384 * Compile a segment of the template into a 'sub-template'
12390 compileTpl : function(tpl)
12392 var fm = Roo.util.Format;
12393 var useF = this.disableFormats !== true;
12395 var sep = Roo.isGecko ? "+\n" : ",\n";
12397 var undef = function(str) {
12398 Roo.debug && Roo.log("Property not found :" + str);
12402 //Roo.log(tpl.body);
12406 var fn = function(m, lbrace, name, format, args)
12409 //Roo.log(arguments);
12410 args = args ? args.replace(/\\'/g,"'") : args;
12411 //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
12412 if (typeof(format) == 'undefined') {
12413 format = 'htmlEncode';
12415 if (format == 'raw' ) {
12419 if(name.substr(0, 6) == 'domtpl'){
12420 return "'"+ sep +'this.applySubTemplate('+name.substr(6)+', values, parent)'+sep+"'";
12423 // build an array of options to determine if value is undefined..
12425 // basically get 'xxxx.yyyy' then do
12426 // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
12427 // (function () { Roo.log("Property not found"); return ''; })() :
12432 Roo.each(name.split('.'), function(st) {
12433 lookfor += (lookfor.length ? '.': '') + st;
12434 udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
12437 var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
12440 if(format && useF){
12442 args = args ? ',' + args : "";
12444 if(format.substr(0, 5) != "this."){
12445 format = "fm." + format + '(';
12447 format = 'this.call("'+ format.substr(5) + '", ';
12451 return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
12454 if (args && args.length) {
12455 // called with xxyx.yuu:(test,test)
12457 return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
12459 // raw.. - :raw modifier..
12460 return "'"+ sep + udef_st + name + ")"+sep+"'";
12464 // branched to use + in gecko and [].join() in others
12466 body = "tpl.compiled = function(values, parent){ with(values) { return '" +
12467 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
12470 body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
12471 body.push(tpl.body.replace(/(\r\n|\n)/g,
12472 '\\n').replace(/'/g, "\\'").replace(this.re, fn));
12473 body.push("'].join('');};};");
12474 body = body.join('');
12477 Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
12479 /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
12486 * same as applyTemplate, except it's done to one of the subTemplates
12487 * when using named templates, you can do:
12489 * var str = pl.applySubTemplate('your-name', values);
12492 * @param {Number} id of the template
12493 * @param {Object} values to apply to template
12494 * @param {Object} parent (normaly the instance of this object)
12496 applySubTemplate : function(id, values, parent)
12500 var t = this.tpls[id];
12504 if(t.ifCall && !t.ifCall.call(this, values, parent)){
12505 Roo.debug && Roo.log('if call on ' + t.value + ' return false');
12509 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-if="' + t.value + '" - ' + e.toString());
12516 if(t.execCall && t.execCall.call(this, values, parent)){
12520 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
12526 var vs = t.forCall ? t.forCall.call(this, values, parent) : values;
12527 parent = t.target ? values : parent;
12528 if(t.forCall && vs instanceof Array){
12530 for(var i = 0, len = vs.length; i < len; i++){
12532 buf[buf.length] = t.compiled.call(this, vs[i], parent);
12534 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
12536 //Roo.log(t.compiled);
12540 return buf.join('');
12543 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
12548 return t.compiled.call(this, vs, parent);
12550 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
12552 //Roo.log(t.compiled);
12560 applyTemplate : function(values){
12561 return this.master.compiled.call(this, values, {});
12562 //var s = this.subs;
12565 apply : function(){
12566 return this.applyTemplate.apply(this, arguments);
12571 Roo.DomTemplate.from = function(el){
12572 el = Roo.getDom(el);
12573 return new Roo.Domtemplate(el.value || el.innerHTML);
12576 * Ext JS Library 1.1.1
12577 * Copyright(c) 2006-2007, Ext JS, LLC.
12579 * Originally Released Under LGPL - original licence link has changed is not relivant.
12582 * <script type="text/javascript">
12586 * @class Roo.util.DelayedTask
12587 * Provides a convenient method of performing setTimeout where a new
12588 * timeout cancels the old timeout. An example would be performing validation on a keypress.
12589 * You can use this class to buffer
12590 * the keypress events for a certain number of milliseconds, and perform only if they stop
12591 * for that amount of time.
12592 * @constructor The parameters to this constructor serve as defaults and are not required.
12593 * @param {Function} fn (optional) The default function to timeout
12594 * @param {Object} scope (optional) The default scope of that timeout
12595 * @param {Array} args (optional) The default Array of arguments
12597 Roo.util.DelayedTask = function(fn, scope, args){
12598 var id = null, d, t;
12600 var call = function(){
12601 var now = new Date().getTime();
12605 fn.apply(scope, args || []);
12609 * Cancels any pending timeout and queues a new one
12610 * @param {Number} delay The milliseconds to delay
12611 * @param {Function} newFn (optional) Overrides function passed to constructor
12612 * @param {Object} newScope (optional) Overrides scope passed to constructor
12613 * @param {Array} newArgs (optional) Overrides args passed to constructor
12615 this.delay = function(delay, newFn, newScope, newArgs){
12616 if(id && delay != d){
12620 t = new Date().getTime();
12622 scope = newScope || scope;
12623 args = newArgs || args;
12625 id = setInterval(call, d);
12630 * Cancel the last queued timeout
12632 this.cancel = function(){
12640 * Ext JS Library 1.1.1
12641 * Copyright(c) 2006-2007, Ext JS, LLC.
12643 * Originally Released Under LGPL - original licence link has changed is not relivant.
12646 * <script type="text/javascript">
12650 Roo.util.TaskRunner = function(interval){
12651 interval = interval || 10;
12652 var tasks = [], removeQueue = [];
12654 var running = false;
12656 var stopThread = function(){
12662 var startThread = function(){
12665 id = setInterval(runTasks, interval);
12669 var removeTask = function(task){
12670 removeQueue.push(task);
12676 var runTasks = function(){
12677 if(removeQueue.length > 0){
12678 for(var i = 0, len = removeQueue.length; i < len; i++){
12679 tasks.remove(removeQueue[i]);
12682 if(tasks.length < 1){
12687 var now = new Date().getTime();
12688 for(var i = 0, len = tasks.length; i < len; ++i){
12690 var itime = now - t.taskRunTime;
12691 if(t.interval <= itime){
12692 var rt = t.run.apply(t.scope || t, t.args || [++t.taskRunCount]);
12693 t.taskRunTime = now;
12694 if(rt === false || t.taskRunCount === t.repeat){
12699 if(t.duration && t.duration <= (now - t.taskStartTime)){
12706 * Queues a new task.
12707 * @param {Object} task
12709 this.start = function(task){
12711 task.taskStartTime = new Date().getTime();
12712 task.taskRunTime = 0;
12713 task.taskRunCount = 0;
12718 this.stop = function(task){
12723 this.stopAll = function(){
12725 for(var i = 0, len = tasks.length; i < len; i++){
12726 if(tasks[i].onStop){
12735 Roo.TaskMgr = new Roo.util.TaskRunner();/*
12737 * Ext JS Library 1.1.1
12738 * Copyright(c) 2006-2007, Ext JS, LLC.
12740 * Originally Released Under LGPL - original licence link has changed is not relivant.
12743 * <script type="text/javascript">
12748 * @class Roo.util.MixedCollection
12749 * @extends Roo.util.Observable
12750 * A Collection class that maintains both numeric indexes and keys and exposes events.
12752 * @param {Boolean} allowFunctions True if the addAll function should add function references to the
12753 * collection (defaults to false)
12754 * @param {Function} keyFn A function that can accept an item of the type(s) stored in this MixedCollection
12755 * and return the key value for that item. This is used when available to look up the key on items that
12756 * were passed without an explicit key parameter to a MixedCollection method. Passing this parameter is
12757 * equivalent to providing an implementation for the {@link #getKey} method.
12759 Roo.util.MixedCollection = function(allowFunctions, keyFn){
12767 * Fires when the collection is cleared.
12772 * Fires when an item is added to the collection.
12773 * @param {Number} index The index at which the item was added.
12774 * @param {Object} o The item added.
12775 * @param {String} key The key associated with the added item.
12780 * Fires when an item is replaced in the collection.
12781 * @param {String} key he key associated with the new added.
12782 * @param {Object} old The item being replaced.
12783 * @param {Object} new The new item.
12788 * Fires when an item is removed from the collection.
12789 * @param {Object} o The item being removed.
12790 * @param {String} key (optional) The key associated with the removed item.
12795 this.allowFunctions = allowFunctions === true;
12797 this.getKey = keyFn;
12799 Roo.util.MixedCollection.superclass.constructor.call(this);
12802 Roo.extend(Roo.util.MixedCollection, Roo.util.Observable, {
12803 allowFunctions : false,
12806 * Adds an item to the collection.
12807 * @param {String} key The key to associate with the item
12808 * @param {Object} o The item to add.
12809 * @return {Object} The item added.
12811 add : function(key, o){
12812 if(arguments.length == 1){
12814 key = this.getKey(o);
12816 if(typeof key == "undefined" || key === null){
12818 this.items.push(o);
12819 this.keys.push(null);
12821 var old = this.map[key];
12823 return this.replace(key, o);
12826 this.items.push(o);
12828 this.keys.push(key);
12830 this.fireEvent("add", this.length-1, o, key);
12835 * MixedCollection has a generic way to fetch keys if you implement getKey.
12838 var mc = new Roo.util.MixedCollection();
12839 mc.add(someEl.dom.id, someEl);
12840 mc.add(otherEl.dom.id, otherEl);
12844 var mc = new Roo.util.MixedCollection();
12845 mc.getKey = function(el){
12851 // or via the constructor
12852 var mc = new Roo.util.MixedCollection(false, function(el){
12858 * @param o {Object} The item for which to find the key.
12859 * @return {Object} The key for the passed item.
12861 getKey : function(o){
12866 * Replaces an item in the collection.
12867 * @param {String} key The key associated with the item to replace, or the item to replace.
12868 * @param o {Object} o (optional) If the first parameter passed was a key, the item to associate with that key.
12869 * @return {Object} The new item.
12871 replace : function(key, o){
12872 if(arguments.length == 1){
12874 key = this.getKey(o);
12876 var old = this.item(key);
12877 if(typeof key == "undefined" || key === null || typeof old == "undefined"){
12878 return this.add(key, o);
12880 var index = this.indexOfKey(key);
12881 this.items[index] = o;
12883 this.fireEvent("replace", key, old, o);
12888 * Adds all elements of an Array or an Object to the collection.
12889 * @param {Object/Array} objs An Object containing properties which will be added to the collection, or
12890 * an Array of values, each of which are added to the collection.
12892 addAll : function(objs){
12893 if(arguments.length > 1 || objs instanceof Array){
12894 var args = arguments.length > 1 ? arguments : objs;
12895 for(var i = 0, len = args.length; i < len; i++){
12899 for(var key in objs){
12900 if(this.allowFunctions || typeof objs[key] != "function"){
12901 this.add(key, objs[key]);
12908 * Executes the specified function once for every item in the collection, passing each
12909 * item as the first and only parameter. returning false from the function will stop the iteration.
12910 * @param {Function} fn The function to execute for each item.
12911 * @param {Object} scope (optional) The scope in which to execute the function.
12913 each : function(fn, scope){
12914 var items = [].concat(this.items); // each safe for removal
12915 for(var i = 0, len = items.length; i < len; i++){
12916 if(fn.call(scope || items[i], items[i], i, len) === false){
12923 * Executes the specified function once for every key in the collection, passing each
12924 * key, and its associated item as the first two parameters.
12925 * @param {Function} fn The function to execute for each item.
12926 * @param {Object} scope (optional) The scope in which to execute the function.
12928 eachKey : function(fn, scope){
12929 for(var i = 0, len = this.keys.length; i < len; i++){
12930 fn.call(scope || window, this.keys[i], this.items[i], i, len);
12935 * Returns the first item in the collection which elicits a true return value from the
12936 * passed selection function.
12937 * @param {Function} fn The selection function to execute for each item.
12938 * @param {Object} scope (optional) The scope in which to execute the function.
12939 * @return {Object} The first item in the collection which returned true from the selection function.
12941 find : function(fn, scope){
12942 for(var i = 0, len = this.items.length; i < len; i++){
12943 if(fn.call(scope || window, this.items[i], this.keys[i])){
12944 return this.items[i];
12951 * Inserts an item at the specified index in the collection.
12952 * @param {Number} index The index to insert the item at.
12953 * @param {String} key The key to associate with the new item, or the item itself.
12954 * @param {Object} o (optional) If the second parameter was a key, the new item.
12955 * @return {Object} The item inserted.
12957 insert : function(index, key, o){
12958 if(arguments.length == 2){
12960 key = this.getKey(o);
12962 if(index >= this.length){
12963 return this.add(key, o);
12966 this.items.splice(index, 0, o);
12967 if(typeof key != "undefined" && key != null){
12970 this.keys.splice(index, 0, key);
12971 this.fireEvent("add", index, o, key);
12976 * Removed an item from the collection.
12977 * @param {Object} o The item to remove.
12978 * @return {Object} The item removed.
12980 remove : function(o){
12981 return this.removeAt(this.indexOf(o));
12985 * Remove an item from a specified index in the collection.
12986 * @param {Number} index The index within the collection of the item to remove.
12988 removeAt : function(index){
12989 if(index < this.length && index >= 0){
12991 var o = this.items[index];
12992 this.items.splice(index, 1);
12993 var key = this.keys[index];
12994 if(typeof key != "undefined"){
12995 delete this.map[key];
12997 this.keys.splice(index, 1);
12998 this.fireEvent("remove", o, key);
13003 * Removed an item associated with the passed key fom the collection.
13004 * @param {String} key The key of the item to remove.
13006 removeKey : function(key){
13007 return this.removeAt(this.indexOfKey(key));
13011 * Returns the number of items in the collection.
13012 * @return {Number} the number of items in the collection.
13014 getCount : function(){
13015 return this.length;
13019 * Returns index within the collection of the passed Object.
13020 * @param {Object} o The item to find the index of.
13021 * @return {Number} index of the item.
13023 indexOf : function(o){
13024 if(!this.items.indexOf){
13025 for(var i = 0, len = this.items.length; i < len; i++){
13026 if(this.items[i] == o) return i;
13030 return this.items.indexOf(o);
13035 * Returns index within the collection of the passed key.
13036 * @param {String} key The key to find the index of.
13037 * @return {Number} index of the key.
13039 indexOfKey : function(key){
13040 if(!this.keys.indexOf){
13041 for(var i = 0, len = this.keys.length; i < len; i++){
13042 if(this.keys[i] == key) return i;
13046 return this.keys.indexOf(key);
13051 * Returns the item associated with the passed key OR index. Key has priority over index.
13052 * @param {String/Number} key The key or index of the item.
13053 * @return {Object} The item associated with the passed key.
13055 item : function(key){
13056 var item = typeof this.map[key] != "undefined" ? this.map[key] : this.items[key];
13057 return typeof item != 'function' || this.allowFunctions ? item : null; // for prototype!
13061 * Returns the item at the specified index.
13062 * @param {Number} index The index of the item.
13065 itemAt : function(index){
13066 return this.items[index];
13070 * Returns the item associated with the passed key.
13071 * @param {String/Number} key The key of the item.
13072 * @return {Object} The item associated with the passed key.
13074 key : function(key){
13075 return this.map[key];
13079 * Returns true if the collection contains the passed Object as an item.
13080 * @param {Object} o The Object to look for in the collection.
13081 * @return {Boolean} True if the collection contains the Object as an item.
13083 contains : function(o){
13084 return this.indexOf(o) != -1;
13088 * Returns true if the collection contains the passed Object as a key.
13089 * @param {String} key The key to look for in the collection.
13090 * @return {Boolean} True if the collection contains the Object as a key.
13092 containsKey : function(key){
13093 return typeof this.map[key] != "undefined";
13097 * Removes all items from the collection.
13099 clear : function(){
13104 this.fireEvent("clear");
13108 * Returns the first item in the collection.
13109 * @return {Object} the first item in the collection..
13111 first : function(){
13112 return this.items[0];
13116 * Returns the last item in the collection.
13117 * @return {Object} the last item in the collection..
13120 return this.items[this.length-1];
13123 _sort : function(property, dir, fn){
13124 var dsc = String(dir).toUpperCase() == "DESC" ? -1 : 1;
13125 fn = fn || function(a, b){
13128 var c = [], k = this.keys, items = this.items;
13129 for(var i = 0, len = items.length; i < len; i++){
13130 c[c.length] = {key: k[i], value: items[i], index: i};
13132 c.sort(function(a, b){
13133 var v = fn(a[property], b[property]) * dsc;
13135 v = (a.index < b.index ? -1 : 1);
13139 for(var i = 0, len = c.length; i < len; i++){
13140 items[i] = c[i].value;
13143 this.fireEvent("sort", this);
13147 * Sorts this collection with the passed comparison function
13148 * @param {String} direction (optional) "ASC" or "DESC"
13149 * @param {Function} fn (optional) comparison function
13151 sort : function(dir, fn){
13152 this._sort("value", dir, fn);
13156 * Sorts this collection by keys
13157 * @param {String} direction (optional) "ASC" or "DESC"
13158 * @param {Function} fn (optional) a comparison function (defaults to case insensitive string)
13160 keySort : function(dir, fn){
13161 this._sort("key", dir, fn || function(a, b){
13162 return String(a).toUpperCase()-String(b).toUpperCase();
13167 * Returns a range of items in this collection
13168 * @param {Number} startIndex (optional) defaults to 0
13169 * @param {Number} endIndex (optional) default to the last item
13170 * @return {Array} An array of items
13172 getRange : function(start, end){
13173 var items = this.items;
13174 if(items.length < 1){
13177 start = start || 0;
13178 end = Math.min(typeof end == "undefined" ? this.length-1 : end, this.length-1);
13181 for(var i = start; i <= end; i++) {
13182 r[r.length] = items[i];
13185 for(var i = start; i >= end; i--) {
13186 r[r.length] = items[i];
13193 * Filter the <i>objects</i> in this collection by a specific property.
13194 * Returns a new collection that has been filtered.
13195 * @param {String} property A property on your objects
13196 * @param {String/RegExp} value Either string that the property values
13197 * should start with or a RegExp to test against the property
13198 * @return {MixedCollection} The new filtered collection
13200 filter : function(property, value){
13201 if(!value.exec){ // not a regex
13202 value = String(value);
13203 if(value.length == 0){
13204 return this.clone();
13206 value = new RegExp("^" + Roo.escapeRe(value), "i");
13208 return this.filterBy(function(o){
13209 return o && value.test(o[property]);
13214 * Filter by a function. * Returns a new collection that has been filtered.
13215 * The passed function will be called with each
13216 * object in the collection. If the function returns true, the value is included
13217 * otherwise it is filtered.
13218 * @param {Function} fn The function to be called, it will receive the args o (the object), k (the key)
13219 * @param {Object} scope (optional) The scope of the function (defaults to this)
13220 * @return {MixedCollection} The new filtered collection
13222 filterBy : function(fn, scope){
13223 var r = new Roo.util.MixedCollection();
13224 r.getKey = this.getKey;
13225 var k = this.keys, it = this.items;
13226 for(var i = 0, len = it.length; i < len; i++){
13227 if(fn.call(scope||this, it[i], k[i])){
13228 r.add(k[i], it[i]);
13235 * Creates a duplicate of this collection
13236 * @return {MixedCollection}
13238 clone : function(){
13239 var r = new Roo.util.MixedCollection();
13240 var k = this.keys, it = this.items;
13241 for(var i = 0, len = it.length; i < len; i++){
13242 r.add(k[i], it[i]);
13244 r.getKey = this.getKey;
13249 * Returns the item associated with the passed key or index.
13251 * @param {String/Number} key The key or index of the item.
13252 * @return {Object} The item associated with the passed key.
13254 Roo.util.MixedCollection.prototype.get = Roo.util.MixedCollection.prototype.item;/*
13256 * Ext JS Library 1.1.1
13257 * Copyright(c) 2006-2007, Ext JS, LLC.
13259 * Originally Released Under LGPL - original licence link has changed is not relivant.
13262 * <script type="text/javascript">
13265 * @class Roo.util.JSON
13266 * Modified version of Douglas Crockford"s json.js that doesn"t
13267 * mess with the Object prototype
13268 * http://www.json.org/js.html
13271 Roo.util.JSON = new (function(){
13272 var useHasOwn = {}.hasOwnProperty ? true : false;
13274 // crashes Safari in some instances
13275 //var validRE = /^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/;
13277 var pad = function(n) {
13278 return n < 10 ? "0" + n : n;
13291 var encodeString = function(s){
13292 if (/["\\\x00-\x1f]/.test(s)) {
13293 return '"' + s.replace(/([\x00-\x1f\\"])/g, function(a, b) {
13298 c = b.charCodeAt();
13300 Math.floor(c / 16).toString(16) +
13301 (c % 16).toString(16);
13304 return '"' + s + '"';
13307 var encodeArray = function(o){
13308 var a = ["["], b, i, l = o.length, v;
13309 for (i = 0; i < l; i += 1) {
13311 switch (typeof v) {
13320 a.push(v === null ? "null" : Roo.util.JSON.encode(v));
13328 var encodeDate = function(o){
13329 return '"' + o.getFullYear() + "-" +
13330 pad(o.getMonth() + 1) + "-" +
13331 pad(o.getDate()) + "T" +
13332 pad(o.getHours()) + ":" +
13333 pad(o.getMinutes()) + ":" +
13334 pad(o.getSeconds()) + '"';
13338 * Encodes an Object, Array or other value
13339 * @param {Mixed} o The variable to encode
13340 * @return {String} The JSON string
13342 this.encode = function(o)
13344 // should this be extended to fully wrap stringify..
13346 if(typeof o == "undefined" || o === null){
13348 }else if(o instanceof Array){
13349 return encodeArray(o);
13350 }else if(o instanceof Date){
13351 return encodeDate(o);
13352 }else if(typeof o == "string"){
13353 return encodeString(o);
13354 }else if(typeof o == "number"){
13355 return isFinite(o) ? String(o) : "null";
13356 }else if(typeof o == "boolean"){
13359 var a = ["{"], b, i, v;
13361 if(!useHasOwn || o.hasOwnProperty(i)) {
13363 switch (typeof v) {
13372 a.push(this.encode(i), ":",
13373 v === null ? "null" : this.encode(v));
13384 * Decodes (parses) a JSON string to an object. If the JSON is invalid, this function throws a SyntaxError.
13385 * @param {String} json The JSON string
13386 * @return {Object} The resulting object
13388 this.decode = function(json){
13390 return /** eval:var:json */ eval("(" + json + ')');
13394 * Shorthand for {@link Roo.util.JSON#encode}
13395 * @member Roo encode
13397 Roo.encode = typeof(JSON) != 'undefined' && JSON.stringify ? JSON.stringify : Roo.util.JSON.encode;
13399 * Shorthand for {@link Roo.util.JSON#decode}
13400 * @member Roo decode
13402 Roo.decode = typeof(JSON) != 'undefined' && JSON.parse ? JSON.parse : Roo.util.JSON.decode;
13405 * Ext JS Library 1.1.1
13406 * Copyright(c) 2006-2007, Ext JS, LLC.
13408 * Originally Released Under LGPL - original licence link has changed is not relivant.
13411 * <script type="text/javascript">
13415 * @class Roo.util.Format
13416 * Reusable data formatting functions
13419 Roo.util.Format = function(){
13420 var trimRe = /^\s+|\s+$/g;
13423 * Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length
13424 * @param {String} value The string to truncate
13425 * @param {Number} length The maximum length to allow before truncating
13426 * @return {String} The converted text
13428 ellipsis : function(value, len){
13429 if(value && value.length > len){
13430 return value.substr(0, len-3)+"...";
13436 * Checks a reference and converts it to empty string if it is undefined
13437 * @param {Mixed} value Reference to check
13438 * @return {Mixed} Empty string if converted, otherwise the original value
13440 undef : function(value){
13441 return typeof value != "undefined" ? value : "";
13445 * Convert certain characters (&, <, >, and ') to their HTML character equivalents for literal display in web pages.
13446 * @param {String} value The string to encode
13447 * @return {String} The encoded text
13449 htmlEncode : function(value){
13450 return !value ? value : String(value).replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, """);
13454 * Convert certain characters (&, <, >, and ') from their HTML character equivalents.
13455 * @param {String} value The string to decode
13456 * @return {String} The decoded text
13458 htmlDecode : function(value){
13459 return !value ? value : String(value).replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, '"');
13463 * Trims any whitespace from either side of a string
13464 * @param {String} value The text to trim
13465 * @return {String} The trimmed text
13467 trim : function(value){
13468 return String(value).replace(trimRe, "");
13472 * Returns a substring from within an original string
13473 * @param {String} value The original text
13474 * @param {Number} start The start index of the substring
13475 * @param {Number} length The length of the substring
13476 * @return {String} The substring
13478 substr : function(value, start, length){
13479 return String(value).substr(start, length);
13483 * Converts a string to all lower case letters
13484 * @param {String} value The text to convert
13485 * @return {String} The converted text
13487 lowercase : function(value){
13488 return String(value).toLowerCase();
13492 * Converts a string to all upper case letters
13493 * @param {String} value The text to convert
13494 * @return {String} The converted text
13496 uppercase : function(value){
13497 return String(value).toUpperCase();
13501 * Converts the first character only of a string to upper case
13502 * @param {String} value The text to convert
13503 * @return {String} The converted text
13505 capitalize : function(value){
13506 return !value ? value : value.charAt(0).toUpperCase() + value.substr(1).toLowerCase();
13510 call : function(value, fn){
13511 if(arguments.length > 2){
13512 var args = Array.prototype.slice.call(arguments, 2);
13513 args.unshift(value);
13515 return /** eval:var:value */ eval(fn).apply(window, args);
13517 /** eval:var:value */
13518 return /** eval:var:value */ eval(fn).call(window, value);
13524 * safer version of Math.toFixed..??/
13525 * @param {Number/String} value The numeric value to format
13526 * @param {Number/String} value Decimal places
13527 * @return {String} The formatted currency string
13529 toFixed : function(v, n)
13531 // why not use to fixed - precision is buggered???
13533 return Math.round(v-0);
13535 var fact = Math.pow(10,n+1);
13536 v = (Math.round((v-0)*fact))/fact;
13537 var z = (''+fact).substring(2);
13538 if (v == Math.floor(v)) {
13539 return Math.floor(v) + '.' + z;
13542 // now just padd decimals..
13543 var ps = String(v).split('.');
13544 var fd = (ps[1] + z);
13545 var r = fd.substring(0,n);
13546 var rm = fd.substring(n);
13548 return ps[0] + '.' + r;
13550 r*=1; // turn it into a number;
13552 if (String(r).length != n) {
13555 r = String(r).substring(1); // chop the end off.
13558 return ps[0] + '.' + r;
13563 * Format a number as US currency
13564 * @param {Number/String} value The numeric value to format
13565 * @return {String} The formatted currency string
13567 usMoney : function(v){
13568 return '$' + Roo.util.Format.number(v);
13573 * eventually this should probably emulate php's number_format
13574 * @param {Number/String} value The numeric value to format
13575 * @param {Number} decimals number of decimal places
13576 * @return {String} The formatted currency string
13578 number : function(v,decimals)
13580 // multiply and round.
13581 decimals = typeof(decimals) == 'undefined' ? 2 : decimals;
13582 var mul = Math.pow(10, decimals);
13583 var zero = String(mul).substring(1);
13584 v = (Math.round((v-0)*mul))/mul;
13586 // if it's '0' number.. then
13588 //v = (v == Math.floor(v)) ? v + "." + zero : ((v*10 == Math.floor(v*10)) ? v + "0" : v);
13590 var ps = v.split('.');
13594 var r = /(\d+)(\d{3})/;
13596 while (r.test(whole)) {
13597 whole = whole.replace(r, '$1' + ',' + '$2');
13603 (decimals ? ('.'+ ps[1] + zero.substring(ps[1].length)) : '') :
13604 // does not have decimals
13605 (decimals ? ('.' + zero) : '');
13608 return whole + sub ;
13612 * Parse a value into a formatted date using the specified format pattern.
13613 * @param {Mixed} value The value to format
13614 * @param {String} format (optional) Any valid date format string (defaults to 'm/d/Y')
13615 * @return {String} The formatted date string
13617 date : function(v, format){
13621 if(!(v instanceof Date)){
13622 v = new Date(Date.parse(v));
13624 return v.dateFormat(format || Roo.util.Format.defaults.date);
13628 * Returns a date rendering function that can be reused to apply a date format multiple times efficiently
13629 * @param {String} format Any valid date format string
13630 * @return {Function} The date formatting function
13632 dateRenderer : function(format){
13633 return function(v){
13634 return Roo.util.Format.date(v, format);
13639 stripTagsRE : /<\/?[^>]+>/gi,
13642 * Strips all HTML tags
13643 * @param {Mixed} value The text from which to strip tags
13644 * @return {String} The stripped text
13646 stripTags : function(v){
13647 return !v ? v : String(v).replace(this.stripTagsRE, "");
13651 Roo.util.Format.defaults = {
13655 * Ext JS Library 1.1.1
13656 * Copyright(c) 2006-2007, Ext JS, LLC.
13658 * Originally Released Under LGPL - original licence link has changed is not relivant.
13661 * <script type="text/javascript">
13668 * @class Roo.MasterTemplate
13669 * @extends Roo.Template
13670 * Provides a template that can have child templates. The syntax is:
13672 var t = new Roo.MasterTemplate(
13673 '<select name="{name}">',
13674 '<tpl name="options"><option value="{value:trim}">{text:ellipsis(10)}</option></tpl>',
13677 t.add('options', {value: 'foo', text: 'bar'});
13678 // or you can add multiple child elements in one shot
13679 t.addAll('options', [
13680 {value: 'foo', text: 'bar'},
13681 {value: 'foo2', text: 'bar2'},
13682 {value: 'foo3', text: 'bar3'}
13684 // then append, applying the master template values
13685 t.append('my-form', {name: 'my-select'});
13687 * A name attribute for the child template is not required if you have only one child
13688 * template or you want to refer to them by index.
13690 Roo.MasterTemplate = function(){
13691 Roo.MasterTemplate.superclass.constructor.apply(this, arguments);
13692 this.originalHtml = this.html;
13694 var m, re = this.subTemplateRe;
13697 while(m = re.exec(this.html)){
13698 var name = m[1], content = m[2];
13703 tpl : new Roo.Template(content)
13706 st[name] = st[subIndex];
13708 st[subIndex].tpl.compile();
13709 st[subIndex].tpl.call = this.call.createDelegate(this);
13712 this.subCount = subIndex;
13715 Roo.extend(Roo.MasterTemplate, Roo.Template, {
13717 * The regular expression used to match sub templates
13721 subTemplateRe : /<tpl(?:\sname="([\w-]+)")?>((?:.|\n)*?)<\/tpl>/gi,
13724 * Applies the passed values to a child template.
13725 * @param {String/Number} name (optional) The name or index of the child template
13726 * @param {Array/Object} values The values to be applied to the template
13727 * @return {MasterTemplate} this
13729 add : function(name, values){
13730 if(arguments.length == 1){
13731 values = arguments[0];
13734 var s = this.subs[name];
13735 s.buffer[s.buffer.length] = s.tpl.apply(values);
13740 * Applies all the passed values to a child template.
13741 * @param {String/Number} name (optional) The name or index of the child template
13742 * @param {Array} values The values to be applied to the template, this should be an array of objects.
13743 * @param {Boolean} reset (optional) True to reset the template first
13744 * @return {MasterTemplate} this
13746 fill : function(name, values, reset){
13748 if(a.length == 1 || (a.length == 2 && typeof a[1] == "boolean")){
13756 for(var i = 0, len = values.length; i < len; i++){
13757 this.add(name, values[i]);
13763 * Resets the template for reuse
13764 * @return {MasterTemplate} this
13766 reset : function(){
13768 for(var i = 0; i < this.subCount; i++){
13774 applyTemplate : function(values){
13776 var replaceIndex = -1;
13777 this.html = this.originalHtml.replace(this.subTemplateRe, function(m, name){
13778 return s[++replaceIndex].buffer.join("");
13780 return Roo.MasterTemplate.superclass.applyTemplate.call(this, values);
13783 apply : function(){
13784 return this.applyTemplate.apply(this, arguments);
13787 compile : function(){return this;}
13791 * Alias for fill().
13794 Roo.MasterTemplate.prototype.addAll = Roo.MasterTemplate.prototype.fill;
13796 * Creates a template from the passed element's value (display:none textarea, preferred) or innerHTML. e.g.
13797 * var tpl = Roo.MasterTemplate.from('element-id');
13798 * @param {String/HTMLElement} el
13799 * @param {Object} config
13802 Roo.MasterTemplate.from = function(el, config){
13803 el = Roo.getDom(el);
13804 return new Roo.MasterTemplate(el.value || el.innerHTML, config || '');
13807 * Ext JS Library 1.1.1
13808 * Copyright(c) 2006-2007, Ext JS, LLC.
13810 * Originally Released Under LGPL - original licence link has changed is not relivant.
13813 * <script type="text/javascript">
13818 * @class Roo.util.CSS
13819 * Utility class for manipulating CSS rules
13822 Roo.util.CSS = function(){
13824 var doc = document;
13826 var camelRe = /(-[a-z])/gi;
13827 var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); };
13831 * Very simple dynamic creation of stylesheets from a text blob of rules. The text will wrapped in a style
13832 * tag and appended to the HEAD of the document.
13833 * @param {String|Object} cssText The text containing the css rules
13834 * @param {String} id An id to add to the stylesheet for later removal
13835 * @return {StyleSheet}
13837 createStyleSheet : function(cssText, id){
13839 var head = doc.getElementsByTagName("head")[0];
13840 var nrules = doc.createElement("style");
13841 nrules.setAttribute("type", "text/css");
13843 nrules.setAttribute("id", id);
13845 if (typeof(cssText) != 'string') {
13846 // support object maps..
13847 // not sure if this a good idea..
13848 // perhaps it should be merged with the general css handling
13849 // and handle js style props.
13850 var cssTextNew = [];
13851 for(var n in cssText) {
13853 for(var k in cssText[n]) {
13854 citems.push( k + ' : ' +cssText[n][k] + ';' );
13856 cssTextNew.push( n + ' { ' + citems.join(' ') + '} ');
13859 cssText = cssTextNew.join("\n");
13865 head.appendChild(nrules);
13866 ss = nrules.styleSheet;
13867 ss.cssText = cssText;
13870 nrules.appendChild(doc.createTextNode(cssText));
13872 nrules.cssText = cssText;
13874 head.appendChild(nrules);
13875 ss = nrules.styleSheet ? nrules.styleSheet : (nrules.sheet || doc.styleSheets[doc.styleSheets.length-1]);
13877 this.cacheStyleSheet(ss);
13882 * Removes a style or link tag by id
13883 * @param {String} id The id of the tag
13885 removeStyleSheet : function(id){
13886 var existing = doc.getElementById(id);
13888 existing.parentNode.removeChild(existing);
13893 * Dynamically swaps an existing stylesheet reference for a new one
13894 * @param {String} id The id of an existing link tag to remove
13895 * @param {String} url The href of the new stylesheet to include
13897 swapStyleSheet : function(id, url){
13898 this.removeStyleSheet(id);
13899 var ss = doc.createElement("link");
13900 ss.setAttribute("rel", "stylesheet");
13901 ss.setAttribute("type", "text/css");
13902 ss.setAttribute("id", id);
13903 ss.setAttribute("href", url);
13904 doc.getElementsByTagName("head")[0].appendChild(ss);
13908 * Refresh the rule cache if you have dynamically added stylesheets
13909 * @return {Object} An object (hash) of rules indexed by selector
13911 refreshCache : function(){
13912 return this.getRules(true);
13916 cacheStyleSheet : function(stylesheet){
13920 try{// try catch for cross domain access issue
13921 var ssRules = stylesheet.cssRules || stylesheet.rules;
13922 for(var j = ssRules.length-1; j >= 0; --j){
13923 rules[ssRules[j].selectorText] = ssRules[j];
13929 * Gets all css rules for the document
13930 * @param {Boolean} refreshCache true to refresh the internal cache
13931 * @return {Object} An object (hash) of rules indexed by selector
13933 getRules : function(refreshCache){
13934 if(rules == null || refreshCache){
13936 var ds = doc.styleSheets;
13937 for(var i =0, len = ds.length; i < len; i++){
13939 this.cacheStyleSheet(ds[i]);
13947 * Gets an an individual CSS rule by selector(s)
13948 * @param {String/Array} selector The CSS selector or an array of selectors to try. The first selector that is found is returned.
13949 * @param {Boolean} refreshCache true to refresh the internal cache if you have recently updated any rules or added styles dynamically
13950 * @return {CSSRule} The CSS rule or null if one is not found
13952 getRule : function(selector, refreshCache){
13953 var rs = this.getRules(refreshCache);
13954 if(!(selector instanceof Array)){
13955 return rs[selector];
13957 for(var i = 0; i < selector.length; i++){
13958 if(rs[selector[i]]){
13959 return rs[selector[i]];
13967 * Updates a rule property
13968 * @param {String/Array} selector If it's an array it tries each selector until it finds one. Stops immediately once one is found.
13969 * @param {String} property The css property
13970 * @param {String} value The new value for the property
13971 * @return {Boolean} true If a rule was found and updated
13973 updateRule : function(selector, property, value){
13974 if(!(selector instanceof Array)){
13975 var rule = this.getRule(selector);
13977 rule.style[property.replace(camelRe, camelFn)] = value;
13981 for(var i = 0; i < selector.length; i++){
13982 if(this.updateRule(selector[i], property, value)){
13992 * Ext JS Library 1.1.1
13993 * Copyright(c) 2006-2007, Ext JS, LLC.
13995 * Originally Released Under LGPL - original licence link has changed is not relivant.
13998 * <script type="text/javascript">
14004 * @class Roo.util.ClickRepeater
14005 * @extends Roo.util.Observable
14007 * A wrapper class which can be applied to any element. Fires a "click" event while the
14008 * mouse is pressed. The interval between firings may be specified in the config but
14009 * defaults to 10 milliseconds.
14011 * Optionally, a CSS class may be applied to the element during the time it is pressed.
14013 * @cfg {String/HTMLElement/Element} el The element to act as a button.
14014 * @cfg {Number} delay The initial delay before the repeating event begins firing.
14015 * Similar to an autorepeat key delay.
14016 * @cfg {Number} interval The interval between firings of the "click" event. Default 10 ms.
14017 * @cfg {String} pressClass A CSS class name to be applied to the element while pressed.
14018 * @cfg {Boolean} accelerate True if autorepeating should start slowly and accelerate.
14019 * "interval" and "delay" are ignored. "immediate" is honored.
14020 * @cfg {Boolean} preventDefault True to prevent the default click event
14021 * @cfg {Boolean} stopDefault True to stop the default click event
14024 * 2007-02-02 jvs Original code contributed by Nige "Animal" White
14025 * 2007-02-02 jvs Renamed to ClickRepeater
14026 * 2007-02-03 jvs Modifications for FF Mac and Safari
14029 * @param {String/HTMLElement/Element} el The element to listen on
14030 * @param {Object} config
14032 Roo.util.ClickRepeater = function(el, config)
14034 this.el = Roo.get(el);
14035 this.el.unselectable();
14037 Roo.apply(this, config);
14042 * Fires when the mouse button is depressed.
14043 * @param {Roo.util.ClickRepeater} this
14045 "mousedown" : true,
14048 * Fires on a specified interval during the time the element is pressed.
14049 * @param {Roo.util.ClickRepeater} this
14054 * Fires when the mouse key is released.
14055 * @param {Roo.util.ClickRepeater} this
14060 this.el.on("mousedown", this.handleMouseDown, this);
14061 if(this.preventDefault || this.stopDefault){
14062 this.el.on("click", function(e){
14063 if(this.preventDefault){
14064 e.preventDefault();
14066 if(this.stopDefault){
14072 // allow inline handler
14074 this.on("click", this.handler, this.scope || this);
14077 Roo.util.ClickRepeater.superclass.constructor.call(this);
14080 Roo.extend(Roo.util.ClickRepeater, Roo.util.Observable, {
14083 preventDefault : true,
14084 stopDefault : false,
14088 handleMouseDown : function(){
14089 clearTimeout(this.timer);
14091 if(this.pressClass){
14092 this.el.addClass(this.pressClass);
14094 this.mousedownTime = new Date();
14096 Roo.get(document).on("mouseup", this.handleMouseUp, this);
14097 this.el.on("mouseout", this.handleMouseOut, this);
14099 this.fireEvent("mousedown", this);
14100 this.fireEvent("click", this);
14102 this.timer = this.click.defer(this.delay || this.interval, this);
14106 click : function(){
14107 this.fireEvent("click", this);
14108 this.timer = this.click.defer(this.getInterval(), this);
14112 getInterval: function(){
14113 if(!this.accelerate){
14114 return this.interval;
14116 var pressTime = this.mousedownTime.getElapsed();
14117 if(pressTime < 500){
14119 }else if(pressTime < 1700){
14121 }else if(pressTime < 2600){
14123 }else if(pressTime < 3500){
14125 }else if(pressTime < 4400){
14127 }else if(pressTime < 5300){
14129 }else if(pressTime < 6200){
14137 handleMouseOut : function(){
14138 clearTimeout(this.timer);
14139 if(this.pressClass){
14140 this.el.removeClass(this.pressClass);
14142 this.el.on("mouseover", this.handleMouseReturn, this);
14146 handleMouseReturn : function(){
14147 this.el.un("mouseover", this.handleMouseReturn);
14148 if(this.pressClass){
14149 this.el.addClass(this.pressClass);
14155 handleMouseUp : function(){
14156 clearTimeout(this.timer);
14157 this.el.un("mouseover", this.handleMouseReturn);
14158 this.el.un("mouseout", this.handleMouseOut);
14159 Roo.get(document).un("mouseup", this.handleMouseUp);
14160 this.el.removeClass(this.pressClass);
14161 this.fireEvent("mouseup", this);
14165 * Ext JS Library 1.1.1
14166 * Copyright(c) 2006-2007, Ext JS, LLC.
14168 * Originally Released Under LGPL - original licence link has changed is not relivant.
14171 * <script type="text/javascript">
14176 * @class Roo.KeyNav
14177 * <p>Provides a convenient wrapper for normalized keyboard navigation. KeyNav allows you to bind
14178 * navigation keys to function calls that will get called when the keys are pressed, providing an easy
14179 * way to implement custom navigation schemes for any UI component.</p>
14180 * <p>The following are all of the possible keys that can be implemented: enter, left, right, up, down, tab, esc,
14181 * pageUp, pageDown, del, home, end. Usage:</p>
14183 var nav = new Roo.KeyNav("my-element", {
14184 "left" : function(e){
14185 this.moveLeft(e.ctrlKey);
14187 "right" : function(e){
14188 this.moveRight(e.ctrlKey);
14190 "enter" : function(e){
14197 * @param {String/HTMLElement/Roo.Element} el The element to bind to
14198 * @param {Object} config The config
14200 Roo.KeyNav = function(el, config){
14201 this.el = Roo.get(el);
14202 Roo.apply(this, config);
14203 if(!this.disabled){
14204 this.disabled = true;
14209 Roo.KeyNav.prototype = {
14211 * @cfg {Boolean} disabled
14212 * True to disable this KeyNav instance (defaults to false)
14216 * @cfg {String} defaultEventAction
14217 * The method to call on the {@link Roo.EventObject} after this KeyNav intercepts a key. Valid values are
14218 * {@link Roo.EventObject#stopEvent}, {@link Roo.EventObject#preventDefault} and
14219 * {@link Roo.EventObject#stopPropagation} (defaults to 'stopEvent')
14221 defaultEventAction: "stopEvent",
14223 * @cfg {Boolean} forceKeyDown
14224 * Handle the keydown event instead of keypress (defaults to false). KeyNav automatically does this for IE since
14225 * IE does not propagate special keys on keypress, but setting this to true will force other browsers to also
14226 * handle keydown instead of keypress.
14228 forceKeyDown : false,
14231 prepareEvent : function(e){
14232 var k = e.getKey();
14233 var h = this.keyToHandler[k];
14234 //if(h && this[h]){
14235 // e.stopPropagation();
14237 if(Roo.isSafari && h && k >= 37 && k <= 40){
14243 relay : function(e){
14244 var k = e.getKey();
14245 var h = this.keyToHandler[k];
14247 if(this.doRelay(e, this[h], h) !== true){
14248 e[this.defaultEventAction]();
14254 doRelay : function(e, h, hname){
14255 return h.call(this.scope || this, e);
14258 // possible handlers
14272 // quick lookup hash
14289 * Enable this KeyNav
14291 enable: function(){
14293 // ie won't do special keys on keypress, no one else will repeat keys with keydown
14294 // the EventObject will normalize Safari automatically
14295 if(this.forceKeyDown || Roo.isIE || Roo.isAir){
14296 this.el.on("keydown", this.relay, this);
14298 this.el.on("keydown", this.prepareEvent, this);
14299 this.el.on("keypress", this.relay, this);
14301 this.disabled = false;
14306 * Disable this KeyNav
14308 disable: function(){
14309 if(!this.disabled){
14310 if(this.forceKeyDown || Roo.isIE || Roo.isAir){
14311 this.el.un("keydown", this.relay);
14313 this.el.un("keydown", this.prepareEvent);
14314 this.el.un("keypress", this.relay);
14316 this.disabled = true;
14321 * Ext JS Library 1.1.1
14322 * Copyright(c) 2006-2007, Ext JS, LLC.
14324 * Originally Released Under LGPL - original licence link has changed is not relivant.
14327 * <script type="text/javascript">
14332 * @class Roo.KeyMap
14333 * Handles mapping keys to actions for an element. One key map can be used for multiple actions.
14334 * The constructor accepts the same config object as defined by {@link #addBinding}.
14335 * If you bind a callback function to a KeyMap, anytime the KeyMap handles an expected key
14336 * combination it will call the function with this signature (if the match is a multi-key
14337 * combination the callback will still be called only once): (String key, Roo.EventObject e)
14338 * A KeyMap can also handle a string representation of keys.<br />
14341 // map one key by key code
14342 var map = new Roo.KeyMap("my-element", {
14343 key: 13, // or Roo.EventObject.ENTER
14348 // map multiple keys to one action by string
14349 var map = new Roo.KeyMap("my-element", {
14355 // map multiple keys to multiple actions by strings and array of codes
14356 var map = new Roo.KeyMap("my-element", [
14359 fn: function(){ alert("Return was pressed"); }
14362 fn: function(){ alert('a, b or c was pressed'); }
14367 fn: function(){ alert('Control + shift + tab was pressed.'); }
14371 * <b>Note: A KeyMap starts enabled</b>
14373 * @param {String/HTMLElement/Roo.Element} el The element to bind to
14374 * @param {Object} config The config (see {@link #addBinding})
14375 * @param {String} eventName (optional) The event to bind to (defaults to "keydown")
14377 Roo.KeyMap = function(el, config, eventName){
14378 this.el = Roo.get(el);
14379 this.eventName = eventName || "keydown";
14380 this.bindings = [];
14382 this.addBinding(config);
14387 Roo.KeyMap.prototype = {
14389 * True to stop the event from bubbling and prevent the default browser action if the
14390 * key was handled by the KeyMap (defaults to false)
14396 * Add a new binding to this KeyMap. The following config object properties are supported:
14398 Property Type Description
14399 ---------- --------------- ----------------------------------------------------------------------
14400 key String/Array A single keycode or an array of keycodes to handle
14401 shift Boolean True to handle key only when shift is pressed (defaults to false)
14402 ctrl Boolean True to handle key only when ctrl is pressed (defaults to false)
14403 alt Boolean True to handle key only when alt is pressed (defaults to false)
14404 fn Function The function to call when KeyMap finds the expected key combination
14405 scope Object The scope of the callback function
14411 var map = new Roo.KeyMap(document, {
14412 key: Roo.EventObject.ENTER,
14417 //Add a new binding to the existing KeyMap later
14425 * @param {Object/Array} config A single KeyMap config or an array of configs
14427 addBinding : function(config){
14428 if(config instanceof Array){
14429 for(var i = 0, len = config.length; i < len; i++){
14430 this.addBinding(config[i]);
14434 var keyCode = config.key,
14435 shift = config.shift,
14436 ctrl = config.ctrl,
14439 scope = config.scope;
14440 if(typeof keyCode == "string"){
14442 var keyString = keyCode.toUpperCase();
14443 for(var j = 0, len = keyString.length; j < len; j++){
14444 ks.push(keyString.charCodeAt(j));
14448 var keyArray = keyCode instanceof Array;
14449 var handler = function(e){
14450 if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) && (!alt || e.altKey)){
14451 var k = e.getKey();
14453 for(var i = 0, len = keyCode.length; i < len; i++){
14454 if(keyCode[i] == k){
14455 if(this.stopEvent){
14458 fn.call(scope || window, k, e);
14464 if(this.stopEvent){
14467 fn.call(scope || window, k, e);
14472 this.bindings.push(handler);
14476 * Shorthand for adding a single key listener
14477 * @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the
14478 * following options:
14479 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
14480 * @param {Function} fn The function to call
14481 * @param {Object} scope (optional) The scope of the function
14483 on : function(key, fn, scope){
14484 var keyCode, shift, ctrl, alt;
14485 if(typeof key == "object" && !(key instanceof Array)){
14504 handleKeyDown : function(e){
14505 if(this.enabled){ //just in case
14506 var b = this.bindings;
14507 for(var i = 0, len = b.length; i < len; i++){
14508 b[i].call(this, e);
14514 * Returns true if this KeyMap is enabled
14515 * @return {Boolean}
14517 isEnabled : function(){
14518 return this.enabled;
14522 * Enables this KeyMap
14524 enable: function(){
14526 this.el.on(this.eventName, this.handleKeyDown, this);
14527 this.enabled = true;
14532 * Disable this KeyMap
14534 disable: function(){
14536 this.el.removeListener(this.eventName, this.handleKeyDown, this);
14537 this.enabled = false;
14542 * Ext JS Library 1.1.1
14543 * Copyright(c) 2006-2007, Ext JS, LLC.
14545 * Originally Released Under LGPL - original licence link has changed is not relivant.
14548 * <script type="text/javascript">
14553 * @class Roo.util.TextMetrics
14554 * Provides precise pixel measurements for blocks of text so that you can determine exactly how high and
14555 * wide, in pixels, a given block of text will be.
14558 Roo.util.TextMetrics = function(){
14562 * Measures the size of the specified text
14563 * @param {String/HTMLElement} el The element, dom node or id from which to copy existing CSS styles
14564 * that can affect the size of the rendered text
14565 * @param {String} text The text to measure
14566 * @param {Number} fixedWidth (optional) If the text will be multiline, you have to set a fixed width
14567 * in order to accurately measure the text height
14568 * @return {Object} An object containing the text's size {width: (width), height: (height)}
14570 measure : function(el, text, fixedWidth){
14572 shared = Roo.util.TextMetrics.Instance(el, fixedWidth);
14575 shared.setFixedWidth(fixedWidth || 'auto');
14576 return shared.getSize(text);
14580 * Return a unique TextMetrics instance that can be bound directly to an element and reused. This reduces
14581 * the overhead of multiple calls to initialize the style properties on each measurement.
14582 * @param {String/HTMLElement} el The element, dom node or id that the instance will be bound to
14583 * @param {Number} fixedWidth (optional) If the text will be multiline, you have to set a fixed width
14584 * in order to accurately measure the text height
14585 * @return {Roo.util.TextMetrics.Instance} instance The new instance
14587 createInstance : function(el, fixedWidth){
14588 return Roo.util.TextMetrics.Instance(el, fixedWidth);
14595 Roo.util.TextMetrics.Instance = function(bindTo, fixedWidth){
14596 var ml = new Roo.Element(document.createElement('div'));
14597 document.body.appendChild(ml.dom);
14598 ml.position('absolute');
14599 ml.setLeftTop(-1000, -1000);
14603 ml.setWidth(fixedWidth);
14608 * Returns the size of the specified text based on the internal element's style and width properties
14609 * @memberOf Roo.util.TextMetrics.Instance#
14610 * @param {String} text The text to measure
14611 * @return {Object} An object containing the text's size {width: (width), height: (height)}
14613 getSize : function(text){
14615 var s = ml.getSize();
14621 * Binds this TextMetrics instance to an element from which to copy existing CSS styles
14622 * that can affect the size of the rendered text
14623 * @memberOf Roo.util.TextMetrics.Instance#
14624 * @param {String/HTMLElement} el The element, dom node or id
14626 bind : function(el){
14628 Roo.fly(el).getStyles('font-size','font-style', 'font-weight', 'font-family','line-height')
14633 * Sets a fixed width on the internal measurement element. If the text will be multiline, you have
14634 * to set a fixed width in order to accurately measure the text height.
14635 * @memberOf Roo.util.TextMetrics.Instance#
14636 * @param {Number} width The width to set on the element
14638 setFixedWidth : function(width){
14639 ml.setWidth(width);
14643 * Returns the measured width of the specified text
14644 * @memberOf Roo.util.TextMetrics.Instance#
14645 * @param {String} text The text to measure
14646 * @return {Number} width The width in pixels
14648 getWidth : function(text){
14649 ml.dom.style.width = 'auto';
14650 return this.getSize(text).width;
14654 * Returns the measured height of the specified text. For multiline text, be sure to call
14655 * {@link #setFixedWidth} if necessary.
14656 * @memberOf Roo.util.TextMetrics.Instance#
14657 * @param {String} text The text to measure
14658 * @return {Number} height The height in pixels
14660 getHeight : function(text){
14661 return this.getSize(text).height;
14665 instance.bind(bindTo);
14670 // backwards compat
14671 Roo.Element.measureText = Roo.util.TextMetrics.measure;/*
14673 * Ext JS Library 1.1.1
14674 * Copyright(c) 2006-2007, Ext JS, LLC.
14676 * Originally Released Under LGPL - original licence link has changed is not relivant.
14679 * <script type="text/javascript">
14683 * @class Roo.state.Provider
14684 * Abstract base class for state provider implementations. This class provides methods
14685 * for encoding and decoding <b>typed</b> variables including dates and defines the
14686 * Provider interface.
14688 Roo.state.Provider = function(){
14690 * @event statechange
14691 * Fires when a state change occurs.
14692 * @param {Provider} this This state provider
14693 * @param {String} key The state key which was changed
14694 * @param {String} value The encoded value for the state
14697 "statechange": true
14700 Roo.state.Provider.superclass.constructor.call(this);
14702 Roo.extend(Roo.state.Provider, Roo.util.Observable, {
14704 * Returns the current value for a key
14705 * @param {String} name The key name
14706 * @param {Mixed} defaultValue A default value to return if the key's value is not found
14707 * @return {Mixed} The state data
14709 get : function(name, defaultValue){
14710 return typeof this.state[name] == "undefined" ?
14711 defaultValue : this.state[name];
14715 * Clears a value from the state
14716 * @param {String} name The key name
14718 clear : function(name){
14719 delete this.state[name];
14720 this.fireEvent("statechange", this, name, null);
14724 * Sets the value for a key
14725 * @param {String} name The key name
14726 * @param {Mixed} value The value to set
14728 set : function(name, value){
14729 this.state[name] = value;
14730 this.fireEvent("statechange", this, name, value);
14734 * Decodes a string previously encoded with {@link #encodeValue}.
14735 * @param {String} value The value to decode
14736 * @return {Mixed} The decoded value
14738 decodeValue : function(cookie){
14739 var re = /^(a|n|d|b|s|o)\:(.*)$/;
14740 var matches = re.exec(unescape(cookie));
14741 if(!matches || !matches[1]) return; // non state cookie
14742 var type = matches[1];
14743 var v = matches[2];
14746 return parseFloat(v);
14748 return new Date(Date.parse(v));
14753 var values = v.split("^");
14754 for(var i = 0, len = values.length; i < len; i++){
14755 all.push(this.decodeValue(values[i]));
14760 var values = v.split("^");
14761 for(var i = 0, len = values.length; i < len; i++){
14762 var kv = values[i].split("=");
14763 all[kv[0]] = this.decodeValue(kv[1]);
14772 * Encodes a value including type information. Decode with {@link #decodeValue}.
14773 * @param {Mixed} value The value to encode
14774 * @return {String} The encoded value
14776 encodeValue : function(v){
14778 if(typeof v == "number"){
14780 }else if(typeof v == "boolean"){
14781 enc = "b:" + (v ? "1" : "0");
14782 }else if(v instanceof Date){
14783 enc = "d:" + v.toGMTString();
14784 }else if(v instanceof Array){
14786 for(var i = 0, len = v.length; i < len; i++){
14787 flat += this.encodeValue(v[i]);
14788 if(i != len-1) flat += "^";
14791 }else if(typeof v == "object"){
14794 if(typeof v[key] != "function"){
14795 flat += key + "=" + this.encodeValue(v[key]) + "^";
14798 enc = "o:" + flat.substring(0, flat.length-1);
14802 return escape(enc);
14808 * Ext JS Library 1.1.1
14809 * Copyright(c) 2006-2007, Ext JS, LLC.
14811 * Originally Released Under LGPL - original licence link has changed is not relivant.
14814 * <script type="text/javascript">
14817 * @class Roo.state.Manager
14818 * This is the global state manager. By default all components that are "state aware" check this class
14819 * for state information if you don't pass them a custom state provider. In order for this class
14820 * to be useful, it must be initialized with a provider when your application initializes.
14822 // in your initialization function
14824 Roo.state.Manager.setProvider(new Roo.state.CookieProvider());
14826 // supposed you have a {@link Roo.BorderLayout}
14827 var layout = new Roo.BorderLayout(...);
14828 layout.restoreState();
14829 // or a {Roo.BasicDialog}
14830 var dialog = new Roo.BasicDialog(...);
14831 dialog.restoreState();
14835 Roo.state.Manager = function(){
14836 var provider = new Roo.state.Provider();
14840 * Configures the default state provider for your application
14841 * @param {Provider} stateProvider The state provider to set
14843 setProvider : function(stateProvider){
14844 provider = stateProvider;
14848 * Returns the current value for a key
14849 * @param {String} name The key name
14850 * @param {Mixed} defaultValue The default value to return if the key lookup does not match
14851 * @return {Mixed} The state data
14853 get : function(key, defaultValue){
14854 return provider.get(key, defaultValue);
14858 * Sets the value for a key
14859 * @param {String} name The key name
14860 * @param {Mixed} value The state data
14862 set : function(key, value){
14863 provider.set(key, value);
14867 * Clears a value from the state
14868 * @param {String} name The key name
14870 clear : function(key){
14871 provider.clear(key);
14875 * Gets the currently configured state provider
14876 * @return {Provider} The state provider
14878 getProvider : function(){
14885 * Ext JS Library 1.1.1
14886 * Copyright(c) 2006-2007, Ext JS, LLC.
14888 * Originally Released Under LGPL - original licence link has changed is not relivant.
14891 * <script type="text/javascript">
14894 * @class Roo.state.CookieProvider
14895 * @extends Roo.state.Provider
14896 * The default Provider implementation which saves state via cookies.
14899 var cp = new Roo.state.CookieProvider({
14901 expires: new Date(new Date().getTime()+(1000*60*60*24*30)); //30 days
14902 domain: "roojs.com"
14904 Roo.state.Manager.setProvider(cp);
14906 * @cfg {String} path The path for which the cookie is active (defaults to root '/' which makes it active for all pages in the site)
14907 * @cfg {Date} expires The cookie expiration date (defaults to 7 days from now)
14908 * @cfg {String} domain The domain to save the cookie for. Note that you cannot specify a different domain than
14909 * your page is on, but you can specify a sub-domain, or simply the domain itself like 'roojs.com' to include
14910 * all sub-domains if you need to access cookies across different sub-domains (defaults to null which uses the same
14911 * domain the page is running on including the 'www' like 'www.roojs.com')
14912 * @cfg {Boolean} secure True if the site is using SSL (defaults to false)
14914 * Create a new CookieProvider
14915 * @param {Object} config The configuration object
14917 Roo.state.CookieProvider = function(config){
14918 Roo.state.CookieProvider.superclass.constructor.call(this);
14920 this.expires = new Date(new Date().getTime()+(1000*60*60*24*7)); //7 days
14921 this.domain = null;
14922 this.secure = false;
14923 Roo.apply(this, config);
14924 this.state = this.readCookies();
14927 Roo.extend(Roo.state.CookieProvider, Roo.state.Provider, {
14929 set : function(name, value){
14930 if(typeof value == "undefined" || value === null){
14934 this.setCookie(name, value);
14935 Roo.state.CookieProvider.superclass.set.call(this, name, value);
14939 clear : function(name){
14940 this.clearCookie(name);
14941 Roo.state.CookieProvider.superclass.clear.call(this, name);
14945 readCookies : function(){
14947 var c = document.cookie + ";";
14948 var re = /\s?(.*?)=(.*?);/g;
14950 while((matches = re.exec(c)) != null){
14951 var name = matches[1];
14952 var value = matches[2];
14953 if(name && name.substring(0,3) == "ys-"){
14954 cookies[name.substr(3)] = this.decodeValue(value);
14961 setCookie : function(name, value){
14962 document.cookie = "ys-"+ name + "=" + this.encodeValue(value) +
14963 ((this.expires == null) ? "" : ("; expires=" + this.expires.toGMTString())) +
14964 ((this.path == null) ? "" : ("; path=" + this.path)) +
14965 ((this.domain == null) ? "" : ("; domain=" + this.domain)) +
14966 ((this.secure == true) ? "; secure" : "");
14970 clearCookie : function(name){
14971 document.cookie = "ys-" + name + "=null; expires=Thu, 01-Jan-70 00:00:01 GMT" +
14972 ((this.path == null) ? "" : ("; path=" + this.path)) +
14973 ((this.domain == null) ? "" : ("; domain=" + this.domain)) +
14974 ((this.secure == true) ? "; secure" : "");
14978 * Ext JS Library 1.1.1
14979 * Copyright(c) 2006-2007, Ext JS, LLC.
14981 * Originally Released Under LGPL - original licence link has changed is not relivant.
14984 * <script type="text/javascript">
14989 * @class Roo.ComponentMgr
14990 * Provides a common registry of all components on a page so that they can be easily accessed by component id (see {@link Roo.getCmp}).
14993 Roo.ComponentMgr = function(){
14994 var all = new Roo.util.MixedCollection();
14998 * Registers a component.
14999 * @param {Roo.Component} c The component
15001 register : function(c){
15006 * Unregisters a component.
15007 * @param {Roo.Component} c The component
15009 unregister : function(c){
15014 * Returns a component by id
15015 * @param {String} id The component id
15017 get : function(id){
15018 return all.get(id);
15022 * Registers a function that will be called when a specified component is added to ComponentMgr
15023 * @param {String} id The component id
15024 * @param {Funtction} fn The callback function
15025 * @param {Object} scope The scope of the callback
15027 onAvailable : function(id, fn, scope){
15028 all.on("add", function(index, o){
15030 fn.call(scope || o, o);
15031 all.un("add", fn, scope);
15038 * Ext JS Library 1.1.1
15039 * Copyright(c) 2006-2007, Ext JS, LLC.
15041 * Originally Released Under LGPL - original licence link has changed is not relivant.
15044 * <script type="text/javascript">
15048 * @class Roo.Component
15049 * @extends Roo.util.Observable
15050 * Base class for all major Roo components. All subclasses of Component can automatically participate in the standard
15051 * Roo component lifecycle of creation, rendering and destruction. They also have automatic support for basic hide/show
15052 * and enable/disable behavior. Component allows any subclass to be lazy-rendered into any {@link Roo.Container} and
15053 * to be automatically registered with the {@link Roo.ComponentMgr} so that it can be referenced at any time via {@link Roo.getCmp}.
15054 * All visual components (widgets) that require rendering into a layout should subclass Component.
15056 * @param {Roo.Element/String/Object} config The configuration options. If an element is passed, it is set as the internal
15057 * element and its id used as the component id. If a string is passed, it is assumed to be the id of an existing element
15058 * and is used as the component id. Otherwise, it is assumed to be a standard config object and is applied to the component.
15060 Roo.Component = function(config){
15061 config = config || {};
15062 if(config.tagName || config.dom || typeof config == "string"){ // element object
15063 config = {el: config, id: config.id || config};
15065 this.initialConfig = config;
15067 Roo.apply(this, config);
15071 * Fires after the component is disabled.
15072 * @param {Roo.Component} this
15077 * Fires after the component is enabled.
15078 * @param {Roo.Component} this
15082 * @event beforeshow
15083 * Fires before the component is shown. Return false to stop the show.
15084 * @param {Roo.Component} this
15089 * Fires after the component is shown.
15090 * @param {Roo.Component} this
15094 * @event beforehide
15095 * Fires before the component is hidden. Return false to stop the hide.
15096 * @param {Roo.Component} this
15101 * Fires after the component is hidden.
15102 * @param {Roo.Component} this
15106 * @event beforerender
15107 * Fires before the component is rendered. Return false to stop the render.
15108 * @param {Roo.Component} this
15110 beforerender : true,
15113 * Fires after the component is rendered.
15114 * @param {Roo.Component} this
15118 * @event beforedestroy
15119 * Fires before the component is destroyed. Return false to stop the destroy.
15120 * @param {Roo.Component} this
15122 beforedestroy : true,
15125 * Fires after the component is destroyed.
15126 * @param {Roo.Component} this
15131 this.id = "ext-comp-" + (++Roo.Component.AUTO_ID);
15133 Roo.ComponentMgr.register(this);
15134 Roo.Component.superclass.constructor.call(this);
15135 this.initComponent();
15136 if(this.renderTo){ // not supported by all components yet. use at your own risk!
15137 this.render(this.renderTo);
15138 delete this.renderTo;
15143 Roo.Component.AUTO_ID = 1000;
15145 Roo.extend(Roo.Component, Roo.util.Observable, {
15147 * @scope Roo.Component.prototype
15149 * true if this component is hidden. Read-only.
15154 * true if this component is disabled. Read-only.
15159 * true if this component has been rendered. Read-only.
15163 /** @cfg {String} disableClass
15164 * CSS class added to the component when it is disabled (defaults to "x-item-disabled").
15166 disabledClass : "x-item-disabled",
15167 /** @cfg {Boolean} allowDomMove
15168 * Whether the component can move the Dom node when rendering (defaults to true).
15170 allowDomMove : true,
15171 /** @cfg {String} hideMode
15172 * How this component should hidden. Supported values are
15173 * "visibility" (css visibility), "offsets" (negative offset position) and
15174 * "display" (css display) - defaults to "display".
15176 hideMode: 'display',
15179 ctype : "Roo.Component",
15182 * @cfg {String} actionMode
15183 * which property holds the element that used for hide() / show() / disable() / enable()
15189 getActionEl : function(){
15190 return this[this.actionMode];
15193 initComponent : Roo.emptyFn,
15195 * If this is a lazy rendering component, render it to its container element.
15196 * @param {String/HTMLElement/Element} container (optional) The element this component should be rendered into. If it is being applied to existing markup, this should be left off.
15198 render : function(container, position){
15199 if(!this.rendered && this.fireEvent("beforerender", this) !== false){
15200 if(!container && this.el){
15201 this.el = Roo.get(this.el);
15202 container = this.el.dom.parentNode;
15203 this.allowDomMove = false;
15205 this.container = Roo.get(container);
15206 this.rendered = true;
15207 if(position !== undefined){
15208 if(typeof position == 'number'){
15209 position = this.container.dom.childNodes[position];
15211 position = Roo.getDom(position);
15214 this.onRender(this.container, position || null);
15216 this.el.addClass(this.cls);
15220 this.el.applyStyles(this.style);
15223 this.fireEvent("render", this);
15224 this.afterRender(this.container);
15236 // default function is not really useful
15237 onRender : function(ct, position){
15239 this.el = Roo.get(this.el);
15240 if(this.allowDomMove !== false){
15241 ct.dom.insertBefore(this.el.dom, position);
15247 getAutoCreate : function(){
15248 var cfg = typeof this.autoCreate == "object" ?
15249 this.autoCreate : Roo.apply({}, this.defaultAutoCreate);
15250 if(this.id && !cfg.id){
15257 afterRender : Roo.emptyFn,
15260 * Destroys this component by purging any event listeners, removing the component's element from the DOM,
15261 * removing the component from its {@link Roo.Container} (if applicable) and unregistering it from {@link Roo.ComponentMgr}.
15263 destroy : function(){
15264 if(this.fireEvent("beforedestroy", this) !== false){
15265 this.purgeListeners();
15266 this.beforeDestroy();
15268 this.el.removeAllListeners();
15270 if(this.actionMode == "container"){
15271 this.container.remove();
15275 Roo.ComponentMgr.unregister(this);
15276 this.fireEvent("destroy", this);
15281 beforeDestroy : function(){
15286 onDestroy : function(){
15291 * Returns the underlying {@link Roo.Element}.
15292 * @return {Roo.Element} The element
15294 getEl : function(){
15299 * Returns the id of this component.
15302 getId : function(){
15307 * Try to focus this component.
15308 * @param {Boolean} selectText True to also select the text in this component (if applicable)
15309 * @return {Roo.Component} this
15311 focus : function(selectText){
15314 if(selectText === true){
15315 this.el.dom.select();
15330 * Disable this component.
15331 * @return {Roo.Component} this
15333 disable : function(){
15337 this.disabled = true;
15338 this.fireEvent("disable", this);
15343 onDisable : function(){
15344 this.getActionEl().addClass(this.disabledClass);
15345 this.el.dom.disabled = true;
15349 * Enable this component.
15350 * @return {Roo.Component} this
15352 enable : function(){
15356 this.disabled = false;
15357 this.fireEvent("enable", this);
15362 onEnable : function(){
15363 this.getActionEl().removeClass(this.disabledClass);
15364 this.el.dom.disabled = false;
15368 * Convenience function for setting disabled/enabled by boolean.
15369 * @param {Boolean} disabled
15371 setDisabled : function(disabled){
15372 this[disabled ? "disable" : "enable"]();
15376 * Show this component.
15377 * @return {Roo.Component} this
15380 if(this.fireEvent("beforeshow", this) !== false){
15381 this.hidden = false;
15385 this.fireEvent("show", this);
15391 onShow : function(){
15392 var ae = this.getActionEl();
15393 if(this.hideMode == 'visibility'){
15394 ae.dom.style.visibility = "visible";
15395 }else if(this.hideMode == 'offsets'){
15396 ae.removeClass('x-hidden');
15398 ae.dom.style.display = "";
15403 * Hide this component.
15404 * @return {Roo.Component} this
15407 if(this.fireEvent("beforehide", this) !== false){
15408 this.hidden = true;
15412 this.fireEvent("hide", this);
15418 onHide : function(){
15419 var ae = this.getActionEl();
15420 if(this.hideMode == 'visibility'){
15421 ae.dom.style.visibility = "hidden";
15422 }else if(this.hideMode == 'offsets'){
15423 ae.addClass('x-hidden');
15425 ae.dom.style.display = "none";
15430 * Convenience function to hide or show this component by boolean.
15431 * @param {Boolean} visible True to show, false to hide
15432 * @return {Roo.Component} this
15434 setVisible: function(visible){
15444 * Returns true if this component is visible.
15446 isVisible : function(){
15447 return this.getActionEl().isVisible();
15450 cloneConfig : function(overrides){
15451 overrides = overrides || {};
15452 var id = overrides.id || Roo.id();
15453 var cfg = Roo.applyIf(overrides, this.initialConfig);
15454 cfg.id = id; // prevent dup id
15455 return new this.constructor(cfg);
15459 * Ext JS Library 1.1.1
15460 * Copyright(c) 2006-2007, Ext JS, LLC.
15462 * Originally Released Under LGPL - original licence link has changed is not relivant.
15465 * <script type="text/javascript">
15469 * @class Roo.BoxComponent
15470 * @extends Roo.Component
15471 * Base class for any visual {@link Roo.Component} that uses a box container. BoxComponent provides automatic box
15472 * model adjustments for sizing and positioning and will work correctly withnin the Component rendering model. All
15473 * container classes should subclass BoxComponent so that they will work consistently when nested within other Ext
15474 * layout containers.
15476 * @param {Roo.Element/String/Object} config The configuration options.
15478 Roo.BoxComponent = function(config){
15479 Roo.Component.call(this, config);
15483 * Fires after the component is resized.
15484 * @param {Roo.Component} this
15485 * @param {Number} adjWidth The box-adjusted width that was set
15486 * @param {Number} adjHeight The box-adjusted height that was set
15487 * @param {Number} rawWidth The width that was originally specified
15488 * @param {Number} rawHeight The height that was originally specified
15493 * Fires after the component is moved.
15494 * @param {Roo.Component} this
15495 * @param {Number} x The new x position
15496 * @param {Number} y The new y position
15502 Roo.extend(Roo.BoxComponent, Roo.Component, {
15503 // private, set in afterRender to signify that the component has been rendered
15505 // private, used to defer height settings to subclasses
15506 deferHeight: false,
15507 /** @cfg {Number} width
15508 * width (optional) size of component
15510 /** @cfg {Number} height
15511 * height (optional) size of component
15515 * Sets the width and height of the component. This method fires the resize event. This method can accept
15516 * either width and height as separate numeric arguments, or you can pass a size object like {width:10, height:20}.
15517 * @param {Number/Object} width The new width to set, or a size object in the format {width, height}
15518 * @param {Number} height The new height to set (not required if a size object is passed as the first arg)
15519 * @return {Roo.BoxComponent} this
15521 setSize : function(w, h){
15522 // support for standard size objects
15523 if(typeof w == 'object'){
15528 if(!this.boxReady){
15534 // prevent recalcs when not needed
15535 if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
15538 this.lastSize = {width: w, height: h};
15540 var adj = this.adjustSize(w, h);
15541 var aw = adj.width, ah = adj.height;
15542 if(aw !== undefined || ah !== undefined){ // this code is nasty but performs better with floaters
15543 var rz = this.getResizeEl();
15544 if(!this.deferHeight && aw !== undefined && ah !== undefined){
15545 rz.setSize(aw, ah);
15546 }else if(!this.deferHeight && ah !== undefined){
15548 }else if(aw !== undefined){
15551 this.onResize(aw, ah, w, h);
15552 this.fireEvent('resize', this, aw, ah, w, h);
15558 * Gets the current size of the component's underlying element.
15559 * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
15561 getSize : function(){
15562 return this.el.getSize();
15566 * Gets the current XY position of the component's underlying element.
15567 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
15568 * @return {Array} The XY position of the element (e.g., [100, 200])
15570 getPosition : function(local){
15571 if(local === true){
15572 return [this.el.getLeft(true), this.el.getTop(true)];
15574 return this.xy || this.el.getXY();
15578 * Gets the current box measurements of the component's underlying element.
15579 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
15580 * @returns {Object} box An object in the format {x, y, width, height}
15582 getBox : function(local){
15583 var s = this.el.getSize();
15585 s.x = this.el.getLeft(true);
15586 s.y = this.el.getTop(true);
15588 var xy = this.xy || this.el.getXY();
15596 * Sets the current box measurements of the component's underlying element.
15597 * @param {Object} box An object in the format {x, y, width, height}
15598 * @returns {Roo.BoxComponent} this
15600 updateBox : function(box){
15601 this.setSize(box.width, box.height);
15602 this.setPagePosition(box.x, box.y);
15607 getResizeEl : function(){
15608 return this.resizeEl || this.el;
15612 getPositionEl : function(){
15613 return this.positionEl || this.el;
15617 * Sets the left and top of the component. To set the page XY position instead, use {@link #setPagePosition}.
15618 * This method fires the move event.
15619 * @param {Number} left The new left
15620 * @param {Number} top The new top
15621 * @returns {Roo.BoxComponent} this
15623 setPosition : function(x, y){
15626 if(!this.boxReady){
15629 var adj = this.adjustPosition(x, y);
15630 var ax = adj.x, ay = adj.y;
15632 var el = this.getPositionEl();
15633 if(ax !== undefined || ay !== undefined){
15634 if(ax !== undefined && ay !== undefined){
15635 el.setLeftTop(ax, ay);
15636 }else if(ax !== undefined){
15638 }else if(ay !== undefined){
15641 this.onPosition(ax, ay);
15642 this.fireEvent('move', this, ax, ay);
15648 * Sets the page XY position of the component. To set the left and top instead, use {@link #setPosition}.
15649 * This method fires the move event.
15650 * @param {Number} x The new x position
15651 * @param {Number} y The new y position
15652 * @returns {Roo.BoxComponent} this
15654 setPagePosition : function(x, y){
15657 if(!this.boxReady){
15660 if(x === undefined || y === undefined){ // cannot translate undefined points
15663 var p = this.el.translatePoints(x, y);
15664 this.setPosition(p.left, p.top);
15669 onRender : function(ct, position){
15670 Roo.BoxComponent.superclass.onRender.call(this, ct, position);
15672 this.resizeEl = Roo.get(this.resizeEl);
15674 if(this.positionEl){
15675 this.positionEl = Roo.get(this.positionEl);
15680 afterRender : function(){
15681 Roo.BoxComponent.superclass.afterRender.call(this);
15682 this.boxReady = true;
15683 this.setSize(this.width, this.height);
15684 if(this.x || this.y){
15685 this.setPosition(this.x, this.y);
15687 if(this.pageX || this.pageY){
15688 this.setPagePosition(this.pageX, this.pageY);
15693 * Force the component's size to recalculate based on the underlying element's current height and width.
15694 * @returns {Roo.BoxComponent} this
15696 syncSize : function(){
15697 delete this.lastSize;
15698 this.setSize(this.el.getWidth(), this.el.getHeight());
15703 * Called after the component is resized, this method is empty by default but can be implemented by any
15704 * subclass that needs to perform custom logic after a resize occurs.
15705 * @param {Number} adjWidth The box-adjusted width that was set
15706 * @param {Number} adjHeight The box-adjusted height that was set
15707 * @param {Number} rawWidth The width that was originally specified
15708 * @param {Number} rawHeight The height that was originally specified
15710 onResize : function(adjWidth, adjHeight, rawWidth, rawHeight){
15715 * Called after the component is moved, this method is empty by default but can be implemented by any
15716 * subclass that needs to perform custom logic after a move occurs.
15717 * @param {Number} x The new x position
15718 * @param {Number} y The new y position
15720 onPosition : function(x, y){
15725 adjustSize : function(w, h){
15726 if(this.autoWidth){
15729 if(this.autoHeight){
15732 return {width : w, height: h};
15736 adjustPosition : function(x, y){
15737 return {x : x, y: y};
15740 * Original code for Roojs - LGPL
15741 * <script type="text/javascript">
15745 * @class Roo.XComponent
15746 * A delayed Element creator...
15747 * Or a way to group chunks of interface together.
15749 * Mypart.xyx = new Roo.XComponent({
15751 parent : 'Mypart.xyz', // empty == document.element.!!
15755 disabled : function() {}
15757 tree : function() { // return an tree of xtype declared components
15761 xtype : 'NestedLayoutPanel',
15768 * It can be used to build a big heiracy, with parent etc.
15769 * or you can just use this to render a single compoent to a dom element
15770 * MYPART.render(Roo.Element | String(id) | dom_element )
15772 * @extends Roo.util.Observable
15774 * @param cfg {Object} configuration of component
15777 Roo.XComponent = function(cfg) {
15778 Roo.apply(this, cfg);
15782 * Fires when this the componnt is built
15783 * @param {Roo.XComponent} c the component
15788 this.region = this.region || 'center'; // default..
15789 Roo.XComponent.register(this);
15790 this.modules = false;
15791 this.el = false; // where the layout goes..
15795 Roo.extend(Roo.XComponent, Roo.util.Observable, {
15798 * The created element (with Roo.factory())
15799 * @type {Roo.Layout}
15805 * for BC - use el in new code
15806 * @type {Roo.Layout}
15812 * for BC - use el in new code
15813 * @type {Roo.Layout}
15818 * @cfg {Function|boolean} disabled
15819 * If this module is disabled by some rule, return true from the funtion
15824 * @cfg {String} parent
15825 * Name of parent element which it get xtype added to..
15830 * @cfg {String} order
15831 * Used to set the order in which elements are created (usefull for multiple tabs)
15836 * @cfg {String} name
15837 * String to display while loading.
15841 * @cfg {String} region
15842 * Region to render component to (defaults to center)
15847 * @cfg {Array} items
15848 * A single item array - the first element is the root of the tree..
15849 * It's done this way to stay compatible with the Xtype system...
15855 * The method that retuns the tree of parts that make up this compoennt
15862 * render element to dom or tree
15863 * @param {Roo.Element|String|DomElement} optional render to if parent is not set.
15866 render : function(el)
15870 var hp = this.parent ? 1 : 0;
15872 if (!el && typeof(this.parent) == 'string' && this.parent.substring(0,1) == '#') {
15873 // if parent is a '#.....' string, then let's use that..
15874 var ename = this.parent.substr(1)
15875 this.parent = (this.parent == '#bootstrap') ? { el : true} : false; // flags it as a top module...
15876 el = Roo.get(ename);
15877 if (!el && !this.parent) {
15878 Roo.log("Warning - element can not be found :#" + ename );
15882 var tree = this._tree ? this._tree() : this.tree();
15885 if (!this.parent && typeof(Roo.bootstrap) != 'undefined' && tree.xns == Roo.bootstrap) {
15886 //el = Roo.get(document.body);
15887 this.parent = { el : true };
15892 if (!this.parent) {
15894 Roo.log("no parent - creating one");
15896 el = el ? Roo.get(el) : false;
15898 // it's a top level one..
15900 el : new Roo.BorderLayout(el || document.body, {
15906 tabPosition: 'top',
15907 //resizeTabs: true,
15908 alwaysShowTabs: el && hp? false : true,
15909 hideTabs: el || !hp ? true : false,
15916 if (!this.parent.el) {
15917 // probably an old style ctor, which has been disabled.
15921 // The 'tree' method is '_tree now'
15923 tree.region = tree.region || this.region;
15925 if (this.parent.el === true) {
15926 // bootstrap... - body..
15927 this.parent.el = Roo.factory(tree);
15930 this.el = this.parent.el.addxtype(tree);
15931 this.fireEvent('built', this);
15933 this.panel = this.el;
15934 this.layout = this.panel.layout;
15935 this.parentLayout = this.parent.layout || false;
15941 Roo.apply(Roo.XComponent, {
15943 * @property hideProgress
15944 * true to disable the building progress bar.. usefull on single page renders.
15947 hideProgress : false,
15949 * @property buildCompleted
15950 * True when the builder has completed building the interface.
15953 buildCompleted : false,
15956 * @property topModule
15957 * the upper most module - uses document.element as it's constructor.
15964 * @property modules
15965 * array of modules to be created by registration system.
15966 * @type {Array} of Roo.XComponent
15971 * @property elmodules
15972 * array of modules to be created by which use #ID
15973 * @type {Array} of Roo.XComponent
15979 * @property build_from_html
15980 * Build elements from html - used by bootstrap HTML stuff
15981 * - this is cleared after build is completed
15982 * @type {boolean} true (default false)
15985 build_from_html : false,
15988 * Register components to be built later.
15990 * This solves the following issues
15991 * - Building is not done on page load, but after an authentication process has occured.
15992 * - Interface elements are registered on page load
15993 * - Parent Interface elements may not be loaded before child, so this handles that..
16000 module : 'Pman.Tab.projectMgr',
16002 parent : 'Pman.layout',
16003 disabled : false, // or use a function..
16006 * * @param {Object} details about module
16008 register : function(obj) {
16010 Roo.XComponent.event.fireEvent('register', obj);
16011 switch(typeof(obj.disabled) ) {
16017 if ( obj.disabled() ) {
16023 if (obj.disabled) {
16029 this.modules.push(obj);
16033 * convert a string to an object..
16034 * eg. 'AAA.BBB' -> finds AAA.BBB
16038 toObject : function(str)
16040 if (!str || typeof(str) == 'object') {
16043 if (str.substring(0,1) == '#') {
16047 var ar = str.split('.');
16052 eval('if (typeof ' + rt + ' == "undefined"){ o = false;} o = ' + rt + ';');
16054 throw "Module not found : " + str;
16058 throw "Module not found : " + str;
16060 Roo.each(ar, function(e) {
16061 if (typeof(o[e]) == 'undefined') {
16062 throw "Module not found : " + str;
16073 * move modules into their correct place in the tree..
16076 preBuild : function ()
16079 Roo.each(this.modules , function (obj)
16081 Roo.XComponent.event.fireEvent('beforebuild', obj);
16083 var opar = obj.parent;
16085 obj.parent = this.toObject(opar);
16087 Roo.log("parent:toObject failed: " + e.toString());
16092 Roo.debug && Roo.log("GOT top level module");
16093 Roo.debug && Roo.log(obj);
16094 obj.modules = new Roo.util.MixedCollection(false,
16095 function(o) { return o.order + '' }
16097 this.topModule = obj;
16100 // parent is a string (usually a dom element name..)
16101 if (typeof(obj.parent) == 'string') {
16102 this.elmodules.push(obj);
16105 if (obj.parent.constructor != Roo.XComponent) {
16106 Roo.log("Warning : Object Parent is not instance of XComponent:" + obj.name)
16108 if (!obj.parent.modules) {
16109 obj.parent.modules = new Roo.util.MixedCollection(false,
16110 function(o) { return o.order + '' }
16113 if (obj.parent.disabled) {
16114 obj.disabled = true;
16116 obj.parent.modules.add(obj);
16121 * make a list of modules to build.
16122 * @return {Array} list of modules.
16125 buildOrder : function()
16128 var cmp = function(a,b) {
16129 return String(a).toUpperCase() > String(b).toUpperCase() ? 1 : -1;
16131 if ((!this.topModule || !this.topModule.modules) && !this.elmodules.length) {
16132 throw "No top level modules to build";
16135 // make a flat list in order of modules to build.
16136 var mods = this.topModule ? [ this.topModule ] : [];
16139 // elmodules (is a list of DOM based modules )
16140 Roo.each(this.elmodules, function(e) {
16142 if (!this.topModule &&
16143 typeof(e.parent) == 'string' &&
16144 e.parent.substring(0,1) == '#' &&
16145 Roo.get(e.parent.substr(1))
16148 _this.topModule = e;
16154 // add modules to their parents..
16155 var addMod = function(m) {
16156 Roo.debug && Roo.log("build Order: add: " + m.name);
16159 if (m.modules && !m.disabled) {
16160 Roo.debug && Roo.log("build Order: " + m.modules.length + " child modules");
16161 m.modules.keySort('ASC', cmp );
16162 Roo.debug && Roo.log("build Order: " + m.modules.length + " child modules (after sort)");
16164 m.modules.each(addMod);
16166 Roo.debug && Roo.log("build Order: no child modules");
16168 // not sure if this is used any more..
16170 m.finalize.name = m.name + " (clean up) ";
16171 mods.push(m.finalize);
16175 if (this.topModule && this.topModule.modules) {
16176 this.topModule.modules.keySort('ASC', cmp );
16177 this.topModule.modules.each(addMod);
16183 * Build the registered modules.
16184 * @param {Object} parent element.
16185 * @param {Function} optional method to call after module has been added.
16189 build : function(opts)
16192 if (typeof(opts) != 'undefined') {
16193 Roo.apply(this,opts);
16197 var mods = this.buildOrder();
16199 //this.allmods = mods;
16200 //Roo.debug && Roo.log(mods);
16202 if (!mods.length) { // should not happen
16203 throw "NO modules!!!";
16207 var msg = "Building Interface...";
16208 // flash it up as modal - so we store the mask!?
16209 if (!this.hideProgress && Roo.MessageBox) {
16210 Roo.MessageBox.show({ title: 'loading' });
16211 Roo.MessageBox.show({
16212 title: "Please wait...",
16221 var total = mods.length;
16224 var progressRun = function() {
16225 if (!mods.length) {
16226 Roo.debug && Roo.log('hide?');
16227 if (!this.hideProgress && Roo.MessageBox) {
16228 Roo.MessageBox.hide();
16230 Roo.XComponent.build_from_html = false; // reset, so dialogs will be build from javascript
16232 Roo.XComponent.event.fireEvent('buildcomplete', _this.topModule);
16238 var m = mods.shift();
16241 Roo.debug && Roo.log(m);
16242 // not sure if this is supported any more.. - modules that are are just function
16243 if (typeof(m) == 'function') {
16245 return progressRun.defer(10, _this);
16249 msg = "Building Interface " + (total - mods.length) +
16251 (m.name ? (' - ' + m.name) : '');
16252 Roo.debug && Roo.log(msg);
16253 if (!this.hideProgress && Roo.MessageBox) {
16254 Roo.MessageBox.updateProgress( (total - mods.length)/total, msg );
16258 // is the module disabled?
16259 var disabled = (typeof(m.disabled) == 'function') ?
16260 m.disabled.call(m.module.disabled) : m.disabled;
16264 return progressRun(); // we do not update the display!
16272 // it's 10 on top level, and 1 on others??? why...
16273 return progressRun.defer(10, _this);
16276 progressRun.defer(1, _this);
16290 * wrapper for event.on - aliased later..
16291 * Typically use to register a event handler for register:
16293 * eg. Roo.XComponent.on('register', function(comp) { comp.disable = true } );
16302 Roo.XComponent.event = new Roo.util.Observable({
16306 * Fires when an Component is registered,
16307 * set the disable property on the Component to stop registration.
16308 * @param {Roo.XComponent} c the component being registerd.
16313 * @event beforebuild
16314 * Fires before each Component is built
16315 * can be used to apply permissions.
16316 * @param {Roo.XComponent} c the component being registerd.
16319 'beforebuild' : true,
16321 * @event buildcomplete
16322 * Fires on the top level element when all elements have been built
16323 * @param {Roo.XComponent} the top level component.
16325 'buildcomplete' : true
16330 Roo.XComponent.on = Roo.XComponent.event.on.createDelegate(Roo.XComponent.event);