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 isFirefox = ua.indexOf("firefox") > -1,
57 isIE = ua.indexOf("msie") > -1,
58 isIE7 = ua.indexOf("msie 7") > -1,
59 isIE11 = /trident.*rv\:11\./.test(ua),
60 isGecko = !isSafari && ua.indexOf("gecko") > -1,
61 isBorderBox = isIE && !isStrict,
62 isWindows = (ua.indexOf("windows") != -1 || ua.indexOf("win32") != -1),
63 isMac = (ua.indexOf("macintosh") != -1 || ua.indexOf("mac os x") != -1),
64 isLinux = (ua.indexOf("linux") != -1),
65 isSecure = window.location.href.toLowerCase().indexOf("https") === 0,
66 isIOS = /iphone|ipad/.test(ua),
67 isTouch = (function() {
69 document.createEvent("TouchEvent");
76 // remove css image flicker
79 document.execCommand("BackgroundImageCache", false, true);
85 * True if the browser is in strict mode
90 * True if the page is running over SSL
95 * True when the document is fully initialized and ready for action
100 * Turn on debugging output (currently only the factory uses this)
107 * True to automatically uncache orphaned Roo.Elements periodically (defaults to true)
110 enableGarbageCollector : true,
113 * True to automatically purge event listeners after uncaching an element (defaults to false).
114 * Note: this only happens if enableGarbageCollector is true.
117 enableListenerCollection:false,
120 * URL to a blank file used by Roo when in secure mode for iframe src and onReady src to prevent
121 * the IE insecure content warning (defaults to javascript:false).
124 SSL_SECURE_URL : "javascript:false",
127 * URL to a 1x1 transparent gif image used by Roo to create inline icons with CSS background images. (Defaults to
128 * "http://Roojs.com/s.gif" and you should change this to a URL on your server).
131 BLANK_IMAGE_URL : "http:/"+"/localhost/s.gif",
133 emptyFn : function(){},
136 * Copies all the properties of config to obj if they don't already exist.
137 * @param {Object} obj The receiver of the properties
138 * @param {Object} config The source of the properties
139 * @return {Object} returns obj
141 applyIf : function(o, c){
144 if(typeof o[p] == "undefined"){ o[p] = c[p]; }
151 * Applies event listeners to elements by selectors when the document is ready.
152 * The event name is specified with an @ suffix.
155 // add a listener for click on all anchors in element with id foo
156 '#foo a@click' : function(e, t){
160 // add the same listener to multiple selectors (separated by comma BEFORE the @)
161 '#foo a, #bar span.some-class@mouseover' : function(){
166 * @param {Object} obj The list of behaviors to apply
168 addBehaviors : function(o){
170 Roo.onReady(function(){
175 var cache = {}; // simple cache for applying multiple behaviors to same selector does query multiple times
177 var parts = b.split('@');
178 if(parts[1]){ // for Object prototype breakers
181 cache[s] = Roo.select(s);
183 cache[s].on(parts[1], o[b]);
190 * Generates unique ids. If the element already has an id, it is unchanged
191 * @param {String/HTMLElement/Element} el (optional) The element to generate an id for
192 * @param {String} prefix (optional) Id prefix (defaults "Roo-gen")
193 * @return {String} The generated Id.
195 id : function(el, prefix){
196 prefix = prefix || "roo-gen";
198 var id = prefix + (++idSeed);
199 return el ? (el.id ? el.id : (el.id = id)) : id;
204 * Extends one class with another class and optionally overrides members with the passed literal. This class
205 * also adds the function "override()" to the class that can be used to override
206 * members on an instance.
207 * @param {Object} subclass The class inheriting the functionality
208 * @param {Object} superclass The class being extended
209 * @param {Object} overrides (optional) A literal with members
214 var io = function(o){
219 return function(sb, sp, overrides){
220 if(typeof sp == 'object'){ // eg. prototype, rather than function constructor..
223 sb = function(){sp.apply(this, arguments);};
225 var F = function(){}, sbp, spp = sp.prototype;
227 sbp = sb.prototype = new F();
231 if(spp.constructor == Object.prototype.constructor){
236 sb.override = function(o){
240 Roo.override(sb, overrides);
246 * Adds a list of functions to the prototype of an existing class, overwriting any existing methods with the same name.
248 Roo.override(MyClass, {
249 newMethod1: function(){
252 newMethod2: function(foo){
257 * @param {Object} origclass The class to override
258 * @param {Object} overrides The list of functions to add to origClass. This should be specified as an object literal
259 * containing one or more methods.
262 override : function(origclass, overrides){
264 var p = origclass.prototype;
265 for(var method in overrides){
266 p[method] = overrides[method];
271 * Creates namespaces to be used for scoping variables and classes so that they are not global. Usage:
273 Roo.namespace('Company', 'Company.data');
274 Company.Widget = function() { ... }
275 Company.data.CustomStore = function(config) { ... }
277 * @param {String} namespace1
278 * @param {String} namespace2
279 * @param {String} etc
282 namespace : function(){
283 var a=arguments, o=null, i, j, d, rt;
284 for (i=0; i<a.length; ++i) {
288 eval('if (typeof ' + rt + ' == "undefined"){' + rt + ' = {};} o = ' + rt + ';');
289 for (j=1; j<d.length; ++j) {
290 o[d[j]]=o[d[j]] || {};
296 * Creates namespaces to be used for scoping variables and classes so that they are not global. Usage:
298 Roo.factory({ xns: Roo.data, xtype : 'Store', .....});
299 Roo.factory(conf, Roo.data);
301 * @param {String} classname
302 * @param {String} namespace (optional)
306 factory : function(c, ns)
308 // no xtype, no ns or c.xns - or forced off by c.xns
309 if (!c.xtype || (!ns && !c.xns) || (c.xns === false)) { // not enough info...
312 ns = c.xns ? c.xns : ns; // if c.xns is set, then use that..
313 if (c.constructor == ns[c.xtype]) {// already created...
317 if (Roo.debug) Roo.log("Roo.Factory(" + c.xtype + ")");
318 var ret = new ns[c.xtype](c);
322 c.xns = false; // prevent recursion..
326 * Logs to console if it can.
328 * @param {String|Object} string
333 if ((typeof(console) == 'undefined') || (typeof(console.log) == 'undefined')) {
340 * 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.
344 urlEncode : function(o){
350 var ov = o[key], k = Roo.encodeURIComponent(key);
351 var type = typeof ov;
352 if(type == 'undefined'){
354 }else if(type != "function" && type != "object"){
355 buf.push(k, "=", Roo.encodeURIComponent(ov), "&");
356 }else if(ov instanceof Array){
358 for(var i = 0, len = ov.length; i < len; i++) {
359 buf.push(k, "=", Roo.encodeURIComponent(ov[i] === undefined ? '' : ov[i]), "&");
370 * Safe version of encodeURIComponent
371 * @param {String} data
375 encodeURIComponent : function (data)
378 return encodeURIComponent(data);
379 } catch(e) {} // should be an uri encode error.
381 if (data == '' || data == null){
384 // http://stackoverflow.com/questions/2596483/unicode-and-uri-encoding-decoding-and-escaping-in-javascript
385 function nibble_to_hex(nibble){
386 var chars = '0123456789ABCDEF';
387 return chars.charAt(nibble);
389 data = data.toString();
391 for(var i=0; i<data.length; i++){
392 var c = data.charCodeAt(i);
393 var bs = new Array();
396 bs[0] = 0xF0 | ((c & 0x1C0000) >>> 18);
397 bs[1] = 0x80 | ((c & 0x3F000) >>> 12);
398 bs[2] = 0x80 | ((c & 0xFC0) >>> 6);
399 bs[3] = 0x80 | (c & 0x3F);
400 }else if (c > 0x800){
402 bs[0] = 0xE0 | ((c & 0xF000) >>> 12);
403 bs[1] = 0x80 | ((c & 0xFC0) >>> 6);
404 bs[2] = 0x80 | (c & 0x3F);
407 bs[0] = 0xC0 | ((c & 0x7C0) >>> 6);
408 bs[1] = 0x80 | (c & 0x3F);
413 for(var j=0; j<bs.length; j++){
415 var hex = nibble_to_hex((b & 0xF0) >>> 4)
416 + nibble_to_hex(b &0x0F);
425 * 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]}.
426 * @param {String} string
427 * @param {Boolean} overwrite (optional) Items of the same name will overwrite previous values instead of creating an an array (Defaults to false).
428 * @return {Object} A literal with members
430 urlDecode : function(string, overwrite){
431 if(!string || !string.length){
435 var pairs = string.split('&');
436 var pair, name, value;
437 for(var i = 0, len = pairs.length; i < len; i++){
438 pair = pairs[i].split('=');
439 name = decodeURIComponent(pair[0]);
440 value = decodeURIComponent(pair[1]);
441 if(overwrite !== true){
442 if(typeof obj[name] == "undefined"){
444 }else if(typeof obj[name] == "string"){
445 obj[name] = [obj[name]];
446 obj[name].push(value);
448 obj[name].push(value);
458 * Iterates an array calling the passed function with each item, stopping if your function returns false. If the
459 * passed array is not really an array, your function is called once with it.
460 * The supplied function is called with (Object item, Number index, Array allItems).
461 * @param {Array/NodeList/Mixed} array
462 * @param {Function} fn
463 * @param {Object} scope
465 each : function(array, fn, scope){
466 if(typeof array.length == "undefined" || typeof array == "string"){
469 for(var i = 0, len = array.length; i < len; i++){
470 if(fn.call(scope || array[i], array[i], i, array) === false){ return i; };
475 combine : function(){
476 var as = arguments, l = as.length, r = [];
477 for(var i = 0; i < l; i++){
479 if(a instanceof Array){
481 }else if(a.length !== undefined && !a.substr){
482 r = r.concat(Array.prototype.slice.call(a, 0));
491 * Escapes the passed string for use in a regular expression
492 * @param {String} str
495 escapeRe : function(s) {
496 return s.replace(/([.*+?^${}()|[\]\/\\])/g, "\\$1");
500 callback : function(cb, scope, args, delay){
501 if(typeof cb == "function"){
503 cb.defer(delay, scope, args || []);
505 cb.apply(scope, args || []);
511 * Return the dom node for the passed string (id), dom node, or Roo.Element
512 * @param {String/HTMLElement/Roo.Element} el
513 * @return HTMLElement
515 getDom : function(el){
519 return el.dom ? el.dom : (typeof el == 'string' ? document.getElementById(el) : el);
523 * Shorthand for {@link Roo.ComponentMgr#get}
525 * @return Roo.Component
527 getCmp : function(id){
528 return Roo.ComponentMgr.get(id);
531 num : function(v, defaultValue){
532 if(typeof v != 'number'){
538 destroy : function(){
539 for(var i = 0, a = arguments, len = a.length; i < len; i++) {
543 as.removeAllListeners();
547 if(typeof as.purgeListeners == 'function'){
550 if(typeof as.destroy == 'function'){
557 // inpired by a similar function in mootools library
559 * Returns the type of object that is passed in. If the object passed in is null or undefined it
560 * return false otherwise it returns one of the following values:<ul>
561 * <li><b>string</b>: If the object passed is a string</li>
562 * <li><b>number</b>: If the object passed is a number</li>
563 * <li><b>boolean</b>: If the object passed is a boolean value</li>
564 * <li><b>function</b>: If the object passed is a function reference</li>
565 * <li><b>object</b>: If the object passed is an object</li>
566 * <li><b>array</b>: If the object passed is an array</li>
567 * <li><b>regexp</b>: If the object passed is a regular expression</li>
568 * <li><b>element</b>: If the object passed is a DOM Element</li>
569 * <li><b>nodelist</b>: If the object passed is a DOM NodeList</li>
570 * <li><b>textnode</b>: If the object passed is a DOM text node and contains something other than whitespace</li>
571 * <li><b>whitespace</b>: If the object passed is a DOM text node and contains only whitespace</li>
572 * @param {Mixed} object
576 if(o === undefined || o === null){
583 if(t == 'object' && o.nodeName) {
585 case 1: return 'element';
586 case 3: return (/\S/).test(o.nodeValue) ? 'textnode' : 'whitespace';
589 if(t == 'object' || t == 'function') {
590 switch(o.constructor) {
591 case Array: return 'array';
592 case RegExp: return 'regexp';
594 if(typeof o.length == 'number' && typeof o.item == 'function') {
602 * Returns true if the passed value is null, undefined or an empty string (optional).
603 * @param {Mixed} value The value to test
604 * @param {Boolean} allowBlank (optional) Pass true if an empty string is not considered empty
607 isEmpty : function(v, allowBlank){
608 return v === null || v === undefined || (!allowBlank ? v === '' : false);
616 isFirefox : isFirefox,
626 isBorderBox : isBorderBox,
628 isWindows : isWindows,
639 * By default, Ext intelligently decides whether floating elements should be shimmed. If you are using flash,
640 * you may want to set this to true.
643 useShims : ((isIE && !isIE7) || (isGecko && isMac)),
648 * Selects a single element as a Roo Element
649 * This is about as close as you can get to jQuery's $('do crazy stuff')
650 * @param {String} selector The selector/xpath query
651 * @param {Node} root (optional) The start of the query (defaults to document).
652 * @return {Roo.Element}
654 selectNode : function(selector, root)
656 var node = Roo.DomQuery.selectNode(selector,root);
657 return node ? Roo.get(node) : new Roo.Element(false);
665 Roo.namespace("Roo", "Roo.util", "Roo.grid", "Roo.dd", "Roo.tree", "Roo.data",
666 "Roo.form", "Roo.menu", "Roo.state", "Roo.lib", "Roo.layout",
669 "Roo.bootstrap.dash");
672 * Ext JS Library 1.1.1
673 * Copyright(c) 2006-2007, Ext JS, LLC.
675 * Originally Released Under LGPL - original licence link has changed is not relivant.
678 * <script type="text/javascript">
682 // wrappedn so fnCleanup is not in global scope...
684 function fnCleanUp() {
685 var p = Function.prototype;
686 delete p.createSequence;
688 delete p.createDelegate;
689 delete p.createCallback;
690 delete p.createInterceptor;
692 window.detachEvent("onunload", fnCleanUp);
694 window.attachEvent("onunload", fnCleanUp);
701 * These functions are available on every Function object (any JavaScript function).
703 Roo.apply(Function.prototype, {
705 * Creates a callback that passes arguments[0], arguments[1], arguments[2], ...
706 * Call directly on any function. Example: <code>myFunction.createCallback(myarg, myarg2)</code>
707 * Will create a function that is bound to those 2 args.
708 * @return {Function} The new function
710 createCallback : function(/*args...*/){
711 // make args available, in function below
712 var args = arguments;
715 return method.apply(window, args);
720 * Creates a delegate (callback) that sets the scope to obj.
721 * Call directly on any function. Example: <code>this.myFunction.createDelegate(this)</code>
722 * Will create a function that is automatically scoped to this.
723 * @param {Object} obj (optional) The object for which the scope is set
724 * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
725 * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
726 * if a number the args are inserted at the specified position
727 * @return {Function} The new function
729 createDelegate : function(obj, args, appendArgs){
732 var callArgs = args || arguments;
733 if(appendArgs === true){
734 callArgs = Array.prototype.slice.call(arguments, 0);
735 callArgs = callArgs.concat(args);
736 }else if(typeof appendArgs == "number"){
737 callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first
738 var applyArgs = [appendArgs, 0].concat(args); // create method call params
739 Array.prototype.splice.apply(callArgs, applyArgs); // splice them in
741 return method.apply(obj || window, callArgs);
746 * Calls this function after the number of millseconds specified.
747 * @param {Number} millis The number of milliseconds for the setTimeout call (if 0 the function is executed immediately)
748 * @param {Object} obj (optional) The object for which the scope is set
749 * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
750 * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
751 * if a number the args are inserted at the specified position
752 * @return {Number} The timeout id that can be used with clearTimeout
754 defer : function(millis, obj, args, appendArgs){
755 var fn = this.createDelegate(obj, args, appendArgs);
757 return setTimeout(fn, millis);
763 * Create a combined function call sequence of the original function + the passed function.
764 * The resulting function returns the results of the original function.
765 * The passed fcn is called with the parameters of the original function
766 * @param {Function} fcn The function to sequence
767 * @param {Object} scope (optional) The scope of the passed fcn (Defaults to scope of original function or window)
768 * @return {Function} The new function
770 createSequence : function(fcn, scope){
771 if(typeof fcn != "function"){
776 var retval = method.apply(this || window, arguments);
777 fcn.apply(scope || this || window, arguments);
783 * Creates an interceptor function. The passed fcn is called before the original one. If it returns false, the original one is not called.
784 * The resulting function returns the results of the original function.
785 * The passed fcn is called with the parameters of the original function.
787 * @param {Function} fcn The function to call before the original
788 * @param {Object} scope (optional) The scope of the passed fcn (Defaults to scope of original function or window)
789 * @return {Function} The new function
791 createInterceptor : function(fcn, scope){
792 if(typeof fcn != "function"){
799 if(fcn.apply(scope || this || window, arguments) === false){
802 return method.apply(this || window, arguments);
808 * Ext JS Library 1.1.1
809 * Copyright(c) 2006-2007, Ext JS, LLC.
811 * Originally Released Under LGPL - original licence link has changed is not relivant.
814 * <script type="text/javascript">
817 Roo.applyIf(String, {
822 * Escapes the passed string for ' and \
823 * @param {String} string The string to escape
824 * @return {String} The escaped string
827 escape : function(string) {
828 return string.replace(/('|\\)/g, "\\$1");
832 * Pads the left side of a string with a specified character. This is especially useful
833 * for normalizing number and date strings. Example usage:
835 var s = String.leftPad('123', 5, '0');
836 // s now contains the string: '00123'
838 * @param {String} string The original string
839 * @param {Number} size The total length of the output string
840 * @param {String} char (optional) The character with which to pad the original string (defaults to empty string " ")
841 * @return {String} The padded string
844 leftPad : function (val, size, ch) {
845 var result = new String(val);
846 if(ch === null || ch === undefined || ch === '') {
849 while (result.length < size) {
850 result = ch + result;
856 * Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens. Each
857 * token must be unique, and must increment in the format {0}, {1}, etc. Example usage:
859 var cls = 'my-class', text = 'Some text';
860 var s = String.format('<div class="{0}">{1}</div>', cls, text);
861 // s now contains the string: '<div class="my-class">Some text</div>'
863 * @param {String} string The tokenized string to be formatted
864 * @param {String} value1 The value to replace token {0}
865 * @param {String} value2 Etc...
866 * @return {String} The formatted string
869 format : function(format){
870 var args = Array.prototype.slice.call(arguments, 1);
871 return format.replace(/\{(\d+)\}/g, function(m, i){
872 return Roo.util.Format.htmlEncode(args[i]);
878 * Utility function that allows you to easily switch a string between two alternating values. The passed value
879 * is compared to the current string, and if they are equal, the other value that was passed in is returned. If
880 * they are already different, the first value passed in is returned. Note that this method returns the new value
881 * but does not change the current string.
883 // alternate sort directions
884 sort = sort.toggle('ASC', 'DESC');
886 // instead of conditional logic:
887 sort = (sort == 'ASC' ? 'DESC' : 'ASC');
889 * @param {String} value The value to compare to the current string
890 * @param {String} other The new value to use if the string already equals the first value passed in
891 * @return {String} The new value
894 String.prototype.toggle = function(value, other){
895 return this == value ? other : value;
898 * Ext JS Library 1.1.1
899 * Copyright(c) 2006-2007, Ext JS, LLC.
901 * Originally Released Under LGPL - original licence link has changed is not relivant.
904 * <script type="text/javascript">
910 Roo.applyIf(Number.prototype, {
912 * Checks whether or not the current number is within a desired range. If the number is already within the
913 * range it is returned, otherwise the min or max value is returned depending on which side of the range is
914 * exceeded. Note that this method returns the constrained value but does not change the current number.
915 * @param {Number} min The minimum number in the range
916 * @param {Number} max The maximum number in the range
917 * @return {Number} The constrained value if outside the range, otherwise the current value
919 constrain : function(min, max){
920 return Math.min(Math.max(this, min), max);
924 * Ext JS Library 1.1.1
925 * Copyright(c) 2006-2007, Ext JS, LLC.
927 * Originally Released Under LGPL - original licence link has changed is not relivant.
930 * <script type="text/javascript">
935 Roo.applyIf(Array.prototype, {
938 * Checks whether or not the specified object exists in the array.
939 * @param {Object} o The object to check for
940 * @return {Number} The index of o in the array (or -1 if it is not found)
942 indexOf : function(o){
943 for (var i = 0, len = this.length; i < len; i++){
944 if(this[i] == o) return i;
950 * Removes the specified object from the array. If the object is not found nothing happens.
951 * @param {Object} o The object to remove
953 remove : function(o){
954 var index = this.indexOf(o);
956 this.splice(index, 1);
960 * Map (JS 1.6 compatibility)
961 * @param {Function} function to call
965 var len = this.length >>> 0;
966 if (typeof fun != "function")
967 throw new TypeError();
969 var res = new Array(len);
970 var thisp = arguments[1];
971 for (var i = 0; i < len; i++)
974 res[i] = fun.call(thisp, this[i], i, this);
985 * Ext JS Library 1.1.1
986 * Copyright(c) 2006-2007, Ext JS, LLC.
988 * Originally Released Under LGPL - original licence link has changed is not relivant.
991 * <script type="text/javascript">
997 * The date parsing and format syntax is a subset of
998 * <a href="http://www.php.net/date">PHP's date() function</a>, and the formats that are
999 * supported will provide results equivalent to their PHP versions.
1001 * Following is the list of all currently supported formats:
1004 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'
1006 Format Output Description
1007 ------ ---------- --------------------------------------------------------------
1008 d 10 Day of the month, 2 digits with leading zeros
1009 D Wed A textual representation of a day, three letters
1010 j 10 Day of the month without leading zeros
1011 l Wednesday A full textual representation of the day of the week
1012 S th English ordinal day of month suffix, 2 chars (use with j)
1013 w 3 Numeric representation of the day of the week
1014 z 9 The julian date, or day of the year (0-365)
1015 W 01 ISO-8601 2-digit week number of year, weeks starting on Monday (00-52)
1016 F January A full textual representation of the month
1017 m 01 Numeric representation of a month, with leading zeros
1018 M Jan Month name abbreviation, three letters
1019 n 1 Numeric representation of a month, without leading zeros
1020 t 31 Number of days in the given month
1021 L 0 Whether it's a leap year (1 if it is a leap year, else 0)
1022 Y 2007 A full numeric representation of a year, 4 digits
1023 y 07 A two digit representation of a year
1024 a pm Lowercase Ante meridiem and Post meridiem
1025 A PM Uppercase Ante meridiem and Post meridiem
1026 g 3 12-hour format of an hour without leading zeros
1027 G 15 24-hour format of an hour without leading zeros
1028 h 03 12-hour format of an hour with leading zeros
1029 H 15 24-hour format of an hour with leading zeros
1030 i 05 Minutes with leading zeros
1031 s 01 Seconds, with leading zeros
1032 O -0600 Difference to Greenwich time (GMT) in hours (Allows +08, without minutes)
1033 P -06:00 Difference to Greenwich time (GMT) with colon between hours and minutes
1034 T CST Timezone setting of the machine running the code
1035 Z -21600 Timezone offset in seconds (negative if west of UTC, positive if east)
1038 * Example usage (note that you must escape format specifiers with '\\' to render them as character literals):
1040 var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
1041 document.write(dt.format('Y-m-d')); //2007-01-10
1042 document.write(dt.format('F j, Y, g:i a')); //January 10, 2007, 3:05 pm
1043 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
1046 * Here are some standard date/time patterns that you might find helpful. They
1047 * are not part of the source of Date.js, but to use them you can simply copy this
1048 * block of code into any script that is included after Date.js and they will also become
1049 * globally available on the Date object. Feel free to add or remove patterns as needed in your code.
1052 ISO8601Long:"Y-m-d H:i:s",
1053 ISO8601Short:"Y-m-d",
1055 LongDate: "l, F d, Y",
1056 FullDateTime: "l, F d, Y g:i:s A",
1059 LongTime: "g:i:s A",
1060 SortableDateTime: "Y-m-d\\TH:i:s",
1061 UniversalSortableDateTime: "Y-m-d H:i:sO",
1068 var dt = new Date();
1069 document.write(dt.format(Date.patterns.ShortDate));
1074 * Most of the date-formatting functions below are the excellent work of Baron Schwartz.
1075 * They generate precompiled functions from date formats instead of parsing and
1076 * processing the pattern every time you format a date. These functions are available
1077 * on every Date object (any javascript function).
1079 * The original article and download are here:
1080 * http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/
1087 Returns the number of milliseconds between this date and date
1088 @param {Date} date (optional) Defaults to now
1089 @return {Number} The diff in milliseconds
1090 @member Date getElapsed
1092 Date.prototype.getElapsed = function(date) {
1093 return Math.abs((date || new Date()).getTime()-this.getTime());
1095 // was in date file..
1099 Date.parseFunctions = {count:0};
1101 Date.parseRegexes = [];
1103 Date.formatFunctions = {count:0};
1106 Date.prototype.dateFormat = function(format) {
1107 if (Date.formatFunctions[format] == null) {
1108 Date.createNewFormat(format);
1110 var func = Date.formatFunctions[format];
1111 return this[func]();
1116 * Formats a date given the supplied format string
1117 * @param {String} format The format string
1118 * @return {String} The formatted date
1121 Date.prototype.format = Date.prototype.dateFormat;
1124 Date.createNewFormat = function(format) {
1125 var funcName = "format" + Date.formatFunctions.count++;
1126 Date.formatFunctions[format] = funcName;
1127 var code = "Date.prototype." + funcName + " = function(){return ";
1128 var special = false;
1130 for (var i = 0; i < format.length; ++i) {
1131 ch = format.charAt(i);
1132 if (!special && ch == "\\") {
1137 code += "'" + String.escape(ch) + "' + ";
1140 code += Date.getFormatCode(ch);
1143 /** eval:var:zzzzzzzzzzzzz */
1144 eval(code.substring(0, code.length - 3) + ";}");
1148 Date.getFormatCode = function(character) {
1149 switch (character) {
1151 return "String.leftPad(this.getDate(), 2, '0') + ";
1153 return "Date.dayNames[this.getDay()].substring(0, 3) + ";
1155 return "this.getDate() + ";
1157 return "Date.dayNames[this.getDay()] + ";
1159 return "this.getSuffix() + ";
1161 return "this.getDay() + ";
1163 return "this.getDayOfYear() + ";
1165 return "this.getWeekOfYear() + ";
1167 return "Date.monthNames[this.getMonth()] + ";
1169 return "String.leftPad(this.getMonth() + 1, 2, '0') + ";
1171 return "Date.monthNames[this.getMonth()].substring(0, 3) + ";
1173 return "(this.getMonth() + 1) + ";
1175 return "this.getDaysInMonth() + ";
1177 return "(this.isLeapYear() ? 1 : 0) + ";
1179 return "this.getFullYear() + ";
1181 return "('' + this.getFullYear()).substring(2, 4) + ";
1183 return "(this.getHours() < 12 ? 'am' : 'pm') + ";
1185 return "(this.getHours() < 12 ? 'AM' : 'PM') + ";
1187 return "((this.getHours() % 12) ? this.getHours() % 12 : 12) + ";
1189 return "this.getHours() + ";
1191 return "String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0') + ";
1193 return "String.leftPad(this.getHours(), 2, '0') + ";
1195 return "String.leftPad(this.getMinutes(), 2, '0') + ";
1197 return "String.leftPad(this.getSeconds(), 2, '0') + ";
1199 return "this.getGMTOffset() + ";
1201 return "this.getGMTColonOffset() + ";
1203 return "this.getTimezone() + ";
1205 return "(this.getTimezoneOffset() * -60) + ";
1207 return "'" + String.escape(character) + "' + ";
1212 * Parses the passed string using the specified format. Note that this function expects dates in normal calendar
1213 * format, meaning that months are 1-based (1 = January) and not zero-based like in JavaScript dates. Any part of
1214 * the date format that is not specified will default to the current date value for that part. Time parts can also
1215 * be specified, but default to 0. Keep in mind that the input date string must precisely match the specified format
1216 * string or the parse operation will fail.
1219 //dt = Fri May 25 2007 (current date)
1220 var dt = new Date();
1222 //dt = Thu May 25 2006 (today's month/day in 2006)
1223 dt = Date.parseDate("2006", "Y");
1225 //dt = Sun Jan 15 2006 (all date parts specified)
1226 dt = Date.parseDate("2006-1-15", "Y-m-d");
1228 //dt = Sun Jan 15 2006 15:20:01 GMT-0600 (CST)
1229 dt = Date.parseDate("2006-1-15 3:20:01 PM", "Y-m-d h:i:s A" );
1231 * @param {String} input The unparsed date as a string
1232 * @param {String} format The format the date is in
1233 * @return {Date} The parsed date
1236 Date.parseDate = function(input, format) {
1237 if (Date.parseFunctions[format] == null) {
1238 Date.createParser(format);
1240 var func = Date.parseFunctions[format];
1241 return Date[func](input);
1247 Date.createParser = function(format) {
1248 var funcName = "parse" + Date.parseFunctions.count++;
1249 var regexNum = Date.parseRegexes.length;
1250 var currentGroup = 1;
1251 Date.parseFunctions[format] = funcName;
1253 var code = "Date." + funcName + " = function(input){\n"
1254 + "var y = -1, m = -1, d = -1, h = -1, i = -1, s = -1, o, z, v;\n"
1255 + "var d = new Date();\n"
1256 + "y = d.getFullYear();\n"
1257 + "m = d.getMonth();\n"
1258 + "d = d.getDate();\n"
1259 + "if (typeof(input) !== 'string') { input = input.toString(); }\n"
1260 + "var results = input.match(Date.parseRegexes[" + regexNum + "]);\n"
1261 + "if (results && results.length > 0) {";
1264 var special = false;
1266 for (var i = 0; i < format.length; ++i) {
1267 ch = format.charAt(i);
1268 if (!special && ch == "\\") {
1273 regex += String.escape(ch);
1276 var obj = Date.formatCodeToRegex(ch, currentGroup);
1277 currentGroup += obj.g;
1279 if (obj.g && obj.c) {
1285 code += "if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0)\n"
1286 + "{v = new Date(y, m, d, h, i, s);}\n"
1287 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0)\n"
1288 + "{v = new Date(y, m, d, h, i);}\n"
1289 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0)\n"
1290 + "{v = new Date(y, m, d, h);}\n"
1291 + "else if (y >= 0 && m >= 0 && d > 0)\n"
1292 + "{v = new Date(y, m, d);}\n"
1293 + "else if (y >= 0 && m >= 0)\n"
1294 + "{v = new Date(y, m);}\n"
1295 + "else if (y >= 0)\n"
1296 + "{v = new Date(y);}\n"
1297 + "}return (v && (z || o))?\n" // favour UTC offset over GMT offset
1298 + " ((z)? v.add(Date.SECOND, (v.getTimezoneOffset() * 60) + (z*1)) :\n" // reset to UTC, then add offset
1299 + " v.add(Date.HOUR, (v.getGMTOffset() / 100) + (o / -100))) : v\n" // reset to GMT, then add offset
1302 Date.parseRegexes[regexNum] = new RegExp("^" + regex + "$");
1303 /** eval:var:zzzzzzzzzzzzz */
1308 Date.formatCodeToRegex = function(character, currentGroup) {
1309 switch (character) {
1313 s:"(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)"};
1316 c:"d = parseInt(results[" + currentGroup + "], 10);\n",
1317 s:"(\\d{1,2})"}; // day of month without leading zeroes
1320 c:"d = parseInt(results[" + currentGroup + "], 10);\n",
1321 s:"(\\d{2})"}; // day of month with leading zeroes
1325 s:"(?:" + Date.dayNames.join("|") + ")"};
1329 s:"(?:st|nd|rd|th)"};
1344 c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "].substring(0, 3)], 10);\n",
1345 s:"(" + Date.monthNames.join("|") + ")"};
1348 c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "]], 10);\n",
1349 s:"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)"};
1352 c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
1353 s:"(\\d{1,2})"}; // Numeric representation of a month, without leading zeros
1356 c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
1357 s:"(\\d{2})"}; // Numeric representation of a month, with leading zeros
1368 c:"y = parseInt(results[" + currentGroup + "], 10);\n",
1372 c:"var ty = parseInt(results[" + currentGroup + "], 10);\n"
1373 + "y = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n",
1377 c:"if (results[" + currentGroup + "] == 'am') {\n"
1378 + "if (h == 12) { h = 0; }\n"
1379 + "} else { if (h < 12) { h += 12; }}",
1383 c:"if (results[" + currentGroup + "] == 'AM') {\n"
1384 + "if (h == 12) { h = 0; }\n"
1385 + "} else { if (h < 12) { h += 12; }}",
1390 c:"h = parseInt(results[" + currentGroup + "], 10);\n",
1391 s:"(\\d{1,2})"}; // 12/24-hr format format of an hour without leading zeroes
1395 c:"h = parseInt(results[" + currentGroup + "], 10);\n",
1396 s:"(\\d{2})"}; // 12/24-hr format format of an hour with leading zeroes
1399 c:"i = parseInt(results[" + currentGroup + "], 10);\n",
1403 c:"s = parseInt(results[" + currentGroup + "], 10);\n",
1408 "o = results[", currentGroup, "];\n",
1409 "var sn = o.substring(0,1);\n", // get + / - sign
1410 "var hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60);\n", // get hours (performs minutes-to-hour conversion also)
1411 "var mn = o.substring(3,5) % 60;\n", // get minutes
1412 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n", // -12hrs <= GMT offset <= 14hrs
1413 " (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"
1415 s:"([+\-]\\d{2,4})"};
1421 "o = results[", currentGroup, "];\n",
1422 "var sn = o.substring(0,1);\n",
1423 "var hr = o.substring(1,3)*1 + Math.floor(o.substring(4,6) / 60);\n",
1424 "var mn = o.substring(4,6) % 60;\n",
1425 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n",
1426 " (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"
1432 s:"[A-Z]{1,4}"}; // timezone abbrev. may be between 1 - 4 chars
1435 c:"z = results[" + currentGroup + "];\n" // -43200 <= UTC offset <= 50400
1436 + "z = (-43200 <= z*1 && z*1 <= 50400)? z : null;\n",
1437 s:"([+\-]?\\d{1,5})"}; // leading '+' sign is optional for UTC offset
1441 s:String.escape(character)};
1446 * Get the timezone abbreviation of the current date (equivalent to the format specifier 'T').
1447 * @return {String} The abbreviated timezone name (e.g. 'CST')
1449 Date.prototype.getTimezone = function() {
1450 return this.toString().replace(/^.*? ([A-Z]{1,4})[\-+][0-9]{4} .*$/, "$1");
1454 * Get the offset from GMT of the current date (equivalent to the format specifier 'O').
1455 * @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600')
1457 Date.prototype.getGMTOffset = function() {
1458 return (this.getTimezoneOffset() > 0 ? "-" : "+")
1459 + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
1460 + String.leftPad(this.getTimezoneOffset() % 60, 2, "0");
1464 * Get the offset from GMT of the current date (equivalent to the format specifier 'P').
1465 * @return {String} 2-characters representing hours and 2-characters representing minutes
1466 * seperated by a colon and prefixed with + or - (e.g. '-06:00')
1468 Date.prototype.getGMTColonOffset = function() {
1469 return (this.getTimezoneOffset() > 0 ? "-" : "+")
1470 + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
1472 + String.leftPad(this.getTimezoneOffset() %60, 2, "0");
1476 * Get the numeric day number of the year, adjusted for leap year.
1477 * @return {Number} 0 through 364 (365 in leap years)
1479 Date.prototype.getDayOfYear = function() {
1481 Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
1482 for (var i = 0; i < this.getMonth(); ++i) {
1483 num += Date.daysInMonth[i];
1485 return num + this.getDate() - 1;
1489 * Get the string representation of the numeric week number of the year
1490 * (equivalent to the format specifier 'W').
1491 * @return {String} '00' through '52'
1493 Date.prototype.getWeekOfYear = function() {
1494 // Skip to Thursday of this week
1495 var now = this.getDayOfYear() + (4 - this.getDay());
1496 // Find the first Thursday of the year
1497 var jan1 = new Date(this.getFullYear(), 0, 1);
1498 var then = (7 - jan1.getDay() + 4);
1499 return String.leftPad(((now - then) / 7) + 1, 2, "0");
1503 * Whether or not the current date is in a leap year.
1504 * @return {Boolean} True if the current date is in a leap year, else false
1506 Date.prototype.isLeapYear = function() {
1507 var year = this.getFullYear();
1508 return ((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
1512 * Get the first day of the current month, adjusted for leap year. The returned value
1513 * is the numeric day index within the week (0-6) which can be used in conjunction with
1514 * the {@link #monthNames} array to retrieve the textual day name.
1517 var dt = new Date('1/10/2007');
1518 document.write(Date.dayNames[dt.getFirstDayOfMonth()]); //output: 'Monday'
1520 * @return {Number} The day number (0-6)
1522 Date.prototype.getFirstDayOfMonth = function() {
1523 var day = (this.getDay() - (this.getDate() - 1)) % 7;
1524 return (day < 0) ? (day + 7) : day;
1528 * Get the last day of the current month, adjusted for leap year. The returned value
1529 * is the numeric day index within the week (0-6) which can be used in conjunction with
1530 * the {@link #monthNames} array to retrieve the textual day name.
1533 var dt = new Date('1/10/2007');
1534 document.write(Date.dayNames[dt.getLastDayOfMonth()]); //output: 'Wednesday'
1536 * @return {Number} The day number (0-6)
1538 Date.prototype.getLastDayOfMonth = function() {
1539 var day = (this.getDay() + (Date.daysInMonth[this.getMonth()] - this.getDate())) % 7;
1540 return (day < 0) ? (day + 7) : day;
1545 * Get the first date of this date's month
1548 Date.prototype.getFirstDateOfMonth = function() {
1549 return new Date(this.getFullYear(), this.getMonth(), 1);
1553 * Get the last date of this date's month
1556 Date.prototype.getLastDateOfMonth = function() {
1557 return new Date(this.getFullYear(), this.getMonth(), this.getDaysInMonth());
1560 * Get the number of days in the current month, adjusted for leap year.
1561 * @return {Number} The number of days in the month
1563 Date.prototype.getDaysInMonth = function() {
1564 Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
1565 return Date.daysInMonth[this.getMonth()];
1569 * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S').
1570 * @return {String} 'st, 'nd', 'rd' or 'th'
1572 Date.prototype.getSuffix = function() {
1573 switch (this.getDate()) {
1590 Date.daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
1593 * An array of textual month names.
1594 * Override these values for international dates, for example...
1595 * Date.monthNames = ['JanInYourLang', 'FebInYourLang', ...];
1614 * An array of textual day names.
1615 * Override these values for international dates, for example...
1616 * Date.dayNames = ['SundayInYourLang', 'MondayInYourLang', ...];
1632 Date.monthNumbers = {
1647 * Creates and returns a new Date instance with the exact same date value as the called instance.
1648 * Dates are copied and passed by reference, so if a copied date variable is modified later, the original
1649 * variable will also be changed. When the intention is to create a new variable that will not
1650 * modify the original instance, you should create a clone.
1652 * Example of correctly cloning a date:
1655 var orig = new Date('10/1/2006');
1658 document.write(orig); //returns 'Thu Oct 05 2006'!
1661 var orig = new Date('10/1/2006');
1662 var copy = orig.clone();
1664 document.write(orig); //returns 'Thu Oct 01 2006'
1666 * @return {Date} The new Date instance
1668 Date.prototype.clone = function() {
1669 return new Date(this.getTime());
1673 * Clears any time information from this date
1674 @param {Boolean} clone true to create a clone of this date, clear the time and return it
1675 @return {Date} this or the clone
1677 Date.prototype.clearTime = function(clone){
1679 return this.clone().clearTime();
1684 this.setMilliseconds(0);
1689 // safari setMonth is broken
1691 Date.brokenSetMonth = Date.prototype.setMonth;
1692 Date.prototype.setMonth = function(num){
1694 var n = Math.ceil(-num);
1695 var back_year = Math.ceil(n/12);
1696 var month = (n % 12) ? 12 - n % 12 : 0 ;
1697 this.setFullYear(this.getFullYear() - back_year);
1698 return Date.brokenSetMonth.call(this, month);
1700 return Date.brokenSetMonth.apply(this, arguments);
1705 /** Date interval constant
1709 /** Date interval constant
1713 /** Date interval constant
1717 /** Date interval constant
1721 /** Date interval constant
1725 /** Date interval constant
1729 /** Date interval constant
1735 * Provides a convenient method of performing basic date arithmetic. This method
1736 * does not modify the Date instance being called - it creates and returns
1737 * a new Date instance containing the resulting date value.
1742 var dt = new Date('10/29/2006').add(Date.DAY, 5);
1743 document.write(dt); //returns 'Fri Oct 06 2006 00:00:00'
1745 //Negative values will subtract correctly:
1746 var dt2 = new Date('10/1/2006').add(Date.DAY, -5);
1747 document.write(dt2); //returns 'Tue Sep 26 2006 00:00:00'
1749 //You can even chain several calls together in one line!
1750 var dt3 = new Date('10/1/2006').add(Date.DAY, 5).add(Date.HOUR, 8).add(Date.MINUTE, -30);
1751 document.write(dt3); //returns 'Fri Oct 06 2006 07:30:00'
1754 * @param {String} interval A valid date interval enum value
1755 * @param {Number} value The amount to add to the current date
1756 * @return {Date} The new Date instance
1758 Date.prototype.add = function(interval, value){
1759 var d = this.clone();
1760 if (!interval || value === 0) return d;
1761 switch(interval.toLowerCase()){
1763 d.setMilliseconds(this.getMilliseconds() + value);
1766 d.setSeconds(this.getSeconds() + value);
1769 d.setMinutes(this.getMinutes() + value);
1772 d.setHours(this.getHours() + value);
1775 d.setDate(this.getDate() + value);
1778 var day = this.getDate();
1780 day = Math.min(day, this.getFirstDateOfMonth().add('mo', value).getLastDateOfMonth().getDate());
1783 d.setMonth(this.getMonth() + value);
1786 d.setFullYear(this.getFullYear() + value);
1793 * Ext JS Library 1.1.1
1794 * Copyright(c) 2006-2007, Ext JS, LLC.
1796 * Originally Released Under LGPL - original licence link has changed is not relivant.
1799 * <script type="text/javascript">
1803 * @class Roo.lib.Dom
1806 * Dom utils (from YIU afaik)
1811 * Get the view width
1812 * @param {Boolean} full True will get the full document, otherwise it's the view width
1813 * @return {Number} The width
1816 getViewWidth : function(full) {
1817 return full ? this.getDocumentWidth() : this.getViewportWidth();
1820 * Get the view height
1821 * @param {Boolean} full True will get the full document, otherwise it's the view height
1822 * @return {Number} The height
1824 getViewHeight : function(full) {
1825 return full ? this.getDocumentHeight() : this.getViewportHeight();
1828 getDocumentHeight: function() {
1829 var scrollHeight = (document.compatMode != "CSS1Compat") ? document.body.scrollHeight : document.documentElement.scrollHeight;
1830 return Math.max(scrollHeight, this.getViewportHeight());
1833 getDocumentWidth: function() {
1834 var scrollWidth = (document.compatMode != "CSS1Compat") ? document.body.scrollWidth : document.documentElement.scrollWidth;
1835 return Math.max(scrollWidth, this.getViewportWidth());
1838 getViewportHeight: function() {
1839 var height = self.innerHeight;
1840 var mode = document.compatMode;
1842 if ((mode || Roo.isIE) && !Roo.isOpera) {
1843 height = (mode == "CSS1Compat") ?
1844 document.documentElement.clientHeight :
1845 document.body.clientHeight;
1851 getViewportWidth: function() {
1852 var width = self.innerWidth;
1853 var mode = document.compatMode;
1855 if (mode || Roo.isIE) {
1856 width = (mode == "CSS1Compat") ?
1857 document.documentElement.clientWidth :
1858 document.body.clientWidth;
1863 isAncestor : function(p, c) {
1870 if (p.contains && !Roo.isSafari) {
1871 return p.contains(c);
1872 } else if (p.compareDocumentPosition) {
1873 return !!(p.compareDocumentPosition(c) & 16);
1875 var parent = c.parentNode;
1880 else if (!parent.tagName || parent.tagName.toUpperCase() == "HTML") {
1883 parent = parent.parentNode;
1889 getRegion : function(el) {
1890 return Roo.lib.Region.getRegion(el);
1893 getY : function(el) {
1894 return this.getXY(el)[1];
1897 getX : function(el) {
1898 return this.getXY(el)[0];
1901 getXY : function(el) {
1902 var p, pe, b, scroll, bd = document.body;
1903 el = Roo.getDom(el);
1904 var fly = Roo.lib.AnimBase.fly;
1905 if (el.getBoundingClientRect) {
1906 b = el.getBoundingClientRect();
1907 scroll = fly(document).getScroll();
1908 return [b.left + scroll.left, b.top + scroll.top];
1914 var hasAbsolute = fly(el).getStyle("position") == "absolute";
1921 if (!hasAbsolute && fly(p).getStyle("position") == "absolute") {
1928 var bt = parseInt(pe.getStyle("borderTopWidth"), 10) || 0;
1929 var bl = parseInt(pe.getStyle("borderLeftWidth"), 10) || 0;
1936 if (p != el && pe.getStyle('overflow') != 'visible') {
1944 if (Roo.isSafari && hasAbsolute) {
1949 if (Roo.isGecko && !hasAbsolute) {
1951 x += parseInt(dbd.getStyle("borderLeftWidth"), 10) || 0;
1952 y += parseInt(dbd.getStyle("borderTopWidth"), 10) || 0;
1956 while (p && p != bd) {
1957 if (!Roo.isOpera || (p.tagName != 'TR' && fly(p).getStyle("display") != "inline")) {
1969 setXY : function(el, xy) {
1970 el = Roo.fly(el, '_setXY');
1972 var pts = el.translatePoints(xy);
1973 if (xy[0] !== false) {
1974 el.dom.style.left = pts.left + "px";
1976 if (xy[1] !== false) {
1977 el.dom.style.top = pts.top + "px";
1981 setX : function(el, x) {
1982 this.setXY(el, [x, false]);
1985 setY : function(el, y) {
1986 this.setXY(el, [false, y]);
1990 * Portions of this file are based on pieces of Yahoo User Interface Library
1991 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
1992 * YUI licensed under the BSD License:
1993 * http://developer.yahoo.net/yui/license.txt
1994 * <script type="text/javascript">
1998 Roo.lib.Event = function() {
1999 var loadComplete = false;
2001 var unloadListeners = [];
2003 var onAvailStack = [];
2005 var lastError = null;
2018 startInterval: function() {
2019 if (!this._interval) {
2021 var callback = function() {
2022 self._tryPreloadAttach();
2024 this._interval = setInterval(callback, this.POLL_INTERVAL);
2029 onAvailable: function(p_id, p_fn, p_obj, p_override) {
2030 onAvailStack.push({ id: p_id,
2033 override: p_override,
2034 checkReady: false });
2036 retryCount = this.POLL_RETRYS;
2037 this.startInterval();
2041 addListener: function(el, eventName, fn) {
2042 el = Roo.getDom(el);
2047 if ("unload" == eventName) {
2048 unloadListeners[unloadListeners.length] =
2049 [el, eventName, fn];
2053 var wrappedFn = function(e) {
2054 return fn(Roo.lib.Event.getEvent(e));
2057 var li = [el, eventName, fn, wrappedFn];
2059 var index = listeners.length;
2060 listeners[index] = li;
2062 this.doAdd(el, eventName, wrappedFn, false);
2068 removeListener: function(el, eventName, fn) {
2071 el = Roo.getDom(el);
2074 return this.purgeElement(el, false, eventName);
2078 if ("unload" == eventName) {
2080 for (i = 0,len = unloadListeners.length; i < len; i++) {
2081 var li = unloadListeners[i];
2084 li[1] == eventName &&
2086 unloadListeners.splice(i, 1);
2094 var cacheItem = null;
2097 var index = arguments[3];
2099 if ("undefined" == typeof index) {
2100 index = this._getCacheIndex(el, eventName, fn);
2104 cacheItem = listeners[index];
2107 if (!el || !cacheItem) {
2111 this.doRemove(el, eventName, cacheItem[this.WFN], false);
2113 delete listeners[index][this.WFN];
2114 delete listeners[index][this.FN];
2115 listeners.splice(index, 1);
2122 getTarget: function(ev, resolveTextNode) {
2123 ev = ev.browserEvent || ev;
2124 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2125 var t = ev.target || ev.srcElement;
2126 return this.resolveTextNode(t);
2130 resolveTextNode: function(node) {
2131 if (Roo.isSafari && node && 3 == node.nodeType) {
2132 return node.parentNode;
2139 getPageX: function(ev) {
2140 ev = ev.browserEvent || ev;
2141 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2143 if (!x && 0 !== x) {
2144 x = ev.clientX || 0;
2147 x += this.getScroll()[1];
2155 getPageY: function(ev) {
2156 ev = ev.browserEvent || ev;
2157 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2159 if (!y && 0 !== y) {
2160 y = ev.clientY || 0;
2163 y += this.getScroll()[0];
2172 getXY: function(ev) {
2173 ev = ev.browserEvent || ev;
2174 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2175 return [this.getPageX(ev), this.getPageY(ev)];
2179 getRelatedTarget: function(ev) {
2180 ev = ev.browserEvent || ev;
2181 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2182 var t = ev.relatedTarget;
2184 if (ev.type == "mouseout") {
2186 } else if (ev.type == "mouseover") {
2191 return this.resolveTextNode(t);
2195 getTime: function(ev) {
2196 ev = ev.browserEvent || ev;
2197 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2199 var t = new Date().getTime();
2203 this.lastError = ex;
2212 stopEvent: function(ev) {
2213 this.stopPropagation(ev);
2214 this.preventDefault(ev);
2218 stopPropagation: function(ev) {
2219 ev = ev.browserEvent || ev;
2220 if (ev.stopPropagation) {
2221 ev.stopPropagation();
2223 ev.cancelBubble = true;
2228 preventDefault: function(ev) {
2229 ev = ev.browserEvent || ev;
2230 if(ev.preventDefault) {
2231 ev.preventDefault();
2233 ev.returnValue = false;
2238 getEvent: function(e) {
2239 var ev = e || window.event;
2241 var c = this.getEvent.caller;
2243 ev = c.arguments[0];
2244 if (ev && Event == ev.constructor) {
2254 getCharCode: function(ev) {
2255 ev = ev.browserEvent || ev;
2256 return ev.charCode || ev.keyCode || 0;
2260 _getCacheIndex: function(el, eventName, fn) {
2261 for (var i = 0,len = listeners.length; i < len; ++i) {
2262 var li = listeners[i];
2264 li[this.FN] == fn &&
2265 li[this.EL] == el &&
2266 li[this.TYPE] == eventName) {
2278 getEl: function(id) {
2279 return document.getElementById(id);
2283 clearCache: function() {
2287 _load: function(e) {
2288 loadComplete = true;
2289 var EU = Roo.lib.Event;
2293 EU.doRemove(window, "load", EU._load);
2298 _tryPreloadAttach: function() {
2307 var tryAgain = !loadComplete;
2309 tryAgain = (retryCount > 0);
2314 for (var i = 0,len = onAvailStack.length; i < len; ++i) {
2315 var item = onAvailStack[i];
2317 var el = this.getEl(item.id);
2320 if (!item.checkReady ||
2323 (document && document.body)) {
2326 if (item.override) {
2327 if (item.override === true) {
2330 scope = item.override;
2333 item.fn.call(scope, item.obj);
2334 onAvailStack[i] = null;
2337 notAvail.push(item);
2342 retryCount = (notAvail.length === 0) ? 0 : retryCount - 1;
2346 this.startInterval();
2348 clearInterval(this._interval);
2349 this._interval = null;
2352 this.locked = false;
2359 purgeElement: function(el, recurse, eventName) {
2360 var elListeners = this.getListeners(el, eventName);
2362 for (var i = 0,len = elListeners.length; i < len; ++i) {
2363 var l = elListeners[i];
2364 this.removeListener(el, l.type, l.fn);
2368 if (recurse && el && el.childNodes) {
2369 for (i = 0,len = el.childNodes.length; i < len; ++i) {
2370 this.purgeElement(el.childNodes[i], recurse, eventName);
2376 getListeners: function(el, eventName) {
2377 var results = [], searchLists;
2379 searchLists = [listeners, unloadListeners];
2380 } else if (eventName == "unload") {
2381 searchLists = [unloadListeners];
2383 searchLists = [listeners];
2386 for (var j = 0; j < searchLists.length; ++j) {
2387 var searchList = searchLists[j];
2388 if (searchList && searchList.length > 0) {
2389 for (var i = 0,len = searchList.length; i < len; ++i) {
2390 var l = searchList[i];
2391 if (l && l[this.EL] === el &&
2392 (!eventName || eventName === l[this.TYPE])) {
2397 adjust: l[this.ADJ_SCOPE],
2405 return (results.length) ? results : null;
2409 _unload: function(e) {
2411 var EU = Roo.lib.Event, i, j, l, len, index;
2413 for (i = 0,len = unloadListeners.length; i < len; ++i) {
2414 l = unloadListeners[i];
2417 if (l[EU.ADJ_SCOPE]) {
2418 if (l[EU.ADJ_SCOPE] === true) {
2421 scope = l[EU.ADJ_SCOPE];
2424 l[EU.FN].call(scope, EU.getEvent(e), l[EU.OBJ]);
2425 unloadListeners[i] = null;
2431 unloadListeners = null;
2433 if (listeners && listeners.length > 0) {
2434 j = listeners.length;
2437 l = listeners[index];
2439 EU.removeListener(l[EU.EL], l[EU.TYPE],
2449 EU.doRemove(window, "unload", EU._unload);
2454 getScroll: function() {
2455 var dd = document.documentElement, db = document.body;
2456 if (dd && (dd.scrollTop || dd.scrollLeft)) {
2457 return [dd.scrollTop, dd.scrollLeft];
2459 return [db.scrollTop, db.scrollLeft];
2466 doAdd: function () {
2467 if (window.addEventListener) {
2468 return function(el, eventName, fn, capture) {
2469 el.addEventListener(eventName, fn, (capture));
2471 } else if (window.attachEvent) {
2472 return function(el, eventName, fn, capture) {
2473 el.attachEvent("on" + eventName, fn);
2482 doRemove: function() {
2483 if (window.removeEventListener) {
2484 return function (el, eventName, fn, capture) {
2485 el.removeEventListener(eventName, fn, (capture));
2487 } else if (window.detachEvent) {
2488 return function (el, eventName, fn) {
2489 el.detachEvent("on" + eventName, fn);
2501 var E = Roo.lib.Event;
2502 E.on = E.addListener;
2503 E.un = E.removeListener;
2505 if (document && document.body) {
2508 E.doAdd(window, "load", E._load);
2510 E.doAdd(window, "unload", E._unload);
2511 E._tryPreloadAttach();
2515 * Portions of this file are based on pieces of Yahoo User Interface Library
2516 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
2517 * YUI licensed under the BSD License:
2518 * http://developer.yahoo.net/yui/license.txt
2519 * <script type="text/javascript">
2525 * @class Roo.lib.Ajax
2532 request : function(method, uri, cb, data, options) {
2534 var hs = options.headers;
2537 if(hs.hasOwnProperty(h)){
2538 this.initHeader(h, hs[h], false);
2542 if(options.xmlData){
2543 this.initHeader('Content-Type', 'text/xml', false);
2545 data = options.xmlData;
2549 return this.asyncRequest(method, uri, cb, data);
2552 serializeForm : function(form) {
2553 if(typeof form == 'string') {
2554 form = (document.getElementById(form) || document.forms[form]);
2557 var el, name, val, disabled, data = '', hasSubmit = false;
2558 for (var i = 0; i < form.elements.length; i++) {
2559 el = form.elements[i];
2560 disabled = form.elements[i].disabled;
2561 name = form.elements[i].name;
2562 val = form.elements[i].value;
2564 if (!disabled && name){
2568 case 'select-multiple':
2569 for (var j = 0; j < el.options.length; j++) {
2570 if (el.options[j].selected) {
2572 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(el.options[j].attributes['value'].specified ? el.options[j].value : el.options[j].text) + '&';
2575 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(el.options[j].hasAttribute('value') ? el.options[j].value : el.options[j].text) + '&';
2583 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2596 if(hasSubmit == false) {
2597 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2602 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2607 data = data.substr(0, data.length - 1);
2615 useDefaultHeader:true,
2617 defaultPostHeader:'application/x-www-form-urlencoded',
2619 useDefaultXhrHeader:true,
2621 defaultXhrHeader:'XMLHttpRequest',
2623 hasDefaultHeaders:true,
2635 setProgId:function(id)
2637 this.activeX.unshift(id);
2640 setDefaultPostHeader:function(b)
2642 this.useDefaultHeader = b;
2645 setDefaultXhrHeader:function(b)
2647 this.useDefaultXhrHeader = b;
2650 setPollingInterval:function(i)
2652 if (typeof i == 'number' && isFinite(i)) {
2653 this.pollInterval = i;
2657 createXhrObject:function(transactionId)
2663 http = new XMLHttpRequest();
2665 obj = { conn:http, tId:transactionId };
2669 for (var i = 0; i < this.activeX.length; ++i) {
2673 http = new ActiveXObject(this.activeX[i]);
2675 obj = { conn:http, tId:transactionId };
2688 getConnectionObject:function()
2691 var tId = this.transactionId;
2695 o = this.createXhrObject(tId);
2697 this.transactionId++;
2708 asyncRequest:function(method, uri, callback, postData)
2710 var o = this.getConnectionObject();
2716 o.conn.open(method, uri, true);
2718 if (this.useDefaultXhrHeader) {
2719 if (!this.defaultHeaders['X-Requested-With']) {
2720 this.initHeader('X-Requested-With', this.defaultXhrHeader, true);
2724 if(postData && this.useDefaultHeader){
2725 this.initHeader('Content-Type', this.defaultPostHeader);
2728 if (this.hasDefaultHeaders || this.hasHeaders) {
2732 this.handleReadyState(o, callback);
2733 o.conn.send(postData || null);
2739 handleReadyState:function(o, callback)
2743 if (callback && callback.timeout) {
2745 this.timeout[o.tId] = window.setTimeout(function() {
2746 oConn.abort(o, callback, true);
2747 }, callback.timeout);
2750 this.poll[o.tId] = window.setInterval(
2752 if (o.conn && o.conn.readyState == 4) {
2753 window.clearInterval(oConn.poll[o.tId]);
2754 delete oConn.poll[o.tId];
2756 if(callback && callback.timeout) {
2757 window.clearTimeout(oConn.timeout[o.tId]);
2758 delete oConn.timeout[o.tId];
2761 oConn.handleTransactionResponse(o, callback);
2764 , this.pollInterval);
2767 handleTransactionResponse:function(o, callback, isAbort)
2771 this.releaseObject(o);
2775 var httpStatus, responseObject;
2779 if (o.conn.status !== undefined && o.conn.status != 0) {
2780 httpStatus = o.conn.status;
2792 if (httpStatus >= 200 && httpStatus < 300) {
2793 responseObject = this.createResponseObject(o, callback.argument);
2794 if (callback.success) {
2795 if (!callback.scope) {
2796 callback.success(responseObject);
2801 callback.success.apply(callback.scope, [responseObject]);
2806 switch (httpStatus) {
2814 responseObject = this.createExceptionObject(o.tId, callback.argument, (isAbort ? isAbort : false));
2815 if (callback.failure) {
2816 if (!callback.scope) {
2817 callback.failure(responseObject);
2820 callback.failure.apply(callback.scope, [responseObject]);
2825 responseObject = this.createResponseObject(o, callback.argument);
2826 if (callback.failure) {
2827 if (!callback.scope) {
2828 callback.failure(responseObject);
2831 callback.failure.apply(callback.scope, [responseObject]);
2837 this.releaseObject(o);
2838 responseObject = null;
2841 createResponseObject:function(o, callbackArg)
2848 var headerStr = o.conn.getAllResponseHeaders();
2849 var header = headerStr.split('\n');
2850 for (var i = 0; i < header.length; i++) {
2851 var delimitPos = header[i].indexOf(':');
2852 if (delimitPos != -1) {
2853 headerObj[header[i].substring(0, delimitPos)] = header[i].substring(delimitPos + 2);
2861 obj.status = o.conn.status;
2862 obj.statusText = o.conn.statusText;
2863 obj.getResponseHeader = headerObj;
2864 obj.getAllResponseHeaders = headerStr;
2865 obj.responseText = o.conn.responseText;
2866 obj.responseXML = o.conn.responseXML;
2868 if (typeof callbackArg !== undefined) {
2869 obj.argument = callbackArg;
2875 createExceptionObject:function(tId, callbackArg, isAbort)
2878 var COMM_ERROR = 'communication failure';
2879 var ABORT_CODE = -1;
2880 var ABORT_ERROR = 'transaction aborted';
2886 obj.status = ABORT_CODE;
2887 obj.statusText = ABORT_ERROR;
2890 obj.status = COMM_CODE;
2891 obj.statusText = COMM_ERROR;
2895 obj.argument = callbackArg;
2901 initHeader:function(label, value, isDefault)
2903 var headerObj = (isDefault) ? this.defaultHeaders : this.headers;
2905 if (headerObj[label] === undefined) {
2906 headerObj[label] = value;
2911 headerObj[label] = value + "," + headerObj[label];
2915 this.hasDefaultHeaders = true;
2918 this.hasHeaders = true;
2923 setHeader:function(o)
2925 if (this.hasDefaultHeaders) {
2926 for (var prop in this.defaultHeaders) {
2927 if (this.defaultHeaders.hasOwnProperty(prop)) {
2928 o.conn.setRequestHeader(prop, this.defaultHeaders[prop]);
2933 if (this.hasHeaders) {
2934 for (var prop in this.headers) {
2935 if (this.headers.hasOwnProperty(prop)) {
2936 o.conn.setRequestHeader(prop, this.headers[prop]);
2940 this.hasHeaders = false;
2944 resetDefaultHeaders:function() {
2945 delete this.defaultHeaders;
2946 this.defaultHeaders = {};
2947 this.hasDefaultHeaders = false;
2950 abort:function(o, callback, isTimeout)
2952 if(this.isCallInProgress(o)) {
2954 window.clearInterval(this.poll[o.tId]);
2955 delete this.poll[o.tId];
2957 delete this.timeout[o.tId];
2960 this.handleTransactionResponse(o, callback, true);
2970 isCallInProgress:function(o)
2973 return o.conn.readyState != 4 && o.conn.readyState != 0;
2982 releaseObject:function(o)
2991 'MSXML2.XMLHTTP.3.0',
2999 * Portions of this file are based on pieces of Yahoo User Interface Library
3000 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3001 * YUI licensed under the BSD License:
3002 * http://developer.yahoo.net/yui/license.txt
3003 * <script type="text/javascript">
3007 Roo.lib.Region = function(t, r, b, l) {
3017 Roo.lib.Region.prototype = {
3018 contains : function(region) {
3019 return ( region.left >= this.left &&
3020 region.right <= this.right &&
3021 region.top >= this.top &&
3022 region.bottom <= this.bottom );
3026 getArea : function() {
3027 return ( (this.bottom - this.top) * (this.right - this.left) );
3030 intersect : function(region) {
3031 var t = Math.max(this.top, region.top);
3032 var r = Math.min(this.right, region.right);
3033 var b = Math.min(this.bottom, region.bottom);
3034 var l = Math.max(this.left, region.left);
3036 if (b >= t && r >= l) {
3037 return new Roo.lib.Region(t, r, b, l);
3042 union : function(region) {
3043 var t = Math.min(this.top, region.top);
3044 var r = Math.max(this.right, region.right);
3045 var b = Math.max(this.bottom, region.bottom);
3046 var l = Math.min(this.left, region.left);
3048 return new Roo.lib.Region(t, r, b, l);
3051 adjust : function(t, l, b, r) {
3060 Roo.lib.Region.getRegion = function(el) {
3061 var p = Roo.lib.Dom.getXY(el);
3064 var r = p[0] + el.offsetWidth;
3065 var b = p[1] + el.offsetHeight;
3068 return new Roo.lib.Region(t, r, b, l);
3071 * Portions of this file are based on pieces of Yahoo User Interface Library
3072 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3073 * YUI licensed under the BSD License:
3074 * http://developer.yahoo.net/yui/license.txt
3075 * <script type="text/javascript">
3078 //@@dep Roo.lib.Region
3081 Roo.lib.Point = function(x, y) {
3082 if (x instanceof Array) {
3086 this.x = this.right = this.left = this[0] = x;
3087 this.y = this.top = this.bottom = this[1] = y;
3090 Roo.lib.Point.prototype = new Roo.lib.Region();
3092 * Portions of this file are based on pieces of Yahoo User Interface Library
3093 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3094 * YUI licensed under the BSD License:
3095 * http://developer.yahoo.net/yui/license.txt
3096 * <script type="text/javascript">
3103 scroll : function(el, args, duration, easing, cb, scope) {
3104 this.run(el, args, duration, easing, cb, scope, Roo.lib.Scroll);
3107 motion : function(el, args, duration, easing, cb, scope) {
3108 this.run(el, args, duration, easing, cb, scope, Roo.lib.Motion);
3111 color : function(el, args, duration, easing, cb, scope) {
3112 this.run(el, args, duration, easing, cb, scope, Roo.lib.ColorAnim);
3115 run : function(el, args, duration, easing, cb, scope, type) {
3116 type = type || Roo.lib.AnimBase;
3117 if (typeof easing == "string") {
3118 easing = Roo.lib.Easing[easing];
3120 var anim = new type(el, args, duration, easing);
3121 anim.animateX(function() {
3122 Roo.callback(cb, scope);
3128 * Portions of this file are based on pieces of Yahoo User Interface Library
3129 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3130 * YUI licensed under the BSD License:
3131 * http://developer.yahoo.net/yui/license.txt
3132 * <script type="text/javascript">
3140 if (!libFlyweight) {
3141 libFlyweight = new Roo.Element.Flyweight();
3143 libFlyweight.dom = el;
3144 return libFlyweight;
3147 // since this uses fly! - it cant be in DOM (which does not have fly yet..)
3151 Roo.lib.AnimBase = function(el, attributes, duration, method) {
3153 this.init(el, attributes, duration, method);
3157 Roo.lib.AnimBase.fly = fly;
3161 Roo.lib.AnimBase.prototype = {
3163 toString: function() {
3164 var el = this.getEl();
3165 var id = el.id || el.tagName;
3166 return ("Anim " + id);
3170 noNegatives: /width|height|opacity|padding/i,
3171 offsetAttribute: /^((width|height)|(top|left))$/,
3172 defaultUnit: /width|height|top$|bottom$|left$|right$/i,
3173 offsetUnit: /\d+(em|%|en|ex|pt|in|cm|mm|pc)$/i
3177 doMethod: function(attr, start, end) {
3178 return this.method(this.currentFrame, start, end - start, this.totalFrames);
3182 setAttribute: function(attr, val, unit) {
3183 if (this.patterns.noNegatives.test(attr)) {
3184 val = (val > 0) ? val : 0;
3187 Roo.fly(this.getEl(), '_anim').setStyle(attr, val + unit);
3191 getAttribute: function(attr) {
3192 var el = this.getEl();
3193 var val = fly(el).getStyle(attr);
3195 if (val !== 'auto' && !this.patterns.offsetUnit.test(val)) {
3196 return parseFloat(val);
3199 var a = this.patterns.offsetAttribute.exec(attr) || [];
3200 var pos = !!( a[3] );
3201 var box = !!( a[2] );
3204 if (box || (fly(el).getStyle('position') == 'absolute' && pos)) {
3205 val = el['offset' + a[0].charAt(0).toUpperCase() + a[0].substr(1)];
3214 getDefaultUnit: function(attr) {
3215 if (this.patterns.defaultUnit.test(attr)) {
3222 animateX : function(callback, scope) {
3223 var f = function() {
3224 this.onComplete.removeListener(f);
3225 if (typeof callback == "function") {
3226 callback.call(scope || this, this);
3229 this.onComplete.addListener(f, this);
3234 setRuntimeAttribute: function(attr) {
3237 var attributes = this.attributes;
3239 this.runtimeAttributes[attr] = {};
3241 var isset = function(prop) {
3242 return (typeof prop !== 'undefined');
3245 if (!isset(attributes[attr]['to']) && !isset(attributes[attr]['by'])) {
3249 start = ( isset(attributes[attr]['from']) ) ? attributes[attr]['from'] : this.getAttribute(attr);
3252 if (isset(attributes[attr]['to'])) {
3253 end = attributes[attr]['to'];
3254 } else if (isset(attributes[attr]['by'])) {
3255 if (start.constructor == Array) {
3257 for (var i = 0, len = start.length; i < len; ++i) {
3258 end[i] = start[i] + attributes[attr]['by'][i];
3261 end = start + attributes[attr]['by'];
3265 this.runtimeAttributes[attr].start = start;
3266 this.runtimeAttributes[attr].end = end;
3269 this.runtimeAttributes[attr].unit = ( isset(attributes[attr].unit) ) ? attributes[attr]['unit'] : this.getDefaultUnit(attr);
3273 init: function(el, attributes, duration, method) {
3275 var isAnimated = false;
3278 var startTime = null;
3281 var actualFrames = 0;
3284 el = Roo.getDom(el);
3287 this.attributes = attributes || {};
3290 this.duration = duration || 1;
3293 this.method = method || Roo.lib.Easing.easeNone;
3296 this.useSeconds = true;
3299 this.currentFrame = 0;
3302 this.totalFrames = Roo.lib.AnimMgr.fps;
3305 this.getEl = function() {
3310 this.isAnimated = function() {
3315 this.getStartTime = function() {
3319 this.runtimeAttributes = {};
3322 this.animate = function() {
3323 if (this.isAnimated()) {
3327 this.currentFrame = 0;
3329 this.totalFrames = ( this.useSeconds ) ? Math.ceil(Roo.lib.AnimMgr.fps * this.duration) : this.duration;
3331 Roo.lib.AnimMgr.registerElement(this);
3335 this.stop = function(finish) {
3337 this.currentFrame = this.totalFrames;
3338 this._onTween.fire();
3340 Roo.lib.AnimMgr.stop(this);
3343 var onStart = function() {
3344 this.onStart.fire();
3346 this.runtimeAttributes = {};
3347 for (var attr in this.attributes) {
3348 this.setRuntimeAttribute(attr);
3353 startTime = new Date();
3357 var onTween = function() {
3359 duration: new Date() - this.getStartTime(),
3360 currentFrame: this.currentFrame
3363 data.toString = function() {
3365 'duration: ' + data.duration +
3366 ', currentFrame: ' + data.currentFrame
3370 this.onTween.fire(data);
3372 var runtimeAttributes = this.runtimeAttributes;
3374 for (var attr in runtimeAttributes) {
3375 this.setAttribute(attr, this.doMethod(attr, runtimeAttributes[attr].start, runtimeAttributes[attr].end), runtimeAttributes[attr].unit);
3381 var onComplete = function() {
3382 var actual_duration = (new Date() - startTime) / 1000 ;
3385 duration: actual_duration,
3386 frames: actualFrames,
3387 fps: actualFrames / actual_duration
3390 data.toString = function() {
3392 'duration: ' + data.duration +
3393 ', frames: ' + data.frames +
3394 ', fps: ' + data.fps
3400 this.onComplete.fire(data);
3404 this._onStart = new Roo.util.Event(this);
3405 this.onStart = new Roo.util.Event(this);
3406 this.onTween = new Roo.util.Event(this);
3407 this._onTween = new Roo.util.Event(this);
3408 this.onComplete = new Roo.util.Event(this);
3409 this._onComplete = new Roo.util.Event(this);
3410 this._onStart.addListener(onStart);
3411 this._onTween.addListener(onTween);
3412 this._onComplete.addListener(onComplete);
3417 * Portions of this file are based on pieces of Yahoo User Interface Library
3418 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3419 * YUI licensed under the BSD License:
3420 * http://developer.yahoo.net/yui/license.txt
3421 * <script type="text/javascript">
3425 Roo.lib.AnimMgr = new function() {
3442 this.registerElement = function(tween) {
3443 queue[queue.length] = tween;
3445 tween._onStart.fire();
3450 this.unRegister = function(tween, index) {
3451 tween._onComplete.fire();
3452 index = index || getIndex(tween);
3454 queue.splice(index, 1);
3458 if (tweenCount <= 0) {
3464 this.start = function() {
3465 if (thread === null) {
3466 thread = setInterval(this.run, this.delay);
3471 this.stop = function(tween) {
3473 clearInterval(thread);
3475 for (var i = 0, len = queue.length; i < len; ++i) {
3476 if (queue[0].isAnimated()) {
3477 this.unRegister(queue[0], 0);
3486 this.unRegister(tween);
3491 this.run = function() {
3492 for (var i = 0, len = queue.length; i < len; ++i) {
3493 var tween = queue[i];
3494 if (!tween || !tween.isAnimated()) {
3498 if (tween.currentFrame < tween.totalFrames || tween.totalFrames === null)
3500 tween.currentFrame += 1;
3502 if (tween.useSeconds) {
3503 correctFrame(tween);
3505 tween._onTween.fire();
3508 Roo.lib.AnimMgr.stop(tween, i);
3513 var getIndex = function(anim) {
3514 for (var i = 0, len = queue.length; i < len; ++i) {
3515 if (queue[i] == anim) {
3523 var correctFrame = function(tween) {
3524 var frames = tween.totalFrames;
3525 var frame = tween.currentFrame;
3526 var expected = (tween.currentFrame * tween.duration * 1000 / tween.totalFrames);
3527 var elapsed = (new Date() - tween.getStartTime());
3530 if (elapsed < tween.duration * 1000) {
3531 tweak = Math.round((elapsed / expected - 1) * tween.currentFrame);
3533 tweak = frames - (frame + 1);
3535 if (tweak > 0 && isFinite(tweak)) {
3536 if (tween.currentFrame + tweak >= frames) {
3537 tweak = frames - (frame + 1);
3540 tween.currentFrame += tweak;
3546 * Portions of this file are based on pieces of Yahoo User Interface Library
3547 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3548 * YUI licensed under the BSD License:
3549 * http://developer.yahoo.net/yui/license.txt
3550 * <script type="text/javascript">
3553 Roo.lib.Bezier = new function() {
3555 this.getPosition = function(points, t) {
3556 var n = points.length;
3559 for (var i = 0; i < n; ++i) {
3560 tmp[i] = [points[i][0], points[i][1]];
3563 for (var j = 1; j < n; ++j) {
3564 for (i = 0; i < n - j; ++i) {
3565 tmp[i][0] = (1 - t) * tmp[i][0] + t * tmp[parseInt(i + 1, 10)][0];
3566 tmp[i][1] = (1 - t) * tmp[i][1] + t * tmp[parseInt(i + 1, 10)][1];
3570 return [ tmp[0][0], tmp[0][1] ];
3574 * Portions of this file are based on pieces of Yahoo User Interface Library
3575 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3576 * YUI licensed under the BSD License:
3577 * http://developer.yahoo.net/yui/license.txt
3578 * <script type="text/javascript">
3583 Roo.lib.ColorAnim = function(el, attributes, duration, method) {
3584 Roo.lib.ColorAnim.superclass.constructor.call(this, el, attributes, duration, method);
3587 Roo.extend(Roo.lib.ColorAnim, Roo.lib.AnimBase);
3589 var fly = Roo.lib.AnimBase.fly;
3591 var superclass = Y.ColorAnim.superclass;
3592 var proto = Y.ColorAnim.prototype;
3594 proto.toString = function() {
3595 var el = this.getEl();
3596 var id = el.id || el.tagName;
3597 return ("ColorAnim " + id);
3600 proto.patterns.color = /color$/i;
3601 proto.patterns.rgb = /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i;
3602 proto.patterns.hex = /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i;
3603 proto.patterns.hex3 = /^#?([0-9A-F]{1})([0-9A-F]{1})([0-9A-F]{1})$/i;
3604 proto.patterns.transparent = /^transparent|rgba\(0, 0, 0, 0\)$/;
3607 proto.parseColor = function(s) {
3608 if (s.length == 3) {
3612 var c = this.patterns.hex.exec(s);
3613 if (c && c.length == 4) {
3614 return [ parseInt(c[1], 16), parseInt(c[2], 16), parseInt(c[3], 16) ];
3617 c = this.patterns.rgb.exec(s);
3618 if (c && c.length == 4) {
3619 return [ parseInt(c[1], 10), parseInt(c[2], 10), parseInt(c[3], 10) ];
3622 c = this.patterns.hex3.exec(s);
3623 if (c && c.length == 4) {
3624 return [ parseInt(c[1] + c[1], 16), parseInt(c[2] + c[2], 16), parseInt(c[3] + c[3], 16) ];
3629 // since this uses fly! - it cant be in ColorAnim (which does not have fly yet..)
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);
3653 proto.getAttribute = function(attr) {
3654 var el = this.getEl();
3655 if (this.patterns.color.test(attr)) {
3656 var val = fly(el).getStyle(attr);
3658 if (this.patterns.transparent.test(val)) {
3659 var parent = el.parentNode;
3660 val = fly(parent).getStyle(attr);
3662 while (parent && this.patterns.transparent.test(val)) {
3663 parent = parent.parentNode;
3664 val = fly(parent).getStyle(attr);
3665 if (parent.tagName.toUpperCase() == 'HTML') {
3671 val = superclass.getAttribute.call(this, attr);
3677 proto.doMethod = function(attr, start, end) {
3680 if (this.patterns.color.test(attr)) {
3682 for (var i = 0, len = start.length; i < len; ++i) {
3683 val[i] = superclass.doMethod.call(this, attr, start[i], end[i]);
3686 val = 'rgb(' + Math.floor(val[0]) + ',' + Math.floor(val[1]) + ',' + Math.floor(val[2]) + ')';
3689 val = superclass.doMethod.call(this, attr, start, end);
3695 proto.setRuntimeAttribute = function(attr) {
3696 superclass.setRuntimeAttribute.call(this, attr);
3698 if (this.patterns.color.test(attr)) {
3699 var attributes = this.attributes;
3700 var start = this.parseColor(this.runtimeAttributes[attr].start);
3701 var end = this.parseColor(this.runtimeAttributes[attr].end);
3703 if (typeof attributes[attr]['to'] === 'undefined' && typeof attributes[attr]['by'] !== 'undefined') {
3704 end = this.parseColor(attributes[attr].by);
3706 for (var i = 0, len = start.length; i < len; ++i) {
3707 end[i] = start[i] + end[i];
3711 this.runtimeAttributes[attr].start = start;
3712 this.runtimeAttributes[attr].end = end;
3718 * Portions of this file are based on pieces of Yahoo User Interface Library
3719 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3720 * YUI licensed under the BSD License:
3721 * http://developer.yahoo.net/yui/license.txt
3722 * <script type="text/javascript">
3728 easeNone: function (t, b, c, d) {
3729 return c * t / d + b;
3733 easeIn: function (t, b, c, d) {
3734 return c * (t /= d) * t + b;
3738 easeOut: function (t, b, c, d) {
3739 return -c * (t /= d) * (t - 2) + b;
3743 easeBoth: function (t, b, c, d) {
3744 if ((t /= d / 2) < 1) {
3745 return c / 2 * t * t + b;
3748 return -c / 2 * ((--t) * (t - 2) - 1) + b;
3752 easeInStrong: function (t, b, c, d) {
3753 return c * (t /= d) * t * t * t + b;
3757 easeOutStrong: function (t, b, c, d) {
3758 return -c * ((t = t / d - 1) * t * t * t - 1) + b;
3762 easeBothStrong: function (t, b, c, d) {
3763 if ((t /= d / 2) < 1) {
3764 return c / 2 * t * t * t * t + b;
3767 return -c / 2 * ((t -= 2) * t * t * t - 2) + b;
3772 elasticIn: 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 -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
3795 elasticOut: function (t, b, c, d, a, p) {
3799 if ((t /= d) == 1) {
3806 if (!a || a < Math.abs(c)) {
3811 var s = p / (2 * Math.PI) * Math.asin(c / a);
3814 return a * Math.pow(2, -10 * t) * Math.sin((t * d - s) * (2 * Math.PI) / p) + c + b;
3818 elasticBoth: function (t, b, c, d, a, p) {
3823 if ((t /= d / 2) == 2) {
3831 if (!a || a < Math.abs(c)) {
3836 var s = p / (2 * Math.PI) * Math.asin(c / a);
3840 return -.5 * (a * Math.pow(2, 10 * (t -= 1)) *
3841 Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
3843 return a * Math.pow(2, -10 * (t -= 1)) *
3844 Math.sin((t * d - s) * (2 * Math.PI) / p) * .5 + c + b;
3849 backIn: function (t, b, c, d, s) {
3850 if (typeof s == 'undefined') {
3853 return c * (t /= d) * t * ((s + 1) * t - s) + b;
3857 backOut: function (t, b, c, d, s) {
3858 if (typeof s == 'undefined') {
3861 return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
3865 backBoth: function (t, b, c, d, s) {
3866 if (typeof s == 'undefined') {
3870 if ((t /= d / 2 ) < 1) {
3871 return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b;
3873 return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;
3877 bounceIn: function (t, b, c, d) {
3878 return c - Roo.lib.Easing.bounceOut(d - t, 0, c, d) + b;
3882 bounceOut: function (t, b, c, d) {
3883 if ((t /= d) < (1 / 2.75)) {
3884 return c * (7.5625 * t * t) + b;
3885 } else if (t < (2 / 2.75)) {
3886 return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b;
3887 } else if (t < (2.5 / 2.75)) {
3888 return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b;
3890 return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b;
3894 bounceBoth: function (t, b, c, d) {
3896 return Roo.lib.Easing.bounceIn(t * 2, 0, c, d) * .5 + b;
3898 return Roo.lib.Easing.bounceOut(t * 2 - d, 0, c, d) * .5 + c * .5 + b;
3901 * Portions of this file are based on pieces of Yahoo User Interface Library
3902 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3903 * YUI licensed under the BSD License:
3904 * http://developer.yahoo.net/yui/license.txt
3905 * <script type="text/javascript">
3909 Roo.lib.Motion = function(el, attributes, duration, method) {
3911 Roo.lib.Motion.superclass.constructor.call(this, el, attributes, duration, method);
3915 Roo.extend(Roo.lib.Motion, Roo.lib.ColorAnim);
3919 var superclass = Y.Motion.superclass;
3920 var proto = Y.Motion.prototype;
3922 proto.toString = function() {
3923 var el = this.getEl();
3924 var id = el.id || el.tagName;
3925 return ("Motion " + id);
3928 proto.patterns.points = /^points$/i;
3930 proto.setAttribute = function(attr, val, unit) {
3931 if (this.patterns.points.test(attr)) {
3932 unit = unit || 'px';
3933 superclass.setAttribute.call(this, 'left', val[0], unit);
3934 superclass.setAttribute.call(this, 'top', val[1], unit);
3936 superclass.setAttribute.call(this, attr, val, unit);
3940 proto.getAttribute = function(attr) {
3941 if (this.patterns.points.test(attr)) {
3943 superclass.getAttribute.call(this, 'left'),
3944 superclass.getAttribute.call(this, 'top')
3947 val = superclass.getAttribute.call(this, attr);
3953 proto.doMethod = function(attr, start, end) {
3956 if (this.patterns.points.test(attr)) {
3957 var t = this.method(this.currentFrame, 0, 100, this.totalFrames) / 100;
3958 val = Y.Bezier.getPosition(this.runtimeAttributes[attr], t);
3960 val = superclass.doMethod.call(this, attr, start, end);
3965 proto.setRuntimeAttribute = function(attr) {
3966 if (this.patterns.points.test(attr)) {
3967 var el = this.getEl();
3968 var attributes = this.attributes;
3970 var control = attributes['points']['control'] || [];
3974 if (control.length > 0 && !(control[0] instanceof Array)) {
3975 control = [control];
3978 for (i = 0,len = control.length; i < len; ++i) {
3979 tmp[i] = control[i];
3984 Roo.fly(el).position();
3986 if (isset(attributes['points']['from'])) {
3987 Roo.lib.Dom.setXY(el, attributes['points']['from']);
3990 Roo.lib.Dom.setXY(el, Roo.lib.Dom.getXY(el));
3993 start = this.getAttribute('points');
3996 if (isset(attributes['points']['to'])) {
3997 end = translateValues.call(this, attributes['points']['to'], start);
3999 var pageXY = Roo.lib.Dom.getXY(this.getEl());
4000 for (i = 0,len = control.length; i < len; ++i) {
4001 control[i] = translateValues.call(this, control[i], start);
4005 } else if (isset(attributes['points']['by'])) {
4006 end = [ start[0] + attributes['points']['by'][0], start[1] + attributes['points']['by'][1] ];
4008 for (i = 0,len = control.length; i < len; ++i) {
4009 control[i] = [ start[0] + control[i][0], start[1] + control[i][1] ];
4013 this.runtimeAttributes[attr] = [start];
4015 if (control.length > 0) {
4016 this.runtimeAttributes[attr] = this.runtimeAttributes[attr].concat(control);
4019 this.runtimeAttributes[attr][this.runtimeAttributes[attr].length] = end;
4022 superclass.setRuntimeAttribute.call(this, attr);
4026 var translateValues = function(val, start) {
4027 var pageXY = Roo.lib.Dom.getXY(this.getEl());
4028 val = [ val[0] - pageXY[0] + start[0], val[1] - pageXY[1] + start[1] ];
4033 var isset = function(prop) {
4034 return (typeof prop !== 'undefined');
4038 * Portions of this file are based on pieces of Yahoo User Interface Library
4039 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
4040 * YUI licensed under the BSD License:
4041 * http://developer.yahoo.net/yui/license.txt
4042 * <script type="text/javascript">
4046 Roo.lib.Scroll = function(el, attributes, duration, method) {
4048 Roo.lib.Scroll.superclass.constructor.call(this, el, attributes, duration, method);
4052 Roo.extend(Roo.lib.Scroll, Roo.lib.ColorAnim);
4056 var superclass = Y.Scroll.superclass;
4057 var proto = Y.Scroll.prototype;
4059 proto.toString = function() {
4060 var el = this.getEl();
4061 var id = el.id || el.tagName;
4062 return ("Scroll " + id);
4065 proto.doMethod = function(attr, start, end) {
4068 if (attr == 'scroll') {
4070 this.method(this.currentFrame, start[0], end[0] - start[0], this.totalFrames),
4071 this.method(this.currentFrame, start[1], end[1] - start[1], this.totalFrames)
4075 val = superclass.doMethod.call(this, attr, start, end);
4080 proto.getAttribute = function(attr) {
4082 var el = this.getEl();
4084 if (attr == 'scroll') {
4085 val = [ el.scrollLeft, el.scrollTop ];
4087 val = superclass.getAttribute.call(this, attr);
4093 proto.setAttribute = function(attr, val, unit) {
4094 var el = this.getEl();
4096 if (attr == 'scroll') {
4097 el.scrollLeft = val[0];
4098 el.scrollTop = val[1];
4100 superclass.setAttribute.call(this, attr, val, unit);
4106 * Ext JS Library 1.1.1
4107 * Copyright(c) 2006-2007, Ext JS, LLC.
4109 * Originally Released Under LGPL - original licence link has changed is not relivant.
4112 * <script type="text/javascript">
4116 // nasty IE9 hack - what a pile of crap that is..
4118 if (typeof Range != "undefined" && typeof Range.prototype.createContextualFragment == "undefined") {
4119 Range.prototype.createContextualFragment = function (html) {
4120 var doc = window.document;
4121 var container = doc.createElement("div");
4122 container.innerHTML = html;
4123 var frag = doc.createDocumentFragment(), n;
4124 while ((n = container.firstChild)) {
4125 frag.appendChild(n);
4132 * @class Roo.DomHelper
4133 * Utility class for working with DOM and/or Templates. It transparently supports using HTML fragments or DOM.
4134 * 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>.
4137 Roo.DomHelper = function(){
4138 var tempTableEl = null;
4139 var emptyTags = /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i;
4140 var tableRe = /^table|tbody|tr|td$/i;
4142 // build as innerHTML where available
4144 var createHtml = function(o){
4145 if(typeof o == 'string'){
4154 if(attr == "tag" || attr == "children" || attr == "cn" || attr == "html" || typeof o[attr] == "function") continue;
4155 if(attr == "style"){
4157 if(typeof s == "function"){
4160 if(typeof s == "string"){
4161 b += ' style="' + s + '"';
4162 }else if(typeof s == "object"){
4165 if(typeof s[key] != "function"){
4166 b += key + ":" + s[key] + ";";
4173 b += ' class="' + o["cls"] + '"';
4174 }else if(attr == "htmlFor"){
4175 b += ' for="' + o["htmlFor"] + '"';
4177 b += " " + attr + '="' + o[attr] + '"';
4181 if(emptyTags.test(o.tag)){
4185 var cn = o.children || o.cn;
4187 //http://bugs.kde.org/show_bug.cgi?id=71506
4188 if((cn instanceof Array) || (Roo.isSafari && typeof(cn.join) == "function")){
4189 for(var i = 0, len = cn.length; i < len; i++) {
4190 b += createHtml(cn[i], b);
4193 b += createHtml(cn, b);
4199 b += "</" + o.tag + ">";
4206 var createDom = function(o, parentNode){
4208 // defininition craeted..
4210 if (o.ns && o.ns != 'html') {
4212 if (o.xmlns && typeof(xmlns[o.ns]) == 'undefined') {
4213 xmlns[o.ns] = o.xmlns;
4216 if (typeof(xmlns[o.ns]) == 'undefined') {
4217 console.log("Trying to create namespace element " + o.ns + ", however no xmlns was sent to builder previously");
4223 if (typeof(o) == 'string') {
4224 return parentNode.appendChild(document.createTextNode(o));
4226 o.tag = o.tag || div;
4227 if (o.ns && Roo.isIE) {
4229 o.tag = o.ns + ':' + o.tag;
4232 var el = ns ? document.createElementNS( ns, o.tag||'div') : document.createElement(o.tag||'div');
4233 var useSet = el.setAttribute ? true : false; // In IE some elements don't have setAttribute
4236 if(attr == "tag" || attr == "ns" ||attr == "xmlns" ||attr == "children" || attr == "cn" || attr == "html" ||
4237 attr == "style" || typeof o[attr] == "function") continue;
4239 if(attr=="cls" && Roo.isIE){
4240 el.className = o["cls"];
4242 if(useSet) { el.setAttribute(attr=="cls" ? 'class' : attr, o[attr]);}
4248 Roo.DomHelper.applyStyles(el, o.style);
4249 var cn = o.children || o.cn;
4251 //http://bugs.kde.org/show_bug.cgi?id=71506
4252 if((cn instanceof Array) || (Roo.isSafari && typeof(cn.join) == "function")){
4253 for(var i = 0, len = cn.length; i < len; i++) {
4254 createDom(cn[i], el);
4261 el.innerHTML = o.html;
4264 parentNode.appendChild(el);
4269 var ieTable = function(depth, s, h, e){
4270 tempTableEl.innerHTML = [s, h, e].join('');
4271 var i = -1, el = tempTableEl;
4278 // kill repeat to save bytes
4282 tbe = '</tbody>'+te,
4288 * Nasty code for IE's broken table implementation
4290 var insertIntoTable = function(tag, where, el, html){
4292 tempTableEl = document.createElement('div');
4297 if(where == 'afterbegin' || where == 'beforeend'){ // INTO a TD
4300 if(where == 'beforebegin'){
4304 before = el.nextSibling;
4307 node = ieTable(4, trs, html, tre);
4309 else if(tag == 'tr'){
4310 if(where == 'beforebegin'){
4313 node = ieTable(3, tbs, html, tbe);
4314 } else if(where == 'afterend'){
4315 before = el.nextSibling;
4317 node = ieTable(3, tbs, html, tbe);
4318 } else{ // INTO a TR
4319 if(where == 'afterbegin'){
4320 before = el.firstChild;
4322 node = ieTable(4, trs, html, tre);
4324 } else if(tag == 'tbody'){
4325 if(where == 'beforebegin'){
4328 node = ieTable(2, ts, html, te);
4329 } else if(where == 'afterend'){
4330 before = el.nextSibling;
4332 node = ieTable(2, ts, html, te);
4334 if(where == 'afterbegin'){
4335 before = el.firstChild;
4337 node = ieTable(3, tbs, html, tbe);
4340 if(where == 'beforebegin' || where == 'afterend'){ // OUTSIDE the table
4343 if(where == 'afterbegin'){
4344 before = el.firstChild;
4346 node = ieTable(2, ts, html, te);
4348 el.insertBefore(node, before);
4353 /** True to force the use of DOM instead of html fragments @type Boolean */
4357 * Returns the markup for the passed Element(s) config
4358 * @param {Object} o The Dom object spec (and children)
4361 markup : function(o){
4362 return createHtml(o);
4366 * Applies a style specification to an element
4367 * @param {String/HTMLElement} el The element to apply styles to
4368 * @param {String/Object/Function} styles A style specification string eg "width:100px", or object in the form {width:"100px"}, or
4369 * a function which returns such a specification.
4371 applyStyles : function(el, styles){
4374 if(typeof styles == "string"){
4375 var re = /\s?([a-z\-]*)\:\s?([^;]*);?/gi;
4377 while ((matches = re.exec(styles)) != null){
4378 el.setStyle(matches[1], matches[2]);
4380 }else if (typeof styles == "object"){
4381 for (var style in styles){
4382 el.setStyle(style, styles[style]);
4384 }else if (typeof styles == "function"){
4385 Roo.DomHelper.applyStyles(el, styles.call());
4391 * Inserts an HTML fragment into the Dom
4392 * @param {String} where Where to insert the html in relation to el - beforeBegin, afterBegin, beforeEnd, afterEnd.
4393 * @param {HTMLElement} el The context element
4394 * @param {String} html The HTML fragmenet
4395 * @return {HTMLElement} The new node
4397 insertHtml : function(where, el, html){
4398 where = where.toLowerCase();
4399 if(el.insertAdjacentHTML){
4400 if(tableRe.test(el.tagName)){
4402 if(rs = insertIntoTable(el.tagName.toLowerCase(), where, el, html)){
4408 el.insertAdjacentHTML('BeforeBegin', html);
4409 return el.previousSibling;
4411 el.insertAdjacentHTML('AfterBegin', html);
4412 return el.firstChild;
4414 el.insertAdjacentHTML('BeforeEnd', html);
4415 return el.lastChild;
4417 el.insertAdjacentHTML('AfterEnd', html);
4418 return el.nextSibling;
4420 throw 'Illegal insertion point -> "' + where + '"';
4422 var range = el.ownerDocument.createRange();
4426 range.setStartBefore(el);
4427 frag = range.createContextualFragment(html);
4428 el.parentNode.insertBefore(frag, el);
4429 return el.previousSibling;
4432 range.setStartBefore(el.firstChild);
4433 frag = range.createContextualFragment(html);
4434 el.insertBefore(frag, el.firstChild);
4435 return el.firstChild;
4437 el.innerHTML = html;
4438 return el.firstChild;
4442 range.setStartAfter(el.lastChild);
4443 frag = range.createContextualFragment(html);
4444 el.appendChild(frag);
4445 return el.lastChild;
4447 el.innerHTML = html;
4448 return el.lastChild;
4451 range.setStartAfter(el);
4452 frag = range.createContextualFragment(html);
4453 el.parentNode.insertBefore(frag, el.nextSibling);
4454 return el.nextSibling;
4456 throw 'Illegal insertion point -> "' + where + '"';
4460 * Creates new Dom element(s) and inserts them before el
4461 * @param {String/HTMLElement/Element} el The context element
4462 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
4463 * @param {Boolean} returnElement (optional) true to return a Roo.Element
4464 * @return {HTMLElement/Roo.Element} The new node
4466 insertBefore : function(el, o, returnElement){
4467 return this.doInsert(el, o, returnElement, "beforeBegin");
4471 * Creates new Dom element(s) and inserts them after el
4472 * @param {String/HTMLElement/Element} el The context element
4473 * @param {Object} o The Dom object spec (and children)
4474 * @param {Boolean} returnElement (optional) true to return a Roo.Element
4475 * @return {HTMLElement/Roo.Element} The new node
4477 insertAfter : function(el, o, returnElement){
4478 return this.doInsert(el, o, returnElement, "afterEnd", "nextSibling");
4482 * Creates new Dom element(s) and inserts them as the first child of 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 insertFirst : function(el, o, returnElement){
4489 return this.doInsert(el, o, returnElement, "afterBegin");
4493 doInsert : function(el, o, returnElement, pos, sibling){
4494 el = Roo.getDom(el);
4496 if(this.useDom || o.ns){
4497 newNode = createDom(o, null);
4498 el.parentNode.insertBefore(newNode, sibling ? el[sibling] : el);
4500 var html = createHtml(o);
4501 newNode = this.insertHtml(pos, el, html);
4503 return returnElement ? Roo.get(newNode, true) : newNode;
4507 * Creates new Dom element(s) and appends them to el
4508 * @param {String/HTMLElement/Element} el The context element
4509 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
4510 * @param {Boolean} returnElement (optional) true to return a Roo.Element
4511 * @return {HTMLElement/Roo.Element} The new node
4513 append : function(el, o, returnElement){
4514 el = Roo.getDom(el);
4516 if(this.useDom || o.ns){
4517 newNode = createDom(o, null);
4518 el.appendChild(newNode);
4520 var html = createHtml(o);
4521 newNode = this.insertHtml("beforeEnd", el, html);
4523 return returnElement ? Roo.get(newNode, true) : newNode;
4527 * Creates new Dom element(s) and overwrites the contents of el with them
4528 * @param {String/HTMLElement/Element} el The context element
4529 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
4530 * @param {Boolean} returnElement (optional) true to return a Roo.Element
4531 * @return {HTMLElement/Roo.Element} The new node
4533 overwrite : function(el, o, returnElement){
4534 el = Roo.getDom(el);
4537 while (el.childNodes.length) {
4538 el.removeChild(el.firstChild);
4542 el.innerHTML = createHtml(o);
4545 return returnElement ? Roo.get(el.firstChild, true) : el.firstChild;
4549 * Creates a new Roo.DomHelper.Template from the Dom object spec
4550 * @param {Object} o The Dom object spec (and children)
4551 * @return {Roo.DomHelper.Template} The new template
4553 createTemplate : function(o){
4554 var html = createHtml(o);
4555 return new Roo.Template(html);
4561 * Ext JS Library 1.1.1
4562 * Copyright(c) 2006-2007, Ext JS, LLC.
4564 * Originally Released Under LGPL - original licence link has changed is not relivant.
4567 * <script type="text/javascript">
4571 * @class Roo.Template
4572 * Represents an HTML fragment template. Templates can be precompiled for greater performance.
4573 * For a list of available format functions, see {@link Roo.util.Format}.<br />
4576 var t = new Roo.Template({
4577 html : '<div name="{id}">' +
4578 '<span class="{cls}">{name:trim} {someval:this.myformat}{value:ellipsis(10)}</span>' +
4580 myformat: function (value, allValues) {
4581 return 'XX' + value;
4584 t.append('some-element', {id: 'myid', cls: 'myclass', name: 'foo', value: 'bar'});
4586 * For more information see this blog post with examples:
4587 * <a href="http://www.cnitblog.com/seeyeah/archive/2011/12/30/38728.html/">DomHelper
4588 - Create Elements using DOM, HTML fragments and Templates</a>.
4590 * @param {Object} cfg - Configuration object.
4592 Roo.Template = function(cfg){
4594 if(cfg instanceof Array){
4596 }else if(arguments.length > 1){
4597 cfg = Array.prototype.join.call(arguments, "");
4601 if (typeof(cfg) == 'object') {
4612 Roo.Template.prototype = {
4615 * @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..
4616 * it should be fixed so that template is observable...
4620 * @cfg {String} html The HTML fragment or an array of fragments to join("") or multiple arguments to join("")
4624 * Returns an HTML fragment of this template with the specified values applied.
4625 * @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'})
4626 * @return {String} The HTML fragment
4628 applyTemplate : function(values){
4632 return this.compiled(values);
4634 var useF = this.disableFormats !== true;
4635 var fm = Roo.util.Format, tpl = this;
4636 var fn = function(m, name, format, args){
4638 if(format.substr(0, 5) == "this."){
4639 return tpl.call(format.substr(5), values[name], values);
4642 // quoted values are required for strings in compiled templates,
4643 // but for non compiled we need to strip them
4644 // quoted reversed for jsmin
4645 var re = /^\s*['"](.*)["']\s*$/;
4646 args = args.split(',');
4647 for(var i = 0, len = args.length; i < len; i++){
4648 args[i] = args[i].replace(re, "$1");
4650 args = [values[name]].concat(args);
4652 args = [values[name]];
4654 return fm[format].apply(fm, args);
4657 return values[name] !== undefined ? values[name] : "";
4660 return this.html.replace(this.re, fn);
4678 this.loading = true;
4679 this.compiled = false;
4681 var cx = new Roo.data.Connection();
4685 success : function (response) {
4687 _t.html = response.responseText;
4691 failure : function(response) {
4692 Roo.log("Template failed to load from " + _t.url);
4699 * Sets the HTML used as the template and optionally compiles it.
4700 * @param {String} html
4701 * @param {Boolean} compile (optional) True to compile the template (defaults to undefined)
4702 * @return {Roo.Template} this
4704 set : function(html, compile){
4706 this.compiled = null;
4714 * True to disable format functions (defaults to false)
4717 disableFormats : false,
4720 * The regular expression used to match template variables
4724 re : /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
4727 * Compiles the template into an internal function, eliminating the RegEx overhead.
4728 * @return {Roo.Template} this
4730 compile : function(){
4731 var fm = Roo.util.Format;
4732 var useF = this.disableFormats !== true;
4733 var sep = Roo.isGecko ? "+" : ",";
4734 var fn = function(m, name, format, args){
4736 args = args ? ',' + args : "";
4737 if(format.substr(0, 5) != "this."){
4738 format = "fm." + format + '(';
4740 format = 'this.call("'+ format.substr(5) + '", ';
4744 args= ''; format = "(values['" + name + "'] == undefined ? '' : ";
4746 return "'"+ sep + format + "values['" + name + "']" + args + ")"+sep+"'";
4749 // branched to use + in gecko and [].join() in others
4751 body = "this.compiled = function(values){ return '" +
4752 this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
4755 body = ["this.compiled = function(values){ return ['"];
4756 body.push(this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn));
4757 body.push("'].join('');};");
4758 body = body.join('');
4768 // private function used to call members
4769 call : function(fnName, value, allValues){
4770 return this[fnName](value, allValues);
4774 * Applies the supplied values to the template and inserts the new node(s) as the first child of el.
4775 * @param {String/HTMLElement/Roo.Element} el The context element
4776 * @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'})
4777 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
4778 * @return {HTMLElement/Roo.Element} The new node or Element
4780 insertFirst: function(el, values, returnElement){
4781 return this.doInsert('afterBegin', el, values, returnElement);
4785 * Applies the supplied values to the template and inserts the new node(s) before el.
4786 * @param {String/HTMLElement/Roo.Element} el The context element
4787 * @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'})
4788 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
4789 * @return {HTMLElement/Roo.Element} The new node or Element
4791 insertBefore: function(el, values, returnElement){
4792 return this.doInsert('beforeBegin', el, values, returnElement);
4796 * Applies the supplied values to the template and inserts the new node(s) after el.
4797 * @param {String/HTMLElement/Roo.Element} el The context element
4798 * @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'})
4799 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
4800 * @return {HTMLElement/Roo.Element} The new node or Element
4802 insertAfter : function(el, values, returnElement){
4803 return this.doInsert('afterEnd', el, values, returnElement);
4807 * Applies the supplied values to the template and appends the new node(s) to el.
4808 * @param {String/HTMLElement/Roo.Element} el The context element
4809 * @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'})
4810 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
4811 * @return {HTMLElement/Roo.Element} The new node or Element
4813 append : function(el, values, returnElement){
4814 return this.doInsert('beforeEnd', el, values, returnElement);
4817 doInsert : function(where, el, values, returnEl){
4818 el = Roo.getDom(el);
4819 var newNode = Roo.DomHelper.insertHtml(where, el, this.applyTemplate(values));
4820 return returnEl ? Roo.get(newNode, true) : newNode;
4824 * Applies the supplied values to the template and overwrites the content of el with the new node(s).
4825 * @param {String/HTMLElement/Roo.Element} el The context element
4826 * @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'})
4827 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
4828 * @return {HTMLElement/Roo.Element} The new node or Element
4830 overwrite : function(el, values, returnElement){
4831 el = Roo.getDom(el);
4832 el.innerHTML = this.applyTemplate(values);
4833 return returnElement ? Roo.get(el.firstChild, true) : el.firstChild;
4837 * Alias for {@link #applyTemplate}
4840 Roo.Template.prototype.apply = Roo.Template.prototype.applyTemplate;
4843 Roo.DomHelper.Template = Roo.Template;
4846 * Creates a template from the passed element's value (<i>display:none</i> textarea, preferred) or innerHTML.
4847 * @param {String/HTMLElement} el A DOM element or its id
4848 * @returns {Roo.Template} The created template
4851 Roo.Template.from = function(el){
4852 el = Roo.getDom(el);
4853 return new Roo.Template(el.value || el.innerHTML);
4856 * Ext JS Library 1.1.1
4857 * Copyright(c) 2006-2007, Ext JS, LLC.
4859 * Originally Released Under LGPL - original licence link has changed is not relivant.
4862 * <script type="text/javascript">
4867 * This is code is also distributed under MIT license for use
4868 * with jQuery and prototype JavaScript libraries.
4871 * @class Roo.DomQuery
4872 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).
4874 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>
4877 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.
4879 <h4>Element Selectors:</h4>
4881 <li> <b>*</b> any element</li>
4882 <li> <b>E</b> an element with the tag E</li>
4883 <li> <b>E F</b> All descendent elements of E that have the tag F</li>
4884 <li> <b>E > F</b> or <b>E/F</b> all direct children elements of E that have the tag F</li>
4885 <li> <b>E + F</b> all elements with the tag F that are immediately preceded by an element with the tag E</li>
4886 <li> <b>E ~ F</b> all elements with the tag F that are preceded by a sibling element with the tag E</li>
4888 <h4>Attribute Selectors:</h4>
4889 <p>The use of @ and quotes are optional. For example, div[@foo='bar'] is also a valid attribute selector.</p>
4891 <li> <b>E[foo]</b> has an attribute "foo"</li>
4892 <li> <b>E[foo=bar]</b> has an attribute "foo" that equals "bar"</li>
4893 <li> <b>E[foo^=bar]</b> has an attribute "foo" that starts with "bar"</li>
4894 <li> <b>E[foo$=bar]</b> has an attribute "foo" that ends with "bar"</li>
4895 <li> <b>E[foo*=bar]</b> has an attribute "foo" that contains the substring "bar"</li>
4896 <li> <b>E[foo%=2]</b> has an attribute "foo" that is evenly divisible by 2</li>
4897 <li> <b>E[foo!=bar]</b> has an attribute "foo" that does not equal "bar"</li>
4899 <h4>Pseudo Classes:</h4>
4901 <li> <b>E:first-child</b> E is the first child of its parent</li>
4902 <li> <b>E:last-child</b> E is the last child of its parent</li>
4903 <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>
4904 <li> <b>E:nth-child(odd)</b> E is an odd child of its parent</li>
4905 <li> <b>E:nth-child(even)</b> E is an even child of its parent</li>
4906 <li> <b>E:only-child</b> E is the only child of its parent</li>
4907 <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>
4908 <li> <b>E:first</b> the first E in the resultset</li>
4909 <li> <b>E:last</b> the last E in the resultset</li>
4910 <li> <b>E:nth(<i>n</i>)</b> the <i>n</i>th E in the resultset (1 based)</li>
4911 <li> <b>E:odd</b> shortcut for :nth-child(odd)</li>
4912 <li> <b>E:even</b> shortcut for :nth-child(even)</li>
4913 <li> <b>E:contains(foo)</b> E's innerHTML contains the substring "foo"</li>
4914 <li> <b>E:nodeValue(foo)</b> E contains a textNode with a nodeValue that equals "foo"</li>
4915 <li> <b>E:not(S)</b> an E element that does not match simple selector S</li>
4916 <li> <b>E:has(S)</b> an E element that has a descendent that matches simple selector S</li>
4917 <li> <b>E:next(S)</b> an E element whose next sibling matches simple selector S</li>
4918 <li> <b>E:prev(S)</b> an E element whose previous sibling matches simple selector S</li>
4920 <h4>CSS Value Selectors:</h4>
4922 <li> <b>E{display=none}</b> css value "display" that equals "none"</li>
4923 <li> <b>E{display^=none}</b> css value "display" that starts with "none"</li>
4924 <li> <b>E{display$=none}</b> css value "display" that ends with "none"</li>
4925 <li> <b>E{display*=none}</b> css value "display" that contains the substring "none"</li>
4926 <li> <b>E{display%=2}</b> css value "display" that is evenly divisible by 2</li>
4927 <li> <b>E{display!=none}</b> css value "display" that does not equal "none"</li>
4931 Roo.DomQuery = function(){
4932 var cache = {}, simpleCache = {}, valueCache = {};
4933 var nonSpace = /\S/;
4934 var trimRe = /^\s+|\s+$/g;
4935 var tplRe = /\{(\d+)\}/g;
4936 var modeRe = /^(\s?[\/>+~]\s?|\s|$)/;
4937 var tagTokenRe = /^(#)?([\w-\*]+)/;
4938 var nthRe = /(\d*)n\+?(\d*)/, nthRe2 = /\D/;
4940 function child(p, index){
4942 var n = p.firstChild;
4944 if(n.nodeType == 1){
4955 while((n = n.nextSibling) && n.nodeType != 1);
4960 while((n = n.previousSibling) && n.nodeType != 1);
4964 function children(d){
4965 var n = d.firstChild, ni = -1;
4967 var nx = n.nextSibling;
4968 if(n.nodeType == 3 && !nonSpace.test(n.nodeValue)){
4978 function byClassName(c, a, v){
4982 var r = [], ri = -1, cn;
4983 for(var i = 0, ci; ci = c[i]; i++){
4984 if((' '+ci.className+' ').indexOf(v) != -1){
4991 function attrValue(n, attr){
4992 if(!n.tagName && typeof n.length != "undefined"){
5001 if(attr == "class" || attr == "className"){
5004 return n.getAttribute(attr) || n[attr];
5008 function getNodes(ns, mode, tagName){
5009 var result = [], ri = -1, cs;
5013 tagName = tagName || "*";
5014 if(typeof ns.getElementsByTagName != "undefined"){
5018 for(var i = 0, ni; ni = ns[i]; i++){
5019 cs = ni.getElementsByTagName(tagName);
5020 for(var j = 0, ci; ci = cs[j]; j++){
5024 }else if(mode == "/" || mode == ">"){
5025 var utag = tagName.toUpperCase();
5026 for(var i = 0, ni, cn; ni = ns[i]; i++){
5027 cn = ni.children || ni.childNodes;
5028 for(var j = 0, cj; cj = cn[j]; j++){
5029 if(cj.nodeName == utag || cj.nodeName == tagName || tagName == '*'){
5034 }else if(mode == "+"){
5035 var utag = tagName.toUpperCase();
5036 for(var i = 0, n; n = ns[i]; i++){
5037 while((n = n.nextSibling) && n.nodeType != 1);
5038 if(n && (n.nodeName == utag || n.nodeName == tagName || tagName == '*')){
5042 }else if(mode == "~"){
5043 for(var i = 0, n; n = ns[i]; i++){
5044 while((n = n.nextSibling) && (n.nodeType != 1 || (tagName == '*' || n.tagName.toLowerCase()!=tagName)));
5053 function concat(a, b){
5057 for(var i = 0, l = b.length; i < l; i++){
5063 function byTag(cs, tagName){
5064 if(cs.tagName || cs == document){
5070 var r = [], ri = -1;
5071 tagName = tagName.toLowerCase();
5072 for(var i = 0, ci; ci = cs[i]; i++){
5073 if(ci.nodeType == 1 && ci.tagName.toLowerCase()==tagName){
5080 function byId(cs, attr, id){
5081 if(cs.tagName || cs == document){
5087 var r = [], ri = -1;
5088 for(var i = 0,ci; ci = cs[i]; i++){
5089 if(ci && ci.id == id){
5097 function byAttribute(cs, attr, value, op, custom){
5098 var r = [], ri = -1, st = custom=="{";
5099 var f = Roo.DomQuery.operators[op];
5100 for(var i = 0, ci; ci = cs[i]; i++){
5103 a = Roo.DomQuery.getStyle(ci, attr);
5105 else if(attr == "class" || attr == "className"){
5107 }else if(attr == "for"){
5109 }else if(attr == "href"){
5110 a = ci.getAttribute("href", 2);
5112 a = ci.getAttribute(attr);
5114 if((f && f(a, value)) || (!f && a)){
5121 function byPseudo(cs, name, value){
5122 return Roo.DomQuery.pseudos[name](cs, value);
5125 // This is for IE MSXML which does not support expandos.
5126 // IE runs the same speed using setAttribute, however FF slows way down
5127 // and Safari completely fails so they need to continue to use expandos.
5128 var isIE = window.ActiveXObject ? true : false;
5130 // this eval is stop the compressor from
5131 // renaming the variable to something shorter
5133 /** eval:var:batch */
5138 function nodupIEXml(cs){
5140 cs[0].setAttribute("_nodup", d);
5142 for(var i = 1, len = cs.length; i < len; i++){
5144 if(!c.getAttribute("_nodup") != d){
5145 c.setAttribute("_nodup", d);
5149 for(var i = 0, len = cs.length; i < len; i++){
5150 cs[i].removeAttribute("_nodup");
5159 var len = cs.length, c, i, r = cs, cj, ri = -1;
5160 if(!len || typeof cs.nodeType != "undefined" || len == 1){
5163 if(isIE && typeof cs[0].selectSingleNode != "undefined"){
5164 return nodupIEXml(cs);
5168 for(i = 1; c = cs[i]; i++){
5173 for(var j = 0; j < i; j++){
5176 for(j = i+1; cj = cs[j]; j++){
5188 function quickDiffIEXml(c1, c2){
5190 for(var i = 0, len = c1.length; i < len; i++){
5191 c1[i].setAttribute("_qdiff", d);
5194 for(var i = 0, len = c2.length; i < len; i++){
5195 if(c2[i].getAttribute("_qdiff") != d){
5196 r[r.length] = c2[i];
5199 for(var i = 0, len = c1.length; i < len; i++){
5200 c1[i].removeAttribute("_qdiff");
5205 function quickDiff(c1, c2){
5206 var len1 = c1.length;
5210 if(isIE && c1[0].selectSingleNode){
5211 return quickDiffIEXml(c1, c2);
5214 for(var i = 0; i < len1; i++){
5218 for(var i = 0, len = c2.length; i < len; i++){
5219 if(c2[i]._qdiff != d){
5220 r[r.length] = c2[i];
5226 function quickId(ns, mode, root, id){
5228 var d = root.ownerDocument || root;
5229 return d.getElementById(id);
5231 ns = getNodes(ns, mode, "*");
5232 return byId(ns, null, id);
5236 getStyle : function(el, name){
5237 return Roo.fly(el).getStyle(name);
5240 * Compiles a selector/xpath query into a reusable function. The returned function
5241 * takes one parameter "root" (optional), which is the context node from where the query should start.
5242 * @param {String} selector The selector/xpath query
5243 * @param {String} type (optional) Either "select" (the default) or "simple" for a simple selector match
5244 * @return {Function}
5246 compile : function(path, type){
5247 type = type || "select";
5249 var fn = ["var f = function(root){\n var mode; ++batch; var n = root || document;\n"];
5250 var q = path, mode, lq;
5251 var tk = Roo.DomQuery.matchers;
5252 var tklen = tk.length;
5255 // accept leading mode switch
5256 var lmode = q.match(modeRe);
5257 if(lmode && lmode[1]){
5258 fn[fn.length] = 'mode="'+lmode[1].replace(trimRe, "")+'";';
5259 q = q.replace(lmode[1], "");
5261 // strip leading slashes
5262 while(path.substr(0, 1)=="/"){
5263 path = path.substr(1);
5266 while(q && lq != q){
5268 var tm = q.match(tagTokenRe);
5269 if(type == "select"){
5272 fn[fn.length] = 'n = quickId(n, mode, root, "'+tm[2]+'");';
5274 fn[fn.length] = 'n = getNodes(n, mode, "'+tm[2]+'");';
5276 q = q.replace(tm[0], "");
5277 }else if(q.substr(0, 1) != '@'){
5278 fn[fn.length] = 'n = getNodes(n, mode, "*");';
5283 fn[fn.length] = 'n = byId(n, null, "'+tm[2]+'");';
5285 fn[fn.length] = 'n = byTag(n, "'+tm[2]+'");';
5287 q = q.replace(tm[0], "");
5290 while(!(mm = q.match(modeRe))){
5291 var matched = false;
5292 for(var j = 0; j < tklen; j++){
5294 var m = q.match(t.re);
5296 fn[fn.length] = t.select.replace(tplRe, function(x, i){
5299 q = q.replace(m[0], "");
5304 // prevent infinite loop on bad selector
5306 throw 'Error parsing selector, parsing failed at "' + q + '"';
5310 fn[fn.length] = 'mode="'+mm[1].replace(trimRe, "")+'";';
5311 q = q.replace(mm[1], "");
5314 fn[fn.length] = "return nodup(n);\n}";
5317 * list of variables that need from compression as they are used by eval.
5327 * eval:var:byClassName
5329 * eval:var:byAttribute
5330 * eval:var:attrValue
5338 * Selects a group of elements.
5339 * @param {String} selector The selector/xpath query (can be a comma separated list of selectors)
5340 * @param {Node} root (optional) The start of the query (defaults to document).
5343 select : function(path, root, type){
5344 if(!root || root == document){
5347 if(typeof root == "string"){
5348 root = document.getElementById(root);
5350 var paths = path.split(",");
5352 for(var i = 0, len = paths.length; i < len; i++){
5353 var p = paths[i].replace(trimRe, "");
5355 cache[p] = Roo.DomQuery.compile(p);
5357 throw p + " is not a valid selector";
5360 var result = cache[p](root);
5361 if(result && result != document){
5362 results = results.concat(result);
5365 if(paths.length > 1){
5366 return nodup(results);
5372 * Selects a single element.
5373 * @param {String} selector The selector/xpath query
5374 * @param {Node} root (optional) The start of the query (defaults to document).
5377 selectNode : function(path, root){
5378 return Roo.DomQuery.select(path, root)[0];
5382 * Selects the value of a node, optionally replacing null with the defaultValue.
5383 * @param {String} selector The selector/xpath query
5384 * @param {Node} root (optional) The start of the query (defaults to document).
5385 * @param {String} defaultValue
5387 selectValue : function(path, root, defaultValue){
5388 path = path.replace(trimRe, "");
5389 if(!valueCache[path]){
5390 valueCache[path] = Roo.DomQuery.compile(path, "select");
5392 var n = valueCache[path](root);
5393 n = n[0] ? n[0] : n;
5394 var v = (n && n.firstChild ? n.firstChild.nodeValue : null);
5395 return ((v === null||v === undefined||v==='') ? defaultValue : v);
5399 * Selects the value of a node, parsing integers and floats.
5400 * @param {String} selector The selector/xpath query
5401 * @param {Node} root (optional) The start of the query (defaults to document).
5402 * @param {Number} defaultValue
5405 selectNumber : function(path, root, defaultValue){
5406 var v = Roo.DomQuery.selectValue(path, root, defaultValue || 0);
5407 return parseFloat(v);
5411 * Returns true if the passed element(s) match the passed simple selector (e.g. div.some-class or span:first-child)
5412 * @param {String/HTMLElement/Array} el An element id, element or array of elements
5413 * @param {String} selector The simple selector to test
5416 is : function(el, ss){
5417 if(typeof el == "string"){
5418 el = document.getElementById(el);
5420 var isArray = (el instanceof Array);
5421 var result = Roo.DomQuery.filter(isArray ? el : [el], ss);
5422 return isArray ? (result.length == el.length) : (result.length > 0);
5426 * Filters an array of elements to only include matches of a simple selector (e.g. div.some-class or span:first-child)
5427 * @param {Array} el An array of elements to filter
5428 * @param {String} selector The simple selector to test
5429 * @param {Boolean} nonMatches If true, it returns the elements that DON'T match
5430 * the selector instead of the ones that match
5433 filter : function(els, ss, nonMatches){
5434 ss = ss.replace(trimRe, "");
5435 if(!simpleCache[ss]){
5436 simpleCache[ss] = Roo.DomQuery.compile(ss, "simple");
5438 var result = simpleCache[ss](els);
5439 return nonMatches ? quickDiff(result, els) : result;
5443 * Collection of matching regular expressions and code snippets.
5447 select: 'n = byClassName(n, null, " {1} ");'
5449 re: /^\:([\w-]+)(?:\(((?:[^\s>\/]*|.*?))\))?/,
5450 select: 'n = byPseudo(n, "{1}", "{2}");'
5452 re: /^(?:([\[\{])(?:@)?([\w-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]\}])/,
5453 select: 'n = byAttribute(n, "{2}", "{4}", "{3}", "{1}");'
5456 select: 'n = byId(n, null, "{1}");'
5459 select: 'return {firstChild:{nodeValue:attrValue(n, "{1}")}};'
5464 * Collection of operator comparison functions. The default operators are =, !=, ^=, $=, *=, %=, |= and ~=.
5465 * 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, > <.
5468 "=" : function(a, v){
5471 "!=" : function(a, v){
5474 "^=" : function(a, v){
5475 return a && a.substr(0, v.length) == v;
5477 "$=" : function(a, v){
5478 return a && a.substr(a.length-v.length) == v;
5480 "*=" : function(a, v){
5481 return a && a.indexOf(v) !== -1;
5483 "%=" : function(a, v){
5484 return (a % v) == 0;
5486 "|=" : function(a, v){
5487 return a && (a == v || a.substr(0, v.length+1) == v+'-');
5489 "~=" : function(a, v){
5490 return a && (' '+a+' ').indexOf(' '+v+' ') != -1;
5495 * Collection of "pseudo class" processors. Each processor is passed the current nodeset (array)
5496 * and the argument (if any) supplied in the selector.
5499 "first-child" : function(c){
5500 var r = [], ri = -1, n;
5501 for(var i = 0, ci; ci = n = c[i]; i++){
5502 while((n = n.previousSibling) && n.nodeType != 1);
5510 "last-child" : function(c){
5511 var r = [], ri = -1, n;
5512 for(var i = 0, ci; ci = n = c[i]; i++){
5513 while((n = n.nextSibling) && n.nodeType != 1);
5521 "nth-child" : function(c, a) {
5522 var r = [], ri = -1;
5523 var m = nthRe.exec(a == "even" && "2n" || a == "odd" && "2n+1" || !nthRe2.test(a) && "n+" + a || a);
5524 var f = (m[1] || 1) - 0, l = m[2] - 0;
5525 for(var i = 0, n; n = c[i]; i++){
5526 var pn = n.parentNode;
5527 if (batch != pn._batch) {
5529 for(var cn = pn.firstChild; cn; cn = cn.nextSibling){
5530 if(cn.nodeType == 1){
5537 if (l == 0 || n.nodeIndex == l){
5540 } else if ((n.nodeIndex + l) % f == 0){
5548 "only-child" : function(c){
5549 var r = [], ri = -1;;
5550 for(var i = 0, ci; ci = c[i]; i++){
5551 if(!prev(ci) && !next(ci)){
5558 "empty" : function(c){
5559 var r = [], ri = -1;
5560 for(var i = 0, ci; ci = c[i]; i++){
5561 var cns = ci.childNodes, j = 0, cn, empty = true;
5564 if(cn.nodeType == 1 || cn.nodeType == 3){
5576 "contains" : function(c, v){
5577 var r = [], ri = -1;
5578 for(var i = 0, ci; ci = c[i]; i++){
5579 if((ci.textContent||ci.innerText||'').indexOf(v) != -1){
5586 "nodeValue" : function(c, v){
5587 var r = [], ri = -1;
5588 for(var i = 0, ci; ci = c[i]; i++){
5589 if(ci.firstChild && ci.firstChild.nodeValue == v){
5596 "checked" : function(c){
5597 var r = [], ri = -1;
5598 for(var i = 0, ci; ci = c[i]; i++){
5599 if(ci.checked == true){
5606 "not" : function(c, ss){
5607 return Roo.DomQuery.filter(c, ss, true);
5610 "odd" : function(c){
5611 return this["nth-child"](c, "odd");
5614 "even" : function(c){
5615 return this["nth-child"](c, "even");
5618 "nth" : function(c, a){
5619 return c[a-1] || [];
5622 "first" : function(c){
5626 "last" : function(c){
5627 return c[c.length-1] || [];
5630 "has" : function(c, ss){
5631 var s = Roo.DomQuery.select;
5632 var r = [], ri = -1;
5633 for(var i = 0, ci; ci = c[i]; i++){
5634 if(s(ss, ci).length > 0){
5641 "next" : function(c, ss){
5642 var is = Roo.DomQuery.is;
5643 var r = [], ri = -1;
5644 for(var i = 0, ci; ci = c[i]; i++){
5653 "prev" : function(c, ss){
5654 var is = Roo.DomQuery.is;
5655 var r = [], ri = -1;
5656 for(var i = 0, ci; ci = c[i]; i++){
5669 * Selects an array of DOM nodes by CSS/XPath selector. Shorthand of {@link Roo.DomQuery#select}
5670 * @param {String} path The selector/xpath query
5671 * @param {Node} root (optional) The start of the query (defaults to document).
5676 Roo.query = Roo.DomQuery.select;
5679 * Ext JS Library 1.1.1
5680 * Copyright(c) 2006-2007, Ext JS, LLC.
5682 * Originally Released Under LGPL - original licence link has changed is not relivant.
5685 * <script type="text/javascript">
5689 * @class Roo.util.Observable
5690 * Base class that provides a common interface for publishing events. Subclasses are expected to
5691 * to have a property "events" with all the events defined.<br>
5694 Employee = function(name){
5701 Roo.extend(Employee, Roo.util.Observable);
5703 * @param {Object} config properties to use (incuding events / listeners)
5706 Roo.util.Observable = function(cfg){
5709 this.addEvents(cfg.events || {});
5711 delete cfg.events; // make sure
5714 Roo.apply(this, cfg);
5717 this.on(this.listeners);
5718 delete this.listeners;
5721 Roo.util.Observable.prototype = {
5723 * @cfg {Object} listeners list of events and functions to call for this object,
5727 'click' : function(e) {
5737 * Fires the specified event with the passed parameters (minus the event name).
5738 * @param {String} eventName
5739 * @param {Object...} args Variable number of parameters are passed to handlers
5740 * @return {Boolean} returns false if any of the handlers return false otherwise it returns true
5742 fireEvent : function(){
5743 var ce = this.events[arguments[0].toLowerCase()];
5744 if(typeof ce == "object"){
5745 return ce.fire.apply(ce, Array.prototype.slice.call(arguments, 1));
5752 filterOptRe : /^(?:scope|delay|buffer|single)$/,
5755 * Appends an event handler to this component
5756 * @param {String} eventName The type of event to listen for
5757 * @param {Function} handler The method the event invokes
5758 * @param {Object} scope (optional) The scope in which to execute the handler
5759 * function. The handler function's "this" context.
5760 * @param {Object} options (optional) An object containing handler configuration
5761 * properties. This may contain any of the following properties:<ul>
5762 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
5763 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
5764 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
5765 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
5766 * by the specified number of milliseconds. If the event fires again within that time, the original
5767 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
5770 * <b>Combining Options</b><br>
5771 * Using the options argument, it is possible to combine different types of listeners:<br>
5773 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)
5775 el.on('click', this.onClick, this, {
5782 * <b>Attaching multiple handlers in 1 call</b><br>
5783 * The method also allows for a single argument to be passed which is a config object containing properties
5784 * which specify multiple handlers.
5793 fn: this.onMouseOver,
5797 fn: this.onMouseOut,
5803 * Or a shorthand syntax which passes the same scope object to all handlers:
5806 'click': this.onClick,
5807 'mouseover': this.onMouseOver,
5808 'mouseout': this.onMouseOut,
5813 addListener : function(eventName, fn, scope, o){
5814 if(typeof eventName == "object"){
5817 if(this.filterOptRe.test(e)){
5820 if(typeof o[e] == "function"){
5822 this.addListener(e, o[e], o.scope, o);
5824 // individual options
5825 this.addListener(e, o[e].fn, o[e].scope, o[e]);
5830 o = (!o || typeof o == "boolean") ? {} : o;
5831 eventName = eventName.toLowerCase();
5832 var ce = this.events[eventName] || true;
5833 if(typeof ce == "boolean"){
5834 ce = new Roo.util.Event(this, eventName);
5835 this.events[eventName] = ce;
5837 ce.addListener(fn, scope, o);
5841 * Removes a listener
5842 * @param {String} eventName The type of event to listen for
5843 * @param {Function} handler The handler to remove
5844 * @param {Object} scope (optional) The scope (this object) for the handler
5846 removeListener : function(eventName, fn, scope){
5847 var ce = this.events[eventName.toLowerCase()];
5848 if(typeof ce == "object"){
5849 ce.removeListener(fn, scope);
5854 * Removes all listeners for this object
5856 purgeListeners : function(){
5857 for(var evt in this.events){
5858 if(typeof this.events[evt] == "object"){
5859 this.events[evt].clearListeners();
5864 relayEvents : function(o, events){
5865 var createHandler = function(ename){
5867 return this.fireEvent.apply(this, Roo.combine(ename, Array.prototype.slice.call(arguments, 0)));
5870 for(var i = 0, len = events.length; i < len; i++){
5871 var ename = events[i];
5872 if(!this.events[ename]){ this.events[ename] = true; };
5873 o.on(ename, createHandler(ename), this);
5878 * Used to define events on this Observable
5879 * @param {Object} object The object with the events defined
5881 addEvents : function(o){
5885 Roo.applyIf(this.events, o);
5889 * Checks to see if this object has any listeners for a specified event
5890 * @param {String} eventName The name of the event to check for
5891 * @return {Boolean} True if the event is being listened for, else false
5893 hasListener : function(eventName){
5894 var e = this.events[eventName];
5895 return typeof e == "object" && e.listeners.length > 0;
5899 * Appends an event handler to this element (shorthand for addListener)
5900 * @param {String} eventName The type of event to listen for
5901 * @param {Function} handler The method the event invokes
5902 * @param {Object} scope (optional) The scope in which to execute the handler
5903 * function. The handler function's "this" context.
5904 * @param {Object} options (optional)
5907 Roo.util.Observable.prototype.on = Roo.util.Observable.prototype.addListener;
5909 * Removes a listener (shorthand for removeListener)
5910 * @param {String} eventName The type of event to listen for
5911 * @param {Function} handler The handler to remove
5912 * @param {Object} scope (optional) The scope (this object) for the handler
5915 Roo.util.Observable.prototype.un = Roo.util.Observable.prototype.removeListener;
5918 * Starts capture on the specified Observable. All events will be passed
5919 * to the supplied function with the event name + standard signature of the event
5920 * <b>before</b> the event is fired. If the supplied function returns false,
5921 * the event will not fire.
5922 * @param {Observable} o The Observable to capture
5923 * @param {Function} fn The function to call
5924 * @param {Object} scope (optional) The scope (this object) for the fn
5927 Roo.util.Observable.capture = function(o, fn, scope){
5928 o.fireEvent = o.fireEvent.createInterceptor(fn, scope);
5932 * Removes <b>all</b> added captures from the Observable.
5933 * @param {Observable} o The Observable to release
5936 Roo.util.Observable.releaseCapture = function(o){
5937 o.fireEvent = Roo.util.Observable.prototype.fireEvent;
5942 var createBuffered = function(h, o, scope){
5943 var task = new Roo.util.DelayedTask();
5945 task.delay(o.buffer, h, scope, Array.prototype.slice.call(arguments, 0));
5949 var createSingle = function(h, e, fn, scope){
5951 e.removeListener(fn, scope);
5952 return h.apply(scope, arguments);
5956 var createDelayed = function(h, o, scope){
5958 var args = Array.prototype.slice.call(arguments, 0);
5959 setTimeout(function(){
5960 h.apply(scope, args);
5965 Roo.util.Event = function(obj, name){
5968 this.listeners = [];
5971 Roo.util.Event.prototype = {
5972 addListener : function(fn, scope, options){
5973 var o = options || {};
5974 scope = scope || this.obj;
5975 if(!this.isListening(fn, scope)){
5976 var l = {fn: fn, scope: scope, options: o};
5979 h = createDelayed(h, o, scope);
5982 h = createSingle(h, this, fn, scope);
5985 h = createBuffered(h, o, scope);
5988 if(!this.firing){ // if we are currently firing this event, don't disturb the listener loop
5989 this.listeners.push(l);
5991 this.listeners = this.listeners.slice(0);
5992 this.listeners.push(l);
5997 findListener : function(fn, scope){
5998 scope = scope || this.obj;
5999 var ls = this.listeners;
6000 for(var i = 0, len = ls.length; i < len; i++){
6002 if(l.fn == fn && l.scope == scope){
6009 isListening : function(fn, scope){
6010 return this.findListener(fn, scope) != -1;
6013 removeListener : function(fn, scope){
6015 if((index = this.findListener(fn, scope)) != -1){
6017 this.listeners.splice(index, 1);
6019 this.listeners = this.listeners.slice(0);
6020 this.listeners.splice(index, 1);
6027 clearListeners : function(){
6028 this.listeners = [];
6032 var ls = this.listeners, scope, len = ls.length;
6035 var args = Array.prototype.slice.call(arguments, 0);
6036 for(var i = 0; i < len; i++){
6038 if(l.fireFn.apply(l.scope||this.obj||window, arguments) === false){
6039 this.firing = false;
6043 this.firing = false;
6050 * Ext JS Library 1.1.1
6051 * Copyright(c) 2006-2007, Ext JS, LLC.
6053 * Originally Released Under LGPL - original licence link has changed is not relivant.
6056 * <script type="text/javascript">
6060 * @class Roo.EventManager
6061 * Registers event handlers that want to receive a normalized EventObject instead of the standard browser event and provides
6062 * several useful events directly.
6063 * See {@link Roo.EventObject} for more details on normalized event objects.
6066 Roo.EventManager = function(){
6067 var docReadyEvent, docReadyProcId, docReadyState = false;
6068 var resizeEvent, resizeTask, textEvent, textSize;
6069 var E = Roo.lib.Event;
6070 var D = Roo.lib.Dom;
6075 var fireDocReady = function(){
6077 docReadyState = true;
6080 clearInterval(docReadyProcId);
6082 if(Roo.isGecko || Roo.isOpera) {
6083 document.removeEventListener("DOMContentLoaded", fireDocReady, false);
6086 var defer = document.getElementById("ie-deferred-loader");
6088 defer.onreadystatechange = null;
6089 defer.parentNode.removeChild(defer);
6093 docReadyEvent.fire();
6094 docReadyEvent.clearListeners();
6099 var initDocReady = function(){
6100 docReadyEvent = new Roo.util.Event();
6101 if(Roo.isGecko || Roo.isOpera) {
6102 document.addEventListener("DOMContentLoaded", fireDocReady, false);
6104 document.write("<s"+'cript id="ie-deferred-loader" defer="defer" src="/'+'/:"></s'+"cript>");
6105 var defer = document.getElementById("ie-deferred-loader");
6106 defer.onreadystatechange = function(){
6107 if(this.readyState == "complete"){
6111 }else if(Roo.isSafari){
6112 docReadyProcId = setInterval(function(){
6113 var rs = document.readyState;
6114 if(rs == "complete") {
6119 // no matter what, make sure it fires on load
6120 E.on(window, "load", fireDocReady);
6123 var createBuffered = function(h, o){
6124 var task = new Roo.util.DelayedTask(h);
6126 // create new event object impl so new events don't wipe out properties
6127 e = new Roo.EventObjectImpl(e);
6128 task.delay(o.buffer, h, null, [e]);
6132 var createSingle = function(h, el, ename, fn){
6134 Roo.EventManager.removeListener(el, ename, fn);
6139 var createDelayed = function(h, o){
6141 // create new event object impl so new events don't wipe out properties
6142 e = new Roo.EventObjectImpl(e);
6143 setTimeout(function(){
6148 var transitionEndVal = false;
6150 var transitionEnd = function()
6152 if (transitionEndVal) {
6153 return transitionEndVal;
6155 var el = document.createElement('div');
6157 var transEndEventNames = {
6158 WebkitTransition : 'webkitTransitionEnd',
6159 MozTransition : 'transitionend',
6160 OTransition : 'oTransitionEnd otransitionend',
6161 transition : 'transitionend'
6164 for (var name in transEndEventNames) {
6165 if (el.style[name] !== undefined) {
6166 transitionEndVal = transEndEventNames[name];
6167 return transitionEndVal ;
6173 var listen = function(element, ename, opt, fn, scope){
6174 var o = (!opt || typeof opt == "boolean") ? {} : opt;
6175 fn = fn || o.fn; scope = scope || o.scope;
6176 var el = Roo.getDom(element);
6180 throw "Error listening for \"" + ename + '\". Element "' + element + '" doesn\'t exist.';
6183 if (ename == 'transitionend') {
6184 ename = transitionEnd();
6186 var h = function(e){
6187 e = Roo.EventObject.setEvent(e);
6190 t = e.getTarget(o.delegate, el);
6197 if(o.stopEvent === true){
6200 if(o.preventDefault === true){
6203 if(o.stopPropagation === true){
6204 e.stopPropagation();
6207 if(o.normalized === false){
6211 fn.call(scope || el, e, t, o);
6214 h = createDelayed(h, o);
6217 h = createSingle(h, el, ename, fn);
6220 h = createBuffered(h, o);
6222 fn._handlers = fn._handlers || [];
6225 fn._handlers.push([Roo.id(el), ename, h]);
6230 if(ename == "mousewheel" && el.addEventListener){ // workaround for jQuery
6231 el.addEventListener("DOMMouseScroll", h, false);
6232 E.on(window, 'unload', function(){
6233 el.removeEventListener("DOMMouseScroll", h, false);
6236 if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
6237 Roo.EventManager.stoppedMouseDownEvent.addListener(h);
6242 var stopListening = function(el, ename, fn){
6243 var id = Roo.id(el), hds = fn._handlers, hd = fn;
6245 for(var i = 0, len = hds.length; i < len; i++){
6247 if(h[0] == id && h[1] == ename){
6254 E.un(el, ename, hd);
6255 el = Roo.getDom(el);
6256 if(ename == "mousewheel" && el.addEventListener){
6257 el.removeEventListener("DOMMouseScroll", hd, false);
6259 if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
6260 Roo.EventManager.stoppedMouseDownEvent.removeListener(hd);
6264 var propRe = /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/;
6271 * @scope Roo.EventManager
6276 * This is no longer needed and is deprecated. Places a simple wrapper around an event handler to override the browser event
6277 * object with a Roo.EventObject
6278 * @param {Function} fn The method the event invokes
6279 * @param {Object} scope An object that becomes the scope of the handler
6280 * @param {boolean} override If true, the obj passed in becomes
6281 * the execution scope of the listener
6282 * @return {Function} The wrapped function
6285 wrap : function(fn, scope, override){
6287 Roo.EventObject.setEvent(e);
6288 fn.call(override ? scope || window : window, Roo.EventObject, scope);
6293 * Appends an event handler to an element (shorthand for addListener)
6294 * @param {String/HTMLElement} element The html element or id to assign the
6295 * @param {String} eventName The type of event to listen for
6296 * @param {Function} handler The method the event invokes
6297 * @param {Object} scope (optional) The scope in which to execute the handler
6298 * function. The handler function's "this" context.
6299 * @param {Object} options (optional) An object containing handler configuration
6300 * properties. This may contain any of the following properties:<ul>
6301 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
6302 * <li>delegate {String} A simple selector to filter the target or look for a descendant of the target</li>
6303 * <li>stopEvent {Boolean} True to stop the event. That is stop propagation, and prevent the default action.</li>
6304 * <li>preventDefault {Boolean} True to prevent the default action</li>
6305 * <li>stopPropagation {Boolean} True to prevent event propagation</li>
6306 * <li>normalized {Boolean} False to pass a browser event to the handler function instead of an Roo.EventObject</li>
6307 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
6308 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
6309 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
6310 * by the specified number of milliseconds. If the event fires again within that time, the original
6311 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
6314 * <b>Combining Options</b><br>
6315 * Using the options argument, it is possible to combine different types of listeners:<br>
6317 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)<div style="margin: 5px 20px 20px;">
6319 el.on('click', this.onClick, this, {
6326 * <b>Attaching multiple handlers in 1 call</b><br>
6327 * The method also allows for a single argument to be passed which is a config object containing properties
6328 * which specify multiple handlers.
6338 fn: this.onMouseOver
6347 * Or a shorthand syntax:<br>
6350 'click' : this.onClick,
6351 'mouseover' : this.onMouseOver,
6352 'mouseout' : this.onMouseOut
6356 addListener : function(element, eventName, fn, scope, options){
6357 if(typeof eventName == "object"){
6363 if(typeof o[e] == "function"){
6365 listen(element, e, o, o[e], o.scope);
6367 // individual options
6368 listen(element, e, o[e]);
6373 return listen(element, eventName, options, fn, scope);
6377 * Removes an event handler
6379 * @param {String/HTMLElement} element The id or html element to remove the
6381 * @param {String} eventName The type of event
6382 * @param {Function} fn
6383 * @return {Boolean} True if a listener was actually removed
6385 removeListener : function(element, eventName, fn){
6386 return stopListening(element, eventName, fn);
6390 * Fires when the document is ready (before onload and before images are loaded). Can be
6391 * accessed shorthanded Roo.onReady().
6392 * @param {Function} fn The method the event invokes
6393 * @param {Object} scope An object that becomes the scope of the handler
6394 * @param {boolean} options
6396 onDocumentReady : function(fn, scope, options){
6397 if(docReadyState){ // if it already fired
6398 docReadyEvent.addListener(fn, scope, options);
6399 docReadyEvent.fire();
6400 docReadyEvent.clearListeners();
6406 docReadyEvent.addListener(fn, scope, options);
6410 * Fires when the window is resized and provides resize event buffering (50 milliseconds), passes new viewport width and height to handlers.
6411 * @param {Function} fn The method the event invokes
6412 * @param {Object} scope An object that becomes the scope of the handler
6413 * @param {boolean} options
6415 onWindowResize : function(fn, scope, options){
6417 resizeEvent = new Roo.util.Event();
6418 resizeTask = new Roo.util.DelayedTask(function(){
6419 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
6421 E.on(window, "resize", function(){
6423 resizeTask.delay(50);
6425 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
6429 resizeEvent.addListener(fn, scope, options);
6433 * Fires when the user changes the active text size. Handler gets called with 2 params, the old size and the new size.
6434 * @param {Function} fn The method the event invokes
6435 * @param {Object} scope An object that becomes the scope of the handler
6436 * @param {boolean} options
6438 onTextResize : function(fn, scope, options){
6440 textEvent = new Roo.util.Event();
6441 var textEl = new Roo.Element(document.createElement('div'));
6442 textEl.dom.className = 'x-text-resize';
6443 textEl.dom.innerHTML = 'X';
6444 textEl.appendTo(document.body);
6445 textSize = textEl.dom.offsetHeight;
6446 setInterval(function(){
6447 if(textEl.dom.offsetHeight != textSize){
6448 textEvent.fire(textSize, textSize = textEl.dom.offsetHeight);
6450 }, this.textResizeInterval);
6452 textEvent.addListener(fn, scope, options);
6456 * Removes the passed window resize listener.
6457 * @param {Function} fn The method the event invokes
6458 * @param {Object} scope The scope of handler
6460 removeResizeListener : function(fn, scope){
6462 resizeEvent.removeListener(fn, scope);
6467 fireResize : function(){
6469 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
6473 * Url used for onDocumentReady with using SSL (defaults to Roo.SSL_SECURE_URL)
6477 * The frequency, in milliseconds, to check for text resize events (defaults to 50)
6479 textResizeInterval : 50
6484 * @scopeAlias pub=Roo.EventManager
6488 * Appends an event handler to an element (shorthand for addListener)
6489 * @param {String/HTMLElement} element The html element or id to assign the
6490 * @param {String} eventName The type of event to listen for
6491 * @param {Function} handler The method the event invokes
6492 * @param {Object} scope (optional) The scope in which to execute the handler
6493 * function. The handler function's "this" context.
6494 * @param {Object} options (optional) An object containing handler configuration
6495 * properties. This may contain any of the following properties:<ul>
6496 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
6497 * <li>delegate {String} A simple selector to filter the target or look for a descendant of the target</li>
6498 * <li>stopEvent {Boolean} True to stop the event. That is stop propagation, and prevent the default action.</li>
6499 * <li>preventDefault {Boolean} True to prevent the default action</li>
6500 * <li>stopPropagation {Boolean} True to prevent event propagation</li>
6501 * <li>normalized {Boolean} False to pass a browser event to the handler function instead of an Roo.EventObject</li>
6502 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
6503 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
6504 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
6505 * by the specified number of milliseconds. If the event fires again within that time, the original
6506 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
6509 * <b>Combining Options</b><br>
6510 * Using the options argument, it is possible to combine different types of listeners:<br>
6512 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)<div style="margin: 5px 20px 20px;">
6514 el.on('click', this.onClick, this, {
6521 * <b>Attaching multiple handlers in 1 call</b><br>
6522 * The method also allows for a single argument to be passed which is a config object containing properties
6523 * which specify multiple handlers.
6533 fn: this.onMouseOver
6542 * Or a shorthand syntax:<br>
6545 'click' : this.onClick,
6546 'mouseover' : this.onMouseOver,
6547 'mouseout' : this.onMouseOut
6551 pub.on = pub.addListener;
6552 pub.un = pub.removeListener;
6554 pub.stoppedMouseDownEvent = new Roo.util.Event();
6558 * Fires when the document is ready (before onload and before images are loaded). Shorthand of {@link Roo.EventManager#onDocumentReady}.
6559 * @param {Function} fn The method the event invokes
6560 * @param {Object} scope An object that becomes the scope of the handler
6561 * @param {boolean} override If true, the obj passed in becomes
6562 * the execution scope of the listener
6566 Roo.onReady = Roo.EventManager.onDocumentReady;
6568 Roo.onReady(function(){
6569 var bd = Roo.get(document.body);
6574 : Roo.isGecko ? "roo-gecko"
6575 : Roo.isOpera ? "roo-opera"
6576 : Roo.isSafari ? "roo-safari" : ""];
6579 cls.push("roo-mac");
6582 cls.push("roo-linux");
6585 cls.push("roo-ios");
6587 if(Roo.isBorderBox){
6588 cls.push('roo-border-box');
6590 if(Roo.isStrict){ // add to the parent to allow for selectors like ".ext-strict .ext-ie"
6591 var p = bd.dom.parentNode;
6593 p.className += ' roo-strict';
6596 bd.addClass(cls.join(' '));
6600 * @class Roo.EventObject
6601 * EventObject exposes the Yahoo! UI Event functionality directly on the object
6602 * passed to your event handler. It exists mostly for convenience. It also fixes the annoying null checks automatically to cleanup your code
6605 function handleClick(e){ // e is not a standard event object, it is a Roo.EventObject
6607 var target = e.getTarget();
6610 var myDiv = Roo.get("myDiv");
6611 myDiv.on("click", handleClick);
6613 Roo.EventManager.on("myDiv", 'click', handleClick);
6614 Roo.EventManager.addListener("myDiv", 'click', handleClick);
6618 Roo.EventObject = function(){
6620 var E = Roo.lib.Event;
6622 // safari keypress events for special keys return bad keycodes
6625 63235 : 39, // right
6628 63276 : 33, // page up
6629 63277 : 34, // page down
6630 63272 : 46, // delete
6635 // normalize button clicks
6636 var btnMap = Roo.isIE ? {1:0,4:1,2:2} :
6637 (Roo.isSafari ? {1:0,2:1,3:2} : {0:0,1:1,2:2});
6639 Roo.EventObjectImpl = function(e){
6641 this.setEvent(e.browserEvent || e);
6644 Roo.EventObjectImpl.prototype = {
6646 * Used to fix doc tools.
6647 * @scope Roo.EventObject.prototype
6653 /** The normal browser event */
6654 browserEvent : null,
6655 /** The button pressed in a mouse event */
6657 /** True if the shift key was down during the event */
6659 /** True if the control key was down during the event */
6661 /** True if the alt key was down during the event */
6720 setEvent : function(e){
6721 if(e == this || (e && e.browserEvent)){ // already wrapped
6724 this.browserEvent = e;
6726 // normalize buttons
6727 this.button = e.button ? btnMap[e.button] : (e.which ? e.which-1 : -1);
6728 if(e.type == 'click' && this.button == -1){
6732 this.shiftKey = e.shiftKey;
6733 // mac metaKey behaves like ctrlKey
6734 this.ctrlKey = e.ctrlKey || e.metaKey;
6735 this.altKey = e.altKey;
6736 // in getKey these will be normalized for the mac
6737 this.keyCode = e.keyCode;
6738 // keyup warnings on firefox.
6739 this.charCode = (e.type == 'keyup' || e.type == 'keydown') ? 0 : e.charCode;
6740 // cache the target for the delayed and or buffered events
6741 this.target = E.getTarget(e);
6743 this.xy = E.getXY(e);
6746 this.shiftKey = false;
6747 this.ctrlKey = false;
6748 this.altKey = false;
6758 * Stop the event (preventDefault and stopPropagation)
6760 stopEvent : function(){
6761 if(this.browserEvent){
6762 if(this.browserEvent.type == 'mousedown'){
6763 Roo.EventManager.stoppedMouseDownEvent.fire(this);
6765 E.stopEvent(this.browserEvent);
6770 * Prevents the browsers default handling of the event.
6772 preventDefault : function(){
6773 if(this.browserEvent){
6774 E.preventDefault(this.browserEvent);
6779 isNavKeyPress : function(){
6780 var k = this.keyCode;
6781 k = Roo.isSafari ? (safariKeys[k] || k) : k;
6782 return (k >= 33 && k <= 40) || k == this.RETURN || k == this.TAB || k == this.ESC;
6785 isSpecialKey : function(){
6786 var k = this.keyCode;
6787 return (this.type == 'keypress' && this.ctrlKey) || k == 9 || k == 13 || k == 40 || k == 27 ||
6788 (k == 16) || (k == 17) ||
6789 (k >= 18 && k <= 20) ||
6790 (k >= 33 && k <= 35) ||
6791 (k >= 36 && k <= 39) ||
6792 (k >= 44 && k <= 45);
6795 * Cancels bubbling of the event.
6797 stopPropagation : function(){
6798 if(this.browserEvent){
6799 if(this.type == 'mousedown'){
6800 Roo.EventManager.stoppedMouseDownEvent.fire(this);
6802 E.stopPropagation(this.browserEvent);
6807 * Gets the key code for the event.
6810 getCharCode : function(){
6811 return this.charCode || this.keyCode;
6815 * Returns a normalized keyCode for the event.
6816 * @return {Number} The key code
6818 getKey : function(){
6819 var k = this.keyCode || this.charCode;
6820 return Roo.isSafari ? (safariKeys[k] || k) : k;
6824 * Gets the x coordinate of the event.
6827 getPageX : function(){
6832 * Gets the y coordinate of the event.
6835 getPageY : function(){
6840 * Gets the time of the event.
6843 getTime : function(){
6844 if(this.browserEvent){
6845 return E.getTime(this.browserEvent);
6851 * Gets the page coordinates of the event.
6852 * @return {Array} The xy values like [x, y]
6859 * Gets the target for the event.
6860 * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target
6861 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
6862 search as a number or element (defaults to 10 || document.body)
6863 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
6864 * @return {HTMLelement}
6866 getTarget : function(selector, maxDepth, returnEl){
6867 return selector ? Roo.fly(this.target).findParent(selector, maxDepth, returnEl) : this.target;
6870 * Gets the related target.
6871 * @return {HTMLElement}
6873 getRelatedTarget : function(){
6874 if(this.browserEvent){
6875 return E.getRelatedTarget(this.browserEvent);
6881 * Normalizes mouse wheel delta across browsers
6882 * @return {Number} The delta
6884 getWheelDelta : function(){
6885 var e = this.browserEvent;
6887 if(e.wheelDelta){ /* IE/Opera. */
6888 delta = e.wheelDelta/120;
6889 }else if(e.detail){ /* Mozilla case. */
6890 delta = -e.detail/3;
6896 * Returns true if the control, meta, shift or alt key was pressed during this event.
6899 hasModifier : function(){
6900 return !!((this.ctrlKey || this.altKey) || this.shiftKey);
6904 * Returns true if the target of this event equals el or is a child of el
6905 * @param {String/HTMLElement/Element} el
6906 * @param {Boolean} related (optional) true to test if the related target is within el instead of the target
6909 within : function(el, related){
6910 var t = this[related ? "getRelatedTarget" : "getTarget"]();
6911 return t && Roo.fly(el).contains(t);
6914 getPoint : function(){
6915 return new Roo.lib.Point(this.xy[0], this.xy[1]);
6919 return new Roo.EventObjectImpl();
6924 * Ext JS Library 1.1.1
6925 * Copyright(c) 2006-2007, Ext JS, LLC.
6927 * Originally Released Under LGPL - original licence link has changed is not relivant.
6930 * <script type="text/javascript">
6934 // was in Composite Element!??!?!
6937 var D = Roo.lib.Dom;
6938 var E = Roo.lib.Event;
6939 var A = Roo.lib.Anim;
6941 // local style camelizing for speed
6943 var camelRe = /(-[a-z])/gi;
6944 var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); };
6945 var view = document.defaultView;
6948 * @class Roo.Element
6949 * Represents an Element in the DOM.<br><br>
6952 var el = Roo.get("my-div");
6955 var el = getEl("my-div");
6957 // or with a DOM element
6958 var el = Roo.get(myDivElement);
6960 * Using Roo.get() or getEl() instead of calling the constructor directly ensures you get the same object
6961 * each call instead of constructing a new one.<br><br>
6962 * <b>Animations</b><br />
6963 * Many of the functions for manipulating an element have an optional "animate" parameter. The animate parameter
6964 * should either be a boolean (true) or an object literal with animation options. The animation options are:
6966 Option Default Description
6967 --------- -------- ---------------------------------------------
6968 duration .35 The duration of the animation in seconds
6969 easing easeOut The YUI easing method
6970 callback none A function to execute when the anim completes
6971 scope this The scope (this) of the callback function
6973 * Also, the Anim object being used for the animation will be set on your options object as "anim", which allows you to stop or
6974 * manipulate the animation. Here's an example:
6976 var el = Roo.get("my-div");
6981 // default animation
6982 el.setWidth(100, true);
6984 // animation with some options set
6991 // using the "anim" property to get the Anim object
6997 el.setWidth(100, opt);
6999 if(opt.anim.isAnimated()){
7003 * <b> Composite (Collections of) Elements</b><br />
7004 * For working with collections of Elements, see <a href="Roo.CompositeElement.html">Roo.CompositeElement</a>
7005 * @constructor Create a new Element directly.
7006 * @param {String/HTMLElement} element
7007 * @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).
7009 Roo.Element = function(element, forceNew){
7010 var dom = typeof element == "string" ?
7011 document.getElementById(element) : element;
7012 if(!dom){ // invalid id/element
7016 if(forceNew !== true && id && Roo.Element.cache[id]){ // element object already exists
7017 return Roo.Element.cache[id];
7027 * The DOM element ID
7030 this.id = id || Roo.id(dom);
7033 var El = Roo.Element;
7037 * The element's default display mode (defaults to "")
7040 originalDisplay : "",
7044 * The default unit to append to CSS values where a unit isn't provided (defaults to px).
7049 pxReg : '/^\d+(?:\.\d*)?px$/i',
7051 * Sets the element's visibility mode. When setVisible() is called it
7052 * will use this to determine whether to set the visibility or the display property.
7053 * @param visMode Element.VISIBILITY or Element.DISPLAY
7054 * @return {Roo.Element} this
7056 setVisibilityMode : function(visMode){
7057 this.visibilityMode = visMode;
7061 * Convenience method for setVisibilityMode(Element.DISPLAY)
7062 * @param {String} display (optional) What to set display to when visible
7063 * @return {Roo.Element} this
7065 enableDisplayMode : function(display){
7066 this.setVisibilityMode(El.DISPLAY);
7067 if(typeof display != "undefined") this.originalDisplay = display;
7072 * 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)
7073 * @param {String} selector The simple selector to test
7074 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
7075 search as a number or element (defaults to 10 || document.body)
7076 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
7077 * @return {HTMLElement} The matching DOM node (or null if no match was found)
7079 findParent : function(simpleSelector, maxDepth, returnEl){
7080 var p = this.dom, b = document.body, depth = 0, dq = Roo.DomQuery, stopEl;
7081 maxDepth = maxDepth || 50;
7082 if(typeof maxDepth != "number"){
7083 stopEl = Roo.getDom(maxDepth);
7086 while(p && p.nodeType == 1 && depth < maxDepth && p != b && p != stopEl){
7087 if(dq.is(p, simpleSelector)){
7088 return returnEl ? Roo.get(p) : p;
7098 * Looks at parent nodes for a match of the passed simple selector (e.g. div.some-class or span:first-child)
7099 * @param {String} selector The simple selector to test
7100 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
7101 search as a number or element (defaults to 10 || document.body)
7102 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
7103 * @return {HTMLElement} The matching DOM node (or null if no match was found)
7105 findParentNode : function(simpleSelector, maxDepth, returnEl){
7106 var p = Roo.fly(this.dom.parentNode, '_internal');
7107 return p ? p.findParent(simpleSelector, maxDepth, returnEl) : null;
7111 * Walks up the dom looking for a parent node that matches the passed simple selector (e.g. div.some-class or span:first-child).
7112 * This is a shortcut for findParentNode() that always returns an Roo.Element.
7113 * @param {String} selector The simple selector to test
7114 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
7115 search as a number or element (defaults to 10 || document.body)
7116 * @return {Roo.Element} The matching DOM node (or null if no match was found)
7118 up : function(simpleSelector, maxDepth){
7119 return this.findParentNode(simpleSelector, maxDepth, true);
7125 * Returns true if this element matches the passed simple selector (e.g. div.some-class or span:first-child)
7126 * @param {String} selector The simple selector to test
7127 * @return {Boolean} True if this element matches the selector, else false
7129 is : function(simpleSelector){
7130 return Roo.DomQuery.is(this.dom, simpleSelector);
7134 * Perform animation on this element.
7135 * @param {Object} args The YUI animation control args
7136 * @param {Float} duration (optional) How long the animation lasts in seconds (defaults to .35)
7137 * @param {Function} onComplete (optional) Function to call when animation completes
7138 * @param {String} easing (optional) Easing method to use (defaults to 'easeOut')
7139 * @param {String} animType (optional) 'run' is the default. Can also be 'color', 'motion', or 'scroll'
7140 * @return {Roo.Element} this
7142 animate : function(args, duration, onComplete, easing, animType){
7143 this.anim(args, {duration: duration, callback: onComplete, easing: easing}, animType);
7148 * @private Internal animation call
7150 anim : function(args, opt, animType, defaultDur, defaultEase, cb){
7151 animType = animType || 'run';
7153 var anim = Roo.lib.Anim[animType](
7155 (opt.duration || defaultDur) || .35,
7156 (opt.easing || defaultEase) || 'easeOut',
7158 Roo.callback(cb, this);
7159 Roo.callback(opt.callback, opt.scope || this, [this, opt]);
7167 // private legacy anim prep
7168 preanim : function(a, i){
7169 return !a[i] ? false : (typeof a[i] == "object" ? a[i]: {duration: a[i+1], callback: a[i+2], easing: a[i+3]});
7173 * Removes worthless text nodes
7174 * @param {Boolean} forceReclean (optional) By default the element
7175 * keeps track if it has been cleaned already so
7176 * you can call this over and over. However, if you update the element and
7177 * need to force a reclean, you can pass true.
7179 clean : function(forceReclean){
7180 if(this.isCleaned && forceReclean !== true){
7184 var d = this.dom, n = d.firstChild, ni = -1;
7186 var nx = n.nextSibling;
7187 if(n.nodeType == 3 && !ns.test(n.nodeValue)){
7194 this.isCleaned = true;
7199 calcOffsetsTo : function(el){
7202 var restorePos = false;
7203 if(el.getStyle('position') == 'static'){
7204 el.position('relative');
7209 while(op && op != d && op.tagName != 'HTML'){
7212 op = op.offsetParent;
7215 el.position('static');
7221 * Scrolls this element into view within the passed container.
7222 * @param {String/HTMLElement/Element} container (optional) The container element to scroll (defaults to document.body)
7223 * @param {Boolean} hscroll (optional) False to disable horizontal scroll (defaults to true)
7224 * @return {Roo.Element} this
7226 scrollIntoView : function(container, hscroll){
7227 var c = Roo.getDom(container) || document.body;
7230 var o = this.calcOffsetsTo(c),
7233 b = t+el.offsetHeight,
7234 r = l+el.offsetWidth;
7236 var ch = c.clientHeight;
7237 var ct = parseInt(c.scrollTop, 10);
7238 var cl = parseInt(c.scrollLeft, 10);
7240 var cr = cl + c.clientWidth;
7248 if(hscroll !== false){
7252 c.scrollLeft = r-c.clientWidth;
7259 scrollChildIntoView : function(child, hscroll){
7260 Roo.fly(child, '_scrollChildIntoView').scrollIntoView(this, hscroll);
7264 * Measures the element's content height and updates height to match. Note: this function uses setTimeout so
7265 * the new height may not be available immediately.
7266 * @param {Boolean} animate (optional) Animate the transition (defaults to false)
7267 * @param {Float} duration (optional) Length of the animation in seconds (defaults to .35)
7268 * @param {Function} onComplete (optional) Function to call when animation completes
7269 * @param {String} easing (optional) Easing method to use (defaults to easeOut)
7270 * @return {Roo.Element} this
7272 autoHeight : function(animate, duration, onComplete, easing){
7273 var oldHeight = this.getHeight();
7275 this.setHeight(1); // force clipping
7276 setTimeout(function(){
7277 var height = parseInt(this.dom.scrollHeight, 10); // parseInt for Safari
7279 this.setHeight(height);
7281 if(typeof onComplete == "function"){
7285 this.setHeight(oldHeight); // restore original height
7286 this.setHeight(height, animate, duration, function(){
7288 if(typeof onComplete == "function") onComplete();
7289 }.createDelegate(this), easing);
7291 }.createDelegate(this), 0);
7296 * Returns true if this element is an ancestor of the passed element
7297 * @param {HTMLElement/String} el The element to check
7298 * @return {Boolean} True if this element is an ancestor of el, else false
7300 contains : function(el){
7301 if(!el){return false;}
7302 return D.isAncestor(this.dom, el.dom ? el.dom : el);
7306 * Checks whether the element is currently visible using both visibility and display properties.
7307 * @param {Boolean} deep (optional) True to walk the dom and see if parent elements are hidden (defaults to false)
7308 * @return {Boolean} True if the element is currently visible, else false
7310 isVisible : function(deep) {
7311 var vis = !(this.getStyle("visibility") == "hidden" || this.getStyle("display") == "none");
7312 if(deep !== true || !vis){
7315 var p = this.dom.parentNode;
7316 while(p && p.tagName.toLowerCase() != "body"){
7317 if(!Roo.fly(p, '_isVisible').isVisible()){
7326 * Creates a {@link Roo.CompositeElement} for child nodes based on the passed CSS selector (the selector should not contain an id).
7327 * @param {String} selector The CSS selector
7328 * @param {Boolean} unique (optional) True to create a unique Roo.Element for each child (defaults to false, which creates a single shared flyweight object)
7329 * @return {CompositeElement/CompositeElementLite} The composite element
7331 select : function(selector, unique){
7332 return El.select(selector, unique, this.dom);
7336 * Selects child nodes based on the passed CSS selector (the selector should not contain an id).
7337 * @param {String} selector The CSS selector
7338 * @return {Array} An array of the matched nodes
7340 query : function(selector, unique){
7341 return Roo.DomQuery.select(selector, this.dom);
7345 * Selects a single child at any depth below this element based on the passed CSS selector (the selector should not contain an id).
7346 * @param {String} selector The CSS selector
7347 * @param {Boolean} returnDom (optional) True to return the DOM node instead of Roo.Element (defaults to false)
7348 * @return {HTMLElement/Roo.Element} The child Roo.Element (or DOM node if returnDom = true)
7350 child : function(selector, returnDom){
7351 var n = Roo.DomQuery.selectNode(selector, this.dom);
7352 return returnDom ? n : Roo.get(n);
7356 * Selects a single *direct* child based on the passed CSS selector (the selector should not contain an id).
7357 * @param {String} selector The CSS selector
7358 * @param {Boolean} returnDom (optional) True to return the DOM node instead of Roo.Element (defaults to false)
7359 * @return {HTMLElement/Roo.Element} The child Roo.Element (or DOM node if returnDom = true)
7361 down : function(selector, returnDom){
7362 var n = Roo.DomQuery.selectNode(" > " + selector, this.dom);
7363 return returnDom ? n : Roo.get(n);
7367 * Initializes a {@link Roo.dd.DD} drag drop object for this element.
7368 * @param {String} group The group the DD object is member of
7369 * @param {Object} config The DD config object
7370 * @param {Object} overrides An object containing methods to override/implement on the DD object
7371 * @return {Roo.dd.DD} The DD object
7373 initDD : function(group, config, overrides){
7374 var dd = new Roo.dd.DD(Roo.id(this.dom), group, config);
7375 return Roo.apply(dd, overrides);
7379 * Initializes a {@link Roo.dd.DDProxy} object for this element.
7380 * @param {String} group The group the DDProxy object is member of
7381 * @param {Object} config The DDProxy config object
7382 * @param {Object} overrides An object containing methods to override/implement on the DDProxy object
7383 * @return {Roo.dd.DDProxy} The DDProxy object
7385 initDDProxy : function(group, config, overrides){
7386 var dd = new Roo.dd.DDProxy(Roo.id(this.dom), group, config);
7387 return Roo.apply(dd, overrides);
7391 * Initializes a {@link Roo.dd.DDTarget} object for this element.
7392 * @param {String} group The group the DDTarget object is member of
7393 * @param {Object} config The DDTarget config object
7394 * @param {Object} overrides An object containing methods to override/implement on the DDTarget object
7395 * @return {Roo.dd.DDTarget} The DDTarget object
7397 initDDTarget : function(group, config, overrides){
7398 var dd = new Roo.dd.DDTarget(Roo.id(this.dom), group, config);
7399 return Roo.apply(dd, overrides);
7403 * Sets the visibility of the element (see details). If the visibilityMode is set to Element.DISPLAY, it will use
7404 * the display property to hide the element, otherwise it uses visibility. The default is to hide and show using the visibility property.
7405 * @param {Boolean} visible Whether the element is visible
7406 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7407 * @return {Roo.Element} this
7409 setVisible : function(visible, animate){
7411 if(this.visibilityMode == El.DISPLAY){
7412 this.setDisplayed(visible);
7415 this.dom.style.visibility = visible ? "visible" : "hidden";
7418 // closure for composites
7420 var visMode = this.visibilityMode;
7422 this.setOpacity(.01);
7423 this.setVisible(true);
7425 this.anim({opacity: { to: (visible?1:0) }},
7426 this.preanim(arguments, 1),
7427 null, .35, 'easeIn', function(){
7429 if(visMode == El.DISPLAY){
7430 dom.style.display = "none";
7432 dom.style.visibility = "hidden";
7434 Roo.get(dom).setOpacity(1);
7442 * Returns true if display is not "none"
7445 isDisplayed : function() {
7446 return this.getStyle("display") != "none";
7450 * Toggles the element's visibility or display, depending on visibility mode.
7451 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7452 * @return {Roo.Element} this
7454 toggle : function(animate){
7455 this.setVisible(!this.isVisible(), this.preanim(arguments, 0));
7460 * Sets the CSS display property. Uses originalDisplay if the specified value is a boolean true.
7461 * @param {Boolean} value Boolean value to display the element using its default display, or a string to set the display directly
7462 * @return {Roo.Element} this
7464 setDisplayed : function(value) {
7465 if(typeof value == "boolean"){
7466 value = value ? this.originalDisplay : "none";
7468 this.setStyle("display", value);
7473 * Tries to focus the element. Any exceptions are caught and ignored.
7474 * @return {Roo.Element} this
7476 focus : function() {
7484 * Tries to blur the element. Any exceptions are caught and ignored.
7485 * @return {Roo.Element} this
7495 * Adds one or more CSS classes to the element. Duplicate classes are automatically filtered out.
7496 * @param {String/Array} className The CSS class to add, or an array of classes
7497 * @return {Roo.Element} this
7499 addClass : function(className){
7500 if(className instanceof Array){
7501 for(var i = 0, len = className.length; i < len; i++) {
7502 this.addClass(className[i]);
7505 if(className && !this.hasClass(className)){
7506 this.dom.className = this.dom.className + " " + className;
7513 * Adds one or more CSS classes to this element and removes the same class(es) from all siblings.
7514 * @param {String/Array} className The CSS class to add, or an array of classes
7515 * @return {Roo.Element} this
7517 radioClass : function(className){
7518 var siblings = this.dom.parentNode.childNodes;
7519 for(var i = 0; i < siblings.length; i++) {
7520 var s = siblings[i];
7521 if(s.nodeType == 1){
7522 Roo.get(s).removeClass(className);
7525 this.addClass(className);
7530 * Removes one or more CSS classes from the element.
7531 * @param {String/Array} className The CSS class to remove, or an array of classes
7532 * @return {Roo.Element} this
7534 removeClass : function(className){
7535 if(!className || !this.dom.className){
7538 if(className instanceof Array){
7539 for(var i = 0, len = className.length; i < len; i++) {
7540 this.removeClass(className[i]);
7543 if(this.hasClass(className)){
7544 var re = this.classReCache[className];
7546 re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)', "g");
7547 this.classReCache[className] = re;
7549 this.dom.className =
7550 this.dom.className.replace(re, " ");
7560 * Toggles the specified CSS class on this element (removes it if it already exists, otherwise adds it).
7561 * @param {String} className The CSS class to toggle
7562 * @return {Roo.Element} this
7564 toggleClass : function(className){
7565 if(this.hasClass(className)){
7566 this.removeClass(className);
7568 this.addClass(className);
7574 * Checks if the specified CSS class exists on this element's DOM node.
7575 * @param {String} className The CSS class to check for
7576 * @return {Boolean} True if the class exists, else false
7578 hasClass : function(className){
7579 return className && (' '+this.dom.className+' ').indexOf(' '+className+' ') != -1;
7583 * Replaces a CSS class on the element with another. If the old name does not exist, the new name will simply be added.
7584 * @param {String} oldClassName The CSS class to replace
7585 * @param {String} newClassName The replacement CSS class
7586 * @return {Roo.Element} this
7588 replaceClass : function(oldClassName, newClassName){
7589 this.removeClass(oldClassName);
7590 this.addClass(newClassName);
7595 * Returns an object with properties matching the styles requested.
7596 * For example, el.getStyles('color', 'font-size', 'width') might return
7597 * {'color': '#FFFFFF', 'font-size': '13px', 'width': '100px'}.
7598 * @param {String} style1 A style name
7599 * @param {String} style2 A style name
7600 * @param {String} etc.
7601 * @return {Object} The style object
7603 getStyles : function(){
7604 var a = arguments, len = a.length, r = {};
7605 for(var i = 0; i < len; i++){
7606 r[a[i]] = this.getStyle(a[i]);
7612 * Normalizes currentStyle and computedStyle. This is not YUI getStyle, it is an optimised version.
7613 * @param {String} property The style property whose value is returned.
7614 * @return {String} The current value of the style property for this element.
7616 getStyle : function(){
7617 return view && view.getComputedStyle ?
7619 var el = this.dom, v, cs, camel;
7620 if(prop == 'float'){
7623 if(el.style && (v = el.style[prop])){
7626 if(cs = view.getComputedStyle(el, "")){
7627 if(!(camel = propCache[prop])){
7628 camel = propCache[prop] = prop.replace(camelRe, camelFn);
7635 var el = this.dom, v, cs, camel;
7636 if(prop == 'opacity'){
7637 if(typeof el.style.filter == 'string'){
7638 var m = el.style.filter.match(/alpha\(opacity=(.*)\)/i);
7640 var fv = parseFloat(m[1]);
7642 return fv ? fv / 100 : 0;
7647 }else if(prop == 'float'){
7648 prop = "styleFloat";
7650 if(!(camel = propCache[prop])){
7651 camel = propCache[prop] = prop.replace(camelRe, camelFn);
7653 if(v = el.style[camel]){
7656 if(cs = el.currentStyle){
7664 * Wrapper for setting style properties, also takes single object parameter of multiple styles.
7665 * @param {String/Object} property The style property to be set, or an object of multiple styles.
7666 * @param {String} value (optional) The value to apply to the given property, or null if an object was passed.
7667 * @return {Roo.Element} this
7669 setStyle : function(prop, value){
7670 if(typeof prop == "string"){
7672 if (prop == 'float') {
7673 this.setStyle(Roo.isIE ? 'styleFloat' : 'cssFloat', value);
7678 if(!(camel = propCache[prop])){
7679 camel = propCache[prop] = prop.replace(camelRe, camelFn);
7682 if(camel == 'opacity') {
7683 this.setOpacity(value);
7685 this.dom.style[camel] = value;
7688 for(var style in prop){
7689 if(typeof prop[style] != "function"){
7690 this.setStyle(style, prop[style]);
7698 * More flexible version of {@link #setStyle} for setting style properties.
7699 * @param {String/Object/Function} styles A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
7700 * a function which returns such a specification.
7701 * @return {Roo.Element} this
7703 applyStyles : function(style){
7704 Roo.DomHelper.applyStyles(this.dom, style);
7709 * 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).
7710 * @return {Number} The X position of the element
7713 return D.getX(this.dom);
7717 * 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).
7718 * @return {Number} The Y position of the element
7721 return D.getY(this.dom);
7725 * 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).
7726 * @return {Array} The XY position of the element
7729 return D.getXY(this.dom);
7733 * 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).
7734 * @param {Number} The X position of the element
7735 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7736 * @return {Roo.Element} this
7738 setX : function(x, animate){
7740 D.setX(this.dom, x);
7742 this.setXY([x, this.getY()], this.preanim(arguments, 1));
7748 * 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).
7749 * @param {Number} The Y position of the element
7750 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7751 * @return {Roo.Element} this
7753 setY : function(y, animate){
7755 D.setY(this.dom, y);
7757 this.setXY([this.getX(), y], this.preanim(arguments, 1));
7763 * Sets the element's left position directly using CSS style (instead of {@link #setX}).
7764 * @param {String} left The left CSS property value
7765 * @return {Roo.Element} this
7767 setLeft : function(left){
7768 this.setStyle("left", this.addUnits(left));
7773 * Sets the element's top position directly using CSS style (instead of {@link #setY}).
7774 * @param {String} top The top CSS property value
7775 * @return {Roo.Element} this
7777 setTop : function(top){
7778 this.setStyle("top", this.addUnits(top));
7783 * Sets the element's CSS right style.
7784 * @param {String} right The right CSS property value
7785 * @return {Roo.Element} this
7787 setRight : function(right){
7788 this.setStyle("right", this.addUnits(right));
7793 * Sets the element's CSS bottom style.
7794 * @param {String} bottom The bottom CSS property value
7795 * @return {Roo.Element} this
7797 setBottom : function(bottom){
7798 this.setStyle("bottom", this.addUnits(bottom));
7803 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
7804 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
7805 * @param {Array} pos Contains X & Y [x, y] values for new position (coordinates are page-based)
7806 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7807 * @return {Roo.Element} this
7809 setXY : function(pos, animate){
7811 D.setXY(this.dom, pos);
7813 this.anim({points: {to: pos}}, this.preanim(arguments, 1), 'motion');
7819 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
7820 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
7821 * @param {Number} x X value for new position (coordinates are page-based)
7822 * @param {Number} y Y value for new position (coordinates are page-based)
7823 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7824 * @return {Roo.Element} this
7826 setLocation : function(x, y, animate){
7827 this.setXY([x, y], this.preanim(arguments, 2));
7832 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
7833 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
7834 * @param {Number} x X value for new position (coordinates are page-based)
7835 * @param {Number} y Y value for new position (coordinates are page-based)
7836 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
7837 * @return {Roo.Element} this
7839 moveTo : function(x, y, animate){
7840 this.setXY([x, y], this.preanim(arguments, 2));
7845 * Returns the region of the given element.
7846 * The element must be part of the DOM tree to have a region (display:none or elements not appended return false).
7847 * @return {Region} A Roo.lib.Region containing "top, left, bottom, right" member data.
7849 getRegion : function(){
7850 return D.getRegion(this.dom);
7854 * Returns the offset height of the element
7855 * @param {Boolean} contentHeight (optional) true to get the height minus borders and padding
7856 * @return {Number} The element's height
7858 getHeight : function(contentHeight){
7859 var h = this.dom.offsetHeight || 0;
7860 return contentHeight !== true ? h : h-this.getBorderWidth("tb")-this.getPadding("tb");
7864 * Returns the offset width of the element
7865 * @param {Boolean} contentWidth (optional) true to get the width minus borders and padding
7866 * @return {Number} The element's width
7868 getWidth : function(contentWidth){
7869 var w = this.dom.offsetWidth || 0;
7870 return contentWidth !== true ? w : w-this.getBorderWidth("lr")-this.getPadding("lr");
7874 * Returns either the offsetHeight or the height of this element based on CSS height adjusted by padding or borders
7875 * when needed to simulate offsetHeight when offsets aren't available. This may not work on display:none elements
7876 * if a height has not been set using CSS.
7879 getComputedHeight : function(){
7880 var h = Math.max(this.dom.offsetHeight, this.dom.clientHeight);
7882 h = parseInt(this.getStyle('height'), 10) || 0;
7883 if(!this.isBorderBox()){
7884 h += this.getFrameWidth('tb');
7891 * Returns either the offsetWidth or the width of this element based on CSS width adjusted by padding or borders
7892 * when needed to simulate offsetWidth when offsets aren't available. This may not work on display:none elements
7893 * if a width has not been set using CSS.
7896 getComputedWidth : function(){
7897 var w = Math.max(this.dom.offsetWidth, this.dom.clientWidth);
7899 w = parseInt(this.getStyle('width'), 10) || 0;
7900 if(!this.isBorderBox()){
7901 w += this.getFrameWidth('lr');
7908 * Returns the size of the element.
7909 * @param {Boolean} contentSize (optional) true to get the width/size minus borders and padding
7910 * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
7912 getSize : function(contentSize){
7913 return {width: this.getWidth(contentSize), height: this.getHeight(contentSize)};
7917 * Returns the width and height of the viewport.
7918 * @return {Object} An object containing the viewport's size {width: (viewport width), height: (viewport height)}
7920 getViewSize : function(){
7921 var d = this.dom, doc = document, aw = 0, ah = 0;
7922 if(d == doc || d == doc.body){
7923 return {width : D.getViewWidth(), height: D.getViewHeight()};
7926 width : d.clientWidth,
7927 height: d.clientHeight
7933 * Returns the value of the "value" attribute
7934 * @param {Boolean} asNumber true to parse the value as a number
7935 * @return {String/Number}
7937 getValue : function(asNumber){
7938 return asNumber ? parseInt(this.dom.value, 10) : this.dom.value;
7942 adjustWidth : function(width){
7943 if(typeof width == "number"){
7944 if(this.autoBoxAdjust && !this.isBorderBox()){
7945 width -= (this.getBorderWidth("lr") + this.getPadding("lr"));
7955 adjustHeight : function(height){
7956 if(typeof height == "number"){
7957 if(this.autoBoxAdjust && !this.isBorderBox()){
7958 height -= (this.getBorderWidth("tb") + this.getPadding("tb"));
7968 * Set the width of the element
7969 * @param {Number} width The new width
7970 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
7971 * @return {Roo.Element} this
7973 setWidth : function(width, animate){
7974 width = this.adjustWidth(width);
7976 this.dom.style.width = this.addUnits(width);
7978 this.anim({width: {to: width}}, this.preanim(arguments, 1));
7984 * Set the height of the element
7985 * @param {Number} height The new height
7986 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
7987 * @return {Roo.Element} this
7989 setHeight : function(height, animate){
7990 height = this.adjustHeight(height);
7992 this.dom.style.height = this.addUnits(height);
7994 this.anim({height: {to: height}}, this.preanim(arguments, 1));
8000 * Set the size of the element. If animation is true, both width an height will be animated concurrently.
8001 * @param {Number} width The new width
8002 * @param {Number} height The new height
8003 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8004 * @return {Roo.Element} this
8006 setSize : function(width, height, animate){
8007 if(typeof width == "object"){ // in case of object from getSize()
8008 height = width.height; width = width.width;
8010 width = this.adjustWidth(width); height = this.adjustHeight(height);
8012 this.dom.style.width = this.addUnits(width);
8013 this.dom.style.height = this.addUnits(height);
8015 this.anim({width: {to: width}, height: {to: height}}, this.preanim(arguments, 2));
8021 * Sets the element's position and size in one shot. If animation is true then width, height, x and y will be animated concurrently.
8022 * @param {Number} x X value for new position (coordinates are page-based)
8023 * @param {Number} y Y value for new position (coordinates are page-based)
8024 * @param {Number} width The new width
8025 * @param {Number} height The new height
8026 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8027 * @return {Roo.Element} this
8029 setBounds : function(x, y, width, height, animate){
8031 this.setSize(width, height);
8032 this.setLocation(x, y);
8034 width = this.adjustWidth(width); height = this.adjustHeight(height);
8035 this.anim({points: {to: [x, y]}, width: {to: width}, height: {to: height}},
8036 this.preanim(arguments, 4), 'motion');
8042 * 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.
8043 * @param {Roo.lib.Region} region The region to fill
8044 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8045 * @return {Roo.Element} this
8047 setRegion : function(region, animate){
8048 this.setBounds(region.left, region.top, region.right-region.left, region.bottom-region.top, this.preanim(arguments, 1));
8053 * Appends an event handler
8055 * @param {String} eventName The type of event to append
8056 * @param {Function} fn The method the event invokes
8057 * @param {Object} scope (optional) The scope (this object) of the fn
8058 * @param {Object} options (optional)An object with standard {@link Roo.EventManager#addListener} options
8060 addListener : function(eventName, fn, scope, options){
8062 Roo.EventManager.on(this.dom, eventName, fn, scope || this, options);
8067 * Removes an event handler from this element
8068 * @param {String} eventName the type of event to remove
8069 * @param {Function} fn the method the event invokes
8070 * @return {Roo.Element} this
8072 removeListener : function(eventName, fn){
8073 Roo.EventManager.removeListener(this.dom, eventName, fn);
8078 * Removes all previous added listeners from this element
8079 * @return {Roo.Element} this
8081 removeAllListeners : function(){
8082 E.purgeElement(this.dom);
8086 relayEvent : function(eventName, observable){
8087 this.on(eventName, function(e){
8088 observable.fireEvent(eventName, e);
8093 * Set the opacity of the element
8094 * @param {Float} opacity The new opacity. 0 = transparent, .5 = 50% visibile, 1 = fully visible, etc
8095 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8096 * @return {Roo.Element} this
8098 setOpacity : function(opacity, animate){
8100 var s = this.dom.style;
8103 s.filter = (s.filter || '').replace(/alpha\([^\)]*\)/gi,"") +
8104 (opacity == 1 ? "" : "alpha(opacity=" + opacity * 100 + ")");
8106 s.opacity = opacity;
8109 this.anim({opacity: {to: opacity}}, this.preanim(arguments, 1), null, .35, 'easeIn');
8115 * Gets the left X coordinate
8116 * @param {Boolean} local True to get the local css position instead of page coordinate
8119 getLeft : function(local){
8123 var x = this.getStyle("left");
8125 if(!x || x === 'AUTO'){
8129 if(new RegExp(this.pxReg).test(x)){
8130 return parseFloat(x);
8135 var par = this.dom.offsetParent ? Roo.fly(this.dom.offsetParent) : false;
8137 if (par !== false) {
8146 * Gets the right X coordinate of the element (element X position + element width)
8147 * @param {Boolean} local True to get the local css position instead of page coordinate
8150 getRight : function(local){
8152 return this.getX() + this.getWidth();
8154 return (this.getLeft(true) + this.getWidth()) || 0;
8159 * Gets the top Y coordinate
8160 * @param {Boolean} local True to get the local css position instead of page coordinate
8163 getTop : function(local) {
8167 return parseInt(this.getStyle("top"), 10) || 0;
8172 * Gets the bottom Y coordinate of the element (element Y position + element height)
8173 * @param {Boolean} local True to get the local css position instead of page coordinate
8176 getBottom : function(local){
8178 return this.getY() + this.getHeight();
8180 return (this.getTop(true) + this.getHeight()) || 0;
8185 * Initializes positioning on this element. If a desired position is not passed, it will make the
8186 * the element positioned relative IF it is not already positioned.
8187 * @param {String} pos (optional) Positioning to use "relative", "absolute" or "fixed"
8188 * @param {Number} zIndex (optional) The zIndex to apply
8189 * @param {Number} x (optional) Set the page X position
8190 * @param {Number} y (optional) Set the page Y position
8192 position : function(pos, zIndex, x, y){
8194 if(this.getStyle('position') == 'static'){
8195 this.setStyle('position', 'relative');
8198 this.setStyle("position", pos);
8201 this.setStyle("z-index", zIndex);
8203 if(x !== undefined && y !== undefined){
8205 }else if(x !== undefined){
8207 }else if(y !== undefined){
8213 * Clear positioning back to the default when the document was loaded
8214 * @param {String} value (optional) The value to use for the left,right,top,bottom, defaults to '' (empty string). You could use 'auto'.
8215 * @return {Roo.Element} this
8217 clearPositioning : function(value){
8225 "position" : "static"
8231 * Gets an object with all CSS positioning properties. Useful along with setPostioning to get
8232 * snapshot before performing an update and then restoring the element.
8235 getPositioning : function(){
8236 var l = this.getStyle("left");
8237 var t = this.getStyle("top");
8239 "position" : this.getStyle("position"),
8241 "right" : l ? "" : this.getStyle("right"),
8243 "bottom" : t ? "" : this.getStyle("bottom"),
8244 "z-index" : this.getStyle("z-index")
8249 * Gets the width of the border(s) for the specified side(s)
8250 * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
8251 * passing lr would get the border (l)eft width + the border (r)ight width.
8252 * @return {Number} The width of the sides passed added together
8254 getBorderWidth : function(side){
8255 return this.addStyles(side, El.borders);
8259 * Gets the width of the padding(s) for the specified side(s)
8260 * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
8261 * passing lr would get the padding (l)eft + the padding (r)ight.
8262 * @return {Number} The padding of the sides passed added together
8264 getPadding : function(side){
8265 return this.addStyles(side, El.paddings);
8269 * Set positioning with an object returned by getPositioning().
8270 * @param {Object} posCfg
8271 * @return {Roo.Element} this
8273 setPositioning : function(pc){
8274 this.applyStyles(pc);
8275 if(pc.right == "auto"){
8276 this.dom.style.right = "";
8278 if(pc.bottom == "auto"){
8279 this.dom.style.bottom = "";
8285 fixDisplay : function(){
8286 if(this.getStyle("display") == "none"){
8287 this.setStyle("visibility", "hidden");
8288 this.setStyle("display", this.originalDisplay); // first try reverting to default
8289 if(this.getStyle("display") == "none"){ // if that fails, default to block
8290 this.setStyle("display", "block");
8296 * Quick set left and top adding default units
8297 * @param {String} left The left CSS property value
8298 * @param {String} top The top CSS property value
8299 * @return {Roo.Element} this
8301 setLeftTop : function(left, top){
8302 this.dom.style.left = this.addUnits(left);
8303 this.dom.style.top = this.addUnits(top);
8308 * Move this element relative to its current position.
8309 * @param {String} direction Possible values are: "l","left" - "r","right" - "t","top","up" - "b","bottom","down".
8310 * @param {Number} distance How far to move the element in pixels
8311 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8312 * @return {Roo.Element} this
8314 move : function(direction, distance, animate){
8315 var xy = this.getXY();
8316 direction = direction.toLowerCase();
8320 this.moveTo(xy[0]-distance, xy[1], this.preanim(arguments, 2));
8324 this.moveTo(xy[0]+distance, xy[1], this.preanim(arguments, 2));
8329 this.moveTo(xy[0], xy[1]-distance, this.preanim(arguments, 2));
8334 this.moveTo(xy[0], xy[1]+distance, this.preanim(arguments, 2));
8341 * Store the current overflow setting and clip overflow on the element - use {@link #unclip} to remove
8342 * @return {Roo.Element} this
8345 if(!this.isClipped){
8346 this.isClipped = true;
8347 this.originalClip = {
8348 "o": this.getStyle("overflow"),
8349 "x": this.getStyle("overflow-x"),
8350 "y": this.getStyle("overflow-y")
8352 this.setStyle("overflow", "hidden");
8353 this.setStyle("overflow-x", "hidden");
8354 this.setStyle("overflow-y", "hidden");
8360 * Return clipping (overflow) to original clipping before clip() was called
8361 * @return {Roo.Element} this
8363 unclip : function(){
8365 this.isClipped = false;
8366 var o = this.originalClip;
8367 if(o.o){this.setStyle("overflow", o.o);}
8368 if(o.x){this.setStyle("overflow-x", o.x);}
8369 if(o.y){this.setStyle("overflow-y", o.y);}
8376 * Gets the x,y coordinates specified by the anchor position on the element.
8377 * @param {String} anchor (optional) The specified anchor position (defaults to "c"). See {@link #alignTo} for details on supported anchor positions.
8378 * @param {Object} size (optional) An object containing the size to use for calculating anchor position
8379 * {width: (target width), height: (target height)} (defaults to the element's current size)
8380 * @param {Boolean} local (optional) True to get the local (element top/left-relative) anchor position instead of page coordinates
8381 * @return {Array} [x, y] An array containing the element's x and y coordinates
8383 getAnchorXY : function(anchor, local, s){
8384 //Passing a different size is useful for pre-calculating anchors,
8385 //especially for anchored animations that change the el size.
8387 var w, h, vp = false;
8390 if(d == document.body || d == document){
8392 w = D.getViewWidth(); h = D.getViewHeight();
8394 w = this.getWidth(); h = this.getHeight();
8397 w = s.width; h = s.height;
8399 var x = 0, y = 0, r = Math.round;
8400 switch((anchor || "tl").toLowerCase()){
8442 var sc = this.getScroll();
8443 return [x + sc.left, y + sc.top];
8445 //Add the element's offset xy
8446 var o = this.getXY();
8447 return [x+o[0], y+o[1]];
8451 * Gets the x,y coordinates to align this element with another element. See {@link #alignTo} for more info on the
8452 * supported position values.
8453 * @param {String/HTMLElement/Roo.Element} element The element to align to.
8454 * @param {String} position The position to align to.
8455 * @param {Array} offsets (optional) Offset the positioning by [x, y]
8456 * @return {Array} [x, y]
8458 getAlignToXY : function(el, p, o){
8462 throw "Element.alignTo with an element that doesn't exist";
8464 var c = false; //constrain to viewport
8465 var p1 = "", p2 = "";
8472 }else if(p.indexOf("-") == -1){
8475 p = p.toLowerCase();
8476 var m = p.match(/^([a-z]+)-([a-z]+)(\?)?$/);
8478 throw "Element.alignTo with an invalid alignment " + p;
8480 p1 = m[1]; p2 = m[2]; c = !!m[3];
8482 //Subtract the aligned el's internal xy from the target's offset xy
8483 //plus custom offset to get the aligned el's new offset xy
8484 var a1 = this.getAnchorXY(p1, true);
8485 var a2 = el.getAnchorXY(p2, false);
8486 var x = a2[0] - a1[0] + o[0];
8487 var y = a2[1] - a1[1] + o[1];
8489 //constrain the aligned el to viewport if necessary
8490 var w = this.getWidth(), h = this.getHeight(), r = el.getRegion();
8491 // 5px of margin for ie
8492 var dw = D.getViewWidth()-5, dh = D.getViewHeight()-5;
8494 //If we are at a viewport boundary and the aligned el is anchored on a target border that is
8495 //perpendicular to the vp border, allow the aligned el to slide on that border,
8496 //otherwise swap the aligned el to the opposite border of the target.
8497 var p1y = p1.charAt(0), p1x = p1.charAt(p1.length-1);
8498 var p2y = p2.charAt(0), p2x = p2.charAt(p2.length-1);
8499 var swapY = ((p1y=="t" && p2y=="b") || (p1y=="b" && p2y=="t"));
8500 var swapX = ((p1x=="r" && p2x=="l") || (p1x=="l" && p2x=="r"));
8503 var scrollX = (doc.documentElement.scrollLeft || doc.body.scrollLeft || 0)+5;
8504 var scrollY = (doc.documentElement.scrollTop || doc.body.scrollTop || 0)+5;
8506 if((x+w) > dw + scrollX){
8507 x = swapX ? r.left-w : dw+scrollX-w;
8510 x = swapX ? r.right : scrollX;
8512 if((y+h) > dh + scrollY){
8513 y = swapY ? r.top-h : dh+scrollY-h;
8516 y = swapY ? r.bottom : scrollY;
8523 getConstrainToXY : function(){
8524 var os = {top:0, left:0, bottom:0, right: 0};
8526 return function(el, local, offsets, proposedXY){
8528 offsets = offsets ? Roo.applyIf(offsets, os) : os;
8530 var vw, vh, vx = 0, vy = 0;
8531 if(el.dom == document.body || el.dom == document){
8532 vw = Roo.lib.Dom.getViewWidth();
8533 vh = Roo.lib.Dom.getViewHeight();
8535 vw = el.dom.clientWidth;
8536 vh = el.dom.clientHeight;
8538 var vxy = el.getXY();
8544 var s = el.getScroll();
8546 vx += offsets.left + s.left;
8547 vy += offsets.top + s.top;
8549 vw -= offsets.right;
8550 vh -= offsets.bottom;
8555 var xy = proposedXY || (!local ? this.getXY() : [this.getLeft(true), this.getTop(true)]);
8556 var x = xy[0], y = xy[1];
8557 var w = this.dom.offsetWidth, h = this.dom.offsetHeight;
8559 // only move it if it needs it
8562 // first validate right/bottom
8571 // then make sure top/left isn't negative
8580 return moved ? [x, y] : false;
8585 adjustForConstraints : function(xy, parent, offsets){
8586 return this.getConstrainToXY(parent || document, false, offsets, xy) || xy;
8590 * Aligns this element with another element relative to the specified anchor points. If the other element is the
8591 * document it aligns it to the viewport.
8592 * The position parameter is optional, and can be specified in any one of the following formats:
8594 * <li><b>Blank</b>: Defaults to aligning the element's top-left corner to the target's bottom-left corner ("tl-bl").</li>
8595 * <li><b>One anchor (deprecated)</b>: The passed anchor position is used as the target element's anchor point.
8596 * The element being aligned will position its top-left corner (tl) to that point. <i>This method has been
8597 * deprecated in favor of the newer two anchor syntax below</i>.</li>
8598 * <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
8599 * element's anchor point, and the second value is used as the target's anchor point.</li>
8601 * In addition to the anchor points, the position parameter also supports the "?" character. If "?" is passed at the end of
8602 * the position string, the element will attempt to align as specified, but the position will be adjusted to constrain to
8603 * the viewport if necessary. Note that the element being aligned might be swapped to align to a different position than
8604 * that specified in order to enforce the viewport constraints.
8605 * Following are all of the supported anchor positions:
8608 ----- -----------------------------
8609 tl The top left corner (default)
8610 t The center of the top edge
8611 tr The top right corner
8612 l The center of the left edge
8613 c In the center of the element
8614 r The center of the right edge
8615 bl The bottom left corner
8616 b The center of the bottom edge
8617 br The bottom right corner
8621 // align el to other-el using the default positioning ("tl-bl", non-constrained)
8622 el.alignTo("other-el");
8624 // align the top left corner of el with the top right corner of other-el (constrained to viewport)
8625 el.alignTo("other-el", "tr?");
8627 // align the bottom right corner of el with the center left edge of other-el
8628 el.alignTo("other-el", "br-l?");
8630 // align the center of el with the bottom left corner of other-el and
8631 // adjust the x position by -6 pixels (and the y position by 0)
8632 el.alignTo("other-el", "c-bl", [-6, 0]);
8634 * @param {String/HTMLElement/Roo.Element} element The element to align to.
8635 * @param {String} position The position to align to.
8636 * @param {Array} offsets (optional) Offset the positioning by [x, y]
8637 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8638 * @return {Roo.Element} this
8640 alignTo : function(element, position, offsets, animate){
8641 var xy = this.getAlignToXY(element, position, offsets);
8642 this.setXY(xy, this.preanim(arguments, 3));
8647 * Anchors an element to another element and realigns it when the window is resized.
8648 * @param {String/HTMLElement/Roo.Element} element The element to align to.
8649 * @param {String} position The position to align to.
8650 * @param {Array} offsets (optional) Offset the positioning by [x, y]
8651 * @param {Boolean/Object} animate (optional) True for the default animation or a standard Element animation config object
8652 * @param {Boolean/Number} monitorScroll (optional) True to monitor body scroll and reposition. If this parameter
8653 * is a number, it is used as the buffer delay (defaults to 50ms).
8654 * @param {Function} callback The function to call after the animation finishes
8655 * @return {Roo.Element} this
8657 anchorTo : function(el, alignment, offsets, animate, monitorScroll, callback){
8658 var action = function(){
8659 this.alignTo(el, alignment, offsets, animate);
8660 Roo.callback(callback, this);
8662 Roo.EventManager.onWindowResize(action, this);
8663 var tm = typeof monitorScroll;
8664 if(tm != 'undefined'){
8665 Roo.EventManager.on(window, 'scroll', action, this,
8666 {buffer: tm == 'number' ? monitorScroll : 50});
8668 action.call(this); // align immediately
8672 * Clears any opacity settings from this element. Required in some cases for IE.
8673 * @return {Roo.Element} this
8675 clearOpacity : function(){
8676 if (window.ActiveXObject) {
8677 if(typeof this.dom.style.filter == 'string' && (/alpha/i).test(this.dom.style.filter)){
8678 this.dom.style.filter = "";
8681 this.dom.style.opacity = "";
8682 this.dom.style["-moz-opacity"] = "";
8683 this.dom.style["-khtml-opacity"] = "";
8689 * Hide this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
8690 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8691 * @return {Roo.Element} this
8693 hide : function(animate){
8694 this.setVisible(false, this.preanim(arguments, 0));
8699 * Show this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
8700 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8701 * @return {Roo.Element} this
8703 show : function(animate){
8704 this.setVisible(true, this.preanim(arguments, 0));
8709 * @private Test if size has a unit, otherwise appends the default
8711 addUnits : function(size){
8712 return Roo.Element.addUnits(size, this.defaultUnit);
8716 * Temporarily enables offsets (width,height,x,y) for an element with display:none, use endMeasure() when done.
8717 * @return {Roo.Element} this
8719 beginMeasure : function(){
8721 if(el.offsetWidth || el.offsetHeight){
8722 return this; // offsets work already
8725 var p = this.dom, b = document.body; // start with this element
8726 while((!el.offsetWidth && !el.offsetHeight) && p && p.tagName && p != b){
8727 var pe = Roo.get(p);
8728 if(pe.getStyle('display') == 'none'){
8729 changed.push({el: p, visibility: pe.getStyle("visibility")});
8730 p.style.visibility = "hidden";
8731 p.style.display = "block";
8735 this._measureChanged = changed;
8741 * Restores displays to before beginMeasure was called
8742 * @return {Roo.Element} this
8744 endMeasure : function(){
8745 var changed = this._measureChanged;
8747 for(var i = 0, len = changed.length; i < len; i++) {
8749 r.el.style.visibility = r.visibility;
8750 r.el.style.display = "none";
8752 this._measureChanged = null;
8758 * Update the innerHTML of this element, optionally searching for and processing scripts
8759 * @param {String} html The new HTML
8760 * @param {Boolean} loadScripts (optional) true to look for and process scripts
8761 * @param {Function} callback For async script loading you can be noticed when the update completes
8762 * @return {Roo.Element} this
8764 update : function(html, loadScripts, callback){
8765 if(typeof html == "undefined"){
8768 if(loadScripts !== true){
8769 this.dom.innerHTML = html;
8770 if(typeof callback == "function"){
8778 html += '<span id="' + id + '"></span>';
8780 E.onAvailable(id, function(){
8781 var hd = document.getElementsByTagName("head")[0];
8782 var re = /(?:<script([^>]*)?>)((\n|\r|.)*?)(?:<\/script>)/ig;
8783 var srcRe = /\ssrc=([\'\"])(.*?)\1/i;
8784 var typeRe = /\stype=([\'\"])(.*?)\1/i;
8787 while(match = re.exec(html)){
8788 var attrs = match[1];
8789 var srcMatch = attrs ? attrs.match(srcRe) : false;
8790 if(srcMatch && srcMatch[2]){
8791 var s = document.createElement("script");
8792 s.src = srcMatch[2];
8793 var typeMatch = attrs.match(typeRe);
8794 if(typeMatch && typeMatch[2]){
8795 s.type = typeMatch[2];
8798 }else if(match[2] && match[2].length > 0){
8799 if(window.execScript) {
8800 window.execScript(match[2]);
8808 window.eval(match[2]);
8812 var el = document.getElementById(id);
8813 if(el){el.parentNode.removeChild(el);}
8814 if(typeof callback == "function"){
8818 dom.innerHTML = html.replace(/(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig, "");
8823 * Direct access to the UpdateManager update() method (takes the same parameters).
8824 * @param {String/Function} url The url for this request or a function to call to get the url
8825 * @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}
8826 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
8827 * @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.
8828 * @return {Roo.Element} this
8831 var um = this.getUpdateManager();
8832 um.update.apply(um, arguments);
8837 * Gets this element's UpdateManager
8838 * @return {Roo.UpdateManager} The UpdateManager
8840 getUpdateManager : function(){
8841 if(!this.updateManager){
8842 this.updateManager = new Roo.UpdateManager(this);
8844 return this.updateManager;
8848 * Disables text selection for this element (normalized across browsers)
8849 * @return {Roo.Element} this
8851 unselectable : function(){
8852 this.dom.unselectable = "on";
8853 this.swallowEvent("selectstart", true);
8854 this.applyStyles("-moz-user-select:none;-khtml-user-select:none;");
8855 this.addClass("x-unselectable");
8860 * Calculates the x, y to center this element on the screen
8861 * @return {Array} The x, y values [x, y]
8863 getCenterXY : function(){
8864 return this.getAlignToXY(document, 'c-c');
8868 * Centers the Element in either the viewport, or another Element.
8869 * @param {String/HTMLElement/Roo.Element} centerIn (optional) The element in which to center the element.
8871 center : function(centerIn){
8872 this.alignTo(centerIn || document, 'c-c');
8877 * Tests various css rules/browsers to determine if this element uses a border box
8880 isBorderBox : function(){
8881 return noBoxAdjust[this.dom.tagName.toLowerCase()] || Roo.isBorderBox;
8885 * Return a box {x, y, width, height} that can be used to set another elements
8886 * size/location to match this element.
8887 * @param {Boolean} contentBox (optional) If true a box for the content of the element is returned.
8888 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page x/y.
8889 * @return {Object} box An object in the format {x, y, width, height}
8891 getBox : function(contentBox, local){
8896 var left = parseInt(this.getStyle("left"), 10) || 0;
8897 var top = parseInt(this.getStyle("top"), 10) || 0;
8900 var el = this.dom, w = el.offsetWidth, h = el.offsetHeight, bx;
8902 bx = {x: xy[0], y: xy[1], 0: xy[0], 1: xy[1], width: w, height: h};
8904 var l = this.getBorderWidth("l")+this.getPadding("l");
8905 var r = this.getBorderWidth("r")+this.getPadding("r");
8906 var t = this.getBorderWidth("t")+this.getPadding("t");
8907 var b = this.getBorderWidth("b")+this.getPadding("b");
8908 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)};
8910 bx.right = bx.x + bx.width;
8911 bx.bottom = bx.y + bx.height;
8916 * Returns the sum width of the padding and borders for the passed "sides". See getBorderWidth()
8917 for more information about the sides.
8918 * @param {String} sides
8921 getFrameWidth : function(sides, onlyContentBox){
8922 return onlyContentBox && Roo.isBorderBox ? 0 : (this.getPadding(sides) + this.getBorderWidth(sides));
8926 * 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.
8927 * @param {Object} box The box to fill {x, y, width, height}
8928 * @param {Boolean} adjust (optional) Whether to adjust for box-model issues automatically
8929 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8930 * @return {Roo.Element} this
8932 setBox : function(box, adjust, animate){
8933 var w = box.width, h = box.height;
8934 if((adjust && !this.autoBoxAdjust) && !this.isBorderBox()){
8935 w -= (this.getBorderWidth("lr") + this.getPadding("lr"));
8936 h -= (this.getBorderWidth("tb") + this.getPadding("tb"));
8938 this.setBounds(box.x, box.y, w, h, this.preanim(arguments, 2));
8943 * Forces the browser to repaint this element
8944 * @return {Roo.Element} this
8946 repaint : function(){
8948 this.addClass("x-repaint");
8949 setTimeout(function(){
8950 Roo.get(dom).removeClass("x-repaint");
8956 * Returns an object with properties top, left, right and bottom representing the margins of this element unless sides is passed,
8957 * then it returns the calculated width of the sides (see getPadding)
8958 * @param {String} sides (optional) Any combination of l, r, t, b to get the sum of those sides
8959 * @return {Object/Number}
8961 getMargins : function(side){
8964 top: parseInt(this.getStyle("margin-top"), 10) || 0,
8965 left: parseInt(this.getStyle("margin-left"), 10) || 0,
8966 bottom: parseInt(this.getStyle("margin-bottom"), 10) || 0,
8967 right: parseInt(this.getStyle("margin-right"), 10) || 0
8970 return this.addStyles(side, El.margins);
8975 addStyles : function(sides, styles){
8977 for(var i = 0, len = sides.length; i < len; i++){
8978 v = this.getStyle(styles[sides.charAt(i)]);
8980 w = parseInt(v, 10);
8988 * Creates a proxy element of this element
8989 * @param {String/Object} config The class name of the proxy element or a DomHelper config object
8990 * @param {String/HTMLElement} renderTo (optional) The element or element id to render the proxy to (defaults to document.body)
8991 * @param {Boolean} matchBox (optional) True to align and size the proxy to this element now (defaults to false)
8992 * @return {Roo.Element} The new proxy element
8994 createProxy : function(config, renderTo, matchBox){
8996 renderTo = Roo.getDom(renderTo);
8998 renderTo = document.body;
9000 config = typeof config == "object" ?
9001 config : {tag : "div", cls: config};
9002 var proxy = Roo.DomHelper.append(renderTo, config, true);
9004 proxy.setBox(this.getBox());
9010 * Puts a mask over this element to disable user interaction. Requires core.css.
9011 * This method can only be applied to elements which accept child nodes.
9012 * @param {String} msg (optional) A message to display in the mask
9013 * @param {String} msgCls (optional) A css class to apply to the msg element
9014 * @return {Element} The mask element
9016 mask : function(msg, msgCls)
9018 if(this.getStyle("position") == "static" && this.dom.tagName !== 'BODY'){
9019 this.setStyle("position", "relative");
9022 this._mask = Roo.DomHelper.append(this.dom, {cls:"roo-el-mask"}, true);
9024 this.addClass("x-masked");
9025 this._mask.setDisplayed(true);
9030 while (dom && dom.style) {
9031 if (!isNaN(parseInt(dom.style.zIndex))) {
9032 z = Math.max(z, parseInt(dom.style.zIndex));
9034 dom = dom.parentNode;
9036 // if we are masking the body - then it hides everything..
9037 if (this.dom == document.body) {
9039 this._mask.setWidth(Roo.lib.Dom.getDocumentWidth());
9040 this._mask.setHeight(Roo.lib.Dom.getDocumentHeight());
9043 if(typeof msg == 'string'){
9045 this._maskMsg = Roo.DomHelper.append(this.dom, {cls:"roo-el-mask-msg", cn:{tag:'div'}}, true);
9047 var mm = this._maskMsg;
9048 mm.dom.className = msgCls ? "roo-el-mask-msg " + msgCls : "roo-el-mask-msg";
9049 if (mm.dom.firstChild) { // weird IE issue?
9050 mm.dom.firstChild.innerHTML = msg;
9052 mm.setDisplayed(true);
9054 mm.setStyle('z-index', z + 102);
9056 if(Roo.isIE && !(Roo.isIE7 && Roo.isStrict) && this.getStyle('height') == 'auto'){ // ie will not expand full height automatically
9057 this._mask.setHeight(this.getHeight());
9059 this._mask.setStyle('z-index', z + 100);
9065 * Removes a previously applied mask. If removeEl is true the mask overlay is destroyed, otherwise
9066 * it is cached for reuse.
9068 unmask : function(removeEl){
9070 if(removeEl === true){
9071 this._mask.remove();
9074 this._maskMsg.remove();
9075 delete this._maskMsg;
9078 this._mask.setDisplayed(false);
9080 this._maskMsg.setDisplayed(false);
9084 this.removeClass("x-masked");
9088 * Returns true if this element is masked
9091 isMasked : function(){
9092 return this._mask && this._mask.isVisible();
9096 * Creates an iframe shim for this element to keep selects and other windowed objects from
9098 * @return {Roo.Element} The new shim element
9100 createShim : function(){
9101 var el = document.createElement('iframe');
9102 el.frameBorder = 'no';
9103 el.className = 'roo-shim';
9104 if(Roo.isIE && Roo.isSecure){
9105 el.src = Roo.SSL_SECURE_URL;
9107 var shim = Roo.get(this.dom.parentNode.insertBefore(el, this.dom));
9108 shim.autoBoxAdjust = false;
9113 * Removes this element from the DOM and deletes it from the cache
9115 remove : function(){
9116 if(this.dom.parentNode){
9117 this.dom.parentNode.removeChild(this.dom);
9119 delete El.cache[this.dom.id];
9123 * Sets up event handlers to add and remove a css class when the mouse is over this element
9124 * @param {String} className
9125 * @param {Boolean} preventFlicker (optional) If set to true, it prevents flickering by filtering
9126 * mouseout events for children elements
9127 * @return {Roo.Element} this
9129 addClassOnOver : function(className, preventFlicker){
9130 this.on("mouseover", function(){
9131 Roo.fly(this, '_internal').addClass(className);
9133 var removeFn = function(e){
9134 if(preventFlicker !== true || !e.within(this, true)){
9135 Roo.fly(this, '_internal').removeClass(className);
9138 this.on("mouseout", removeFn, this.dom);
9143 * Sets up event handlers to add and remove a css class when this element has the focus
9144 * @param {String} className
9145 * @return {Roo.Element} this
9147 addClassOnFocus : function(className){
9148 this.on("focus", function(){
9149 Roo.fly(this, '_internal').addClass(className);
9151 this.on("blur", function(){
9152 Roo.fly(this, '_internal').removeClass(className);
9157 * 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)
9158 * @param {String} className
9159 * @return {Roo.Element} this
9161 addClassOnClick : function(className){
9163 this.on("mousedown", function(){
9164 Roo.fly(dom, '_internal').addClass(className);
9165 var d = Roo.get(document);
9166 var fn = function(){
9167 Roo.fly(dom, '_internal').removeClass(className);
9168 d.removeListener("mouseup", fn);
9170 d.on("mouseup", fn);
9176 * Stops the specified event from bubbling and optionally prevents the default action
9177 * @param {String} eventName
9178 * @param {Boolean} preventDefault (optional) true to prevent the default action too
9179 * @return {Roo.Element} this
9181 swallowEvent : function(eventName, preventDefault){
9182 var fn = function(e){
9183 e.stopPropagation();
9188 if(eventName instanceof Array){
9189 for(var i = 0, len = eventName.length; i < len; i++){
9190 this.on(eventName[i], fn);
9194 this.on(eventName, fn);
9201 fitToParentDelegate : Roo.emptyFn, // keep a reference to the fitToParent delegate
9204 * Sizes this element to its parent element's dimensions performing
9205 * neccessary box adjustments.
9206 * @param {Boolean} monitorResize (optional) If true maintains the fit when the browser window is resized.
9207 * @param {String/HTMLElment/Element} targetParent (optional) The target parent, default to the parentNode.
9208 * @return {Roo.Element} this
9210 fitToParent : function(monitorResize, targetParent) {
9211 Roo.EventManager.removeResizeListener(this.fitToParentDelegate); // always remove previous fitToParent delegate from onWindowResize
9212 this.fitToParentDelegate = Roo.emptyFn; // remove reference to previous delegate
9213 if (monitorResize === true && !this.dom.parentNode) { // check if this Element still exists
9216 var p = Roo.get(targetParent || this.dom.parentNode);
9217 this.setSize(p.getComputedWidth() - p.getFrameWidth('lr'), p.getComputedHeight() - p.getFrameWidth('tb'));
9218 if (monitorResize === true) {
9219 this.fitToParentDelegate = this.fitToParent.createDelegate(this, [true, targetParent]);
9220 Roo.EventManager.onWindowResize(this.fitToParentDelegate);
9226 * Gets the next sibling, skipping text nodes
9227 * @return {HTMLElement} The next sibling or null
9229 getNextSibling : function(){
9230 var n = this.dom.nextSibling;
9231 while(n && n.nodeType != 1){
9238 * Gets the previous sibling, skipping text nodes
9239 * @return {HTMLElement} The previous sibling or null
9241 getPrevSibling : function(){
9242 var n = this.dom.previousSibling;
9243 while(n && n.nodeType != 1){
9244 n = n.previousSibling;
9251 * Appends the passed element(s) to this element
9252 * @param {String/HTMLElement/Array/Element/CompositeElement} el
9253 * @return {Roo.Element} this
9255 appendChild: function(el){
9262 * Creates the passed DomHelper config and appends it to this element or optionally inserts it before the passed child element.
9263 * @param {Object} config DomHelper element config object. If no tag is specified (e.g., {tag:'input'}) then a div will be
9264 * automatically generated with the specified attributes.
9265 * @param {HTMLElement} insertBefore (optional) a child element of this element
9266 * @param {Boolean} returnDom (optional) true to return the dom node instead of creating an Element
9267 * @return {Roo.Element} The new child element
9269 createChild: function(config, insertBefore, returnDom){
9270 config = config || {tag:'div'};
9272 return Roo.DomHelper.insertBefore(insertBefore, config, returnDom !== true);
9274 return Roo.DomHelper[!this.dom.firstChild ? 'overwrite' : 'append'](this.dom, config, returnDom !== true);
9278 * Appends this element to the passed element
9279 * @param {String/HTMLElement/Element} el The new parent element
9280 * @return {Roo.Element} this
9282 appendTo: function(el){
9283 el = Roo.getDom(el);
9284 el.appendChild(this.dom);
9289 * Inserts this element before the passed element in the DOM
9290 * @param {String/HTMLElement/Element} el The element to insert before
9291 * @return {Roo.Element} this
9293 insertBefore: function(el){
9294 el = Roo.getDom(el);
9295 el.parentNode.insertBefore(this.dom, el);
9300 * Inserts this element after the passed element in the DOM
9301 * @param {String/HTMLElement/Element} el The element to insert after
9302 * @return {Roo.Element} this
9304 insertAfter: function(el){
9305 el = Roo.getDom(el);
9306 el.parentNode.insertBefore(this.dom, el.nextSibling);
9311 * Inserts (or creates) an element (or DomHelper config) as the first child of the this element
9312 * @param {String/HTMLElement/Element/Object} el The id or element to insert or a DomHelper config to create and insert
9313 * @return {Roo.Element} The new child
9315 insertFirst: function(el, returnDom){
9317 if(typeof el == 'object' && !el.nodeType){ // dh config
9318 return this.createChild(el, this.dom.firstChild, returnDom);
9320 el = Roo.getDom(el);
9321 this.dom.insertBefore(el, this.dom.firstChild);
9322 return !returnDom ? Roo.get(el) : el;
9327 * Inserts (or creates) the passed element (or DomHelper config) as a sibling of this element
9328 * @param {String/HTMLElement/Element/Object} el The id or element to insert or a DomHelper config to create and insert
9329 * @param {String} where (optional) 'before' or 'after' defaults to before
9330 * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Roo.Element
9331 * @return {Roo.Element} the inserted Element
9333 insertSibling: function(el, where, returnDom){
9334 where = where ? where.toLowerCase() : 'before';
9336 var rt, refNode = where == 'before' ? this.dom : this.dom.nextSibling;
9338 if(typeof el == 'object' && !el.nodeType){ // dh config
9339 if(where == 'after' && !this.dom.nextSibling){
9340 rt = Roo.DomHelper.append(this.dom.parentNode, el, !returnDom);
9342 rt = Roo.DomHelper[where == 'after' ? 'insertAfter' : 'insertBefore'](this.dom, el, !returnDom);
9346 rt = this.dom.parentNode.insertBefore(Roo.getDom(el),
9347 where == 'before' ? this.dom : this.dom.nextSibling);
9356 * Creates and wraps this element with another element
9357 * @param {Object} config (optional) DomHelper element config object for the wrapper element or null for an empty div
9358 * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Roo.Element
9359 * @return {HTMLElement/Element} The newly created wrapper element
9361 wrap: function(config, returnDom){
9363 config = {tag: "div"};
9365 var newEl = Roo.DomHelper.insertBefore(this.dom, config, !returnDom);
9366 newEl.dom ? newEl.dom.appendChild(this.dom) : newEl.appendChild(this.dom);
9371 * Replaces the passed element with this element
9372 * @param {String/HTMLElement/Element} el The element to replace
9373 * @return {Roo.Element} this
9375 replace: function(el){
9377 this.insertBefore(el);
9383 * Inserts an html fragment into this element
9384 * @param {String} where Where to insert the html in relation to the this element - beforeBegin, afterBegin, beforeEnd, afterEnd.
9385 * @param {String} html The HTML fragment
9386 * @param {Boolean} returnEl True to return an Roo.Element
9387 * @return {HTMLElement/Roo.Element} The inserted node (or nearest related if more than 1 inserted)
9389 insertHtml : function(where, html, returnEl){
9390 var el = Roo.DomHelper.insertHtml(where, this.dom, html);
9391 return returnEl ? Roo.get(el) : el;
9395 * Sets the passed attributes as attributes of this element (a style attribute can be a string, object or function)
9396 * @param {Object} o The object with the attributes
9397 * @param {Boolean} useSet (optional) false to override the default setAttribute to use expandos.
9398 * @return {Roo.Element} this
9400 set : function(o, useSet){
9402 useSet = typeof useSet == 'undefined' ? (el.setAttribute ? true : false) : useSet;
9404 if(attr == "style" || typeof o[attr] == "function") continue;
9406 el.className = o["cls"];
9408 if(useSet) el.setAttribute(attr, o[attr]);
9409 else el[attr] = o[attr];
9413 Roo.DomHelper.applyStyles(el, o.style);
9419 * Convenience method for constructing a KeyMap
9420 * @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:
9421 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
9422 * @param {Function} fn The function to call
9423 * @param {Object} scope (optional) The scope of the function
9424 * @return {Roo.KeyMap} The KeyMap created
9426 addKeyListener : function(key, fn, scope){
9428 if(typeof key != "object" || key instanceof Array){
9444 return new Roo.KeyMap(this, config);
9448 * Creates a KeyMap for this element
9449 * @param {Object} config The KeyMap config. See {@link Roo.KeyMap} for more details
9450 * @return {Roo.KeyMap} The KeyMap created
9452 addKeyMap : function(config){
9453 return new Roo.KeyMap(this, config);
9457 * Returns true if this element is scrollable.
9460 isScrollable : function(){
9462 return dom.scrollHeight > dom.clientHeight || dom.scrollWidth > dom.clientWidth;
9466 * 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().
9467 * @param {String} side Either "left" for scrollLeft values or "top" for scrollTop values.
9468 * @param {Number} value The new scroll value
9469 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9470 * @return {Element} this
9473 scrollTo : function(side, value, animate){
9474 var prop = side.toLowerCase() == "left" ? "scrollLeft" : "scrollTop";
9476 this.dom[prop] = value;
9478 var to = prop == "scrollLeft" ? [value, this.dom.scrollTop] : [this.dom.scrollLeft, value];
9479 this.anim({scroll: {"to": to}}, this.preanim(arguments, 2), 'scroll');
9485 * Scrolls this element the specified direction. Does bounds checking to make sure the scroll is
9486 * within this element's scrollable range.
9487 * @param {String} direction Possible values are: "l","left" - "r","right" - "t","top","up" - "b","bottom","down".
9488 * @param {Number} distance How far to scroll the element in pixels
9489 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9490 * @return {Boolean} Returns true if a scroll was triggered or false if the element
9491 * was scrolled as far as it could go.
9493 scroll : function(direction, distance, animate){
9494 if(!this.isScrollable()){
9498 var l = el.scrollLeft, t = el.scrollTop;
9499 var w = el.scrollWidth, h = el.scrollHeight;
9500 var cw = el.clientWidth, ch = el.clientHeight;
9501 direction = direction.toLowerCase();
9502 var scrolled = false;
9503 var a = this.preanim(arguments, 2);
9508 var v = Math.min(l + distance, w-cw);
9509 this.scrollTo("left", v, a);
9516 var v = Math.max(l - distance, 0);
9517 this.scrollTo("left", v, a);
9525 var v = Math.max(t - distance, 0);
9526 this.scrollTo("top", v, a);
9534 var v = Math.min(t + distance, h-ch);
9535 this.scrollTo("top", v, a);
9544 * Translates the passed page coordinates into left/top css values for this element
9545 * @param {Number/Array} x The page x or an array containing [x, y]
9546 * @param {Number} y The page y
9547 * @return {Object} An object with left and top properties. e.g. {left: (value), top: (value)}
9549 translatePoints : function(x, y){
9550 if(typeof x == 'object' || x instanceof Array){
9553 var p = this.getStyle('position');
9554 var o = this.getXY();
9556 var l = parseInt(this.getStyle('left'), 10);
9557 var t = parseInt(this.getStyle('top'), 10);
9560 l = (p == "relative") ? 0 : this.dom.offsetLeft;
9563 t = (p == "relative") ? 0 : this.dom.offsetTop;
9566 return {left: (x - o[0] + l), top: (y - o[1] + t)};
9570 * Returns the current scroll position of the element.
9571 * @return {Object} An object containing the scroll position in the format {left: (scrollLeft), top: (scrollTop)}
9573 getScroll : function(){
9574 var d = this.dom, doc = document;
9575 if(d == doc || d == doc.body){
9576 var l = window.pageXOffset || doc.documentElement.scrollLeft || doc.body.scrollLeft || 0;
9577 var t = window.pageYOffset || doc.documentElement.scrollTop || doc.body.scrollTop || 0;
9578 return {left: l, top: t};
9580 return {left: d.scrollLeft, top: d.scrollTop};
9585 * Return the CSS color for the specified CSS attribute. rgb, 3 digit (like #fff) and valid values
9586 * are convert to standard 6 digit hex color.
9587 * @param {String} attr The css attribute
9588 * @param {String} defaultValue The default value to use when a valid color isn't found
9589 * @param {String} prefix (optional) defaults to #. Use an empty string when working with
9592 getColor : function(attr, defaultValue, prefix){
9593 var v = this.getStyle(attr);
9594 if(!v || v == "transparent" || v == "inherit") {
9595 return defaultValue;
9597 var color = typeof prefix == "undefined" ? "#" : prefix;
9598 if(v.substr(0, 4) == "rgb("){
9599 var rvs = v.slice(4, v.length -1).split(",");
9600 for(var i = 0; i < 3; i++){
9601 var h = parseInt(rvs[i]).toString(16);
9608 if(v.substr(0, 1) == "#"){
9610 for(var i = 1; i < 4; i++){
9611 var c = v.charAt(i);
9614 }else if(v.length == 7){
9615 color += v.substr(1);
9619 return(color.length > 5 ? color.toLowerCase() : defaultValue);
9623 * Wraps the specified element with a special markup/CSS block that renders by default as a gray container with a
9624 * gradient background, rounded corners and a 4-way shadow.
9625 * @param {String} class (optional) A base CSS class to apply to the containing wrapper element (defaults to 'x-box').
9626 * Note that there are a number of CSS rules that are dependent on this name to make the overall effect work,
9627 * so if you supply an alternate base class, make sure you also supply all of the necessary rules.
9628 * @return {Roo.Element} this
9630 boxWrap : function(cls){
9631 cls = cls || 'x-box';
9632 var el = Roo.get(this.insertHtml('beforeBegin', String.format('<div class="{0}">'+El.boxMarkup+'</div>', cls)));
9633 el.child('.'+cls+'-mc').dom.appendChild(this.dom);
9638 * Returns the value of a namespaced attribute from the element's underlying DOM node.
9639 * @param {String} namespace The namespace in which to look for the attribute
9640 * @param {String} name The attribute name
9641 * @return {String} The attribute value
9643 getAttributeNS : Roo.isIE ? function(ns, name){
9645 var type = typeof d[ns+":"+name];
9646 if(type != 'undefined' && type != 'unknown'){
9647 return d[ns+":"+name];
9650 } : function(ns, name){
9652 return d.getAttributeNS(ns, name) || d.getAttribute(ns+":"+name) || d.getAttribute(name) || d[name];
9657 * Sets or Returns the value the dom attribute value
9658 * @param {String|Object} name The attribute name (or object to set multiple attributes)
9659 * @param {String} value (optional) The value to set the attribute to
9660 * @return {String} The attribute value
9662 attr : function(name){
9663 if (arguments.length > 1) {
9664 this.dom.setAttribute(name, arguments[1]);
9665 return arguments[1];
9667 if (typeof(name) == 'object') {
9668 for(var i in name) {
9669 this.attr(i, name[i]);
9675 if (!this.dom.hasAttribute(name)) {
9678 return this.dom.getAttribute(name);
9685 var ep = El.prototype;
9688 * Appends an event handler (Shorthand for addListener)
9689 * @param {String} eventName The type of event to append
9690 * @param {Function} fn The method the event invokes
9691 * @param {Object} scope (optional) The scope (this object) of the fn
9692 * @param {Object} options (optional)An object with standard {@link Roo.EventManager#addListener} options
9695 ep.on = ep.addListener;
9697 ep.mon = ep.addListener;
9700 * Removes an event handler from this element (shorthand for removeListener)
9701 * @param {String} eventName the type of event to remove
9702 * @param {Function} fn the method the event invokes
9703 * @return {Roo.Element} this
9706 ep.un = ep.removeListener;
9709 * true to automatically adjust width and height settings for box-model issues (default to true)
9711 ep.autoBoxAdjust = true;
9714 El.unitPattern = /\d+(px|em|%|en|ex|pt|in|cm|mm|pc)$/i;
9717 El.addUnits = function(v, defaultUnit){
9718 if(v === "" || v == "auto"){
9721 if(v === undefined){
9724 if(typeof v == "number" || !El.unitPattern.test(v)){
9725 return v + (defaultUnit || 'px');
9730 // special markup used throughout Roo when box wrapping elements
9731 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>';
9733 * Visibility mode constant - Use visibility to hide element
9739 * Visibility mode constant - Use display to hide element
9745 El.borders = {l: "border-left-width", r: "border-right-width", t: "border-top-width", b: "border-bottom-width"};
9746 El.paddings = {l: "padding-left", r: "padding-right", t: "padding-top", b: "padding-bottom"};
9747 El.margins = {l: "margin-left", r: "margin-right", t: "margin-top", b: "margin-bottom"};
9759 * Static method to retrieve Element objects. Uses simple caching to consistently return the same object.
9760 * Automatically fixes if an object was recreated with the same id via AJAX or DOM.
9761 * @param {String/HTMLElement/Element} el The id of the node, a DOM Node or an existing Element.
9762 * @return {Element} The Element object
9765 El.get = function(el){
9767 if(!el){ return null; }
9768 if(typeof el == "string"){ // element id
9769 if(!(elm = document.getElementById(el))){
9772 if(ex = El.cache[el]){
9775 ex = El.cache[el] = new El(elm);
9778 }else if(el.tagName){ // dom element
9782 if(ex = El.cache[id]){
9785 ex = El.cache[id] = new El(el);
9788 }else if(el instanceof El){
9790 el.dom = document.getElementById(el.id) || el.dom; // refresh dom element in case no longer valid,
9791 // catch case where it hasn't been appended
9792 El.cache[el.id] = el; // in case it was created directly with Element(), let's cache it
9795 }else if(el.isComposite){
9797 }else if(el instanceof Array){
9798 return El.select(el);
9799 }else if(el == document){
9800 // create a bogus element object representing the document object
9802 var f = function(){};
9803 f.prototype = El.prototype;
9805 docEl.dom = document;
9813 El.uncache = function(el){
9814 for(var i = 0, a = arguments, len = a.length; i < len; i++) {
9816 delete El.cache[a[i].id || a[i]];
9822 // Garbage collection - uncache elements/purge listeners on orphaned elements
9823 // so we don't hold a reference and cause the browser to retain them
9824 El.garbageCollect = function(){
9825 if(!Roo.enableGarbageCollector){
9826 clearInterval(El.collectorThread);
9829 for(var eid in El.cache){
9830 var el = El.cache[eid], d = el.dom;
9831 // -------------------------------------------------------
9832 // Determining what is garbage:
9833 // -------------------------------------------------------
9835 // dom node is null, definitely garbage
9836 // -------------------------------------------------------
9838 // no parentNode == direct orphan, definitely garbage
9839 // -------------------------------------------------------
9840 // !d.offsetParent && !document.getElementById(eid)
9841 // display none elements have no offsetParent so we will
9842 // also try to look it up by it's id. However, check
9843 // offsetParent first so we don't do unneeded lookups.
9844 // This enables collection of elements that are not orphans
9845 // directly, but somewhere up the line they have an orphan
9847 // -------------------------------------------------------
9848 if(!d || !d.parentNode || (!d.offsetParent && !document.getElementById(eid))){
9849 delete El.cache[eid];
9850 if(d && Roo.enableListenerCollection){
9856 El.collectorThreadId = setInterval(El.garbageCollect, 30000);
9860 El.Flyweight = function(dom){
9863 El.Flyweight.prototype = El.prototype;
9865 El._flyweights = {};
9867 * Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
9868 * the dom node can be overwritten by other code.
9869 * @param {String/HTMLElement} el The dom node or id
9870 * @param {String} named (optional) Allows for creation of named reusable flyweights to
9871 * prevent conflicts (e.g. internally Roo uses "_internal")
9873 * @return {Element} The shared Element object
9875 El.fly = function(el, named){
9876 named = named || '_global';
9877 el = Roo.getDom(el);
9881 if(!El._flyweights[named]){
9882 El._flyweights[named] = new El.Flyweight();
9884 El._flyweights[named].dom = el;
9885 return El._flyweights[named];
9889 * Static method to retrieve Element objects. Uses simple caching to consistently return the same object.
9890 * Automatically fixes if an object was recreated with the same id via AJAX or DOM.
9891 * Shorthand of {@link Roo.Element#get}
9892 * @param {String/HTMLElement/Element} el The id of the node, a DOM Node or an existing Element.
9893 * @return {Element} The Element object
9899 * Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
9900 * the dom node can be overwritten by other code.
9901 * Shorthand of {@link Roo.Element#fly}
9902 * @param {String/HTMLElement} el The dom node or id
9903 * @param {String} named (optional) Allows for creation of named reusable flyweights to
9904 * prevent conflicts (e.g. internally Roo uses "_internal")
9906 * @return {Element} The shared Element object
9912 // speedy lookup for elements never to box adjust
9913 var noBoxAdjust = Roo.isStrict ? {
9916 input:1, select:1, textarea:1
9918 if(Roo.isIE || Roo.isGecko){
9919 noBoxAdjust['button'] = 1;
9923 Roo.EventManager.on(window, 'unload', function(){
9925 delete El._flyweights;
9933 Roo.Element.selectorFunction = Roo.DomQuery.select;
9936 Roo.Element.select = function(selector, unique, root){
9938 if(typeof selector == "string"){
9939 els = Roo.Element.selectorFunction(selector, root);
9940 }else if(selector.length !== undefined){
9943 throw "Invalid selector";
9945 if(unique === true){
9946 return new Roo.CompositeElement(els);
9948 return new Roo.CompositeElementLite(els);
9952 * Selects elements based on the passed CSS selector to enable working on them as 1.
9953 * @param {String/Array} selector The CSS selector or an array of elements
9954 * @param {Boolean} unique (optional) true to create a unique Roo.Element for each element (defaults to a shared flyweight object)
9955 * @param {HTMLElement/String} root (optional) The root element of the query or id of the root
9956 * @return {CompositeElementLite/CompositeElement}
9960 Roo.select = Roo.Element.select;
9977 * Ext JS Library 1.1.1
9978 * Copyright(c) 2006-2007, Ext JS, LLC.
9980 * Originally Released Under LGPL - original licence link has changed is not relivant.
9983 * <script type="text/javascript">
9988 //Notifies Element that fx methods are available
9989 Roo.enableFx = true;
9993 * <p>A class to provide basic animation and visual effects support. <b>Note:</b> This class is automatically applied
9994 * to the {@link Roo.Element} interface when included, so all effects calls should be performed via Element.
9995 * Conversely, since the effects are not actually defined in Element, Roo.Fx <b>must</b> be included in order for the
9996 * Element effects to work.</p><br/>
9998 * <p>It is important to note that although the Fx methods and many non-Fx Element methods support "method chaining" in that
9999 * they return the Element object itself as the method return value, it is not always possible to mix the two in a single
10000 * method chain. The Fx methods use an internal effects queue so that each effect can be properly timed and sequenced.
10001 * Non-Fx methods, on the other hand, have no such internal queueing and will always execute immediately. For this reason,
10002 * while it may be possible to mix certain Fx and non-Fx method calls in a single chain, it may not always provide the
10003 * expected results and should be done with care.</p><br/>
10005 * <p>Motion effects support 8-way anchoring, meaning that you can choose one of 8 different anchor points on the Element
10006 * that will serve as either the start or end point of the animation. Following are all of the supported anchor positions:</p>
10009 ----- -----------------------------
10010 tl The top left corner
10011 t The center of the top edge
10012 tr The top right corner
10013 l The center of the left edge
10014 r The center of the right edge
10015 bl The bottom left corner
10016 b The center of the bottom edge
10017 br The bottom right corner
10019 * <b>Although some Fx methods accept specific custom config parameters, the ones shown in the Config Options section
10020 * below are common options that can be passed to any Fx method.</b>
10021 * @cfg {Function} callback A function called when the effect is finished
10022 * @cfg {Object} scope The scope of the effect function
10023 * @cfg {String} easing A valid Easing value for the effect
10024 * @cfg {String} afterCls A css class to apply after the effect
10025 * @cfg {Number} duration The length of time (in seconds) that the effect should last
10026 * @cfg {Boolean} remove Whether the Element should be removed from the DOM and destroyed after the effect finishes
10027 * @cfg {Boolean} useDisplay Whether to use the <i>display</i> CSS property instead of <i>visibility</i> when hiding Elements (only applies to
10028 * effects that end with the element being visually hidden, ignored otherwise)
10029 * @cfg {String/Object/Function} afterStyle A style specification string, e.g. "width:100px", or an object in the form {width:"100px"}, or
10030 * a function which returns such a specification that will be applied to the Element after the effect finishes
10031 * @cfg {Boolean} block Whether the effect should block other effects from queueing while it runs
10032 * @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
10033 * @cfg {Boolean} stopFx Whether subsequent effects should be stopped and removed after the current effect finishes
10037 * Slides the element into view. An anchor point can be optionally passed to set the point of
10038 * origin for the slide effect. This function automatically handles wrapping the element with
10039 * a fixed-size container if needed. See the Fx class overview for valid anchor point options.
10042 // default: slide the element in from the top
10045 // custom: slide the element in from the right with a 2-second duration
10046 el.slideIn('r', { duration: 2 });
10048 // common config options shown with default values
10054 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to top: 't')
10055 * @param {Object} options (optional) Object literal with any of the Fx config options
10056 * @return {Roo.Element} The Element
10058 slideIn : function(anchor, o){
10059 var el = this.getFxEl();
10062 el.queueFx(o, function(){
10064 anchor = anchor || "t";
10066 // fix display to visibility
10069 // restore values after effect
10070 var r = this.getFxRestore();
10071 var b = this.getBox();
10072 // fixed size for slide
10076 var wrap = this.fxWrap(r.pos, o, "hidden");
10078 var st = this.dom.style;
10079 st.visibility = "visible";
10080 st.position = "absolute";
10082 // clear out temp styles after slide and unwrap
10083 var after = function(){
10084 el.fxUnwrap(wrap, r.pos, o);
10085 st.width = r.width;
10086 st.height = r.height;
10089 // time to calc the positions
10090 var a, pt = {to: [b.x, b.y]}, bw = {to: b.width}, bh = {to: b.height};
10092 switch(anchor.toLowerCase()){
10094 wrap.setSize(b.width, 0);
10095 st.left = st.bottom = "0";
10099 wrap.setSize(0, b.height);
10100 st.right = st.top = "0";
10104 wrap.setSize(0, b.height);
10105 wrap.setX(b.right);
10106 st.left = st.top = "0";
10107 a = {width: bw, points: pt};
10110 wrap.setSize(b.width, 0);
10111 wrap.setY(b.bottom);
10112 st.left = st.top = "0";
10113 a = {height: bh, points: pt};
10116 wrap.setSize(0, 0);
10117 st.right = st.bottom = "0";
10118 a = {width: bw, height: bh};
10121 wrap.setSize(0, 0);
10122 wrap.setY(b.y+b.height);
10123 st.right = st.top = "0";
10124 a = {width: bw, height: bh, points: pt};
10127 wrap.setSize(0, 0);
10128 wrap.setXY([b.right, b.bottom]);
10129 st.left = st.top = "0";
10130 a = {width: bw, height: bh, points: pt};
10133 wrap.setSize(0, 0);
10134 wrap.setX(b.x+b.width);
10135 st.left = st.bottom = "0";
10136 a = {width: bw, height: bh, points: pt};
10139 this.dom.style.visibility = "visible";
10142 arguments.callee.anim = wrap.fxanim(a,
10152 * Slides the element out of view. An anchor point can be optionally passed to set the end point
10153 * for the slide effect. When the effect is completed, the element will be hidden (visibility =
10154 * 'hidden') but block elements will still take up space in the document. The element must be removed
10155 * from the DOM using the 'remove' config option if desired. This function automatically handles
10156 * wrapping the element with a fixed-size container if needed. See the Fx class overview for valid anchor point options.
10159 // default: slide the element out to the top
10162 // custom: slide the element out to the right with a 2-second duration
10163 el.slideOut('r', { duration: 2 });
10165 // common config options shown with default values
10173 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to top: 't')
10174 * @param {Object} options (optional) Object literal with any of the Fx config options
10175 * @return {Roo.Element} The Element
10177 slideOut : function(anchor, o){
10178 var el = this.getFxEl();
10181 el.queueFx(o, function(){
10183 anchor = anchor || "t";
10185 // restore values after effect
10186 var r = this.getFxRestore();
10188 var b = this.getBox();
10189 // fixed size for slide
10193 var wrap = this.fxWrap(r.pos, o, "visible");
10195 var st = this.dom.style;
10196 st.visibility = "visible";
10197 st.position = "absolute";
10201 var after = function(){
10203 el.setDisplayed(false);
10208 el.fxUnwrap(wrap, r.pos, o);
10210 st.width = r.width;
10211 st.height = r.height;
10216 var a, zero = {to: 0};
10217 switch(anchor.toLowerCase()){
10219 st.left = st.bottom = "0";
10220 a = {height: zero};
10223 st.right = st.top = "0";
10227 st.left = st.top = "0";
10228 a = {width: zero, points: {to:[b.right, b.y]}};
10231 st.left = st.top = "0";
10232 a = {height: zero, points: {to:[b.x, b.bottom]}};
10235 st.right = st.bottom = "0";
10236 a = {width: zero, height: zero};
10239 st.right = st.top = "0";
10240 a = {width: zero, height: zero, points: {to:[b.x, b.bottom]}};
10243 st.left = st.top = "0";
10244 a = {width: zero, height: zero, points: {to:[b.x+b.width, b.bottom]}};
10247 st.left = st.bottom = "0";
10248 a = {width: zero, height: zero, points: {to:[b.right, b.y]}};
10252 arguments.callee.anim = wrap.fxanim(a,
10262 * Fades the element out while slowly expanding it in all directions. When the effect is completed, the
10263 * element will be hidden (visibility = 'hidden') but block elements will still take up space in the document.
10264 * The element must be removed from the DOM using the 'remove' config option if desired.
10270 // common config options shown with default values
10278 * @param {Object} options (optional) Object literal with any of the Fx config options
10279 * @return {Roo.Element} The Element
10281 puff : function(o){
10282 var el = this.getFxEl();
10285 el.queueFx(o, function(){
10286 this.clearOpacity();
10289 // restore values after effect
10290 var r = this.getFxRestore();
10291 var st = this.dom.style;
10293 var after = function(){
10295 el.setDisplayed(false);
10302 el.setPositioning(r.pos);
10303 st.width = r.width;
10304 st.height = r.height;
10309 var width = this.getWidth();
10310 var height = this.getHeight();
10312 arguments.callee.anim = this.fxanim({
10313 width : {to: this.adjustWidth(width * 2)},
10314 height : {to: this.adjustHeight(height * 2)},
10315 points : {by: [-(width * .5), -(height * .5)]},
10317 fontSize: {to:200, unit: "%"}
10328 * Blinks the element as if it was clicked and then collapses on its center (similar to switching off a television).
10329 * When the effect is completed, the element will be hidden (visibility = 'hidden') but block elements will still
10330 * take up space in the document. The element must be removed from the DOM using the 'remove' config option if desired.
10336 // all config options shown with default values
10344 * @param {Object} options (optional) Object literal with any of the Fx config options
10345 * @return {Roo.Element} The Element
10347 switchOff : function(o){
10348 var el = this.getFxEl();
10351 el.queueFx(o, function(){
10352 this.clearOpacity();
10355 // restore values after effect
10356 var r = this.getFxRestore();
10357 var st = this.dom.style;
10359 var after = function(){
10361 el.setDisplayed(false);
10367 el.setPositioning(r.pos);
10368 st.width = r.width;
10369 st.height = r.height;
10374 this.fxanim({opacity:{to:0.3}}, null, null, .1, null, function(){
10375 this.clearOpacity();
10379 points:{by:[0, this.getHeight() * .5]}
10380 }, o, 'motion', 0.3, 'easeIn', after);
10381 }).defer(100, this);
10388 * Highlights the Element by setting a color (applies to the background-color by default, but can be
10389 * changed using the "attr" config option) and then fading back to the original color. If no original
10390 * color is available, you should provide the "endColor" config option which will be cleared after the animation.
10393 // default: highlight background to yellow
10396 // custom: highlight foreground text to blue for 2 seconds
10397 el.highlight("0000ff", { attr: 'color', duration: 2 });
10399 // common config options shown with default values
10400 el.highlight("ffff9c", {
10401 attr: "background-color", //can be any valid CSS property (attribute) that supports a color value
10402 endColor: (current color) or "ffffff",
10407 * @param {String} color (optional) The highlight color. Should be a 6 char hex color without the leading # (defaults to yellow: 'ffff9c')
10408 * @param {Object} options (optional) Object literal with any of the Fx config options
10409 * @return {Roo.Element} The Element
10411 highlight : function(color, o){
10412 var el = this.getFxEl();
10415 el.queueFx(o, function(){
10416 color = color || "ffff9c";
10417 attr = o.attr || "backgroundColor";
10419 this.clearOpacity();
10422 var origColor = this.getColor(attr);
10423 var restoreColor = this.dom.style[attr];
10424 endColor = (o.endColor || origColor) || "ffffff";
10426 var after = function(){
10427 el.dom.style[attr] = restoreColor;
10432 a[attr] = {from: color, to: endColor};
10433 arguments.callee.anim = this.fxanim(a,
10443 * Shows a ripple of exploding, attenuating borders to draw attention to an Element.
10446 // default: a single light blue ripple
10449 // custom: 3 red ripples lasting 3 seconds total
10450 el.frame("ff0000", 3, { duration: 3 });
10452 // common config options shown with default values
10453 el.frame("C3DAF9", 1, {
10454 duration: 1 //duration of entire animation (not each individual ripple)
10455 // Note: Easing is not configurable and will be ignored if included
10458 * @param {String} color (optional) The color of the border. Should be a 6 char hex color without the leading # (defaults to light blue: 'C3DAF9').
10459 * @param {Number} count (optional) The number of ripples to display (defaults to 1)
10460 * @param {Object} options (optional) Object literal with any of the Fx config options
10461 * @return {Roo.Element} The Element
10463 frame : function(color, count, o){
10464 var el = this.getFxEl();
10467 el.queueFx(o, function(){
10468 color = color || "#C3DAF9";
10469 if(color.length == 6){
10470 color = "#" + color;
10472 count = count || 1;
10473 duration = o.duration || 1;
10476 var b = this.getBox();
10477 var animFn = function(){
10478 var proxy = this.createProxy({
10481 visbility:"hidden",
10482 position:"absolute",
10483 "z-index":"35000", // yee haw
10484 border:"0px solid " + color
10487 var scale = Roo.isBorderBox ? 2 : 1;
10489 top:{from:b.y, to:b.y - 20},
10490 left:{from:b.x, to:b.x - 20},
10491 borderWidth:{from:0, to:10},
10492 opacity:{from:1, to:0},
10493 height:{from:b.height, to:(b.height + (20*scale))},
10494 width:{from:b.width, to:(b.width + (20*scale))}
10495 }, duration, function(){
10499 animFn.defer((duration/2)*1000, this);
10510 * Creates a pause before any subsequent queued effects begin. If there are
10511 * no effects queued after the pause it will have no effect.
10516 * @param {Number} seconds The length of time to pause (in seconds)
10517 * @return {Roo.Element} The Element
10519 pause : function(seconds){
10520 var el = this.getFxEl();
10523 el.queueFx(o, function(){
10524 setTimeout(function(){
10526 }, seconds * 1000);
10532 * Fade an element in (from transparent to opaque). The ending opacity can be specified
10533 * using the "endOpacity" config option.
10536 // default: fade in from opacity 0 to 100%
10539 // custom: fade in from opacity 0 to 75% over 2 seconds
10540 el.fadeIn({ endOpacity: .75, duration: 2});
10542 // common config options shown with default values
10544 endOpacity: 1, //can be any value between 0 and 1 (e.g. .5)
10549 * @param {Object} options (optional) Object literal with any of the Fx config options
10550 * @return {Roo.Element} The Element
10552 fadeIn : function(o){
10553 var el = this.getFxEl();
10555 el.queueFx(o, function(){
10556 this.setOpacity(0);
10558 this.dom.style.visibility = 'visible';
10559 var to = o.endOpacity || 1;
10560 arguments.callee.anim = this.fxanim({opacity:{to:to}},
10561 o, null, .5, "easeOut", function(){
10563 this.clearOpacity();
10572 * Fade an element out (from opaque to transparent). The ending opacity can be specified
10573 * using the "endOpacity" config option.
10576 // default: fade out from the element's current opacity to 0
10579 // custom: fade out from the element's current opacity to 25% over 2 seconds
10580 el.fadeOut({ endOpacity: .25, duration: 2});
10582 // common config options shown with default values
10584 endOpacity: 0, //can be any value between 0 and 1 (e.g. .5)
10591 * @param {Object} options (optional) Object literal with any of the Fx config options
10592 * @return {Roo.Element} The Element
10594 fadeOut : function(o){
10595 var el = this.getFxEl();
10597 el.queueFx(o, function(){
10598 arguments.callee.anim = this.fxanim({opacity:{to:o.endOpacity || 0}},
10599 o, null, .5, "easeOut", function(){
10600 if(this.visibilityMode == Roo.Element.DISPLAY || o.useDisplay){
10601 this.dom.style.display = "none";
10603 this.dom.style.visibility = "hidden";
10605 this.clearOpacity();
10613 * Animates the transition of an element's dimensions from a starting height/width
10614 * to an ending height/width.
10617 // change height and width to 100x100 pixels
10618 el.scale(100, 100);
10620 // common config options shown with default values. The height and width will default to
10621 // the element's existing values if passed as null.
10624 [element's height], {
10629 * @param {Number} width The new width (pass undefined to keep the original width)
10630 * @param {Number} height The new height (pass undefined to keep the original height)
10631 * @param {Object} options (optional) Object literal with any of the Fx config options
10632 * @return {Roo.Element} The Element
10634 scale : function(w, h, o){
10635 this.shift(Roo.apply({}, o, {
10643 * Animates the transition of any combination of an element's dimensions, xy position and/or opacity.
10644 * Any of these properties not specified in the config object will not be changed. This effect
10645 * requires that at least one new dimension, position or opacity setting must be passed in on
10646 * the config object in order for the function to have any effect.
10649 // slide the element horizontally to x position 200 while changing the height and opacity
10650 el.shift({ x: 200, height: 50, opacity: .8 });
10652 // common config options shown with default values.
10654 width: [element's width],
10655 height: [element's height],
10656 x: [element's x position],
10657 y: [element's y position],
10658 opacity: [element's opacity],
10663 * @param {Object} options Object literal with any of the Fx config options
10664 * @return {Roo.Element} The Element
10666 shift : function(o){
10667 var el = this.getFxEl();
10669 el.queueFx(o, function(){
10670 var a = {}, w = o.width, h = o.height, x = o.x, y = o.y, op = o.opacity;
10671 if(w !== undefined){
10672 a.width = {to: this.adjustWidth(w)};
10674 if(h !== undefined){
10675 a.height = {to: this.adjustHeight(h)};
10677 if(x !== undefined || y !== undefined){
10679 x !== undefined ? x : this.getX(),
10680 y !== undefined ? y : this.getY()
10683 if(op !== undefined){
10684 a.opacity = {to: op};
10686 if(o.xy !== undefined){
10687 a.points = {to: o.xy};
10689 arguments.callee.anim = this.fxanim(a,
10690 o, 'motion', .35, "easeOut", function(){
10698 * Slides the element while fading it out of view. An anchor point can be optionally passed to set the
10699 * ending point of the effect.
10702 // default: slide the element downward while fading out
10705 // custom: slide the element out to the right with a 2-second duration
10706 el.ghost('r', { duration: 2 });
10708 // common config options shown with default values
10716 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to bottom: 'b')
10717 * @param {Object} options (optional) Object literal with any of the Fx config options
10718 * @return {Roo.Element} The Element
10720 ghost : function(anchor, o){
10721 var el = this.getFxEl();
10724 el.queueFx(o, function(){
10725 anchor = anchor || "b";
10727 // restore values after effect
10728 var r = this.getFxRestore();
10729 var w = this.getWidth(),
10730 h = this.getHeight();
10732 var st = this.dom.style;
10734 var after = function(){
10736 el.setDisplayed(false);
10742 el.setPositioning(r.pos);
10743 st.width = r.width;
10744 st.height = r.height;
10749 var a = {opacity: {to: 0}, points: {}}, pt = a.points;
10750 switch(anchor.toLowerCase()){
10777 arguments.callee.anim = this.fxanim(a,
10787 * Ensures that all effects queued after syncFx is called on the element are
10788 * run concurrently. This is the opposite of {@link #sequenceFx}.
10789 * @return {Roo.Element} The Element
10791 syncFx : function(){
10792 this.fxDefaults = Roo.apply(this.fxDefaults || {}, {
10801 * Ensures that all effects queued after sequenceFx is called on the element are
10802 * run in sequence. This is the opposite of {@link #syncFx}.
10803 * @return {Roo.Element} The Element
10805 sequenceFx : function(){
10806 this.fxDefaults = Roo.apply(this.fxDefaults || {}, {
10808 concurrent : false,
10815 nextFx : function(){
10816 var ef = this.fxQueue[0];
10823 * Returns true if the element has any effects actively running or queued, else returns false.
10824 * @return {Boolean} True if element has active effects, else false
10826 hasActiveFx : function(){
10827 return this.fxQueue && this.fxQueue[0];
10831 * Stops any running effects and clears the element's internal effects queue if it contains
10832 * any additional effects that haven't started yet.
10833 * @return {Roo.Element} The Element
10835 stopFx : function(){
10836 if(this.hasActiveFx()){
10837 var cur = this.fxQueue[0];
10838 if(cur && cur.anim && cur.anim.isAnimated()){
10839 this.fxQueue = [cur]; // clear out others
10840 cur.anim.stop(true);
10847 beforeFx : function(o){
10848 if(this.hasActiveFx() && !o.concurrent){
10859 * Returns true if the element is currently blocking so that no other effect can be queued
10860 * until this effect is finished, else returns false if blocking is not set. This is commonly
10861 * used to ensure that an effect initiated by a user action runs to completion prior to the
10862 * same effect being restarted (e.g., firing only one effect even if the user clicks several times).
10863 * @return {Boolean} True if blocking, else false
10865 hasFxBlock : function(){
10866 var q = this.fxQueue;
10867 return q && q[0] && q[0].block;
10871 queueFx : function(o, fn){
10875 if(!this.hasFxBlock()){
10876 Roo.applyIf(o, this.fxDefaults);
10878 var run = this.beforeFx(o);
10879 fn.block = o.block;
10880 this.fxQueue.push(fn);
10892 fxWrap : function(pos, o, vis){
10894 if(!o.wrap || !(wrap = Roo.get(o.wrap))){
10897 wrapXY = this.getXY();
10899 var div = document.createElement("div");
10900 div.style.visibility = vis;
10901 wrap = Roo.get(this.dom.parentNode.insertBefore(div, this.dom));
10902 wrap.setPositioning(pos);
10903 if(wrap.getStyle("position") == "static"){
10904 wrap.position("relative");
10906 this.clearPositioning('auto');
10908 wrap.dom.appendChild(this.dom);
10910 wrap.setXY(wrapXY);
10917 fxUnwrap : function(wrap, pos, o){
10918 this.clearPositioning();
10919 this.setPositioning(pos);
10921 wrap.dom.parentNode.insertBefore(this.dom, wrap.dom);
10927 getFxRestore : function(){
10928 var st = this.dom.style;
10929 return {pos: this.getPositioning(), width: st.width, height : st.height};
10933 afterFx : function(o){
10935 this.applyStyles(o.afterStyle);
10938 this.addClass(o.afterCls);
10940 if(o.remove === true){
10943 Roo.callback(o.callback, o.scope, [this]);
10945 this.fxQueue.shift();
10951 getFxEl : function(){ // support for composite element fx
10952 return Roo.get(this.dom);
10956 fxanim : function(args, opt, animType, defaultDur, defaultEase, cb){
10957 animType = animType || 'run';
10959 var anim = Roo.lib.Anim[animType](
10961 (opt.duration || defaultDur) || .35,
10962 (opt.easing || defaultEase) || 'easeOut',
10964 Roo.callback(cb, this);
10973 // backwords compat
10974 Roo.Fx.resize = Roo.Fx.scale;
10976 //When included, Roo.Fx is automatically applied to Element so that all basic
10977 //effects are available directly via the Element API
10978 Roo.apply(Roo.Element.prototype, Roo.Fx);/*
10980 * Ext JS Library 1.1.1
10981 * Copyright(c) 2006-2007, Ext JS, LLC.
10983 * Originally Released Under LGPL - original licence link has changed is not relivant.
10986 * <script type="text/javascript">
10991 * @class Roo.CompositeElement
10992 * Standard composite class. Creates a Roo.Element for every element in the collection.
10994 * <b>NOTE: Although they are not listed, this class supports all of the set/update methods of Roo.Element. All Roo.Element
10995 * actions will be performed on all the elements in this collection.</b>
10997 * All methods return <i>this</i> and can be chained.
10999 var els = Roo.select("#some-el div.some-class", true);
11000 // or select directly from an existing element
11001 var el = Roo.get('some-el');
11002 el.select('div.some-class', true);
11004 els.setWidth(100); // all elements become 100 width
11005 els.hide(true); // all elements fade out and hide
11007 els.setWidth(100).hide(true);
11010 Roo.CompositeElement = function(els){
11011 this.elements = [];
11012 this.addElements(els);
11014 Roo.CompositeElement.prototype = {
11016 addElements : function(els){
11017 if(!els) return this;
11018 if(typeof els == "string"){
11019 els = Roo.Element.selectorFunction(els);
11021 var yels = this.elements;
11022 var index = yels.length-1;
11023 for(var i = 0, len = els.length; i < len; i++) {
11024 yels[++index] = Roo.get(els[i]);
11030 * Clears this composite and adds the elements returned by the passed selector.
11031 * @param {String/Array} els A string CSS selector, an array of elements or an element
11032 * @return {CompositeElement} this
11034 fill : function(els){
11035 this.elements = [];
11041 * Filters this composite to only elements that match the passed selector.
11042 * @param {String} selector A string CSS selector
11043 * @param {Boolean} inverse return inverse filter (not matches)
11044 * @return {CompositeElement} this
11046 filter : function(selector, inverse){
11048 inverse = inverse || false;
11049 this.each(function(el){
11050 var match = inverse ? !el.is(selector) : el.is(selector);
11052 els[els.length] = el.dom;
11059 invoke : function(fn, args){
11060 var els = this.elements;
11061 for(var i = 0, len = els.length; i < len; i++) {
11062 Roo.Element.prototype[fn].apply(els[i], args);
11067 * Adds elements to this composite.
11068 * @param {String/Array} els A string CSS selector, an array of elements or an element
11069 * @return {CompositeElement} this
11071 add : function(els){
11072 if(typeof els == "string"){
11073 this.addElements(Roo.Element.selectorFunction(els));
11074 }else if(els.length !== undefined){
11075 this.addElements(els);
11077 this.addElements([els]);
11082 * Calls the passed function passing (el, this, index) for each element in this composite.
11083 * @param {Function} fn The function to call
11084 * @param {Object} scope (optional) The <i>this</i> object (defaults to the element)
11085 * @return {CompositeElement} this
11087 each : function(fn, scope){
11088 var els = this.elements;
11089 for(var i = 0, len = els.length; i < len; i++){
11090 if(fn.call(scope || els[i], els[i], this, i) === false) {
11098 * Returns the Element object at the specified index
11099 * @param {Number} index
11100 * @return {Roo.Element}
11102 item : function(index){
11103 return this.elements[index] || null;
11107 * Returns the first Element
11108 * @return {Roo.Element}
11110 first : function(){
11111 return this.item(0);
11115 * Returns the last Element
11116 * @return {Roo.Element}
11119 return this.item(this.elements.length-1);
11123 * Returns the number of elements in this composite
11126 getCount : function(){
11127 return this.elements.length;
11131 * Returns true if this composite contains the passed element
11134 contains : function(el){
11135 return this.indexOf(el) !== -1;
11139 * Returns true if this composite contains the passed element
11142 indexOf : function(el){
11143 return this.elements.indexOf(Roo.get(el));
11148 * Removes the specified element(s).
11149 * @param {Mixed} el The id of an element, the Element itself, the index of the element in this composite
11150 * or an array of any of those.
11151 * @param {Boolean} removeDom (optional) True to also remove the element from the document
11152 * @return {CompositeElement} this
11154 removeElement : function(el, removeDom){
11155 if(el instanceof Array){
11156 for(var i = 0, len = el.length; i < len; i++){
11157 this.removeElement(el[i]);
11161 var index = typeof el == 'number' ? el : this.indexOf(el);
11164 var d = this.elements[index];
11168 d.parentNode.removeChild(d);
11171 this.elements.splice(index, 1);
11177 * Replaces the specified element with the passed element.
11178 * @param {String/HTMLElement/Element/Number} el The id of an element, the Element itself, the index of the element in this composite
11180 * @param {String/HTMLElement/Element} replacement The id of an element or the Element itself.
11181 * @param {Boolean} domReplace (Optional) True to remove and replace the element in the document too.
11182 * @return {CompositeElement} this
11184 replaceElement : function(el, replacement, domReplace){
11185 var index = typeof el == 'number' ? el : this.indexOf(el);
11188 this.elements[index].replaceWith(replacement);
11190 this.elements.splice(index, 1, Roo.get(replacement))
11197 * Removes all elements.
11199 clear : function(){
11200 this.elements = [];
11204 Roo.CompositeElement.createCall = function(proto, fnName){
11205 if(!proto[fnName]){
11206 proto[fnName] = function(){
11207 return this.invoke(fnName, arguments);
11211 for(var fnName in Roo.Element.prototype){
11212 if(typeof Roo.Element.prototype[fnName] == "function"){
11213 Roo.CompositeElement.createCall(Roo.CompositeElement.prototype, fnName);
11219 * Ext JS Library 1.1.1
11220 * Copyright(c) 2006-2007, Ext JS, LLC.
11222 * Originally Released Under LGPL - original licence link has changed is not relivant.
11225 * <script type="text/javascript">
11229 * @class Roo.CompositeElementLite
11230 * @extends Roo.CompositeElement
11231 * Flyweight composite class. Reuses the same Roo.Element for element operations.
11233 var els = Roo.select("#some-el div.some-class");
11234 // or select directly from an existing element
11235 var el = Roo.get('some-el');
11236 el.select('div.some-class');
11238 els.setWidth(100); // all elements become 100 width
11239 els.hide(true); // all elements fade out and hide
11241 els.setWidth(100).hide(true);
11242 </code></pre><br><br>
11243 * <b>NOTE: Although they are not listed, this class supports all of the set/update methods of Roo.Element. All Roo.Element
11244 * actions will be performed on all the elements in this collection.</b>
11246 Roo.CompositeElementLite = function(els){
11247 Roo.CompositeElementLite.superclass.constructor.call(this, els);
11248 this.el = new Roo.Element.Flyweight();
11250 Roo.extend(Roo.CompositeElementLite, Roo.CompositeElement, {
11251 addElements : function(els){
11253 if(els instanceof Array){
11254 this.elements = this.elements.concat(els);
11256 var yels = this.elements;
11257 var index = yels.length-1;
11258 for(var i = 0, len = els.length; i < len; i++) {
11259 yels[++index] = els[i];
11265 invoke : function(fn, args){
11266 var els = this.elements;
11268 for(var i = 0, len = els.length; i < len; i++) {
11270 Roo.Element.prototype[fn].apply(el, args);
11275 * Returns a flyweight Element of the dom element object at the specified index
11276 * @param {Number} index
11277 * @return {Roo.Element}
11279 item : function(index){
11280 if(!this.elements[index]){
11283 this.el.dom = this.elements[index];
11287 // fixes scope with flyweight
11288 addListener : function(eventName, handler, scope, opt){
11289 var els = this.elements;
11290 for(var i = 0, len = els.length; i < len; i++) {
11291 Roo.EventManager.on(els[i], eventName, handler, scope || els[i], opt);
11297 * Calls the passed function passing (el, this, index) for each element in this composite. <b>The element
11298 * passed is the flyweight (shared) Roo.Element instance, so if you require a
11299 * a reference to the dom node, use el.dom.</b>
11300 * @param {Function} fn The function to call
11301 * @param {Object} scope (optional) The <i>this</i> object (defaults to the element)
11302 * @return {CompositeElement} this
11304 each : function(fn, scope){
11305 var els = this.elements;
11307 for(var i = 0, len = els.length; i < len; i++){
11309 if(fn.call(scope || el, el, this, i) === false){
11316 indexOf : function(el){
11317 return this.elements.indexOf(Roo.getDom(el));
11320 replaceElement : function(el, replacement, domReplace){
11321 var index = typeof el == 'number' ? el : this.indexOf(el);
11323 replacement = Roo.getDom(replacement);
11325 var d = this.elements[index];
11326 d.parentNode.insertBefore(replacement, d);
11327 d.parentNode.removeChild(d);
11329 this.elements.splice(index, 1, replacement);
11334 Roo.CompositeElementLite.prototype.on = Roo.CompositeElementLite.prototype.addListener;
11338 * Ext JS Library 1.1.1
11339 * Copyright(c) 2006-2007, Ext JS, LLC.
11341 * Originally Released Under LGPL - original licence link has changed is not relivant.
11344 * <script type="text/javascript">
11350 * @class Roo.data.Connection
11351 * @extends Roo.util.Observable
11352 * The class encapsulates a connection to the page's originating domain, allowing requests to be made
11353 * either to a configured URL, or to a URL specified at request time.<br><br>
11355 * Requests made by this class are asynchronous, and will return immediately. No data from
11356 * the server will be available to the statement immediately following the {@link #request} call.
11357 * To process returned data, use a callback in the request options object, or an event listener.</p><br>
11359 * Note: If you are doing a file upload, you will not get a normal response object sent back to
11360 * your callback or event handler. Since the upload is handled via in IFRAME, there is no XMLHttpRequest.
11361 * The response object is created using the innerHTML of the IFRAME's document as the responseText
11362 * property and, if present, the IFRAME's XML document as the responseXML property.</p><br>
11363 * This means that a valid XML or HTML document must be returned. If JSON data is required, it is suggested
11364 * that it be placed either inside a <textarea> in an HTML document and retrieved from the responseText
11365 * using a regex, or inside a CDATA section in an XML document and retrieved from the responseXML using
11366 * standard DOM methods.
11368 * @param {Object} config a configuration object.
11370 Roo.data.Connection = function(config){
11371 Roo.apply(this, config);
11374 * @event beforerequest
11375 * Fires before a network request is made to retrieve a data object.
11376 * @param {Connection} conn This Connection object.
11377 * @param {Object} options The options config object passed to the {@link #request} method.
11379 "beforerequest" : true,
11381 * @event requestcomplete
11382 * Fires if the request was successfully completed.
11383 * @param {Connection} conn This Connection object.
11384 * @param {Object} response The XHR object containing the response data.
11385 * See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
11386 * @param {Object} options The options config object passed to the {@link #request} method.
11388 "requestcomplete" : true,
11390 * @event requestexception
11391 * Fires if an error HTTP status was returned from the server.
11392 * See {@link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html} for details of HTTP status codes.
11393 * @param {Connection} conn This Connection object.
11394 * @param {Object} response The XHR object containing the response data.
11395 * See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
11396 * @param {Object} options The options config object passed to the {@link #request} method.
11398 "requestexception" : true
11400 Roo.data.Connection.superclass.constructor.call(this);
11403 Roo.extend(Roo.data.Connection, Roo.util.Observable, {
11405 * @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
11408 * @cfg {Object} extraParams (Optional) An object containing properties which are used as
11409 * extra parameters to each request made by this object. (defaults to undefined)
11412 * @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
11413 * to each request made by this object. (defaults to undefined)
11416 * @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)
11419 * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
11423 * @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
11429 * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
11432 disableCaching: true,
11435 * Sends an HTTP request to a remote server.
11436 * @param {Object} options An object which may contain the following properties:<ul>
11437 * <li><b>url</b> {String} (Optional) The URL to which to send the request. Defaults to configured URL</li>
11438 * <li><b>params</b> {Object/String/Function} (Optional) An object containing properties which are used as parameters to the
11439 * request, a url encoded string or a function to call to get either.</li>
11440 * <li><b>method</b> {String} (Optional) The HTTP method to use for the request. Defaults to the configured method, or
11441 * if no method was configured, "GET" if no parameters are being sent, and "POST" if parameters are being sent.</li>
11442 * <li><b>callback</b> {Function} (Optional) The function to be called upon receipt of the HTTP response.
11443 * The callback is called regardless of success or failure and is passed the following parameters:<ul>
11444 * <li>options {Object} The parameter to the request call.</li>
11445 * <li>success {Boolean} True if the request succeeded.</li>
11446 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
11448 * <li><b>success</b> {Function} (Optional) The function to be called upon success of the request.
11449 * The callback is passed the following parameters:<ul>
11450 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
11451 * <li>options {Object} The parameter to the request call.</li>
11453 * <li><b>failure</b> {Function} (Optional) The function to be called upon failure of the request.
11454 * The callback is passed the following parameters:<ul>
11455 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
11456 * <li>options {Object} The parameter to the request call.</li>
11458 * <li><b>scope</b> {Object} (Optional) The scope in which to execute the callbacks: The "this" object
11459 * for the callback function. Defaults to the browser window.</li>
11460 * <li><b>form</b> {Object/String} (Optional) A form object or id to pull parameters from.</li>
11461 * <li><b>isUpload</b> {Boolean} (Optional) True if the form object is a file upload (will usually be automatically detected).</li>
11462 * <li><b>headers</b> {Object} (Optional) Request headers to set for the request.</li>
11463 * <li><b>xmlData</b> {Object} (Optional) XML document to use for the post. Note: This will be used instead of
11464 * params for the post data. Any params will be appended to the URL.</li>
11465 * <li><b>disableCaching</b> {Boolean} (Optional) True to add a unique cache-buster param to GET requests.</li>
11467 * @return {Number} transactionId
11469 request : function(o){
11470 if(this.fireEvent("beforerequest", this, o) !== false){
11473 if(typeof p == "function"){
11474 p = p.call(o.scope||window, o);
11476 if(typeof p == "object"){
11477 p = Roo.urlEncode(o.params);
11479 if(this.extraParams){
11480 var extras = Roo.urlEncode(this.extraParams);
11481 p = p ? (p + '&' + extras) : extras;
11484 var url = o.url || this.url;
11485 if(typeof url == 'function'){
11486 url = url.call(o.scope||window, o);
11490 var form = Roo.getDom(o.form);
11491 url = url || form.action;
11493 var enctype = form.getAttribute("enctype");
11494 if(o.isUpload || (enctype && enctype.toLowerCase() == 'multipart/form-data')){
11495 return this.doFormUpload(o, p, url);
11497 var f = Roo.lib.Ajax.serializeForm(form);
11498 p = p ? (p + '&' + f) : f;
11501 var hs = o.headers;
11502 if(this.defaultHeaders){
11503 hs = Roo.apply(hs || {}, this.defaultHeaders);
11510 success: this.handleResponse,
11511 failure: this.handleFailure,
11513 argument: {options: o},
11514 timeout : o.timeout || this.timeout
11517 var method = o.method||this.method||(p ? "POST" : "GET");
11519 if(method == 'GET' && (this.disableCaching && o.disableCaching !== false) || o.disableCaching === true){
11520 url += (url.indexOf('?') != -1 ? '&' : '?') + '_dc=' + (new Date().getTime());
11523 if(typeof o.autoAbort == 'boolean'){ // options gets top priority
11527 }else if(this.autoAbort !== false){
11531 if((method == 'GET' && p) || o.xmlData){
11532 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
11535 this.transId = Roo.lib.Ajax.request(method, url, cb, p, o);
11536 return this.transId;
11538 Roo.callback(o.callback, o.scope, [o, null, null]);
11544 * Determine whether this object has a request outstanding.
11545 * @param {Number} transactionId (Optional) defaults to the last transaction
11546 * @return {Boolean} True if there is an outstanding request.
11548 isLoading : function(transId){
11550 return Roo.lib.Ajax.isCallInProgress(transId);
11552 return this.transId ? true : false;
11557 * Aborts any outstanding request.
11558 * @param {Number} transactionId (Optional) defaults to the last transaction
11560 abort : function(transId){
11561 if(transId || this.isLoading()){
11562 Roo.lib.Ajax.abort(transId || this.transId);
11567 handleResponse : function(response){
11568 this.transId = false;
11569 var options = response.argument.options;
11570 response.argument = options ? options.argument : null;
11571 this.fireEvent("requestcomplete", this, response, options);
11572 Roo.callback(options.success, options.scope, [response, options]);
11573 Roo.callback(options.callback, options.scope, [options, true, response]);
11577 handleFailure : function(response, e){
11578 this.transId = false;
11579 var options = response.argument.options;
11580 response.argument = options ? options.argument : null;
11581 this.fireEvent("requestexception", this, response, options, e);
11582 Roo.callback(options.failure, options.scope, [response, options]);
11583 Roo.callback(options.callback, options.scope, [options, false, response]);
11587 doFormUpload : function(o, ps, url){
11589 var frame = document.createElement('iframe');
11592 frame.className = 'x-hidden';
11594 frame.src = Roo.SSL_SECURE_URL;
11596 document.body.appendChild(frame);
11599 document.frames[id].name = id;
11602 var form = Roo.getDom(o.form);
11604 form.method = 'POST';
11605 form.enctype = form.encoding = 'multipart/form-data';
11611 if(ps){ // add dynamic params
11613 ps = Roo.urlDecode(ps, false);
11615 if(ps.hasOwnProperty(k)){
11616 hd = document.createElement('input');
11617 hd.type = 'hidden';
11620 form.appendChild(hd);
11627 var r = { // bogus response object
11632 r.argument = o ? o.argument : null;
11637 doc = frame.contentWindow.document;
11639 doc = (frame.contentDocument || window.frames[id].document);
11641 if(doc && doc.body){
11642 r.responseText = doc.body.innerHTML;
11644 if(doc && doc.XMLDocument){
11645 r.responseXML = doc.XMLDocument;
11647 r.responseXML = doc;
11654 Roo.EventManager.removeListener(frame, 'load', cb, this);
11656 this.fireEvent("requestcomplete", this, r, o);
11657 Roo.callback(o.success, o.scope, [r, o]);
11658 Roo.callback(o.callback, o.scope, [o, true, r]);
11660 setTimeout(function(){document.body.removeChild(frame);}, 100);
11663 Roo.EventManager.on(frame, 'load', cb, this);
11666 if(hiddens){ // remove dynamic params
11667 for(var i = 0, len = hiddens.length; i < len; i++){
11668 form.removeChild(hiddens[i]);
11675 * Ext JS Library 1.1.1
11676 * Copyright(c) 2006-2007, Ext JS, LLC.
11678 * Originally Released Under LGPL - original licence link has changed is not relivant.
11681 * <script type="text/javascript">
11685 * Global Ajax request class.
11688 * @extends Roo.data.Connection
11691 * @cfg {String} url The default URL to be used for requests to the server. (defaults to undefined)
11692 * @cfg {Object} extraParams An object containing properties which are used as extra parameters to each request made by this object. (defaults to undefined)
11693 * @cfg {Object} defaultHeaders An object containing request headers which are added to each request made by this object. (defaults to undefined)
11694 * @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)
11695 * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
11696 * @cfg {Boolean} autoAbort (Optional) Whether a new request should abort any pending requests. (defaults to false)
11697 * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
11699 Roo.Ajax = new Roo.data.Connection({
11708 * Serialize the passed form into a url encoded string
11710 * @param {String/HTMLElement} form
11713 serializeForm : function(form){
11714 return Roo.lib.Ajax.serializeForm(form);
11718 * Ext JS Library 1.1.1
11719 * Copyright(c) 2006-2007, Ext JS, LLC.
11721 * Originally Released Under LGPL - original licence link has changed is not relivant.
11724 * <script type="text/javascript">
11729 * @class Roo.UpdateManager
11730 * @extends Roo.util.Observable
11731 * Provides AJAX-style update for Element object.<br><br>
11734 * // Get it from a Roo.Element object
11735 * var el = Roo.get("foo");
11736 * var mgr = el.getUpdateManager();
11737 * mgr.update("http://myserver.com/index.php", "param1=1&param2=2");
11739 * mgr.formUpdate("myFormId", "http://myserver.com/index.php");
11741 * // or directly (returns the same UpdateManager instance)
11742 * var mgr = new Roo.UpdateManager("myElementId");
11743 * mgr.startAutoRefresh(60, "http://myserver.com/index.php");
11744 * mgr.on("update", myFcnNeedsToKnow);
11746 // short handed call directly from the element object
11747 Roo.get("foo").load({
11751 text: "Loading Foo..."
11755 * Create new UpdateManager directly.
11756 * @param {String/HTMLElement/Roo.Element} el The element to update
11757 * @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).
11759 Roo.UpdateManager = function(el, forceNew){
11761 if(!forceNew && el.updateManager){
11762 return el.updateManager;
11765 * The Element object
11766 * @type Roo.Element
11770 * Cached url to use for refreshes. Overwritten every time update() is called unless "discardUrl" param is set to true.
11773 this.defaultUrl = null;
11777 * @event beforeupdate
11778 * Fired before an update is made, return false from your handler and the update is cancelled.
11779 * @param {Roo.Element} el
11780 * @param {String/Object/Function} url
11781 * @param {String/Object} params
11783 "beforeupdate": true,
11786 * Fired after successful update is made.
11787 * @param {Roo.Element} el
11788 * @param {Object} oResponseObject The response Object
11793 * Fired on update failure.
11794 * @param {Roo.Element} el
11795 * @param {Object} oResponseObject The response Object
11799 var d = Roo.UpdateManager.defaults;
11801 * Blank page URL to use with SSL file uploads (Defaults to Roo.UpdateManager.defaults.sslBlankUrl or "about:blank").
11804 this.sslBlankUrl = d.sslBlankUrl;
11806 * Whether to append unique parameter on get request to disable caching (Defaults to Roo.UpdateManager.defaults.disableCaching or false).
11809 this.disableCaching = d.disableCaching;
11811 * Text for loading indicator (Defaults to Roo.UpdateManager.defaults.indicatorText or '<div class="loading-indicator">Loading...</div>').
11814 this.indicatorText = d.indicatorText;
11816 * Whether to show indicatorText when loading (Defaults to Roo.UpdateManager.defaults.showLoadIndicator or true).
11819 this.showLoadIndicator = d.showLoadIndicator;
11821 * Timeout for requests or form posts in seconds (Defaults to Roo.UpdateManager.defaults.timeout or 30 seconds).
11824 this.timeout = d.timeout;
11827 * True to process scripts in the output (Defaults to Roo.UpdateManager.defaults.loadScripts (false)).
11830 this.loadScripts = d.loadScripts;
11833 * Transaction object of current executing transaction
11835 this.transaction = null;
11840 this.autoRefreshProcId = null;
11842 * Delegate for refresh() prebound to "this", use myUpdater.refreshDelegate.createCallback(arg1, arg2) to bind arguments
11845 this.refreshDelegate = this.refresh.createDelegate(this);
11847 * Delegate for update() prebound to "this", use myUpdater.updateDelegate.createCallback(arg1, arg2) to bind arguments
11850 this.updateDelegate = this.update.createDelegate(this);
11852 * Delegate for formUpdate() prebound to "this", use myUpdater.formUpdateDelegate.createCallback(arg1, arg2) to bind arguments
11855 this.formUpdateDelegate = this.formUpdate.createDelegate(this);
11859 this.successDelegate = this.processSuccess.createDelegate(this);
11863 this.failureDelegate = this.processFailure.createDelegate(this);
11865 if(!this.renderer){
11867 * The renderer for this UpdateManager. Defaults to {@link Roo.UpdateManager.BasicRenderer}.
11869 this.renderer = new Roo.UpdateManager.BasicRenderer();
11872 Roo.UpdateManager.superclass.constructor.call(this);
11875 Roo.extend(Roo.UpdateManager, Roo.util.Observable, {
11877 * Get the Element this UpdateManager is bound to
11878 * @return {Roo.Element} The element
11880 getEl : function(){
11884 * Performs an async request, updating this element with the response. If params are specified it uses POST, otherwise it uses GET.
11885 * @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:
11888 url: "your-url.php",<br/>
11889 params: {param1: "foo", param2: "bar"}, // or a URL encoded string<br/>
11890 callback: yourFunction,<br/>
11891 scope: yourObject, //(optional scope) <br/>
11892 discardUrl: false, <br/>
11893 nocache: false,<br/>
11894 text: "Loading...",<br/>
11896 scripts: false<br/>
11899 * The only required property is url. The optional properties nocache, text and scripts
11900 * are shorthand for disableCaching, indicatorText and loadScripts and are used to set their associated property on this UpdateManager instance.
11901 * @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}
11902 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess, oResponse)
11903 * @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.
11905 update : function(url, params, callback, discardUrl){
11906 if(this.fireEvent("beforeupdate", this.el, url, params) !== false){
11907 var method = this.method,
11909 if(typeof url == "object"){ // must be config object
11912 params = params || cfg.params;
11913 callback = callback || cfg.callback;
11914 discardUrl = discardUrl || cfg.discardUrl;
11915 if(callback && cfg.scope){
11916 callback = callback.createDelegate(cfg.scope);
11918 if(typeof cfg.method != "undefined"){method = cfg.method;};
11919 if(typeof cfg.nocache != "undefined"){this.disableCaching = cfg.nocache;};
11920 if(typeof cfg.text != "undefined"){this.indicatorText = '<div class="loading-indicator">'+cfg.text+"</div>";};
11921 if(typeof cfg.scripts != "undefined"){this.loadScripts = cfg.scripts;};
11922 if(typeof cfg.timeout != "undefined"){this.timeout = cfg.timeout;};
11924 this.showLoading();
11926 this.defaultUrl = url;
11928 if(typeof url == "function"){
11929 url = url.call(this);
11932 method = method || (params ? "POST" : "GET");
11933 if(method == "GET"){
11934 url = this.prepareUrl(url);
11937 var o = Roo.apply(cfg ||{}, {
11940 success: this.successDelegate,
11941 failure: this.failureDelegate,
11942 callback: undefined,
11943 timeout: (this.timeout*1000),
11944 argument: {"url": url, "form": null, "callback": callback, "params": params}
11946 Roo.log("updated manager called with timeout of " + o.timeout);
11947 this.transaction = Roo.Ajax.request(o);
11952 * 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.
11953 * Uses this.sslBlankUrl for SSL file uploads to prevent IE security warning.
11954 * @param {String/HTMLElement} form The form Id or form element
11955 * @param {String} url (optional) The url to pass the form to. If omitted the action attribute on the form will be used.
11956 * @param {Boolean} reset (optional) Whether to try to reset the form after the update
11957 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess, oResponse)
11959 formUpdate : function(form, url, reset, callback){
11960 if(this.fireEvent("beforeupdate", this.el, form, url) !== false){
11961 if(typeof url == "function"){
11962 url = url.call(this);
11964 form = Roo.getDom(form);
11965 this.transaction = Roo.Ajax.request({
11968 success: this.successDelegate,
11969 failure: this.failureDelegate,
11970 timeout: (this.timeout*1000),
11971 argument: {"url": url, "form": form, "callback": callback, "reset": reset}
11973 this.showLoading.defer(1, this);
11978 * Refresh the element with the last used url or defaultUrl. If there is no url, it returns immediately
11979 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
11981 refresh : function(callback){
11982 if(this.defaultUrl == null){
11985 this.update(this.defaultUrl, null, callback, true);
11989 * Set this element to auto refresh.
11990 * @param {Number} interval How often to update (in seconds).
11991 * @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)
11992 * @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}
11993 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
11994 * @param {Boolean} refreshNow (optional) Whether to execute the refresh now, or wait the interval
11996 startAutoRefresh : function(interval, url, params, callback, refreshNow){
11998 this.update(url || this.defaultUrl, params, callback, true);
12000 if(this.autoRefreshProcId){
12001 clearInterval(this.autoRefreshProcId);
12003 this.autoRefreshProcId = setInterval(this.update.createDelegate(this, [url || this.defaultUrl, params, callback, true]), interval*1000);
12007 * Stop auto refresh on this element.
12009 stopAutoRefresh : function(){
12010 if(this.autoRefreshProcId){
12011 clearInterval(this.autoRefreshProcId);
12012 delete this.autoRefreshProcId;
12016 isAutoRefreshing : function(){
12017 return this.autoRefreshProcId ? true : false;
12020 * Called to update the element to "Loading" state. Override to perform custom action.
12022 showLoading : function(){
12023 if(this.showLoadIndicator){
12024 this.el.update(this.indicatorText);
12029 * Adds unique parameter to query string if disableCaching = true
12032 prepareUrl : function(url){
12033 if(this.disableCaching){
12034 var append = "_dc=" + (new Date().getTime());
12035 if(url.indexOf("?") !== -1){
12036 url += "&" + append;
12038 url += "?" + append;
12047 processSuccess : function(response){
12048 this.transaction = null;
12049 if(response.argument.form && response.argument.reset){
12050 try{ // put in try/catch since some older FF releases had problems with this
12051 response.argument.form.reset();
12054 if(this.loadScripts){
12055 this.renderer.render(this.el, response, this,
12056 this.updateComplete.createDelegate(this, [response]));
12058 this.renderer.render(this.el, response, this);
12059 this.updateComplete(response);
12063 updateComplete : function(response){
12064 this.fireEvent("update", this.el, response);
12065 if(typeof response.argument.callback == "function"){
12066 response.argument.callback(this.el, true, response);
12073 processFailure : function(response){
12074 this.transaction = null;
12075 this.fireEvent("failure", this.el, response);
12076 if(typeof response.argument.callback == "function"){
12077 response.argument.callback(this.el, false, response);
12082 * Set the content renderer for this UpdateManager. See {@link Roo.UpdateManager.BasicRenderer#render} for more details.
12083 * @param {Object} renderer The object implementing the render() method
12085 setRenderer : function(renderer){
12086 this.renderer = renderer;
12089 getRenderer : function(){
12090 return this.renderer;
12094 * Set the defaultUrl used for updates
12095 * @param {String/Function} defaultUrl The url or a function to call to get the url
12097 setDefaultUrl : function(defaultUrl){
12098 this.defaultUrl = defaultUrl;
12102 * Aborts the executing transaction
12104 abort : function(){
12105 if(this.transaction){
12106 Roo.Ajax.abort(this.transaction);
12111 * Returns true if an update is in progress
12112 * @return {Boolean}
12114 isUpdating : function(){
12115 if(this.transaction){
12116 return Roo.Ajax.isLoading(this.transaction);
12123 * @class Roo.UpdateManager.defaults
12124 * @static (not really - but it helps the doc tool)
12125 * The defaults collection enables customizing the default properties of UpdateManager
12127 Roo.UpdateManager.defaults = {
12129 * Timeout for requests or form posts in seconds (Defaults 30 seconds).
12135 * True to process scripts by default (Defaults to false).
12138 loadScripts : false,
12141 * Blank page URL to use with SSL file uploads (Defaults to "javascript:false").
12144 sslBlankUrl : (Roo.SSL_SECURE_URL || "javascript:false"),
12146 * Whether to append unique parameter on get request to disable caching (Defaults to false).
12149 disableCaching : false,
12151 * Whether to show indicatorText when loading (Defaults to true).
12154 showLoadIndicator : true,
12156 * Text for loading indicator (Defaults to '<div class="loading-indicator">Loading...</div>').
12159 indicatorText : '<div class="loading-indicator">Loading...</div>'
12163 * Static convenience method. This method is deprecated in favor of el.load({url:'foo.php', ...}).
12165 * <pre><code>Roo.UpdateManager.updateElement("my-div", "stuff.php");</code></pre>
12166 * @param {String/HTMLElement/Roo.Element} el The element to update
12167 * @param {String} url The url
12168 * @param {String/Object} params (optional) Url encoded param string or an object of name/value pairs
12169 * @param {Object} options (optional) A config object with any of the UpdateManager properties you want to set - for example: {disableCaching:true, indicatorText: "Loading data..."}
12172 * @member Roo.UpdateManager
12174 Roo.UpdateManager.updateElement = function(el, url, params, options){
12175 var um = Roo.get(el, true).getUpdateManager();
12176 Roo.apply(um, options);
12177 um.update(url, params, options ? options.callback : null);
12179 // alias for backwards compat
12180 Roo.UpdateManager.update = Roo.UpdateManager.updateElement;
12182 * @class Roo.UpdateManager.BasicRenderer
12183 * Default Content renderer. Updates the elements innerHTML with the responseText.
12185 Roo.UpdateManager.BasicRenderer = function(){};
12187 Roo.UpdateManager.BasicRenderer.prototype = {
12189 * This is called when the transaction is completed and it's time to update the element - The BasicRenderer
12190 * updates the elements innerHTML with the responseText - To perform a custom render (i.e. XML or JSON processing),
12191 * create an object with a "render(el, response)" method and pass it to setRenderer on the UpdateManager.
12192 * @param {Roo.Element} el The element being rendered
12193 * @param {Object} response The YUI Connect response object
12194 * @param {UpdateManager} updateManager The calling update manager
12195 * @param {Function} callback A callback that will need to be called if loadScripts is true on the UpdateManager
12197 render : function(el, response, updateManager, callback){
12198 el.update(response.responseText, updateManager.loadScripts, callback);
12204 * (c)) Alan Knowles
12210 * @class Roo.DomTemplate
12211 * @extends Roo.Template
12212 * An effort at a dom based template engine..
12214 * Similar to XTemplate, except it uses dom parsing to create the template..
12216 * Supported features:
12221 {a_variable} - output encoded.
12222 {a_variable.format:("Y-m-d")} - call a method on the variable
12223 {a_variable:raw} - unencoded output
12224 {a_variable:toFixed(1,2)} - Roo.util.Format."toFixed"
12225 {a_variable:this.method_on_template(...)} - call a method on the template object.
12230 <div roo-for="a_variable or condition.."></div>
12231 <div roo-if="a_variable or condition"></div>
12232 <div roo-exec="some javascript"></div>
12233 <div roo-name="named_template"></div>
12238 Roo.DomTemplate = function()
12240 Roo.DomTemplate.superclass.constructor.apply(this, arguments);
12247 Roo.extend(Roo.DomTemplate, Roo.Template, {
12249 * id counter for sub templates.
12253 * flag to indicate if dom parser is inside a pre,
12254 * it will strip whitespace if not.
12259 * The various sub templates
12267 * basic tag replacing syntax
12270 * // you can fake an object call by doing this
12274 re : /(\{|\%7B)([\w-\.]+)(?:\:([\w\.]*)(?:\(([^)]*?)?\))?)?(\}|\%7D)/g,
12275 //re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
12277 iterChild : function (node, method) {
12279 var oldPre = this.inPre;
12280 if (node.tagName == 'PRE') {
12283 for( var i = 0; i < node.childNodes.length; i++) {
12284 method.call(this, node.childNodes[i]);
12286 this.inPre = oldPre;
12292 * compile the template
12294 * This is not recursive, so I'm not sure how nested templates are really going to be handled..
12297 compile: function()
12301 // covert the html into DOM...
12305 doc = document.implementation.createHTMLDocument("");
12306 doc.documentElement.innerHTML = this.html ;
12307 div = doc.documentElement;
12309 // old IE... - nasty -- it causes all sorts of issues.. with
12310 // images getting pulled from server..
12311 div = document.createElement('div');
12312 div.innerHTML = this.html;
12314 //doc.documentElement.innerHTML = htmlBody
12320 this.iterChild(div, function(n) {_t.compileNode(n, true); });
12322 var tpls = this.tpls;
12324 // create a top level template from the snippet..
12326 //Roo.log(div.innerHTML);
12333 body : div.innerHTML,
12346 Roo.each(tpls, function(tp){
12347 this.compileTpl(tp);
12348 this.tpls[tp.id] = tp;
12351 this.master = tpls[0];
12357 compileNode : function(node, istop) {
12362 // skip anything not a tag..
12363 if (node.nodeType != 1) {
12364 if (node.nodeType == 3 && !this.inPre) {
12365 // reduce white space..
12366 node.nodeValue = node.nodeValue.replace(/\s+/g, ' ');
12389 case (node.hasAttribute('roo-for')): tpl.attr = 'for'; break;
12390 case (node.hasAttribute('roo-if')): tpl.attr = 'if'; break;
12391 case (node.hasAttribute('roo-name')): tpl.attr = 'name'; break;
12392 case (node.hasAttribute('roo-exec')): tpl.attr = 'exec'; break;
12398 // just itterate children..
12399 this.iterChild(node,this.compileNode);
12402 tpl.uid = this.id++;
12403 tpl.value = node.getAttribute('roo-' + tpl.attr);
12404 node.removeAttribute('roo-'+ tpl.attr);
12405 if (tpl.attr != 'name') {
12406 var placeholder = document.createTextNode('{domtpl' + tpl.uid + '}');
12407 node.parentNode.replaceChild(placeholder, node);
12410 var placeholder = document.createElement('span');
12411 placeholder.className = 'roo-tpl-' + tpl.value;
12412 node.parentNode.replaceChild(placeholder, node);
12415 // parent now sees '{domtplXXXX}
12416 this.iterChild(node,this.compileNode);
12418 // we should now have node body...
12419 var div = document.createElement('div');
12420 div.appendChild(node);
12422 // this has the unfortunate side effect of converting tagged attributes
12423 // eg. href="{...}" into %7C...%7D
12424 // this has been fixed by searching for those combo's although it's a bit hacky..
12427 tpl.body = div.innerHTML;
12434 switch (tpl.value) {
12435 case '.': tpl.forCall = new Function('values', 'parent', 'with(values){ return values; }'); break;
12436 case '..': tpl.forCall= new Function('values', 'parent', 'with(values){ return parent; }'); break;
12437 default: tpl.forCall= new Function('values', 'parent', 'with(values){ return '+tpl.value+'; }');
12442 tpl.execCall = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
12446 tpl.ifCall = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
12450 tpl.id = tpl.value; // replace non characters???
12456 this.tpls.push(tpl);
12466 * Compile a segment of the template into a 'sub-template'
12472 compileTpl : function(tpl)
12474 var fm = Roo.util.Format;
12475 var useF = this.disableFormats !== true;
12477 var sep = Roo.isGecko ? "+\n" : ",\n";
12479 var undef = function(str) {
12480 Roo.debug && Roo.log("Property not found :" + str);
12484 //Roo.log(tpl.body);
12488 var fn = function(m, lbrace, name, format, args)
12491 //Roo.log(arguments);
12492 args = args ? args.replace(/\\'/g,"'") : args;
12493 //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
12494 if (typeof(format) == 'undefined') {
12495 format = 'htmlEncode';
12497 if (format == 'raw' ) {
12501 if(name.substr(0, 6) == 'domtpl'){
12502 return "'"+ sep +'this.applySubTemplate('+name.substr(6)+', values, parent)'+sep+"'";
12505 // build an array of options to determine if value is undefined..
12507 // basically get 'xxxx.yyyy' then do
12508 // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
12509 // (function () { Roo.log("Property not found"); return ''; })() :
12514 Roo.each(name.split('.'), function(st) {
12515 lookfor += (lookfor.length ? '.': '') + st;
12516 udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
12519 var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
12522 if(format && useF){
12524 args = args ? ',' + args : "";
12526 if(format.substr(0, 5) != "this."){
12527 format = "fm." + format + '(';
12529 format = 'this.call("'+ format.substr(5) + '", ';
12533 return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
12536 if (args && args.length) {
12537 // called with xxyx.yuu:(test,test)
12539 return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
12541 // raw.. - :raw modifier..
12542 return "'"+ sep + udef_st + name + ")"+sep+"'";
12546 // branched to use + in gecko and [].join() in others
12548 body = "tpl.compiled = function(values, parent){ with(values) { return '" +
12549 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
12552 body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
12553 body.push(tpl.body.replace(/(\r\n|\n)/g,
12554 '\\n').replace(/'/g, "\\'").replace(this.re, fn));
12555 body.push("'].join('');};};");
12556 body = body.join('');
12559 Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
12561 /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
12568 * same as applyTemplate, except it's done to one of the subTemplates
12569 * when using named templates, you can do:
12571 * var str = pl.applySubTemplate('your-name', values);
12574 * @param {Number} id of the template
12575 * @param {Object} values to apply to template
12576 * @param {Object} parent (normaly the instance of this object)
12578 applySubTemplate : function(id, values, parent)
12582 var t = this.tpls[id];
12586 if(t.ifCall && !t.ifCall.call(this, values, parent)){
12587 Roo.debug && Roo.log('if call on ' + t.value + ' return false');
12591 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-if="' + t.value + '" - ' + e.toString());
12598 if(t.execCall && t.execCall.call(this, values, parent)){
12602 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
12608 var vs = t.forCall ? t.forCall.call(this, values, parent) : values;
12609 parent = t.target ? values : parent;
12610 if(t.forCall && vs instanceof Array){
12612 for(var i = 0, len = vs.length; i < len; i++){
12614 buf[buf.length] = t.compiled.call(this, vs[i], parent);
12616 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
12618 //Roo.log(t.compiled);
12622 return buf.join('');
12625 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
12630 return t.compiled.call(this, vs, parent);
12632 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
12634 //Roo.log(t.compiled);
12642 applyTemplate : function(values){
12643 return this.master.compiled.call(this, values, {});
12644 //var s = this.subs;
12647 apply : function(){
12648 return this.applyTemplate.apply(this, arguments);
12653 Roo.DomTemplate.from = function(el){
12654 el = Roo.getDom(el);
12655 return new Roo.Domtemplate(el.value || el.innerHTML);
12658 * Ext JS Library 1.1.1
12659 * Copyright(c) 2006-2007, Ext JS, LLC.
12661 * Originally Released Under LGPL - original licence link has changed is not relivant.
12664 * <script type="text/javascript">
12668 * @class Roo.util.DelayedTask
12669 * Provides a convenient method of performing setTimeout where a new
12670 * timeout cancels the old timeout. An example would be performing validation on a keypress.
12671 * You can use this class to buffer
12672 * the keypress events for a certain number of milliseconds, and perform only if they stop
12673 * for that amount of time.
12674 * @constructor The parameters to this constructor serve as defaults and are not required.
12675 * @param {Function} fn (optional) The default function to timeout
12676 * @param {Object} scope (optional) The default scope of that timeout
12677 * @param {Array} args (optional) The default Array of arguments
12679 Roo.util.DelayedTask = function(fn, scope, args){
12680 var id = null, d, t;
12682 var call = function(){
12683 var now = new Date().getTime();
12687 fn.apply(scope, args || []);
12691 * Cancels any pending timeout and queues a new one
12692 * @param {Number} delay The milliseconds to delay
12693 * @param {Function} newFn (optional) Overrides function passed to constructor
12694 * @param {Object} newScope (optional) Overrides scope passed to constructor
12695 * @param {Array} newArgs (optional) Overrides args passed to constructor
12697 this.delay = function(delay, newFn, newScope, newArgs){
12698 if(id && delay != d){
12702 t = new Date().getTime();
12704 scope = newScope || scope;
12705 args = newArgs || args;
12707 id = setInterval(call, d);
12712 * Cancel the last queued timeout
12714 this.cancel = function(){
12722 * Ext JS Library 1.1.1
12723 * Copyright(c) 2006-2007, Ext JS, LLC.
12725 * Originally Released Under LGPL - original licence link has changed is not relivant.
12728 * <script type="text/javascript">
12732 Roo.util.TaskRunner = function(interval){
12733 interval = interval || 10;
12734 var tasks = [], removeQueue = [];
12736 var running = false;
12738 var stopThread = function(){
12744 var startThread = function(){
12747 id = setInterval(runTasks, interval);
12751 var removeTask = function(task){
12752 removeQueue.push(task);
12758 var runTasks = function(){
12759 if(removeQueue.length > 0){
12760 for(var i = 0, len = removeQueue.length; i < len; i++){
12761 tasks.remove(removeQueue[i]);
12764 if(tasks.length < 1){
12769 var now = new Date().getTime();
12770 for(var i = 0, len = tasks.length; i < len; ++i){
12772 var itime = now - t.taskRunTime;
12773 if(t.interval <= itime){
12774 var rt = t.run.apply(t.scope || t, t.args || [++t.taskRunCount]);
12775 t.taskRunTime = now;
12776 if(rt === false || t.taskRunCount === t.repeat){
12781 if(t.duration && t.duration <= (now - t.taskStartTime)){
12788 * Queues a new task.
12789 * @param {Object} task
12791 this.start = function(task){
12793 task.taskStartTime = new Date().getTime();
12794 task.taskRunTime = 0;
12795 task.taskRunCount = 0;
12800 this.stop = function(task){
12805 this.stopAll = function(){
12807 for(var i = 0, len = tasks.length; i < len; i++){
12808 if(tasks[i].onStop){
12817 Roo.TaskMgr = new Roo.util.TaskRunner();/*
12819 * Ext JS Library 1.1.1
12820 * Copyright(c) 2006-2007, Ext JS, LLC.
12822 * Originally Released Under LGPL - original licence link has changed is not relivant.
12825 * <script type="text/javascript">
12830 * @class Roo.util.MixedCollection
12831 * @extends Roo.util.Observable
12832 * A Collection class that maintains both numeric indexes and keys and exposes events.
12834 * @param {Boolean} allowFunctions True if the addAll function should add function references to the
12835 * collection (defaults to false)
12836 * @param {Function} keyFn A function that can accept an item of the type(s) stored in this MixedCollection
12837 * and return the key value for that item. This is used when available to look up the key on items that
12838 * were passed without an explicit key parameter to a MixedCollection method. Passing this parameter is
12839 * equivalent to providing an implementation for the {@link #getKey} method.
12841 Roo.util.MixedCollection = function(allowFunctions, keyFn){
12849 * Fires when the collection is cleared.
12854 * Fires when an item is added to the collection.
12855 * @param {Number} index The index at which the item was added.
12856 * @param {Object} o The item added.
12857 * @param {String} key The key associated with the added item.
12862 * Fires when an item is replaced in the collection.
12863 * @param {String} key he key associated with the new added.
12864 * @param {Object} old The item being replaced.
12865 * @param {Object} new The new item.
12870 * Fires when an item is removed from the collection.
12871 * @param {Object} o The item being removed.
12872 * @param {String} key (optional) The key associated with the removed item.
12877 this.allowFunctions = allowFunctions === true;
12879 this.getKey = keyFn;
12881 Roo.util.MixedCollection.superclass.constructor.call(this);
12884 Roo.extend(Roo.util.MixedCollection, Roo.util.Observable, {
12885 allowFunctions : false,
12888 * Adds an item to the collection.
12889 * @param {String} key The key to associate with the item
12890 * @param {Object} o The item to add.
12891 * @return {Object} The item added.
12893 add : function(key, o){
12894 if(arguments.length == 1){
12896 key = this.getKey(o);
12898 if(typeof key == "undefined" || key === null){
12900 this.items.push(o);
12901 this.keys.push(null);
12903 var old = this.map[key];
12905 return this.replace(key, o);
12908 this.items.push(o);
12910 this.keys.push(key);
12912 this.fireEvent("add", this.length-1, o, key);
12917 * MixedCollection has a generic way to fetch keys if you implement getKey.
12920 var mc = new Roo.util.MixedCollection();
12921 mc.add(someEl.dom.id, someEl);
12922 mc.add(otherEl.dom.id, otherEl);
12926 var mc = new Roo.util.MixedCollection();
12927 mc.getKey = function(el){
12933 // or via the constructor
12934 var mc = new Roo.util.MixedCollection(false, function(el){
12940 * @param o {Object} The item for which to find the key.
12941 * @return {Object} The key for the passed item.
12943 getKey : function(o){
12948 * Replaces an item in the collection.
12949 * @param {String} key The key associated with the item to replace, or the item to replace.
12950 * @param o {Object} o (optional) If the first parameter passed was a key, the item to associate with that key.
12951 * @return {Object} The new item.
12953 replace : function(key, o){
12954 if(arguments.length == 1){
12956 key = this.getKey(o);
12958 var old = this.item(key);
12959 if(typeof key == "undefined" || key === null || typeof old == "undefined"){
12960 return this.add(key, o);
12962 var index = this.indexOfKey(key);
12963 this.items[index] = o;
12965 this.fireEvent("replace", key, old, o);
12970 * Adds all elements of an Array or an Object to the collection.
12971 * @param {Object/Array} objs An Object containing properties which will be added to the collection, or
12972 * an Array of values, each of which are added to the collection.
12974 addAll : function(objs){
12975 if(arguments.length > 1 || objs instanceof Array){
12976 var args = arguments.length > 1 ? arguments : objs;
12977 for(var i = 0, len = args.length; i < len; i++){
12981 for(var key in objs){
12982 if(this.allowFunctions || typeof objs[key] != "function"){
12983 this.add(key, objs[key]);
12990 * Executes the specified function once for every item in the collection, passing each
12991 * item as the first and only parameter. returning false from the function will stop the iteration.
12992 * @param {Function} fn The function to execute for each item.
12993 * @param {Object} scope (optional) The scope in which to execute the function.
12995 each : function(fn, scope){
12996 var items = [].concat(this.items); // each safe for removal
12997 for(var i = 0, len = items.length; i < len; i++){
12998 if(fn.call(scope || items[i], items[i], i, len) === false){
13005 * Executes the specified function once for every key in the collection, passing each
13006 * key, and its associated item as the first two parameters.
13007 * @param {Function} fn The function to execute for each item.
13008 * @param {Object} scope (optional) The scope in which to execute the function.
13010 eachKey : function(fn, scope){
13011 for(var i = 0, len = this.keys.length; i < len; i++){
13012 fn.call(scope || window, this.keys[i], this.items[i], i, len);
13017 * Returns the first item in the collection which elicits a true return value from the
13018 * passed selection function.
13019 * @param {Function} fn The selection function to execute for each item.
13020 * @param {Object} scope (optional) The scope in which to execute the function.
13021 * @return {Object} The first item in the collection which returned true from the selection function.
13023 find : function(fn, scope){
13024 for(var i = 0, len = this.items.length; i < len; i++){
13025 if(fn.call(scope || window, this.items[i], this.keys[i])){
13026 return this.items[i];
13033 * Inserts an item at the specified index in the collection.
13034 * @param {Number} index The index to insert the item at.
13035 * @param {String} key The key to associate with the new item, or the item itself.
13036 * @param {Object} o (optional) If the second parameter was a key, the new item.
13037 * @return {Object} The item inserted.
13039 insert : function(index, key, o){
13040 if(arguments.length == 2){
13042 key = this.getKey(o);
13044 if(index >= this.length){
13045 return this.add(key, o);
13048 this.items.splice(index, 0, o);
13049 if(typeof key != "undefined" && key != null){
13052 this.keys.splice(index, 0, key);
13053 this.fireEvent("add", index, o, key);
13058 * Removed an item from the collection.
13059 * @param {Object} o The item to remove.
13060 * @return {Object} The item removed.
13062 remove : function(o){
13063 return this.removeAt(this.indexOf(o));
13067 * Remove an item from a specified index in the collection.
13068 * @param {Number} index The index within the collection of the item to remove.
13070 removeAt : function(index){
13071 if(index < this.length && index >= 0){
13073 var o = this.items[index];
13074 this.items.splice(index, 1);
13075 var key = this.keys[index];
13076 if(typeof key != "undefined"){
13077 delete this.map[key];
13079 this.keys.splice(index, 1);
13080 this.fireEvent("remove", o, key);
13085 * Removed an item associated with the passed key fom the collection.
13086 * @param {String} key The key of the item to remove.
13088 removeKey : function(key){
13089 return this.removeAt(this.indexOfKey(key));
13093 * Returns the number of items in the collection.
13094 * @return {Number} the number of items in the collection.
13096 getCount : function(){
13097 return this.length;
13101 * Returns index within the collection of the passed Object.
13102 * @param {Object} o The item to find the index of.
13103 * @return {Number} index of the item.
13105 indexOf : function(o){
13106 if(!this.items.indexOf){
13107 for(var i = 0, len = this.items.length; i < len; i++){
13108 if(this.items[i] == o) return i;
13112 return this.items.indexOf(o);
13117 * Returns index within the collection of the passed key.
13118 * @param {String} key The key to find the index of.
13119 * @return {Number} index of the key.
13121 indexOfKey : function(key){
13122 if(!this.keys.indexOf){
13123 for(var i = 0, len = this.keys.length; i < len; i++){
13124 if(this.keys[i] == key) return i;
13128 return this.keys.indexOf(key);
13133 * Returns the item associated with the passed key OR index. Key has priority over index.
13134 * @param {String/Number} key The key or index of the item.
13135 * @return {Object} The item associated with the passed key.
13137 item : function(key){
13138 var item = typeof this.map[key] != "undefined" ? this.map[key] : this.items[key];
13139 return typeof item != 'function' || this.allowFunctions ? item : null; // for prototype!
13143 * Returns the item at the specified index.
13144 * @param {Number} index The index of the item.
13147 itemAt : function(index){
13148 return this.items[index];
13152 * Returns the item associated with the passed key.
13153 * @param {String/Number} key The key of the item.
13154 * @return {Object} The item associated with the passed key.
13156 key : function(key){
13157 return this.map[key];
13161 * Returns true if the collection contains the passed Object as an item.
13162 * @param {Object} o The Object to look for in the collection.
13163 * @return {Boolean} True if the collection contains the Object as an item.
13165 contains : function(o){
13166 return this.indexOf(o) != -1;
13170 * Returns true if the collection contains the passed Object as a key.
13171 * @param {String} key The key to look for in the collection.
13172 * @return {Boolean} True if the collection contains the Object as a key.
13174 containsKey : function(key){
13175 return typeof this.map[key] != "undefined";
13179 * Removes all items from the collection.
13181 clear : function(){
13186 this.fireEvent("clear");
13190 * Returns the first item in the collection.
13191 * @return {Object} the first item in the collection..
13193 first : function(){
13194 return this.items[0];
13198 * Returns the last item in the collection.
13199 * @return {Object} the last item in the collection..
13202 return this.items[this.length-1];
13205 _sort : function(property, dir, fn){
13206 var dsc = String(dir).toUpperCase() == "DESC" ? -1 : 1;
13207 fn = fn || function(a, b){
13210 var c = [], k = this.keys, items = this.items;
13211 for(var i = 0, len = items.length; i < len; i++){
13212 c[c.length] = {key: k[i], value: items[i], index: i};
13214 c.sort(function(a, b){
13215 var v = fn(a[property], b[property]) * dsc;
13217 v = (a.index < b.index ? -1 : 1);
13221 for(var i = 0, len = c.length; i < len; i++){
13222 items[i] = c[i].value;
13225 this.fireEvent("sort", this);
13229 * Sorts this collection with the passed comparison function
13230 * @param {String} direction (optional) "ASC" or "DESC"
13231 * @param {Function} fn (optional) comparison function
13233 sort : function(dir, fn){
13234 this._sort("value", dir, fn);
13238 * Sorts this collection by keys
13239 * @param {String} direction (optional) "ASC" or "DESC"
13240 * @param {Function} fn (optional) a comparison function (defaults to case insensitive string)
13242 keySort : function(dir, fn){
13243 this._sort("key", dir, fn || function(a, b){
13244 return String(a).toUpperCase()-String(b).toUpperCase();
13249 * Returns a range of items in this collection
13250 * @param {Number} startIndex (optional) defaults to 0
13251 * @param {Number} endIndex (optional) default to the last item
13252 * @return {Array} An array of items
13254 getRange : function(start, end){
13255 var items = this.items;
13256 if(items.length < 1){
13259 start = start || 0;
13260 end = Math.min(typeof end == "undefined" ? this.length-1 : end, this.length-1);
13263 for(var i = start; i <= end; i++) {
13264 r[r.length] = items[i];
13267 for(var i = start; i >= end; i--) {
13268 r[r.length] = items[i];
13275 * Filter the <i>objects</i> in this collection by a specific property.
13276 * Returns a new collection that has been filtered.
13277 * @param {String} property A property on your objects
13278 * @param {String/RegExp} value Either string that the property values
13279 * should start with or a RegExp to test against the property
13280 * @return {MixedCollection} The new filtered collection
13282 filter : function(property, value){
13283 if(!value.exec){ // not a regex
13284 value = String(value);
13285 if(value.length == 0){
13286 return this.clone();
13288 value = new RegExp("^" + Roo.escapeRe(value), "i");
13290 return this.filterBy(function(o){
13291 return o && value.test(o[property]);
13296 * Filter by a function. * Returns a new collection that has been filtered.
13297 * The passed function will be called with each
13298 * object in the collection. If the function returns true, the value is included
13299 * otherwise it is filtered.
13300 * @param {Function} fn The function to be called, it will receive the args o (the object), k (the key)
13301 * @param {Object} scope (optional) The scope of the function (defaults to this)
13302 * @return {MixedCollection} The new filtered collection
13304 filterBy : function(fn, scope){
13305 var r = new Roo.util.MixedCollection();
13306 r.getKey = this.getKey;
13307 var k = this.keys, it = this.items;
13308 for(var i = 0, len = it.length; i < len; i++){
13309 if(fn.call(scope||this, it[i], k[i])){
13310 r.add(k[i], it[i]);
13317 * Creates a duplicate of this collection
13318 * @return {MixedCollection}
13320 clone : function(){
13321 var r = new Roo.util.MixedCollection();
13322 var k = this.keys, it = this.items;
13323 for(var i = 0, len = it.length; i < len; i++){
13324 r.add(k[i], it[i]);
13326 r.getKey = this.getKey;
13331 * Returns the item associated with the passed key or index.
13333 * @param {String/Number} key The key or index of the item.
13334 * @return {Object} The item associated with the passed key.
13336 Roo.util.MixedCollection.prototype.get = Roo.util.MixedCollection.prototype.item;/*
13338 * Ext JS Library 1.1.1
13339 * Copyright(c) 2006-2007, Ext JS, LLC.
13341 * Originally Released Under LGPL - original licence link has changed is not relivant.
13344 * <script type="text/javascript">
13347 * @class Roo.util.JSON
13348 * Modified version of Douglas Crockford"s json.js that doesn"t
13349 * mess with the Object prototype
13350 * http://www.json.org/js.html
13353 Roo.util.JSON = new (function(){
13354 var useHasOwn = {}.hasOwnProperty ? true : false;
13356 // crashes Safari in some instances
13357 //var validRE = /^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/;
13359 var pad = function(n) {
13360 return n < 10 ? "0" + n : n;
13373 var encodeString = function(s){
13374 if (/["\\\x00-\x1f]/.test(s)) {
13375 return '"' + s.replace(/([\x00-\x1f\\"])/g, function(a, b) {
13380 c = b.charCodeAt();
13382 Math.floor(c / 16).toString(16) +
13383 (c % 16).toString(16);
13386 return '"' + s + '"';
13389 var encodeArray = function(o){
13390 var a = ["["], b, i, l = o.length, v;
13391 for (i = 0; i < l; i += 1) {
13393 switch (typeof v) {
13402 a.push(v === null ? "null" : Roo.util.JSON.encode(v));
13410 var encodeDate = function(o){
13411 return '"' + o.getFullYear() + "-" +
13412 pad(o.getMonth() + 1) + "-" +
13413 pad(o.getDate()) + "T" +
13414 pad(o.getHours()) + ":" +
13415 pad(o.getMinutes()) + ":" +
13416 pad(o.getSeconds()) + '"';
13420 * Encodes an Object, Array or other value
13421 * @param {Mixed} o The variable to encode
13422 * @return {String} The JSON string
13424 this.encode = function(o)
13426 // should this be extended to fully wrap stringify..
13428 if(typeof o == "undefined" || o === null){
13430 }else if(o instanceof Array){
13431 return encodeArray(o);
13432 }else if(o instanceof Date){
13433 return encodeDate(o);
13434 }else if(typeof o == "string"){
13435 return encodeString(o);
13436 }else if(typeof o == "number"){
13437 return isFinite(o) ? String(o) : "null";
13438 }else if(typeof o == "boolean"){
13441 var a = ["{"], b, i, v;
13443 if(!useHasOwn || o.hasOwnProperty(i)) {
13445 switch (typeof v) {
13454 a.push(this.encode(i), ":",
13455 v === null ? "null" : this.encode(v));
13466 * Decodes (parses) a JSON string to an object. If the JSON is invalid, this function throws a SyntaxError.
13467 * @param {String} json The JSON string
13468 * @return {Object} The resulting object
13470 this.decode = function(json){
13472 return /** eval:var:json */ eval("(" + json + ')');
13476 * Shorthand for {@link Roo.util.JSON#encode}
13477 * @member Roo encode
13479 Roo.encode = typeof(JSON) != 'undefined' && JSON.stringify ? JSON.stringify : Roo.util.JSON.encode;
13481 * Shorthand for {@link Roo.util.JSON#decode}
13482 * @member Roo decode
13484 Roo.decode = typeof(JSON) != 'undefined' && JSON.parse ? JSON.parse : Roo.util.JSON.decode;
13487 * Ext JS Library 1.1.1
13488 * Copyright(c) 2006-2007, Ext JS, LLC.
13490 * Originally Released Under LGPL - original licence link has changed is not relivant.
13493 * <script type="text/javascript">
13497 * @class Roo.util.Format
13498 * Reusable data formatting functions
13501 Roo.util.Format = function(){
13502 var trimRe = /^\s+|\s+$/g;
13505 * Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length
13506 * @param {String} value The string to truncate
13507 * @param {Number} length The maximum length to allow before truncating
13508 * @return {String} The converted text
13510 ellipsis : function(value, len){
13511 if(value && value.length > len){
13512 return value.substr(0, len-3)+"...";
13518 * Checks a reference and converts it to empty string if it is undefined
13519 * @param {Mixed} value Reference to check
13520 * @return {Mixed} Empty string if converted, otherwise the original value
13522 undef : function(value){
13523 return typeof value != "undefined" ? value : "";
13527 * Convert certain characters (&, <, >, and ') to their HTML character equivalents for literal display in web pages.
13528 * @param {String} value The string to encode
13529 * @return {String} The encoded text
13531 htmlEncode : function(value){
13532 return !value ? value : String(value).replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, """);
13536 * Convert certain characters (&, <, >, and ') from their HTML character equivalents.
13537 * @param {String} value The string to decode
13538 * @return {String} The decoded text
13540 htmlDecode : function(value){
13541 return !value ? value : String(value).replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, '"');
13545 * Trims any whitespace from either side of a string
13546 * @param {String} value The text to trim
13547 * @return {String} The trimmed text
13549 trim : function(value){
13550 return String(value).replace(trimRe, "");
13554 * Returns a substring from within an original string
13555 * @param {String} value The original text
13556 * @param {Number} start The start index of the substring
13557 * @param {Number} length The length of the substring
13558 * @return {String} The substring
13560 substr : function(value, start, length){
13561 return String(value).substr(start, length);
13565 * Converts a string to all lower case letters
13566 * @param {String} value The text to convert
13567 * @return {String} The converted text
13569 lowercase : function(value){
13570 return String(value).toLowerCase();
13574 * Converts a string to all upper case letters
13575 * @param {String} value The text to convert
13576 * @return {String} The converted text
13578 uppercase : function(value){
13579 return String(value).toUpperCase();
13583 * Converts the first character only of a string to upper case
13584 * @param {String} value The text to convert
13585 * @return {String} The converted text
13587 capitalize : function(value){
13588 return !value ? value : value.charAt(0).toUpperCase() + value.substr(1).toLowerCase();
13592 call : function(value, fn){
13593 if(arguments.length > 2){
13594 var args = Array.prototype.slice.call(arguments, 2);
13595 args.unshift(value);
13597 return /** eval:var:value */ eval(fn).apply(window, args);
13599 /** eval:var:value */
13600 return /** eval:var:value */ eval(fn).call(window, value);
13606 * safer version of Math.toFixed..??/
13607 * @param {Number/String} value The numeric value to format
13608 * @param {Number/String} value Decimal places
13609 * @return {String} The formatted currency string
13611 toFixed : function(v, n)
13613 // why not use to fixed - precision is buggered???
13615 return Math.round(v-0);
13617 var fact = Math.pow(10,n+1);
13618 v = (Math.round((v-0)*fact))/fact;
13619 var z = (''+fact).substring(2);
13620 if (v == Math.floor(v)) {
13621 return Math.floor(v) + '.' + z;
13624 // now just padd decimals..
13625 var ps = String(v).split('.');
13626 var fd = (ps[1] + z);
13627 var r = fd.substring(0,n);
13628 var rm = fd.substring(n);
13630 return ps[0] + '.' + r;
13632 r*=1; // turn it into a number;
13634 if (String(r).length != n) {
13637 r = String(r).substring(1); // chop the end off.
13640 return ps[0] + '.' + r;
13645 * Format a number as US currency
13646 * @param {Number/String} value The numeric value to format
13647 * @return {String} The formatted currency string
13649 usMoney : function(v){
13650 return '$' + Roo.util.Format.number(v);
13655 * eventually this should probably emulate php's number_format
13656 * @param {Number/String} value The numeric value to format
13657 * @param {Number} decimals number of decimal places
13658 * @return {String} The formatted currency string
13660 number : function(v,decimals)
13662 // multiply and round.
13663 decimals = typeof(decimals) == 'undefined' ? 2 : decimals;
13664 var mul = Math.pow(10, decimals);
13665 var zero = String(mul).substring(1);
13666 v = (Math.round((v-0)*mul))/mul;
13668 // if it's '0' number.. then
13670 //v = (v == Math.floor(v)) ? v + "." + zero : ((v*10 == Math.floor(v*10)) ? v + "0" : v);
13672 var ps = v.split('.');
13676 var r = /(\d+)(\d{3})/;
13678 while (r.test(whole)) {
13679 whole = whole.replace(r, '$1' + ',' + '$2');
13685 (decimals ? ('.'+ ps[1] + zero.substring(ps[1].length)) : '') :
13686 // does not have decimals
13687 (decimals ? ('.' + zero) : '');
13690 return whole + sub ;
13694 * Parse a value into a formatted date using the specified format pattern.
13695 * @param {Mixed} value The value to format
13696 * @param {String} format (optional) Any valid date format string (defaults to 'm/d/Y')
13697 * @return {String} The formatted date string
13699 date : function(v, format){
13703 if(!(v instanceof Date)){
13704 v = new Date(Date.parse(v));
13706 return v.dateFormat(format || Roo.util.Format.defaults.date);
13710 * Returns a date rendering function that can be reused to apply a date format multiple times efficiently
13711 * @param {String} format Any valid date format string
13712 * @return {Function} The date formatting function
13714 dateRenderer : function(format){
13715 return function(v){
13716 return Roo.util.Format.date(v, format);
13721 stripTagsRE : /<\/?[^>]+>/gi,
13724 * Strips all HTML tags
13725 * @param {Mixed} value The text from which to strip tags
13726 * @return {String} The stripped text
13728 stripTags : function(v){
13729 return !v ? v : String(v).replace(this.stripTagsRE, "");
13733 Roo.util.Format.defaults = {
13737 * Ext JS Library 1.1.1
13738 * Copyright(c) 2006-2007, Ext JS, LLC.
13740 * Originally Released Under LGPL - original licence link has changed is not relivant.
13743 * <script type="text/javascript">
13750 * @class Roo.MasterTemplate
13751 * @extends Roo.Template
13752 * Provides a template that can have child templates. The syntax is:
13754 var t = new Roo.MasterTemplate(
13755 '<select name="{name}">',
13756 '<tpl name="options"><option value="{value:trim}">{text:ellipsis(10)}</option></tpl>',
13759 t.add('options', {value: 'foo', text: 'bar'});
13760 // or you can add multiple child elements in one shot
13761 t.addAll('options', [
13762 {value: 'foo', text: 'bar'},
13763 {value: 'foo2', text: 'bar2'},
13764 {value: 'foo3', text: 'bar3'}
13766 // then append, applying the master template values
13767 t.append('my-form', {name: 'my-select'});
13769 * A name attribute for the child template is not required if you have only one child
13770 * template or you want to refer to them by index.
13772 Roo.MasterTemplate = function(){
13773 Roo.MasterTemplate.superclass.constructor.apply(this, arguments);
13774 this.originalHtml = this.html;
13776 var m, re = this.subTemplateRe;
13779 while(m = re.exec(this.html)){
13780 var name = m[1], content = m[2];
13785 tpl : new Roo.Template(content)
13788 st[name] = st[subIndex];
13790 st[subIndex].tpl.compile();
13791 st[subIndex].tpl.call = this.call.createDelegate(this);
13794 this.subCount = subIndex;
13797 Roo.extend(Roo.MasterTemplate, Roo.Template, {
13799 * The regular expression used to match sub templates
13803 subTemplateRe : /<tpl(?:\sname="([\w-]+)")?>((?:.|\n)*?)<\/tpl>/gi,
13806 * Applies the passed values to a child template.
13807 * @param {String/Number} name (optional) The name or index of the child template
13808 * @param {Array/Object} values The values to be applied to the template
13809 * @return {MasterTemplate} this
13811 add : function(name, values){
13812 if(arguments.length == 1){
13813 values = arguments[0];
13816 var s = this.subs[name];
13817 s.buffer[s.buffer.length] = s.tpl.apply(values);
13822 * Applies all the passed values to a child template.
13823 * @param {String/Number} name (optional) The name or index of the child template
13824 * @param {Array} values The values to be applied to the template, this should be an array of objects.
13825 * @param {Boolean} reset (optional) True to reset the template first
13826 * @return {MasterTemplate} this
13828 fill : function(name, values, reset){
13830 if(a.length == 1 || (a.length == 2 && typeof a[1] == "boolean")){
13838 for(var i = 0, len = values.length; i < len; i++){
13839 this.add(name, values[i]);
13845 * Resets the template for reuse
13846 * @return {MasterTemplate} this
13848 reset : function(){
13850 for(var i = 0; i < this.subCount; i++){
13856 applyTemplate : function(values){
13858 var replaceIndex = -1;
13859 this.html = this.originalHtml.replace(this.subTemplateRe, function(m, name){
13860 return s[++replaceIndex].buffer.join("");
13862 return Roo.MasterTemplate.superclass.applyTemplate.call(this, values);
13865 apply : function(){
13866 return this.applyTemplate.apply(this, arguments);
13869 compile : function(){return this;}
13873 * Alias for fill().
13876 Roo.MasterTemplate.prototype.addAll = Roo.MasterTemplate.prototype.fill;
13878 * Creates a template from the passed element's value (display:none textarea, preferred) or innerHTML. e.g.
13879 * var tpl = Roo.MasterTemplate.from('element-id');
13880 * @param {String/HTMLElement} el
13881 * @param {Object} config
13884 Roo.MasterTemplate.from = function(el, config){
13885 el = Roo.getDom(el);
13886 return new Roo.MasterTemplate(el.value || el.innerHTML, config || '');
13889 * Ext JS Library 1.1.1
13890 * Copyright(c) 2006-2007, Ext JS, LLC.
13892 * Originally Released Under LGPL - original licence link has changed is not relivant.
13895 * <script type="text/javascript">
13900 * @class Roo.util.CSS
13901 * Utility class for manipulating CSS rules
13904 Roo.util.CSS = function(){
13906 var doc = document;
13908 var camelRe = /(-[a-z])/gi;
13909 var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); };
13913 * Very simple dynamic creation of stylesheets from a text blob of rules. The text will wrapped in a style
13914 * tag and appended to the HEAD of the document.
13915 * @param {String|Object} cssText The text containing the css rules
13916 * @param {String} id An id to add to the stylesheet for later removal
13917 * @return {StyleSheet}
13919 createStyleSheet : function(cssText, id){
13921 var head = doc.getElementsByTagName("head")[0];
13922 var nrules = doc.createElement("style");
13923 nrules.setAttribute("type", "text/css");
13925 nrules.setAttribute("id", id);
13927 if (typeof(cssText) != 'string') {
13928 // support object maps..
13929 // not sure if this a good idea..
13930 // perhaps it should be merged with the general css handling
13931 // and handle js style props.
13932 var cssTextNew = [];
13933 for(var n in cssText) {
13935 for(var k in cssText[n]) {
13936 citems.push( k + ' : ' +cssText[n][k] + ';' );
13938 cssTextNew.push( n + ' { ' + citems.join(' ') + '} ');
13941 cssText = cssTextNew.join("\n");
13947 head.appendChild(nrules);
13948 ss = nrules.styleSheet;
13949 ss.cssText = cssText;
13952 nrules.appendChild(doc.createTextNode(cssText));
13954 nrules.cssText = cssText;
13956 head.appendChild(nrules);
13957 ss = nrules.styleSheet ? nrules.styleSheet : (nrules.sheet || doc.styleSheets[doc.styleSheets.length-1]);
13959 this.cacheStyleSheet(ss);
13964 * Removes a style or link tag by id
13965 * @param {String} id The id of the tag
13967 removeStyleSheet : function(id){
13968 var existing = doc.getElementById(id);
13970 existing.parentNode.removeChild(existing);
13975 * Dynamically swaps an existing stylesheet reference for a new one
13976 * @param {String} id The id of an existing link tag to remove
13977 * @param {String} url The href of the new stylesheet to include
13979 swapStyleSheet : function(id, url){
13980 this.removeStyleSheet(id);
13981 var ss = doc.createElement("link");
13982 ss.setAttribute("rel", "stylesheet");
13983 ss.setAttribute("type", "text/css");
13984 ss.setAttribute("id", id);
13985 ss.setAttribute("href", url);
13986 doc.getElementsByTagName("head")[0].appendChild(ss);
13990 * Refresh the rule cache if you have dynamically added stylesheets
13991 * @return {Object} An object (hash) of rules indexed by selector
13993 refreshCache : function(){
13994 return this.getRules(true);
13998 cacheStyleSheet : function(stylesheet){
14002 try{// try catch for cross domain access issue
14003 var ssRules = stylesheet.cssRules || stylesheet.rules;
14004 for(var j = ssRules.length-1; j >= 0; --j){
14005 rules[ssRules[j].selectorText] = ssRules[j];
14011 * Gets all css rules for the document
14012 * @param {Boolean} refreshCache true to refresh the internal cache
14013 * @return {Object} An object (hash) of rules indexed by selector
14015 getRules : function(refreshCache){
14016 if(rules == null || refreshCache){
14018 var ds = doc.styleSheets;
14019 for(var i =0, len = ds.length; i < len; i++){
14021 this.cacheStyleSheet(ds[i]);
14029 * Gets an an individual CSS rule by selector(s)
14030 * @param {String/Array} selector The CSS selector or an array of selectors to try. The first selector that is found is returned.
14031 * @param {Boolean} refreshCache true to refresh the internal cache if you have recently updated any rules or added styles dynamically
14032 * @return {CSSRule} The CSS rule or null if one is not found
14034 getRule : function(selector, refreshCache){
14035 var rs = this.getRules(refreshCache);
14036 if(!(selector instanceof Array)){
14037 return rs[selector];
14039 for(var i = 0; i < selector.length; i++){
14040 if(rs[selector[i]]){
14041 return rs[selector[i]];
14049 * Updates a rule property
14050 * @param {String/Array} selector If it's an array it tries each selector until it finds one. Stops immediately once one is found.
14051 * @param {String} property The css property
14052 * @param {String} value The new value for the property
14053 * @return {Boolean} true If a rule was found and updated
14055 updateRule : function(selector, property, value){
14056 if(!(selector instanceof Array)){
14057 var rule = this.getRule(selector);
14059 rule.style[property.replace(camelRe, camelFn)] = value;
14063 for(var i = 0; i < selector.length; i++){
14064 if(this.updateRule(selector[i], property, value)){
14074 * Ext JS Library 1.1.1
14075 * Copyright(c) 2006-2007, Ext JS, LLC.
14077 * Originally Released Under LGPL - original licence link has changed is not relivant.
14080 * <script type="text/javascript">
14086 * @class Roo.util.ClickRepeater
14087 * @extends Roo.util.Observable
14089 * A wrapper class which can be applied to any element. Fires a "click" event while the
14090 * mouse is pressed. The interval between firings may be specified in the config but
14091 * defaults to 10 milliseconds.
14093 * Optionally, a CSS class may be applied to the element during the time it is pressed.
14095 * @cfg {String/HTMLElement/Element} el The element to act as a button.
14096 * @cfg {Number} delay The initial delay before the repeating event begins firing.
14097 * Similar to an autorepeat key delay.
14098 * @cfg {Number} interval The interval between firings of the "click" event. Default 10 ms.
14099 * @cfg {String} pressClass A CSS class name to be applied to the element while pressed.
14100 * @cfg {Boolean} accelerate True if autorepeating should start slowly and accelerate.
14101 * "interval" and "delay" are ignored. "immediate" is honored.
14102 * @cfg {Boolean} preventDefault True to prevent the default click event
14103 * @cfg {Boolean} stopDefault True to stop the default click event
14106 * 2007-02-02 jvs Original code contributed by Nige "Animal" White
14107 * 2007-02-02 jvs Renamed to ClickRepeater
14108 * 2007-02-03 jvs Modifications for FF Mac and Safari
14111 * @param {String/HTMLElement/Element} el The element to listen on
14112 * @param {Object} config
14114 Roo.util.ClickRepeater = function(el, config)
14116 this.el = Roo.get(el);
14117 this.el.unselectable();
14119 Roo.apply(this, config);
14124 * Fires when the mouse button is depressed.
14125 * @param {Roo.util.ClickRepeater} this
14127 "mousedown" : true,
14130 * Fires on a specified interval during the time the element is pressed.
14131 * @param {Roo.util.ClickRepeater} this
14136 * Fires when the mouse key is released.
14137 * @param {Roo.util.ClickRepeater} this
14142 this.el.on("mousedown", this.handleMouseDown, this);
14143 if(this.preventDefault || this.stopDefault){
14144 this.el.on("click", function(e){
14145 if(this.preventDefault){
14146 e.preventDefault();
14148 if(this.stopDefault){
14154 // allow inline handler
14156 this.on("click", this.handler, this.scope || this);
14159 Roo.util.ClickRepeater.superclass.constructor.call(this);
14162 Roo.extend(Roo.util.ClickRepeater, Roo.util.Observable, {
14165 preventDefault : true,
14166 stopDefault : false,
14170 handleMouseDown : function(){
14171 clearTimeout(this.timer);
14173 if(this.pressClass){
14174 this.el.addClass(this.pressClass);
14176 this.mousedownTime = new Date();
14178 Roo.get(document).on("mouseup", this.handleMouseUp, this);
14179 this.el.on("mouseout", this.handleMouseOut, this);
14181 this.fireEvent("mousedown", this);
14182 this.fireEvent("click", this);
14184 this.timer = this.click.defer(this.delay || this.interval, this);
14188 click : function(){
14189 this.fireEvent("click", this);
14190 this.timer = this.click.defer(this.getInterval(), this);
14194 getInterval: function(){
14195 if(!this.accelerate){
14196 return this.interval;
14198 var pressTime = this.mousedownTime.getElapsed();
14199 if(pressTime < 500){
14201 }else if(pressTime < 1700){
14203 }else if(pressTime < 2600){
14205 }else if(pressTime < 3500){
14207 }else if(pressTime < 4400){
14209 }else if(pressTime < 5300){
14211 }else if(pressTime < 6200){
14219 handleMouseOut : function(){
14220 clearTimeout(this.timer);
14221 if(this.pressClass){
14222 this.el.removeClass(this.pressClass);
14224 this.el.on("mouseover", this.handleMouseReturn, this);
14228 handleMouseReturn : function(){
14229 this.el.un("mouseover", this.handleMouseReturn);
14230 if(this.pressClass){
14231 this.el.addClass(this.pressClass);
14237 handleMouseUp : function(){
14238 clearTimeout(this.timer);
14239 this.el.un("mouseover", this.handleMouseReturn);
14240 this.el.un("mouseout", this.handleMouseOut);
14241 Roo.get(document).un("mouseup", this.handleMouseUp);
14242 this.el.removeClass(this.pressClass);
14243 this.fireEvent("mouseup", this);
14247 * Ext JS Library 1.1.1
14248 * Copyright(c) 2006-2007, Ext JS, LLC.
14250 * Originally Released Under LGPL - original licence link has changed is not relivant.
14253 * <script type="text/javascript">
14258 * @class Roo.KeyNav
14259 * <p>Provides a convenient wrapper for normalized keyboard navigation. KeyNav allows you to bind
14260 * navigation keys to function calls that will get called when the keys are pressed, providing an easy
14261 * way to implement custom navigation schemes for any UI component.</p>
14262 * <p>The following are all of the possible keys that can be implemented: enter, left, right, up, down, tab, esc,
14263 * pageUp, pageDown, del, home, end. Usage:</p>
14265 var nav = new Roo.KeyNav("my-element", {
14266 "left" : function(e){
14267 this.moveLeft(e.ctrlKey);
14269 "right" : function(e){
14270 this.moveRight(e.ctrlKey);
14272 "enter" : function(e){
14279 * @param {String/HTMLElement/Roo.Element} el The element to bind to
14280 * @param {Object} config The config
14282 Roo.KeyNav = function(el, config){
14283 this.el = Roo.get(el);
14284 Roo.apply(this, config);
14285 if(!this.disabled){
14286 this.disabled = true;
14291 Roo.KeyNav.prototype = {
14293 * @cfg {Boolean} disabled
14294 * True to disable this KeyNav instance (defaults to false)
14298 * @cfg {String} defaultEventAction
14299 * The method to call on the {@link Roo.EventObject} after this KeyNav intercepts a key. Valid values are
14300 * {@link Roo.EventObject#stopEvent}, {@link Roo.EventObject#preventDefault} and
14301 * {@link Roo.EventObject#stopPropagation} (defaults to 'stopEvent')
14303 defaultEventAction: "stopEvent",
14305 * @cfg {Boolean} forceKeyDown
14306 * Handle the keydown event instead of keypress (defaults to false). KeyNav automatically does this for IE since
14307 * IE does not propagate special keys on keypress, but setting this to true will force other browsers to also
14308 * handle keydown instead of keypress.
14310 forceKeyDown : false,
14313 prepareEvent : function(e){
14314 var k = e.getKey();
14315 var h = this.keyToHandler[k];
14316 //if(h && this[h]){
14317 // e.stopPropagation();
14319 if(Roo.isSafari && h && k >= 37 && k <= 40){
14325 relay : function(e){
14326 var k = e.getKey();
14327 var h = this.keyToHandler[k];
14329 if(this.doRelay(e, this[h], h) !== true){
14330 e[this.defaultEventAction]();
14336 doRelay : function(e, h, hname){
14337 return h.call(this.scope || this, e);
14340 // possible handlers
14354 // quick lookup hash
14371 * Enable this KeyNav
14373 enable: function(){
14375 // ie won't do special keys on keypress, no one else will repeat keys with keydown
14376 // the EventObject will normalize Safari automatically
14377 if(this.forceKeyDown || Roo.isIE || Roo.isAir){
14378 this.el.on("keydown", this.relay, this);
14380 this.el.on("keydown", this.prepareEvent, this);
14381 this.el.on("keypress", this.relay, this);
14383 this.disabled = false;
14388 * Disable this KeyNav
14390 disable: function(){
14391 if(!this.disabled){
14392 if(this.forceKeyDown || Roo.isIE || Roo.isAir){
14393 this.el.un("keydown", this.relay);
14395 this.el.un("keydown", this.prepareEvent);
14396 this.el.un("keypress", this.relay);
14398 this.disabled = true;
14403 * Ext JS Library 1.1.1
14404 * Copyright(c) 2006-2007, Ext JS, LLC.
14406 * Originally Released Under LGPL - original licence link has changed is not relivant.
14409 * <script type="text/javascript">
14414 * @class Roo.KeyMap
14415 * Handles mapping keys to actions for an element. One key map can be used for multiple actions.
14416 * The constructor accepts the same config object as defined by {@link #addBinding}.
14417 * If you bind a callback function to a KeyMap, anytime the KeyMap handles an expected key
14418 * combination it will call the function with this signature (if the match is a multi-key
14419 * combination the callback will still be called only once): (String key, Roo.EventObject e)
14420 * A KeyMap can also handle a string representation of keys.<br />
14423 // map one key by key code
14424 var map = new Roo.KeyMap("my-element", {
14425 key: 13, // or Roo.EventObject.ENTER
14430 // map multiple keys to one action by string
14431 var map = new Roo.KeyMap("my-element", {
14437 // map multiple keys to multiple actions by strings and array of codes
14438 var map = new Roo.KeyMap("my-element", [
14441 fn: function(){ alert("Return was pressed"); }
14444 fn: function(){ alert('a, b or c was pressed'); }
14449 fn: function(){ alert('Control + shift + tab was pressed.'); }
14453 * <b>Note: A KeyMap starts enabled</b>
14455 * @param {String/HTMLElement/Roo.Element} el The element to bind to
14456 * @param {Object} config The config (see {@link #addBinding})
14457 * @param {String} eventName (optional) The event to bind to (defaults to "keydown")
14459 Roo.KeyMap = function(el, config, eventName){
14460 this.el = Roo.get(el);
14461 this.eventName = eventName || "keydown";
14462 this.bindings = [];
14464 this.addBinding(config);
14469 Roo.KeyMap.prototype = {
14471 * True to stop the event from bubbling and prevent the default browser action if the
14472 * key was handled by the KeyMap (defaults to false)
14478 * Add a new binding to this KeyMap. The following config object properties are supported:
14480 Property Type Description
14481 ---------- --------------- ----------------------------------------------------------------------
14482 key String/Array A single keycode or an array of keycodes to handle
14483 shift Boolean True to handle key only when shift is pressed (defaults to false)
14484 ctrl Boolean True to handle key only when ctrl is pressed (defaults to false)
14485 alt Boolean True to handle key only when alt is pressed (defaults to false)
14486 fn Function The function to call when KeyMap finds the expected key combination
14487 scope Object The scope of the callback function
14493 var map = new Roo.KeyMap(document, {
14494 key: Roo.EventObject.ENTER,
14499 //Add a new binding to the existing KeyMap later
14507 * @param {Object/Array} config A single KeyMap config or an array of configs
14509 addBinding : function(config){
14510 if(config instanceof Array){
14511 for(var i = 0, len = config.length; i < len; i++){
14512 this.addBinding(config[i]);
14516 var keyCode = config.key,
14517 shift = config.shift,
14518 ctrl = config.ctrl,
14521 scope = config.scope;
14522 if(typeof keyCode == "string"){
14524 var keyString = keyCode.toUpperCase();
14525 for(var j = 0, len = keyString.length; j < len; j++){
14526 ks.push(keyString.charCodeAt(j));
14530 var keyArray = keyCode instanceof Array;
14531 var handler = function(e){
14532 if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) && (!alt || e.altKey)){
14533 var k = e.getKey();
14535 for(var i = 0, len = keyCode.length; i < len; i++){
14536 if(keyCode[i] == k){
14537 if(this.stopEvent){
14540 fn.call(scope || window, k, e);
14546 if(this.stopEvent){
14549 fn.call(scope || window, k, e);
14554 this.bindings.push(handler);
14558 * Shorthand for adding a single key listener
14559 * @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the
14560 * following options:
14561 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
14562 * @param {Function} fn The function to call
14563 * @param {Object} scope (optional) The scope of the function
14565 on : function(key, fn, scope){
14566 var keyCode, shift, ctrl, alt;
14567 if(typeof key == "object" && !(key instanceof Array)){
14586 handleKeyDown : function(e){
14587 if(this.enabled){ //just in case
14588 var b = this.bindings;
14589 for(var i = 0, len = b.length; i < len; i++){
14590 b[i].call(this, e);
14596 * Returns true if this KeyMap is enabled
14597 * @return {Boolean}
14599 isEnabled : function(){
14600 return this.enabled;
14604 * Enables this KeyMap
14606 enable: function(){
14608 this.el.on(this.eventName, this.handleKeyDown, this);
14609 this.enabled = true;
14614 * Disable this KeyMap
14616 disable: function(){
14618 this.el.removeListener(this.eventName, this.handleKeyDown, this);
14619 this.enabled = false;
14624 * Ext JS Library 1.1.1
14625 * Copyright(c) 2006-2007, Ext JS, LLC.
14627 * Originally Released Under LGPL - original licence link has changed is not relivant.
14630 * <script type="text/javascript">
14635 * @class Roo.util.TextMetrics
14636 * Provides precise pixel measurements for blocks of text so that you can determine exactly how high and
14637 * wide, in pixels, a given block of text will be.
14640 Roo.util.TextMetrics = function(){
14644 * Measures the size of the specified text
14645 * @param {String/HTMLElement} el The element, dom node or id from which to copy existing CSS styles
14646 * that can affect the size of the rendered text
14647 * @param {String} text The text to measure
14648 * @param {Number} fixedWidth (optional) If the text will be multiline, you have to set a fixed width
14649 * in order to accurately measure the text height
14650 * @return {Object} An object containing the text's size {width: (width), height: (height)}
14652 measure : function(el, text, fixedWidth){
14654 shared = Roo.util.TextMetrics.Instance(el, fixedWidth);
14657 shared.setFixedWidth(fixedWidth || 'auto');
14658 return shared.getSize(text);
14662 * Return a unique TextMetrics instance that can be bound directly to an element and reused. This reduces
14663 * the overhead of multiple calls to initialize the style properties on each measurement.
14664 * @param {String/HTMLElement} el The element, dom node or id that the instance will be bound to
14665 * @param {Number} fixedWidth (optional) If the text will be multiline, you have to set a fixed width
14666 * in order to accurately measure the text height
14667 * @return {Roo.util.TextMetrics.Instance} instance The new instance
14669 createInstance : function(el, fixedWidth){
14670 return Roo.util.TextMetrics.Instance(el, fixedWidth);
14677 Roo.util.TextMetrics.Instance = function(bindTo, fixedWidth){
14678 var ml = new Roo.Element(document.createElement('div'));
14679 document.body.appendChild(ml.dom);
14680 ml.position('absolute');
14681 ml.setLeftTop(-1000, -1000);
14685 ml.setWidth(fixedWidth);
14690 * Returns the size of the specified text based on the internal element's style and width properties
14691 * @memberOf Roo.util.TextMetrics.Instance#
14692 * @param {String} text The text to measure
14693 * @return {Object} An object containing the text's size {width: (width), height: (height)}
14695 getSize : function(text){
14697 var s = ml.getSize();
14703 * Binds this TextMetrics instance to an element from which to copy existing CSS styles
14704 * that can affect the size of the rendered text
14705 * @memberOf Roo.util.TextMetrics.Instance#
14706 * @param {String/HTMLElement} el The element, dom node or id
14708 bind : function(el){
14710 Roo.fly(el).getStyles('font-size','font-style', 'font-weight', 'font-family','line-height')
14715 * Sets a fixed width on the internal measurement element. If the text will be multiline, you have
14716 * to set a fixed width in order to accurately measure the text height.
14717 * @memberOf Roo.util.TextMetrics.Instance#
14718 * @param {Number} width The width to set on the element
14720 setFixedWidth : function(width){
14721 ml.setWidth(width);
14725 * Returns the measured width of the specified text
14726 * @memberOf Roo.util.TextMetrics.Instance#
14727 * @param {String} text The text to measure
14728 * @return {Number} width The width in pixels
14730 getWidth : function(text){
14731 ml.dom.style.width = 'auto';
14732 return this.getSize(text).width;
14736 * Returns the measured height of the specified text. For multiline text, be sure to call
14737 * {@link #setFixedWidth} if necessary.
14738 * @memberOf Roo.util.TextMetrics.Instance#
14739 * @param {String} text The text to measure
14740 * @return {Number} height The height in pixels
14742 getHeight : function(text){
14743 return this.getSize(text).height;
14747 instance.bind(bindTo);
14752 // backwards compat
14753 Roo.Element.measureText = Roo.util.TextMetrics.measure;/*
14755 * Ext JS Library 1.1.1
14756 * Copyright(c) 2006-2007, Ext JS, LLC.
14758 * Originally Released Under LGPL - original licence link has changed is not relivant.
14761 * <script type="text/javascript">
14765 * @class Roo.state.Provider
14766 * Abstract base class for state provider implementations. This class provides methods
14767 * for encoding and decoding <b>typed</b> variables including dates and defines the
14768 * Provider interface.
14770 Roo.state.Provider = function(){
14772 * @event statechange
14773 * Fires when a state change occurs.
14774 * @param {Provider} this This state provider
14775 * @param {String} key The state key which was changed
14776 * @param {String} value The encoded value for the state
14779 "statechange": true
14782 Roo.state.Provider.superclass.constructor.call(this);
14784 Roo.extend(Roo.state.Provider, Roo.util.Observable, {
14786 * Returns the current value for a key
14787 * @param {String} name The key name
14788 * @param {Mixed} defaultValue A default value to return if the key's value is not found
14789 * @return {Mixed} The state data
14791 get : function(name, defaultValue){
14792 return typeof this.state[name] == "undefined" ?
14793 defaultValue : this.state[name];
14797 * Clears a value from the state
14798 * @param {String} name The key name
14800 clear : function(name){
14801 delete this.state[name];
14802 this.fireEvent("statechange", this, name, null);
14806 * Sets the value for a key
14807 * @param {String} name The key name
14808 * @param {Mixed} value The value to set
14810 set : function(name, value){
14811 this.state[name] = value;
14812 this.fireEvent("statechange", this, name, value);
14816 * Decodes a string previously encoded with {@link #encodeValue}.
14817 * @param {String} value The value to decode
14818 * @return {Mixed} The decoded value
14820 decodeValue : function(cookie){
14821 var re = /^(a|n|d|b|s|o)\:(.*)$/;
14822 var matches = re.exec(unescape(cookie));
14823 if(!matches || !matches[1]) return; // non state cookie
14824 var type = matches[1];
14825 var v = matches[2];
14828 return parseFloat(v);
14830 return new Date(Date.parse(v));
14835 var values = v.split("^");
14836 for(var i = 0, len = values.length; i < len; i++){
14837 all.push(this.decodeValue(values[i]));
14842 var values = v.split("^");
14843 for(var i = 0, len = values.length; i < len; i++){
14844 var kv = values[i].split("=");
14845 all[kv[0]] = this.decodeValue(kv[1]);
14854 * Encodes a value including type information. Decode with {@link #decodeValue}.
14855 * @param {Mixed} value The value to encode
14856 * @return {String} The encoded value
14858 encodeValue : function(v){
14860 if(typeof v == "number"){
14862 }else if(typeof v == "boolean"){
14863 enc = "b:" + (v ? "1" : "0");
14864 }else if(v instanceof Date){
14865 enc = "d:" + v.toGMTString();
14866 }else if(v instanceof Array){
14868 for(var i = 0, len = v.length; i < len; i++){
14869 flat += this.encodeValue(v[i]);
14870 if(i != len-1) flat += "^";
14873 }else if(typeof v == "object"){
14876 if(typeof v[key] != "function"){
14877 flat += key + "=" + this.encodeValue(v[key]) + "^";
14880 enc = "o:" + flat.substring(0, flat.length-1);
14884 return escape(enc);
14890 * Ext JS Library 1.1.1
14891 * Copyright(c) 2006-2007, Ext JS, LLC.
14893 * Originally Released Under LGPL - original licence link has changed is not relivant.
14896 * <script type="text/javascript">
14899 * @class Roo.state.Manager
14900 * This is the global state manager. By default all components that are "state aware" check this class
14901 * for state information if you don't pass them a custom state provider. In order for this class
14902 * to be useful, it must be initialized with a provider when your application initializes.
14904 // in your initialization function
14906 Roo.state.Manager.setProvider(new Roo.state.CookieProvider());
14908 // supposed you have a {@link Roo.BorderLayout}
14909 var layout = new Roo.BorderLayout(...);
14910 layout.restoreState();
14911 // or a {Roo.BasicDialog}
14912 var dialog = new Roo.BasicDialog(...);
14913 dialog.restoreState();
14917 Roo.state.Manager = function(){
14918 var provider = new Roo.state.Provider();
14922 * Configures the default state provider for your application
14923 * @param {Provider} stateProvider The state provider to set
14925 setProvider : function(stateProvider){
14926 provider = stateProvider;
14930 * Returns the current value for a key
14931 * @param {String} name The key name
14932 * @param {Mixed} defaultValue The default value to return if the key lookup does not match
14933 * @return {Mixed} The state data
14935 get : function(key, defaultValue){
14936 return provider.get(key, defaultValue);
14940 * Sets the value for a key
14941 * @param {String} name The key name
14942 * @param {Mixed} value The state data
14944 set : function(key, value){
14945 provider.set(key, value);
14949 * Clears a value from the state
14950 * @param {String} name The key name
14952 clear : function(key){
14953 provider.clear(key);
14957 * Gets the currently configured state provider
14958 * @return {Provider} The state provider
14960 getProvider : function(){
14967 * Ext JS Library 1.1.1
14968 * Copyright(c) 2006-2007, Ext JS, LLC.
14970 * Originally Released Under LGPL - original licence link has changed is not relivant.
14973 * <script type="text/javascript">
14976 * @class Roo.state.CookieProvider
14977 * @extends Roo.state.Provider
14978 * The default Provider implementation which saves state via cookies.
14981 var cp = new Roo.state.CookieProvider({
14983 expires: new Date(new Date().getTime()+(1000*60*60*24*30)); //30 days
14984 domain: "roojs.com"
14986 Roo.state.Manager.setProvider(cp);
14988 * @cfg {String} path The path for which the cookie is active (defaults to root '/' which makes it active for all pages in the site)
14989 * @cfg {Date} expires The cookie expiration date (defaults to 7 days from now)
14990 * @cfg {String} domain The domain to save the cookie for. Note that you cannot specify a different domain than
14991 * your page is on, but you can specify a sub-domain, or simply the domain itself like 'roojs.com' to include
14992 * all sub-domains if you need to access cookies across different sub-domains (defaults to null which uses the same
14993 * domain the page is running on including the 'www' like 'www.roojs.com')
14994 * @cfg {Boolean} secure True if the site is using SSL (defaults to false)
14996 * Create a new CookieProvider
14997 * @param {Object} config The configuration object
14999 Roo.state.CookieProvider = function(config){
15000 Roo.state.CookieProvider.superclass.constructor.call(this);
15002 this.expires = new Date(new Date().getTime()+(1000*60*60*24*7)); //7 days
15003 this.domain = null;
15004 this.secure = false;
15005 Roo.apply(this, config);
15006 this.state = this.readCookies();
15009 Roo.extend(Roo.state.CookieProvider, Roo.state.Provider, {
15011 set : function(name, value){
15012 if(typeof value == "undefined" || value === null){
15016 this.setCookie(name, value);
15017 Roo.state.CookieProvider.superclass.set.call(this, name, value);
15021 clear : function(name){
15022 this.clearCookie(name);
15023 Roo.state.CookieProvider.superclass.clear.call(this, name);
15027 readCookies : function(){
15029 var c = document.cookie + ";";
15030 var re = /\s?(.*?)=(.*?);/g;
15032 while((matches = re.exec(c)) != null){
15033 var name = matches[1];
15034 var value = matches[2];
15035 if(name && name.substring(0,3) == "ys-"){
15036 cookies[name.substr(3)] = this.decodeValue(value);
15043 setCookie : function(name, value){
15044 document.cookie = "ys-"+ name + "=" + this.encodeValue(value) +
15045 ((this.expires == null) ? "" : ("; expires=" + this.expires.toGMTString())) +
15046 ((this.path == null) ? "" : ("; path=" + this.path)) +
15047 ((this.domain == null) ? "" : ("; domain=" + this.domain)) +
15048 ((this.secure == true) ? "; secure" : "");
15052 clearCookie : function(name){
15053 document.cookie = "ys-" + name + "=null; expires=Thu, 01-Jan-70 00:00:01 GMT" +
15054 ((this.path == null) ? "" : ("; path=" + this.path)) +
15055 ((this.domain == null) ? "" : ("; domain=" + this.domain)) +
15056 ((this.secure == true) ? "; secure" : "");
15060 * Ext JS Library 1.1.1
15061 * Copyright(c) 2006-2007, Ext JS, LLC.
15063 * Originally Released Under LGPL - original licence link has changed is not relivant.
15066 * <script type="text/javascript">
15071 * @class Roo.ComponentMgr
15072 * Provides a common registry of all components on a page so that they can be easily accessed by component id (see {@link Roo.getCmp}).
15075 Roo.ComponentMgr = function(){
15076 var all = new Roo.util.MixedCollection();
15080 * Registers a component.
15081 * @param {Roo.Component} c The component
15083 register : function(c){
15088 * Unregisters a component.
15089 * @param {Roo.Component} c The component
15091 unregister : function(c){
15096 * Returns a component by id
15097 * @param {String} id The component id
15099 get : function(id){
15100 return all.get(id);
15104 * Registers a function that will be called when a specified component is added to ComponentMgr
15105 * @param {String} id The component id
15106 * @param {Funtction} fn The callback function
15107 * @param {Object} scope The scope of the callback
15109 onAvailable : function(id, fn, scope){
15110 all.on("add", function(index, o){
15112 fn.call(scope || o, o);
15113 all.un("add", fn, scope);
15120 * Ext JS Library 1.1.1
15121 * Copyright(c) 2006-2007, Ext JS, LLC.
15123 * Originally Released Under LGPL - original licence link has changed is not relivant.
15126 * <script type="text/javascript">
15130 * @class Roo.Component
15131 * @extends Roo.util.Observable
15132 * Base class for all major Roo components. All subclasses of Component can automatically participate in the standard
15133 * Roo component lifecycle of creation, rendering and destruction. They also have automatic support for basic hide/show
15134 * and enable/disable behavior. Component allows any subclass to be lazy-rendered into any {@link Roo.Container} and
15135 * to be automatically registered with the {@link Roo.ComponentMgr} so that it can be referenced at any time via {@link Roo.getCmp}.
15136 * All visual components (widgets) that require rendering into a layout should subclass Component.
15138 * @param {Roo.Element/String/Object} config The configuration options. If an element is passed, it is set as the internal
15139 * 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
15140 * and is used as the component id. Otherwise, it is assumed to be a standard config object and is applied to the component.
15142 Roo.Component = function(config){
15143 config = config || {};
15144 if(config.tagName || config.dom || typeof config == "string"){ // element object
15145 config = {el: config, id: config.id || config};
15147 this.initialConfig = config;
15149 Roo.apply(this, config);
15153 * Fires after the component is disabled.
15154 * @param {Roo.Component} this
15159 * Fires after the component is enabled.
15160 * @param {Roo.Component} this
15164 * @event beforeshow
15165 * Fires before the component is shown. Return false to stop the show.
15166 * @param {Roo.Component} this
15171 * Fires after the component is shown.
15172 * @param {Roo.Component} this
15176 * @event beforehide
15177 * Fires before the component is hidden. Return false to stop the hide.
15178 * @param {Roo.Component} this
15183 * Fires after the component is hidden.
15184 * @param {Roo.Component} this
15188 * @event beforerender
15189 * Fires before the component is rendered. Return false to stop the render.
15190 * @param {Roo.Component} this
15192 beforerender : true,
15195 * Fires after the component is rendered.
15196 * @param {Roo.Component} this
15200 * @event beforedestroy
15201 * Fires before the component is destroyed. Return false to stop the destroy.
15202 * @param {Roo.Component} this
15204 beforedestroy : true,
15207 * Fires after the component is destroyed.
15208 * @param {Roo.Component} this
15213 this.id = "roo-comp-" + (++Roo.Component.AUTO_ID);
15215 Roo.ComponentMgr.register(this);
15216 Roo.Component.superclass.constructor.call(this);
15217 this.initComponent();
15218 if(this.renderTo){ // not supported by all components yet. use at your own risk!
15219 this.render(this.renderTo);
15220 delete this.renderTo;
15225 Roo.Component.AUTO_ID = 1000;
15227 Roo.extend(Roo.Component, Roo.util.Observable, {
15229 * @scope Roo.Component.prototype
15231 * true if this component is hidden. Read-only.
15236 * true if this component is disabled. Read-only.
15241 * true if this component has been rendered. Read-only.
15245 /** @cfg {String} disableClass
15246 * CSS class added to the component when it is disabled (defaults to "x-item-disabled").
15248 disabledClass : "x-item-disabled",
15249 /** @cfg {Boolean} allowDomMove
15250 * Whether the component can move the Dom node when rendering (defaults to true).
15252 allowDomMove : true,
15253 /** @cfg {String} hideMode (display|visibility)
15254 * How this component should hidden. Supported values are
15255 * "visibility" (css visibility), "offsets" (negative offset position) and
15256 * "display" (css display) - defaults to "display".
15258 hideMode: 'display',
15261 ctype : "Roo.Component",
15264 * @cfg {String} actionMode
15265 * which property holds the element that used for hide() / show() / disable() / enable()
15271 getActionEl : function(){
15272 return this[this.actionMode];
15275 initComponent : Roo.emptyFn,
15277 * If this is a lazy rendering component, render it to its container element.
15278 * @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.
15280 render : function(container, position){
15281 if(!this.rendered && this.fireEvent("beforerender", this) !== false){
15282 if(!container && this.el){
15283 this.el = Roo.get(this.el);
15284 container = this.el.dom.parentNode;
15285 this.allowDomMove = false;
15287 this.container = Roo.get(container);
15288 this.rendered = true;
15289 if(position !== undefined){
15290 if(typeof position == 'number'){
15291 position = this.container.dom.childNodes[position];
15293 position = Roo.getDom(position);
15296 this.onRender(this.container, position || null);
15298 this.el.addClass(this.cls);
15302 this.el.applyStyles(this.style);
15305 this.fireEvent("render", this);
15306 this.afterRender(this.container);
15318 // default function is not really useful
15319 onRender : function(ct, position){
15321 this.el = Roo.get(this.el);
15322 if(this.allowDomMove !== false){
15323 ct.dom.insertBefore(this.el.dom, position);
15329 getAutoCreate : function(){
15330 var cfg = typeof this.autoCreate == "object" ?
15331 this.autoCreate : Roo.apply({}, this.defaultAutoCreate);
15332 if(this.id && !cfg.id){
15339 afterRender : Roo.emptyFn,
15342 * Destroys this component by purging any event listeners, removing the component's element from the DOM,
15343 * removing the component from its {@link Roo.Container} (if applicable) and unregistering it from {@link Roo.ComponentMgr}.
15345 destroy : function(){
15346 if(this.fireEvent("beforedestroy", this) !== false){
15347 this.purgeListeners();
15348 this.beforeDestroy();
15350 this.el.removeAllListeners();
15352 if(this.actionMode == "container"){
15353 this.container.remove();
15357 Roo.ComponentMgr.unregister(this);
15358 this.fireEvent("destroy", this);
15363 beforeDestroy : function(){
15368 onDestroy : function(){
15373 * Returns the underlying {@link Roo.Element}.
15374 * @return {Roo.Element} The element
15376 getEl : function(){
15381 * Returns the id of this component.
15384 getId : function(){
15389 * Try to focus this component.
15390 * @param {Boolean} selectText True to also select the text in this component (if applicable)
15391 * @return {Roo.Component} this
15393 focus : function(selectText){
15396 if(selectText === true){
15397 this.el.dom.select();
15412 * Disable this component.
15413 * @return {Roo.Component} this
15415 disable : function(){
15419 this.disabled = true;
15420 this.fireEvent("disable", this);
15425 onDisable : function(){
15426 this.getActionEl().addClass(this.disabledClass);
15427 this.el.dom.disabled = true;
15431 * Enable this component.
15432 * @return {Roo.Component} this
15434 enable : function(){
15438 this.disabled = false;
15439 this.fireEvent("enable", this);
15444 onEnable : function(){
15445 this.getActionEl().removeClass(this.disabledClass);
15446 this.el.dom.disabled = false;
15450 * Convenience function for setting disabled/enabled by boolean.
15451 * @param {Boolean} disabled
15453 setDisabled : function(disabled){
15454 this[disabled ? "disable" : "enable"]();
15458 * Show this component.
15459 * @return {Roo.Component} this
15462 if(this.fireEvent("beforeshow", this) !== false){
15463 this.hidden = false;
15467 this.fireEvent("show", this);
15473 onShow : function(){
15474 var ae = this.getActionEl();
15475 if(this.hideMode == 'visibility'){
15476 ae.dom.style.visibility = "visible";
15477 }else if(this.hideMode == 'offsets'){
15478 ae.removeClass('x-hidden');
15480 ae.dom.style.display = "";
15485 * Hide this component.
15486 * @return {Roo.Component} this
15489 if(this.fireEvent("beforehide", this) !== false){
15490 this.hidden = true;
15494 this.fireEvent("hide", this);
15500 onHide : function(){
15501 var ae = this.getActionEl();
15502 if(this.hideMode == 'visibility'){
15503 ae.dom.style.visibility = "hidden";
15504 }else if(this.hideMode == 'offsets'){
15505 ae.addClass('x-hidden');
15507 ae.dom.style.display = "none";
15512 * Convenience function to hide or show this component by boolean.
15513 * @param {Boolean} visible True to show, false to hide
15514 * @return {Roo.Component} this
15516 setVisible: function(visible){
15526 * Returns true if this component is visible.
15528 isVisible : function(){
15529 return this.getActionEl().isVisible();
15532 cloneConfig : function(overrides){
15533 overrides = overrides || {};
15534 var id = overrides.id || Roo.id();
15535 var cfg = Roo.applyIf(overrides, this.initialConfig);
15536 cfg.id = id; // prevent dup id
15537 return new this.constructor(cfg);
15541 * Ext JS Library 1.1.1
15542 * Copyright(c) 2006-2007, Ext JS, LLC.
15544 * Originally Released Under LGPL - original licence link has changed is not relivant.
15547 * <script type="text/javascript">
15551 * @class Roo.BoxComponent
15552 * @extends Roo.Component
15553 * Base class for any visual {@link Roo.Component} that uses a box container. BoxComponent provides automatic box
15554 * model adjustments for sizing and positioning and will work correctly withnin the Component rendering model. All
15555 * container classes should subclass BoxComponent so that they will work consistently when nested within other Ext
15556 * layout containers.
15558 * @param {Roo.Element/String/Object} config The configuration options.
15560 Roo.BoxComponent = function(config){
15561 Roo.Component.call(this, config);
15565 * Fires after the component is resized.
15566 * @param {Roo.Component} this
15567 * @param {Number} adjWidth The box-adjusted width that was set
15568 * @param {Number} adjHeight The box-adjusted height that was set
15569 * @param {Number} rawWidth The width that was originally specified
15570 * @param {Number} rawHeight The height that was originally specified
15575 * Fires after the component is moved.
15576 * @param {Roo.Component} this
15577 * @param {Number} x The new x position
15578 * @param {Number} y The new y position
15584 Roo.extend(Roo.BoxComponent, Roo.Component, {
15585 // private, set in afterRender to signify that the component has been rendered
15587 // private, used to defer height settings to subclasses
15588 deferHeight: false,
15589 /** @cfg {Number} width
15590 * width (optional) size of component
15592 /** @cfg {Number} height
15593 * height (optional) size of component
15597 * Sets the width and height of the component. This method fires the resize event. This method can accept
15598 * either width and height as separate numeric arguments, or you can pass a size object like {width:10, height:20}.
15599 * @param {Number/Object} width The new width to set, or a size object in the format {width, height}
15600 * @param {Number} height The new height to set (not required if a size object is passed as the first arg)
15601 * @return {Roo.BoxComponent} this
15603 setSize : function(w, h){
15604 // support for standard size objects
15605 if(typeof w == 'object'){
15610 if(!this.boxReady){
15616 // prevent recalcs when not needed
15617 if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
15620 this.lastSize = {width: w, height: h};
15622 var adj = this.adjustSize(w, h);
15623 var aw = adj.width, ah = adj.height;
15624 if(aw !== undefined || ah !== undefined){ // this code is nasty but performs better with floaters
15625 var rz = this.getResizeEl();
15626 if(!this.deferHeight && aw !== undefined && ah !== undefined){
15627 rz.setSize(aw, ah);
15628 }else if(!this.deferHeight && ah !== undefined){
15630 }else if(aw !== undefined){
15633 this.onResize(aw, ah, w, h);
15634 this.fireEvent('resize', this, aw, ah, w, h);
15640 * Gets the current size of the component's underlying element.
15641 * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
15643 getSize : function(){
15644 return this.el.getSize();
15648 * Gets the current XY position of the component's underlying element.
15649 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
15650 * @return {Array} The XY position of the element (e.g., [100, 200])
15652 getPosition : function(local){
15653 if(local === true){
15654 return [this.el.getLeft(true), this.el.getTop(true)];
15656 return this.xy || this.el.getXY();
15660 * Gets the current box measurements of the component's underlying element.
15661 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
15662 * @returns {Object} box An object in the format {x, y, width, height}
15664 getBox : function(local){
15665 var s = this.el.getSize();
15667 s.x = this.el.getLeft(true);
15668 s.y = this.el.getTop(true);
15670 var xy = this.xy || this.el.getXY();
15678 * Sets the current box measurements of the component's underlying element.
15679 * @param {Object} box An object in the format {x, y, width, height}
15680 * @returns {Roo.BoxComponent} this
15682 updateBox : function(box){
15683 this.setSize(box.width, box.height);
15684 this.setPagePosition(box.x, box.y);
15689 getResizeEl : function(){
15690 return this.resizeEl || this.el;
15694 getPositionEl : function(){
15695 return this.positionEl || this.el;
15699 * Sets the left and top of the component. To set the page XY position instead, use {@link #setPagePosition}.
15700 * This method fires the move event.
15701 * @param {Number} left The new left
15702 * @param {Number} top The new top
15703 * @returns {Roo.BoxComponent} this
15705 setPosition : function(x, y){
15708 if(!this.boxReady){
15711 var adj = this.adjustPosition(x, y);
15712 var ax = adj.x, ay = adj.y;
15714 var el = this.getPositionEl();
15715 if(ax !== undefined || ay !== undefined){
15716 if(ax !== undefined && ay !== undefined){
15717 el.setLeftTop(ax, ay);
15718 }else if(ax !== undefined){
15720 }else if(ay !== undefined){
15723 this.onPosition(ax, ay);
15724 this.fireEvent('move', this, ax, ay);
15730 * Sets the page XY position of the component. To set the left and top instead, use {@link #setPosition}.
15731 * This method fires the move event.
15732 * @param {Number} x The new x position
15733 * @param {Number} y The new y position
15734 * @returns {Roo.BoxComponent} this
15736 setPagePosition : function(x, y){
15739 if(!this.boxReady){
15742 if(x === undefined || y === undefined){ // cannot translate undefined points
15745 var p = this.el.translatePoints(x, y);
15746 this.setPosition(p.left, p.top);
15751 onRender : function(ct, position){
15752 Roo.BoxComponent.superclass.onRender.call(this, ct, position);
15754 this.resizeEl = Roo.get(this.resizeEl);
15756 if(this.positionEl){
15757 this.positionEl = Roo.get(this.positionEl);
15762 afterRender : function(){
15763 Roo.BoxComponent.superclass.afterRender.call(this);
15764 this.boxReady = true;
15765 this.setSize(this.width, this.height);
15766 if(this.x || this.y){
15767 this.setPosition(this.x, this.y);
15769 if(this.pageX || this.pageY){
15770 this.setPagePosition(this.pageX, this.pageY);
15775 * Force the component's size to recalculate based on the underlying element's current height and width.
15776 * @returns {Roo.BoxComponent} this
15778 syncSize : function(){
15779 delete this.lastSize;
15780 this.setSize(this.el.getWidth(), this.el.getHeight());
15785 * Called after the component is resized, this method is empty by default but can be implemented by any
15786 * subclass that needs to perform custom logic after a resize occurs.
15787 * @param {Number} adjWidth The box-adjusted width that was set
15788 * @param {Number} adjHeight The box-adjusted height that was set
15789 * @param {Number} rawWidth The width that was originally specified
15790 * @param {Number} rawHeight The height that was originally specified
15792 onResize : function(adjWidth, adjHeight, rawWidth, rawHeight){
15797 * Called after the component is moved, this method is empty by default but can be implemented by any
15798 * subclass that needs to perform custom logic after a move occurs.
15799 * @param {Number} x The new x position
15800 * @param {Number} y The new y position
15802 onPosition : function(x, y){
15807 adjustSize : function(w, h){
15808 if(this.autoWidth){
15811 if(this.autoHeight){
15814 return {width : w, height: h};
15818 adjustPosition : function(x, y){
15819 return {x : x, y: y};
15822 * Original code for Roojs - LGPL
15823 * <script type="text/javascript">
15827 * @class Roo.XComponent
15828 * A delayed Element creator...
15829 * Or a way to group chunks of interface together.
15830 * technically this is a wrapper around a tree of Roo elements (which defines a 'module'),
15831 * used in conjunction with XComponent.build() it will create an instance of each element,
15832 * then call addxtype() to build the User interface.
15834 * Mypart.xyx = new Roo.XComponent({
15836 parent : 'Mypart.xyz', // empty == document.element.!!
15840 disabled : function() {}
15842 tree : function() { // return an tree of xtype declared components
15846 xtype : 'NestedLayoutPanel',
15853 * It can be used to build a big heiracy, with parent etc.
15854 * or you can just use this to render a single compoent to a dom element
15855 * MYPART.render(Roo.Element | String(id) | dom_element )
15862 * Roo is designed primarily as a single page application, so the UI build for a standard interface will
15863 * expect a single 'TOP' level module normally indicated by the 'parent' of the XComponent definition being defined as false.
15865 * Each sub module is expected to have a parent pointing to the class name of it's parent module.
15867 * When the top level is false, a 'Roo.BorderLayout' is created and the element is flagged as 'topModule'
15868 * - if mulitple topModules exist, the last one is defined as the top module.
15872 * When the top level or multiple modules are to embedded into a existing HTML page,
15873 * the parent element can container '#id' of the element where the module will be drawn.
15877 * Unlike classic Roo, the bootstrap tends not to be used as a single page.
15878 * it relies more on a include mechanism, where sub modules are included into an outer page.
15879 * This is normally managed by the builder tools using Roo.apply( options, Included.Sub.Module )
15881 * Bootstrap Roo Included elements
15883 * Our builder application needs the ability to preview these sub compoennts. They will normally have parent=false set,
15884 * hence confusing the component builder as it thinks there are multiple top level elements.
15888 * @extends Roo.util.Observable
15890 * @param cfg {Object} configuration of component
15893 Roo.XComponent = function(cfg) {
15894 Roo.apply(this, cfg);
15898 * Fires when this the componnt is built
15899 * @param {Roo.XComponent} c the component
15904 this.region = this.region || 'center'; // default..
15905 Roo.XComponent.register(this);
15906 this.modules = false;
15907 this.el = false; // where the layout goes..
15911 Roo.extend(Roo.XComponent, Roo.util.Observable, {
15914 * The created element (with Roo.factory())
15915 * @type {Roo.Layout}
15921 * for BC - use el in new code
15922 * @type {Roo.Layout}
15928 * for BC - use el in new code
15929 * @type {Roo.Layout}
15934 * @cfg {Function|boolean} disabled
15935 * If this module is disabled by some rule, return true from the funtion
15940 * @cfg {String} parent
15941 * Name of parent element which it get xtype added to..
15946 * @cfg {String} order
15947 * Used to set the order in which elements are created (usefull for multiple tabs)
15952 * @cfg {String} name
15953 * String to display while loading.
15957 * @cfg {String} region
15958 * Region to render component to (defaults to center)
15963 * @cfg {Array} items
15964 * A single item array - the first element is the root of the tree..
15965 * It's done this way to stay compatible with the Xtype system...
15971 * The method that retuns the tree of parts that make up this compoennt
15978 * render element to dom or tree
15979 * @param {Roo.Element|String|DomElement} optional render to if parent is not set.
15982 render : function(el)
15986 var hp = this.parent ? 1 : 0;
15987 Roo.debug && Roo.log(this);
15989 if (!el && typeof(this.parent) == 'string' && this.parent.substring(0,1) == '#') {
15990 // if parent is a '#.....' string, then let's use that..
15991 var ename = this.parent.substr(1);
15992 this.parent = false;
15993 Roo.debug && Roo.log(ename);
15995 case 'bootstrap-body' :
15996 if (typeof(Roo.bootstrap.Body) != 'undefined') {
15997 this.parent = { el : new Roo.bootstrap.Body() };
15998 Roo.debug && Roo.log("setting el to doc body");
16001 throw "Container is bootstrap body, but Roo.bootstrap.Body is not defined";
16005 this.parent = { el : true};
16008 el = Roo.get(ename);
16013 if (!el && !this.parent) {
16014 Roo.debug && Roo.log("Warning - element can not be found :#" + ename );
16018 Roo.debug && Roo.log("EL:");
16019 Roo.debug && Roo.log(el);
16020 Roo.debug && Roo.log("this.parent.el:");
16021 Roo.debug && Roo.log(this.parent.el);
16023 var tree = this._tree ? this._tree() : this.tree();
16025 // altertive root elements ??? - we need a better way to indicate these.
16026 var is_alt = (typeof(Roo.bootstrap) != 'undefined' && tree.xns == Roo.bootstrap) ||
16027 (typeof(Roo.mailer) != 'undefined' && tree.xns == Roo.mailer) ;
16029 if (!this.parent && is_alt) {
16030 //el = Roo.get(document.body);
16031 this.parent = { el : true };
16036 if (!this.parent) {
16038 Roo.debug && Roo.log("no parent - creating one");
16040 el = el ? Roo.get(el) : false;
16042 // it's a top level one..
16044 el : new Roo.BorderLayout(el || document.body, {
16050 tabPosition: 'top',
16051 //resizeTabs: true,
16052 alwaysShowTabs: el && hp? false : true,
16053 hideTabs: el || !hp ? true : false,
16060 if (!this.parent.el) {
16061 // probably an old style ctor, which has been disabled.
16065 // The 'tree' method is '_tree now'
16067 tree.region = tree.region || this.region;
16069 if (this.parent.el === true) {
16070 // bootstrap... - body..
16071 this.parent.el = Roo.factory(tree);
16074 this.el = this.parent.el.addxtype(tree);
16075 this.fireEvent('built', this);
16077 this.panel = this.el;
16078 this.layout = this.panel.layout;
16079 this.parentLayout = this.parent.layout || false;
16085 Roo.apply(Roo.XComponent, {
16087 * @property hideProgress
16088 * true to disable the building progress bar.. usefull on single page renders.
16091 hideProgress : false,
16093 * @property buildCompleted
16094 * True when the builder has completed building the interface.
16097 buildCompleted : false,
16100 * @property topModule
16101 * the upper most module - uses document.element as it's constructor.
16108 * @property modules
16109 * array of modules to be created by registration system.
16110 * @type {Array} of Roo.XComponent
16115 * @property elmodules
16116 * array of modules to be created by which use #ID
16117 * @type {Array} of Roo.XComponent
16123 * @property build_from_html
16124 * Build elements from html - used by bootstrap HTML stuff
16125 * - this is cleared after build is completed
16126 * @type {boolean} true (default false)
16129 build_from_html : false,
16132 * Register components to be built later.
16134 * This solves the following issues
16135 * - Building is not done on page load, but after an authentication process has occured.
16136 * - Interface elements are registered on page load
16137 * - Parent Interface elements may not be loaded before child, so this handles that..
16144 module : 'Pman.Tab.projectMgr',
16146 parent : 'Pman.layout',
16147 disabled : false, // or use a function..
16150 * * @param {Object} details about module
16152 register : function(obj) {
16154 Roo.XComponent.event.fireEvent('register', obj);
16155 switch(typeof(obj.disabled) ) {
16161 if ( obj.disabled() ) {
16167 if (obj.disabled) {
16173 this.modules.push(obj);
16177 * convert a string to an object..
16178 * eg. 'AAA.BBB' -> finds AAA.BBB
16182 toObject : function(str)
16184 if (!str || typeof(str) == 'object') {
16187 if (str.substring(0,1) == '#') {
16191 var ar = str.split('.');
16196 eval('if (typeof ' + rt + ' == "undefined"){ o = false;} o = ' + rt + ';');
16198 throw "Module not found : " + str;
16202 throw "Module not found : " + str;
16204 Roo.each(ar, function(e) {
16205 if (typeof(o[e]) == 'undefined') {
16206 throw "Module not found : " + str;
16217 * move modules into their correct place in the tree..
16220 preBuild : function ()
16223 Roo.each(this.modules , function (obj)
16225 Roo.XComponent.event.fireEvent('beforebuild', obj);
16227 var opar = obj.parent;
16229 obj.parent = this.toObject(opar);
16231 Roo.debug && Roo.log("parent:toObject failed: " + e.toString());
16236 Roo.debug && Roo.log("GOT top level module");
16237 Roo.debug && Roo.log(obj);
16238 obj.modules = new Roo.util.MixedCollection(false,
16239 function(o) { return o.order + '' }
16241 this.topModule = obj;
16244 // parent is a string (usually a dom element name..)
16245 if (typeof(obj.parent) == 'string') {
16246 this.elmodules.push(obj);
16249 if (obj.parent.constructor != Roo.XComponent) {
16250 Roo.debug && Roo.log("Warning : Object Parent is not instance of XComponent:" + obj.name)
16252 if (!obj.parent.modules) {
16253 obj.parent.modules = new Roo.util.MixedCollection(false,
16254 function(o) { return o.order + '' }
16257 if (obj.parent.disabled) {
16258 obj.disabled = true;
16260 obj.parent.modules.add(obj);
16265 * make a list of modules to build.
16266 * @return {Array} list of modules.
16269 buildOrder : function()
16272 var cmp = function(a,b) {
16273 return String(a).toUpperCase() > String(b).toUpperCase() ? 1 : -1;
16275 if ((!this.topModule || !this.topModule.modules) && !this.elmodules.length) {
16276 throw "No top level modules to build";
16279 // make a flat list in order of modules to build.
16280 var mods = this.topModule ? [ this.topModule ] : [];
16283 // elmodules (is a list of DOM based modules )
16284 Roo.each(this.elmodules, function(e) {
16286 if (!this.topModule &&
16287 typeof(e.parent) == 'string' &&
16288 e.parent.substring(0,1) == '#' &&
16289 Roo.get(e.parent.substr(1))
16292 _this.topModule = e;
16298 // add modules to their parents..
16299 var addMod = function(m) {
16300 Roo.debug && Roo.log("build Order: add: " + m.name);
16303 if (m.modules && !m.disabled) {
16304 Roo.debug && Roo.log("build Order: " + m.modules.length + " child modules");
16305 m.modules.keySort('ASC', cmp );
16306 Roo.debug && Roo.log("build Order: " + m.modules.length + " child modules (after sort)");
16308 m.modules.each(addMod);
16310 Roo.debug && Roo.log("build Order: no child modules");
16312 // not sure if this is used any more..
16314 m.finalize.name = m.name + " (clean up) ";
16315 mods.push(m.finalize);
16319 if (this.topModule && this.topModule.modules) {
16320 this.topModule.modules.keySort('ASC', cmp );
16321 this.topModule.modules.each(addMod);
16327 * Build the registered modules.
16328 * @param {Object} parent element.
16329 * @param {Function} optional method to call after module has been added.
16333 build : function(opts)
16336 if (typeof(opts) != 'undefined') {
16337 Roo.apply(this,opts);
16341 var mods = this.buildOrder();
16343 //this.allmods = mods;
16344 //Roo.debug && Roo.log(mods);
16346 if (!mods.length) { // should not happen
16347 throw "NO modules!!!";
16351 var msg = "Building Interface...";
16352 // flash it up as modal - so we store the mask!?
16353 if (!this.hideProgress && Roo.MessageBox) {
16354 Roo.MessageBox.show({ title: 'loading' });
16355 Roo.MessageBox.show({
16356 title: "Please wait...",
16365 var total = mods.length;
16368 var progressRun = function() {
16369 if (!mods.length) {
16370 Roo.debug && Roo.log('hide?');
16371 if (!this.hideProgress && Roo.MessageBox) {
16372 Roo.MessageBox.hide();
16374 Roo.XComponent.build_from_html = false; // reset, so dialogs will be build from javascript
16376 Roo.XComponent.event.fireEvent('buildcomplete', _this.topModule);
16382 var m = mods.shift();
16385 Roo.debug && Roo.log(m);
16386 // not sure if this is supported any more.. - modules that are are just function
16387 if (typeof(m) == 'function') {
16389 return progressRun.defer(10, _this);
16393 msg = "Building Interface " + (total - mods.length) +
16395 (m.name ? (' - ' + m.name) : '');
16396 Roo.debug && Roo.log(msg);
16397 if (!this.hideProgress && Roo.MessageBox) {
16398 Roo.MessageBox.updateProgress( (total - mods.length)/total, msg );
16402 // is the module disabled?
16403 var disabled = (typeof(m.disabled) == 'function') ?
16404 m.disabled.call(m.module.disabled) : m.disabled;
16408 return progressRun(); // we do not update the display!
16416 // it's 10 on top level, and 1 on others??? why...
16417 return progressRun.defer(10, _this);
16420 progressRun.defer(1, _this);
16434 * wrapper for event.on - aliased later..
16435 * Typically use to register a event handler for register:
16437 * eg. Roo.XComponent.on('register', function(comp) { comp.disable = true } );
16446 Roo.XComponent.event = new Roo.util.Observable({
16450 * Fires when an Component is registered,
16451 * set the disable property on the Component to stop registration.
16452 * @param {Roo.XComponent} c the component being registerd.
16457 * @event beforebuild
16458 * Fires before each Component is built
16459 * can be used to apply permissions.
16460 * @param {Roo.XComponent} c the component being registerd.
16463 'beforebuild' : true,
16465 * @event buildcomplete
16466 * Fires on the top level element when all elements have been built
16467 * @param {Roo.XComponent} the top level component.
16469 'buildcomplete' : true
16474 Roo.XComponent.on = Roo.XComponent.event.on.createDelegate(Roo.XComponent.event);