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 isEdge = ua.indexOf("edge") > -1,
61 isGecko = !isSafari && ua.indexOf("gecko") > -1,
62 isBorderBox = isIE && !isStrict,
63 isWindows = (ua.indexOf("windows") != -1 || ua.indexOf("win32") != -1),
64 isMac = (ua.indexOf("macintosh") != -1 || ua.indexOf("mac os x") != -1),
65 isLinux = (ua.indexOf("linux") != -1),
66 isSecure = window.location.href.toLowerCase().indexOf("https") === 0,
67 isIOS = /iphone|ipad/.test(ua),
68 isAndroid = /android/.test(ua),
69 isTouch = (function() {
71 if (ua.indexOf('chrome') != -1 && ua.indexOf('android') == -1) {
72 window.addEventListener('touchstart', function __set_has_touch__ () {
74 window.removeEventListener('touchstart', __set_has_touch__);
76 return false; // no touch on chrome!?
78 document.createEvent("TouchEvent");
85 // remove css image flicker
88 document.execCommand("BackgroundImageCache", false, true);
94 * True if the browser is in strict mode
99 * True if the page is running over SSL
104 * True when the document is fully initialized and ready for action
109 * Turn on debugging output (currently only the factory uses this)
116 * True to automatically uncache orphaned Roo.Elements periodically (defaults to true)
119 enableGarbageCollector : true,
122 * True to automatically purge event listeners after uncaching an element (defaults to false).
123 * Note: this only happens if enableGarbageCollector is true.
126 enableListenerCollection:false,
129 * URL to a blank file used by Roo when in secure mode for iframe src and onReady src to prevent
130 * the IE insecure content warning (defaults to javascript:false).
133 SSL_SECURE_URL : "javascript:false",
136 * URL to a 1x1 transparent gif image used by Roo to create inline icons with CSS background images. (Defaults to
137 * "http://Roojs.com/s.gif" and you should change this to a URL on your server).
140 BLANK_IMAGE_URL : "http:/"+"/localhost/s.gif",
142 emptyFn : function(){},
145 * Copies all the properties of config to obj if they don't already exist.
146 * @param {Object} obj The receiver of the properties
147 * @param {Object} config The source of the properties
148 * @return {Object} returns obj
150 applyIf : function(o, c){
153 if(typeof o[p] == "undefined"){ o[p] = c[p]; }
160 * Applies event listeners to elements by selectors when the document is ready.
161 * The event name is specified with an @ suffix.
164 // add a listener for click on all anchors in element with id foo
165 '#foo a@click' : function(e, t){
169 // add the same listener to multiple selectors (separated by comma BEFORE the @)
170 '#foo a, #bar span.some-class@mouseover' : function(){
175 * @param {Object} obj The list of behaviors to apply
177 addBehaviors : function(o){
179 Roo.onReady(function(){
184 var cache = {}; // simple cache for applying multiple behaviors to same selector does query multiple times
186 var parts = b.split('@');
187 if(parts[1]){ // for Object prototype breakers
190 cache[s] = Roo.select(s);
192 cache[s].on(parts[1], o[b]);
199 * Generates unique ids. If the element already has an id, it is unchanged
200 * @param {String/HTMLElement/Element} el (optional) The element to generate an id for
201 * @param {String} prefix (optional) Id prefix (defaults "Roo-gen")
202 * @return {String} The generated Id.
204 id : function(el, prefix){
205 prefix = prefix || "roo-gen";
207 var id = prefix + (++idSeed);
208 return el ? (el.id ? el.id : (el.id = id)) : id;
213 * Extends one class with another class and optionally overrides members with the passed literal. This class
214 * also adds the function "override()" to the class that can be used to override
215 * members on an instance.
216 * @param {Object} subclass The class inheriting the functionality
217 * @param {Object} superclass The class being extended
218 * @param {Object} overrides (optional) A literal with members
223 var io = function(o){
228 return function(sb, sp, overrides){
229 if(typeof sp == 'object'){ // eg. prototype, rather than function constructor..
232 sb = function(){sp.apply(this, arguments);};
234 var F = function(){}, sbp, spp = sp.prototype;
236 sbp = sb.prototype = new F();
240 if(spp.constructor == Object.prototype.constructor){
245 sb.override = function(o){
249 Roo.override(sb, overrides);
255 * Adds a list of functions to the prototype of an existing class, overwriting any existing methods with the same name.
257 Roo.override(MyClass, {
258 newMethod1: function(){
261 newMethod2: function(foo){
266 * @param {Object} origclass The class to override
267 * @param {Object} overrides The list of functions to add to origClass. This should be specified as an object literal
268 * containing one or more methods.
271 override : function(origclass, overrides){
273 var p = origclass.prototype;
274 for(var method in overrides){
275 p[method] = overrides[method];
280 * Creates namespaces to be used for scoping variables and classes so that they are not global. Usage:
282 Roo.namespace('Company', 'Company.data');
283 Company.Widget = function() { ... }
284 Company.data.CustomStore = function(config) { ... }
286 * @param {String} namespace1
287 * @param {String} namespace2
288 * @param {String} etc
291 namespace : function(){
292 var a=arguments, o=null, i, j, d, rt;
293 for (i=0; i<a.length; ++i) {
297 eval('if (typeof ' + rt + ' == "undefined"){' + rt + ' = {};} o = ' + rt + ';');
298 for (j=1; j<d.length; ++j) {
299 o[d[j]]=o[d[j]] || {};
305 * Creates namespaces to be used for scoping variables and classes so that they are not global. Usage:
307 Roo.factory({ xns: Roo.data, xtype : 'Store', .....});
308 Roo.factory(conf, Roo.data);
310 * @param {String} classname
311 * @param {String} namespace (optional)
315 factory : function(c, ns)
317 // no xtype, no ns or c.xns - or forced off by c.xns
318 if (!c.xtype || (!ns && !c.xns) || (c.xns === false)) { // not enough info...
321 ns = c.xns ? c.xns : ns; // if c.xns is set, then use that..
322 if (c.constructor == ns[c.xtype]) {// already created...
326 if (Roo.debug) { Roo.log("Roo.Factory(" + c.xtype + ")"); }
327 var ret = new ns[c.xtype](c);
331 c.xns = false; // prevent recursion..
335 * Logs to console if it can.
337 * @param {String|Object} string
342 if ((typeof(console) == 'undefined') || (typeof(console.log) == 'undefined')) {
349 * 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.
353 urlEncode : function(o){
359 var ov = o[key], k = Roo.encodeURIComponent(key);
360 var type = typeof ov;
361 if(type == 'undefined'){
363 }else if(type != "function" && type != "object"){
364 buf.push(k, "=", Roo.encodeURIComponent(ov), "&");
365 }else if(ov instanceof Array){
367 for(var i = 0, len = ov.length; i < len; i++) {
368 buf.push(k, "=", Roo.encodeURIComponent(ov[i] === undefined ? '' : ov[i]), "&");
379 * Safe version of encodeURIComponent
380 * @param {String} data
384 encodeURIComponent : function (data)
387 return encodeURIComponent(data);
388 } catch(e) {} // should be an uri encode error.
390 if (data == '' || data == null){
393 // http://stackoverflow.com/questions/2596483/unicode-and-uri-encoding-decoding-and-escaping-in-javascript
394 function nibble_to_hex(nibble){
395 var chars = '0123456789ABCDEF';
396 return chars.charAt(nibble);
398 data = data.toString();
400 for(var i=0; i<data.length; i++){
401 var c = data.charCodeAt(i);
402 var bs = new Array();
405 bs[0] = 0xF0 | ((c & 0x1C0000) >>> 18);
406 bs[1] = 0x80 | ((c & 0x3F000) >>> 12);
407 bs[2] = 0x80 | ((c & 0xFC0) >>> 6);
408 bs[3] = 0x80 | (c & 0x3F);
409 }else if (c > 0x800){
411 bs[0] = 0xE0 | ((c & 0xF000) >>> 12);
412 bs[1] = 0x80 | ((c & 0xFC0) >>> 6);
413 bs[2] = 0x80 | (c & 0x3F);
416 bs[0] = 0xC0 | ((c & 0x7C0) >>> 6);
417 bs[1] = 0x80 | (c & 0x3F);
422 for(var j=0; j<bs.length; j++){
424 var hex = nibble_to_hex((b & 0xF0) >>> 4)
425 + nibble_to_hex(b &0x0F);
434 * 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]}.
435 * @param {String} string
436 * @param {Boolean} overwrite (optional) Items of the same name will overwrite previous values instead of creating an an array (Defaults to false).
437 * @return {Object} A literal with members
439 urlDecode : function(string, overwrite){
440 if(!string || !string.length){
444 var pairs = string.split('&');
445 var pair, name, value;
446 for(var i = 0, len = pairs.length; i < len; i++){
447 pair = pairs[i].split('=');
448 name = decodeURIComponent(pair[0]);
449 value = decodeURIComponent(pair[1]);
450 if(overwrite !== true){
451 if(typeof obj[name] == "undefined"){
453 }else if(typeof obj[name] == "string"){
454 obj[name] = [obj[name]];
455 obj[name].push(value);
457 obj[name].push(value);
467 * Iterates an array calling the passed function with each item, stopping if your function returns false. If the
468 * passed array is not really an array, your function is called once with it.
469 * The supplied function is called with (Object item, Number index, Array allItems).
470 * @param {Array/NodeList/Mixed} array
471 * @param {Function} fn
472 * @param {Object} scope
474 each : function(array, fn, scope){
475 if(typeof array.length == "undefined" || typeof array == "string"){
478 for(var i = 0, len = array.length; i < len; i++){
479 if(fn.call(scope || array[i], array[i], i, array) === false){ return i; };
484 combine : function(){
485 var as = arguments, l = as.length, r = [];
486 for(var i = 0; i < l; i++){
488 if(a instanceof Array){
490 }else if(a.length !== undefined && !a.substr){
491 r = r.concat(Array.prototype.slice.call(a, 0));
500 * Escapes the passed string for use in a regular expression
501 * @param {String} str
504 escapeRe : function(s) {
505 return s.replace(/([.*+?^${}()|[\]\/\\])/g, "\\$1");
509 callback : function(cb, scope, args, delay){
510 if(typeof cb == "function"){
512 cb.defer(delay, scope, args || []);
514 cb.apply(scope, args || []);
520 * Return the dom node for the passed string (id), dom node, or Roo.Element
521 * @param {String/HTMLElement/Roo.Element} el
522 * @return HTMLElement
524 getDom : function(el){
528 return el.dom ? el.dom : (typeof el == 'string' ? document.getElementById(el) : el);
532 * Shorthand for {@link Roo.ComponentMgr#get}
534 * @return Roo.Component
536 getCmp : function(id){
537 return Roo.ComponentMgr.get(id);
540 num : function(v, defaultValue){
541 if(typeof v != 'number'){
547 destroy : function(){
548 for(var i = 0, a = arguments, len = a.length; i < len; i++) {
552 as.removeAllListeners();
556 if(typeof as.purgeListeners == 'function'){
559 if(typeof as.destroy == 'function'){
566 // inpired by a similar function in mootools library
568 * Returns the type of object that is passed in. If the object passed in is null or undefined it
569 * return false otherwise it returns one of the following values:<ul>
570 * <li><b>string</b>: If the object passed is a string</li>
571 * <li><b>number</b>: If the object passed is a number</li>
572 * <li><b>boolean</b>: If the object passed is a boolean value</li>
573 * <li><b>function</b>: If the object passed is a function reference</li>
574 * <li><b>object</b>: If the object passed is an object</li>
575 * <li><b>array</b>: If the object passed is an array</li>
576 * <li><b>regexp</b>: If the object passed is a regular expression</li>
577 * <li><b>element</b>: If the object passed is a DOM Element</li>
578 * <li><b>nodelist</b>: If the object passed is a DOM NodeList</li>
579 * <li><b>textnode</b>: If the object passed is a DOM text node and contains something other than whitespace</li>
580 * <li><b>whitespace</b>: If the object passed is a DOM text node and contains only whitespace</li>
581 * @param {Mixed} object
585 if(o === undefined || o === null){
592 if(t == 'object' && o.nodeName) {
594 case 1: return 'element';
595 case 3: return (/\S/).test(o.nodeValue) ? 'textnode' : 'whitespace';
598 if(t == 'object' || t == 'function') {
599 switch(o.constructor) {
600 case Array: return 'array';
601 case RegExp: return 'regexp';
603 if(typeof o.length == 'number' && typeof o.item == 'function') {
611 * Returns true if the passed value is null, undefined or an empty string (optional).
612 * @param {Mixed} value The value to test
613 * @param {Boolean} allowBlank (optional) Pass true if an empty string is not considered empty
616 isEmpty : function(v, allowBlank){
617 return v === null || v === undefined || (!allowBlank ? v === '' : false);
625 isFirefox : isFirefox,
637 isBorderBox : isBorderBox,
639 isWindows : isWindows,
647 isAndroid : isAndroid,
652 * By default, Ext intelligently decides whether floating elements should be shimmed. If you are using flash,
653 * you may want to set this to true.
656 useShims : ((isIE && !isIE7) || (isGecko && isMac)),
661 * Selects a single element as a Roo Element
662 * This is about as close as you can get to jQuery's $('do crazy stuff')
663 * @param {String} selector The selector/xpath query
664 * @param {Node} root (optional) The start of the query (defaults to document).
665 * @return {Roo.Element}
667 selectNode : function(selector, root)
669 var node = Roo.DomQuery.selectNode(selector,root);
670 return node ? Roo.get(node) : new Roo.Element(false);
673 * Find the current bootstrap width Grid size
674 * Note xs is the default for smaller.. - this is currently used by grids to render correct columns
675 * @returns {String} (xs|sm|md|lg|xl)
678 getGridSize : function()
680 var w = Roo.lib.Dom.getViewWidth();
701 Roo.namespace("Roo", "Roo.util", "Roo.grid", "Roo.dd", "Roo.tree", "Roo.data",
702 "Roo.form", "Roo.menu", "Roo.state", "Roo.lib", "Roo.layout",
705 "Roo.bootstrap.dash");
708 * Ext JS Library 1.1.1
709 * Copyright(c) 2006-2007, Ext JS, LLC.
711 * Originally Released Under LGPL - original licence link has changed is not relivant.
714 * <script type="text/javascript">
718 // wrappedn so fnCleanup is not in global scope...
720 function fnCleanUp() {
721 var p = Function.prototype;
722 delete p.createSequence;
724 delete p.createDelegate;
725 delete p.createCallback;
726 delete p.createInterceptor;
728 window.detachEvent("onunload", fnCleanUp);
730 window.attachEvent("onunload", fnCleanUp);
737 * These functions are available on every Function object (any JavaScript function).
739 Roo.apply(Function.prototype, {
741 * Creates a callback that passes arguments[0], arguments[1], arguments[2], ...
742 * Call directly on any function. Example: <code>myFunction.createCallback(myarg, myarg2)</code>
743 * Will create a function that is bound to those 2 args.
744 * @return {Function} The new function
746 createCallback : function(/*args...*/){
747 // make args available, in function below
748 var args = arguments;
751 return method.apply(window, args);
756 * Creates a delegate (callback) that sets the scope to obj.
757 * Call directly on any function. Example: <code>this.myFunction.createDelegate(this)</code>
758 * Will create a function that is automatically scoped to this.
759 * @param {Object} obj (optional) The object for which the scope is set
760 * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
761 * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
762 * if a number the args are inserted at the specified position
763 * @return {Function} The new function
765 createDelegate : function(obj, args, appendArgs){
768 var callArgs = args || arguments;
769 if(appendArgs === true){
770 callArgs = Array.prototype.slice.call(arguments, 0);
771 callArgs = callArgs.concat(args);
772 }else if(typeof appendArgs == "number"){
773 callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first
774 var applyArgs = [appendArgs, 0].concat(args); // create method call params
775 Array.prototype.splice.apply(callArgs, applyArgs); // splice them in
777 return method.apply(obj || window, callArgs);
782 * Calls this function after the number of millseconds specified.
783 * @param {Number} millis The number of milliseconds for the setTimeout call (if 0 the function is executed immediately)
784 * @param {Object} obj (optional) The object for which the scope is set
785 * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
786 * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
787 * if a number the args are inserted at the specified position
788 * @return {Number} The timeout id that can be used with clearTimeout
790 defer : function(millis, obj, args, appendArgs){
791 var fn = this.createDelegate(obj, args, appendArgs);
793 return setTimeout(fn, millis);
799 * Create a combined function call sequence of the original function + the passed function.
800 * The resulting function returns the results of the original function.
801 * The passed fcn is called with the parameters of the original function
802 * @param {Function} fcn The function to sequence
803 * @param {Object} scope (optional) The scope of the passed fcn (Defaults to scope of original function or window)
804 * @return {Function} The new function
806 createSequence : function(fcn, scope){
807 if(typeof fcn != "function"){
812 var retval = method.apply(this || window, arguments);
813 fcn.apply(scope || this || window, arguments);
819 * Creates an interceptor function. The passed fcn is called before the original one. If it returns false, the original one is not called.
820 * The resulting function returns the results of the original function.
821 * The passed fcn is called with the parameters of the original function.
823 * @param {Function} fcn The function to call before the original
824 * @param {Object} scope (optional) The scope of the passed fcn (Defaults to scope of original function or window)
825 * @return {Function} The new function
827 createInterceptor : function(fcn, scope){
828 if(typeof fcn != "function"){
835 if(fcn.apply(scope || this || window, arguments) === false){
838 return method.apply(this || window, arguments);
844 * Ext JS Library 1.1.1
845 * Copyright(c) 2006-2007, Ext JS, LLC.
847 * Originally Released Under LGPL - original licence link has changed is not relivant.
850 * <script type="text/javascript">
853 Roo.applyIf(String, {
858 * Escapes the passed string for ' and \
859 * @param {String} string The string to escape
860 * @return {String} The escaped string
863 escape : function(string) {
864 return string.replace(/('|\\)/g, "\\$1");
868 * Pads the left side of a string with a specified character. This is especially useful
869 * for normalizing number and date strings. Example usage:
871 var s = String.leftPad('123', 5, '0');
872 // s now contains the string: '00123'
874 * @param {String} string The original string
875 * @param {Number} size The total length of the output string
876 * @param {String} char (optional) The character with which to pad the original string (defaults to empty string " ")
877 * @return {String} The padded string
880 leftPad : function (val, size, ch) {
881 var result = new String(val);
882 if(ch === null || ch === undefined || ch === '') {
885 while (result.length < size) {
886 result = ch + result;
892 * Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens. Each
893 * token must be unique, and must increment in the format {0}, {1}, etc. Example usage:
895 var cls = 'my-class', text = 'Some text';
896 var s = String.format('<div class="{0}">{1}</div>', cls, text);
897 // s now contains the string: '<div class="my-class">Some text</div>'
899 * @param {String} string The tokenized string to be formatted
900 * @param {String} value1 The value to replace token {0}
901 * @param {String} value2 Etc...
902 * @return {String} The formatted string
905 format : function(format){
906 var args = Array.prototype.slice.call(arguments, 1);
907 return format.replace(/\{(\d+)\}/g, function(m, i){
908 return Roo.util.Format.htmlEncode(args[i]);
916 * Utility function that allows you to easily switch a string between two alternating values. The passed value
917 * is compared to the current string, and if they are equal, the other value that was passed in is returned. If
918 * they are already different, the first value passed in is returned. Note that this method returns the new value
919 * but does not change the current string.
921 // alternate sort directions
922 sort = sort.toggle('ASC', 'DESC');
924 // instead of conditional logic:
925 sort = (sort == 'ASC' ? 'DESC' : 'ASC');
927 * @param {String} value The value to compare to the current string
928 * @param {String} other The new value to use if the string already equals the first value passed in
929 * @return {String} The new value
932 String.prototype.toggle = function(value, other){
933 return this == value ? other : value;
938 * Remove invalid unicode characters from a string
940 * @return {String} The clean string
942 String.prototype.unicodeClean = function () {
943 return this.replace(/[\s\S]/g,
944 function(character) {
945 if (character.charCodeAt()< 256) {
949 encodeURIComponent(character);
960 * Ext JS Library 1.1.1
961 * Copyright(c) 2006-2007, Ext JS, LLC.
963 * Originally Released Under LGPL - original licence link has changed is not relivant.
966 * <script type="text/javascript">
972 Roo.applyIf(Number.prototype, {
974 * Checks whether or not the current number is within a desired range. If the number is already within the
975 * range it is returned, otherwise the min or max value is returned depending on which side of the range is
976 * exceeded. Note that this method returns the constrained value but does not change the current number.
977 * @param {Number} min The minimum number in the range
978 * @param {Number} max The maximum number in the range
979 * @return {Number} The constrained value if outside the range, otherwise the current value
981 constrain : function(min, max){
982 return Math.min(Math.max(this, min), max);
986 * Ext JS Library 1.1.1
987 * Copyright(c) 2006-2007, Ext JS, LLC.
989 * Originally Released Under LGPL - original licence link has changed is not relivant.
992 * <script type="text/javascript">
997 Roo.applyIf(Array.prototype, {
1000 * Checks whether or not the specified object exists in the array.
1001 * @param {Object} o The object to check for
1002 * @return {Number} The index of o in the array (or -1 if it is not found)
1004 indexOf : function(o){
1005 for (var i = 0, len = this.length; i < len; i++){
1006 if(this[i] == o) { return i; }
1012 * Removes the specified object from the array. If the object is not found nothing happens.
1013 * @param {Object} o The object to remove
1015 remove : function(o){
1016 var index = this.indexOf(o);
1018 this.splice(index, 1);
1022 * Map (JS 1.6 compatibility)
1023 * @param {Function} function to call
1025 map : function(fun )
1027 var len = this.length >>> 0;
1028 if (typeof fun != "function") {
1029 throw new TypeError();
1031 var res = new Array(len);
1032 var thisp = arguments[1];
1033 for (var i = 0; i < len; i++)
1036 res[i] = fun.call(thisp, this[i], i, this);
1044 * @param {Array} o The array to compare to
1045 * @returns {Boolean} true if the same
1047 equals : function(b)
1049 // https://stackoverflow.com/questions/3115982/how-to-check-if-two-arrays-are-equal-with-javascript
1056 if (this.length !== b.length) {
1060 // sort?? a.sort().equals(b.sort());
1062 for (var i = 0; i < this.length; ++i) {
1063 if (this[i] !== b[i]) {
1075 Roo.applyIf(Array, {
1079 * @param {Array} o Or Array like object (eg. nodelist)
1086 for (var i =0; i < o.length; i++) {
1095 * Ext JS Library 1.1.1
1096 * Copyright(c) 2006-2007, Ext JS, LLC.
1098 * Originally Released Under LGPL - original licence link has changed is not relivant.
1101 * <script type="text/javascript">
1107 * The date parsing and format syntax is a subset of
1108 * <a href="http://www.php.net/date">PHP's date() function</a>, and the formats that are
1109 * supported will provide results equivalent to their PHP versions.
1111 * Following is the list of all currently supported formats:
1114 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'
1116 Format Output Description
1117 ------ ---------- --------------------------------------------------------------
1118 d 10 Day of the month, 2 digits with leading zeros
1119 D Wed A textual representation of a day, three letters
1120 j 10 Day of the month without leading zeros
1121 l Wednesday A full textual representation of the day of the week
1122 S th English ordinal day of month suffix, 2 chars (use with j)
1123 w 3 Numeric representation of the day of the week
1124 z 9 The julian date, or day of the year (0-365)
1125 W 01 ISO-8601 2-digit week number of year, weeks starting on Monday (00-52)
1126 F January A full textual representation of the month
1127 m 01 Numeric representation of a month, with leading zeros
1128 M Jan Month name abbreviation, three letters
1129 n 1 Numeric representation of a month, without leading zeros
1130 t 31 Number of days in the given month
1131 L 0 Whether it's a leap year (1 if it is a leap year, else 0)
1132 Y 2007 A full numeric representation of a year, 4 digits
1133 y 07 A two digit representation of a year
1134 a pm Lowercase Ante meridiem and Post meridiem
1135 A PM Uppercase Ante meridiem and Post meridiem
1136 g 3 12-hour format of an hour without leading zeros
1137 G 15 24-hour format of an hour without leading zeros
1138 h 03 12-hour format of an hour with leading zeros
1139 H 15 24-hour format of an hour with leading zeros
1140 i 05 Minutes with leading zeros
1141 s 01 Seconds, with leading zeros
1142 O -0600 Difference to Greenwich time (GMT) in hours (Allows +08, without minutes)
1143 P -06:00 Difference to Greenwich time (GMT) with colon between hours and minutes
1144 T CST Timezone setting of the machine running the code
1145 Z -21600 Timezone offset in seconds (negative if west of UTC, positive if east)
1148 * Example usage (note that you must escape format specifiers with '\\' to render them as character literals):
1150 var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
1151 document.write(dt.format('Y-m-d')); //2007-01-10
1152 document.write(dt.format('F j, Y, g:i a')); //January 10, 2007, 3:05 pm
1153 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
1156 * Here are some standard date/time patterns that you might find helpful. They
1157 * are not part of the source of Date.js, but to use them you can simply copy this
1158 * block of code into any script that is included after Date.js and they will also become
1159 * globally available on the Date object. Feel free to add or remove patterns as needed in your code.
1162 ISO8601Long:"Y-m-d H:i:s",
1163 ISO8601Short:"Y-m-d",
1165 LongDate: "l, F d, Y",
1166 FullDateTime: "l, F d, Y g:i:s A",
1169 LongTime: "g:i:s A",
1170 SortableDateTime: "Y-m-d\\TH:i:s",
1171 UniversalSortableDateTime: "Y-m-d H:i:sO",
1178 var dt = new Date();
1179 document.write(dt.format(Date.patterns.ShortDate));
1184 * Most of the date-formatting functions below are the excellent work of Baron Schwartz.
1185 * They generate precompiled functions from date formats instead of parsing and
1186 * processing the pattern every time you format a date. These functions are available
1187 * on every Date object (any javascript function).
1189 * The original article and download are here:
1190 * http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/
1197 Returns the number of milliseconds between this date and date
1198 @param {Date} date (optional) Defaults to now
1199 @return {Number} The diff in milliseconds
1200 @member Date getElapsed
1202 Date.prototype.getElapsed = function(date) {
1203 return Math.abs((date || new Date()).getTime()-this.getTime());
1205 // was in date file..
1209 Date.parseFunctions = {count:0};
1211 Date.parseRegexes = [];
1213 Date.formatFunctions = {count:0};
1216 Date.prototype.dateFormat = function(format) {
1217 if (Date.formatFunctions[format] == null) {
1218 Date.createNewFormat(format);
1220 var func = Date.formatFunctions[format];
1221 return this[func]();
1226 * Formats a date given the supplied format string
1227 * @param {String} format The format string
1228 * @return {String} The formatted date
1231 Date.prototype.format = Date.prototype.dateFormat;
1234 Date.createNewFormat = function(format) {
1235 var funcName = "format" + Date.formatFunctions.count++;
1236 Date.formatFunctions[format] = funcName;
1237 var code = "Date.prototype." + funcName + " = function(){return ";
1238 var special = false;
1240 for (var i = 0; i < format.length; ++i) {
1241 ch = format.charAt(i);
1242 if (!special && ch == "\\") {
1247 code += "'" + String.escape(ch) + "' + ";
1250 code += Date.getFormatCode(ch);
1253 /** eval:var:zzzzzzzzzzzzz */
1254 eval(code.substring(0, code.length - 3) + ";}");
1258 Date.getFormatCode = function(character) {
1259 switch (character) {
1261 return "String.leftPad(this.getDate(), 2, '0') + ";
1263 return "Date.dayNames[this.getDay()].substring(0, 3) + ";
1265 return "this.getDate() + ";
1267 return "Date.dayNames[this.getDay()] + ";
1269 return "this.getSuffix() + ";
1271 return "this.getDay() + ";
1273 return "this.getDayOfYear() + ";
1275 return "this.getWeekOfYear() + ";
1277 return "Date.monthNames[this.getMonth()] + ";
1279 return "String.leftPad(this.getMonth() + 1, 2, '0') + ";
1281 return "Date.monthNames[this.getMonth()].substring(0, 3) + ";
1283 return "(this.getMonth() + 1) + ";
1285 return "this.getDaysInMonth() + ";
1287 return "(this.isLeapYear() ? 1 : 0) + ";
1289 return "this.getFullYear() + ";
1291 return "('' + this.getFullYear()).substring(2, 4) + ";
1293 return "(this.getHours() < 12 ? 'am' : 'pm') + ";
1295 return "(this.getHours() < 12 ? 'AM' : 'PM') + ";
1297 return "((this.getHours() % 12) ? this.getHours() % 12 : 12) + ";
1299 return "this.getHours() + ";
1301 return "String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0') + ";
1303 return "String.leftPad(this.getHours(), 2, '0') + ";
1305 return "String.leftPad(this.getMinutes(), 2, '0') + ";
1307 return "String.leftPad(this.getSeconds(), 2, '0') + ";
1309 return "this.getGMTOffset() + ";
1311 return "this.getGMTColonOffset() + ";
1313 return "this.getTimezone() + ";
1315 return "(this.getTimezoneOffset() * -60) + ";
1317 return "'" + String.escape(character) + "' + ";
1322 * Parses the passed string using the specified format. Note that this function expects dates in normal calendar
1323 * format, meaning that months are 1-based (1 = January) and not zero-based like in JavaScript dates. Any part of
1324 * the date format that is not specified will default to the current date value for that part. Time parts can also
1325 * be specified, but default to 0. Keep in mind that the input date string must precisely match the specified format
1326 * string or the parse operation will fail.
1329 //dt = Fri May 25 2007 (current date)
1330 var dt = new Date();
1332 //dt = Thu May 25 2006 (today's month/day in 2006)
1333 dt = Date.parseDate("2006", "Y");
1335 //dt = Sun Jan 15 2006 (all date parts specified)
1336 dt = Date.parseDate("2006-1-15", "Y-m-d");
1338 //dt = Sun Jan 15 2006 15:20:01 GMT-0600 (CST)
1339 dt = Date.parseDate("2006-1-15 3:20:01 PM", "Y-m-d h:i:s A" );
1341 * @param {String} input The unparsed date as a string
1342 * @param {String} format The format the date is in
1343 * @return {Date} The parsed date
1346 Date.parseDate = function(input, format) {
1347 if (Date.parseFunctions[format] == null) {
1348 Date.createParser(format);
1350 var func = Date.parseFunctions[format];
1351 return Date[func](input);
1357 Date.createParser = function(format) {
1358 var funcName = "parse" + Date.parseFunctions.count++;
1359 var regexNum = Date.parseRegexes.length;
1360 var currentGroup = 1;
1361 Date.parseFunctions[format] = funcName;
1363 var code = "Date." + funcName + " = function(input){\n"
1364 + "var y = -1, m = -1, d = -1, h = -1, i = -1, s = -1, o, z, v;\n"
1365 + "var d = new Date();\n"
1366 + "y = d.getFullYear();\n"
1367 + "m = d.getMonth();\n"
1368 + "d = d.getDate();\n"
1369 + "if (typeof(input) !== 'string') { input = input.toString(); }\n"
1370 + "var results = input.match(Date.parseRegexes[" + regexNum + "]);\n"
1371 + "if (results && results.length > 0) {";
1374 var special = false;
1376 for (var i = 0; i < format.length; ++i) {
1377 ch = format.charAt(i);
1378 if (!special && ch == "\\") {
1383 regex += String.escape(ch);
1386 var obj = Date.formatCodeToRegex(ch, currentGroup);
1387 currentGroup += obj.g;
1389 if (obj.g && obj.c) {
1395 code += "if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0)\n"
1396 + "{v = new Date(y, m, d, h, i, s);}\n"
1397 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0)\n"
1398 + "{v = new Date(y, m, d, h, i);}\n"
1399 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0)\n"
1400 + "{v = new Date(y, m, d, h);}\n"
1401 + "else if (y >= 0 && m >= 0 && d > 0)\n"
1402 + "{v = new Date(y, m, d);}\n"
1403 + "else if (y >= 0 && m >= 0)\n"
1404 + "{v = new Date(y, m);}\n"
1405 + "else if (y >= 0)\n"
1406 + "{v = new Date(y);}\n"
1407 + "}return (v && (z || o))?\n" // favour UTC offset over GMT offset
1408 + " ((z)? v.add(Date.SECOND, (v.getTimezoneOffset() * 60) + (z*1)) :\n" // reset to UTC, then add offset
1409 + " v.add(Date.HOUR, (v.getGMTOffset() / 100) + (o / -100))) : v\n" // reset to GMT, then add offset
1412 Date.parseRegexes[regexNum] = new RegExp("^" + regex + "$");
1413 /** eval:var:zzzzzzzzzzzzz */
1418 Date.formatCodeToRegex = function(character, currentGroup) {
1419 switch (character) {
1423 s:"(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)"};
1426 c:"d = parseInt(results[" + currentGroup + "], 10);\n",
1427 s:"(\\d{1,2})"}; // day of month without leading zeroes
1430 c:"d = parseInt(results[" + currentGroup + "], 10);\n",
1431 s:"(\\d{2})"}; // day of month with leading zeroes
1435 s:"(?:" + Date.dayNames.join("|") + ")"};
1439 s:"(?:st|nd|rd|th)"};
1454 c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "].substring(0, 3)], 10);\n",
1455 s:"(" + Date.monthNames.join("|") + ")"};
1458 c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "]], 10);\n",
1459 s:"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)"};
1462 c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
1463 s:"(\\d{1,2})"}; // Numeric representation of a month, without leading zeros
1466 c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
1467 s:"(\\d{2})"}; // Numeric representation of a month, with leading zeros
1478 c:"y = parseInt(results[" + currentGroup + "], 10);\n",
1482 c:"var ty = parseInt(results[" + currentGroup + "], 10);\n"
1483 + "y = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n",
1487 c:"if (results[" + currentGroup + "] == 'am') {\n"
1488 + "if (h == 12) { h = 0; }\n"
1489 + "} else { if (h < 12) { h += 12; }}",
1493 c:"if (results[" + currentGroup + "] == 'AM') {\n"
1494 + "if (h == 12) { h = 0; }\n"
1495 + "} else { if (h < 12) { h += 12; }}",
1500 c:"h = parseInt(results[" + currentGroup + "], 10);\n",
1501 s:"(\\d{1,2})"}; // 12/24-hr format format of an hour without leading zeroes
1505 c:"h = parseInt(results[" + currentGroup + "], 10);\n",
1506 s:"(\\d{2})"}; // 12/24-hr format format of an hour with leading zeroes
1509 c:"i = parseInt(results[" + currentGroup + "], 10);\n",
1513 c:"s = parseInt(results[" + currentGroup + "], 10);\n",
1518 "o = results[", currentGroup, "];\n",
1519 "var sn = o.substring(0,1);\n", // get + / - sign
1520 "var hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60);\n", // get hours (performs minutes-to-hour conversion also)
1521 "var mn = o.substring(3,5) % 60;\n", // get minutes
1522 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n", // -12hrs <= GMT offset <= 14hrs
1523 " (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"
1525 s:"([+\-]\\d{2,4})"};
1531 "o = results[", currentGroup, "];\n",
1532 "var sn = o.substring(0,1);\n",
1533 "var hr = o.substring(1,3)*1 + Math.floor(o.substring(4,6) / 60);\n",
1534 "var mn = o.substring(4,6) % 60;\n",
1535 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n",
1536 " (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"
1542 s:"[A-Z]{1,4}"}; // timezone abbrev. may be between 1 - 4 chars
1545 c:"z = results[" + currentGroup + "];\n" // -43200 <= UTC offset <= 50400
1546 + "z = (-43200 <= z*1 && z*1 <= 50400)? z : null;\n",
1547 s:"([+\-]?\\d{1,5})"}; // leading '+' sign is optional for UTC offset
1551 s:String.escape(character)};
1556 * Get the timezone abbreviation of the current date (equivalent to the format specifier 'T').
1557 * @return {String} The abbreviated timezone name (e.g. 'CST')
1559 Date.prototype.getTimezone = function() {
1560 return this.toString().replace(/^.*? ([A-Z]{1,4})[\-+][0-9]{4} .*$/, "$1");
1564 * Get the offset from GMT of the current date (equivalent to the format specifier 'O').
1565 * @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600')
1567 Date.prototype.getGMTOffset = function() {
1568 return (this.getTimezoneOffset() > 0 ? "-" : "+")
1569 + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
1570 + String.leftPad(this.getTimezoneOffset() % 60, 2, "0");
1574 * Get the offset from GMT of the current date (equivalent to the format specifier 'P').
1575 * @return {String} 2-characters representing hours and 2-characters representing minutes
1576 * seperated by a colon and prefixed with + or - (e.g. '-06:00')
1578 Date.prototype.getGMTColonOffset = function() {
1579 return (this.getTimezoneOffset() > 0 ? "-" : "+")
1580 + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
1582 + String.leftPad(this.getTimezoneOffset() %60, 2, "0");
1586 * Get the numeric day number of the year, adjusted for leap year.
1587 * @return {Number} 0 through 364 (365 in leap years)
1589 Date.prototype.getDayOfYear = function() {
1591 Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
1592 for (var i = 0; i < this.getMonth(); ++i) {
1593 num += Date.daysInMonth[i];
1595 return num + this.getDate() - 1;
1599 * Get the string representation of the numeric week number of the year
1600 * (equivalent to the format specifier 'W').
1601 * @return {String} '00' through '52'
1603 Date.prototype.getWeekOfYear = function() {
1604 // Skip to Thursday of this week
1605 var now = this.getDayOfYear() + (4 - this.getDay());
1606 // Find the first Thursday of the year
1607 var jan1 = new Date(this.getFullYear(), 0, 1);
1608 var then = (7 - jan1.getDay() + 4);
1609 return String.leftPad(((now - then) / 7) + 1, 2, "0");
1613 * Whether or not the current date is in a leap year.
1614 * @return {Boolean} True if the current date is in a leap year, else false
1616 Date.prototype.isLeapYear = function() {
1617 var year = this.getFullYear();
1618 return ((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
1622 * Get the first day of the current month, adjusted for leap year. The returned value
1623 * is the numeric day index within the week (0-6) which can be used in conjunction with
1624 * the {@link #monthNames} array to retrieve the textual day name.
1627 var dt = new Date('1/10/2007');
1628 document.write(Date.dayNames[dt.getFirstDayOfMonth()]); //output: 'Monday'
1630 * @return {Number} The day number (0-6)
1632 Date.prototype.getFirstDayOfMonth = function() {
1633 var day = (this.getDay() - (this.getDate() - 1)) % 7;
1634 return (day < 0) ? (day + 7) : day;
1638 * Get the last day of the current month, adjusted for leap year. The returned value
1639 * is the numeric day index within the week (0-6) which can be used in conjunction with
1640 * the {@link #monthNames} array to retrieve the textual day name.
1643 var dt = new Date('1/10/2007');
1644 document.write(Date.dayNames[dt.getLastDayOfMonth()]); //output: 'Wednesday'
1646 * @return {Number} The day number (0-6)
1648 Date.prototype.getLastDayOfMonth = function() {
1649 var day = (this.getDay() + (Date.daysInMonth[this.getMonth()] - this.getDate())) % 7;
1650 return (day < 0) ? (day + 7) : day;
1655 * Get the first date of this date's month
1658 Date.prototype.getFirstDateOfMonth = function() {
1659 return new Date(this.getFullYear(), this.getMonth(), 1);
1663 * Get the last date of this date's month
1666 Date.prototype.getLastDateOfMonth = function() {
1667 return new Date(this.getFullYear(), this.getMonth(), this.getDaysInMonth());
1670 * Get the number of days in the current month, adjusted for leap year.
1671 * @return {Number} The number of days in the month
1673 Date.prototype.getDaysInMonth = function() {
1674 Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
1675 return Date.daysInMonth[this.getMonth()];
1679 * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S').
1680 * @return {String} 'st, 'nd', 'rd' or 'th'
1682 Date.prototype.getSuffix = function() {
1683 switch (this.getDate()) {
1700 Date.daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
1703 * An array of textual month names.
1704 * Override these values for international dates, for example...
1705 * Date.monthNames = ['JanInYourLang', 'FebInYourLang', ...];
1724 * An array of textual day names.
1725 * Override these values for international dates, for example...
1726 * Date.dayNames = ['SundayInYourLang', 'MondayInYourLang', ...];
1742 Date.monthNumbers = {
1757 * Creates and returns a new Date instance with the exact same date value as the called instance.
1758 * Dates are copied and passed by reference, so if a copied date variable is modified later, the original
1759 * variable will also be changed. When the intention is to create a new variable that will not
1760 * modify the original instance, you should create a clone.
1762 * Example of correctly cloning a date:
1765 var orig = new Date('10/1/2006');
1768 document.write(orig); //returns 'Thu Oct 05 2006'!
1771 var orig = new Date('10/1/2006');
1772 var copy = orig.clone();
1774 document.write(orig); //returns 'Thu Oct 01 2006'
1776 * @return {Date} The new Date instance
1778 Date.prototype.clone = function() {
1779 return new Date(this.getTime());
1783 * Clears any time information from this date
1784 @param {Boolean} clone true to create a clone of this date, clear the time and return it
1785 @return {Date} this or the clone
1787 Date.prototype.clearTime = function(clone){
1789 return this.clone().clearTime();
1794 this.setMilliseconds(0);
1799 // safari setMonth is broken -- check that this is only donw once...
1800 if(Roo.isSafari && typeof(Date.brokenSetMonth) == 'undefined'){
1801 Date.brokenSetMonth = Date.prototype.setMonth;
1802 Date.prototype.setMonth = function(num){
1804 var n = Math.ceil(-num);
1805 var back_year = Math.ceil(n/12);
1806 var month = (n % 12) ? 12 - n % 12 : 0 ;
1807 this.setFullYear(this.getFullYear() - back_year);
1808 return Date.brokenSetMonth.call(this, month);
1810 return Date.brokenSetMonth.apply(this, arguments);
1815 /** Date interval constant
1819 /** Date interval constant
1823 /** Date interval constant
1827 /** Date interval constant
1831 /** Date interval constant
1835 /** Date interval constant
1839 /** Date interval constant
1845 * Provides a convenient method of performing basic date arithmetic. This method
1846 * does not modify the Date instance being called - it creates and returns
1847 * a new Date instance containing the resulting date value.
1852 var dt = new Date('10/29/2006').add(Date.DAY, 5);
1853 document.write(dt); //returns 'Fri Oct 06 2006 00:00:00'
1855 //Negative values will subtract correctly:
1856 var dt2 = new Date('10/1/2006').add(Date.DAY, -5);
1857 document.write(dt2); //returns 'Tue Sep 26 2006 00:00:00'
1859 //You can even chain several calls together in one line!
1860 var dt3 = new Date('10/1/2006').add(Date.DAY, 5).add(Date.HOUR, 8).add(Date.MINUTE, -30);
1861 document.write(dt3); //returns 'Fri Oct 06 2006 07:30:00'
1864 * @param {String} interval A valid date interval enum value
1865 * @param {Number} value The amount to add to the current date
1866 * @return {Date} The new Date instance
1868 Date.prototype.add = function(interval, value){
1869 var d = this.clone();
1870 if (!interval || value === 0) { return d; }
1871 switch(interval.toLowerCase()){
1873 d.setMilliseconds(this.getMilliseconds() + value);
1876 d.setSeconds(this.getSeconds() + value);
1879 d.setMinutes(this.getMinutes() + value);
1882 d.setHours(this.getHours() + value);
1885 d.setDate(this.getDate() + value);
1888 var day = this.getDate();
1890 day = Math.min(day, this.getFirstDateOfMonth().add('mo', value).getLastDateOfMonth().getDate());
1893 d.setMonth(this.getMonth() + value);
1896 d.setFullYear(this.getFullYear() + value);
1902 * @class Roo.lib.Dom
1906 * Dom utils (from YIU afaik)
1912 * Get the view width
1913 * @param {Boolean} full True will get the full document, otherwise it's the view width
1914 * @return {Number} The width
1917 getViewWidth : function(full) {
1918 return full ? this.getDocumentWidth() : this.getViewportWidth();
1921 * Get the view height
1922 * @param {Boolean} full True will get the full document, otherwise it's the view height
1923 * @return {Number} The height
1925 getViewHeight : function(full) {
1926 return full ? this.getDocumentHeight() : this.getViewportHeight();
1929 * Get the Full Document height
1930 * @return {Number} The height
1932 getDocumentHeight: function() {
1933 var scrollHeight = (document.compatMode != "CSS1Compat") ? document.body.scrollHeight : document.documentElement.scrollHeight;
1934 return Math.max(scrollHeight, this.getViewportHeight());
1937 * Get the Full Document width
1938 * @return {Number} The width
1940 getDocumentWidth: function() {
1941 var scrollWidth = (document.compatMode != "CSS1Compat") ? document.body.scrollWidth : document.documentElement.scrollWidth;
1942 return Math.max(scrollWidth, this.getViewportWidth());
1945 * Get the Window Viewport height
1946 * @return {Number} The height
1948 getViewportHeight: function() {
1949 var height = self.innerHeight;
1950 var mode = document.compatMode;
1952 if ((mode || Roo.isIE) && !Roo.isOpera) {
1953 height = (mode == "CSS1Compat") ?
1954 document.documentElement.clientHeight :
1955 document.body.clientHeight;
1961 * Get the Window Viewport width
1962 * @return {Number} The width
1964 getViewportWidth: function() {
1965 var width = self.innerWidth;
1966 var mode = document.compatMode;
1968 if (mode || Roo.isIE) {
1969 width = (mode == "CSS1Compat") ?
1970 document.documentElement.clientWidth :
1971 document.body.clientWidth;
1976 isAncestor : function(p, c) {
1983 if (p.contains && !Roo.isSafari) {
1984 return p.contains(c);
1985 } else if (p.compareDocumentPosition) {
1986 return !!(p.compareDocumentPosition(c) & 16);
1988 var parent = c.parentNode;
1993 else if (!parent.tagName || parent.tagName.toUpperCase() == "HTML") {
1996 parent = parent.parentNode;
2002 getRegion : function(el) {
2003 return Roo.lib.Region.getRegion(el);
2006 getY : function(el) {
2007 return this.getXY(el)[1];
2010 getX : function(el) {
2011 return this.getXY(el)[0];
2014 getXY : function(el) {
2015 var p, pe, b, scroll, bd = document.body;
2016 el = Roo.getDom(el);
2017 var fly = Roo.lib.AnimBase.fly;
2018 if (el.getBoundingClientRect) {
2019 b = el.getBoundingClientRect();
2020 scroll = fly(document).getScroll();
2021 return [b.left + scroll.left, b.top + scroll.top];
2027 var hasAbsolute = fly(el).getStyle("position") == "absolute";
2034 if (!hasAbsolute && fly(p).getStyle("position") == "absolute") {
2041 var bt = parseInt(pe.getStyle("borderTopWidth"), 10) || 0;
2042 var bl = parseInt(pe.getStyle("borderLeftWidth"), 10) || 0;
2049 if (p != el && pe.getStyle('overflow') != 'visible') {
2057 if (Roo.isSafari && hasAbsolute) {
2062 if (Roo.isGecko && !hasAbsolute) {
2064 x += parseInt(dbd.getStyle("borderLeftWidth"), 10) || 0;
2065 y += parseInt(dbd.getStyle("borderTopWidth"), 10) || 0;
2069 while (p && p != bd) {
2070 if (!Roo.isOpera || (p.tagName != 'TR' && fly(p).getStyle("display") != "inline")) {
2082 setXY : function(el, xy) {
2083 el = Roo.fly(el, '_setXY');
2085 var pts = el.translatePoints(xy);
2086 if (xy[0] !== false) {
2087 el.dom.style.left = pts.left + "px";
2089 if (xy[1] !== false) {
2090 el.dom.style.top = pts.top + "px";
2094 setX : function(el, x) {
2095 this.setXY(el, [x, false]);
2098 setY : function(el, y) {
2099 this.setXY(el, [false, y]);
2103 * Portions of this file are based on pieces of Yahoo User Interface Library
2104 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
2105 * YUI licensed under the BSD License:
2106 * http://developer.yahoo.net/yui/license.txt
2107 * <script type="text/javascript">
2111 Roo.lib.Event = function() {
2112 var loadComplete = false;
2114 var unloadListeners = [];
2116 var onAvailStack = [];
2118 var lastError = null;
2131 startInterval: function() {
2132 if (!this._interval) {
2134 var callback = function() {
2135 self._tryPreloadAttach();
2137 this._interval = setInterval(callback, this.POLL_INTERVAL);
2142 onAvailable: function(p_id, p_fn, p_obj, p_override) {
2143 onAvailStack.push({ id: p_id,
2146 override: p_override,
2147 checkReady: false });
2149 retryCount = this.POLL_RETRYS;
2150 this.startInterval();
2154 addListener: function(el, eventName, fn) {
2155 el = Roo.getDom(el);
2160 if ("unload" == eventName) {
2161 unloadListeners[unloadListeners.length] =
2162 [el, eventName, fn];
2166 var wrappedFn = function(e) {
2167 return fn(Roo.lib.Event.getEvent(e));
2170 var li = [el, eventName, fn, wrappedFn];
2172 var index = listeners.length;
2173 listeners[index] = li;
2175 this.doAdd(el, eventName, wrappedFn, false);
2181 removeListener: function(el, eventName, fn) {
2184 el = Roo.getDom(el);
2187 return this.purgeElement(el, false, eventName);
2191 if ("unload" == eventName) {
2193 for (i = 0,len = unloadListeners.length; i < len; i++) {
2194 var li = unloadListeners[i];
2197 li[1] == eventName &&
2199 unloadListeners.splice(i, 1);
2207 var cacheItem = null;
2210 var index = arguments[3];
2212 if ("undefined" == typeof index) {
2213 index = this._getCacheIndex(el, eventName, fn);
2217 cacheItem = listeners[index];
2220 if (!el || !cacheItem) {
2224 this.doRemove(el, eventName, cacheItem[this.WFN], false);
2226 delete listeners[index][this.WFN];
2227 delete listeners[index][this.FN];
2228 listeners.splice(index, 1);
2235 getTarget: function(ev, resolveTextNode) {
2236 ev = ev.browserEvent || ev;
2237 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2238 var t = ev.target || ev.srcElement;
2239 return this.resolveTextNode(t);
2243 resolveTextNode: function(node) {
2244 if (Roo.isSafari && node && 3 == node.nodeType) {
2245 return node.parentNode;
2252 getPageX: function(ev) {
2253 ev = ev.browserEvent || ev;
2254 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2256 if (!x && 0 !== x) {
2257 x = ev.clientX || 0;
2260 x += this.getScroll()[1];
2268 getPageY: function(ev) {
2269 ev = ev.browserEvent || ev;
2270 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2272 if (!y && 0 !== y) {
2273 y = ev.clientY || 0;
2276 y += this.getScroll()[0];
2285 getXY: function(ev) {
2286 ev = ev.browserEvent || ev;
2287 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2288 return [this.getPageX(ev), this.getPageY(ev)];
2292 getRelatedTarget: function(ev) {
2293 ev = ev.browserEvent || ev;
2294 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2295 var t = ev.relatedTarget;
2297 if (ev.type == "mouseout") {
2299 } else if (ev.type == "mouseover") {
2304 return this.resolveTextNode(t);
2308 getTime: function(ev) {
2309 ev = ev.browserEvent || ev;
2310 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2312 var t = new Date().getTime();
2316 this.lastError = ex;
2325 stopEvent: function(ev) {
2326 this.stopPropagation(ev);
2327 this.preventDefault(ev);
2331 stopPropagation: function(ev) {
2332 ev = ev.browserEvent || ev;
2333 if (ev.stopPropagation) {
2334 ev.stopPropagation();
2336 ev.cancelBubble = true;
2341 preventDefault: function(ev) {
2342 ev = ev.browserEvent || ev;
2343 if(ev.preventDefault) {
2344 ev.preventDefault();
2346 ev.returnValue = false;
2351 getEvent: function(e) {
2352 var ev = e || window.event;
2354 var c = this.getEvent.caller;
2356 ev = c.arguments[0];
2357 if (ev && Event == ev.constructor) {
2367 getCharCode: function(ev) {
2368 ev = ev.browserEvent || ev;
2369 return ev.charCode || ev.keyCode || 0;
2373 _getCacheIndex: function(el, eventName, fn) {
2374 for (var i = 0,len = listeners.length; i < len; ++i) {
2375 var li = listeners[i];
2377 li[this.FN] == fn &&
2378 li[this.EL] == el &&
2379 li[this.TYPE] == eventName) {
2391 getEl: function(id) {
2392 return document.getElementById(id);
2396 clearCache: function() {
2400 _load: function(e) {
2401 loadComplete = true;
2402 var EU = Roo.lib.Event;
2406 EU.doRemove(window, "load", EU._load);
2411 _tryPreloadAttach: function() {
2420 var tryAgain = !loadComplete;
2422 tryAgain = (retryCount > 0);
2427 for (var i = 0,len = onAvailStack.length; i < len; ++i) {
2428 var item = onAvailStack[i];
2430 var el = this.getEl(item.id);
2433 if (!item.checkReady ||
2436 (document && document.body)) {
2439 if (item.override) {
2440 if (item.override === true) {
2443 scope = item.override;
2446 item.fn.call(scope, item.obj);
2447 onAvailStack[i] = null;
2450 notAvail.push(item);
2455 retryCount = (notAvail.length === 0) ? 0 : retryCount - 1;
2459 this.startInterval();
2461 clearInterval(this._interval);
2462 this._interval = null;
2465 this.locked = false;
2472 purgeElement: function(el, recurse, eventName) {
2473 var elListeners = this.getListeners(el, eventName);
2475 for (var i = 0,len = elListeners.length; i < len; ++i) {
2476 var l = elListeners[i];
2477 this.removeListener(el, l.type, l.fn);
2481 if (recurse && el && el.childNodes) {
2482 for (i = 0,len = el.childNodes.length; i < len; ++i) {
2483 this.purgeElement(el.childNodes[i], recurse, eventName);
2489 getListeners: function(el, eventName) {
2490 var results = [], searchLists;
2492 searchLists = [listeners, unloadListeners];
2493 } else if (eventName == "unload") {
2494 searchLists = [unloadListeners];
2496 searchLists = [listeners];
2499 for (var j = 0; j < searchLists.length; ++j) {
2500 var searchList = searchLists[j];
2501 if (searchList && searchList.length > 0) {
2502 for (var i = 0,len = searchList.length; i < len; ++i) {
2503 var l = searchList[i];
2504 if (l && l[this.EL] === el &&
2505 (!eventName || eventName === l[this.TYPE])) {
2510 adjust: l[this.ADJ_SCOPE],
2518 return (results.length) ? results : null;
2522 _unload: function(e) {
2524 var EU = Roo.lib.Event, i, j, l, len, index;
2526 for (i = 0,len = unloadListeners.length; i < len; ++i) {
2527 l = unloadListeners[i];
2530 if (l[EU.ADJ_SCOPE]) {
2531 if (l[EU.ADJ_SCOPE] === true) {
2534 scope = l[EU.ADJ_SCOPE];
2537 l[EU.FN].call(scope, EU.getEvent(e), l[EU.OBJ]);
2538 unloadListeners[i] = null;
2544 unloadListeners = null;
2546 if (listeners && listeners.length > 0) {
2547 j = listeners.length;
2550 l = listeners[index];
2552 EU.removeListener(l[EU.EL], l[EU.TYPE],
2562 EU.doRemove(window, "unload", EU._unload);
2567 getScroll: function() {
2568 var dd = document.documentElement, db = document.body;
2569 if (dd && (dd.scrollTop || dd.scrollLeft)) {
2570 return [dd.scrollTop, dd.scrollLeft];
2572 return [db.scrollTop, db.scrollLeft];
2579 doAdd: function () {
2580 if (window.addEventListener) {
2581 return function(el, eventName, fn, capture) {
2582 el.addEventListener(eventName, fn, (capture));
2584 } else if (window.attachEvent) {
2585 return function(el, eventName, fn, capture) {
2586 el.attachEvent("on" + eventName, fn);
2595 doRemove: function() {
2596 if (window.removeEventListener) {
2597 return function (el, eventName, fn, capture) {
2598 el.removeEventListener(eventName, fn, (capture));
2600 } else if (window.detachEvent) {
2601 return function (el, eventName, fn) {
2602 el.detachEvent("on" + eventName, fn);
2614 var E = Roo.lib.Event;
2615 E.on = E.addListener;
2616 E.un = E.removeListener;
2618 if (document && document.body) {
2621 E.doAdd(window, "load", E._load);
2623 E.doAdd(window, "unload", E._unload);
2624 E._tryPreloadAttach();
2631 * @class Roo.lib.Ajax
2633 * provide a simple Ajax request utility functions
2635 * Portions of this file are based on pieces of Yahoo User Interface Library
2636 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
2637 * YUI licensed under the BSD License:
2638 * http://developer.yahoo.net/yui/license.txt
2639 * <script type="text/javascript">
2647 request : function(method, uri, cb, data, options) {
2649 var hs = options.headers;
2652 if(hs.hasOwnProperty(h)){
2653 this.initHeader(h, hs[h], false);
2657 if(options.xmlData){
2658 this.initHeader('Content-Type', 'text/xml', false);
2660 data = options.xmlData;
2664 return this.asyncRequest(method, uri, cb, data);
2670 * @param {DomForm} form element
2671 * @return {String} urlencode form output.
2673 serializeForm : function(form) {
2674 if(typeof form == 'string') {
2675 form = (document.getElementById(form) || document.forms[form]);
2678 var el, name, val, disabled, data = '', hasSubmit = false;
2679 for (var i = 0; i < form.elements.length; i++) {
2680 el = form.elements[i];
2681 disabled = form.elements[i].disabled;
2682 name = form.elements[i].name;
2683 val = form.elements[i].value;
2685 if (!disabled && name){
2689 case 'select-multiple':
2690 for (var j = 0; j < el.options.length; j++) {
2691 if (el.options[j].selected) {
2693 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(el.options[j].attributes['value'].specified ? el.options[j].value : el.options[j].text) + '&';
2696 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(el.options[j].hasAttribute('value') ? el.options[j].value : el.options[j].text) + '&';
2704 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2717 if(hasSubmit == false) {
2718 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2723 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2728 data = data.substr(0, data.length - 1);
2736 useDefaultHeader:true,
2738 defaultPostHeader:'application/x-www-form-urlencoded',
2740 useDefaultXhrHeader:true,
2742 defaultXhrHeader:'XMLHttpRequest',
2744 hasDefaultHeaders:true,
2756 setProgId:function(id)
2758 this.activeX.unshift(id);
2761 setDefaultPostHeader:function(b)
2763 this.useDefaultHeader = b;
2766 setDefaultXhrHeader:function(b)
2768 this.useDefaultXhrHeader = b;
2771 setPollingInterval:function(i)
2773 if (typeof i == 'number' && isFinite(i)) {
2774 this.pollInterval = i;
2778 createXhrObject:function(transactionId)
2784 http = new XMLHttpRequest();
2786 obj = { conn:http, tId:transactionId };
2790 for (var i = 0; i < this.activeX.length; ++i) {
2794 http = new ActiveXObject(this.activeX[i]);
2796 obj = { conn:http, tId:transactionId };
2809 getConnectionObject:function()
2812 var tId = this.transactionId;
2816 o = this.createXhrObject(tId);
2818 this.transactionId++;
2829 asyncRequest:function(method, uri, callback, postData)
2831 var o = this.getConnectionObject();
2837 o.conn.open(method, uri, true);
2839 if (this.useDefaultXhrHeader) {
2840 if (!this.defaultHeaders['X-Requested-With']) {
2841 this.initHeader('X-Requested-With', this.defaultXhrHeader, true);
2845 if(postData && this.useDefaultHeader){
2846 this.initHeader('Content-Type', this.defaultPostHeader);
2849 if (this.hasDefaultHeaders || this.hasHeaders) {
2853 this.handleReadyState(o, callback);
2854 o.conn.send(postData || null);
2860 handleReadyState:function(o, callback)
2864 if (callback && callback.timeout) {
2866 this.timeout[o.tId] = window.setTimeout(function() {
2867 oConn.abort(o, callback, true);
2868 }, callback.timeout);
2871 this.poll[o.tId] = window.setInterval(
2873 if (o.conn && o.conn.readyState == 4) {
2874 window.clearInterval(oConn.poll[o.tId]);
2875 delete oConn.poll[o.tId];
2877 if(callback && callback.timeout) {
2878 window.clearTimeout(oConn.timeout[o.tId]);
2879 delete oConn.timeout[o.tId];
2882 oConn.handleTransactionResponse(o, callback);
2885 , this.pollInterval);
2888 handleTransactionResponse:function(o, callback, isAbort)
2892 this.releaseObject(o);
2896 var httpStatus, responseObject;
2900 if (o.conn.status !== undefined && o.conn.status != 0) {
2901 httpStatus = o.conn.status;
2913 if (httpStatus >= 200 && httpStatus < 300) {
2914 responseObject = this.createResponseObject(o, callback.argument);
2915 if (callback.success) {
2916 if (!callback.scope) {
2917 callback.success(responseObject);
2922 callback.success.apply(callback.scope, [responseObject]);
2927 switch (httpStatus) {
2935 responseObject = this.createExceptionObject(o.tId, callback.argument, (isAbort ? isAbort : false));
2936 if (callback.failure) {
2937 if (!callback.scope) {
2938 callback.failure(responseObject);
2941 callback.failure.apply(callback.scope, [responseObject]);
2946 responseObject = this.createResponseObject(o, callback.argument);
2947 if (callback.failure) {
2948 if (!callback.scope) {
2949 callback.failure(responseObject);
2952 callback.failure.apply(callback.scope, [responseObject]);
2958 this.releaseObject(o);
2959 responseObject = null;
2962 createResponseObject:function(o, callbackArg)
2969 var headerStr = o.conn.getAllResponseHeaders();
2970 var header = headerStr.split('\n');
2971 for (var i = 0; i < header.length; i++) {
2972 var delimitPos = header[i].indexOf(':');
2973 if (delimitPos != -1) {
2974 headerObj[header[i].substring(0, delimitPos)] = header[i].substring(delimitPos + 2);
2982 obj.status = o.conn.status;
2983 obj.statusText = o.conn.statusText;
2984 obj.getResponseHeader = headerObj;
2985 obj.getAllResponseHeaders = headerStr;
2986 obj.responseText = o.conn.responseText;
2987 obj.responseXML = o.conn.responseXML;
2989 if (typeof callbackArg !== undefined) {
2990 obj.argument = callbackArg;
2996 createExceptionObject:function(tId, callbackArg, isAbort)
2999 var COMM_ERROR = 'communication failure';
3000 var ABORT_CODE = -1;
3001 var ABORT_ERROR = 'transaction aborted';
3007 obj.status = ABORT_CODE;
3008 obj.statusText = ABORT_ERROR;
3011 obj.status = COMM_CODE;
3012 obj.statusText = COMM_ERROR;
3016 obj.argument = callbackArg;
3022 initHeader:function(label, value, isDefault)
3024 var headerObj = (isDefault) ? this.defaultHeaders : this.headers;
3026 if (headerObj[label] === undefined) {
3027 headerObj[label] = value;
3032 headerObj[label] = value + "," + headerObj[label];
3036 this.hasDefaultHeaders = true;
3039 this.hasHeaders = true;
3044 setHeader:function(o)
3046 if (this.hasDefaultHeaders) {
3047 for (var prop in this.defaultHeaders) {
3048 if (this.defaultHeaders.hasOwnProperty(prop)) {
3049 o.conn.setRequestHeader(prop, this.defaultHeaders[prop]);
3054 if (this.hasHeaders) {
3055 for (var prop in this.headers) {
3056 if (this.headers.hasOwnProperty(prop)) {
3057 o.conn.setRequestHeader(prop, this.headers[prop]);
3061 this.hasHeaders = false;
3065 resetDefaultHeaders:function() {
3066 delete this.defaultHeaders;
3067 this.defaultHeaders = {};
3068 this.hasDefaultHeaders = false;
3071 abort:function(o, callback, isTimeout)
3073 if(this.isCallInProgress(o)) {
3075 window.clearInterval(this.poll[o.tId]);
3076 delete this.poll[o.tId];
3078 delete this.timeout[o.tId];
3081 this.handleTransactionResponse(o, callback, true);
3091 isCallInProgress:function(o)
3094 return o.conn.readyState != 4 && o.conn.readyState != 0;
3103 releaseObject:function(o)
3112 'MSXML2.XMLHTTP.3.0',
3120 * Portions of this file are based on pieces of Yahoo User Interface Library
3121 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3122 * YUI licensed under the BSD License:
3123 * http://developer.yahoo.net/yui/license.txt
3124 * <script type="text/javascript">
3128 Roo.lib.Region = function(t, r, b, l) {
3138 Roo.lib.Region.prototype = {
3139 contains : function(region) {
3140 return ( region.left >= this.left &&
3141 region.right <= this.right &&
3142 region.top >= this.top &&
3143 region.bottom <= this.bottom );
3147 getArea : function() {
3148 return ( (this.bottom - this.top) * (this.right - this.left) );
3151 intersect : function(region) {
3152 var t = Math.max(this.top, region.top);
3153 var r = Math.min(this.right, region.right);
3154 var b = Math.min(this.bottom, region.bottom);
3155 var l = Math.max(this.left, region.left);
3157 if (b >= t && r >= l) {
3158 return new Roo.lib.Region(t, r, b, l);
3163 union : function(region) {
3164 var t = Math.min(this.top, region.top);
3165 var r = Math.max(this.right, region.right);
3166 var b = Math.max(this.bottom, region.bottom);
3167 var l = Math.min(this.left, region.left);
3169 return new Roo.lib.Region(t, r, b, l);
3172 adjust : function(t, l, b, r) {
3181 Roo.lib.Region.getRegion = function(el) {
3182 var p = Roo.lib.Dom.getXY(el);
3185 var r = p[0] + el.offsetWidth;
3186 var b = p[1] + el.offsetHeight;
3189 return new Roo.lib.Region(t, r, b, l);
3192 * Portions of this file are based on pieces of Yahoo User Interface Library
3193 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3194 * YUI licensed under the BSD License:
3195 * http://developer.yahoo.net/yui/license.txt
3196 * <script type="text/javascript">
3199 //@@dep Roo.lib.Region
3202 Roo.lib.Point = function(x, y) {
3203 if (x instanceof Array) {
3207 this.x = this.right = this.left = this[0] = x;
3208 this.y = this.top = this.bottom = this[1] = y;
3211 Roo.lib.Point.prototype = new Roo.lib.Region();
3213 * Portions of this file are based on pieces of Yahoo User Interface Library
3214 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3215 * YUI licensed under the BSD License:
3216 * http://developer.yahoo.net/yui/license.txt
3217 * <script type="text/javascript">
3224 scroll : function(el, args, duration, easing, cb, scope) {
3225 this.run(el, args, duration, easing, cb, scope, Roo.lib.Scroll);
3228 motion : function(el, args, duration, easing, cb, scope) {
3229 this.run(el, args, duration, easing, cb, scope, Roo.lib.Motion);
3232 color : function(el, args, duration, easing, cb, scope) {
3233 this.run(el, args, duration, easing, cb, scope, Roo.lib.ColorAnim);
3236 run : function(el, args, duration, easing, cb, scope, type) {
3237 type = type || Roo.lib.AnimBase;
3238 if (typeof easing == "string") {
3239 easing = Roo.lib.Easing[easing];
3241 var anim = new type(el, args, duration, easing);
3242 anim.animateX(function() {
3243 Roo.callback(cb, scope);
3249 * Portions of this file are based on pieces of Yahoo User Interface Library
3250 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3251 * YUI licensed under the BSD License:
3252 * http://developer.yahoo.net/yui/license.txt
3253 * <script type="text/javascript">
3261 if (!libFlyweight) {
3262 libFlyweight = new Roo.Element.Flyweight();
3264 libFlyweight.dom = el;
3265 return libFlyweight;
3268 // since this uses fly! - it cant be in DOM (which does not have fly yet..)
3272 Roo.lib.AnimBase = function(el, attributes, duration, method) {
3274 this.init(el, attributes, duration, method);
3278 Roo.lib.AnimBase.fly = fly;
3282 Roo.lib.AnimBase.prototype = {
3284 toString: function() {
3285 var el = this.getEl();
3286 var id = el.id || el.tagName;
3287 return ("Anim " + id);
3291 noNegatives: /width|height|opacity|padding/i,
3292 offsetAttribute: /^((width|height)|(top|left))$/,
3293 defaultUnit: /width|height|top$|bottom$|left$|right$/i,
3294 offsetUnit: /\d+(em|%|en|ex|pt|in|cm|mm|pc)$/i
3298 doMethod: function(attr, start, end) {
3299 return this.method(this.currentFrame, start, end - start, this.totalFrames);
3303 setAttribute: function(attr, val, unit) {
3304 if (this.patterns.noNegatives.test(attr)) {
3305 val = (val > 0) ? val : 0;
3308 Roo.fly(this.getEl(), '_anim').setStyle(attr, val + unit);
3312 getAttribute: function(attr) {
3313 var el = this.getEl();
3314 var val = fly(el).getStyle(attr);
3316 if (val !== 'auto' && !this.patterns.offsetUnit.test(val)) {
3317 return parseFloat(val);
3320 var a = this.patterns.offsetAttribute.exec(attr) || [];
3321 var pos = !!( a[3] );
3322 var box = !!( a[2] );
3325 if (box || (fly(el).getStyle('position') == 'absolute' && pos)) {
3326 val = el['offset' + a[0].charAt(0).toUpperCase() + a[0].substr(1)];
3335 getDefaultUnit: function(attr) {
3336 if (this.patterns.defaultUnit.test(attr)) {
3343 animateX : function(callback, scope) {
3344 var f = function() {
3345 this.onComplete.removeListener(f);
3346 if (typeof callback == "function") {
3347 callback.call(scope || this, this);
3350 this.onComplete.addListener(f, this);
3355 setRuntimeAttribute: function(attr) {
3358 var attributes = this.attributes;
3360 this.runtimeAttributes[attr] = {};
3362 var isset = function(prop) {
3363 return (typeof prop !== 'undefined');
3366 if (!isset(attributes[attr]['to']) && !isset(attributes[attr]['by'])) {
3370 start = ( isset(attributes[attr]['from']) ) ? attributes[attr]['from'] : this.getAttribute(attr);
3373 if (isset(attributes[attr]['to'])) {
3374 end = attributes[attr]['to'];
3375 } else if (isset(attributes[attr]['by'])) {
3376 if (start.constructor == Array) {
3378 for (var i = 0, len = start.length; i < len; ++i) {
3379 end[i] = start[i] + attributes[attr]['by'][i];
3382 end = start + attributes[attr]['by'];
3386 this.runtimeAttributes[attr].start = start;
3387 this.runtimeAttributes[attr].end = end;
3390 this.runtimeAttributes[attr].unit = ( isset(attributes[attr].unit) ) ? attributes[attr]['unit'] : this.getDefaultUnit(attr);
3394 init: function(el, attributes, duration, method) {
3396 var isAnimated = false;
3399 var startTime = null;
3402 var actualFrames = 0;
3405 el = Roo.getDom(el);
3408 this.attributes = attributes || {};
3411 this.duration = duration || 1;
3414 this.method = method || Roo.lib.Easing.easeNone;
3417 this.useSeconds = true;
3420 this.currentFrame = 0;
3423 this.totalFrames = Roo.lib.AnimMgr.fps;
3426 this.getEl = function() {
3431 this.isAnimated = function() {
3436 this.getStartTime = function() {
3440 this.runtimeAttributes = {};
3443 this.animate = function() {
3444 if (this.isAnimated()) {
3448 this.currentFrame = 0;
3450 this.totalFrames = ( this.useSeconds ) ? Math.ceil(Roo.lib.AnimMgr.fps * this.duration) : this.duration;
3452 Roo.lib.AnimMgr.registerElement(this);
3456 this.stop = function(finish) {
3458 this.currentFrame = this.totalFrames;
3459 this._onTween.fire();
3461 Roo.lib.AnimMgr.stop(this);
3464 var onStart = function() {
3465 this.onStart.fire();
3467 this.runtimeAttributes = {};
3468 for (var attr in this.attributes) {
3469 this.setRuntimeAttribute(attr);
3474 startTime = new Date();
3478 var onTween = function() {
3480 duration: new Date() - this.getStartTime(),
3481 currentFrame: this.currentFrame
3484 data.toString = function() {
3486 'duration: ' + data.duration +
3487 ', currentFrame: ' + data.currentFrame
3491 this.onTween.fire(data);
3493 var runtimeAttributes = this.runtimeAttributes;
3495 for (var attr in runtimeAttributes) {
3496 this.setAttribute(attr, this.doMethod(attr, runtimeAttributes[attr].start, runtimeAttributes[attr].end), runtimeAttributes[attr].unit);
3502 var onComplete = function() {
3503 var actual_duration = (new Date() - startTime) / 1000 ;
3506 duration: actual_duration,
3507 frames: actualFrames,
3508 fps: actualFrames / actual_duration
3511 data.toString = function() {
3513 'duration: ' + data.duration +
3514 ', frames: ' + data.frames +
3515 ', fps: ' + data.fps
3521 this.onComplete.fire(data);
3525 this._onStart = new Roo.util.Event(this);
3526 this.onStart = new Roo.util.Event(this);
3527 this.onTween = new Roo.util.Event(this);
3528 this._onTween = new Roo.util.Event(this);
3529 this.onComplete = new Roo.util.Event(this);
3530 this._onComplete = new Roo.util.Event(this);
3531 this._onStart.addListener(onStart);
3532 this._onTween.addListener(onTween);
3533 this._onComplete.addListener(onComplete);
3538 * Portions of this file are based on pieces of Yahoo User Interface Library
3539 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3540 * YUI licensed under the BSD License:
3541 * http://developer.yahoo.net/yui/license.txt
3542 * <script type="text/javascript">
3546 Roo.lib.AnimMgr = new function() {
3563 this.registerElement = function(tween) {
3564 queue[queue.length] = tween;
3566 tween._onStart.fire();
3571 this.unRegister = function(tween, index) {
3572 tween._onComplete.fire();
3573 index = index || getIndex(tween);
3575 queue.splice(index, 1);
3579 if (tweenCount <= 0) {
3585 this.start = function() {
3586 if (thread === null) {
3587 thread = setInterval(this.run, this.delay);
3592 this.stop = function(tween) {
3594 clearInterval(thread);
3596 for (var i = 0, len = queue.length; i < len; ++i) {
3597 if (queue[0].isAnimated()) {
3598 this.unRegister(queue[0], 0);
3607 this.unRegister(tween);
3612 this.run = function() {
3613 for (var i = 0, len = queue.length; i < len; ++i) {
3614 var tween = queue[i];
3615 if (!tween || !tween.isAnimated()) {
3619 if (tween.currentFrame < tween.totalFrames || tween.totalFrames === null)
3621 tween.currentFrame += 1;
3623 if (tween.useSeconds) {
3624 correctFrame(tween);
3626 tween._onTween.fire();
3629 Roo.lib.AnimMgr.stop(tween, i);
3634 var getIndex = function(anim) {
3635 for (var i = 0, len = queue.length; i < len; ++i) {
3636 if (queue[i] == anim) {
3644 var correctFrame = function(tween) {
3645 var frames = tween.totalFrames;
3646 var frame = tween.currentFrame;
3647 var expected = (tween.currentFrame * tween.duration * 1000 / tween.totalFrames);
3648 var elapsed = (new Date() - tween.getStartTime());
3651 if (elapsed < tween.duration * 1000) {
3652 tweak = Math.round((elapsed / expected - 1) * tween.currentFrame);
3654 tweak = frames - (frame + 1);
3656 if (tweak > 0 && isFinite(tweak)) {
3657 if (tween.currentFrame + tweak >= frames) {
3658 tweak = frames - (frame + 1);
3661 tween.currentFrame += tweak;
3667 * Portions of this file are based on pieces of Yahoo User Interface Library
3668 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3669 * YUI licensed under the BSD License:
3670 * http://developer.yahoo.net/yui/license.txt
3671 * <script type="text/javascript">
3674 Roo.lib.Bezier = new function() {
3676 this.getPosition = function(points, t) {
3677 var n = points.length;
3680 for (var i = 0; i < n; ++i) {
3681 tmp[i] = [points[i][0], points[i][1]];
3684 for (var j = 1; j < n; ++j) {
3685 for (i = 0; i < n - j; ++i) {
3686 tmp[i][0] = (1 - t) * tmp[i][0] + t * tmp[parseInt(i + 1, 10)][0];
3687 tmp[i][1] = (1 - t) * tmp[i][1] + t * tmp[parseInt(i + 1, 10)][1];
3691 return [ tmp[0][0], tmp[0][1] ];
3697 * @class Roo.lib.Color
3699 * An abstract Color implementation. Concrete Color implementations should use
3700 * an instance of this function as their prototype, and implement the getRGB and
3701 * getHSL functions. getRGB should return an object representing the RGB
3702 * components of this Color, with the red, green, and blue components in the
3703 * range [0,255] and the alpha component in the range [0,100]. getHSL should
3704 * return an object representing the HSL components of this Color, with the hue
3705 * component in the range [0,360), the saturation and lightness components in
3706 * the range [0,100], and the alpha component in the range [0,1].
3711 * Functions for Color handling and processing.
3713 * http://www.safalra.com/web-design/javascript/Color-handling-and-processing/
3715 * The author of this program, Safalra (Stephen Morley), irrevocably releases all
3716 * rights to this program, with the intention of it becoming part of the public
3717 * domain. Because this program is released into the public domain, it comes with
3718 * no warranty either expressed or implied, to the extent permitted by law.
3720 * For more free and public domain JavaScript code by the same author, visit:
3721 * http://www.safalra.com/web-design/javascript/
3724 Roo.lib.Color = function() { }
3727 Roo.apply(Roo.lib.Color.prototype, {
3735 * @return {Object} an object representing the RGBA components of this Color. The red,
3736 * green, and blue components are converted to integers in the range [0,255].
3737 * The alpha is a value in the range [0,1].
3739 getIntegerRGB : function(){
3741 // get the RGB components of this Color
3742 var rgb = this.getRGB();
3744 // return the integer components
3746 'r' : Math.round(rgb.r),
3747 'g' : Math.round(rgb.g),
3748 'b' : Math.round(rgb.b),
3756 * @return {Object} an object representing the RGBA components of this Color. The red,
3757 * green, and blue components are converted to numbers in the range [0,100].
3758 * The alpha is a value in the range [0,1].
3760 getPercentageRGB : function(){
3762 // get the RGB components of this Color
3763 var rgb = this.getRGB();
3765 // return the percentage components
3767 'r' : 100 * rgb.r / 255,
3768 'g' : 100 * rgb.g / 255,
3769 'b' : 100 * rgb.b / 255,
3776 * getCSSHexadecimalRGB
3777 * @return {String} a string representing this Color as a CSS hexadecimal RGB Color
3778 * value - that is, a string of the form #RRGGBB where each of RR, GG, and BB
3779 * are two-digit hexadecimal numbers.
3781 getCSSHexadecimalRGB : function()
3784 // get the integer RGB components
3785 var rgb = this.getIntegerRGB();
3787 // determine the hexadecimal equivalents
3788 var r16 = rgb.r.toString(16);
3789 var g16 = rgb.g.toString(16);
3790 var b16 = rgb.b.toString(16);
3792 // return the CSS RGB Color value
3794 + (r16.length == 2 ? r16 : '0' + r16)
3795 + (g16.length == 2 ? g16 : '0' + g16)
3796 + (b16.length == 2 ? b16 : '0' + b16);
3802 * @return {String} a string representing this Color as a CSS integer RGB Color
3803 * value - that is, a string of the form rgb(r,g,b) where each of r, g, and b
3804 * are integers in the range [0,255].
3806 getCSSIntegerRGB : function(){
3808 // get the integer RGB components
3809 var rgb = this.getIntegerRGB();
3811 // return the CSS RGB Color value
3812 return 'rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ')';
3818 * @return {String} Returns a string representing this Color as a CSS integer RGBA Color
3819 * value - that is, a string of the form rgba(r,g,b,a) where each of r, g, and
3820 * b are integers in the range [0,255] and a is in the range [0,1].
3822 getCSSIntegerRGBA : function(){
3824 // get the integer RGB components
3825 var rgb = this.getIntegerRGB();
3827 // return the CSS integer RGBA Color value
3828 return 'rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + rgb.a + ')';
3833 * getCSSPercentageRGB
3834 * @return {String} a string representing this Color as a CSS percentage RGB Color
3835 * value - that is, a string of the form rgb(r%,g%,b%) where each of r, g, and
3836 * b are in the range [0,100].
3838 getCSSPercentageRGB : function(){
3840 // get the percentage RGB components
3841 var rgb = this.getPercentageRGB();
3843 // return the CSS RGB Color value
3844 return 'rgb(' + rgb.r + '%,' + rgb.g + '%,' + rgb.b + '%)';
3849 * getCSSPercentageRGBA
3850 * @return {String} a string representing this Color as a CSS percentage RGBA Color
3851 * value - that is, a string of the form rgba(r%,g%,b%,a) where each of r, g,
3852 * and b are in the range [0,100] and a is in the range [0,1].
3854 getCSSPercentageRGBA : function(){
3856 // get the percentage RGB components
3857 var rgb = this.getPercentageRGB();
3859 // return the CSS percentage RGBA Color value
3860 return 'rgb(' + rgb.r + '%,' + rgb.g + '%,' + rgb.b + '%,' + rgb.a + ')';
3866 * @return {String} a string representing this Color as a CSS HSL Color value - that
3867 * is, a string of the form hsl(h,s%,l%) where h is in the range [0,100] and
3868 * s and l are in the range [0,100].
3870 getCSSHSL : function(){
3872 // get the HSL components
3873 var hsl = this.getHSL();
3875 // return the CSS HSL Color value
3876 return 'hsl(' + hsl.h + ',' + hsl.s + '%,' + hsl.l + '%)';
3882 * @return {String} a string representing this Color as a CSS HSLA Color value - that
3883 * is, a string of the form hsla(h,s%,l%,a) where h is in the range [0,100],
3884 * s and l are in the range [0,100], and a is in the range [0,1].
3886 getCSSHSLA : function(){
3888 // get the HSL components
3889 var hsl = this.getHSL();
3891 // return the CSS HSL Color value
3892 return 'hsl(' + hsl.h + ',' + hsl.s + '%,' + hsl.l + '%,' + hsl.a + ')';
3897 * Sets the Color of the specified node to this Color. This functions sets
3898 * the CSS 'color' property for the node. The parameter is:
3900 * @param {DomElement} node - the node whose Color should be set
3902 setNodeColor : function(node){
3904 // set the Color of the node
3905 node.style.color = this.getCSSHexadecimalRGB();
3910 * Sets the background Color of the specified node to this Color. This
3911 * functions sets the CSS 'background-color' property for the node. The
3914 * @param {DomElement} node - the node whose background Color should be set
3916 setNodeBackgroundColor : function(node){
3918 // set the background Color of the node
3919 node.style.backgroundColor = this.getCSSHexadecimalRGB();
3922 // convert between formats..
3925 var r = this.getIntegerRGB();
3926 return new Roo.lib.RGBColor(r.r,r.g,r.b,r.a);
3931 var hsl = this.getHSL();
3932 // return the CSS HSL Color value
3933 return new Roo.lib.HSLColor(hsl.h, hsl.s, hsl.l , hsl.a );
3939 var rgb = this.toRGB();
3940 var hsv = rgb.getHSV();
3941 // return the CSS HSL Color value
3942 return new Roo.lib.HSVColor(hsv.h, hsv.s, hsv.v , hsv.a );
3946 // modify v = 0 ... 1 (eg. 0.5)
3947 saturate : function(v)
3949 var rgb = this.toRGB();
3950 var hsv = rgb.getHSV();
3951 return new Roo.lib.HSVColor(hsv.h, hsv.s * v, hsv.v , hsv.a );
3959 * @return {Object} the RGB and alpha components of this Color as an object with r,
3960 * g, b, and a properties. r, g, and b are in the range [0,255] and a is in
3965 // return the RGB components
3977 * @return {Object} the HSV and alpha components of this Color as an object with h,
3978 * s, v, and a properties. h is in the range [0,360), s and v are in the range
3979 * [0,100], and a is in the range [0,1].
3984 // calculate the HSV components if necessary
3985 if (this.hsv == null) {
3986 this.calculateHSV();
3989 // return the HSV components
4001 * @return {Object} the HSL and alpha components of this Color as an object with h,
4002 * s, l, and a properties. h is in the range [0,360), s and l are in the range
4003 * [0,100], and a is in the range [0,1].
4005 getHSL : function(){
4008 // calculate the HSV components if necessary
4009 if (this.hsl == null) { this.calculateHSL(); }
4011 // return the HSL components
4026 * @class Roo.lib.RGBColor
4027 * @extends Roo.lib.Color
4028 * Creates a Color specified in the RGB Color space, with an optional alpha
4029 * component. The parameters are:
4033 * @param {Number} r - the red component, clipped to the range [0,255]
4034 * @param {Number} g - the green component, clipped to the range [0,255]
4035 * @param {Number} b - the blue component, clipped to the range [0,255]
4036 * @param {Number} a - the alpha component, clipped to the range [0,1] - this parameter is
4037 * optional and defaults to 1
4039 Roo.lib.RGBColor = function (r, g, b, a){
4041 // store the alpha component after clipping it if necessary
4042 this.alpha = (a === undefined ? 1 : Math.max(0, Math.min(1, a)));
4044 // store the RGB components after clipping them if necessary
4047 'r' : Math.max(0, Math.min(255, r)),
4048 'g' : Math.max(0, Math.min(255, g)),
4049 'b' : Math.max(0, Math.min(255, b))
4052 // initialise the HSV and HSL components to null
4056 * //private returns the HSV or HSL hue component of this RGBColor. The hue is in the
4057 * range [0,360). The parameters are:
4059 * maximum - the maximum of the RGB component values
4060 * range - the range of the RGB component values
4065 // this does an 'exteds'
4066 Roo.extend(Roo.lib.RGBColor, Roo.lib.Color, {
4069 getHue : function(maximum, range)
4073 // check whether the range is zero
4076 // set the hue to zero (any hue is acceptable as the Color is grey)
4081 // determine which of the components has the highest value and set the hue
4084 // red has the highest value
4086 var hue = (rgb.g - rgb.b) / range * 60;
4087 if (hue < 0) { hue += 360; }
4090 // green has the highest value
4092 var hue = (rgb.b - rgb.r) / range * 60 + 120;
4095 // blue has the highest value
4097 var hue = (rgb.r - rgb.g) / range * 60 + 240;
4109 /* //private Calculates and stores the HSV components of this RGBColor so that they can
4110 * be returned be the getHSV function.
4112 calculateHSV : function(){
4114 // get the maximum and range of the RGB component values
4115 var maximum = Math.max(rgb.r, rgb.g, rgb.b);
4116 var range = maximum - Math.min(rgb.r, rgb.g, rgb.b);
4118 // store the HSV components
4121 'h' : this.getHue(maximum, range),
4122 's' : (maximum == 0 ? 0 : 100 * range / maximum),
4123 'v' : maximum / 2.55
4128 /* //private Calculates and stores the HSL components of this RGBColor so that they can
4129 * be returned be the getHSL function.
4131 calculateHSL : function(){
4133 // get the maximum and range of the RGB component values
4134 var maximum = Math.max(rgb.r, rgb.g, rgb.b);
4135 var range = maximum - Math.min(rgb.r, rgb.g, rgb.b);
4137 // determine the lightness in the range [0,1]
4138 var l = maximum / 255 - range / 510;
4140 // store the HSL components
4143 'h' : this.getHue(maximum, range),
4144 's' : (range == 0 ? 0 : range / 2.55 / (l < 0.5 ? l * 2 : 2 - l * 2)),
4153 * @class Roo.lib.HSVColor
4154 * @extends Roo.lib.Color
4155 * Creates a Color specified in the HSV Color space, with an optional alpha
4156 * component. The parameters are:
4159 * @param {Number} h - the hue component, wrapped to the range [0,360)
4160 * @param {Number} s - the saturation component, clipped to the range [0,100]
4161 * @param {Number} v - the value component, clipped to the range [0,100]
4162 * @param {Number} a - the alpha component, clipped to the range [0,1] - this parameter is
4163 * optional and defaults to 1
4165 Roo.lib.HSVColor = function (h, s, v, a){
4167 // store the alpha component after clipping it if necessary
4168 this.alpha = (a === undefined ? 1 : Math.max(0, Math.min(1, a)));
4170 // store the HSV components after clipping or wrapping them if necessary
4173 'h' : (h % 360 + 360) % 360,
4174 's' : Math.max(0, Math.min(100, s)),
4175 'v' : Math.max(0, Math.min(100, v))
4178 // initialise the RGB and HSL components to null
4183 Roo.extend(Roo.lib.HSVColor, Roo.lib.Color, {
4184 /* Calculates and stores the RGB components of this HSVColor so that they can
4185 * be returned be the getRGB function.
4187 calculateRGB: function ()
4190 // check whether the saturation is zero
4193 // set the Color to the appropriate shade of grey
4200 // set some temporary values
4201 var f = hsv.h / 60 - Math.floor(hsv.h / 60);
4202 var p = hsv.v * (1 - hsv.s / 100);
4203 var q = hsv.v * (1 - hsv.s / 100 * f);
4204 var t = hsv.v * (1 - hsv.s / 100 * (1 - f));
4206 // set the RGB Color components to their temporary values
4207 switch (Math.floor(hsv.h / 60)){
4208 case 0: var r = hsv.v; var g = t; var b = p; break;
4209 case 1: var r = q; var g = hsv.v; var b = p; break;
4210 case 2: var r = p; var g = hsv.v; var b = t; break;
4211 case 3: var r = p; var g = q; var b = hsv.v; break;
4212 case 4: var r = t; var g = p; var b = hsv.v; break;
4213 case 5: var r = hsv.v; var g = p; var b = q; break;
4218 // store the RGB components
4228 /* Calculates and stores the HSL components of this HSVColor so that they can
4229 * be returned be the getHSL function.
4231 calculateHSL : function (){
4234 // determine the lightness in the range [0,100]
4235 var l = (2 - hsv.s / 100) * hsv.v / 2;
4237 // store the HSL components
4241 's' : hsv.s * hsv.v / (l < 50 ? l * 2 : 200 - l * 2),
4245 // correct a division-by-zero error
4246 if (isNaN(hsl.s)) { hsl.s = 0; }
4255 * @class Roo.lib.HSLColor
4256 * @extends Roo.lib.Color
4259 * Creates a Color specified in the HSL Color space, with an optional alpha
4260 * component. The parameters are:
4262 * @param {Number} h - the hue component, wrapped to the range [0,360)
4263 * @param {Number} s - the saturation component, clipped to the range [0,100]
4264 * @param {Number} l - the lightness component, clipped to the range [0,100]
4265 * @param {Number} a - the alpha component, clipped to the range [0,1] - this parameter is
4266 * optional and defaults to 1
4269 Roo.lib.HSLColor = function(h, s, l, a){
4271 // store the alpha component after clipping it if necessary
4272 this.alpha = (a === undefined ? 1 : Math.max(0, Math.min(1, a)));
4274 // store the HSL components after clipping or wrapping them if necessary
4277 'h' : (h % 360 + 360) % 360,
4278 's' : Math.max(0, Math.min(100, s)),
4279 'l' : Math.max(0, Math.min(100, l))
4282 // initialise the RGB and HSV components to null
4285 Roo.extend(Roo.lib.HSLColor, Roo.lib.Color, {
4287 /* Calculates and stores the RGB components of this HSLColor so that they can
4288 * be returned be the getRGB function.
4290 calculateRGB: function (){
4292 // check whether the saturation is zero
4293 if (this.hsl.s == 0){
4295 // store the RGB components representing the appropriate shade of grey
4298 'r' : this.hsl.l * 2.55,
4299 'g' : this.hsl.l * 2.55,
4300 'b' : this.hsl.l * 2.55
4305 // set some temporary values
4306 var p = this.hsl.l < 50
4307 ? this.hsl.l * (1 + hsl.s / 100)
4308 : this.hsl.l + hsl.s - hsl.l * hsl.s / 100;
4309 var q = 2 * hsl.l - p;
4311 // initialise the RGB components
4314 'r' : (h + 120) / 60 % 6,
4316 'b' : (h + 240) / 60 % 6
4319 // loop over the RGB components
4320 for (var key in this.rgb){
4322 // ensure that the property is not inherited from the root object
4323 if (this.rgb.hasOwnProperty(key)){
4325 // set the component to its value in the range [0,100]
4326 if (this.rgb[key] < 1){
4327 this.rgb[key] = q + (p - q) * this.rgb[key];
4328 }else if (this.rgb[key] < 3){
4330 }else if (this.rgb[key] < 4){
4331 this.rgb[key] = q + (p - q) * (4 - this.rgb[key]);
4336 // set the component to its value in the range [0,255]
4337 this.rgb[key] *= 2.55;
4347 /* Calculates and stores the HSV components of this HSLColor so that they can
4348 * be returned be the getHSL function.
4350 calculateHSV : function(){
4352 // set a temporary value
4353 var t = this.hsl.s * (this.hsl.l < 50 ? this.hsl.l : 100 - this.hsl.l) / 100;
4355 // store the HSV components
4359 's' : 200 * t / (this.hsl.l + t),
4360 'v' : t + this.hsl.l
4363 // correct a division-by-zero error
4364 if (isNaN(this.hsv.s)) { this.hsv.s = 0; }
4371 * Portions of this file are based on pieces of Yahoo User Interface Library
4372 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
4373 * YUI licensed under the BSD License:
4374 * http://developer.yahoo.net/yui/license.txt
4375 * <script type="text/javascript">
4380 Roo.lib.ColorAnim = function(el, attributes, duration, method) {
4381 Roo.lib.ColorAnim.superclass.constructor.call(this, el, attributes, duration, method);
4384 Roo.extend(Roo.lib.ColorAnim, Roo.lib.AnimBase);
4386 var fly = Roo.lib.AnimBase.fly;
4388 var superclass = Y.ColorAnim.superclass;
4389 var proto = Y.ColorAnim.prototype;
4391 proto.toString = function() {
4392 var el = this.getEl();
4393 var id = el.id || el.tagName;
4394 return ("ColorAnim " + id);
4397 proto.patterns.color = /color$/i;
4398 proto.patterns.rgb = /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i;
4399 proto.patterns.hex = /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i;
4400 proto.patterns.hex3 = /^#?([0-9A-F]{1})([0-9A-F]{1})([0-9A-F]{1})$/i;
4401 proto.patterns.transparent = /^transparent|rgba\(0, 0, 0, 0\)$/;
4404 proto.parseColor = function(s) {
4405 if (s.length == 3) {
4409 var c = this.patterns.hex.exec(s);
4410 if (c && c.length == 4) {
4411 return [ parseInt(c[1], 16), parseInt(c[2], 16), parseInt(c[3], 16) ];
4414 c = this.patterns.rgb.exec(s);
4415 if (c && c.length == 4) {
4416 return [ parseInt(c[1], 10), parseInt(c[2], 10), parseInt(c[3], 10) ];
4419 c = this.patterns.hex3.exec(s);
4420 if (c && c.length == 4) {
4421 return [ parseInt(c[1] + c[1], 16), parseInt(c[2] + c[2], 16), parseInt(c[3] + c[3], 16) ];
4426 // since this uses fly! - it cant be in ColorAnim (which does not have fly yet..)
4427 proto.getAttribute = function(attr) {
4428 var el = this.getEl();
4429 if (this.patterns.color.test(attr)) {
4430 var val = fly(el).getStyle(attr);
4432 if (this.patterns.transparent.test(val)) {
4433 var parent = el.parentNode;
4434 val = fly(parent).getStyle(attr);
4436 while (parent && this.patterns.transparent.test(val)) {
4437 parent = parent.parentNode;
4438 val = fly(parent).getStyle(attr);
4439 if (parent.tagName.toUpperCase() == 'HTML') {
4445 val = superclass.getAttribute.call(this, attr);
4450 proto.getAttribute = function(attr) {
4451 var el = this.getEl();
4452 if (this.patterns.color.test(attr)) {
4453 var val = fly(el).getStyle(attr);
4455 if (this.patterns.transparent.test(val)) {
4456 var parent = el.parentNode;
4457 val = fly(parent).getStyle(attr);
4459 while (parent && this.patterns.transparent.test(val)) {
4460 parent = parent.parentNode;
4461 val = fly(parent).getStyle(attr);
4462 if (parent.tagName.toUpperCase() == 'HTML') {
4468 val = superclass.getAttribute.call(this, attr);
4474 proto.doMethod = function(attr, start, end) {
4477 if (this.patterns.color.test(attr)) {
4479 for (var i = 0, len = start.length; i < len; ++i) {
4480 val[i] = superclass.doMethod.call(this, attr, start[i], end[i]);
4483 val = 'rgb(' + Math.floor(val[0]) + ',' + Math.floor(val[1]) + ',' + Math.floor(val[2]) + ')';
4486 val = superclass.doMethod.call(this, attr, start, end);
4492 proto.setRuntimeAttribute = function(attr) {
4493 superclass.setRuntimeAttribute.call(this, attr);
4495 if (this.patterns.color.test(attr)) {
4496 var attributes = this.attributes;
4497 var start = this.parseColor(this.runtimeAttributes[attr].start);
4498 var end = this.parseColor(this.runtimeAttributes[attr].end);
4500 if (typeof attributes[attr]['to'] === 'undefined' && typeof attributes[attr]['by'] !== 'undefined') {
4501 end = this.parseColor(attributes[attr].by);
4503 for (var i = 0, len = start.length; i < len; ++i) {
4504 end[i] = start[i] + end[i];
4508 this.runtimeAttributes[attr].start = start;
4509 this.runtimeAttributes[attr].end = end;
4515 * Portions of this file are based on pieces of Yahoo User Interface Library
4516 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
4517 * YUI licensed under the BSD License:
4518 * http://developer.yahoo.net/yui/license.txt
4519 * <script type="text/javascript">
4525 easeNone: function (t, b, c, d) {
4526 return c * t / d + b;
4530 easeIn: function (t, b, c, d) {
4531 return c * (t /= d) * t + b;
4535 easeOut: function (t, b, c, d) {
4536 return -c * (t /= d) * (t - 2) + b;
4540 easeBoth: function (t, b, c, d) {
4541 if ((t /= d / 2) < 1) {
4542 return c / 2 * t * t + b;
4545 return -c / 2 * ((--t) * (t - 2) - 1) + b;
4549 easeInStrong: function (t, b, c, d) {
4550 return c * (t /= d) * t * t * t + b;
4554 easeOutStrong: function (t, b, c, d) {
4555 return -c * ((t = t / d - 1) * t * t * t - 1) + b;
4559 easeBothStrong: function (t, b, c, d) {
4560 if ((t /= d / 2) < 1) {
4561 return c / 2 * t * t * t * t + b;
4564 return -c / 2 * ((t -= 2) * t * t * t - 2) + b;
4569 elasticIn: function (t, b, c, d, a, p) {
4573 if ((t /= d) == 1) {
4580 if (!a || a < Math.abs(c)) {
4585 var s = p / (2 * Math.PI) * Math.asin(c / a);
4588 return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
4592 elasticOut: function (t, b, c, d, a, p) {
4596 if ((t /= d) == 1) {
4603 if (!a || a < Math.abs(c)) {
4608 var s = p / (2 * Math.PI) * Math.asin(c / a);
4611 return a * Math.pow(2, -10 * t) * Math.sin((t * d - s) * (2 * Math.PI) / p) + c + b;
4615 elasticBoth: function (t, b, c, d, a, p) {
4620 if ((t /= d / 2) == 2) {
4628 if (!a || a < Math.abs(c)) {
4633 var s = p / (2 * Math.PI) * Math.asin(c / a);
4637 return -.5 * (a * Math.pow(2, 10 * (t -= 1)) *
4638 Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
4640 return a * Math.pow(2, -10 * (t -= 1)) *
4641 Math.sin((t * d - s) * (2 * Math.PI) / p) * .5 + c + b;
4646 backIn: function (t, b, c, d, s) {
4647 if (typeof s == 'undefined') {
4650 return c * (t /= d) * t * ((s + 1) * t - s) + b;
4654 backOut: function (t, b, c, d, s) {
4655 if (typeof s == 'undefined') {
4658 return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
4662 backBoth: function (t, b, c, d, s) {
4663 if (typeof s == 'undefined') {
4667 if ((t /= d / 2 ) < 1) {
4668 return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b;
4670 return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;
4674 bounceIn: function (t, b, c, d) {
4675 return c - Roo.lib.Easing.bounceOut(d - t, 0, c, d) + b;
4679 bounceOut: function (t, b, c, d) {
4680 if ((t /= d) < (1 / 2.75)) {
4681 return c * (7.5625 * t * t) + b;
4682 } else if (t < (2 / 2.75)) {
4683 return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b;
4684 } else if (t < (2.5 / 2.75)) {
4685 return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b;
4687 return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b;
4691 bounceBoth: function (t, b, c, d) {
4693 return Roo.lib.Easing.bounceIn(t * 2, 0, c, d) * .5 + b;
4695 return Roo.lib.Easing.bounceOut(t * 2 - d, 0, c, d) * .5 + c * .5 + b;
4698 * Portions of this file are based on pieces of Yahoo User Interface Library
4699 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
4700 * YUI licensed under the BSD License:
4701 * http://developer.yahoo.net/yui/license.txt
4702 * <script type="text/javascript">
4706 Roo.lib.Motion = function(el, attributes, duration, method) {
4708 Roo.lib.Motion.superclass.constructor.call(this, el, attributes, duration, method);
4712 Roo.extend(Roo.lib.Motion, Roo.lib.ColorAnim);
4716 var superclass = Y.Motion.superclass;
4717 var proto = Y.Motion.prototype;
4719 proto.toString = function() {
4720 var el = this.getEl();
4721 var id = el.id || el.tagName;
4722 return ("Motion " + id);
4725 proto.patterns.points = /^points$/i;
4727 proto.setAttribute = function(attr, val, unit) {
4728 if (this.patterns.points.test(attr)) {
4729 unit = unit || 'px';
4730 superclass.setAttribute.call(this, 'left', val[0], unit);
4731 superclass.setAttribute.call(this, 'top', val[1], unit);
4733 superclass.setAttribute.call(this, attr, val, unit);
4737 proto.getAttribute = function(attr) {
4738 if (this.patterns.points.test(attr)) {
4740 superclass.getAttribute.call(this, 'left'),
4741 superclass.getAttribute.call(this, 'top')
4744 val = superclass.getAttribute.call(this, attr);
4750 proto.doMethod = function(attr, start, end) {
4753 if (this.patterns.points.test(attr)) {
4754 var t = this.method(this.currentFrame, 0, 100, this.totalFrames) / 100;
4755 val = Y.Bezier.getPosition(this.runtimeAttributes[attr], t);
4757 val = superclass.doMethod.call(this, attr, start, end);
4762 proto.setRuntimeAttribute = function(attr) {
4763 if (this.patterns.points.test(attr)) {
4764 var el = this.getEl();
4765 var attributes = this.attributes;
4767 var control = attributes['points']['control'] || [];
4771 if (control.length > 0 && !(control[0] instanceof Array)) {
4772 control = [control];
4775 for (i = 0,len = control.length; i < len; ++i) {
4776 tmp[i] = control[i];
4781 Roo.fly(el).position();
4783 if (isset(attributes['points']['from'])) {
4784 Roo.lib.Dom.setXY(el, attributes['points']['from']);
4787 Roo.lib.Dom.setXY(el, Roo.lib.Dom.getXY(el));
4790 start = this.getAttribute('points');
4793 if (isset(attributes['points']['to'])) {
4794 end = translateValues.call(this, attributes['points']['to'], start);
4796 var pageXY = Roo.lib.Dom.getXY(this.getEl());
4797 for (i = 0,len = control.length; i < len; ++i) {
4798 control[i] = translateValues.call(this, control[i], start);
4802 } else if (isset(attributes['points']['by'])) {
4803 end = [ start[0] + attributes['points']['by'][0], start[1] + attributes['points']['by'][1] ];
4805 for (i = 0,len = control.length; i < len; ++i) {
4806 control[i] = [ start[0] + control[i][0], start[1] + control[i][1] ];
4810 this.runtimeAttributes[attr] = [start];
4812 if (control.length > 0) {
4813 this.runtimeAttributes[attr] = this.runtimeAttributes[attr].concat(control);
4816 this.runtimeAttributes[attr][this.runtimeAttributes[attr].length] = end;
4819 superclass.setRuntimeAttribute.call(this, attr);
4823 var translateValues = function(val, start) {
4824 var pageXY = Roo.lib.Dom.getXY(this.getEl());
4825 val = [ val[0] - pageXY[0] + start[0], val[1] - pageXY[1] + start[1] ];
4830 var isset = function(prop) {
4831 return (typeof prop !== 'undefined');
4835 * Portions of this file are based on pieces of Yahoo User Interface Library
4836 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
4837 * YUI licensed under the BSD License:
4838 * http://developer.yahoo.net/yui/license.txt
4839 * <script type="text/javascript">
4843 Roo.lib.Scroll = function(el, attributes, duration, method) {
4845 Roo.lib.Scroll.superclass.constructor.call(this, el, attributes, duration, method);
4849 Roo.extend(Roo.lib.Scroll, Roo.lib.ColorAnim);
4853 var superclass = Y.Scroll.superclass;
4854 var proto = Y.Scroll.prototype;
4856 proto.toString = function() {
4857 var el = this.getEl();
4858 var id = el.id || el.tagName;
4859 return ("Scroll " + id);
4862 proto.doMethod = function(attr, start, end) {
4865 if (attr == 'scroll') {
4867 this.method(this.currentFrame, start[0], end[0] - start[0], this.totalFrames),
4868 this.method(this.currentFrame, start[1], end[1] - start[1], this.totalFrames)
4872 val = superclass.doMethod.call(this, attr, start, end);
4877 proto.getAttribute = function(attr) {
4879 var el = this.getEl();
4881 if (attr == 'scroll') {
4882 val = [ el.scrollLeft, el.scrollTop ];
4884 val = superclass.getAttribute.call(this, attr);
4890 proto.setAttribute = function(attr, val, unit) {
4891 var el = this.getEl();
4893 if (attr == 'scroll') {
4894 el.scrollLeft = val[0];
4895 el.scrollTop = val[1];
4897 superclass.setAttribute.call(this, attr, val, unit);
4903 * Ext JS Library 1.1.1
4904 * Copyright(c) 2006-2007, Ext JS, LLC.
4906 * Originally Released Under LGPL - original licence link has changed is not relivant.
4909 * <script type="text/javascript">
4913 // nasty IE9 hack - what a pile of crap that is..
4915 if (typeof Range != "undefined" && typeof Range.prototype.createContextualFragment == "undefined") {
4916 Range.prototype.createContextualFragment = function (html) {
4917 var doc = window.document;
4918 var container = doc.createElement("div");
4919 container.innerHTML = html;
4920 var frag = doc.createDocumentFragment(), n;
4921 while ((n = container.firstChild)) {
4922 frag.appendChild(n);
4929 * @class Roo.DomHelper
4930 * Utility class for working with DOM and/or Templates. It transparently supports using HTML fragments or DOM.
4931 * 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>.
4934 Roo.DomHelper = function(){
4935 var tempTableEl = null;
4936 var emptyTags = /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i;
4937 var tableRe = /^table|tbody|tr|td$/i;
4939 // build as innerHTML where available
4941 var createHtml = function(o){
4942 if(typeof o == 'string'){
4951 if(attr == "tag" || attr == "children" || attr == "cn" || attr == "html" || typeof o[attr] == "function") { continue; }
4952 if(attr == "style"){
4954 if(typeof s == "function"){
4957 if(typeof s == "string"){
4958 b += ' style="' + s + '"';
4959 }else if(typeof s == "object"){
4962 if(typeof s[key] != "function"){
4963 b += key + ":" + s[key] + ";";
4970 b += ' class="' + o["cls"] + '"';
4971 }else if(attr == "htmlFor"){
4972 b += ' for="' + o["htmlFor"] + '"';
4974 b += " " + attr + '="' + o[attr] + '"';
4978 if(emptyTags.test(o.tag)){
4982 var cn = o.children || o.cn;
4984 //http://bugs.kde.org/show_bug.cgi?id=71506
4985 if((cn instanceof Array) || (Roo.isSafari && typeof(cn.join) == "function")){
4986 for(var i = 0, len = cn.length; i < len; i++) {
4987 b += createHtml(cn[i], b);
4990 b += createHtml(cn, b);
4996 b += "</" + o.tag + ">";
5003 var createDom = function(o, parentNode){
5005 // defininition craeted..
5007 if (o.ns && o.ns != 'html') {
5009 if (o.xmlns && typeof(xmlns[o.ns]) == 'undefined') {
5010 xmlns[o.ns] = o.xmlns;
5013 if (typeof(xmlns[o.ns]) == 'undefined') {
5014 console.log("Trying to create namespace element " + o.ns + ", however no xmlns was sent to builder previously");
5020 if (typeof(o) == 'string') {
5021 return parentNode.appendChild(document.createTextNode(o));
5023 o.tag = o.tag || div;
5024 if (o.ns && Roo.isIE) {
5026 o.tag = o.ns + ':' + o.tag;
5029 var el = ns ? document.createElementNS( ns, o.tag||'div') : document.createElement(o.tag||'div');
5030 var useSet = el.setAttribute ? true : false; // In IE some elements don't have setAttribute
5033 if(attr == "tag" || attr == "ns" ||attr == "xmlns" ||attr == "children" || attr == "cn" || attr == "html" ||
5034 attr == "style" || typeof o[attr] == "function") { continue; }
5036 if(attr=="cls" && Roo.isIE){
5037 el.className = o["cls"];
5039 if(useSet) { el.setAttribute(attr=="cls" ? 'class' : attr, o[attr]);}
5045 Roo.DomHelper.applyStyles(el, o.style);
5046 var cn = o.children || o.cn;
5048 //http://bugs.kde.org/show_bug.cgi?id=71506
5049 if((cn instanceof Array) || (Roo.isSafari && typeof(cn.join) == "function")){
5050 for(var i = 0, len = cn.length; i < len; i++) {
5051 createDom(cn[i], el);
5058 el.innerHTML = o.html;
5061 parentNode.appendChild(el);
5066 var ieTable = function(depth, s, h, e){
5067 tempTableEl.innerHTML = [s, h, e].join('');
5068 var i = -1, el = tempTableEl;
5069 while(++i < depth && el.firstChild){
5075 // kill repeat to save bytes
5079 tbe = '</tbody>'+te,
5085 * Nasty code for IE's broken table implementation
5087 var insertIntoTable = function(tag, where, el, html){
5089 tempTableEl = document.createElement('div');
5094 if(where == 'afterbegin' || where == 'beforeend'){ // INTO a TD
5097 if(where == 'beforebegin'){
5101 before = el.nextSibling;
5104 node = ieTable(4, trs, html, tre);
5106 else if(tag == 'tr'){
5107 if(where == 'beforebegin'){
5110 node = ieTable(3, tbs, html, tbe);
5111 } else if(where == 'afterend'){
5112 before = el.nextSibling;
5114 node = ieTable(3, tbs, html, tbe);
5115 } else{ // INTO a TR
5116 if(where == 'afterbegin'){
5117 before = el.firstChild;
5119 node = ieTable(4, trs, html, tre);
5121 } else if(tag == 'tbody'){
5122 if(where == 'beforebegin'){
5125 node = ieTable(2, ts, html, te);
5126 } else if(where == 'afterend'){
5127 before = el.nextSibling;
5129 node = ieTable(2, ts, html, te);
5131 if(where == 'afterbegin'){
5132 before = el.firstChild;
5134 node = ieTable(3, tbs, html, tbe);
5137 if(where == 'beforebegin' || where == 'afterend'){ // OUTSIDE the table
5140 if(where == 'afterbegin'){
5141 before = el.firstChild;
5143 node = ieTable(2, ts, html, te);
5145 el.insertBefore(node, before);
5150 /** True to force the use of DOM instead of html fragments @type Boolean */
5154 * Returns the markup for the passed Element(s) config
5155 * @param {Object} o The Dom object spec (and children)
5158 markup : function(o){
5159 return createHtml(o);
5163 * Applies a style specification to an element
5164 * @param {String/HTMLElement} el The element to apply styles to
5165 * @param {String/Object/Function} styles A style specification string eg "width:100px", or object in the form {width:"100px"}, or
5166 * a function which returns such a specification.
5168 applyStyles : function(el, styles){
5171 if(typeof styles == "string"){
5172 var re = /\s?([a-z\-]*)\:\s?([^;]*);?/gi;
5174 while ((matches = re.exec(styles)) != null){
5175 el.setStyle(matches[1], matches[2]);
5177 }else if (typeof styles == "object"){
5178 for (var style in styles){
5179 el.setStyle(style, styles[style]);
5181 }else if (typeof styles == "function"){
5182 Roo.DomHelper.applyStyles(el, styles.call());
5188 * Inserts an HTML fragment into the Dom
5189 * @param {String} where Where to insert the html in relation to el - beforeBegin, afterBegin, beforeEnd, afterEnd.
5190 * @param {HTMLElement} el The context element
5191 * @param {String} html The HTML fragmenet
5192 * @return {HTMLElement} The new node
5194 insertHtml : function(where, el, html){
5195 where = where.toLowerCase();
5196 if(el.insertAdjacentHTML){
5197 if(tableRe.test(el.tagName)){
5199 if(rs = insertIntoTable(el.tagName.toLowerCase(), where, el, html)){
5205 el.insertAdjacentHTML('BeforeBegin', html);
5206 return el.previousSibling;
5208 el.insertAdjacentHTML('AfterBegin', html);
5209 return el.firstChild;
5211 el.insertAdjacentHTML('BeforeEnd', html);
5212 return el.lastChild;
5214 el.insertAdjacentHTML('AfterEnd', html);
5215 return el.nextSibling;
5217 throw 'Illegal insertion point -> "' + where + '"';
5219 var range = el.ownerDocument.createRange();
5223 range.setStartBefore(el);
5224 frag = range.createContextualFragment(html);
5225 el.parentNode.insertBefore(frag, el);
5226 return el.previousSibling;
5229 range.setStartBefore(el.firstChild);
5230 frag = range.createContextualFragment(html);
5231 el.insertBefore(frag, el.firstChild);
5232 return el.firstChild;
5234 el.innerHTML = html;
5235 return el.firstChild;
5239 range.setStartAfter(el.lastChild);
5240 frag = range.createContextualFragment(html);
5241 el.appendChild(frag);
5242 return el.lastChild;
5244 el.innerHTML = html;
5245 return el.lastChild;
5248 range.setStartAfter(el);
5249 frag = range.createContextualFragment(html);
5250 el.parentNode.insertBefore(frag, el.nextSibling);
5251 return el.nextSibling;
5253 throw 'Illegal insertion point -> "' + where + '"';
5257 * Creates new Dom element(s) and inserts them before el
5258 * @param {String/HTMLElement/Element} el The context element
5259 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5260 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5261 * @return {HTMLElement/Roo.Element} The new node
5263 insertBefore : function(el, o, returnElement){
5264 return this.doInsert(el, o, returnElement, "beforeBegin");
5268 * Creates new Dom element(s) and inserts them after el
5269 * @param {String/HTMLElement/Element} el The context element
5270 * @param {Object} o The Dom object spec (and children)
5271 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5272 * @return {HTMLElement/Roo.Element} The new node
5274 insertAfter : function(el, o, returnElement){
5275 return this.doInsert(el, o, returnElement, "afterEnd", "nextSibling");
5279 * Creates new Dom element(s) and inserts them as the first child of el
5280 * @param {String/HTMLElement/Element} el The context element
5281 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5282 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5283 * @return {HTMLElement/Roo.Element} The new node
5285 insertFirst : function(el, o, returnElement){
5286 return this.doInsert(el, o, returnElement, "afterBegin");
5290 doInsert : function(el, o, returnElement, pos, sibling){
5291 el = Roo.getDom(el);
5293 if(this.useDom || o.ns){
5294 newNode = createDom(o, null);
5295 el.parentNode.insertBefore(newNode, sibling ? el[sibling] : el);
5297 var html = createHtml(o);
5298 newNode = this.insertHtml(pos, el, html);
5300 return returnElement ? Roo.get(newNode, true) : newNode;
5304 * Creates new Dom element(s) and appends them to el
5305 * @param {String/HTMLElement/Element} el The context element
5306 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5307 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5308 * @return {HTMLElement/Roo.Element} The new node
5310 append : function(el, o, returnElement){
5311 el = Roo.getDom(el);
5313 if(this.useDom || o.ns){
5314 newNode = createDom(o, null);
5315 el.appendChild(newNode);
5317 var html = createHtml(o);
5318 newNode = this.insertHtml("beforeEnd", el, html);
5320 return returnElement ? Roo.get(newNode, true) : newNode;
5324 * Creates new Dom element(s) and overwrites the contents of el with them
5325 * @param {String/HTMLElement/Element} el The context element
5326 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5327 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5328 * @return {HTMLElement/Roo.Element} The new node
5330 overwrite : function(el, o, returnElement){
5331 el = Roo.getDom(el);
5334 while (el.childNodes.length) {
5335 el.removeChild(el.firstChild);
5339 el.innerHTML = createHtml(o);
5342 return returnElement ? Roo.get(el.firstChild, true) : el.firstChild;
5346 * Creates a new Roo.DomHelper.Template from the Dom object spec
5347 * @param {Object} o The Dom object spec (and children)
5348 * @return {Roo.DomHelper.Template} The new template
5350 createTemplate : function(o){
5351 var html = createHtml(o);
5352 return new Roo.Template(html);
5358 * Ext JS Library 1.1.1
5359 * Copyright(c) 2006-2007, Ext JS, LLC.
5361 * Originally Released Under LGPL - original licence link has changed is not relivant.
5364 * <script type="text/javascript">
5368 * @class Roo.Template
5369 * Represents an HTML fragment template. Templates can be precompiled for greater performance.
5370 * For a list of available format functions, see {@link Roo.util.Format}.<br />
5373 var t = new Roo.Template({
5374 html : '<div name="{id}">' +
5375 '<span class="{cls}">{name:trim} {someval:this.myformat}{value:ellipsis(10)}</span>' +
5377 myformat: function (value, allValues) {
5378 return 'XX' + value;
5381 t.append('some-element', {id: 'myid', cls: 'myclass', name: 'foo', value: 'bar'});
5383 * For more information see this blog post with examples:
5384 * <a href="http://www.cnitblog.com/seeyeah/archive/2011/12/30/38728.html/">DomHelper
5385 - Create Elements using DOM, HTML fragments and Templates</a>.
5387 * @param {Object} cfg - Configuration object.
5389 Roo.Template = function(cfg){
5391 if(cfg instanceof Array){
5393 }else if(arguments.length > 1){
5394 cfg = Array.prototype.join.call(arguments, "");
5398 if (typeof(cfg) == 'object') {
5409 Roo.Template.prototype = {
5412 * @cfg {Function} onLoad Called after the template has been loaded and complied (usually from a remove source)
5418 * @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..
5419 * it should be fixed so that template is observable...
5423 * @cfg {String} html The HTML fragment or an array of fragments to join("") or multiple arguments to join("")
5431 * Returns an HTML fragment of this template with the specified values applied.
5432 * @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'})
5433 * @return {String} The HTML fragment
5438 applyTemplate : function(values){
5439 //Roo.log(["applyTemplate", values]);
5443 return this.compiled(values);
5445 var useF = this.disableFormats !== true;
5446 var fm = Roo.util.Format, tpl = this;
5447 var fn = function(m, name, format, args){
5449 if(format.substr(0, 5) == "this."){
5450 return tpl.call(format.substr(5), values[name], values);
5453 // quoted values are required for strings in compiled templates,
5454 // but for non compiled we need to strip them
5455 // quoted reversed for jsmin
5456 var re = /^\s*['"](.*)["']\s*$/;
5457 args = args.split(',');
5458 for(var i = 0, len = args.length; i < len; i++){
5459 args[i] = args[i].replace(re, "$1");
5461 args = [values[name]].concat(args);
5463 args = [values[name]];
5465 return fm[format].apply(fm, args);
5468 return values[name] !== undefined ? values[name] : "";
5471 return this.html.replace(this.re, fn);
5489 this.loading = true;
5490 this.compiled = false;
5492 var cx = new Roo.data.Connection();
5496 success : function (response) {
5500 _t.set(response.responseText,true);
5506 failure : function(response) {
5507 Roo.log("Template failed to load from " + _t.url);
5514 * Sets the HTML used as the template and optionally compiles it.
5515 * @param {String} html
5516 * @param {Boolean} compile (optional) True to compile the template (defaults to undefined)
5517 * @return {Roo.Template} this
5519 set : function(html, compile){
5521 this.compiled = false;
5529 * True to disable format functions (defaults to false)
5532 disableFormats : false,
5535 * The regular expression used to match template variables
5539 re : /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
5542 * Compiles the template into an internal function, eliminating the RegEx overhead.
5543 * @return {Roo.Template} this
5545 compile : function(){
5546 var fm = Roo.util.Format;
5547 var useF = this.disableFormats !== true;
5548 var sep = Roo.isGecko ? "+" : ",";
5549 var fn = function(m, name, format, args){
5551 args = args ? ',' + args : "";
5552 if(format.substr(0, 5) != "this."){
5553 format = "fm." + format + '(';
5555 format = 'this.call("'+ format.substr(5) + '", ';
5559 args= ''; format = "(values['" + name + "'] == undefined ? '' : ";
5561 return "'"+ sep + format + "values['" + name + "']" + args + ")"+sep+"'";
5564 // branched to use + in gecko and [].join() in others
5566 body = "this.compiled = function(values){ return '" +
5567 this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
5570 body = ["this.compiled = function(values){ return ['"];
5571 body.push(this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn));
5572 body.push("'].join('');};");
5573 body = body.join('');
5583 // private function used to call members
5584 call : function(fnName, value, allValues){
5585 return this[fnName](value, allValues);
5589 * Applies the supplied values to the template and inserts the new node(s) as the first child of el.
5590 * @param {String/HTMLElement/Roo.Element} el The context element
5591 * @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'})
5592 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
5593 * @return {HTMLElement/Roo.Element} The new node or Element
5595 insertFirst: function(el, values, returnElement){
5596 return this.doInsert('afterBegin', el, values, returnElement);
5600 * Applies the supplied values to the template and inserts the new node(s) before el.
5601 * @param {String/HTMLElement/Roo.Element} el The context element
5602 * @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'})
5603 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
5604 * @return {HTMLElement/Roo.Element} The new node or Element
5606 insertBefore: function(el, values, returnElement){
5607 return this.doInsert('beforeBegin', el, values, returnElement);
5611 * Applies the supplied values to the template and inserts the new node(s) after el.
5612 * @param {String/HTMLElement/Roo.Element} el The context element
5613 * @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'})
5614 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
5615 * @return {HTMLElement/Roo.Element} The new node or Element
5617 insertAfter : function(el, values, returnElement){
5618 return this.doInsert('afterEnd', el, values, returnElement);
5622 * Applies the supplied values to the template and appends the new node(s) to el.
5623 * @param {String/HTMLElement/Roo.Element} el The context element
5624 * @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'})
5625 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
5626 * @return {HTMLElement/Roo.Element} The new node or Element
5628 append : function(el, values, returnElement){
5629 return this.doInsert('beforeEnd', el, values, returnElement);
5632 doInsert : function(where, el, values, returnEl){
5633 el = Roo.getDom(el);
5634 var newNode = Roo.DomHelper.insertHtml(where, el, this.applyTemplate(values));
5635 return returnEl ? Roo.get(newNode, true) : newNode;
5639 * Applies the supplied values to the template and overwrites the content of el with the new node(s).
5640 * @param {String/HTMLElement/Roo.Element} el The context element
5641 * @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'})
5642 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
5643 * @return {HTMLElement/Roo.Element} The new node or Element
5645 overwrite : function(el, values, returnElement){
5646 el = Roo.getDom(el);
5647 el.innerHTML = this.applyTemplate(values);
5648 return returnElement ? Roo.get(el.firstChild, true) : el.firstChild;
5652 * Alias for {@link #applyTemplate}
5655 Roo.Template.prototype.apply = Roo.Template.prototype.applyTemplate;
5658 Roo.DomHelper.Template = Roo.Template;
5661 * Creates a template from the passed element's value (<i>display:none</i> textarea, preferred) or innerHTML.
5662 * @param {String/HTMLElement} el A DOM element or its id
5663 * @returns {Roo.Template} The created template
5666 Roo.Template.from = function(el){
5667 el = Roo.getDom(el);
5668 return new Roo.Template(el.value || el.innerHTML);
5671 * Ext JS Library 1.1.1
5672 * Copyright(c) 2006-2007, Ext JS, LLC.
5674 * Originally Released Under LGPL - original licence link has changed is not relivant.
5677 * <script type="text/javascript">
5682 * This is code is also distributed under MIT license for use
5683 * with jQuery and prototype JavaScript libraries.
5686 * @class Roo.DomQuery
5687 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).
5689 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>
5692 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.
5694 <h4>Element Selectors:</h4>
5696 <li> <b>*</b> any element</li>
5697 <li> <b>E</b> an element with the tag E</li>
5698 <li> <b>E F</b> All descendent elements of E that have the tag F</li>
5699 <li> <b>E > F</b> or <b>E/F</b> all direct children elements of E that have the tag F</li>
5700 <li> <b>E + F</b> all elements with the tag F that are immediately preceded by an element with the tag E</li>
5701 <li> <b>E ~ F</b> all elements with the tag F that are preceded by a sibling element with the tag E</li>
5703 <h4>Attribute Selectors:</h4>
5704 <p>The use of @ and quotes are optional. For example, div[@foo='bar'] is also a valid attribute selector.</p>
5706 <li> <b>E[foo]</b> has an attribute "foo"</li>
5707 <li> <b>E[foo=bar]</b> has an attribute "foo" that equals "bar"</li>
5708 <li> <b>E[foo^=bar]</b> has an attribute "foo" that starts with "bar"</li>
5709 <li> <b>E[foo$=bar]</b> has an attribute "foo" that ends with "bar"</li>
5710 <li> <b>E[foo*=bar]</b> has an attribute "foo" that contains the substring "bar"</li>
5711 <li> <b>E[foo%=2]</b> has an attribute "foo" that is evenly divisible by 2</li>
5712 <li> <b>E[foo!=bar]</b> has an attribute "foo" that does not equal "bar"</li>
5714 <h4>Pseudo Classes:</h4>
5716 <li> <b>E:first-child</b> E is the first child of its parent</li>
5717 <li> <b>E:last-child</b> E is the last child of its parent</li>
5718 <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>
5719 <li> <b>E:nth-child(odd)</b> E is an odd child of its parent</li>
5720 <li> <b>E:nth-child(even)</b> E is an even child of its parent</li>
5721 <li> <b>E:only-child</b> E is the only child of its parent</li>
5722 <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>
5723 <li> <b>E:first</b> the first E in the resultset</li>
5724 <li> <b>E:last</b> the last E in the resultset</li>
5725 <li> <b>E:nth(<i>n</i>)</b> the <i>n</i>th E in the resultset (1 based)</li>
5726 <li> <b>E:odd</b> shortcut for :nth-child(odd)</li>
5727 <li> <b>E:even</b> shortcut for :nth-child(even)</li>
5728 <li> <b>E:contains(foo)</b> E's innerHTML contains the substring "foo"</li>
5729 <li> <b>E:nodeValue(foo)</b> E contains a textNode with a nodeValue that equals "foo"</li>
5730 <li> <b>E:not(S)</b> an E element that does not match simple selector S</li>
5731 <li> <b>E:has(S)</b> an E element that has a descendent that matches simple selector S</li>
5732 <li> <b>E:next(S)</b> an E element whose next sibling matches simple selector S</li>
5733 <li> <b>E:prev(S)</b> an E element whose previous sibling matches simple selector S</li>
5735 <h4>CSS Value Selectors:</h4>
5737 <li> <b>E{display=none}</b> css value "display" that equals "none"</li>
5738 <li> <b>E{display^=none}</b> css value "display" that starts with "none"</li>
5739 <li> <b>E{display$=none}</b> css value "display" that ends with "none"</li>
5740 <li> <b>E{display*=none}</b> css value "display" that contains the substring "none"</li>
5741 <li> <b>E{display%=2}</b> css value "display" that is evenly divisible by 2</li>
5742 <li> <b>E{display!=none}</b> css value "display" that does not equal "none"</li>
5746 Roo.DomQuery = function(){
5747 var cache = {}, simpleCache = {}, valueCache = {};
5748 var nonSpace = /\S/;
5749 var trimRe = /^\s+|\s+$/g;
5750 var tplRe = /\{(\d+)\}/g;
5751 var modeRe = /^(\s?[\/>+~]\s?|\s|$)/;
5752 var tagTokenRe = /^(#)?([\w-\*]+)/;
5753 var nthRe = /(\d*)n\+?(\d*)/, nthRe2 = /\D/;
5755 function child(p, index){
5757 var n = p.firstChild;
5759 if(n.nodeType == 1){
5770 while((n = n.nextSibling) && n.nodeType != 1);
5775 while((n = n.previousSibling) && n.nodeType != 1);
5779 function children(d){
5780 var n = d.firstChild, ni = -1;
5782 var nx = n.nextSibling;
5783 if(n.nodeType == 3 && !nonSpace.test(n.nodeValue)){
5793 function byClassName(c, a, v){
5797 var r = [], ri = -1, cn;
5798 for(var i = 0, ci; ci = c[i]; i++){
5802 ( (ci instanceof SVGElement) ? ci.className.baseVal : ci.className)
5803 +' ').indexOf(v) != -1){
5810 function attrValue(n, attr){
5811 if(!n.tagName && typeof n.length != "undefined"){
5820 if(attr == "class" || attr == "className"){
5821 return (n instanceof SVGElement) ? n.className.baseVal : n.className;
5823 return n.getAttribute(attr) || n[attr];
5827 function getNodes(ns, mode, tagName){
5828 var result = [], ri = -1, cs;
5832 tagName = tagName || "*";
5833 if(typeof ns.getElementsByTagName != "undefined"){
5837 for(var i = 0, ni; ni = ns[i]; i++){
5838 cs = ni.getElementsByTagName(tagName);
5839 for(var j = 0, ci; ci = cs[j]; j++){
5843 }else if(mode == "/" || mode == ">"){
5844 var utag = tagName.toUpperCase();
5845 for(var i = 0, ni, cn; ni = ns[i]; i++){
5846 cn = ni.children || ni.childNodes;
5847 for(var j = 0, cj; cj = cn[j]; j++){
5848 if(cj.nodeName == utag || cj.nodeName == tagName || tagName == '*'){
5853 }else if(mode == "+"){
5854 var utag = tagName.toUpperCase();
5855 for(var i = 0, n; n = ns[i]; i++){
5856 while((n = n.nextSibling) && n.nodeType != 1);
5857 if(n && (n.nodeName == utag || n.nodeName == tagName || tagName == '*')){
5861 }else if(mode == "~"){
5862 for(var i = 0, n; n = ns[i]; i++){
5863 while((n = n.nextSibling) && (n.nodeType != 1 || (tagName == '*' || n.tagName.toLowerCase()!=tagName)));
5872 function concat(a, b){
5876 for(var i = 0, l = b.length; i < l; i++){
5882 function byTag(cs, tagName){
5883 if(cs.tagName || cs == document){
5889 var r = [], ri = -1;
5890 tagName = tagName.toLowerCase();
5891 for(var i = 0, ci; ci = cs[i]; i++){
5892 if(ci.nodeType == 1 && ci.tagName.toLowerCase()==tagName){
5899 function byId(cs, attr, id){
5900 if(cs.tagName || cs == document){
5906 var r = [], ri = -1;
5907 for(var i = 0,ci; ci = cs[i]; i++){
5908 if(ci && ci.id == id){
5916 function byAttribute(cs, attr, value, op, custom){
5917 var r = [], ri = -1, st = custom=="{";
5918 var f = Roo.DomQuery.operators[op];
5919 for(var i = 0, ci; ci = cs[i]; i++){
5922 a = Roo.DomQuery.getStyle(ci, attr);
5924 else if(attr == "class" || attr == "className"){
5925 a = (ci instanceof SVGElement) ? ci.className.baseVal : ci.className;
5926 }else if(attr == "for"){
5928 }else if(attr == "href"){
5929 a = ci.getAttribute("href", 2);
5931 a = ci.getAttribute(attr);
5933 if((f && f(a, value)) || (!f && a)){
5940 function byPseudo(cs, name, value){
5941 return Roo.DomQuery.pseudos[name](cs, value);
5944 // This is for IE MSXML which does not support expandos.
5945 // IE runs the same speed using setAttribute, however FF slows way down
5946 // and Safari completely fails so they need to continue to use expandos.
5947 var isIE = window.ActiveXObject ? true : false;
5949 // this eval is stop the compressor from
5950 // renaming the variable to something shorter
5952 /** eval:var:batch */
5957 function nodupIEXml(cs){
5959 cs[0].setAttribute("_nodup", d);
5961 for(var i = 1, len = cs.length; i < len; i++){
5963 if(!c.getAttribute("_nodup") != d){
5964 c.setAttribute("_nodup", d);
5968 for(var i = 0, len = cs.length; i < len; i++){
5969 cs[i].removeAttribute("_nodup");
5978 var len = cs.length, c, i, r = cs, cj, ri = -1;
5979 if(!len || typeof cs.nodeType != "undefined" || len == 1){
5982 if(isIE && typeof cs[0].selectSingleNode != "undefined"){
5983 return nodupIEXml(cs);
5987 for(i = 1; c = cs[i]; i++){
5992 for(var j = 0; j < i; j++){
5995 for(j = i+1; cj = cs[j]; j++){
6007 function quickDiffIEXml(c1, c2){
6009 for(var i = 0, len = c1.length; i < len; i++){
6010 c1[i].setAttribute("_qdiff", d);
6013 for(var i = 0, len = c2.length; i < len; i++){
6014 if(c2[i].getAttribute("_qdiff") != d){
6015 r[r.length] = c2[i];
6018 for(var i = 0, len = c1.length; i < len; i++){
6019 c1[i].removeAttribute("_qdiff");
6024 function quickDiff(c1, c2){
6025 var len1 = c1.length;
6029 if(isIE && c1[0].selectSingleNode){
6030 return quickDiffIEXml(c1, c2);
6033 for(var i = 0; i < len1; i++){
6037 for(var i = 0, len = c2.length; i < len; i++){
6038 if(c2[i]._qdiff != d){
6039 r[r.length] = c2[i];
6045 function quickId(ns, mode, root, id){
6047 var d = root.ownerDocument || root;
6048 return d.getElementById(id);
6050 ns = getNodes(ns, mode, "*");
6051 return byId(ns, null, id);
6055 getStyle : function(el, name){
6056 return Roo.fly(el).getStyle(name);
6059 * Compiles a selector/xpath query into a reusable function. The returned function
6060 * takes one parameter "root" (optional), which is the context node from where the query should start.
6061 * @param {String} selector The selector/xpath query
6062 * @param {String} type (optional) Either "select" (the default) or "simple" for a simple selector match
6063 * @return {Function}
6065 compile : function(path, type){
6066 type = type || "select";
6068 var fn = ["var f = function(root){\n var mode; ++batch; var n = root || document;\n"];
6069 var q = path, mode, lq;
6070 var tk = Roo.DomQuery.matchers;
6071 var tklen = tk.length;
6074 // accept leading mode switch
6075 var lmode = q.match(modeRe);
6076 if(lmode && lmode[1]){
6077 fn[fn.length] = 'mode="'+lmode[1].replace(trimRe, "")+'";';
6078 q = q.replace(lmode[1], "");
6080 // strip leading slashes
6081 while(path.substr(0, 1)=="/"){
6082 path = path.substr(1);
6085 while(q && lq != q){
6087 var tm = q.match(tagTokenRe);
6088 if(type == "select"){
6091 fn[fn.length] = 'n = quickId(n, mode, root, "'+tm[2]+'");';
6093 fn[fn.length] = 'n = getNodes(n, mode, "'+tm[2]+'");';
6095 q = q.replace(tm[0], "");
6096 }else if(q.substr(0, 1) != '@'){
6097 fn[fn.length] = 'n = getNodes(n, mode, "*");';
6102 fn[fn.length] = 'n = byId(n, null, "'+tm[2]+'");';
6104 fn[fn.length] = 'n = byTag(n, "'+tm[2]+'");';
6106 q = q.replace(tm[0], "");
6109 while(!(mm = q.match(modeRe))){
6110 var matched = false;
6111 for(var j = 0; j < tklen; j++){
6113 var m = q.match(t.re);
6115 fn[fn.length] = t.select.replace(tplRe, function(x, i){
6118 q = q.replace(m[0], "");
6123 // prevent infinite loop on bad selector
6125 throw 'Error parsing selector, parsing failed at "' + q + '"';
6129 fn[fn.length] = 'mode="'+mm[1].replace(trimRe, "")+'";';
6130 q = q.replace(mm[1], "");
6133 fn[fn.length] = "return nodup(n);\n}";
6136 * list of variables that need from compression as they are used by eval.
6146 * eval:var:byClassName
6148 * eval:var:byAttribute
6149 * eval:var:attrValue
6157 * Selects a group of elements.
6158 * @param {String} selector The selector/xpath query (can be a comma separated list of selectors)
6159 * @param {Node} root (optional) The start of the query (defaults to document).
6162 select : function(path, root, type){
6163 if(!root || root == document){
6166 if(typeof root == "string"){
6167 root = document.getElementById(root);
6169 var paths = path.split(",");
6171 for(var i = 0, len = paths.length; i < len; i++){
6172 var p = paths[i].replace(trimRe, "");
6174 cache[p] = Roo.DomQuery.compile(p);
6176 throw p + " is not a valid selector";
6179 var result = cache[p](root);
6180 if(result && result != document){
6181 results = results.concat(result);
6184 if(paths.length > 1){
6185 return nodup(results);
6191 * Selects a single element.
6192 * @param {String} selector The selector/xpath query
6193 * @param {Node} root (optional) The start of the query (defaults to document).
6196 selectNode : function(path, root){
6197 return Roo.DomQuery.select(path, root)[0];
6201 * Selects the value of a node, optionally replacing null with the defaultValue.
6202 * @param {String} selector The selector/xpath query
6203 * @param {Node} root (optional) The start of the query (defaults to document).
6204 * @param {String} defaultValue
6206 selectValue : function(path, root, defaultValue){
6207 path = path.replace(trimRe, "");
6208 if(!valueCache[path]){
6209 valueCache[path] = Roo.DomQuery.compile(path, "select");
6211 var n = valueCache[path](root);
6212 n = n[0] ? n[0] : n;
6213 var v = (n && n.firstChild ? n.firstChild.nodeValue : null);
6214 return ((v === null||v === undefined||v==='') ? defaultValue : v);
6218 * Selects the value of a node, parsing integers and floats.
6219 * @param {String} selector The selector/xpath query
6220 * @param {Node} root (optional) The start of the query (defaults to document).
6221 * @param {Number} defaultValue
6224 selectNumber : function(path, root, defaultValue){
6225 var v = Roo.DomQuery.selectValue(path, root, defaultValue || 0);
6226 return parseFloat(v);
6230 * Returns true if the passed element(s) match the passed simple selector (e.g. div.some-class or span:first-child)
6231 * @param {String/HTMLElement/Array} el An element id, element or array of elements
6232 * @param {String} selector The simple selector to test
6235 is : function(el, ss){
6236 if(typeof el == "string"){
6237 el = document.getElementById(el);
6239 var isArray = (el instanceof Array);
6240 var result = Roo.DomQuery.filter(isArray ? el : [el], ss);
6241 return isArray ? (result.length == el.length) : (result.length > 0);
6245 * Filters an array of elements to only include matches of a simple selector (e.g. div.some-class or span:first-child)
6246 * @param {Array} el An array of elements to filter
6247 * @param {String} selector The simple selector to test
6248 * @param {Boolean} nonMatches If true, it returns the elements that DON'T match
6249 * the selector instead of the ones that match
6252 filter : function(els, ss, nonMatches){
6253 ss = ss.replace(trimRe, "");
6254 if(!simpleCache[ss]){
6255 simpleCache[ss] = Roo.DomQuery.compile(ss, "simple");
6257 var result = simpleCache[ss](els);
6258 return nonMatches ? quickDiff(result, els) : result;
6262 * Collection of matching regular expressions and code snippets.
6266 select: 'n = byClassName(n, null, " {1} ");'
6268 re: /^\:([\w-]+)(?:\(((?:[^\s>\/]*|.*?))\))?/,
6269 select: 'n = byPseudo(n, "{1}", "{2}");'
6271 re: /^(?:([\[\{])(?:@)?([\w-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]\}])/,
6272 select: 'n = byAttribute(n, "{2}", "{4}", "{3}", "{1}");'
6275 select: 'n = byId(n, null, "{1}");'
6278 select: 'return {firstChild:{nodeValue:attrValue(n, "{1}")}};'
6283 * Collection of operator comparison functions. The default operators are =, !=, ^=, $=, *=, %=, |= and ~=.
6284 * 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, > <.
6287 "=" : function(a, v){
6290 "!=" : function(a, v){
6293 "^=" : function(a, v){
6294 return a && a.substr(0, v.length) == v;
6296 "$=" : function(a, v){
6297 return a && a.substr(a.length-v.length) == v;
6299 "*=" : function(a, v){
6300 return a && a.indexOf(v) !== -1;
6302 "%=" : function(a, v){
6303 return (a % v) == 0;
6305 "|=" : function(a, v){
6306 return a && (a == v || a.substr(0, v.length+1) == v+'-');
6308 "~=" : function(a, v){
6309 return a && (' '+a+' ').indexOf(' '+v+' ') != -1;
6314 * Collection of "pseudo class" processors. Each processor is passed the current nodeset (array)
6315 * and the argument (if any) supplied in the selector.
6318 "first-child" : function(c){
6319 var r = [], ri = -1, n;
6320 for(var i = 0, ci; ci = n = c[i]; i++){
6321 while((n = n.previousSibling) && n.nodeType != 1);
6329 "last-child" : function(c){
6330 var r = [], ri = -1, n;
6331 for(var i = 0, ci; ci = n = c[i]; i++){
6332 while((n = n.nextSibling) && n.nodeType != 1);
6340 "nth-child" : function(c, a) {
6341 var r = [], ri = -1;
6342 var m = nthRe.exec(a == "even" && "2n" || a == "odd" && "2n+1" || !nthRe2.test(a) && "n+" + a || a);
6343 var f = (m[1] || 1) - 0, l = m[2] - 0;
6344 for(var i = 0, n; n = c[i]; i++){
6345 var pn = n.parentNode;
6346 if (batch != pn._batch) {
6348 for(var cn = pn.firstChild; cn; cn = cn.nextSibling){
6349 if(cn.nodeType == 1){
6356 if (l == 0 || n.nodeIndex == l){
6359 } else if ((n.nodeIndex + l) % f == 0){
6367 "only-child" : function(c){
6368 var r = [], ri = -1;;
6369 for(var i = 0, ci; ci = c[i]; i++){
6370 if(!prev(ci) && !next(ci)){
6377 "empty" : function(c){
6378 var r = [], ri = -1;
6379 for(var i = 0, ci; ci = c[i]; i++){
6380 var cns = ci.childNodes, j = 0, cn, empty = true;
6383 if(cn.nodeType == 1 || cn.nodeType == 3){
6395 "contains" : function(c, v){
6396 var r = [], ri = -1;
6397 for(var i = 0, ci; ci = c[i]; i++){
6398 if((ci.textContent||ci.innerText||'').indexOf(v) != -1){
6405 "nodeValue" : function(c, v){
6406 var r = [], ri = -1;
6407 for(var i = 0, ci; ci = c[i]; i++){
6408 if(ci.firstChild && ci.firstChild.nodeValue == v){
6415 "checked" : function(c){
6416 var r = [], ri = -1;
6417 for(var i = 0, ci; ci = c[i]; i++){
6418 if(ci.checked == true){
6425 "not" : function(c, ss){
6426 return Roo.DomQuery.filter(c, ss, true);
6429 "odd" : function(c){
6430 return this["nth-child"](c, "odd");
6433 "even" : function(c){
6434 return this["nth-child"](c, "even");
6437 "nth" : function(c, a){
6438 return c[a-1] || [];
6441 "first" : function(c){
6445 "last" : function(c){
6446 return c[c.length-1] || [];
6449 "has" : function(c, ss){
6450 var s = Roo.DomQuery.select;
6451 var r = [], ri = -1;
6452 for(var i = 0, ci; ci = c[i]; i++){
6453 if(s(ss, ci).length > 0){
6460 "next" : function(c, ss){
6461 var is = Roo.DomQuery.is;
6462 var r = [], ri = -1;
6463 for(var i = 0, ci; ci = c[i]; i++){
6472 "prev" : function(c, ss){
6473 var is = Roo.DomQuery.is;
6474 var r = [], ri = -1;
6475 for(var i = 0, ci; ci = c[i]; i++){
6488 * Selects an array of DOM nodes by CSS/XPath selector. Shorthand of {@link Roo.DomQuery#select}
6489 * @param {String} path The selector/xpath query
6490 * @param {Node} root (optional) The start of the query (defaults to document).
6495 Roo.query = Roo.DomQuery.select;
6498 * Ext JS Library 1.1.1
6499 * Copyright(c) 2006-2007, Ext JS, LLC.
6501 * Originally Released Under LGPL - original licence link has changed is not relivant.
6504 * <script type="text/javascript">
6508 * @class Roo.util.Observable
6509 * Base class that provides a common interface for publishing events. Subclasses are expected to
6510 * to have a property "events" with all the events defined.<br>
6513 Employee = function(name){
6520 Roo.extend(Employee, Roo.util.Observable);
6522 * @param {Object} config properties to use (incuding events / listeners)
6525 Roo.util.Observable = function(cfg){
6528 this.addEvents(cfg.events || {});
6530 delete cfg.events; // make sure
6533 Roo.apply(this, cfg);
6536 this.on(this.listeners);
6537 delete this.listeners;
6540 Roo.util.Observable.prototype = {
6542 * @cfg {Object} listeners list of events and functions to call for this object,
6546 'click' : function(e) {
6556 * Fires the specified event with the passed parameters (minus the event name).
6557 * @param {String} eventName
6558 * @param {Object...} args Variable number of parameters are passed to handlers
6559 * @return {Boolean} returns false if any of the handlers return false otherwise it returns true
6561 fireEvent : function(){
6562 var ce = this.events[arguments[0].toLowerCase()];
6563 if(typeof ce == "object"){
6564 return ce.fire.apply(ce, Array.prototype.slice.call(arguments, 1));
6571 filterOptRe : /^(?:scope|delay|buffer|single)$/,
6574 * Appends an event handler to this component
6575 * @param {String} eventName The type of event to listen for
6576 * @param {Function} handler The method the event invokes
6577 * @param {Object} scope (optional) The scope in which to execute the handler
6578 * function. The handler function's "this" context.
6579 * @param {Object} options (optional) An object containing handler configuration
6580 * properties. This may contain any of the following properties:<ul>
6581 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
6582 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
6583 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
6584 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
6585 * by the specified number of milliseconds. If the event fires again within that time, the original
6586 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
6589 * <b>Combining Options</b><br>
6590 * Using the options argument, it is possible to combine different types of listeners:<br>
6592 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)
6594 el.on('click', this.onClick, this, {
6601 * <b>Attaching multiple handlers in 1 call</b><br>
6602 * The method also allows for a single argument to be passed which is a config object containing properties
6603 * which specify multiple handlers.
6612 fn: this.onMouseOver,
6616 fn: this.onMouseOut,
6622 * Or a shorthand syntax which passes the same scope object to all handlers:
6625 'click': this.onClick,
6626 'mouseover': this.onMouseOver,
6627 'mouseout': this.onMouseOut,
6632 addListener : function(eventName, fn, scope, o){
6633 if(typeof eventName == "object"){
6636 if(this.filterOptRe.test(e)){
6639 if(typeof o[e] == "function"){
6641 this.addListener(e, o[e], o.scope, o);
6643 // individual options
6644 this.addListener(e, o[e].fn, o[e].scope, o[e]);
6649 o = (!o || typeof o == "boolean") ? {} : o;
6650 eventName = eventName.toLowerCase();
6651 var ce = this.events[eventName] || true;
6652 if(typeof ce == "boolean"){
6653 ce = new Roo.util.Event(this, eventName);
6654 this.events[eventName] = ce;
6656 ce.addListener(fn, scope, o);
6660 * Removes a listener
6661 * @param {String} eventName The type of event to listen for
6662 * @param {Function} handler The handler to remove
6663 * @param {Object} scope (optional) The scope (this object) for the handler
6665 removeListener : function(eventName, fn, scope){
6666 var ce = this.events[eventName.toLowerCase()];
6667 if(typeof ce == "object"){
6668 ce.removeListener(fn, scope);
6673 * Removes all listeners for this object
6675 purgeListeners : function(){
6676 for(var evt in this.events){
6677 if(typeof this.events[evt] == "object"){
6678 this.events[evt].clearListeners();
6683 relayEvents : function(o, events){
6684 var createHandler = function(ename){
6687 return this.fireEvent.apply(this, Roo.combine(ename, Array.prototype.slice.call(arguments, 0)));
6690 for(var i = 0, len = events.length; i < len; i++){
6691 var ename = events[i];
6692 if(!this.events[ename]){
6693 this.events[ename] = true;
6695 o.on(ename, createHandler(ename), this);
6700 * Used to define events on this Observable
6701 * @param {Object} object The object with the events defined
6703 addEvents : function(o){
6707 Roo.applyIf(this.events, o);
6711 * Checks to see if this object has any listeners for a specified event
6712 * @param {String} eventName The name of the event to check for
6713 * @return {Boolean} True if the event is being listened for, else false
6715 hasListener : function(eventName){
6716 var e = this.events[eventName];
6717 return typeof e == "object" && e.listeners.length > 0;
6721 * Appends an event handler to this element (shorthand for addListener)
6722 * @param {String} eventName The type of event to listen for
6723 * @param {Function} handler The method the event invokes
6724 * @param {Object} scope (optional) The scope in which to execute the handler
6725 * function. The handler function's "this" context.
6726 * @param {Object} options (optional)
6729 Roo.util.Observable.prototype.on = Roo.util.Observable.prototype.addListener;
6731 * Removes a listener (shorthand for removeListener)
6732 * @param {String} eventName The type of event to listen for
6733 * @param {Function} handler The handler to remove
6734 * @param {Object} scope (optional) The scope (this object) for the handler
6737 Roo.util.Observable.prototype.un = Roo.util.Observable.prototype.removeListener;
6740 * Starts capture on the specified Observable. All events will be passed
6741 * to the supplied function with the event name + standard signature of the event
6742 * <b>before</b> the event is fired. If the supplied function returns false,
6743 * the event will not fire.
6744 * @param {Observable} o The Observable to capture
6745 * @param {Function} fn The function to call
6746 * @param {Object} scope (optional) The scope (this object) for the fn
6749 Roo.util.Observable.capture = function(o, fn, scope){
6750 o.fireEvent = o.fireEvent.createInterceptor(fn, scope);
6754 * Removes <b>all</b> added captures from the Observable.
6755 * @param {Observable} o The Observable to release
6758 Roo.util.Observable.releaseCapture = function(o){
6759 o.fireEvent = Roo.util.Observable.prototype.fireEvent;
6764 var createBuffered = function(h, o, scope){
6765 var task = new Roo.util.DelayedTask();
6767 task.delay(o.buffer, h, scope, Array.prototype.slice.call(arguments, 0));
6771 var createSingle = function(h, e, fn, scope){
6773 e.removeListener(fn, scope);
6774 return h.apply(scope, arguments);
6778 var createDelayed = function(h, o, scope){
6780 var args = Array.prototype.slice.call(arguments, 0);
6781 setTimeout(function(){
6782 h.apply(scope, args);
6787 Roo.util.Event = function(obj, name){
6790 this.listeners = [];
6793 Roo.util.Event.prototype = {
6794 addListener : function(fn, scope, options){
6795 var o = options || {};
6796 scope = scope || this.obj;
6797 if(!this.isListening(fn, scope)){
6798 var l = {fn: fn, scope: scope, options: o};
6801 h = createDelayed(h, o, scope);
6804 h = createSingle(h, this, fn, scope);
6807 h = createBuffered(h, o, scope);
6810 if(!this.firing){ // if we are currently firing this event, don't disturb the listener loop
6811 this.listeners.push(l);
6813 this.listeners = this.listeners.slice(0);
6814 this.listeners.push(l);
6819 findListener : function(fn, scope){
6820 scope = scope || this.obj;
6821 var ls = this.listeners;
6822 for(var i = 0, len = ls.length; i < len; i++){
6824 if(l.fn == fn && l.scope == scope){
6831 isListening : function(fn, scope){
6832 return this.findListener(fn, scope) != -1;
6835 removeListener : function(fn, scope){
6837 if((index = this.findListener(fn, scope)) != -1){
6839 this.listeners.splice(index, 1);
6841 this.listeners = this.listeners.slice(0);
6842 this.listeners.splice(index, 1);
6849 clearListeners : function(){
6850 this.listeners = [];
6854 var ls = this.listeners, scope, len = ls.length;
6857 var args = Array.prototype.slice.call(arguments, 0);
6858 for(var i = 0; i < len; i++){
6860 if(l.fireFn.apply(l.scope||this.obj||window, args) === false){
6861 this.firing = false;
6865 this.firing = false;
6872 * Copyright(c) 2007-2017, Roo J Solutions Ltd
6879 * @class Roo.Document
6880 * @extends Roo.util.Observable
6881 * This is a convience class to wrap up the main document loading code.. , rather than adding Roo.onReady(......)
6883 * @param {Object} config the methods and properties of the 'base' class for the application.
6885 * Generic Page handler - implement this to start your app..
6888 * MyProject = new Roo.Document({
6890 'load' : true // your events..
6893 'ready' : function() {
6894 // fired on Roo.onReady()
6899 Roo.Document = function(cfg) {
6904 Roo.util.Observable.call(this,cfg);
6908 Roo.onReady(function() {
6909 _this.fireEvent('ready');
6915 Roo.extend(Roo.Document, Roo.util.Observable, {});/*
6917 * Ext JS Library 1.1.1
6918 * Copyright(c) 2006-2007, Ext JS, LLC.
6920 * Originally Released Under LGPL - original licence link has changed is not relivant.
6923 * <script type="text/javascript">
6927 * @class Roo.EventManager
6928 * Registers event handlers that want to receive a normalized EventObject instead of the standard browser event and provides
6929 * several useful events directly.
6930 * See {@link Roo.EventObject} for more details on normalized event objects.
6933 Roo.EventManager = function(){
6934 var docReadyEvent, docReadyProcId, docReadyState = false;
6935 var resizeEvent, resizeTask, textEvent, textSize;
6936 var E = Roo.lib.Event;
6937 var D = Roo.lib.Dom;
6942 var fireDocReady = function(){
6944 docReadyState = true;
6947 clearInterval(docReadyProcId);
6949 if(Roo.isGecko || Roo.isOpera) {
6950 document.removeEventListener("DOMContentLoaded", fireDocReady, false);
6953 var defer = document.getElementById("ie-deferred-loader");
6955 defer.onreadystatechange = null;
6956 defer.parentNode.removeChild(defer);
6960 docReadyEvent.fire();
6961 docReadyEvent.clearListeners();
6966 var initDocReady = function(){
6967 docReadyEvent = new Roo.util.Event();
6968 if(Roo.isGecko || Roo.isOpera) {
6969 document.addEventListener("DOMContentLoaded", fireDocReady, false);
6971 document.write("<s"+'cript id="ie-deferred-loader" defer="defer" src="/'+'/:"></s'+"cript>");
6972 var defer = document.getElementById("ie-deferred-loader");
6973 defer.onreadystatechange = function(){
6974 if(this.readyState == "complete"){
6978 }else if(Roo.isSafari){
6979 docReadyProcId = setInterval(function(){
6980 var rs = document.readyState;
6981 if(rs == "complete") {
6986 // no matter what, make sure it fires on load
6987 E.on(window, "load", fireDocReady);
6990 var createBuffered = function(h, o){
6991 var task = new Roo.util.DelayedTask(h);
6993 // create new event object impl so new events don't wipe out properties
6994 e = new Roo.EventObjectImpl(e);
6995 task.delay(o.buffer, h, null, [e]);
6999 var createSingle = function(h, el, ename, fn){
7001 Roo.EventManager.removeListener(el, ename, fn);
7006 var createDelayed = function(h, o){
7008 // create new event object impl so new events don't wipe out properties
7009 e = new Roo.EventObjectImpl(e);
7010 setTimeout(function(){
7015 var transitionEndVal = false;
7017 var transitionEnd = function()
7019 if (transitionEndVal) {
7020 return transitionEndVal;
7022 var el = document.createElement('div');
7024 var transEndEventNames = {
7025 WebkitTransition : 'webkitTransitionEnd',
7026 MozTransition : 'transitionend',
7027 OTransition : 'oTransitionEnd otransitionend',
7028 transition : 'transitionend'
7031 for (var name in transEndEventNames) {
7032 if (el.style[name] !== undefined) {
7033 transitionEndVal = transEndEventNames[name];
7034 return transitionEndVal ;
7041 var listen = function(element, ename, opt, fn, scope)
7043 var o = (!opt || typeof opt == "boolean") ? {} : opt;
7044 fn = fn || o.fn; scope = scope || o.scope;
7045 var el = Roo.getDom(element);
7049 throw "Error listening for \"" + ename + '\". Element "' + element + '" doesn\'t exist.';
7052 if (ename == 'transitionend') {
7053 ename = transitionEnd();
7055 var h = function(e){
7056 e = Roo.EventObject.setEvent(e);
7059 t = e.getTarget(o.delegate, el);
7066 if(o.stopEvent === true){
7069 if(o.preventDefault === true){
7072 if(o.stopPropagation === true){
7073 e.stopPropagation();
7076 if(o.normalized === false){
7080 fn.call(scope || el, e, t, o);
7083 h = createDelayed(h, o);
7086 h = createSingle(h, el, ename, fn);
7089 h = createBuffered(h, o);
7092 fn._handlers = fn._handlers || [];
7095 fn._handlers.push([Roo.id(el), ename, h]);
7099 E.on(el, ename, h); // this adds the actuall listener to the object..
7102 if(ename == "mousewheel" && el.addEventListener){ // workaround for jQuery
7103 el.addEventListener("DOMMouseScroll", h, false);
7104 E.on(window, 'unload', function(){
7105 el.removeEventListener("DOMMouseScroll", h, false);
7108 if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
7109 Roo.EventManager.stoppedMouseDownEvent.addListener(h);
7114 var stopListening = function(el, ename, fn){
7115 var id = Roo.id(el), hds = fn._handlers, hd = fn;
7117 for(var i = 0, len = hds.length; i < len; i++){
7119 if(h[0] == id && h[1] == ename){
7126 E.un(el, ename, hd);
7127 el = Roo.getDom(el);
7128 if(ename == "mousewheel" && el.addEventListener){
7129 el.removeEventListener("DOMMouseScroll", hd, false);
7131 if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
7132 Roo.EventManager.stoppedMouseDownEvent.removeListener(hd);
7136 var propRe = /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/;
7143 * @scope Roo.EventManager
7148 * This is no longer needed and is deprecated. Places a simple wrapper around an event handler to override the browser event
7149 * object with a Roo.EventObject
7150 * @param {Function} fn The method the event invokes
7151 * @param {Object} scope An object that becomes the scope of the handler
7152 * @param {boolean} override If true, the obj passed in becomes
7153 * the execution scope of the listener
7154 * @return {Function} The wrapped function
7157 wrap : function(fn, scope, override){
7159 Roo.EventObject.setEvent(e);
7160 fn.call(override ? scope || window : window, Roo.EventObject, scope);
7165 * Appends an event handler to an element (shorthand for addListener)
7166 * @param {String/HTMLElement} element The html element or id to assign the
7167 * @param {String} eventName The type of event to listen for
7168 * @param {Function} handler The method the event invokes
7169 * @param {Object} scope (optional) The scope in which to execute the handler
7170 * function. The handler function's "this" context.
7171 * @param {Object} options (optional) An object containing handler configuration
7172 * properties. This may contain any of the following properties:<ul>
7173 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
7174 * <li>delegate {String} A simple selector to filter the target or look for a descendant of the target</li>
7175 * <li>stopEvent {Boolean} True to stop the event. That is stop propagation, and prevent the default action.</li>
7176 * <li>preventDefault {Boolean} True to prevent the default action</li>
7177 * <li>stopPropagation {Boolean} True to prevent event propagation</li>
7178 * <li>normalized {Boolean} False to pass a browser event to the handler function instead of an Roo.EventObject</li>
7179 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
7180 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
7181 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
7182 * by the specified number of milliseconds. If the event fires again within that time, the original
7183 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
7186 * <b>Combining Options</b><br>
7187 * Using the options argument, it is possible to combine different types of listeners:<br>
7189 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)<div style="margin: 5px 20px 20px;">
7191 el.on('click', this.onClick, this, {
7198 * <b>Attaching multiple handlers in 1 call</b><br>
7199 * The method also allows for a single argument to be passed which is a config object containing properties
7200 * which specify multiple handlers.
7210 fn: this.onMouseOver
7219 * Or a shorthand syntax:<br>
7222 'click' : this.onClick,
7223 'mouseover' : this.onMouseOver,
7224 'mouseout' : this.onMouseOut
7228 addListener : function(element, eventName, fn, scope, options){
7229 if(typeof eventName == "object"){
7235 if(typeof o[e] == "function"){
7237 listen(element, e, o, o[e], o.scope);
7239 // individual options
7240 listen(element, e, o[e]);
7245 return listen(element, eventName, options, fn, scope);
7249 * Removes an event handler
7251 * @param {String/HTMLElement} element The id or html element to remove the
7253 * @param {String} eventName The type of event
7254 * @param {Function} fn
7255 * @return {Boolean} True if a listener was actually removed
7257 removeListener : function(element, eventName, fn){
7258 return stopListening(element, eventName, fn);
7262 * Fires when the document is ready (before onload and before images are loaded). Can be
7263 * accessed shorthanded Roo.onReady().
7264 * @param {Function} fn The method the event invokes
7265 * @param {Object} scope An object that becomes the scope of the handler
7266 * @param {boolean} options
7268 onDocumentReady : function(fn, scope, options){
7269 if(docReadyState){ // if it already fired
7270 docReadyEvent.addListener(fn, scope, options);
7271 docReadyEvent.fire();
7272 docReadyEvent.clearListeners();
7278 docReadyEvent.addListener(fn, scope, options);
7282 * Fires when the window is resized and provides resize event buffering (50 milliseconds), passes new viewport width and height to handlers.
7283 * @param {Function} fn The method the event invokes
7284 * @param {Object} scope An object that becomes the scope of the handler
7285 * @param {boolean} options
7287 onWindowResize : function(fn, scope, options)
7290 resizeEvent = new Roo.util.Event();
7291 resizeTask = new Roo.util.DelayedTask(function(){
7292 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
7294 E.on(window, "resize", function()
7297 resizeTask.delay(50);
7299 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
7303 resizeEvent.addListener(fn, scope, options);
7307 * Fires when the user changes the active text size. Handler gets called with 2 params, the old size and the new size.
7308 * @param {Function} fn The method the event invokes
7309 * @param {Object} scope An object that becomes the scope of the handler
7310 * @param {boolean} options
7312 onTextResize : function(fn, scope, options){
7314 textEvent = new Roo.util.Event();
7315 var textEl = new Roo.Element(document.createElement('div'));
7316 textEl.dom.className = 'x-text-resize';
7317 textEl.dom.innerHTML = 'X';
7318 textEl.appendTo(document.body);
7319 textSize = textEl.dom.offsetHeight;
7320 setInterval(function(){
7321 if(textEl.dom.offsetHeight != textSize){
7322 textEvent.fire(textSize, textSize = textEl.dom.offsetHeight);
7324 }, this.textResizeInterval);
7326 textEvent.addListener(fn, scope, options);
7330 * Removes the passed window resize listener.
7331 * @param {Function} fn The method the event invokes
7332 * @param {Object} scope The scope of handler
7334 removeResizeListener : function(fn, scope){
7336 resizeEvent.removeListener(fn, scope);
7341 fireResize : function(){
7343 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
7347 * Url used for onDocumentReady with using SSL (defaults to Roo.SSL_SECURE_URL)
7351 * The frequency, in milliseconds, to check for text resize events (defaults to 50)
7353 textResizeInterval : 50
7358 * @scopeAlias pub=Roo.EventManager
7362 * Appends an event handler to an element (shorthand for addListener)
7363 * @param {String/HTMLElement} element The html element or id to assign the
7364 * @param {String} eventName The type of event to listen for
7365 * @param {Function} handler The method the event invokes
7366 * @param {Object} scope (optional) The scope in which to execute the handler
7367 * function. The handler function's "this" context.
7368 * @param {Object} options (optional) An object containing handler configuration
7369 * properties. This may contain any of the following properties:<ul>
7370 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
7371 * <li>delegate {String} A simple selector to filter the target or look for a descendant of the target</li>
7372 * <li>stopEvent {Boolean} True to stop the event. That is stop propagation, and prevent the default action.</li>
7373 * <li>preventDefault {Boolean} True to prevent the default action</li>
7374 * <li>stopPropagation {Boolean} True to prevent event propagation</li>
7375 * <li>normalized {Boolean} False to pass a browser event to the handler function instead of an Roo.EventObject</li>
7376 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
7377 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
7378 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
7379 * by the specified number of milliseconds. If the event fires again within that time, the original
7380 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
7383 * <b>Combining Options</b><br>
7384 * Using the options argument, it is possible to combine different types of listeners:<br>
7386 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)<div style="margin: 5px 20px 20px;">
7388 el.on('click', this.onClick, this, {
7395 * <b>Attaching multiple handlers in 1 call</b><br>
7396 * The method also allows for a single argument to be passed which is a config object containing properties
7397 * which specify multiple handlers.
7407 fn: this.onMouseOver
7416 * Or a shorthand syntax:<br>
7419 'click' : this.onClick,
7420 'mouseover' : this.onMouseOver,
7421 'mouseout' : this.onMouseOut
7425 pub.on = pub.addListener;
7426 pub.un = pub.removeListener;
7428 pub.stoppedMouseDownEvent = new Roo.util.Event();
7432 * Fires when the document is ready (before onload and before images are loaded). Shorthand of {@link Roo.EventManager#onDocumentReady}.
7433 * @param {Function} fn The method the event invokes
7434 * @param {Object} scope An object that becomes the scope of the handler
7435 * @param {boolean} override If true, the obj passed in becomes
7436 * the execution scope of the listener
7440 Roo.onReady = Roo.EventManager.onDocumentReady;
7442 Roo.onReady(function(){
7443 var bd = Roo.get(document.body);
7448 : Roo.isIE11 ? "roo-ie11"
7449 : Roo.isEdge ? "roo-edge"
7450 : Roo.isGecko ? "roo-gecko"
7451 : Roo.isOpera ? "roo-opera"
7452 : Roo.isSafari ? "roo-safari" : ""];
7455 cls.push("roo-mac");
7458 cls.push("roo-linux");
7461 cls.push("roo-ios");
7464 cls.push("roo-touch");
7466 if(Roo.isBorderBox){
7467 cls.push('roo-border-box');
7469 if(Roo.isStrict){ // add to the parent to allow for selectors like ".ext-strict .ext-ie"
7470 var p = bd.dom.parentNode;
7472 p.className += ' roo-strict';
7475 bd.addClass(cls.join(' '));
7479 * @class Roo.EventObject
7480 * EventObject exposes the Yahoo! UI Event functionality directly on the object
7481 * passed to your event handler. It exists mostly for convenience. It also fixes the annoying null checks automatically to cleanup your code
7484 function handleClick(e){ // e is not a standard event object, it is a Roo.EventObject
7486 var target = e.getTarget();
7489 var myDiv = Roo.get("myDiv");
7490 myDiv.on("click", handleClick);
7492 Roo.EventManager.on("myDiv", 'click', handleClick);
7493 Roo.EventManager.addListener("myDiv", 'click', handleClick);
7497 Roo.EventObject = function(){
7499 var E = Roo.lib.Event;
7501 // safari keypress events for special keys return bad keycodes
7504 63235 : 39, // right
7507 63276 : 33, // page up
7508 63277 : 34, // page down
7509 63272 : 46, // delete
7514 // normalize button clicks
7515 var btnMap = Roo.isIE ? {1:0,4:1,2:2} :
7516 (Roo.isSafari ? {1:0,2:1,3:2} : {0:0,1:1,2:2});
7518 Roo.EventObjectImpl = function(e){
7520 this.setEvent(e.browserEvent || e);
7523 Roo.EventObjectImpl.prototype = {
7525 * Used to fix doc tools.
7526 * @scope Roo.EventObject.prototype
7532 /** The normal browser event */
7533 browserEvent : null,
7534 /** The button pressed in a mouse event */
7536 /** True if the shift key was down during the event */
7538 /** True if the control key was down during the event */
7540 /** True if the alt key was down during the event */
7599 setEvent : function(e){
7600 if(e == this || (e && e.browserEvent)){ // already wrapped
7603 this.browserEvent = e;
7605 // normalize buttons
7606 this.button = e.button ? btnMap[e.button] : (e.which ? e.which-1 : -1);
7607 if(e.type == 'click' && this.button == -1){
7611 this.shiftKey = e.shiftKey;
7612 // mac metaKey behaves like ctrlKey
7613 this.ctrlKey = e.ctrlKey || e.metaKey;
7614 this.altKey = e.altKey;
7615 // in getKey these will be normalized for the mac
7616 this.keyCode = e.keyCode;
7617 // keyup warnings on firefox.
7618 this.charCode = (e.type == 'keyup' || e.type == 'keydown') ? 0 : e.charCode;
7619 // cache the target for the delayed and or buffered events
7620 this.target = E.getTarget(e);
7622 this.xy = E.getXY(e);
7625 this.shiftKey = false;
7626 this.ctrlKey = false;
7627 this.altKey = false;
7637 * Stop the event (preventDefault and stopPropagation)
7639 stopEvent : function(){
7640 if(this.browserEvent){
7641 if(this.browserEvent.type == 'mousedown'){
7642 Roo.EventManager.stoppedMouseDownEvent.fire(this);
7644 E.stopEvent(this.browserEvent);
7649 * Prevents the browsers default handling of the event.
7651 preventDefault : function(){
7652 if(this.browserEvent){
7653 E.preventDefault(this.browserEvent);
7658 isNavKeyPress : function(){
7659 var k = this.keyCode;
7660 k = Roo.isSafari ? (safariKeys[k] || k) : k;
7661 return (k >= 33 && k <= 40) || k == this.RETURN || k == this.TAB || k == this.ESC;
7664 isSpecialKey : function(){
7665 var k = this.keyCode;
7666 return (this.type == 'keypress' && this.ctrlKey) || k == 9 || k == 13 || k == 40 || k == 27 ||
7667 (k == 16) || (k == 17) ||
7668 (k >= 18 && k <= 20) ||
7669 (k >= 33 && k <= 35) ||
7670 (k >= 36 && k <= 39) ||
7671 (k >= 44 && k <= 45);
7674 * Cancels bubbling of the event.
7676 stopPropagation : function(){
7677 if(this.browserEvent){
7678 if(this.type == 'mousedown'){
7679 Roo.EventManager.stoppedMouseDownEvent.fire(this);
7681 E.stopPropagation(this.browserEvent);
7686 * Gets the key code for the event.
7689 getCharCode : function(){
7690 return this.charCode || this.keyCode;
7694 * Returns a normalized keyCode for the event.
7695 * @return {Number} The key code
7697 getKey : function(){
7698 var k = this.keyCode || this.charCode;
7699 return Roo.isSafari ? (safariKeys[k] || k) : k;
7703 * Gets the x coordinate of the event.
7706 getPageX : function(){
7711 * Gets the y coordinate of the event.
7714 getPageY : function(){
7719 * Gets the time of the event.
7722 getTime : function(){
7723 if(this.browserEvent){
7724 return E.getTime(this.browserEvent);
7730 * Gets the page coordinates of the event.
7731 * @return {Array} The xy values like [x, y]
7738 * Gets the target for the event.
7739 * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target
7740 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
7741 search as a number or element (defaults to 10 || document.body)
7742 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
7743 * @return {HTMLelement}
7745 getTarget : function(selector, maxDepth, returnEl){
7746 return selector ? Roo.fly(this.target).findParent(selector, maxDepth, returnEl) : this.target;
7749 * Gets the related target.
7750 * @return {HTMLElement}
7752 getRelatedTarget : function(){
7753 if(this.browserEvent){
7754 return E.getRelatedTarget(this.browserEvent);
7760 * Normalizes mouse wheel delta across browsers
7761 * @return {Number} The delta
7763 getWheelDelta : function(){
7764 var e = this.browserEvent;
7766 if(e.wheelDelta){ /* IE/Opera. */
7767 delta = e.wheelDelta/120;
7768 }else if(e.detail){ /* Mozilla case. */
7769 delta = -e.detail/3;
7775 * Returns true if the control, meta, shift or alt key was pressed during this event.
7778 hasModifier : function(){
7779 return !!((this.ctrlKey || this.altKey) || this.shiftKey);
7783 * Returns true if the target of this event equals el or is a child of el
7784 * @param {String/HTMLElement/Element} el
7785 * @param {Boolean} related (optional) true to test if the related target is within el instead of the target
7788 within : function(el, related){
7789 var t = this[related ? "getRelatedTarget" : "getTarget"]();
7790 return t && Roo.fly(el).contains(t);
7793 getPoint : function(){
7794 return new Roo.lib.Point(this.xy[0], this.xy[1]);
7798 return new Roo.EventObjectImpl();
7803 * Ext JS Library 1.1.1
7804 * Copyright(c) 2006-2007, Ext JS, LLC.
7806 * Originally Released Under LGPL - original licence link has changed is not relivant.
7809 * <script type="text/javascript">
7813 // was in Composite Element!??!?!
7816 var D = Roo.lib.Dom;
7817 var E = Roo.lib.Event;
7818 var A = Roo.lib.Anim;
7820 // local style camelizing for speed
7822 var camelRe = /(-[a-z])/gi;
7823 var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); };
7824 var view = document.defaultView;
7827 * @class Roo.Element
7828 * Represents an Element in the DOM.<br><br>
7831 var el = Roo.get("my-div");
7834 var el = getEl("my-div");
7836 // or with a DOM element
7837 var el = Roo.get(myDivElement);
7839 * Using Roo.get() or getEl() instead of calling the constructor directly ensures you get the same object
7840 * each call instead of constructing a new one.<br><br>
7841 * <b>Animations</b><br />
7842 * Many of the functions for manipulating an element have an optional "animate" parameter. The animate parameter
7843 * should either be a boolean (true) or an object literal with animation options. The animation options are:
7845 Option Default Description
7846 --------- -------- ---------------------------------------------
7847 duration .35 The duration of the animation in seconds
7848 easing easeOut The YUI easing method
7849 callback none A function to execute when the anim completes
7850 scope this The scope (this) of the callback function
7852 * Also, the Anim object being used for the animation will be set on your options object as "anim", which allows you to stop or
7853 * manipulate the animation. Here's an example:
7855 var el = Roo.get("my-div");
7860 // default animation
7861 el.setWidth(100, true);
7863 // animation with some options set
7870 // using the "anim" property to get the Anim object
7876 el.setWidth(100, opt);
7878 if(opt.anim.isAnimated()){
7882 * <b> Composite (Collections of) Elements</b><br />
7883 * For working with collections of Elements, see <a href="Roo.CompositeElement.html">Roo.CompositeElement</a>
7884 * @constructor Create a new Element directly.
7885 * @param {String/HTMLElement} element
7886 * @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).
7888 Roo.Element = function(element, forceNew)
7890 var dom = typeof element == "string" ?
7891 document.getElementById(element) : element;
7893 this.listeners = {};
7895 if(!dom){ // invalid id/element
7899 if(forceNew !== true && id && Roo.Element.cache[id]){ // element object already exists
7900 return Roo.Element.cache[id];
7910 * The DOM element ID
7913 this.id = id || Roo.id(dom);
7915 return this; // assumed for cctor?
7918 var El = Roo.Element;
7922 * The element's default display mode (defaults to "")
7925 originalDisplay : "",
7928 // note this is overridden in BS version..
7931 * The default unit to append to CSS values where a unit isn't provided (defaults to px).
7937 * Sets the element's visibility mode. When setVisible() is called it
7938 * will use this to determine whether to set the visibility or the display property.
7939 * @param visMode Element.VISIBILITY or Element.DISPLAY
7940 * @return {Roo.Element} this
7942 setVisibilityMode : function(visMode){
7943 this.visibilityMode = visMode;
7947 * Convenience method for setVisibilityMode(Element.DISPLAY)
7948 * @param {String} display (optional) What to set display to when visible
7949 * @return {Roo.Element} this
7951 enableDisplayMode : function(display){
7952 this.setVisibilityMode(El.DISPLAY);
7953 if(typeof display != "undefined") { this.originalDisplay = display; }
7958 * 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)
7959 * @param {String} selector The simple selector to test
7960 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
7961 search as a number or element (defaults to 10 || document.body)
7962 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
7963 * @return {HTMLElement} The matching DOM node (or null if no match was found)
7965 findParent : function(simpleSelector, maxDepth, returnEl){
7966 var p = this.dom, b = document.body, depth = 0, dq = Roo.DomQuery, stopEl;
7967 maxDepth = maxDepth || 50;
7968 if(typeof maxDepth != "number"){
7969 stopEl = Roo.getDom(maxDepth);
7972 while(p && p.nodeType == 1 && depth < maxDepth && p != b && p != stopEl){
7973 if(dq.is(p, simpleSelector)){
7974 return returnEl ? Roo.get(p) : p;
7984 * Looks at parent nodes for a match of the passed simple selector (e.g. div.some-class or span:first-child)
7985 * @param {String} selector The simple selector to test
7986 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
7987 search as a number or element (defaults to 10 || document.body)
7988 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
7989 * @return {HTMLElement} The matching DOM node (or null if no match was found)
7991 findParentNode : function(simpleSelector, maxDepth, returnEl){
7992 var p = Roo.fly(this.dom.parentNode, '_internal');
7993 return p ? p.findParent(simpleSelector, maxDepth, returnEl) : null;
7997 * Looks at the scrollable parent element
7999 findScrollableParent : function()
8001 var overflowRegex = /(auto|scroll)/;
8003 if(this.getStyle('position') === 'fixed'){
8004 return Roo.isAndroid ? Roo.get(document.documentElement) : Roo.get(document.body);
8007 var excludeStaticParent = this.getStyle('position') === "absolute";
8009 for (var parent = this; (parent = Roo.get(parent.dom.parentNode));){
8011 if (excludeStaticParent && parent.getStyle('position') === "static") {
8015 if (overflowRegex.test(parent.getStyle('overflow') + parent.getStyle('overflow-x') + parent.getStyle('overflow-y'))){
8019 if(parent.dom.nodeName.toLowerCase() == 'body'){
8020 return Roo.isAndroid ? Roo.get(document.documentElement) : Roo.get(document.body);
8024 return Roo.isAndroid ? Roo.get(document.documentElement) : Roo.get(document.body);
8028 * Walks up the dom looking for a parent node that matches the passed simple selector (e.g. div.some-class or span:first-child).
8029 * This is a shortcut for findParentNode() that always returns an Roo.Element.
8030 * @param {String} selector The simple selector to test
8031 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
8032 search as a number or element (defaults to 10 || document.body)
8033 * @return {Roo.Element} The matching DOM node (or null if no match was found)
8035 up : function(simpleSelector, maxDepth){
8036 return this.findParentNode(simpleSelector, maxDepth, true);
8042 * Returns true if this element matches the passed simple selector (e.g. div.some-class or span:first-child)
8043 * @param {String} selector The simple selector to test
8044 * @return {Boolean} True if this element matches the selector, else false
8046 is : function(simpleSelector){
8047 return Roo.DomQuery.is(this.dom, simpleSelector);
8051 * Perform animation on this element.
8052 * @param {Object} args The YUI animation control args
8053 * @param {Float} duration (optional) How long the animation lasts in seconds (defaults to .35)
8054 * @param {Function} onComplete (optional) Function to call when animation completes
8055 * @param {String} easing (optional) Easing method to use (defaults to 'easeOut')
8056 * @param {String} animType (optional) 'run' is the default. Can also be 'color', 'motion', or 'scroll'
8057 * @return {Roo.Element} this
8059 animate : function(args, duration, onComplete, easing, animType){
8060 this.anim(args, {duration: duration, callback: onComplete, easing: easing}, animType);
8065 * @private Internal animation call
8067 anim : function(args, opt, animType, defaultDur, defaultEase, cb){
8068 animType = animType || 'run';
8070 var anim = Roo.lib.Anim[animType](
8072 (opt.duration || defaultDur) || .35,
8073 (opt.easing || defaultEase) || 'easeOut',
8075 Roo.callback(cb, this);
8076 Roo.callback(opt.callback, opt.scope || this, [this, opt]);
8084 // private legacy anim prep
8085 preanim : function(a, i){
8086 return !a[i] ? false : (typeof a[i] == "object" ? a[i]: {duration: a[i+1], callback: a[i+2], easing: a[i+3]});
8090 * Removes worthless text nodes
8091 * @param {Boolean} forceReclean (optional) By default the element
8092 * keeps track if it has been cleaned already so
8093 * you can call this over and over. However, if you update the element and
8094 * need to force a reclean, you can pass true.
8096 clean : function(forceReclean){
8097 if(this.isCleaned && forceReclean !== true){
8101 var d = this.dom, n = d.firstChild, ni = -1;
8103 var nx = n.nextSibling;
8104 if(n.nodeType == 3 && !ns.test(n.nodeValue)){
8111 this.isCleaned = true;
8116 calcOffsetsTo : function(el){
8119 var restorePos = false;
8120 if(el.getStyle('position') == 'static'){
8121 el.position('relative');
8126 while(op && op != d && op.tagName != 'HTML'){
8129 op = op.offsetParent;
8132 el.position('static');
8138 * Scrolls this element into view within the passed container.
8139 * @param {String/HTMLElement/Element} container (optional) The container element to scroll (defaults to document.body)
8140 * @param {Boolean} hscroll (optional) False to disable horizontal scroll (defaults to true)
8141 * @return {Roo.Element} this
8143 scrollIntoView : function(container, hscroll){
8144 var c = Roo.getDom(container) || document.body;
8147 var o = this.calcOffsetsTo(c),
8150 b = t+el.offsetHeight,
8151 r = l+el.offsetWidth;
8153 var ch = c.clientHeight;
8154 var ct = parseInt(c.scrollTop, 10);
8155 var cl = parseInt(c.scrollLeft, 10);
8157 var cr = cl + c.clientWidth;
8165 if(hscroll !== false){
8169 c.scrollLeft = r-c.clientWidth;
8176 scrollChildIntoView : function(child, hscroll){
8177 Roo.fly(child, '_scrollChildIntoView').scrollIntoView(this, hscroll);
8181 * Measures the element's content height and updates height to match. Note: this function uses setTimeout so
8182 * the new height may not be available immediately.
8183 * @param {Boolean} animate (optional) Animate the transition (defaults to false)
8184 * @param {Float} duration (optional) Length of the animation in seconds (defaults to .35)
8185 * @param {Function} onComplete (optional) Function to call when animation completes
8186 * @param {String} easing (optional) Easing method to use (defaults to easeOut)
8187 * @return {Roo.Element} this
8189 autoHeight : function(animate, duration, onComplete, easing){
8190 var oldHeight = this.getHeight();
8192 this.setHeight(1); // force clipping
8193 setTimeout(function(){
8194 var height = parseInt(this.dom.scrollHeight, 10); // parseInt for Safari
8196 this.setHeight(height);
8198 if(typeof onComplete == "function"){
8202 this.setHeight(oldHeight); // restore original height
8203 this.setHeight(height, animate, duration, function(){
8205 if(typeof onComplete == "function") { onComplete(); }
8206 }.createDelegate(this), easing);
8208 }.createDelegate(this), 0);
8213 * Returns true if this element is an ancestor of the passed element
8214 * @param {HTMLElement/String} el The element to check
8215 * @return {Boolean} True if this element is an ancestor of el, else false
8217 contains : function(el){
8218 if(!el){return false;}
8219 return D.isAncestor(this.dom, el.dom ? el.dom : el);
8223 * Checks whether the element is currently visible using both visibility and display properties.
8224 * @param {Boolean} deep (optional) True to walk the dom and see if parent elements are hidden (defaults to false)
8225 * @return {Boolean} True if the element is currently visible, else false
8227 isVisible : function(deep) {
8228 var vis = !(this.getStyle("visibility") == "hidden" || this.getStyle("display") == "none");
8229 if(deep !== true || !vis){
8232 var p = this.dom.parentNode;
8233 while(p && p.tagName.toLowerCase() != "body"){
8234 if(!Roo.fly(p, '_isVisible').isVisible()){
8243 * Creates a {@link Roo.CompositeElement} for child nodes based on the passed CSS selector (the selector should not contain an id).
8244 * @param {String} selector The CSS selector
8245 * @param {Boolean} unique (optional) True to create a unique Roo.Element for each child (defaults to false, which creates a single shared flyweight object)
8246 * @return {CompositeElement/CompositeElementLite} The composite element
8248 select : function(selector, unique){
8249 return El.select(selector, unique, this.dom);
8253 * Selects child nodes based on the passed CSS selector (the selector should not contain an id).
8254 * @param {String} selector The CSS selector
8255 * @return {Array} An array of the matched nodes
8257 query : function(selector, unique){
8258 return Roo.DomQuery.select(selector, this.dom);
8262 * Selects a single child at any depth below this element based on the passed CSS selector (the selector should not contain an id).
8263 * @param {String} selector The CSS selector
8264 * @param {Boolean} returnDom (optional) True to return the DOM node instead of Roo.Element (defaults to false)
8265 * @return {HTMLElement/Roo.Element} The child Roo.Element (or DOM node if returnDom = true)
8267 child : function(selector, returnDom){
8268 var n = Roo.DomQuery.selectNode(selector, this.dom);
8269 return returnDom ? n : Roo.get(n);
8273 * Selects a single *direct* child based on the passed CSS selector (the selector should not contain an id).
8274 * @param {String} selector The CSS selector
8275 * @param {Boolean} returnDom (optional) True to return the DOM node instead of Roo.Element (defaults to false)
8276 * @return {HTMLElement/Roo.Element} The child Roo.Element (or DOM node if returnDom = true)
8278 down : function(selector, returnDom){
8279 var n = Roo.DomQuery.selectNode(" > " + selector, this.dom);
8280 return returnDom ? n : Roo.get(n);
8284 * Initializes a {@link Roo.dd.DD} drag drop object for this element.
8285 * @param {String} group The group the DD object is member of
8286 * @param {Object} config The DD config object
8287 * @param {Object} overrides An object containing methods to override/implement on the DD object
8288 * @return {Roo.dd.DD} The DD object
8290 initDD : function(group, config, overrides){
8291 var dd = new Roo.dd.DD(Roo.id(this.dom), group, config);
8292 return Roo.apply(dd, overrides);
8296 * Initializes a {@link Roo.dd.DDProxy} object for this element.
8297 * @param {String} group The group the DDProxy object is member of
8298 * @param {Object} config The DDProxy config object
8299 * @param {Object} overrides An object containing methods to override/implement on the DDProxy object
8300 * @return {Roo.dd.DDProxy} The DDProxy object
8302 initDDProxy : function(group, config, overrides){
8303 var dd = new Roo.dd.DDProxy(Roo.id(this.dom), group, config);
8304 return Roo.apply(dd, overrides);
8308 * Initializes a {@link Roo.dd.DDTarget} object for this element.
8309 * @param {String} group The group the DDTarget object is member of
8310 * @param {Object} config The DDTarget config object
8311 * @param {Object} overrides An object containing methods to override/implement on the DDTarget object
8312 * @return {Roo.dd.DDTarget} The DDTarget object
8314 initDDTarget : function(group, config, overrides){
8315 var dd = new Roo.dd.DDTarget(Roo.id(this.dom), group, config);
8316 return Roo.apply(dd, overrides);
8320 * Sets the visibility of the element (see details). If the visibilityMode is set to Element.DISPLAY, it will use
8321 * the display property to hide the element, otherwise it uses visibility. The default is to hide and show using the visibility property.
8322 * @param {Boolean} visible Whether the element is visible
8323 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8324 * @return {Roo.Element} this
8326 setVisible : function(visible, animate){
8328 if(this.visibilityMode == El.DISPLAY){
8329 this.setDisplayed(visible);
8332 this.dom.style.visibility = visible ? "visible" : "hidden";
8335 // closure for composites
8337 var visMode = this.visibilityMode;
8339 this.setOpacity(.01);
8340 this.setVisible(true);
8342 this.anim({opacity: { to: (visible?1:0) }},
8343 this.preanim(arguments, 1),
8344 null, .35, 'easeIn', function(){
8346 if(visMode == El.DISPLAY){
8347 dom.style.display = "none";
8349 dom.style.visibility = "hidden";
8351 Roo.get(dom).setOpacity(1);
8359 * Returns true if display is not "none"
8362 isDisplayed : function() {
8363 return this.getStyle("display") != "none";
8367 * Toggles the element's visibility or display, depending on visibility mode.
8368 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8369 * @return {Roo.Element} this
8371 toggle : function(animate){
8372 this.setVisible(!this.isVisible(), this.preanim(arguments, 0));
8377 * Sets the CSS display property. Uses originalDisplay if the specified value is a boolean true.
8378 * @param {Boolean} value Boolean value to display the element using its default display, or a string to set the display directly
8379 * @return {Roo.Element} this
8381 setDisplayed : function(value) {
8382 if(typeof value == "boolean"){
8383 value = value ? this.originalDisplay : "none";
8385 this.setStyle("display", value);
8390 * Tries to focus the element. Any exceptions are caught and ignored.
8391 * @return {Roo.Element} this
8393 focus : function() {
8401 * Tries to blur the element. Any exceptions are caught and ignored.
8402 * @return {Roo.Element} this
8412 * Adds one or more CSS classes to the element. Duplicate classes are automatically filtered out.
8413 * @param {String/Array} className The CSS class to add, or an array of classes
8414 * @return {Roo.Element} this
8416 addClass : function(className){
8417 if(className instanceof Array){
8418 for(var i = 0, len = className.length; i < len; i++) {
8419 this.addClass(className[i]);
8422 if(className && !this.hasClass(className)){
8423 if (this.dom instanceof SVGElement) {
8424 this.dom.className.baseVal =this.dom.className.baseVal + " " + className;
8426 this.dom.className = this.dom.className + " " + className;
8434 * Adds one or more CSS classes to this element and removes the same class(es) from all siblings.
8435 * @param {String/Array} className The CSS class to add, or an array of classes
8436 * @return {Roo.Element} this
8438 radioClass : function(className){
8439 var siblings = this.dom.parentNode.childNodes;
8440 for(var i = 0; i < siblings.length; i++) {
8441 var s = siblings[i];
8442 if(s.nodeType == 1){
8443 Roo.get(s).removeClass(className);
8446 this.addClass(className);
8451 * Removes one or more CSS classes from the element.
8452 * @param {String/Array} className The CSS class to remove, or an array of classes
8453 * @return {Roo.Element} this
8455 removeClass : function(className){
8457 var cn = this.dom instanceof SVGElement ? this.dom.className.baseVal : this.dom.className;
8458 if(!className || !cn){
8461 if(className instanceof Array){
8462 for(var i = 0, len = className.length; i < len; i++) {
8463 this.removeClass(className[i]);
8466 if(this.hasClass(className)){
8467 var re = this.classReCache[className];
8469 re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)', "g");
8470 this.classReCache[className] = re;
8472 if (this.dom instanceof SVGElement) {
8473 this.dom.className.baseVal = cn.replace(re, " ");
8475 this.dom.className = cn.replace(re, " ");
8486 * Toggles the specified CSS class on this element (removes it if it already exists, otherwise adds it).
8487 * @param {String} className The CSS class to toggle
8488 * @return {Roo.Element} this
8490 toggleClass : function(className){
8491 if(this.hasClass(className)){
8492 this.removeClass(className);
8494 this.addClass(className);
8500 * Checks if the specified CSS class exists on this element's DOM node.
8501 * @param {String} className The CSS class to check for
8502 * @return {Boolean} True if the class exists, else false
8504 hasClass : function(className){
8505 if (this.dom instanceof SVGElement) {
8506 return className && (' '+this.dom.className.baseVal +' ').indexOf(' '+className+' ') != -1;
8508 return className && (' '+this.dom.className+' ').indexOf(' '+className+' ') != -1;
8512 * Replaces a CSS class on the element with another. If the old name does not exist, the new name will simply be added.
8513 * @param {String} oldClassName The CSS class to replace
8514 * @param {String} newClassName The replacement CSS class
8515 * @return {Roo.Element} this
8517 replaceClass : function(oldClassName, newClassName){
8518 this.removeClass(oldClassName);
8519 this.addClass(newClassName);
8524 * Returns an object with properties matching the styles requested.
8525 * For example, el.getStyles('color', 'font-size', 'width') might return
8526 * {'color': '#FFFFFF', 'font-size': '13px', 'width': '100px'}.
8527 * @param {String} style1 A style name
8528 * @param {String} style2 A style name
8529 * @param {String} etc.
8530 * @return {Object} The style object
8532 getStyles : function(){
8533 var a = arguments, len = a.length, r = {};
8534 for(var i = 0; i < len; i++){
8535 r[a[i]] = this.getStyle(a[i]);
8541 * Normalizes currentStyle and computedStyle. This is not YUI getStyle, it is an optimised version.
8542 * @param {String} property The style property whose value is returned.
8543 * @return {String} The current value of the style property for this element.
8545 getStyle : function(){
8546 return view && view.getComputedStyle ?
8548 var el = this.dom, v, cs, camel;
8549 if(prop == 'float'){
8552 if(el.style && (v = el.style[prop])){
8555 if(cs = view.getComputedStyle(el, "")){
8556 if(!(camel = propCache[prop])){
8557 camel = propCache[prop] = prop.replace(camelRe, camelFn);
8564 var el = this.dom, v, cs, camel;
8565 if(prop == 'opacity'){
8566 if(typeof el.style.filter == 'string'){
8567 var m = el.style.filter.match(/alpha\(opacity=(.*)\)/i);
8569 var fv = parseFloat(m[1]);
8571 return fv ? fv / 100 : 0;
8576 }else if(prop == 'float'){
8577 prop = "styleFloat";
8579 if(!(camel = propCache[prop])){
8580 camel = propCache[prop] = prop.replace(camelRe, camelFn);
8582 if(v = el.style[camel]){
8585 if(cs = el.currentStyle){
8593 * Wrapper for setting style properties, also takes single object parameter of multiple styles.
8594 * @param {String/Object} property The style property to be set, or an object of multiple styles.
8595 * @param {String} value (optional) The value to apply to the given property, or null if an object was passed.
8596 * @return {Roo.Element} this
8598 setStyle : function(prop, value){
8599 if(typeof prop == "string"){
8601 if (prop == 'float') {
8602 this.setStyle(Roo.isIE ? 'styleFloat' : 'cssFloat', value);
8607 if(!(camel = propCache[prop])){
8608 camel = propCache[prop] = prop.replace(camelRe, camelFn);
8611 if(camel == 'opacity') {
8612 this.setOpacity(value);
8614 this.dom.style[camel] = value;
8617 for(var style in prop){
8618 if(typeof prop[style] != "function"){
8619 this.setStyle(style, prop[style]);
8627 * More flexible version of {@link #setStyle} for setting style properties.
8628 * @param {String/Object/Function} styles A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
8629 * a function which returns such a specification.
8630 * @return {Roo.Element} this
8632 applyStyles : function(style){
8633 Roo.DomHelper.applyStyles(this.dom, style);
8638 * 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).
8639 * @return {Number} The X position of the element
8642 return D.getX(this.dom);
8646 * 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).
8647 * @return {Number} The Y position of the element
8650 return D.getY(this.dom);
8654 * 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).
8655 * @return {Array} The XY position of the element
8658 return D.getXY(this.dom);
8662 * 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).
8663 * @param {Number} The X position of the element
8664 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8665 * @return {Roo.Element} this
8667 setX : function(x, animate){
8669 D.setX(this.dom, x);
8671 this.setXY([x, this.getY()], this.preanim(arguments, 1));
8677 * 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).
8678 * @param {Number} The Y position of the element
8679 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8680 * @return {Roo.Element} this
8682 setY : function(y, animate){
8684 D.setY(this.dom, y);
8686 this.setXY([this.getX(), y], this.preanim(arguments, 1));
8692 * Sets the element's left position directly using CSS style (instead of {@link #setX}).
8693 * @param {String} left The left CSS property value
8694 * @return {Roo.Element} this
8696 setLeft : function(left){
8697 this.setStyle("left", this.addUnits(left));
8702 * Sets the element's top position directly using CSS style (instead of {@link #setY}).
8703 * @param {String} top The top CSS property value
8704 * @return {Roo.Element} this
8706 setTop : function(top){
8707 this.setStyle("top", this.addUnits(top));
8712 * Sets the element's CSS right style.
8713 * @param {String} right The right CSS property value
8714 * @return {Roo.Element} this
8716 setRight : function(right){
8717 this.setStyle("right", this.addUnits(right));
8722 * Sets the element's CSS bottom style.
8723 * @param {String} bottom The bottom CSS property value
8724 * @return {Roo.Element} this
8726 setBottom : function(bottom){
8727 this.setStyle("bottom", this.addUnits(bottom));
8732 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
8733 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
8734 * @param {Array} pos Contains X & Y [x, y] values for new position (coordinates are page-based)
8735 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8736 * @return {Roo.Element} this
8738 setXY : function(pos, animate){
8740 D.setXY(this.dom, pos);
8742 this.anim({points: {to: pos}}, this.preanim(arguments, 1), 'motion');
8748 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
8749 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
8750 * @param {Number} x X value for new position (coordinates are page-based)
8751 * @param {Number} y Y value for new position (coordinates are page-based)
8752 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8753 * @return {Roo.Element} this
8755 setLocation : function(x, y, animate){
8756 this.setXY([x, y], this.preanim(arguments, 2));
8761 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
8762 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
8763 * @param {Number} x X value for new position (coordinates are page-based)
8764 * @param {Number} y Y value for new position (coordinates are page-based)
8765 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8766 * @return {Roo.Element} this
8768 moveTo : function(x, y, animate){
8769 this.setXY([x, y], this.preanim(arguments, 2));
8774 * Returns the region of the given element.
8775 * The element must be part of the DOM tree to have a region (display:none or elements not appended return false).
8776 * @return {Region} A Roo.lib.Region containing "top, left, bottom, right" member data.
8778 getRegion : function(){
8779 return D.getRegion(this.dom);
8783 * Returns the offset height of the element
8784 * @param {Boolean} contentHeight (optional) true to get the height minus borders and padding
8785 * @return {Number} The element's height
8787 getHeight : function(contentHeight){
8788 var h = this.dom.offsetHeight || 0;
8789 return contentHeight !== true ? h : h-this.getBorderWidth("tb")-this.getPadding("tb");
8793 * Returns the offset width of the element
8794 * @param {Boolean} contentWidth (optional) true to get the width minus borders and padding
8795 * @return {Number} The element's width
8797 getWidth : function(contentWidth){
8798 var w = this.dom.offsetWidth || 0;
8799 return contentWidth !== true ? w : w-this.getBorderWidth("lr")-this.getPadding("lr");
8803 * Returns either the offsetHeight or the height of this element based on CSS height adjusted by padding or borders
8804 * when needed to simulate offsetHeight when offsets aren't available. This may not work on display:none elements
8805 * if a height has not been set using CSS.
8808 getComputedHeight : function(){
8809 var h = Math.max(this.dom.offsetHeight, this.dom.clientHeight);
8811 h = parseInt(this.getStyle('height'), 10) || 0;
8812 if(!this.isBorderBox()){
8813 h += this.getFrameWidth('tb');
8820 * Returns either the offsetWidth or the width of this element based on CSS width adjusted by padding or borders
8821 * when needed to simulate offsetWidth when offsets aren't available. This may not work on display:none elements
8822 * if a width has not been set using CSS.
8825 getComputedWidth : function(){
8826 var w = Math.max(this.dom.offsetWidth, this.dom.clientWidth);
8828 w = parseInt(this.getStyle('width'), 10) || 0;
8829 if(!this.isBorderBox()){
8830 w += this.getFrameWidth('lr');
8837 * Returns the size of the element.
8838 * @param {Boolean} contentSize (optional) true to get the width/size minus borders and padding
8839 * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
8841 getSize : function(contentSize){
8842 return {width: this.getWidth(contentSize), height: this.getHeight(contentSize)};
8846 * Returns the width and height of the viewport.
8847 * @return {Object} An object containing the viewport's size {width: (viewport width), height: (viewport height)}
8849 getViewSize : function(){
8850 var d = this.dom, doc = document, aw = 0, ah = 0;
8851 if(d == doc || d == doc.body){
8852 return {width : D.getViewWidth(), height: D.getViewHeight()};
8855 width : d.clientWidth,
8856 height: d.clientHeight
8862 * Returns the value of the "value" attribute
8863 * @param {Boolean} asNumber true to parse the value as a number
8864 * @return {String/Number}
8866 getValue : function(asNumber){
8867 return asNumber ? parseInt(this.dom.value, 10) : this.dom.value;
8871 adjustWidth : function(width){
8872 if(typeof width == "number"){
8873 if(this.autoBoxAdjust && !this.isBorderBox()){
8874 width -= (this.getBorderWidth("lr") + this.getPadding("lr"));
8884 adjustHeight : function(height){
8885 if(typeof height == "number"){
8886 if(this.autoBoxAdjust && !this.isBorderBox()){
8887 height -= (this.getBorderWidth("tb") + this.getPadding("tb"));
8897 * Set the width of the element
8898 * @param {Number} width The new width
8899 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8900 * @return {Roo.Element} this
8902 setWidth : function(width, animate){
8903 width = this.adjustWidth(width);
8905 this.dom.style.width = this.addUnits(width);
8907 this.anim({width: {to: width}}, this.preanim(arguments, 1));
8913 * Set the height of the element
8914 * @param {Number} height The new height
8915 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8916 * @return {Roo.Element} this
8918 setHeight : function(height, animate){
8919 height = this.adjustHeight(height);
8921 this.dom.style.height = this.addUnits(height);
8923 this.anim({height: {to: height}}, this.preanim(arguments, 1));
8929 * Set the size of the element. If animation is true, both width an height will be animated concurrently.
8930 * @param {Number} width The new width
8931 * @param {Number} height The new height
8932 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8933 * @return {Roo.Element} this
8935 setSize : function(width, height, animate){
8936 if(typeof width == "object"){ // in case of object from getSize()
8937 height = width.height; width = width.width;
8939 width = this.adjustWidth(width); height = this.adjustHeight(height);
8941 this.dom.style.width = this.addUnits(width);
8942 this.dom.style.height = this.addUnits(height);
8944 this.anim({width: {to: width}, height: {to: height}}, this.preanim(arguments, 2));
8950 * Sets the element's position and size in one shot. If animation is true then width, height, x and y will be animated concurrently.
8951 * @param {Number} x X value for new position (coordinates are page-based)
8952 * @param {Number} y Y value for new position (coordinates are page-based)
8953 * @param {Number} width The new width
8954 * @param {Number} height The new height
8955 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8956 * @return {Roo.Element} this
8958 setBounds : function(x, y, width, height, animate){
8960 this.setSize(width, height);
8961 this.setLocation(x, y);
8963 width = this.adjustWidth(width); height = this.adjustHeight(height);
8964 this.anim({points: {to: [x, y]}, width: {to: width}, height: {to: height}},
8965 this.preanim(arguments, 4), 'motion');
8971 * 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.
8972 * @param {Roo.lib.Region} region The region to fill
8973 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
8974 * @return {Roo.Element} this
8976 setRegion : function(region, animate){
8977 this.setBounds(region.left, region.top, region.right-region.left, region.bottom-region.top, this.preanim(arguments, 1));
8982 * Appends an event handler
8984 * @param {String} eventName The type of event to append
8985 * @param {Function} fn The method the event invokes
8986 * @param {Object} scope (optional) The scope (this object) of the fn
8987 * @param {Object} options (optional)An object with standard {@link Roo.EventManager#addListener} options
8989 addListener : function(eventName, fn, scope, options)
8991 if (eventName == 'dblclick') { // doublclick (touchstart) - faked on touch.
8992 this.addListener('touchstart', this.onTapHandler, this);
8995 // we need to handle a special case where dom element is a svg element.
8996 // in this case we do not actua
9001 if (this.dom instanceof SVGElement && !(this.dom instanceof SVGSVGElement)) {
9002 if (typeof(this.listeners[eventName]) == 'undefined') {
9003 this.listeners[eventName] = new Roo.util.Event(this, eventName);
9005 this.listeners[eventName].addListener(fn, scope, options);
9010 Roo.EventManager.on(this.dom, eventName, fn, scope || this, options);
9015 onTapHandler : function(event)
9017 if(!this.tapedTwice) {
9018 this.tapedTwice = true;
9020 setTimeout( function() {
9021 s.tapedTwice = false;
9025 event.preventDefault();
9026 var revent = new MouseEvent('dblclick', {
9032 this.dom.dispatchEvent(revent);
9033 //action on double tap goes below
9038 * Removes an event handler from this element
9039 * @param {String} eventName the type of event to remove
9040 * @param {Function} fn the method the event invokes
9041 * @param {Function} scope (needed for svg fake listeners)
9042 * @return {Roo.Element} this
9044 removeListener : function(eventName, fn, scope){
9045 Roo.EventManager.removeListener(this.dom, eventName, fn);
9046 if (typeof(this.listeners) == 'undefined' || typeof(this.listeners[eventName]) == 'undefined') {
9049 this.listeners[eventName].removeListener(fn, scope);
9054 * Removes all previous added listeners from this element
9055 * @return {Roo.Element} this
9057 removeAllListeners : function(){
9058 E.purgeElement(this.dom);
9059 this.listeners = {};
9063 relayEvent : function(eventName, observable){
9064 this.on(eventName, function(e){
9065 observable.fireEvent(eventName, e);
9071 * Set the opacity of the element
9072 * @param {Float} opacity The new opacity. 0 = transparent, .5 = 50% visibile, 1 = fully visible, etc
9073 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9074 * @return {Roo.Element} this
9076 setOpacity : function(opacity, animate){
9078 var s = this.dom.style;
9081 s.filter = (s.filter || '').replace(/alpha\([^\)]*\)/gi,"") +
9082 (opacity == 1 ? "" : "alpha(opacity=" + opacity * 100 + ")");
9084 s.opacity = opacity;
9087 this.anim({opacity: {to: opacity}}, this.preanim(arguments, 1), null, .35, 'easeIn');
9093 * Gets the left X coordinate
9094 * @param {Boolean} local True to get the local css position instead of page coordinate
9097 getLeft : function(local){
9101 return parseInt(this.getStyle("left"), 10) || 0;
9106 * Gets the right X coordinate of the element (element X position + element width)
9107 * @param {Boolean} local True to get the local css position instead of page coordinate
9110 getRight : function(local){
9112 return this.getX() + this.getWidth();
9114 return (this.getLeft(true) + this.getWidth()) || 0;
9119 * Gets the top Y coordinate
9120 * @param {Boolean} local True to get the local css position instead of page coordinate
9123 getTop : function(local) {
9127 return parseInt(this.getStyle("top"), 10) || 0;
9132 * Gets the bottom Y coordinate of the element (element Y position + element height)
9133 * @param {Boolean} local True to get the local css position instead of page coordinate
9136 getBottom : function(local){
9138 return this.getY() + this.getHeight();
9140 return (this.getTop(true) + this.getHeight()) || 0;
9145 * Initializes positioning on this element. If a desired position is not passed, it will make the
9146 * the element positioned relative IF it is not already positioned.
9147 * @param {String} pos (optional) Positioning to use "relative", "absolute" or "fixed"
9148 * @param {Number} zIndex (optional) The zIndex to apply
9149 * @param {Number} x (optional) Set the page X position
9150 * @param {Number} y (optional) Set the page Y position
9152 position : function(pos, zIndex, x, y){
9154 if(this.getStyle('position') == 'static'){
9155 this.setStyle('position', 'relative');
9158 this.setStyle("position", pos);
9161 this.setStyle("z-index", zIndex);
9163 if(x !== undefined && y !== undefined){
9165 }else if(x !== undefined){
9167 }else if(y !== undefined){
9173 * Clear positioning back to the default when the document was loaded
9174 * @param {String} value (optional) The value to use for the left,right,top,bottom, defaults to '' (empty string). You could use 'auto'.
9175 * @return {Roo.Element} this
9177 clearPositioning : function(value){
9185 "position" : "static"
9191 * Gets an object with all CSS positioning properties. Useful along with setPostioning to get
9192 * snapshot before performing an update and then restoring the element.
9195 getPositioning : function(){
9196 var l = this.getStyle("left");
9197 var t = this.getStyle("top");
9199 "position" : this.getStyle("position"),
9201 "right" : l ? "" : this.getStyle("right"),
9203 "bottom" : t ? "" : this.getStyle("bottom"),
9204 "z-index" : this.getStyle("z-index")
9209 * Gets the width of the border(s) for the specified side(s)
9210 * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
9211 * passing lr would get the border (l)eft width + the border (r)ight width.
9212 * @return {Number} The width of the sides passed added together
9214 getBorderWidth : function(side){
9215 return this.addStyles(side, El.borders);
9219 * Gets the width of the padding(s) for the specified side(s)
9220 * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
9221 * passing lr would get the padding (l)eft + the padding (r)ight.
9222 * @return {Number} The padding of the sides passed added together
9224 getPadding : function(side){
9225 return this.addStyles(side, El.paddings);
9229 * Set positioning with an object returned by getPositioning().
9230 * @param {Object} posCfg
9231 * @return {Roo.Element} this
9233 setPositioning : function(pc){
9234 this.applyStyles(pc);
9235 if(pc.right == "auto"){
9236 this.dom.style.right = "";
9238 if(pc.bottom == "auto"){
9239 this.dom.style.bottom = "";
9245 fixDisplay : function(){
9246 if(this.getStyle("display") == "none"){
9247 this.setStyle("visibility", "hidden");
9248 this.setStyle("display", this.originalDisplay); // first try reverting to default
9249 if(this.getStyle("display") == "none"){ // if that fails, default to block
9250 this.setStyle("display", "block");
9256 * Quick set left and top adding default units
9257 * @param {String} left The left CSS property value
9258 * @param {String} top The top CSS property value
9259 * @return {Roo.Element} this
9261 setLeftTop : function(left, top){
9262 this.dom.style.left = this.addUnits(left);
9263 this.dom.style.top = this.addUnits(top);
9268 * Move this element relative to its current position.
9269 * @param {String} direction Possible values are: "l","left" - "r","right" - "t","top","up" - "b","bottom","down".
9270 * @param {Number} distance How far to move the element in pixels
9271 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9272 * @return {Roo.Element} this
9274 move : function(direction, distance, animate){
9275 var xy = this.getXY();
9276 direction = direction.toLowerCase();
9280 this.moveTo(xy[0]-distance, xy[1], this.preanim(arguments, 2));
9284 this.moveTo(xy[0]+distance, xy[1], this.preanim(arguments, 2));
9289 this.moveTo(xy[0], xy[1]-distance, this.preanim(arguments, 2));
9294 this.moveTo(xy[0], xy[1]+distance, this.preanim(arguments, 2));
9301 * Store the current overflow setting and clip overflow on the element - use {@link #unclip} to remove
9302 * @return {Roo.Element} this
9305 if(!this.isClipped){
9306 this.isClipped = true;
9307 this.originalClip = {
9308 "o": this.getStyle("overflow"),
9309 "x": this.getStyle("overflow-x"),
9310 "y": this.getStyle("overflow-y")
9312 this.setStyle("overflow", "hidden");
9313 this.setStyle("overflow-x", "hidden");
9314 this.setStyle("overflow-y", "hidden");
9320 * Return clipping (overflow) to original clipping before clip() was called
9321 * @return {Roo.Element} this
9323 unclip : function(){
9325 this.isClipped = false;
9326 var o = this.originalClip;
9327 if(o.o){this.setStyle("overflow", o.o);}
9328 if(o.x){this.setStyle("overflow-x", o.x);}
9329 if(o.y){this.setStyle("overflow-y", o.y);}
9336 * Gets the x,y coordinates specified by the anchor position on the element.
9337 * @param {String} anchor (optional) The specified anchor position (defaults to "c"). See {@link #alignTo} for details on supported anchor positions.
9338 * @param {Object} size (optional) An object containing the size to use for calculating anchor position
9339 * {width: (target width), height: (target height)} (defaults to the element's current size)
9340 * @param {Boolean} local (optional) True to get the local (element top/left-relative) anchor position instead of page coordinates
9341 * @return {Array} [x, y] An array containing the element's x and y coordinates
9343 getAnchorXY : function(anchor, local, s){
9344 //Passing a different size is useful for pre-calculating anchors,
9345 //especially for anchored animations that change the el size.
9347 var w, h, vp = false;
9350 if(d == document.body || d == document){
9352 w = D.getViewWidth(); h = D.getViewHeight();
9354 w = this.getWidth(); h = this.getHeight();
9357 w = s.width; h = s.height;
9359 var x = 0, y = 0, r = Math.round;
9360 switch((anchor || "tl").toLowerCase()){
9402 var sc = this.getScroll();
9403 return [x + sc.left, y + sc.top];
9405 //Add the element's offset xy
9406 var o = this.getXY();
9407 return [x+o[0], y+o[1]];
9411 * Gets the x,y coordinates to align this element with another element. See {@link #alignTo} for more info on the
9412 * supported position values.
9413 * @param {String/HTMLElement/Roo.Element} element The element to align to.
9414 * @param {String} position The position to align to.
9415 * @param {Array} offsets (optional) Offset the positioning by [x, y]
9416 * @return {Array} [x, y]
9418 getAlignToXY : function(el, p, o)
9423 throw "Element.alignTo with an element that doesn't exist";
9425 var c = false; //constrain to viewport
9426 var p1 = "", p2 = "";
9433 }else if(p.indexOf("-") == -1){
9436 p = p.toLowerCase();
9437 var m = p.match(/^([a-z]+)-([a-z]+)(\?)?$/);
9439 throw "Element.alignTo with an invalid alignment " + p;
9441 p1 = m[1]; p2 = m[2]; c = !!m[3];
9443 //Subtract the aligned el's internal xy from the target's offset xy
9444 //plus custom offset to get the aligned el's new offset xy
9445 var a1 = this.getAnchorXY(p1, true);
9446 var a2 = el.getAnchorXY(p2, false);
9447 var x = a2[0] - a1[0] + o[0];
9448 var y = a2[1] - a1[1] + o[1];
9450 //constrain the aligned el to viewport if necessary
9451 var w = this.getWidth(), h = this.getHeight(), r = el.getRegion();
9452 // 5px of margin for ie
9453 var dw = D.getViewWidth()-5, dh = D.getViewHeight()-5;
9455 //If we are at a viewport boundary and the aligned el is anchored on a target border that is
9456 //perpendicular to the vp border, allow the aligned el to slide on that border,
9457 //otherwise swap the aligned el to the opposite border of the target.
9458 var p1y = p1.charAt(0), p1x = p1.charAt(p1.length-1);
9459 var p2y = p2.charAt(0), p2x = p2.charAt(p2.length-1);
9460 var swapY = ((p1y=="t" && p2y=="b") || (p1y=="b" && p2y=="t") );
9461 var swapX = ((p1x=="r" && p2x=="l") || (p1x=="l" && p2x=="r"));
9464 var scrollX = (doc.documentElement.scrollLeft || doc.body.scrollLeft || 0)+5;
9465 var scrollY = (doc.documentElement.scrollTop || doc.body.scrollTop || 0)+5;
9467 if((x+w) > dw + scrollX){
9468 x = swapX ? r.left-w : dw+scrollX-w;
9471 x = swapX ? r.right : scrollX;
9473 if((y+h) > dh + scrollY){
9474 y = swapY ? r.top-h : dh+scrollY-h;
9477 y = swapY ? r.bottom : scrollY;
9484 getConstrainToXY : function(){
9485 var os = {top:0, left:0, bottom:0, right: 0};
9487 return function(el, local, offsets, proposedXY){
9489 offsets = offsets ? Roo.applyIf(offsets, os) : os;
9491 var vw, vh, vx = 0, vy = 0;
9492 if(el.dom == document.body || el.dom == document){
9493 vw = Roo.lib.Dom.getViewWidth();
9494 vh = Roo.lib.Dom.getViewHeight();
9496 vw = el.dom.clientWidth;
9497 vh = el.dom.clientHeight;
9499 var vxy = el.getXY();
9505 var s = el.getScroll();
9507 vx += offsets.left + s.left;
9508 vy += offsets.top + s.top;
9510 vw -= offsets.right;
9511 vh -= offsets.bottom;
9516 var xy = proposedXY || (!local ? this.getXY() : [this.getLeft(true), this.getTop(true)]);
9517 var x = xy[0], y = xy[1];
9518 var w = this.dom.offsetWidth, h = this.dom.offsetHeight;
9520 // only move it if it needs it
9523 // first validate right/bottom
9532 // then make sure top/left isn't negative
9541 return moved ? [x, y] : false;
9546 adjustForConstraints : function(xy, parent, offsets){
9547 return this.getConstrainToXY(parent || document, false, offsets, xy) || xy;
9551 * Aligns this element with another element relative to the specified anchor points. If the other element is the
9552 * document it aligns it to the viewport.
9553 * The position parameter is optional, and can be specified in any one of the following formats:
9555 * <li><b>Blank</b>: Defaults to aligning the element's top-left corner to the target's bottom-left corner ("tl-bl").</li>
9556 * <li><b>One anchor (deprecated)</b>: The passed anchor position is used as the target element's anchor point.
9557 * The element being aligned will position its top-left corner (tl) to that point. <i>This method has been
9558 * deprecated in favor of the newer two anchor syntax below</i>.</li>
9559 * <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
9560 * element's anchor point, and the second value is used as the target's anchor point.</li>
9562 * In addition to the anchor points, the position parameter also supports the "?" character. If "?" is passed at the end of
9563 * the position string, the element will attempt to align as specified, but the position will be adjusted to constrain to
9564 * the viewport if necessary. Note that the element being aligned might be swapped to align to a different position than
9565 * that specified in order to enforce the viewport constraints.
9566 * Following are all of the supported anchor positions:
9569 ----- -----------------------------
9570 tl The top left corner (default)
9571 t The center of the top edge
9572 tr The top right corner
9573 l The center of the left edge
9574 c In the center of the element
9575 r The center of the right edge
9576 bl The bottom left corner
9577 b The center of the bottom edge
9578 br The bottom right corner
9582 // align el to other-el using the default positioning ("tl-bl", non-constrained)
9583 el.alignTo("other-el");
9585 // align the top left corner of el with the top right corner of other-el (constrained to viewport)
9586 el.alignTo("other-el", "tr?");
9588 // align the bottom right corner of el with the center left edge of other-el
9589 el.alignTo("other-el", "br-l?");
9591 // align the center of el with the bottom left corner of other-el and
9592 // adjust the x position by -6 pixels (and the y position by 0)
9593 el.alignTo("other-el", "c-bl", [-6, 0]);
9595 * @param {String/HTMLElement/Roo.Element} element The element to align to.
9596 * @param {String} position The position to align to.
9597 * @param {Array} offsets (optional) Offset the positioning by [x, y]
9598 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9599 * @return {Roo.Element} this
9601 alignTo : function(element, position, offsets, animate){
9602 var xy = this.getAlignToXY(element, position, offsets);
9603 this.setXY(xy, this.preanim(arguments, 3));
9608 * Anchors an element to another element and realigns it when the window is resized.
9609 * @param {String/HTMLElement/Roo.Element} element The element to align to.
9610 * @param {String} position The position to align to.
9611 * @param {Array} offsets (optional) Offset the positioning by [x, y]
9612 * @param {Boolean/Object} animate (optional) True for the default animation or a standard Element animation config object
9613 * @param {Boolean/Number} monitorScroll (optional) True to monitor body scroll and reposition. If this parameter
9614 * is a number, it is used as the buffer delay (defaults to 50ms).
9615 * @param {Function} callback The function to call after the animation finishes
9616 * @return {Roo.Element} this
9618 anchorTo : function(el, alignment, offsets, animate, monitorScroll, callback){
9619 var action = function(){
9620 this.alignTo(el, alignment, offsets, animate);
9621 Roo.callback(callback, this);
9623 Roo.EventManager.onWindowResize(action, this);
9624 var tm = typeof monitorScroll;
9625 if(tm != 'undefined'){
9626 Roo.EventManager.on(window, 'scroll', action, this,
9627 {buffer: tm == 'number' ? monitorScroll : 50});
9629 action.call(this); // align immediately
9633 * Clears any opacity settings from this element. Required in some cases for IE.
9634 * @return {Roo.Element} this
9636 clearOpacity : function(){
9637 if (window.ActiveXObject) {
9638 if(typeof this.dom.style.filter == 'string' && (/alpha/i).test(this.dom.style.filter)){
9639 this.dom.style.filter = "";
9642 this.dom.style.opacity = "";
9643 this.dom.style["-moz-opacity"] = "";
9644 this.dom.style["-khtml-opacity"] = "";
9650 * Hide this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
9651 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9652 * @return {Roo.Element} this
9654 hide : function(animate){
9655 this.setVisible(false, this.preanim(arguments, 0));
9660 * Show this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
9661 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9662 * @return {Roo.Element} this
9664 show : function(animate){
9665 this.setVisible(true, this.preanim(arguments, 0));
9670 * @private Test if size has a unit, otherwise appends the default
9672 addUnits : function(size){
9673 return Roo.Element.addUnits(size, this.defaultUnit);
9677 * Temporarily enables offsets (width,height,x,y) for an element with display:none, use endMeasure() when done.
9678 * @return {Roo.Element} this
9680 beginMeasure : function(){
9682 if(el.offsetWidth || el.offsetHeight){
9683 return this; // offsets work already
9686 var p = this.dom, b = document.body; // start with this element
9687 while((!el.offsetWidth && !el.offsetHeight) && p && p.tagName && p != b){
9688 var pe = Roo.get(p);
9689 if(pe.getStyle('display') == 'none'){
9690 changed.push({el: p, visibility: pe.getStyle("visibility")});
9691 p.style.visibility = "hidden";
9692 p.style.display = "block";
9696 this._measureChanged = changed;
9702 * Restores displays to before beginMeasure was called
9703 * @return {Roo.Element} this
9705 endMeasure : function(){
9706 var changed = this._measureChanged;
9708 for(var i = 0, len = changed.length; i < len; i++) {
9710 r.el.style.visibility = r.visibility;
9711 r.el.style.display = "none";
9713 this._measureChanged = null;
9719 * Update the innerHTML of this element, optionally searching for and processing scripts
9720 * @param {String} html The new HTML
9721 * @param {Boolean} loadScripts (optional) true to look for and process scripts
9722 * @param {Function} callback For async script loading you can be noticed when the update completes
9723 * @return {Roo.Element} this
9725 update : function(html, loadScripts, callback){
9726 if(typeof html == "undefined"){
9729 if(loadScripts !== true){
9730 this.dom.innerHTML = html;
9731 if(typeof callback == "function"){
9739 html += '<span id="' + id + '"></span>';
9741 E.onAvailable(id, function(){
9742 var hd = document.getElementsByTagName("head")[0];
9743 var re = /(?:<script([^>]*)?>)((\n|\r|.)*?)(?:<\/script>)/ig;
9744 var srcRe = /\ssrc=([\'\"])(.*?)\1/i;
9745 var typeRe = /\stype=([\'\"])(.*?)\1/i;
9748 while(match = re.exec(html)){
9749 var attrs = match[1];
9750 var srcMatch = attrs ? attrs.match(srcRe) : false;
9751 if(srcMatch && srcMatch[2]){
9752 var s = document.createElement("script");
9753 s.src = srcMatch[2];
9754 var typeMatch = attrs.match(typeRe);
9755 if(typeMatch && typeMatch[2]){
9756 s.type = typeMatch[2];
9759 }else if(match[2] && match[2].length > 0){
9760 if(window.execScript) {
9761 window.execScript(match[2]);
9769 window.eval(match[2]);
9773 var el = document.getElementById(id);
9774 if(el){el.parentNode.removeChild(el);}
9775 if(typeof callback == "function"){
9779 dom.innerHTML = html.replace(/(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig, "");
9784 * Direct access to the UpdateManager update() method (takes the same parameters).
9785 * @param {String/Function} url The url for this request or a function to call to get the url
9786 * @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}
9787 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
9788 * @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.
9789 * @return {Roo.Element} this
9792 var um = this.getUpdateManager();
9793 um.update.apply(um, arguments);
9798 * Gets this element's UpdateManager
9799 * @return {Roo.UpdateManager} The UpdateManager
9801 getUpdateManager : function(){
9802 if(!this.updateManager){
9803 this.updateManager = new Roo.UpdateManager(this);
9805 return this.updateManager;
9809 * Disables text selection for this element (normalized across browsers)
9810 * @return {Roo.Element} this
9812 unselectable : function(){
9813 this.dom.unselectable = "on";
9814 this.swallowEvent("selectstart", true);
9815 this.applyStyles("-moz-user-select:none;-khtml-user-select:none;");
9816 this.addClass("x-unselectable");
9821 * Calculates the x, y to center this element on the screen
9822 * @return {Array} The x, y values [x, y]
9824 getCenterXY : function(){
9825 return this.getAlignToXY(document, 'c-c');
9829 * Centers the Element in either the viewport, or another Element.
9830 * @param {String/HTMLElement/Roo.Element} centerIn (optional) The element in which to center the element.
9832 center : function(centerIn){
9833 this.alignTo(centerIn || document, 'c-c');
9838 * Tests various css rules/browsers to determine if this element uses a border box
9841 isBorderBox : function(){
9842 return noBoxAdjust[this.dom.tagName.toLowerCase()] || Roo.isBorderBox;
9846 * Return a box {x, y, width, height} that can be used to set another elements
9847 * size/location to match this element.
9848 * @param {Boolean} contentBox (optional) If true a box for the content of the element is returned.
9849 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page x/y.
9850 * @return {Object} box An object in the format {x, y, width, height}
9852 getBox : function(contentBox, local){
9857 var left = parseInt(this.getStyle("left"), 10) || 0;
9858 var top = parseInt(this.getStyle("top"), 10) || 0;
9861 var el = this.dom, w = el.offsetWidth, h = el.offsetHeight, bx;
9863 bx = {x: xy[0], y: xy[1], 0: xy[0], 1: xy[1], width: w, height: h};
9865 var l = this.getBorderWidth("l")+this.getPadding("l");
9866 var r = this.getBorderWidth("r")+this.getPadding("r");
9867 var t = this.getBorderWidth("t")+this.getPadding("t");
9868 var b = this.getBorderWidth("b")+this.getPadding("b");
9869 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)};
9871 bx.right = bx.x + bx.width;
9872 bx.bottom = bx.y + bx.height;
9877 * Returns the sum width of the padding and borders for the passed "sides". See getBorderWidth()
9878 for more information about the sides.
9879 * @param {String} sides
9882 getFrameWidth : function(sides, onlyContentBox){
9883 return onlyContentBox && Roo.isBorderBox ? 0 : (this.getPadding(sides) + this.getBorderWidth(sides));
9887 * 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.
9888 * @param {Object} box The box to fill {x, y, width, height}
9889 * @param {Boolean} adjust (optional) Whether to adjust for box-model issues automatically
9890 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9891 * @return {Roo.Element} this
9893 setBox : function(box, adjust, animate){
9894 var w = box.width, h = box.height;
9895 if((adjust && !this.autoBoxAdjust) && !this.isBorderBox()){
9896 w -= (this.getBorderWidth("lr") + this.getPadding("lr"));
9897 h -= (this.getBorderWidth("tb") + this.getPadding("tb"));
9899 this.setBounds(box.x, box.y, w, h, this.preanim(arguments, 2));
9904 * Forces the browser to repaint this element
9905 * @return {Roo.Element} this
9907 repaint : function(){
9909 this.addClass("x-repaint");
9910 setTimeout(function(){
9911 Roo.get(dom).removeClass("x-repaint");
9917 * Returns an object with properties top, left, right and bottom representing the margins of this element unless sides is passed,
9918 * then it returns the calculated width of the sides (see getPadding)
9919 * @param {String} sides (optional) Any combination of l, r, t, b to get the sum of those sides
9920 * @return {Object/Number}
9922 getMargins : function(side){
9925 top: parseInt(this.getStyle("margin-top"), 10) || 0,
9926 left: parseInt(this.getStyle("margin-left"), 10) || 0,
9927 bottom: parseInt(this.getStyle("margin-bottom"), 10) || 0,
9928 right: parseInt(this.getStyle("margin-right"), 10) || 0
9931 return this.addStyles(side, El.margins);
9936 addStyles : function(sides, styles){
9938 for(var i = 0, len = sides.length; i < len; i++){
9939 v = this.getStyle(styles[sides.charAt(i)]);
9941 w = parseInt(v, 10);
9949 * Creates a proxy element of this element
9950 * @param {String/Object} config The class name of the proxy element or a DomHelper config object
9951 * @param {String/HTMLElement} renderTo (optional) The element or element id to render the proxy to (defaults to document.body)
9952 * @param {Boolean} matchBox (optional) True to align and size the proxy to this element now (defaults to false)
9953 * @return {Roo.Element} The new proxy element
9955 createProxy : function(config, renderTo, matchBox){
9957 renderTo = Roo.getDom(renderTo);
9959 renderTo = document.body;
9961 config = typeof config == "object" ?
9962 config : {tag : "div", cls: config};
9963 var proxy = Roo.DomHelper.append(renderTo, config, true);
9965 proxy.setBox(this.getBox());
9971 * Puts a mask over this element to disable user interaction. Requires core.css.
9972 * This method can only be applied to elements which accept child nodes.
9973 * @param {String} msg (optional) A message to display in the mask
9974 * @param {String} msgCls (optional) A css class to apply to the msg element - use no-spinner to hide the spinner on bootstrap
9975 * @return {Element} The mask element
9977 mask : function(msg, msgCls)
9979 if(this.getStyle("position") == "static" && this.dom.tagName !== 'BODY'){
9980 this.setStyle("position", "relative");
9983 this._mask = Roo.DomHelper.append(this.dom, {cls:"roo-el-mask"}, true);
9986 this.addClass("x-masked");
9987 this._mask.setDisplayed(true);
9992 while (dom && dom.style) {
9993 if (!isNaN(parseInt(dom.style.zIndex))) {
9994 z = Math.max(z, parseInt(dom.style.zIndex));
9996 dom = dom.parentNode;
9998 // if we are masking the body - then it hides everything..
9999 if (this.dom == document.body) {
10001 this._mask.setWidth(Roo.lib.Dom.getDocumentWidth());
10002 this._mask.setHeight(Roo.lib.Dom.getDocumentHeight());
10005 if(typeof msg == 'string'){
10006 if(!this._maskMsg){
10007 this._maskMsg = Roo.DomHelper.append(this.dom, {
10008 cls: "roo-el-mask-msg",
10012 cls: 'fa fa-spinner fa-spin'
10020 var mm = this._maskMsg;
10021 mm.dom.className = msgCls ? "roo-el-mask-msg " + msgCls : "roo-el-mask-msg";
10022 if (mm.dom.lastChild) { // weird IE issue?
10023 mm.dom.lastChild.innerHTML = msg;
10025 mm.setDisplayed(true);
10027 mm.setStyle('z-index', z + 102);
10029 if(Roo.isIE && !(Roo.isIE7 && Roo.isStrict) && this.getStyle('height') == 'auto'){ // ie will not expand full height automatically
10030 this._mask.setHeight(this.getHeight());
10032 this._mask.setStyle('z-index', z + 100);
10038 * Removes a previously applied mask. If removeEl is true the mask overlay is destroyed, otherwise
10039 * it is cached for reuse.
10041 unmask : function(removeEl){
10043 if(removeEl === true){
10044 this._mask.remove();
10047 this._maskMsg.remove();
10048 delete this._maskMsg;
10051 this._mask.setDisplayed(false);
10053 this._maskMsg.setDisplayed(false);
10057 this.removeClass("x-masked");
10061 * Returns true if this element is masked
10062 * @return {Boolean}
10064 isMasked : function(){
10065 return this._mask && this._mask.isVisible();
10069 * Creates an iframe shim for this element to keep selects and other windowed objects from
10071 * @return {Roo.Element} The new shim element
10073 createShim : function(){
10074 var el = document.createElement('iframe');
10075 el.frameBorder = 'no';
10076 el.className = 'roo-shim';
10077 if(Roo.isIE && Roo.isSecure){
10078 el.src = Roo.SSL_SECURE_URL;
10080 var shim = Roo.get(this.dom.parentNode.insertBefore(el, this.dom));
10081 shim.autoBoxAdjust = false;
10086 * Removes this element from the DOM and deletes it from the cache
10088 remove : function(){
10089 if(this.dom.parentNode){
10090 this.dom.parentNode.removeChild(this.dom);
10092 delete El.cache[this.dom.id];
10096 * Sets up event handlers to add and remove a css class when the mouse is over this element
10097 * @param {String} className
10098 * @param {Boolean} preventFlicker (optional) If set to true, it prevents flickering by filtering
10099 * mouseout events for children elements
10100 * @return {Roo.Element} this
10102 addClassOnOver : function(className, preventFlicker){
10103 this.on("mouseover", function(){
10104 Roo.fly(this, '_internal').addClass(className);
10106 var removeFn = function(e){
10107 if(preventFlicker !== true || !e.within(this, true)){
10108 Roo.fly(this, '_internal').removeClass(className);
10111 this.on("mouseout", removeFn, this.dom);
10116 * Sets up event handlers to add and remove a css class when this element has the focus
10117 * @param {String} className
10118 * @return {Roo.Element} this
10120 addClassOnFocus : function(className){
10121 this.on("focus", function(){
10122 Roo.fly(this, '_internal').addClass(className);
10124 this.on("blur", function(){
10125 Roo.fly(this, '_internal').removeClass(className);
10130 * 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)
10131 * @param {String} className
10132 * @return {Roo.Element} this
10134 addClassOnClick : function(className){
10135 var dom = this.dom;
10136 this.on("mousedown", function(){
10137 Roo.fly(dom, '_internal').addClass(className);
10138 var d = Roo.get(document);
10139 var fn = function(){
10140 Roo.fly(dom, '_internal').removeClass(className);
10141 d.removeListener("mouseup", fn);
10143 d.on("mouseup", fn);
10149 * Stops the specified event from bubbling and optionally prevents the default action
10150 * @param {String} eventName
10151 * @param {Boolean} preventDefault (optional) true to prevent the default action too
10152 * @return {Roo.Element} this
10154 swallowEvent : function(eventName, preventDefault){
10155 var fn = function(e){
10156 e.stopPropagation();
10157 if(preventDefault){
10158 e.preventDefault();
10161 if(eventName instanceof Array){
10162 for(var i = 0, len = eventName.length; i < len; i++){
10163 this.on(eventName[i], fn);
10167 this.on(eventName, fn);
10174 fitToParentDelegate : Roo.emptyFn, // keep a reference to the fitToParent delegate
10177 * Sizes this element to its parent element's dimensions performing
10178 * neccessary box adjustments.
10179 * @param {Boolean} monitorResize (optional) If true maintains the fit when the browser window is resized.
10180 * @param {String/HTMLElment/Element} targetParent (optional) The target parent, default to the parentNode.
10181 * @return {Roo.Element} this
10183 fitToParent : function(monitorResize, targetParent) {
10184 Roo.EventManager.removeResizeListener(this.fitToParentDelegate); // always remove previous fitToParent delegate from onWindowResize
10185 this.fitToParentDelegate = Roo.emptyFn; // remove reference to previous delegate
10186 if (monitorResize === true && !this.dom.parentNode) { // check if this Element still exists
10189 var p = Roo.get(targetParent || this.dom.parentNode);
10190 this.setSize(p.getComputedWidth() - p.getFrameWidth('lr'), p.getComputedHeight() - p.getFrameWidth('tb'));
10191 if (monitorResize === true) {
10192 this.fitToParentDelegate = this.fitToParent.createDelegate(this, [true, targetParent]);
10193 Roo.EventManager.onWindowResize(this.fitToParentDelegate);
10199 * Gets the next sibling, skipping text nodes
10200 * @return {HTMLElement} The next sibling or null
10202 getNextSibling : function(){
10203 var n = this.dom.nextSibling;
10204 while(n && n.nodeType != 1){
10211 * Gets the previous sibling, skipping text nodes
10212 * @return {HTMLElement} The previous sibling or null
10214 getPrevSibling : function(){
10215 var n = this.dom.previousSibling;
10216 while(n && n.nodeType != 1){
10217 n = n.previousSibling;
10224 * Appends the passed element(s) to this element
10225 * @param {String/HTMLElement/Array/Element/CompositeElement} el
10226 * @return {Roo.Element} this
10228 appendChild: function(el){
10235 * Creates the passed DomHelper config and appends it to this element or optionally inserts it before the passed child element.
10236 * @param {Object} config DomHelper element config object. If no tag is specified (e.g., {tag:'input'}) then a div will be
10237 * automatically generated with the specified attributes.
10238 * @param {HTMLElement} insertBefore (optional) a child element of this element
10239 * @param {Boolean} returnDom (optional) true to return the dom node instead of creating an Element
10240 * @return {Roo.Element} The new child element
10242 createChild: function(config, insertBefore, returnDom){
10243 config = config || {tag:'div'};
10245 return Roo.DomHelper.insertBefore(insertBefore, config, returnDom !== true);
10247 return Roo.DomHelper[!this.dom.firstChild ? 'overwrite' : 'append'](this.dom, config, returnDom !== true);
10251 * Appends this element to the passed element
10252 * @param {String/HTMLElement/Element} el The new parent element
10253 * @return {Roo.Element} this
10255 appendTo: function(el){
10256 el = Roo.getDom(el);
10257 el.appendChild(this.dom);
10262 * Inserts this element before the passed element in the DOM
10263 * @param {String/HTMLElement/Element} el The element to insert before
10264 * @return {Roo.Element} this
10266 insertBefore: function(el){
10267 el = Roo.getDom(el);
10268 el.parentNode.insertBefore(this.dom, el);
10273 * Inserts this element after the passed element in the DOM
10274 * @param {String/HTMLElement/Element} el The element to insert after
10275 * @return {Roo.Element} this
10277 insertAfter: function(el){
10278 el = Roo.getDom(el);
10279 el.parentNode.insertBefore(this.dom, el.nextSibling);
10284 * Inserts (or creates) an element (or DomHelper config) as the first child of the this element
10285 * @param {String/HTMLElement/Element/Object} el The id or element to insert or a DomHelper config to create and insert
10286 * @return {Roo.Element} The new child
10288 insertFirst: function(el, returnDom){
10290 if(typeof el == 'object' && !el.nodeType){ // dh config
10291 return this.createChild(el, this.dom.firstChild, returnDom);
10293 el = Roo.getDom(el);
10294 this.dom.insertBefore(el, this.dom.firstChild);
10295 return !returnDom ? Roo.get(el) : el;
10300 * Inserts (or creates) the passed element (or DomHelper config) as a sibling of this element
10301 * @param {String/HTMLElement/Element/Object} el The id or element to insert or a DomHelper config to create and insert
10302 * @param {String} where (optional) 'before' or 'after' defaults to before
10303 * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Roo.Element
10304 * @return {Roo.Element} the inserted Element
10306 insertSibling: function(el, where, returnDom){
10307 where = where ? where.toLowerCase() : 'before';
10309 var rt, refNode = where == 'before' ? this.dom : this.dom.nextSibling;
10311 if(typeof el == 'object' && !el.nodeType){ // dh config
10312 if(where == 'after' && !this.dom.nextSibling){
10313 rt = Roo.DomHelper.append(this.dom.parentNode, el, !returnDom);
10315 rt = Roo.DomHelper[where == 'after' ? 'insertAfter' : 'insertBefore'](this.dom, el, !returnDom);
10319 rt = this.dom.parentNode.insertBefore(Roo.getDom(el),
10320 where == 'before' ? this.dom : this.dom.nextSibling);
10329 * Creates and wraps this element with another element
10330 * @param {Object} config (optional) DomHelper element config object for the wrapper element or null for an empty div
10331 * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Roo.Element
10332 * @return {HTMLElement/Element} The newly created wrapper element
10334 wrap: function(config, returnDom){
10336 config = {tag: "div"};
10338 var newEl = Roo.DomHelper.insertBefore(this.dom, config, !returnDom);
10339 newEl.dom ? newEl.dom.appendChild(this.dom) : newEl.appendChild(this.dom);
10344 * Replaces the passed element with this element
10345 * @param {String/HTMLElement/Element} el The element to replace
10346 * @return {Roo.Element} this
10348 replace: function(el){
10350 this.insertBefore(el);
10356 * Inserts an html fragment into this element
10357 * @param {String} where Where to insert the html in relation to the this element - beforeBegin, afterBegin, beforeEnd, afterEnd.
10358 * @param {String} html The HTML fragment
10359 * @param {Boolean} returnEl True to return an Roo.Element
10360 * @return {HTMLElement/Roo.Element} The inserted node (or nearest related if more than 1 inserted)
10362 insertHtml : function(where, html, returnEl){
10363 var el = Roo.DomHelper.insertHtml(where, this.dom, html);
10364 return returnEl ? Roo.get(el) : el;
10368 * Sets the passed attributes as attributes of this element (a style attribute can be a string, object or function)
10369 * @param {Object} o The object with the attributes
10370 * @param {Boolean} useSet (optional) false to override the default setAttribute to use expandos.
10371 * @return {Roo.Element} this
10373 set : function(o, useSet){
10375 useSet = typeof useSet == 'undefined' ? (el.setAttribute ? true : false) : useSet;
10376 for(var attr in o){
10377 if(attr == "style" || typeof o[attr] == "function") { continue; }
10379 el.className = o["cls"];
10382 el.setAttribute(attr, o[attr]);
10384 el[attr] = o[attr];
10389 Roo.DomHelper.applyStyles(el, o.style);
10395 * Convenience method for constructing a KeyMap
10396 * @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:
10397 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
10398 * @param {Function} fn The function to call
10399 * @param {Object} scope (optional) The scope of the function
10400 * @return {Roo.KeyMap} The KeyMap created
10402 addKeyListener : function(key, fn, scope){
10404 if(typeof key != "object" || key instanceof Array){
10420 return new Roo.KeyMap(this, config);
10424 * Creates a KeyMap for this element
10425 * @param {Object} config The KeyMap config. See {@link Roo.KeyMap} for more details
10426 * @return {Roo.KeyMap} The KeyMap created
10428 addKeyMap : function(config){
10429 return new Roo.KeyMap(this, config);
10433 * Returns true if this element is scrollable.
10434 * @return {Boolean}
10436 isScrollable : function(){
10437 var dom = this.dom;
10438 return dom.scrollHeight > dom.clientHeight || dom.scrollWidth > dom.clientWidth;
10442 * 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().
10443 * @param {String} side Either "left" for scrollLeft values or "top" for scrollTop values.
10444 * @param {Number} value The new scroll value
10445 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
10446 * @return {Element} this
10449 scrollTo : function(side, value, animate){
10450 var prop = side.toLowerCase() == "left" ? "scrollLeft" : "scrollTop";
10451 if(!animate || !A){
10452 this.dom[prop] = value;
10454 var to = prop == "scrollLeft" ? [value, this.dom.scrollTop] : [this.dom.scrollLeft, value];
10455 this.anim({scroll: {"to": to}}, this.preanim(arguments, 2), 'scroll');
10461 * Scrolls this element the specified direction. Does bounds checking to make sure the scroll is
10462 * within this element's scrollable range.
10463 * @param {String} direction Possible values are: "l","left" - "r","right" - "t","top","up" - "b","bottom","down".
10464 * @param {Number} distance How far to scroll the element in pixels
10465 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
10466 * @return {Boolean} Returns true if a scroll was triggered or false if the element
10467 * was scrolled as far as it could go.
10469 scroll : function(direction, distance, animate){
10470 if(!this.isScrollable()){
10474 var l = el.scrollLeft, t = el.scrollTop;
10475 var w = el.scrollWidth, h = el.scrollHeight;
10476 var cw = el.clientWidth, ch = el.clientHeight;
10477 direction = direction.toLowerCase();
10478 var scrolled = false;
10479 var a = this.preanim(arguments, 2);
10484 var v = Math.min(l + distance, w-cw);
10485 this.scrollTo("left", v, a);
10492 var v = Math.max(l - distance, 0);
10493 this.scrollTo("left", v, a);
10501 var v = Math.max(t - distance, 0);
10502 this.scrollTo("top", v, a);
10510 var v = Math.min(t + distance, h-ch);
10511 this.scrollTo("top", v, a);
10520 * Translates the passed page coordinates into left/top css values for this element
10521 * @param {Number/Array} x The page x or an array containing [x, y]
10522 * @param {Number} y The page y
10523 * @return {Object} An object with left and top properties. e.g. {left: (value), top: (value)}
10525 translatePoints : function(x, y){
10526 if(typeof x == 'object' || x instanceof Array){
10527 y = x[1]; x = x[0];
10529 var p = this.getStyle('position');
10530 var o = this.getXY();
10532 var l = parseInt(this.getStyle('left'), 10);
10533 var t = parseInt(this.getStyle('top'), 10);
10536 l = (p == "relative") ? 0 : this.dom.offsetLeft;
10539 t = (p == "relative") ? 0 : this.dom.offsetTop;
10542 return {left: (x - o[0] + l), top: (y - o[1] + t)};
10546 * Returns the current scroll position of the element.
10547 * @return {Object} An object containing the scroll position in the format {left: (scrollLeft), top: (scrollTop)}
10549 getScroll : function(){
10550 var d = this.dom, doc = document;
10551 if(d == doc || d == doc.body){
10552 var l = window.pageXOffset || doc.documentElement.scrollLeft || doc.body.scrollLeft || 0;
10553 var t = window.pageYOffset || doc.documentElement.scrollTop || doc.body.scrollTop || 0;
10554 return {left: l, top: t};
10556 return {left: d.scrollLeft, top: d.scrollTop};
10561 * Return the CSS color for the specified CSS attribute. rgb, 3 digit (like #fff) and valid values
10562 * are convert to standard 6 digit hex color.
10563 * @param {String} attr The css attribute
10564 * @param {String} defaultValue The default value to use when a valid color isn't found
10565 * @param {String} prefix (optional) defaults to #. Use an empty string when working with
10568 getColor : function(attr, defaultValue, prefix){
10569 var v = this.getStyle(attr);
10570 if(!v || v == "transparent" || v == "inherit") {
10571 return defaultValue;
10573 var color = typeof prefix == "undefined" ? "#" : prefix;
10574 if(v.substr(0, 4) == "rgb("){
10575 var rvs = v.slice(4, v.length -1).split(",");
10576 for(var i = 0; i < 3; i++){
10577 var h = parseInt(rvs[i]).toString(16);
10584 if(v.substr(0, 1) == "#"){
10585 if(v.length == 4) {
10586 for(var i = 1; i < 4; i++){
10587 var c = v.charAt(i);
10590 }else if(v.length == 7){
10591 color += v.substr(1);
10595 return(color.length > 5 ? color.toLowerCase() : defaultValue);
10599 * Wraps the specified element with a special markup/CSS block that renders by default as a gray container with a
10600 * gradient background, rounded corners and a 4-way shadow.
10601 * @param {String} class (optional) A base CSS class to apply to the containing wrapper element (defaults to 'x-box').
10602 * Note that there are a number of CSS rules that are dependent on this name to make the overall effect work,
10603 * so if you supply an alternate base class, make sure you also supply all of the necessary rules.
10604 * @return {Roo.Element} this
10606 boxWrap : function(cls){
10607 cls = cls || 'x-box';
10608 var el = Roo.get(this.insertHtml('beforeBegin', String.format('<div class="{0}">'+El.boxMarkup+'</div>', cls)));
10609 el.child('.'+cls+'-mc').dom.appendChild(this.dom);
10614 * Returns the value of a namespaced attribute from the element's underlying DOM node.
10615 * @param {String} namespace The namespace in which to look for the attribute
10616 * @param {String} name The attribute name
10617 * @return {String} The attribute value
10619 getAttributeNS : Roo.isIE ? function(ns, name){
10621 var type = typeof d[ns+":"+name];
10622 if(type != 'undefined' && type != 'unknown'){
10623 return d[ns+":"+name];
10626 } : function(ns, name){
10628 return d.getAttributeNS(ns, name) || d.getAttribute(ns+":"+name) || d.getAttribute(name) || d[name];
10633 * Sets or Returns the value the dom attribute value
10634 * @param {String|Object} name The attribute name (or object to set multiple attributes)
10635 * @param {String} value (optional) The value to set the attribute to
10636 * @return {String} The attribute value
10638 attr : function(name){
10639 if (arguments.length > 1) {
10640 this.dom.setAttribute(name, arguments[1]);
10641 return arguments[1];
10643 if (typeof(name) == 'object') {
10644 for(var i in name) {
10645 this.attr(i, name[i]);
10651 if (!this.dom.hasAttribute(name)) {
10654 return this.dom.getAttribute(name);
10661 var ep = El.prototype;
10664 * Appends an event handler (Shorthand for addListener)
10665 * @param {String} eventName The type of event to append
10666 * @param {Function} fn The method the event invokes
10667 * @param {Object} scope (optional) The scope (this object) of the fn
10668 * @param {Object} options (optional)An object with standard {@link Roo.EventManager#addListener} options
10671 ep.on = ep.addListener;
10672 // backwards compat
10673 ep.mon = ep.addListener;
10676 * Removes an event handler from this element (shorthand for removeListener)
10677 * @param {String} eventName the type of event to remove
10678 * @param {Function} fn the method the event invokes
10679 * @return {Roo.Element} this
10682 ep.un = ep.removeListener;
10685 * true to automatically adjust width and height settings for box-model issues (default to true)
10687 ep.autoBoxAdjust = true;
10690 El.unitPattern = /\d+(px|em|%|en|ex|pt|in|cm|mm|pc)$/i;
10693 El.addUnits = function(v, defaultUnit){
10694 if(v === "" || v == "auto"){
10697 if(v === undefined){
10700 if(typeof v == "number" || !El.unitPattern.test(v)){
10701 return v + (defaultUnit || 'px');
10706 // special markup used throughout Roo when box wrapping elements
10707 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>';
10709 * Visibility mode constant - Use visibility to hide element
10715 * Visibility mode constant - Use display to hide element
10721 El.borders = {l: "border-left-width", r: "border-right-width", t: "border-top-width", b: "border-bottom-width"};
10722 El.paddings = {l: "padding-left", r: "padding-right", t: "padding-top", b: "padding-bottom"};
10723 El.margins = {l: "margin-left", r: "margin-right", t: "margin-top", b: "margin-bottom"};
10735 * Static method to retrieve Element objects. Uses simple caching to consistently return the same object.
10736 * Automatically fixes if an object was recreated with the same id via AJAX or DOM.
10737 * @param {String/HTMLElement/Element} el The id of the node, a DOM Node or an existing Element.
10738 * @return {Element} The Element object
10741 El.get = function(el){
10743 if(!el){ return null; }
10744 if(typeof el == "string"){ // element id
10745 if(!(elm = document.getElementById(el))){
10748 if(ex = El.cache[el]){
10751 ex = El.cache[el] = new El(elm);
10754 }else if(el.tagName){ // dom element
10758 if(ex = El.cache[id]){
10761 ex = El.cache[id] = new El(el);
10764 }else if(el instanceof El){
10766 el.dom = document.getElementById(el.id) || el.dom; // refresh dom element in case no longer valid,
10767 // catch case where it hasn't been appended
10768 El.cache[el.id] = el; // in case it was created directly with Element(), let's cache it
10771 }else if(el.isComposite){
10773 }else if(el instanceof Array){
10774 return El.select(el);
10775 }else if(el == document){
10776 // create a bogus element object representing the document object
10778 var f = function(){};
10779 f.prototype = El.prototype;
10781 docEl.dom = document;
10789 El.uncache = function(el){
10790 for(var i = 0, a = arguments, len = a.length; i < len; i++) {
10792 delete El.cache[a[i].id || a[i]];
10798 // Garbage collection - uncache elements/purge listeners on orphaned elements
10799 // so we don't hold a reference and cause the browser to retain them
10800 El.garbageCollect = function(){
10801 if(!Roo.enableGarbageCollector){
10802 clearInterval(El.collectorThread);
10805 for(var eid in El.cache){
10806 var el = El.cache[eid], d = el.dom;
10807 // -------------------------------------------------------
10808 // Determining what is garbage:
10809 // -------------------------------------------------------
10811 // dom node is null, definitely garbage
10812 // -------------------------------------------------------
10814 // no parentNode == direct orphan, definitely garbage
10815 // -------------------------------------------------------
10816 // !d.offsetParent && !document.getElementById(eid)
10817 // display none elements have no offsetParent so we will
10818 // also try to look it up by it's id. However, check
10819 // offsetParent first so we don't do unneeded lookups.
10820 // This enables collection of elements that are not orphans
10821 // directly, but somewhere up the line they have an orphan
10823 // -------------------------------------------------------
10824 if(!d || !d.parentNode || (!d.offsetParent && !document.getElementById(eid))){
10825 delete El.cache[eid];
10826 if(d && Roo.enableListenerCollection){
10832 El.collectorThreadId = setInterval(El.garbageCollect, 30000);
10836 El.Flyweight = function(dom){
10839 El.Flyweight.prototype = El.prototype;
10841 El._flyweights = {};
10843 * Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
10844 * the dom node can be overwritten by other code.
10845 * @param {String/HTMLElement} el The dom node or id
10846 * @param {String} named (optional) Allows for creation of named reusable flyweights to
10847 * prevent conflicts (e.g. internally Roo uses "_internal")
10849 * @return {Element} The shared Element object
10851 El.fly = function(el, named){
10852 named = named || '_global';
10853 el = Roo.getDom(el);
10857 if(!El._flyweights[named]){
10858 El._flyweights[named] = new El.Flyweight();
10860 El._flyweights[named].dom = el;
10861 return El._flyweights[named];
10865 * Static method to retrieve Element objects. Uses simple caching to consistently return the same object.
10866 * Automatically fixes if an object was recreated with the same id via AJAX or DOM.
10867 * Shorthand of {@link Roo.Element#get}
10868 * @param {String/HTMLElement/Element} el The id of the node, a DOM Node or an existing Element.
10869 * @return {Element} The Element object
10875 * Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
10876 * the dom node can be overwritten by other code.
10877 * Shorthand of {@link Roo.Element#fly}
10878 * @param {String/HTMLElement} el The dom node or id
10879 * @param {String} named (optional) Allows for creation of named reusable flyweights to
10880 * prevent conflicts (e.g. internally Roo uses "_internal")
10882 * @return {Element} The shared Element object
10888 // speedy lookup for elements never to box adjust
10889 var noBoxAdjust = Roo.isStrict ? {
10892 input:1, select:1, textarea:1
10894 if(Roo.isIE || Roo.isGecko){
10895 noBoxAdjust['button'] = 1;
10899 Roo.EventManager.on(window, 'unload', function(){
10901 delete El._flyweights;
10909 Roo.Element.selectorFunction = Roo.DomQuery.select;
10912 Roo.Element.select = function(selector, unique, root){
10914 if(typeof selector == "string"){
10915 els = Roo.Element.selectorFunction(selector, root);
10916 }else if(selector.length !== undefined){
10919 throw "Invalid selector";
10921 if(unique === true){
10922 return new Roo.CompositeElement(els);
10924 return new Roo.CompositeElementLite(els);
10928 * Selects elements based on the passed CSS selector to enable working on them as 1.
10929 * @param {String/Array} selector The CSS selector or an array of elements
10930 * @param {Boolean} unique (optional) true to create a unique Roo.Element for each element (defaults to a shared flyweight object)
10931 * @param {HTMLElement/String} root (optional) The root element of the query or id of the root
10932 * @return {CompositeElementLite/CompositeElement}
10936 Roo.select = Roo.Element.select;
10953 * Ext JS Library 1.1.1
10954 * Copyright(c) 2006-2007, Ext JS, LLC.
10956 * Originally Released Under LGPL - original licence link has changed is not relivant.
10959 * <script type="text/javascript">
10964 //Notifies Element that fx methods are available
10965 Roo.enableFx = true;
10969 * <p>A class to provide basic animation and visual effects support. <b>Note:</b> This class is automatically applied
10970 * to the {@link Roo.Element} interface when included, so all effects calls should be performed via Element.
10971 * Conversely, since the effects are not actually defined in Element, Roo.Fx <b>must</b> be included in order for the
10972 * Element effects to work.</p><br/>
10974 * <p>It is important to note that although the Fx methods and many non-Fx Element methods support "method chaining" in that
10975 * they return the Element object itself as the method return value, it is not always possible to mix the two in a single
10976 * method chain. The Fx methods use an internal effects queue so that each effect can be properly timed and sequenced.
10977 * Non-Fx methods, on the other hand, have no such internal queueing and will always execute immediately. For this reason,
10978 * while it may be possible to mix certain Fx and non-Fx method calls in a single chain, it may not always provide the
10979 * expected results and should be done with care.</p><br/>
10981 * <p>Motion effects support 8-way anchoring, meaning that you can choose one of 8 different anchor points on the Element
10982 * that will serve as either the start or end point of the animation. Following are all of the supported anchor positions:</p>
10985 ----- -----------------------------
10986 tl The top left corner
10987 t The center of the top edge
10988 tr The top right corner
10989 l The center of the left edge
10990 r The center of the right edge
10991 bl The bottom left corner
10992 b The center of the bottom edge
10993 br The bottom right corner
10995 * <b>Although some Fx methods accept specific custom config parameters, the ones shown in the Config Options section
10996 * below are common options that can be passed to any Fx method.</b>
10997 * @cfg {Function} callback A function called when the effect is finished
10998 * @cfg {Object} scope The scope of the effect function
10999 * @cfg {String} easing A valid Easing value for the effect
11000 * @cfg {String} afterCls A css class to apply after the effect
11001 * @cfg {Number} duration The length of time (in seconds) that the effect should last
11002 * @cfg {Boolean} remove Whether the Element should be removed from the DOM and destroyed after the effect finishes
11003 * @cfg {Boolean} useDisplay Whether to use the <i>display</i> CSS property instead of <i>visibility</i> when hiding Elements (only applies to
11004 * effects that end with the element being visually hidden, ignored otherwise)
11005 * @cfg {String/Object/Function} afterStyle A style specification string, e.g. "width:100px", or an object in the form {width:"100px"}, or
11006 * a function which returns such a specification that will be applied to the Element after the effect finishes
11007 * @cfg {Boolean} block Whether the effect should block other effects from queueing while it runs
11008 * @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
11009 * @cfg {Boolean} stopFx Whether subsequent effects should be stopped and removed after the current effect finishes
11013 * Slides the element into view. An anchor point can be optionally passed to set the point of
11014 * origin for the slide effect. This function automatically handles wrapping the element with
11015 * a fixed-size container if needed. See the Fx class overview for valid anchor point options.
11018 // default: slide the element in from the top
11021 // custom: slide the element in from the right with a 2-second duration
11022 el.slideIn('r', { duration: 2 });
11024 // common config options shown with default values
11030 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to top: 't')
11031 * @param {Object} options (optional) Object literal with any of the Fx config options
11032 * @return {Roo.Element} The Element
11034 slideIn : function(anchor, o){
11035 var el = this.getFxEl();
11038 el.queueFx(o, function(){
11040 anchor = anchor || "t";
11042 // fix display to visibility
11045 // restore values after effect
11046 var r = this.getFxRestore();
11047 var b = this.getBox();
11048 // fixed size for slide
11052 var wrap = this.fxWrap(r.pos, o, "hidden");
11054 var st = this.dom.style;
11055 st.visibility = "visible";
11056 st.position = "absolute";
11058 // clear out temp styles after slide and unwrap
11059 var after = function(){
11060 el.fxUnwrap(wrap, r.pos, o);
11061 st.width = r.width;
11062 st.height = r.height;
11065 // time to calc the positions
11066 var a, pt = {to: [b.x, b.y]}, bw = {to: b.width}, bh = {to: b.height};
11068 switch(anchor.toLowerCase()){
11070 wrap.setSize(b.width, 0);
11071 st.left = st.bottom = "0";
11075 wrap.setSize(0, b.height);
11076 st.right = st.top = "0";
11080 wrap.setSize(0, b.height);
11081 wrap.setX(b.right);
11082 st.left = st.top = "0";
11083 a = {width: bw, points: pt};
11086 wrap.setSize(b.width, 0);
11087 wrap.setY(b.bottom);
11088 st.left = st.top = "0";
11089 a = {height: bh, points: pt};
11092 wrap.setSize(0, 0);
11093 st.right = st.bottom = "0";
11094 a = {width: bw, height: bh};
11097 wrap.setSize(0, 0);
11098 wrap.setY(b.y+b.height);
11099 st.right = st.top = "0";
11100 a = {width: bw, height: bh, points: pt};
11103 wrap.setSize(0, 0);
11104 wrap.setXY([b.right, b.bottom]);
11105 st.left = st.top = "0";
11106 a = {width: bw, height: bh, points: pt};
11109 wrap.setSize(0, 0);
11110 wrap.setX(b.x+b.width);
11111 st.left = st.bottom = "0";
11112 a = {width: bw, height: bh, points: pt};
11115 this.dom.style.visibility = "visible";
11118 arguments.callee.anim = wrap.fxanim(a,
11128 * Slides the element out of view. An anchor point can be optionally passed to set the end point
11129 * for the slide effect. When the effect is completed, the element will be hidden (visibility =
11130 * 'hidden') but block elements will still take up space in the document. The element must be removed
11131 * from the DOM using the 'remove' config option if desired. This function automatically handles
11132 * wrapping the element with a fixed-size container if needed. See the Fx class overview for valid anchor point options.
11135 // default: slide the element out to the top
11138 // custom: slide the element out to the right with a 2-second duration
11139 el.slideOut('r', { duration: 2 });
11141 // common config options shown with default values
11149 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to top: 't')
11150 * @param {Object} options (optional) Object literal with any of the Fx config options
11151 * @return {Roo.Element} The Element
11153 slideOut : function(anchor, o){
11154 var el = this.getFxEl();
11157 el.queueFx(o, function(){
11159 anchor = anchor || "t";
11161 // restore values after effect
11162 var r = this.getFxRestore();
11164 var b = this.getBox();
11165 // fixed size for slide
11169 var wrap = this.fxWrap(r.pos, o, "visible");
11171 var st = this.dom.style;
11172 st.visibility = "visible";
11173 st.position = "absolute";
11177 var after = function(){
11179 el.setDisplayed(false);
11184 el.fxUnwrap(wrap, r.pos, o);
11186 st.width = r.width;
11187 st.height = r.height;
11192 var a, zero = {to: 0};
11193 switch(anchor.toLowerCase()){
11195 st.left = st.bottom = "0";
11196 a = {height: zero};
11199 st.right = st.top = "0";
11203 st.left = st.top = "0";
11204 a = {width: zero, points: {to:[b.right, b.y]}};
11207 st.left = st.top = "0";
11208 a = {height: zero, points: {to:[b.x, b.bottom]}};
11211 st.right = st.bottom = "0";
11212 a = {width: zero, height: zero};
11215 st.right = st.top = "0";
11216 a = {width: zero, height: zero, points: {to:[b.x, b.bottom]}};
11219 st.left = st.top = "0";
11220 a = {width: zero, height: zero, points: {to:[b.x+b.width, b.bottom]}};
11223 st.left = st.bottom = "0";
11224 a = {width: zero, height: zero, points: {to:[b.right, b.y]}};
11228 arguments.callee.anim = wrap.fxanim(a,
11238 * Fades the element out while slowly expanding it in all directions. When the effect is completed, the
11239 * element will be hidden (visibility = 'hidden') but block elements will still take up space in the document.
11240 * The element must be removed from the DOM using the 'remove' config option if desired.
11246 // common config options shown with default values
11254 * @param {Object} options (optional) Object literal with any of the Fx config options
11255 * @return {Roo.Element} The Element
11257 puff : function(o){
11258 var el = this.getFxEl();
11261 el.queueFx(o, function(){
11262 this.clearOpacity();
11265 // restore values after effect
11266 var r = this.getFxRestore();
11267 var st = this.dom.style;
11269 var after = function(){
11271 el.setDisplayed(false);
11278 el.setPositioning(r.pos);
11279 st.width = r.width;
11280 st.height = r.height;
11285 var width = this.getWidth();
11286 var height = this.getHeight();
11288 arguments.callee.anim = this.fxanim({
11289 width : {to: this.adjustWidth(width * 2)},
11290 height : {to: this.adjustHeight(height * 2)},
11291 points : {by: [-(width * .5), -(height * .5)]},
11293 fontSize: {to:200, unit: "%"}
11304 * Blinks the element as if it was clicked and then collapses on its center (similar to switching off a television).
11305 * When the effect is completed, the element will be hidden (visibility = 'hidden') but block elements will still
11306 * take up space in the document. The element must be removed from the DOM using the 'remove' config option if desired.
11312 // all config options shown with default values
11320 * @param {Object} options (optional) Object literal with any of the Fx config options
11321 * @return {Roo.Element} The Element
11323 switchOff : function(o){
11324 var el = this.getFxEl();
11327 el.queueFx(o, function(){
11328 this.clearOpacity();
11331 // restore values after effect
11332 var r = this.getFxRestore();
11333 var st = this.dom.style;
11335 var after = function(){
11337 el.setDisplayed(false);
11343 el.setPositioning(r.pos);
11344 st.width = r.width;
11345 st.height = r.height;
11350 this.fxanim({opacity:{to:0.3}}, null, null, .1, null, function(){
11351 this.clearOpacity();
11355 points:{by:[0, this.getHeight() * .5]}
11356 }, o, 'motion', 0.3, 'easeIn', after);
11357 }).defer(100, this);
11364 * Highlights the Element by setting a color (applies to the background-color by default, but can be
11365 * changed using the "attr" config option) and then fading back to the original color. If no original
11366 * color is available, you should provide the "endColor" config option which will be cleared after the animation.
11369 // default: highlight background to yellow
11372 // custom: highlight foreground text to blue for 2 seconds
11373 el.highlight("0000ff", { attr: 'color', duration: 2 });
11375 // common config options shown with default values
11376 el.highlight("ffff9c", {
11377 attr: "background-color", //can be any valid CSS property (attribute) that supports a color value
11378 endColor: (current color) or "ffffff",
11383 * @param {String} color (optional) The highlight color. Should be a 6 char hex color without the leading # (defaults to yellow: 'ffff9c')
11384 * @param {Object} options (optional) Object literal with any of the Fx config options
11385 * @return {Roo.Element} The Element
11387 highlight : function(color, o){
11388 var el = this.getFxEl();
11391 el.queueFx(o, function(){
11392 color = color || "ffff9c";
11393 attr = o.attr || "backgroundColor";
11395 this.clearOpacity();
11398 var origColor = this.getColor(attr);
11399 var restoreColor = this.dom.style[attr];
11400 endColor = (o.endColor || origColor) || "ffffff";
11402 var after = function(){
11403 el.dom.style[attr] = restoreColor;
11408 a[attr] = {from: color, to: endColor};
11409 arguments.callee.anim = this.fxanim(a,
11419 * Shows a ripple of exploding, attenuating borders to draw attention to an Element.
11422 // default: a single light blue ripple
11425 // custom: 3 red ripples lasting 3 seconds total
11426 el.frame("ff0000", 3, { duration: 3 });
11428 // common config options shown with default values
11429 el.frame("C3DAF9", 1, {
11430 duration: 1 //duration of entire animation (not each individual ripple)
11431 // Note: Easing is not configurable and will be ignored if included
11434 * @param {String} color (optional) The color of the border. Should be a 6 char hex color without the leading # (defaults to light blue: 'C3DAF9').
11435 * @param {Number} count (optional) The number of ripples to display (defaults to 1)
11436 * @param {Object} options (optional) Object literal with any of the Fx config options
11437 * @return {Roo.Element} The Element
11439 frame : function(color, count, o){
11440 var el = this.getFxEl();
11443 el.queueFx(o, function(){
11444 color = color || "#C3DAF9";
11445 if(color.length == 6){
11446 color = "#" + color;
11448 count = count || 1;
11449 duration = o.duration || 1;
11452 var b = this.getBox();
11453 var animFn = function(){
11454 var proxy = this.createProxy({
11457 visbility:"hidden",
11458 position:"absolute",
11459 "z-index":"35000", // yee haw
11460 border:"0px solid " + color
11463 var scale = Roo.isBorderBox ? 2 : 1;
11465 top:{from:b.y, to:b.y - 20},
11466 left:{from:b.x, to:b.x - 20},
11467 borderWidth:{from:0, to:10},
11468 opacity:{from:1, to:0},
11469 height:{from:b.height, to:(b.height + (20*scale))},
11470 width:{from:b.width, to:(b.width + (20*scale))}
11471 }, duration, function(){
11475 animFn.defer((duration/2)*1000, this);
11486 * Creates a pause before any subsequent queued effects begin. If there are
11487 * no effects queued after the pause it will have no effect.
11492 * @param {Number} seconds The length of time to pause (in seconds)
11493 * @return {Roo.Element} The Element
11495 pause : function(seconds){
11496 var el = this.getFxEl();
11499 el.queueFx(o, function(){
11500 setTimeout(function(){
11502 }, seconds * 1000);
11508 * Fade an element in (from transparent to opaque). The ending opacity can be specified
11509 * using the "endOpacity" config option.
11512 // default: fade in from opacity 0 to 100%
11515 // custom: fade in from opacity 0 to 75% over 2 seconds
11516 el.fadeIn({ endOpacity: .75, duration: 2});
11518 // common config options shown with default values
11520 endOpacity: 1, //can be any value between 0 and 1 (e.g. .5)
11525 * @param {Object} options (optional) Object literal with any of the Fx config options
11526 * @return {Roo.Element} The Element
11528 fadeIn : function(o){
11529 var el = this.getFxEl();
11531 el.queueFx(o, function(){
11532 this.setOpacity(0);
11534 this.dom.style.visibility = 'visible';
11535 var to = o.endOpacity || 1;
11536 arguments.callee.anim = this.fxanim({opacity:{to:to}},
11537 o, null, .5, "easeOut", function(){
11539 this.clearOpacity();
11548 * Fade an element out (from opaque to transparent). The ending opacity can be specified
11549 * using the "endOpacity" config option.
11552 // default: fade out from the element's current opacity to 0
11555 // custom: fade out from the element's current opacity to 25% over 2 seconds
11556 el.fadeOut({ endOpacity: .25, duration: 2});
11558 // common config options shown with default values
11560 endOpacity: 0, //can be any value between 0 and 1 (e.g. .5)
11567 * @param {Object} options (optional) Object literal with any of the Fx config options
11568 * @return {Roo.Element} The Element
11570 fadeOut : function(o){
11571 var el = this.getFxEl();
11573 el.queueFx(o, function(){
11574 arguments.callee.anim = this.fxanim({opacity:{to:o.endOpacity || 0}},
11575 o, null, .5, "easeOut", function(){
11576 if(this.visibilityMode == Roo.Element.DISPLAY || o.useDisplay){
11577 this.dom.style.display = "none";
11579 this.dom.style.visibility = "hidden";
11581 this.clearOpacity();
11589 * Animates the transition of an element's dimensions from a starting height/width
11590 * to an ending height/width.
11593 // change height and width to 100x100 pixels
11594 el.scale(100, 100);
11596 // common config options shown with default values. The height and width will default to
11597 // the element's existing values if passed as null.
11600 [element's height], {
11605 * @param {Number} width The new width (pass undefined to keep the original width)
11606 * @param {Number} height The new height (pass undefined to keep the original height)
11607 * @param {Object} options (optional) Object literal with any of the Fx config options
11608 * @return {Roo.Element} The Element
11610 scale : function(w, h, o){
11611 this.shift(Roo.apply({}, o, {
11619 * Animates the transition of any combination of an element's dimensions, xy position and/or opacity.
11620 * Any of these properties not specified in the config object will not be changed. This effect
11621 * requires that at least one new dimension, position or opacity setting must be passed in on
11622 * the config object in order for the function to have any effect.
11625 // slide the element horizontally to x position 200 while changing the height and opacity
11626 el.shift({ x: 200, height: 50, opacity: .8 });
11628 // common config options shown with default values.
11630 width: [element's width],
11631 height: [element's height],
11632 x: [element's x position],
11633 y: [element's y position],
11634 opacity: [element's opacity],
11639 * @param {Object} options Object literal with any of the Fx config options
11640 * @return {Roo.Element} The Element
11642 shift : function(o){
11643 var el = this.getFxEl();
11645 el.queueFx(o, function(){
11646 var a = {}, w = o.width, h = o.height, x = o.x, y = o.y, op = o.opacity;
11647 if(w !== undefined){
11648 a.width = {to: this.adjustWidth(w)};
11650 if(h !== undefined){
11651 a.height = {to: this.adjustHeight(h)};
11653 if(x !== undefined || y !== undefined){
11655 x !== undefined ? x : this.getX(),
11656 y !== undefined ? y : this.getY()
11659 if(op !== undefined){
11660 a.opacity = {to: op};
11662 if(o.xy !== undefined){
11663 a.points = {to: o.xy};
11665 arguments.callee.anim = this.fxanim(a,
11666 o, 'motion', .35, "easeOut", function(){
11674 * Slides the element while fading it out of view. An anchor point can be optionally passed to set the
11675 * ending point of the effect.
11678 // default: slide the element downward while fading out
11681 // custom: slide the element out to the right with a 2-second duration
11682 el.ghost('r', { duration: 2 });
11684 // common config options shown with default values
11692 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to bottom: 'b')
11693 * @param {Object} options (optional) Object literal with any of the Fx config options
11694 * @return {Roo.Element} The Element
11696 ghost : function(anchor, o){
11697 var el = this.getFxEl();
11700 el.queueFx(o, function(){
11701 anchor = anchor || "b";
11703 // restore values after effect
11704 var r = this.getFxRestore();
11705 var w = this.getWidth(),
11706 h = this.getHeight();
11708 var st = this.dom.style;
11710 var after = function(){
11712 el.setDisplayed(false);
11718 el.setPositioning(r.pos);
11719 st.width = r.width;
11720 st.height = r.height;
11725 var a = {opacity: {to: 0}, points: {}}, pt = a.points;
11726 switch(anchor.toLowerCase()){
11753 arguments.callee.anim = this.fxanim(a,
11763 * Ensures that all effects queued after syncFx is called on the element are
11764 * run concurrently. This is the opposite of {@link #sequenceFx}.
11765 * @return {Roo.Element} The Element
11767 syncFx : function(){
11768 this.fxDefaults = Roo.apply(this.fxDefaults || {}, {
11777 * Ensures that all effects queued after sequenceFx is called on the element are
11778 * run in sequence. This is the opposite of {@link #syncFx}.
11779 * @return {Roo.Element} The Element
11781 sequenceFx : function(){
11782 this.fxDefaults = Roo.apply(this.fxDefaults || {}, {
11784 concurrent : false,
11791 nextFx : function(){
11792 var ef = this.fxQueue[0];
11799 * Returns true if the element has any effects actively running or queued, else returns false.
11800 * @return {Boolean} True if element has active effects, else false
11802 hasActiveFx : function(){
11803 return this.fxQueue && this.fxQueue[0];
11807 * Stops any running effects and clears the element's internal effects queue if it contains
11808 * any additional effects that haven't started yet.
11809 * @return {Roo.Element} The Element
11811 stopFx : function(){
11812 if(this.hasActiveFx()){
11813 var cur = this.fxQueue[0];
11814 if(cur && cur.anim && cur.anim.isAnimated()){
11815 this.fxQueue = [cur]; // clear out others
11816 cur.anim.stop(true);
11823 beforeFx : function(o){
11824 if(this.hasActiveFx() && !o.concurrent){
11835 * Returns true if the element is currently blocking so that no other effect can be queued
11836 * until this effect is finished, else returns false if blocking is not set. This is commonly
11837 * used to ensure that an effect initiated by a user action runs to completion prior to the
11838 * same effect being restarted (e.g., firing only one effect even if the user clicks several times).
11839 * @return {Boolean} True if blocking, else false
11841 hasFxBlock : function(){
11842 var q = this.fxQueue;
11843 return q && q[0] && q[0].block;
11847 queueFx : function(o, fn){
11851 if(!this.hasFxBlock()){
11852 Roo.applyIf(o, this.fxDefaults);
11854 var run = this.beforeFx(o);
11855 fn.block = o.block;
11856 this.fxQueue.push(fn);
11868 fxWrap : function(pos, o, vis){
11870 if(!o.wrap || !(wrap = Roo.get(o.wrap))){
11873 wrapXY = this.getXY();
11875 var div = document.createElement("div");
11876 div.style.visibility = vis;
11877 wrap = Roo.get(this.dom.parentNode.insertBefore(div, this.dom));
11878 wrap.setPositioning(pos);
11879 if(wrap.getStyle("position") == "static"){
11880 wrap.position("relative");
11882 this.clearPositioning('auto');
11884 wrap.dom.appendChild(this.dom);
11886 wrap.setXY(wrapXY);
11893 fxUnwrap : function(wrap, pos, o){
11894 this.clearPositioning();
11895 this.setPositioning(pos);
11897 wrap.dom.parentNode.insertBefore(this.dom, wrap.dom);
11903 getFxRestore : function(){
11904 var st = this.dom.style;
11905 return {pos: this.getPositioning(), width: st.width, height : st.height};
11909 afterFx : function(o){
11911 this.applyStyles(o.afterStyle);
11914 this.addClass(o.afterCls);
11916 if(o.remove === true){
11919 Roo.callback(o.callback, o.scope, [this]);
11921 this.fxQueue.shift();
11927 getFxEl : function(){ // support for composite element fx
11928 return Roo.get(this.dom);
11932 fxanim : function(args, opt, animType, defaultDur, defaultEase, cb){
11933 animType = animType || 'run';
11935 var anim = Roo.lib.Anim[animType](
11937 (opt.duration || defaultDur) || .35,
11938 (opt.easing || defaultEase) || 'easeOut',
11940 Roo.callback(cb, this);
11949 // backwords compat
11950 Roo.Fx.resize = Roo.Fx.scale;
11952 //When included, Roo.Fx is automatically applied to Element so that all basic
11953 //effects are available directly via the Element API
11954 Roo.apply(Roo.Element.prototype, Roo.Fx);/*
11956 * Ext JS Library 1.1.1
11957 * Copyright(c) 2006-2007, Ext JS, LLC.
11959 * Originally Released Under LGPL - original licence link has changed is not relivant.
11962 * <script type="text/javascript">
11967 * @class Roo.CompositeElement
11968 * Standard composite class. Creates a Roo.Element for every element in the collection.
11970 * <b>NOTE: Although they are not listed, this class supports all of the set/update methods of Roo.Element. All Roo.Element
11971 * actions will be performed on all the elements in this collection.</b>
11973 * All methods return <i>this</i> and can be chained.
11975 var els = Roo.select("#some-el div.some-class", true);
11976 // or select directly from an existing element
11977 var el = Roo.get('some-el');
11978 el.select('div.some-class', true);
11980 els.setWidth(100); // all elements become 100 width
11981 els.hide(true); // all elements fade out and hide
11983 els.setWidth(100).hide(true);
11986 Roo.CompositeElement = function(els){
11987 this.elements = [];
11988 this.addElements(els);
11990 Roo.CompositeElement.prototype = {
11992 addElements : function(els){
11996 if(typeof els == "string"){
11997 els = Roo.Element.selectorFunction(els);
11999 var yels = this.elements;
12000 var index = yels.length-1;
12001 for(var i = 0, len = els.length; i < len; i++) {
12002 yels[++index] = Roo.get(els[i]);
12008 * Clears this composite and adds the elements returned by the passed selector.
12009 * @param {String/Array} els A string CSS selector, an array of elements or an element
12010 * @return {CompositeElement} this
12012 fill : function(els){
12013 this.elements = [];
12019 * Filters this composite to only elements that match the passed selector.
12020 * @param {String} selector A string CSS selector
12021 * @param {Boolean} inverse return inverse filter (not matches)
12022 * @return {CompositeElement} this
12024 filter : function(selector, inverse){
12026 inverse = inverse || false;
12027 this.each(function(el){
12028 var match = inverse ? !el.is(selector) : el.is(selector);
12030 els[els.length] = el.dom;
12037 invoke : function(fn, args){
12038 var els = this.elements;
12039 for(var i = 0, len = els.length; i < len; i++) {
12040 Roo.Element.prototype[fn].apply(els[i], args);
12045 * Adds elements to this composite.
12046 * @param {String/Array} els A string CSS selector, an array of elements or an element
12047 * @return {CompositeElement} this
12049 add : function(els){
12050 if(typeof els == "string"){
12051 this.addElements(Roo.Element.selectorFunction(els));
12052 }else if(els.length !== undefined){
12053 this.addElements(els);
12055 this.addElements([els]);
12060 * Calls the passed function passing (el, this, index) for each element in this composite.
12061 * @param {Function} fn The function to call
12062 * @param {Object} scope (optional) The <i>this</i> object (defaults to the element)
12063 * @return {CompositeElement} this
12065 each : function(fn, scope){
12066 var els = this.elements;
12067 for(var i = 0, len = els.length; i < len; i++){
12068 if(fn.call(scope || els[i], els[i], this, i) === false) {
12076 * Returns the Element object at the specified index
12077 * @param {Number} index
12078 * @return {Roo.Element}
12080 item : function(index){
12081 return this.elements[index] || null;
12085 * Returns the first Element
12086 * @return {Roo.Element}
12088 first : function(){
12089 return this.item(0);
12093 * Returns the last Element
12094 * @return {Roo.Element}
12097 return this.item(this.elements.length-1);
12101 * Returns the number of elements in this composite
12104 getCount : function(){
12105 return this.elements.length;
12109 * Returns true if this composite contains the passed element
12112 contains : function(el){
12113 return this.indexOf(el) !== -1;
12117 * Returns true if this composite contains the passed element
12120 indexOf : function(el){
12121 return this.elements.indexOf(Roo.get(el));
12126 * Removes the specified element(s).
12127 * @param {Mixed} el The id of an element, the Element itself, the index of the element in this composite
12128 * or an array of any of those.
12129 * @param {Boolean} removeDom (optional) True to also remove the element from the document
12130 * @return {CompositeElement} this
12132 removeElement : function(el, removeDom){
12133 if(el instanceof Array){
12134 for(var i = 0, len = el.length; i < len; i++){
12135 this.removeElement(el[i]);
12139 var index = typeof el == 'number' ? el : this.indexOf(el);
12142 var d = this.elements[index];
12146 d.parentNode.removeChild(d);
12149 this.elements.splice(index, 1);
12155 * Replaces the specified element with the passed element.
12156 * @param {String/HTMLElement/Element/Number} el The id of an element, the Element itself, the index of the element in this composite
12158 * @param {String/HTMLElement/Element} replacement The id of an element or the Element itself.
12159 * @param {Boolean} domReplace (Optional) True to remove and replace the element in the document too.
12160 * @return {CompositeElement} this
12162 replaceElement : function(el, replacement, domReplace){
12163 var index = typeof el == 'number' ? el : this.indexOf(el);
12166 this.elements[index].replaceWith(replacement);
12168 this.elements.splice(index, 1, Roo.get(replacement))
12175 * Removes all elements.
12177 clear : function(){
12178 this.elements = [];
12182 Roo.CompositeElement.createCall = function(proto, fnName){
12183 if(!proto[fnName]){
12184 proto[fnName] = function(){
12185 return this.invoke(fnName, arguments);
12189 for(var fnName in Roo.Element.prototype){
12190 if(typeof Roo.Element.prototype[fnName] == "function"){
12191 Roo.CompositeElement.createCall(Roo.CompositeElement.prototype, fnName);
12197 * Ext JS Library 1.1.1
12198 * Copyright(c) 2006-2007, Ext JS, LLC.
12200 * Originally Released Under LGPL - original licence link has changed is not relivant.
12203 * <script type="text/javascript">
12207 * @class Roo.CompositeElementLite
12208 * @extends Roo.CompositeElement
12209 * Flyweight composite class. Reuses the same Roo.Element for element operations.
12211 var els = Roo.select("#some-el div.some-class");
12212 // or select directly from an existing element
12213 var el = Roo.get('some-el');
12214 el.select('div.some-class');
12216 els.setWidth(100); // all elements become 100 width
12217 els.hide(true); // all elements fade out and hide
12219 els.setWidth(100).hide(true);
12220 </code></pre><br><br>
12221 * <b>NOTE: Although they are not listed, this class supports all of the set/update methods of Roo.Element. All Roo.Element
12222 * actions will be performed on all the elements in this collection.</b>
12224 Roo.CompositeElementLite = function(els){
12225 Roo.CompositeElementLite.superclass.constructor.call(this, els);
12226 this.el = new Roo.Element.Flyweight();
12228 Roo.extend(Roo.CompositeElementLite, Roo.CompositeElement, {
12229 addElements : function(els){
12231 if(els instanceof Array){
12232 this.elements = this.elements.concat(els);
12234 var yels = this.elements;
12235 var index = yels.length-1;
12236 for(var i = 0, len = els.length; i < len; i++) {
12237 yels[++index] = els[i];
12243 invoke : function(fn, args){
12244 var els = this.elements;
12246 for(var i = 0, len = els.length; i < len; i++) {
12248 Roo.Element.prototype[fn].apply(el, args);
12253 * Returns a flyweight Element of the dom element object at the specified index
12254 * @param {Number} index
12255 * @return {Roo.Element}
12257 item : function(index){
12258 if(!this.elements[index]){
12261 this.el.dom = this.elements[index];
12265 // fixes scope with flyweight
12266 addListener : function(eventName, handler, scope, opt){
12267 var els = this.elements;
12268 for(var i = 0, len = els.length; i < len; i++) {
12269 Roo.EventManager.on(els[i], eventName, handler, scope || els[i], opt);
12275 * Calls the passed function passing (el, this, index) for each element in this composite. <b>The element
12276 * passed is the flyweight (shared) Roo.Element instance, so if you require a
12277 * a reference to the dom node, use el.dom.</b>
12278 * @param {Function} fn The function to call
12279 * @param {Object} scope (optional) The <i>this</i> object (defaults to the element)
12280 * @return {CompositeElement} this
12282 each : function(fn, scope){
12283 var els = this.elements;
12285 for(var i = 0, len = els.length; i < len; i++){
12287 if(fn.call(scope || el, el, this, i) === false){
12294 indexOf : function(el){
12295 return this.elements.indexOf(Roo.getDom(el));
12298 replaceElement : function(el, replacement, domReplace){
12299 var index = typeof el == 'number' ? el : this.indexOf(el);
12301 replacement = Roo.getDom(replacement);
12303 var d = this.elements[index];
12304 d.parentNode.insertBefore(replacement, d);
12305 d.parentNode.removeChild(d);
12307 this.elements.splice(index, 1, replacement);
12312 Roo.CompositeElementLite.prototype.on = Roo.CompositeElementLite.prototype.addListener;
12316 * Ext JS Library 1.1.1
12317 * Copyright(c) 2006-2007, Ext JS, LLC.
12319 * Originally Released Under LGPL - original licence link has changed is not relivant.
12322 * <script type="text/javascript">
12328 * @class Roo.data.Connection
12329 * @extends Roo.util.Observable
12330 * The class encapsulates a connection to the page's originating domain, allowing requests to be made
12331 * either to a configured URL, or to a URL specified at request time.
12333 * Requests made by this class are asynchronous, and will return immediately. No data from
12334 * the server will be available to the statement immediately following the {@link #request} call.
12335 * To process returned data, use a callback in the request options object, or an event listener.
12337 * Note: If you are doing a file upload, you will not get a normal response object sent back to
12338 * your callback or event handler. Since the upload is handled via in IFRAME, there is no XMLHttpRequest.
12339 * The response object is created using the innerHTML of the IFRAME's document as the responseText
12340 * property and, if present, the IFRAME's XML document as the responseXML property.
12342 * This means that a valid XML or HTML document must be returned. If JSON data is required, it is suggested
12343 * that it be placed either inside a <textarea> in an HTML document and retrieved from the responseText
12344 * using a regex, or inside a CDATA section in an XML document and retrieved from the responseXML using
12345 * standard DOM methods.
12347 * @param {Object} config a configuration object.
12349 Roo.data.Connection = function(config){
12350 Roo.apply(this, config);
12353 * @event beforerequest
12354 * Fires before a network request is made to retrieve a data object.
12355 * @param {Connection} conn This Connection object.
12356 * @param {Object} options The options config object passed to the {@link #request} method.
12358 "beforerequest" : true,
12360 * @event requestcomplete
12361 * Fires if the request was successfully completed.
12362 * @param {Connection} conn This Connection object.
12363 * @param {Object} response The XHR object containing the response data.
12364 * See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
12365 * @param {Object} options The options config object passed to the {@link #request} method.
12367 "requestcomplete" : true,
12369 * @event requestexception
12370 * Fires if an error HTTP status was returned from the server.
12371 * See {@link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html} for details of HTTP status codes.
12372 * @param {Connection} conn This Connection object.
12373 * @param {Object} response The XHR object containing the response data.
12374 * See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
12375 * @param {Object} options The options config object passed to the {@link #request} method.
12377 "requestexception" : true
12379 Roo.data.Connection.superclass.constructor.call(this);
12382 Roo.extend(Roo.data.Connection, Roo.util.Observable, {
12384 * @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
12387 * @cfg {Object} extraParams (Optional) An object containing properties which are used as
12388 * extra parameters to each request made by this object. (defaults to undefined)
12391 * @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
12392 * to each request made by this object. (defaults to undefined)
12395 * @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)
12398 * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
12402 * @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
12408 * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
12411 disableCaching: true,
12414 * Sends an HTTP request to a remote server.
12415 * @param {Object} options An object which may contain the following properties:<ul>
12416 * <li><b>url</b> {String} (Optional) The URL to which to send the request. Defaults to configured URL</li>
12417 * <li><b>params</b> {Object/String/Function} (Optional) An object containing properties which are used as parameters to the
12418 * request, a url encoded string or a function to call to get either.</li>
12419 * <li><b>method</b> {String} (Optional) The HTTP method to use for the request. Defaults to the configured method, or
12420 * if no method was configured, "GET" if no parameters are being sent, and "POST" if parameters are being sent.</li>
12421 * <li><b>callback</b> {Function} (Optional) The function to be called upon receipt of the HTTP response.
12422 * The callback is called regardless of success or failure and is passed the following parameters:<ul>
12423 * <li>options {Object} The parameter to the request call.</li>
12424 * <li>success {Boolean} True if the request succeeded.</li>
12425 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
12427 * <li><b>success</b> {Function} (Optional) The function to be called upon success of the request.
12428 * The callback is passed the following parameters:<ul>
12429 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
12430 * <li>options {Object} The parameter to the request call.</li>
12432 * <li><b>failure</b> {Function} (Optional) The function to be called upon failure of the request.
12433 * The callback is passed the following parameters:<ul>
12434 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
12435 * <li>options {Object} The parameter to the request call.</li>
12437 * <li><b>scope</b> {Object} (Optional) The scope in which to execute the callbacks: The "this" object
12438 * for the callback function. Defaults to the browser window.</li>
12439 * <li><b>form</b> {Object/String} (Optional) A form object or id to pull parameters from.</li>
12440 * <li><b>isUpload</b> {Boolean} (Optional) True if the form object is a file upload (will usually be automatically detected).</li>
12441 * <li><b>headers</b> {Object} (Optional) Request headers to set for the request.</li>
12442 * <li><b>xmlData</b> {Object} (Optional) XML document to use for the post. Note: This will be used instead of
12443 * params for the post data. Any params will be appended to the URL.</li>
12444 * <li><b>disableCaching</b> {Boolean} (Optional) True to add a unique cache-buster param to GET requests.</li>
12446 * @return {Number} transactionId
12448 request : function(o){
12449 if(this.fireEvent("beforerequest", this, o) !== false){
12452 if(typeof p == "function"){
12453 p = p.call(o.scope||window, o);
12455 if(typeof p == "object"){
12456 p = Roo.urlEncode(o.params);
12458 if(this.extraParams){
12459 var extras = Roo.urlEncode(this.extraParams);
12460 p = p ? (p + '&' + extras) : extras;
12463 var url = o.url || this.url;
12464 if(typeof url == 'function'){
12465 url = url.call(o.scope||window, o);
12469 var form = Roo.getDom(o.form);
12470 url = url || form.action;
12472 var enctype = form.getAttribute("enctype");
12475 return this.doFormDataUpload(o, url);
12478 if(o.isUpload || (enctype && enctype.toLowerCase() == 'multipart/form-data')){
12479 return this.doFormUpload(o, p, url);
12481 var f = Roo.lib.Ajax.serializeForm(form);
12482 p = p ? (p + '&' + f) : f;
12485 if (!o.form && o.formData) {
12486 o.formData = o.formData === true ? new FormData() : o.formData;
12487 for (var k in o.params) {
12488 o.formData.append(k,o.params[k]);
12491 return this.doFormDataUpload(o, url);
12495 var hs = o.headers;
12496 if(this.defaultHeaders){
12497 hs = Roo.apply(hs || {}, this.defaultHeaders);
12504 success: this.handleResponse,
12505 failure: this.handleFailure,
12507 argument: {options: o},
12508 timeout : o.timeout || this.timeout
12511 var method = o.method||this.method||(p ? "POST" : "GET");
12513 if(method == 'GET' && (this.disableCaching && o.disableCaching !== false) || o.disableCaching === true){
12514 url += (url.indexOf('?') != -1 ? '&' : '?') + '_dc=' + (new Date().getTime());
12517 if(typeof o.autoAbort == 'boolean'){ // options gets top priority
12521 }else if(this.autoAbort !== false){
12525 if((method == 'GET' && p) || o.xmlData){
12526 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
12529 Roo.lib.Ajax.useDefaultHeader = typeof(o.headers) == 'undefined' || typeof(o.headers['Content-Type']) == 'undefined';
12530 this.transId = Roo.lib.Ajax.request(method, url, cb, p, o);
12531 Roo.lib.Ajax.useDefaultHeader == true;
12532 return this.transId;
12534 Roo.callback(o.callback, o.scope, [o, null, null]);
12540 * Determine whether this object has a request outstanding.
12541 * @param {Number} transactionId (Optional) defaults to the last transaction
12542 * @return {Boolean} True if there is an outstanding request.
12544 isLoading : function(transId){
12546 return Roo.lib.Ajax.isCallInProgress(transId);
12548 return this.transId ? true : false;
12553 * Aborts any outstanding request.
12554 * @param {Number} transactionId (Optional) defaults to the last transaction
12556 abort : function(transId){
12557 if(transId || this.isLoading()){
12558 Roo.lib.Ajax.abort(transId || this.transId);
12563 handleResponse : function(response){
12564 this.transId = false;
12565 var options = response.argument.options;
12566 response.argument = options ? options.argument : null;
12567 this.fireEvent("requestcomplete", this, response, options);
12568 Roo.callback(options.success, options.scope, [response, options]);
12569 Roo.callback(options.callback, options.scope, [options, true, response]);
12573 handleFailure : function(response, e){
12574 this.transId = false;
12575 var options = response.argument.options;
12576 response.argument = options ? options.argument : null;
12577 this.fireEvent("requestexception", this, response, options, e);
12578 Roo.callback(options.failure, options.scope, [response, options]);
12579 Roo.callback(options.callback, options.scope, [options, false, response]);
12583 doFormUpload : function(o, ps, url){
12585 var frame = document.createElement('iframe');
12588 frame.className = 'x-hidden';
12590 frame.src = Roo.SSL_SECURE_URL;
12592 document.body.appendChild(frame);
12595 document.frames[id].name = id;
12598 var form = Roo.getDom(o.form);
12600 form.method = 'POST';
12601 form.enctype = form.encoding = 'multipart/form-data';
12607 if(ps){ // add dynamic params
12609 ps = Roo.urlDecode(ps, false);
12611 if(ps.hasOwnProperty(k)){
12612 hd = document.createElement('input');
12613 hd.type = 'hidden';
12616 form.appendChild(hd);
12623 var r = { // bogus response object
12628 r.argument = o ? o.argument : null;
12633 doc = frame.contentWindow.document;
12635 doc = (frame.contentDocument || window.frames[id].document);
12637 if(doc && doc.body){
12638 r.responseText = doc.body.innerHTML;
12640 if(doc && doc.XMLDocument){
12641 r.responseXML = doc.XMLDocument;
12643 r.responseXML = doc;
12650 Roo.EventManager.removeListener(frame, 'load', cb, this);
12652 this.fireEvent("requestcomplete", this, r, o);
12653 Roo.callback(o.success, o.scope, [r, o]);
12654 Roo.callback(o.callback, o.scope, [o, true, r]);
12656 setTimeout(function(){document.body.removeChild(frame);}, 100);
12659 Roo.EventManager.on(frame, 'load', cb, this);
12662 if(hiddens){ // remove dynamic params
12663 for(var i = 0, len = hiddens.length; i < len; i++){
12664 form.removeChild(hiddens[i]);
12668 // this is a 'formdata version???'
12671 doFormDataUpload : function(o, url)
12675 var form = Roo.getDom(o.form);
12676 form.enctype = form.encoding = 'multipart/form-data';
12677 formData = o.formData === true ? new FormData(form) : o.formData;
12679 formData = o.formData === true ? new FormData() : o.formData;
12684 success: this.handleResponse,
12685 failure: this.handleFailure,
12687 argument: {options: o},
12688 timeout : o.timeout || this.timeout
12691 if(typeof o.autoAbort == 'boolean'){ // options gets top priority
12695 }else if(this.autoAbort !== false){
12699 //Roo.lib.Ajax.defaultPostHeader = null;
12700 Roo.lib.Ajax.useDefaultHeader = false;
12701 this.transId = Roo.lib.Ajax.request( "POST", url, cb, formData, o);
12702 Roo.lib.Ajax.useDefaultHeader = true;
12710 * Ext JS Library 1.1.1
12711 * Copyright(c) 2006-2007, Ext JS, LLC.
12713 * Originally Released Under LGPL - original licence link has changed is not relivant.
12716 * <script type="text/javascript">
12720 * Global Ajax request class.
12723 * @extends Roo.data.Connection
12726 * @cfg {String} url The default URL to be used for requests to the server. (defaults to undefined)
12727 * @cfg {Object} extraParams An object containing properties which are used as extra parameters to each request made by this object. (defaults to undefined)
12728 * @cfg {Object} defaultHeaders An object containing request headers which are added to each request made by this object. (defaults to undefined)
12729 * @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)
12730 * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
12731 * @cfg {Boolean} autoAbort (Optional) Whether a new request should abort any pending requests. (defaults to false)
12732 * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
12734 Roo.Ajax = new Roo.data.Connection({
12743 * Serialize the passed form into a url encoded string
12745 * @param {String/HTMLElement} form
12748 serializeForm : function(form){
12749 return Roo.lib.Ajax.serializeForm(form);
12753 * Ext JS Library 1.1.1
12754 * Copyright(c) 2006-2007, Ext JS, LLC.
12756 * Originally Released Under LGPL - original licence link has changed is not relivant.
12759 * <script type="text/javascript">
12764 * @class Roo.UpdateManager
12765 * @extends Roo.util.Observable
12766 * Provides AJAX-style update for Element object.<br><br>
12769 * // Get it from a Roo.Element object
12770 * var el = Roo.get("foo");
12771 * var mgr = el.getUpdateManager();
12772 * mgr.update("http://myserver.com/index.php", "param1=1&param2=2");
12774 * mgr.formUpdate("myFormId", "http://myserver.com/index.php");
12776 * // or directly (returns the same UpdateManager instance)
12777 * var mgr = new Roo.UpdateManager("myElementId");
12778 * mgr.startAutoRefresh(60, "http://myserver.com/index.php");
12779 * mgr.on("update", myFcnNeedsToKnow);
12781 // short handed call directly from the element object
12782 Roo.get("foo").load({
12786 text: "Loading Foo..."
12790 * Create new UpdateManager directly.
12791 * @param {String/HTMLElement/Roo.Element} el The element to update
12792 * @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).
12794 Roo.UpdateManager = function(el, forceNew){
12796 if(!forceNew && el.updateManager){
12797 return el.updateManager;
12800 * The Element object
12801 * @type Roo.Element
12805 * Cached url to use for refreshes. Overwritten every time update() is called unless "discardUrl" param is set to true.
12808 this.defaultUrl = null;
12812 * @event beforeupdate
12813 * Fired before an update is made, return false from your handler and the update is cancelled.
12814 * @param {Roo.Element} el
12815 * @param {String/Object/Function} url
12816 * @param {String/Object} params
12818 "beforeupdate": true,
12821 * Fired after successful update is made.
12822 * @param {Roo.Element} el
12823 * @param {Object} oResponseObject The response Object
12828 * Fired on update failure.
12829 * @param {Roo.Element} el
12830 * @param {Object} oResponseObject The response Object
12834 var d = Roo.UpdateManager.defaults;
12836 * Blank page URL to use with SSL file uploads (Defaults to Roo.UpdateManager.defaults.sslBlankUrl or "about:blank").
12839 this.sslBlankUrl = d.sslBlankUrl;
12841 * Whether to append unique parameter on get request to disable caching (Defaults to Roo.UpdateManager.defaults.disableCaching or false).
12844 this.disableCaching = d.disableCaching;
12846 * Text for loading indicator (Defaults to Roo.UpdateManager.defaults.indicatorText or '<div class="loading-indicator">Loading...</div>').
12849 this.indicatorText = d.indicatorText;
12851 * Whether to show indicatorText when loading (Defaults to Roo.UpdateManager.defaults.showLoadIndicator or true).
12854 this.showLoadIndicator = d.showLoadIndicator;
12856 * Timeout for requests or form posts in seconds (Defaults to Roo.UpdateManager.defaults.timeout or 30 seconds).
12859 this.timeout = d.timeout;
12862 * True to process scripts in the output (Defaults to Roo.UpdateManager.defaults.loadScripts (false)).
12865 this.loadScripts = d.loadScripts;
12868 * Transaction object of current executing transaction
12870 this.transaction = null;
12875 this.autoRefreshProcId = null;
12877 * Delegate for refresh() prebound to "this", use myUpdater.refreshDelegate.createCallback(arg1, arg2) to bind arguments
12880 this.refreshDelegate = this.refresh.createDelegate(this);
12882 * Delegate for update() prebound to "this", use myUpdater.updateDelegate.createCallback(arg1, arg2) to bind arguments
12885 this.updateDelegate = this.update.createDelegate(this);
12887 * Delegate for formUpdate() prebound to "this", use myUpdater.formUpdateDelegate.createCallback(arg1, arg2) to bind arguments
12890 this.formUpdateDelegate = this.formUpdate.createDelegate(this);
12894 this.successDelegate = this.processSuccess.createDelegate(this);
12898 this.failureDelegate = this.processFailure.createDelegate(this);
12900 if(!this.renderer){
12902 * The renderer for this UpdateManager. Defaults to {@link Roo.UpdateManager.BasicRenderer}.
12904 this.renderer = new Roo.UpdateManager.BasicRenderer();
12907 Roo.UpdateManager.superclass.constructor.call(this);
12910 Roo.extend(Roo.UpdateManager, Roo.util.Observable, {
12912 * Get the Element this UpdateManager is bound to
12913 * @return {Roo.Element} The element
12915 getEl : function(){
12919 * Performs an async request, updating this element with the response. If params are specified it uses POST, otherwise it uses GET.
12920 * @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:
12923 url: "your-url.php",<br/>
12924 params: {param1: "foo", param2: "bar"}, // or a URL encoded string<br/>
12925 callback: yourFunction,<br/>
12926 scope: yourObject, //(optional scope) <br/>
12927 discardUrl: false, <br/>
12928 nocache: false,<br/>
12929 text: "Loading...",<br/>
12931 scripts: false<br/>
12934 * The only required property is url. The optional properties nocache, text and scripts
12935 * are shorthand for disableCaching, indicatorText and loadScripts and are used to set their associated property on this UpdateManager instance.
12936 * @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}
12937 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess, oResponse)
12938 * @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.
12940 update : function(url, params, callback, discardUrl){
12941 if(this.fireEvent("beforeupdate", this.el, url, params) !== false){
12942 var method = this.method,
12944 if(typeof url == "object"){ // must be config object
12947 params = params || cfg.params;
12948 callback = callback || cfg.callback;
12949 discardUrl = discardUrl || cfg.discardUrl;
12950 if(callback && cfg.scope){
12951 callback = callback.createDelegate(cfg.scope);
12953 if(typeof cfg.method != "undefined"){method = cfg.method;};
12954 if(typeof cfg.nocache != "undefined"){this.disableCaching = cfg.nocache;};
12955 if(typeof cfg.text != "undefined"){this.indicatorText = '<div class="loading-indicator">'+cfg.text+"</div>";};
12956 if(typeof cfg.scripts != "undefined"){this.loadScripts = cfg.scripts;};
12957 if(typeof cfg.timeout != "undefined"){this.timeout = cfg.timeout;};
12959 this.showLoading();
12961 this.defaultUrl = url;
12963 if(typeof url == "function"){
12964 url = url.call(this);
12967 method = method || (params ? "POST" : "GET");
12968 if(method == "GET"){
12969 url = this.prepareUrl(url);
12972 var o = Roo.apply(cfg ||{}, {
12975 success: this.successDelegate,
12976 failure: this.failureDelegate,
12977 callback: undefined,
12978 timeout: (this.timeout*1000),
12979 argument: {"url": url, "form": null, "callback": callback, "params": params}
12981 Roo.log("updated manager called with timeout of " + o.timeout);
12982 this.transaction = Roo.Ajax.request(o);
12987 * 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.
12988 * Uses this.sslBlankUrl for SSL file uploads to prevent IE security warning.
12989 * @param {String/HTMLElement} form The form Id or form element
12990 * @param {String} url (optional) The url to pass the form to. If omitted the action attribute on the form will be used.
12991 * @param {Boolean} reset (optional) Whether to try to reset the form after the update
12992 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess, oResponse)
12994 formUpdate : function(form, url, reset, callback){
12995 if(this.fireEvent("beforeupdate", this.el, form, url) !== false){
12996 if(typeof url == "function"){
12997 url = url.call(this);
12999 form = Roo.getDom(form);
13000 this.transaction = Roo.Ajax.request({
13003 success: this.successDelegate,
13004 failure: this.failureDelegate,
13005 timeout: (this.timeout*1000),
13006 argument: {"url": url, "form": form, "callback": callback, "reset": reset}
13008 this.showLoading.defer(1, this);
13013 * Refresh the element with the last used url or defaultUrl. If there is no url, it returns immediately
13014 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
13016 refresh : function(callback){
13017 if(this.defaultUrl == null){
13020 this.update(this.defaultUrl, null, callback, true);
13024 * Set this element to auto refresh.
13025 * @param {Number} interval How often to update (in seconds).
13026 * @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)
13027 * @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}
13028 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
13029 * @param {Boolean} refreshNow (optional) Whether to execute the refresh now, or wait the interval
13031 startAutoRefresh : function(interval, url, params, callback, refreshNow){
13033 this.update(url || this.defaultUrl, params, callback, true);
13035 if(this.autoRefreshProcId){
13036 clearInterval(this.autoRefreshProcId);
13038 this.autoRefreshProcId = setInterval(this.update.createDelegate(this, [url || this.defaultUrl, params, callback, true]), interval*1000);
13042 * Stop auto refresh on this element.
13044 stopAutoRefresh : function(){
13045 if(this.autoRefreshProcId){
13046 clearInterval(this.autoRefreshProcId);
13047 delete this.autoRefreshProcId;
13051 isAutoRefreshing : function(){
13052 return this.autoRefreshProcId ? true : false;
13055 * Called to update the element to "Loading" state. Override to perform custom action.
13057 showLoading : function(){
13058 if(this.showLoadIndicator){
13059 this.el.update(this.indicatorText);
13064 * Adds unique parameter to query string if disableCaching = true
13067 prepareUrl : function(url){
13068 if(this.disableCaching){
13069 var append = "_dc=" + (new Date().getTime());
13070 if(url.indexOf("?") !== -1){
13071 url += "&" + append;
13073 url += "?" + append;
13082 processSuccess : function(response){
13083 this.transaction = null;
13084 if(response.argument.form && response.argument.reset){
13085 try{ // put in try/catch since some older FF releases had problems with this
13086 response.argument.form.reset();
13089 if(this.loadScripts){
13090 this.renderer.render(this.el, response, this,
13091 this.updateComplete.createDelegate(this, [response]));
13093 this.renderer.render(this.el, response, this);
13094 this.updateComplete(response);
13098 updateComplete : function(response){
13099 this.fireEvent("update", this.el, response);
13100 if(typeof response.argument.callback == "function"){
13101 response.argument.callback(this.el, true, response);
13108 processFailure : function(response){
13109 this.transaction = null;
13110 this.fireEvent("failure", this.el, response);
13111 if(typeof response.argument.callback == "function"){
13112 response.argument.callback(this.el, false, response);
13117 * Set the content renderer for this UpdateManager. See {@link Roo.UpdateManager.BasicRenderer#render} for more details.
13118 * @param {Object} renderer The object implementing the render() method
13120 setRenderer : function(renderer){
13121 this.renderer = renderer;
13124 getRenderer : function(){
13125 return this.renderer;
13129 * Set the defaultUrl used for updates
13130 * @param {String/Function} defaultUrl The url or a function to call to get the url
13132 setDefaultUrl : function(defaultUrl){
13133 this.defaultUrl = defaultUrl;
13137 * Aborts the executing transaction
13139 abort : function(){
13140 if(this.transaction){
13141 Roo.Ajax.abort(this.transaction);
13146 * Returns true if an update is in progress
13147 * @return {Boolean}
13149 isUpdating : function(){
13150 if(this.transaction){
13151 return Roo.Ajax.isLoading(this.transaction);
13158 * @class Roo.UpdateManager.defaults
13159 * @static (not really - but it helps the doc tool)
13160 * The defaults collection enables customizing the default properties of UpdateManager
13162 Roo.UpdateManager.defaults = {
13164 * Timeout for requests or form posts in seconds (Defaults 30 seconds).
13170 * True to process scripts by default (Defaults to false).
13173 loadScripts : false,
13176 * Blank page URL to use with SSL file uploads (Defaults to "javascript:false").
13179 sslBlankUrl : (Roo.SSL_SECURE_URL || "javascript:false"),
13181 * Whether to append unique parameter on get request to disable caching (Defaults to false).
13184 disableCaching : false,
13186 * Whether to show indicatorText when loading (Defaults to true).
13189 showLoadIndicator : true,
13191 * Text for loading indicator (Defaults to '<div class="loading-indicator">Loading...</div>').
13194 indicatorText : '<div class="loading-indicator">Loading...</div>'
13198 * Static convenience method. This method is deprecated in favor of el.load({url:'foo.php', ...}).
13200 * <pre><code>Roo.UpdateManager.updateElement("my-div", "stuff.php");</code></pre>
13201 * @param {String/HTMLElement/Roo.Element} el The element to update
13202 * @param {String} url The url
13203 * @param {String/Object} params (optional) Url encoded param string or an object of name/value pairs
13204 * @param {Object} options (optional) A config object with any of the UpdateManager properties you want to set - for example: {disableCaching:true, indicatorText: "Loading data..."}
13207 * @member Roo.UpdateManager
13209 Roo.UpdateManager.updateElement = function(el, url, params, options){
13210 var um = Roo.get(el, true).getUpdateManager();
13211 Roo.apply(um, options);
13212 um.update(url, params, options ? options.callback : null);
13214 // alias for backwards compat
13215 Roo.UpdateManager.update = Roo.UpdateManager.updateElement;
13217 * @class Roo.UpdateManager.BasicRenderer
13218 * Default Content renderer. Updates the elements innerHTML with the responseText.
13220 Roo.UpdateManager.BasicRenderer = function(){};
13222 Roo.UpdateManager.BasicRenderer.prototype = {
13224 * This is called when the transaction is completed and it's time to update the element - The BasicRenderer
13225 * updates the elements innerHTML with the responseText - To perform a custom render (i.e. XML or JSON processing),
13226 * create an object with a "render(el, response)" method and pass it to setRenderer on the UpdateManager.
13227 * @param {Roo.Element} el The element being rendered
13228 * @param {Object} response The YUI Connect response object
13229 * @param {UpdateManager} updateManager The calling update manager
13230 * @param {Function} callback A callback that will need to be called if loadScripts is true on the UpdateManager
13232 render : function(el, response, updateManager, callback){
13233 el.update(response.responseText, updateManager.loadScripts, callback);
13239 * (c)) Alan Knowles
13245 * @class Roo.DomTemplate
13246 * @extends Roo.Template
13247 * An effort at a dom based template engine..
13249 * Similar to XTemplate, except it uses dom parsing to create the template..
13251 * Supported features:
13256 {a_variable} - output encoded.
13257 {a_variable.format:("Y-m-d")} - call a method on the variable
13258 {a_variable:raw} - unencoded output
13259 {a_variable:toFixed(1,2)} - Roo.util.Format."toFixed"
13260 {a_variable:this.method_on_template(...)} - call a method on the template object.
13265 <div roo-for="a_variable or condition.."></div>
13266 <div roo-if="a_variable or condition"></div>
13267 <div roo-exec="some javascript"></div>
13268 <div roo-name="named_template"></div>
13273 Roo.DomTemplate = function()
13275 Roo.DomTemplate.superclass.constructor.apply(this, arguments);
13282 Roo.extend(Roo.DomTemplate, Roo.Template, {
13284 * id counter for sub templates.
13288 * flag to indicate if dom parser is inside a pre,
13289 * it will strip whitespace if not.
13294 * The various sub templates
13302 * basic tag replacing syntax
13305 * // you can fake an object call by doing this
13309 re : /(\{|\%7B)([\w-\.]+)(?:\:([\w\.]*)(?:\(([^)]*?)?\))?)?(\}|\%7D)/g,
13310 //re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
13312 iterChild : function (node, method) {
13314 var oldPre = this.inPre;
13315 if (node.tagName == 'PRE') {
13318 for( var i = 0; i < node.childNodes.length; i++) {
13319 method.call(this, node.childNodes[i]);
13321 this.inPre = oldPre;
13327 * compile the template
13329 * This is not recursive, so I'm not sure how nested templates are really going to be handled..
13332 compile: function()
13336 // covert the html into DOM...
13340 doc = document.implementation.createHTMLDocument("");
13341 doc.documentElement.innerHTML = this.html ;
13342 div = doc.documentElement;
13344 // old IE... - nasty -- it causes all sorts of issues.. with
13345 // images getting pulled from server..
13346 div = document.createElement('div');
13347 div.innerHTML = this.html;
13349 //doc.documentElement.innerHTML = htmlBody
13355 this.iterChild(div, function(n) {_t.compileNode(n, true); });
13357 var tpls = this.tpls;
13359 // create a top level template from the snippet..
13361 //Roo.log(div.innerHTML);
13368 body : div.innerHTML,
13381 Roo.each(tpls, function(tp){
13382 this.compileTpl(tp);
13383 this.tpls[tp.id] = tp;
13386 this.master = tpls[0];
13392 compileNode : function(node, istop) {
13397 // skip anything not a tag..
13398 if (node.nodeType != 1) {
13399 if (node.nodeType == 3 && !this.inPre) {
13400 // reduce white space..
13401 node.nodeValue = node.nodeValue.replace(/\s+/g, ' ');
13424 case (node.hasAttribute('roo-for')): tpl.attr = 'for'; break;
13425 case (node.hasAttribute('roo-if')): tpl.attr = 'if'; break;
13426 case (node.hasAttribute('roo-name')): tpl.attr = 'name'; break;
13427 case (node.hasAttribute('roo-exec')): tpl.attr = 'exec'; break;
13433 // just itterate children..
13434 this.iterChild(node,this.compileNode);
13437 tpl.uid = this.id++;
13438 tpl.value = node.getAttribute('roo-' + tpl.attr);
13439 node.removeAttribute('roo-'+ tpl.attr);
13440 if (tpl.attr != 'name') {
13441 var placeholder = document.createTextNode('{domtpl' + tpl.uid + '}');
13442 node.parentNode.replaceChild(placeholder, node);
13445 var placeholder = document.createElement('span');
13446 placeholder.className = 'roo-tpl-' + tpl.value;
13447 node.parentNode.replaceChild(placeholder, node);
13450 // parent now sees '{domtplXXXX}
13451 this.iterChild(node,this.compileNode);
13453 // we should now have node body...
13454 var div = document.createElement('div');
13455 div.appendChild(node);
13457 // this has the unfortunate side effect of converting tagged attributes
13458 // eg. href="{...}" into %7C...%7D
13459 // this has been fixed by searching for those combo's although it's a bit hacky..
13462 tpl.body = div.innerHTML;
13469 switch (tpl.value) {
13470 case '.': tpl.forCall = new Function('values', 'parent', 'with(values){ return values; }'); break;
13471 case '..': tpl.forCall= new Function('values', 'parent', 'with(values){ return parent; }'); break;
13472 default: tpl.forCall= new Function('values', 'parent', 'with(values){ return '+tpl.value+'; }');
13477 tpl.execCall = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
13481 tpl.ifCall = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
13485 tpl.id = tpl.value; // replace non characters???
13491 this.tpls.push(tpl);
13501 * Compile a segment of the template into a 'sub-template'
13507 compileTpl : function(tpl)
13509 var fm = Roo.util.Format;
13510 var useF = this.disableFormats !== true;
13512 var sep = Roo.isGecko ? "+\n" : ",\n";
13514 var undef = function(str) {
13515 Roo.debug && Roo.log("Property not found :" + str);
13519 //Roo.log(tpl.body);
13523 var fn = function(m, lbrace, name, format, args)
13526 //Roo.log(arguments);
13527 args = args ? args.replace(/\\'/g,"'") : args;
13528 //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
13529 if (typeof(format) == 'undefined') {
13530 format = 'htmlEncode';
13532 if (format == 'raw' ) {
13536 if(name.substr(0, 6) == 'domtpl'){
13537 return "'"+ sep +'this.applySubTemplate('+name.substr(6)+', values, parent)'+sep+"'";
13540 // build an array of options to determine if value is undefined..
13542 // basically get 'xxxx.yyyy' then do
13543 // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
13544 // (function () { Roo.log("Property not found"); return ''; })() :
13549 Roo.each(name.split('.'), function(st) {
13550 lookfor += (lookfor.length ? '.': '') + st;
13551 udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
13554 var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
13557 if(format && useF){
13559 args = args ? ',' + args : "";
13561 if(format.substr(0, 5) != "this."){
13562 format = "fm." + format + '(';
13564 format = 'this.call("'+ format.substr(5) + '", ';
13568 return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
13571 if (args && args.length) {
13572 // called with xxyx.yuu:(test,test)
13574 return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
13576 // raw.. - :raw modifier..
13577 return "'"+ sep + udef_st + name + ")"+sep+"'";
13581 // branched to use + in gecko and [].join() in others
13583 body = "tpl.compiled = function(values, parent){ with(values) { return '" +
13584 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
13587 body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
13588 body.push(tpl.body.replace(/(\r\n|\n)/g,
13589 '\\n').replace(/'/g, "\\'").replace(this.re, fn));
13590 body.push("'].join('');};};");
13591 body = body.join('');
13594 Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
13596 /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
13603 * same as applyTemplate, except it's done to one of the subTemplates
13604 * when using named templates, you can do:
13606 * var str = pl.applySubTemplate('your-name', values);
13609 * @param {Number} id of the template
13610 * @param {Object} values to apply to template
13611 * @param {Object} parent (normaly the instance of this object)
13613 applySubTemplate : function(id, values, parent)
13617 var t = this.tpls[id];
13621 if(t.ifCall && !t.ifCall.call(this, values, parent)){
13622 Roo.debug && Roo.log('if call on ' + t.value + ' return false');
13626 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-if="' + t.value + '" - ' + e.toString());
13633 if(t.execCall && t.execCall.call(this, values, parent)){
13637 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
13643 var vs = t.forCall ? t.forCall.call(this, values, parent) : values;
13644 parent = t.target ? values : parent;
13645 if(t.forCall && vs instanceof Array){
13647 for(var i = 0, len = vs.length; i < len; i++){
13649 buf[buf.length] = t.compiled.call(this, vs[i], parent);
13651 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
13653 //Roo.log(t.compiled);
13657 return buf.join('');
13660 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
13665 return t.compiled.call(this, vs, parent);
13667 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
13669 //Roo.log(t.compiled);
13677 applyTemplate : function(values){
13678 return this.master.compiled.call(this, values, {});
13679 //var s = this.subs;
13682 apply : function(){
13683 return this.applyTemplate.apply(this, arguments);
13688 Roo.DomTemplate.from = function(el){
13689 el = Roo.getDom(el);
13690 return new Roo.Domtemplate(el.value || el.innerHTML);
13693 * Ext JS Library 1.1.1
13694 * Copyright(c) 2006-2007, Ext JS, LLC.
13696 * Originally Released Under LGPL - original licence link has changed is not relivant.
13699 * <script type="text/javascript">
13703 * @class Roo.util.DelayedTask
13704 * Provides a convenient method of performing setTimeout where a new
13705 * timeout cancels the old timeout. An example would be performing validation on a keypress.
13706 * You can use this class to buffer
13707 * the keypress events for a certain number of milliseconds, and perform only if they stop
13708 * for that amount of time.
13709 * @constructor The parameters to this constructor serve as defaults and are not required.
13710 * @param {Function} fn (optional) The default function to timeout
13711 * @param {Object} scope (optional) The default scope of that timeout
13712 * @param {Array} args (optional) The default Array of arguments
13714 Roo.util.DelayedTask = function(fn, scope, args){
13715 var id = null, d, t;
13717 var call = function(){
13718 var now = new Date().getTime();
13722 fn.apply(scope, args || []);
13726 * Cancels any pending timeout and queues a new one
13727 * @param {Number} delay The milliseconds to delay
13728 * @param {Function} newFn (optional) Overrides function passed to constructor
13729 * @param {Object} newScope (optional) Overrides scope passed to constructor
13730 * @param {Array} newArgs (optional) Overrides args passed to constructor
13732 this.delay = function(delay, newFn, newScope, newArgs){
13733 if(id && delay != d){
13737 t = new Date().getTime();
13739 scope = newScope || scope;
13740 args = newArgs || args;
13742 id = setInterval(call, d);
13747 * Cancel the last queued timeout
13749 this.cancel = function(){
13757 * Ext JS Library 1.1.1
13758 * Copyright(c) 2006-2007, Ext JS, LLC.
13760 * Originally Released Under LGPL - original licence link has changed is not relivant.
13763 * <script type="text/javascript">
13766 * @class Roo.util.TaskRunner
13767 * Manage background tasks - not sure why this is better that setInterval?
13772 Roo.util.TaskRunner = function(interval){
13773 interval = interval || 10;
13774 var tasks = [], removeQueue = [];
13776 var running = false;
13778 var stopThread = function(){
13784 var startThread = function(){
13787 id = setInterval(runTasks, interval);
13791 var removeTask = function(task){
13792 removeQueue.push(task);
13798 var runTasks = function(){
13799 if(removeQueue.length > 0){
13800 for(var i = 0, len = removeQueue.length; i < len; i++){
13801 tasks.remove(removeQueue[i]);
13804 if(tasks.length < 1){
13809 var now = new Date().getTime();
13810 for(var i = 0, len = tasks.length; i < len; ++i){
13812 var itime = now - t.taskRunTime;
13813 if(t.interval <= itime){
13814 var rt = t.run.apply(t.scope || t, t.args || [++t.taskRunCount]);
13815 t.taskRunTime = now;
13816 if(rt === false || t.taskRunCount === t.repeat){
13821 if(t.duration && t.duration <= (now - t.taskStartTime)){
13828 * Queues a new task.
13829 * @param {Object} task
13831 * Task property : interval = how frequent to run.
13832 * Task object should implement
13834 * Task object may implement
13835 * function onStop()
13837 this.start = function(task){
13839 task.taskStartTime = new Date().getTime();
13840 task.taskRunTime = 0;
13841 task.taskRunCount = 0;
13847 * @param {Object} task
13849 this.stop = function(task){
13856 this.stopAll = function(){
13858 for(var i = 0, len = tasks.length; i < len; i++){
13859 if(tasks[i].onStop){
13868 Roo.TaskMgr = new Roo.util.TaskRunner();/*
13870 * Ext JS Library 1.1.1
13871 * Copyright(c) 2006-2007, Ext JS, LLC.
13873 * Originally Released Under LGPL - original licence link has changed is not relivant.
13876 * <script type="text/javascript">
13881 * @class Roo.util.MixedCollection
13882 * @extends Roo.util.Observable
13883 * A Collection class that maintains both numeric indexes and keys and exposes events.
13885 * @param {Boolean} allowFunctions True if the addAll function should add function references to the
13886 * collection (defaults to false)
13887 * @param {Function} keyFn A function that can accept an item of the type(s) stored in this MixedCollection
13888 * and return the key value for that item. This is used when available to look up the key on items that
13889 * were passed without an explicit key parameter to a MixedCollection method. Passing this parameter is
13890 * equivalent to providing an implementation for the {@link #getKey} method.
13892 Roo.util.MixedCollection = function(allowFunctions, keyFn){
13900 * Fires when the collection is cleared.
13905 * Fires when an item is added to the collection.
13906 * @param {Number} index The index at which the item was added.
13907 * @param {Object} o The item added.
13908 * @param {String} key The key associated with the added item.
13913 * Fires when an item is replaced in the collection.
13914 * @param {String} key he key associated with the new added.
13915 * @param {Object} old The item being replaced.
13916 * @param {Object} new The new item.
13921 * Fires when an item is removed from the collection.
13922 * @param {Object} o The item being removed.
13923 * @param {String} key (optional) The key associated with the removed item.
13928 this.allowFunctions = allowFunctions === true;
13930 this.getKey = keyFn;
13932 Roo.util.MixedCollection.superclass.constructor.call(this);
13935 Roo.extend(Roo.util.MixedCollection, Roo.util.Observable, {
13936 allowFunctions : false,
13939 * Adds an item to the collection.
13940 * @param {String} key The key to associate with the item
13941 * @param {Object} o The item to add.
13942 * @return {Object} The item added.
13944 add : function(key, o){
13945 if(arguments.length == 1){
13947 key = this.getKey(o);
13949 if(typeof key == "undefined" || key === null){
13951 this.items.push(o);
13952 this.keys.push(null);
13954 var old = this.map[key];
13956 return this.replace(key, o);
13959 this.items.push(o);
13961 this.keys.push(key);
13963 this.fireEvent("add", this.length-1, o, key);
13968 * MixedCollection has a generic way to fetch keys if you implement getKey.
13971 var mc = new Roo.util.MixedCollection();
13972 mc.add(someEl.dom.id, someEl);
13973 mc.add(otherEl.dom.id, otherEl);
13977 var mc = new Roo.util.MixedCollection();
13978 mc.getKey = function(el){
13984 // or via the constructor
13985 var mc = new Roo.util.MixedCollection(false, function(el){
13991 * @param o {Object} The item for which to find the key.
13992 * @return {Object} The key for the passed item.
13994 getKey : function(o){
13999 * Replaces an item in the collection.
14000 * @param {String} key The key associated with the item to replace, or the item to replace.
14001 * @param o {Object} o (optional) If the first parameter passed was a key, the item to associate with that key.
14002 * @return {Object} The new item.
14004 replace : function(key, o){
14005 if(arguments.length == 1){
14007 key = this.getKey(o);
14009 var old = this.item(key);
14010 if(typeof key == "undefined" || key === null || typeof old == "undefined"){
14011 return this.add(key, o);
14013 var index = this.indexOfKey(key);
14014 this.items[index] = o;
14016 this.fireEvent("replace", key, old, o);
14021 * Adds all elements of an Array or an Object to the collection.
14022 * @param {Object/Array} objs An Object containing properties which will be added to the collection, or
14023 * an Array of values, each of which are added to the collection.
14025 addAll : function(objs){
14026 if(arguments.length > 1 || objs instanceof Array){
14027 var args = arguments.length > 1 ? arguments : objs;
14028 for(var i = 0, len = args.length; i < len; i++){
14032 for(var key in objs){
14033 if(this.allowFunctions || typeof objs[key] != "function"){
14034 this.add(key, objs[key]);
14041 * Executes the specified function once for every item in the collection, passing each
14042 * item as the first and only parameter. returning false from the function will stop the iteration.
14043 * @param {Function} fn The function to execute for each item.
14044 * @param {Object} scope (optional) The scope in which to execute the function.
14046 each : function(fn, scope){
14047 var items = [].concat(this.items); // each safe for removal
14048 for(var i = 0, len = items.length; i < len; i++){
14049 if(fn.call(scope || items[i], items[i], i, len) === false){
14056 * Executes the specified function once for every key in the collection, passing each
14057 * key, and its associated item as the first two parameters.
14058 * @param {Function} fn The function to execute for each item.
14059 * @param {Object} scope (optional) The scope in which to execute the function.
14061 eachKey : function(fn, scope){
14062 for(var i = 0, len = this.keys.length; i < len; i++){
14063 fn.call(scope || window, this.keys[i], this.items[i], i, len);
14068 * Returns the first item in the collection which elicits a true return value from the
14069 * passed selection function.
14070 * @param {Function} fn The selection function to execute for each item.
14071 * @param {Object} scope (optional) The scope in which to execute the function.
14072 * @return {Object} The first item in the collection which returned true from the selection function.
14074 find : function(fn, scope){
14075 for(var i = 0, len = this.items.length; i < len; i++){
14076 if(fn.call(scope || window, this.items[i], this.keys[i])){
14077 return this.items[i];
14084 * Inserts an item at the specified index in the collection.
14085 * @param {Number} index The index to insert the item at.
14086 * @param {String} key The key to associate with the new item, or the item itself.
14087 * @param {Object} o (optional) If the second parameter was a key, the new item.
14088 * @return {Object} The item inserted.
14090 insert : function(index, key, o){
14091 if(arguments.length == 2){
14093 key = this.getKey(o);
14095 if(index >= this.length){
14096 return this.add(key, o);
14099 this.items.splice(index, 0, o);
14100 if(typeof key != "undefined" && key != null){
14103 this.keys.splice(index, 0, key);
14104 this.fireEvent("add", index, o, key);
14109 * Removed an item from the collection.
14110 * @param {Object} o The item to remove.
14111 * @return {Object} The item removed.
14113 remove : function(o){
14114 return this.removeAt(this.indexOf(o));
14118 * Remove an item from a specified index in the collection.
14119 * @param {Number} index The index within the collection of the item to remove.
14121 removeAt : function(index){
14122 if(index < this.length && index >= 0){
14124 var o = this.items[index];
14125 this.items.splice(index, 1);
14126 var key = this.keys[index];
14127 if(typeof key != "undefined"){
14128 delete this.map[key];
14130 this.keys.splice(index, 1);
14131 this.fireEvent("remove", o, key);
14136 * Removed an item associated with the passed key fom the collection.
14137 * @param {String} key The key of the item to remove.
14139 removeKey : function(key){
14140 return this.removeAt(this.indexOfKey(key));
14144 * Returns the number of items in the collection.
14145 * @return {Number} the number of items in the collection.
14147 getCount : function(){
14148 return this.length;
14152 * Returns index within the collection of the passed Object.
14153 * @param {Object} o The item to find the index of.
14154 * @return {Number} index of the item.
14156 indexOf : function(o){
14157 if(!this.items.indexOf){
14158 for(var i = 0, len = this.items.length; i < len; i++){
14159 if(this.items[i] == o) {
14165 return this.items.indexOf(o);
14170 * Returns index within the collection of the passed key.
14171 * @param {String} key The key to find the index of.
14172 * @return {Number} index of the key.
14174 indexOfKey : function(key){
14175 if(!this.keys.indexOf){
14176 for(var i = 0, len = this.keys.length; i < len; i++){
14177 if(this.keys[i] == key) {
14183 return this.keys.indexOf(key);
14188 * Returns the item associated with the passed key OR index. Key has priority over index.
14189 * @param {String/Number} key The key or index of the item.
14190 * @return {Object} The item associated with the passed key.
14192 item : function(key){
14193 if (key === 'length') {
14196 var item = typeof this.map[key] != "undefined" ? this.map[key] : this.items[key];
14197 return typeof item != 'function' || this.allowFunctions ? item : null; // for prototype!
14201 * Returns the item at the specified index.
14202 * @param {Number} index The index of the item.
14205 itemAt : function(index){
14206 return this.items[index];
14210 * Returns the item associated with the passed key.
14211 * @param {String/Number} key The key of the item.
14212 * @return {Object} The item associated with the passed key.
14214 key : function(key){
14215 return this.map[key];
14219 * Returns true if the collection contains the passed Object as an item.
14220 * @param {Object} o The Object to look for in the collection.
14221 * @return {Boolean} True if the collection contains the Object as an item.
14223 contains : function(o){
14224 return this.indexOf(o) != -1;
14228 * Returns true if the collection contains the passed Object as a key.
14229 * @param {String} key The key to look for in the collection.
14230 * @return {Boolean} True if the collection contains the Object as a key.
14232 containsKey : function(key){
14233 return typeof this.map[key] != "undefined";
14237 * Removes all items from the collection.
14239 clear : function(){
14244 this.fireEvent("clear");
14248 * Returns the first item in the collection.
14249 * @return {Object} the first item in the collection..
14251 first : function(){
14252 return this.items[0];
14256 * Returns the last item in the collection.
14257 * @return {Object} the last item in the collection..
14260 return this.items[this.length-1];
14263 _sort : function(property, dir, fn){
14264 var dsc = String(dir).toUpperCase() == "DESC" ? -1 : 1;
14265 fn = fn || function(a, b){
14268 var c = [], k = this.keys, items = this.items;
14269 for(var i = 0, len = items.length; i < len; i++){
14270 c[c.length] = {key: k[i], value: items[i], index: i};
14272 c.sort(function(a, b){
14273 var v = fn(a[property], b[property]) * dsc;
14275 v = (a.index < b.index ? -1 : 1);
14279 for(var i = 0, len = c.length; i < len; i++){
14280 items[i] = c[i].value;
14283 this.fireEvent("sort", this);
14287 * Sorts this collection with the passed comparison function
14288 * @param {String} direction (optional) "ASC" or "DESC"
14289 * @param {Function} fn (optional) comparison function
14291 sort : function(dir, fn){
14292 this._sort("value", dir, fn);
14296 * Sorts this collection by keys
14297 * @param {String} direction (optional) "ASC" or "DESC"
14298 * @param {Function} fn (optional) a comparison function (defaults to case insensitive string)
14300 keySort : function(dir, fn){
14301 this._sort("key", dir, fn || function(a, b){
14302 return String(a).toUpperCase()-String(b).toUpperCase();
14307 * Returns a range of items in this collection
14308 * @param {Number} startIndex (optional) defaults to 0
14309 * @param {Number} endIndex (optional) default to the last item
14310 * @return {Array} An array of items
14312 getRange : function(start, end){
14313 var items = this.items;
14314 if(items.length < 1){
14317 start = start || 0;
14318 end = Math.min(typeof end == "undefined" ? this.length-1 : end, this.length-1);
14321 for(var i = start; i <= end; i++) {
14322 r[r.length] = items[i];
14325 for(var i = start; i >= end; i--) {
14326 r[r.length] = items[i];
14333 * Filter the <i>objects</i> in this collection by a specific property.
14334 * Returns a new collection that has been filtered.
14335 * @param {String} property A property on your objects
14336 * @param {String/RegExp} value Either string that the property values
14337 * should start with or a RegExp to test against the property
14338 * @return {MixedCollection} The new filtered collection
14340 filter : function(property, value){
14341 if(!value.exec){ // not a regex
14342 value = String(value);
14343 if(value.length == 0){
14344 return this.clone();
14346 value = new RegExp("^" + Roo.escapeRe(value), "i");
14348 return this.filterBy(function(o){
14349 return o && value.test(o[property]);
14354 * Filter by a function. * Returns a new collection that has been filtered.
14355 * The passed function will be called with each
14356 * object in the collection. If the function returns true, the value is included
14357 * otherwise it is filtered.
14358 * @param {Function} fn The function to be called, it will receive the args o (the object), k (the key)
14359 * @param {Object} scope (optional) The scope of the function (defaults to this)
14360 * @return {MixedCollection} The new filtered collection
14362 filterBy : function(fn, scope){
14363 var r = new Roo.util.MixedCollection();
14364 r.getKey = this.getKey;
14365 var k = this.keys, it = this.items;
14366 for(var i = 0, len = it.length; i < len; i++){
14367 if(fn.call(scope||this, it[i], k[i])){
14368 r.add(k[i], it[i]);
14375 * Creates a duplicate of this collection
14376 * @return {MixedCollection}
14378 clone : function(){
14379 var r = new Roo.util.MixedCollection();
14380 var k = this.keys, it = this.items;
14381 for(var i = 0, len = it.length; i < len; i++){
14382 r.add(k[i], it[i]);
14384 r.getKey = this.getKey;
14389 * Returns the item associated with the passed key or index.
14391 * @param {String/Number} key The key or index of the item.
14392 * @return {Object} The item associated with the passed key.
14394 Roo.util.MixedCollection.prototype.get = Roo.util.MixedCollection.prototype.item;/*
14396 * Ext JS Library 1.1.1
14397 * Copyright(c) 2006-2007, Ext JS, LLC.
14399 * Originally Released Under LGPL - original licence link has changed is not relivant.
14402 * <script type="text/javascript">
14405 * @class Roo.util.JSON
14406 * Modified version of Douglas Crockford"s json.js that doesn"t
14407 * mess with the Object prototype
14408 * http://www.json.org/js.html
14411 Roo.util.JSON = new (function(){
14412 var useHasOwn = {}.hasOwnProperty ? true : false;
14414 // crashes Safari in some instances
14415 //var validRE = /^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/;
14417 var pad = function(n) {
14418 return n < 10 ? "0" + n : n;
14431 var encodeString = function(s){
14432 if (/["\\\x00-\x1f]/.test(s)) {
14433 return '"' + s.replace(/([\x00-\x1f\\"])/g, function(a, b) {
14438 c = b.charCodeAt();
14440 Math.floor(c / 16).toString(16) +
14441 (c % 16).toString(16);
14444 return '"' + s + '"';
14447 var encodeArray = function(o){
14448 var a = ["["], b, i, l = o.length, v;
14449 for (i = 0; i < l; i += 1) {
14451 switch (typeof v) {
14460 a.push(v === null ? "null" : Roo.util.JSON.encode(v));
14468 var encodeDate = function(o){
14469 return '"' + o.getFullYear() + "-" +
14470 pad(o.getMonth() + 1) + "-" +
14471 pad(o.getDate()) + "T" +
14472 pad(o.getHours()) + ":" +
14473 pad(o.getMinutes()) + ":" +
14474 pad(o.getSeconds()) + '"';
14478 * Encodes an Object, Array or other value
14479 * @param {Mixed} o The variable to encode
14480 * @return {String} The JSON string
14482 this.encode = function(o)
14484 // should this be extended to fully wrap stringify..
14486 if(typeof o == "undefined" || o === null){
14488 }else if(o instanceof Array){
14489 return encodeArray(o);
14490 }else if(o instanceof Date){
14491 return encodeDate(o);
14492 }else if(typeof o == "string"){
14493 return encodeString(o);
14494 }else if(typeof o == "number"){
14495 return isFinite(o) ? String(o) : "null";
14496 }else if(typeof o == "boolean"){
14499 var a = ["{"], b, i, v;
14501 if(!useHasOwn || o.hasOwnProperty(i)) {
14503 switch (typeof v) {
14512 a.push(this.encode(i), ":",
14513 v === null ? "null" : this.encode(v));
14524 * Decodes (parses) a JSON string to an object. If the JSON is invalid, this function throws a SyntaxError.
14525 * @param {String} json The JSON string
14526 * @return {Object} The resulting object
14528 this.decode = function(json){
14530 return /** eval:var:json */ eval("(" + json + ')');
14534 * Shorthand for {@link Roo.util.JSON#encode}
14535 * @member Roo encode
14537 Roo.encode = typeof(JSON) != 'undefined' && JSON.stringify ? JSON.stringify : Roo.util.JSON.encode;
14539 * Shorthand for {@link Roo.util.JSON#decode}
14540 * @member Roo decode
14542 Roo.decode = typeof(JSON) != 'undefined' && JSON.parse ? JSON.parse : Roo.util.JSON.decode;
14545 * Ext JS Library 1.1.1
14546 * Copyright(c) 2006-2007, Ext JS, LLC.
14548 * Originally Released Under LGPL - original licence link has changed is not relivant.
14551 * <script type="text/javascript">
14555 * @class Roo.util.Format
14556 * Reusable data formatting functions
14559 Roo.util.Format = function(){
14560 var trimRe = /^\s+|\s+$/g;
14563 * Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length
14564 * @param {String} value The string to truncate
14565 * @param {Number} length The maximum length to allow before truncating
14566 * @return {String} The converted text
14568 ellipsis : function(value, len){
14569 if(value && value.length > len){
14570 return value.substr(0, len-3)+"...";
14576 * Checks a reference and converts it to empty string if it is undefined
14577 * @param {Mixed} value Reference to check
14578 * @return {Mixed} Empty string if converted, otherwise the original value
14580 undef : function(value){
14581 return typeof value != "undefined" ? value : "";
14585 * Convert certain characters (&, <, >, and ') to their HTML character equivalents for literal display in web pages.
14586 * @param {String} value The string to encode
14587 * @return {String} The encoded text
14589 htmlEncode : function(value){
14590 return !value ? value : String(value).replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, """);
14594 * Convert certain characters (&, <, >, and ') from their HTML character equivalents.
14595 * @param {String} value The string to decode
14596 * @return {String} The decoded text
14598 htmlDecode : function(value){
14599 return !value ? value : String(value).replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, '"');
14603 * Trims any whitespace from either side of a string
14604 * @param {String} value The text to trim
14605 * @return {String} The trimmed text
14607 trim : function(value){
14608 return String(value).replace(trimRe, "");
14612 * Returns a substring from within an original string
14613 * @param {String} value The original text
14614 * @param {Number} start The start index of the substring
14615 * @param {Number} length The length of the substring
14616 * @return {String} The substring
14618 substr : function(value, start, length){
14619 return String(value).substr(start, length);
14623 * Converts a string to all lower case letters
14624 * @param {String} value The text to convert
14625 * @return {String} The converted text
14627 lowercase : function(value){
14628 return String(value).toLowerCase();
14632 * Converts a string to all upper case letters
14633 * @param {String} value The text to convert
14634 * @return {String} The converted text
14636 uppercase : function(value){
14637 return String(value).toUpperCase();
14641 * Converts the first character only of a string to upper case
14642 * @param {String} value The text to convert
14643 * @return {String} The converted text
14645 capitalize : function(value){
14646 return !value ? value : value.charAt(0).toUpperCase() + value.substr(1).toLowerCase();
14650 call : function(value, fn){
14651 if(arguments.length > 2){
14652 var args = Array.prototype.slice.call(arguments, 2);
14653 args.unshift(value);
14655 return /** eval:var:value */ eval(fn).apply(window, args);
14657 /** eval:var:value */
14658 return /** eval:var:value */ eval(fn).call(window, value);
14664 * safer version of Math.toFixed..??/
14665 * @param {Number/String} value The numeric value to format
14666 * @param {Number/String} value Decimal places
14667 * @return {String} The formatted currency string
14669 toFixed : function(v, n)
14671 // why not use to fixed - precision is buggered???
14673 return Math.round(v-0);
14675 var fact = Math.pow(10,n+1);
14676 v = (Math.round((v-0)*fact))/fact;
14677 var z = (''+fact).substring(2);
14678 if (v == Math.floor(v)) {
14679 return Math.floor(v) + '.' + z;
14682 // now just padd decimals..
14683 var ps = String(v).split('.');
14684 var fd = (ps[1] + z);
14685 var r = fd.substring(0,n);
14686 var rm = fd.substring(n);
14688 return ps[0] + '.' + r;
14690 r*=1; // turn it into a number;
14692 if (String(r).length != n) {
14695 r = String(r).substring(1); // chop the end off.
14698 return ps[0] + '.' + r;
14703 * Format a number as US currency
14704 * @param {Number/String} value The numeric value to format
14705 * @return {String} The formatted currency string
14707 usMoney : function(v){
14708 return '$' + Roo.util.Format.number(v);
14713 * eventually this should probably emulate php's number_format
14714 * @param {Number/String} value The numeric value to format
14715 * @param {Number} decimals number of decimal places
14716 * @param {String} delimiter for thousands (default comma)
14717 * @return {String} The formatted currency string
14719 number : function(v, decimals, thousandsDelimiter)
14721 // multiply and round.
14722 decimals = typeof(decimals) == 'undefined' ? 2 : decimals;
14723 thousandsDelimiter = typeof(thousandsDelimiter) == 'undefined' ? ',' : thousandsDelimiter;
14725 var mul = Math.pow(10, decimals);
14726 var zero = String(mul).substring(1);
14727 v = (Math.round((v-0)*mul))/mul;
14729 // if it's '0' number.. then
14731 //v = (v == Math.floor(v)) ? v + "." + zero : ((v*10 == Math.floor(v*10)) ? v + "0" : v);
14733 var ps = v.split('.');
14736 var r = /(\d+)(\d{3})/;
14739 if(thousandsDelimiter.length != 0) {
14740 whole = whole.replace(/\B(?=(\d{3})+(?!\d))/g, thousandsDelimiter );
14745 (decimals ? ('.'+ ps[1] + zero.substring(ps[1].length)) : '') :
14746 // does not have decimals
14747 (decimals ? ('.' + zero) : '');
14750 return whole + sub ;
14754 * Parse a value into a formatted date using the specified format pattern.
14755 * @param {Mixed} value The value to format
14756 * @param {String} format (optional) Any valid date format string (defaults to 'm/d/Y')
14757 * @return {String} The formatted date string
14759 date : function(v, format){
14763 if(!(v instanceof Date)){
14764 v = new Date(Date.parse(v));
14766 return v.dateFormat(format || Roo.util.Format.defaults.date);
14770 * Returns a date rendering function that can be reused to apply a date format multiple times efficiently
14771 * @param {String} format Any valid date format string
14772 * @return {Function} The date formatting function
14774 dateRenderer : function(format){
14775 return function(v){
14776 return Roo.util.Format.date(v, format);
14781 stripTagsRE : /<\/?[^>]+>/gi,
14784 * Strips all HTML tags
14785 * @param {Mixed} value The text from which to strip tags
14786 * @return {String} The stripped text
14788 stripTags : function(v){
14789 return !v ? v : String(v).replace(this.stripTagsRE, "");
14793 * Size in Mb,Gb etc.
14794 * @param {Number} value The number to be formated
14795 * @param {number} decimals how many decimal places
14796 * @return {String} the formated string
14798 size : function(value, decimals)
14800 var sizes = ['b', 'k', 'M', 'G', 'T'];
14804 var i = parseInt(Math.floor(Math.log(value) / Math.log(1024)));
14805 return Roo.util.Format.number(value/ Math.pow(1024, i) ,decimals) + sizes[i];
14812 Roo.util.Format.defaults = {
14816 * Ext JS Library 1.1.1
14817 * Copyright(c) 2006-2007, Ext JS, LLC.
14819 * Originally Released Under LGPL - original licence link has changed is not relivant.
14822 * <script type="text/javascript">
14829 * @class Roo.MasterTemplate
14830 * @extends Roo.Template
14831 * Provides a template that can have child templates. The syntax is:
14833 var t = new Roo.MasterTemplate(
14834 '<select name="{name}">',
14835 '<tpl name="options"><option value="{value:trim}">{text:ellipsis(10)}</option></tpl>',
14838 t.add('options', {value: 'foo', text: 'bar'});
14839 // or you can add multiple child elements in one shot
14840 t.addAll('options', [
14841 {value: 'foo', text: 'bar'},
14842 {value: 'foo2', text: 'bar2'},
14843 {value: 'foo3', text: 'bar3'}
14845 // then append, applying the master template values
14846 t.append('my-form', {name: 'my-select'});
14848 * A name attribute for the child template is not required if you have only one child
14849 * template or you want to refer to them by index.
14851 Roo.MasterTemplate = function(){
14852 Roo.MasterTemplate.superclass.constructor.apply(this, arguments);
14853 this.originalHtml = this.html;
14855 var m, re = this.subTemplateRe;
14858 while(m = re.exec(this.html)){
14859 var name = m[1], content = m[2];
14864 tpl : new Roo.Template(content)
14867 st[name] = st[subIndex];
14869 st[subIndex].tpl.compile();
14870 st[subIndex].tpl.call = this.call.createDelegate(this);
14873 this.subCount = subIndex;
14876 Roo.extend(Roo.MasterTemplate, Roo.Template, {
14878 * The regular expression used to match sub templates
14882 subTemplateRe : /<tpl(?:\sname="([\w-]+)")?>((?:.|\n)*?)<\/tpl>/gi,
14885 * Applies the passed values to a child template.
14886 * @param {String/Number} name (optional) The name or index of the child template
14887 * @param {Array/Object} values The values to be applied to the template
14888 * @return {MasterTemplate} this
14890 add : function(name, values){
14891 if(arguments.length == 1){
14892 values = arguments[0];
14895 var s = this.subs[name];
14896 s.buffer[s.buffer.length] = s.tpl.apply(values);
14901 * Applies all the passed values to a child template.
14902 * @param {String/Number} name (optional) The name or index of the child template
14903 * @param {Array} values The values to be applied to the template, this should be an array of objects.
14904 * @param {Boolean} reset (optional) True to reset the template first
14905 * @return {MasterTemplate} this
14907 fill : function(name, values, reset){
14909 if(a.length == 1 || (a.length == 2 && typeof a[1] == "boolean")){
14917 for(var i = 0, len = values.length; i < len; i++){
14918 this.add(name, values[i]);
14924 * Resets the template for reuse
14925 * @return {MasterTemplate} this
14927 reset : function(){
14929 for(var i = 0; i < this.subCount; i++){
14935 applyTemplate : function(values){
14937 var replaceIndex = -1;
14938 this.html = this.originalHtml.replace(this.subTemplateRe, function(m, name){
14939 return s[++replaceIndex].buffer.join("");
14941 return Roo.MasterTemplate.superclass.applyTemplate.call(this, values);
14944 apply : function(){
14945 return this.applyTemplate.apply(this, arguments);
14948 compile : function(){return this;}
14952 * Alias for fill().
14955 Roo.MasterTemplate.prototype.addAll = Roo.MasterTemplate.prototype.fill;
14957 * Creates a template from the passed element's value (display:none textarea, preferred) or innerHTML. e.g.
14958 * var tpl = Roo.MasterTemplate.from('element-id');
14959 * @param {String/HTMLElement} el
14960 * @param {Object} config
14963 Roo.MasterTemplate.from = function(el, config){
14964 el = Roo.getDom(el);
14965 return new Roo.MasterTemplate(el.value || el.innerHTML, config || '');
14968 * Ext JS Library 1.1.1
14969 * Copyright(c) 2006-2007, Ext JS, LLC.
14971 * Originally Released Under LGPL - original licence link has changed is not relivant.
14974 * <script type="text/javascript">
14979 * @class Roo.util.CSS
14980 * Utility class for manipulating CSS rules
14984 Roo.util.CSS = function(){
14986 var doc = document;
14988 var camelRe = /(-[a-z])/gi;
14989 var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); };
14993 * Very simple dynamic creation of stylesheets from a text blob of rules. The text will wrapped in a style
14994 * tag and appended to the HEAD of the document.
14995 * @param {String|Object} cssText The text containing the css rules
14996 * @param {String} id An id to add to the stylesheet for later removal
14997 * @return {StyleSheet}
14999 createStyleSheet : function(cssText, id){
15001 var head = doc.getElementsByTagName("head")[0];
15002 var nrules = doc.createElement("style");
15003 nrules.setAttribute("type", "text/css");
15005 nrules.setAttribute("id", id);
15007 if (typeof(cssText) != 'string') {
15008 // support object maps..
15009 // not sure if this a good idea..
15010 // perhaps it should be merged with the general css handling
15011 // and handle js style props.
15012 var cssTextNew = [];
15013 for(var n in cssText) {
15015 for(var k in cssText[n]) {
15016 citems.push( k + ' : ' +cssText[n][k] + ';' );
15018 cssTextNew.push( n + ' { ' + citems.join(' ') + '} ');
15021 cssText = cssTextNew.join("\n");
15027 head.appendChild(nrules);
15028 ss = nrules.styleSheet;
15029 ss.cssText = cssText;
15032 nrules.appendChild(doc.createTextNode(cssText));
15034 nrules.cssText = cssText;
15036 head.appendChild(nrules);
15037 ss = nrules.styleSheet ? nrules.styleSheet : (nrules.sheet || doc.styleSheets[doc.styleSheets.length-1]);
15039 this.cacheStyleSheet(ss);
15044 * Removes a style or link tag by id
15045 * @param {String} id The id of the tag
15047 removeStyleSheet : function(id){
15048 var existing = doc.getElementById(id);
15050 existing.parentNode.removeChild(existing);
15055 * Dynamically swaps an existing stylesheet reference for a new one
15056 * @param {String} id The id of an existing link tag to remove
15057 * @param {String} url The href of the new stylesheet to include
15059 swapStyleSheet : function(id, url){
15060 this.removeStyleSheet(id);
15061 var ss = doc.createElement("link");
15062 ss.setAttribute("rel", "stylesheet");
15063 ss.setAttribute("type", "text/css");
15064 ss.setAttribute("id", id);
15065 ss.setAttribute("href", url);
15066 doc.getElementsByTagName("head")[0].appendChild(ss);
15070 * Refresh the rule cache if you have dynamically added stylesheets
15071 * @return {Object} An object (hash) of rules indexed by selector
15073 refreshCache : function(){
15074 return this.getRules(true);
15078 cacheStyleSheet : function(stylesheet){
15082 try{// try catch for cross domain access issue
15083 var ssRules = stylesheet.cssRules || stylesheet.rules;
15084 for(var j = ssRules.length-1; j >= 0; --j){
15085 rules[ssRules[j].selectorText] = ssRules[j];
15091 * Gets all css rules for the document
15092 * @param {Boolean} refreshCache true to refresh the internal cache
15093 * @return {Object} An object (hash) of rules indexed by selector
15095 getRules : function(refreshCache){
15096 if(rules == null || refreshCache){
15098 var ds = doc.styleSheets;
15099 for(var i =0, len = ds.length; i < len; i++){
15101 this.cacheStyleSheet(ds[i]);
15109 * Gets an an individual CSS rule by selector(s)
15110 * @param {String/Array} selector The CSS selector or an array of selectors to try. The first selector that is found is returned.
15111 * @param {Boolean} refreshCache true to refresh the internal cache if you have recently updated any rules or added styles dynamically
15112 * @return {CSSRule} The CSS rule or null if one is not found
15114 getRule : function(selector, refreshCache){
15115 var rs = this.getRules(refreshCache);
15116 if(!(selector instanceof Array)){
15117 return rs[selector];
15119 for(var i = 0; i < selector.length; i++){
15120 if(rs[selector[i]]){
15121 return rs[selector[i]];
15129 * Updates a rule property
15130 * @param {String/Array} selector If it's an array it tries each selector until it finds one. Stops immediately once one is found.
15131 * @param {String} property The css property
15132 * @param {String} value The new value for the property
15133 * @return {Boolean} true If a rule was found and updated
15135 updateRule : function(selector, property, value){
15136 if(!(selector instanceof Array)){
15137 var rule = this.getRule(selector);
15139 rule.style[property.replace(camelRe, camelFn)] = value;
15143 for(var i = 0; i < selector.length; i++){
15144 if(this.updateRule(selector[i], property, value)){
15154 * Ext JS Library 1.1.1
15155 * Copyright(c) 2006-2007, Ext JS, LLC.
15157 * Originally Released Under LGPL - original licence link has changed is not relivant.
15160 * <script type="text/javascript">
15166 * @class Roo.util.ClickRepeater
15167 * @extends Roo.util.Observable
15169 * A wrapper class which can be applied to any element. Fires a "click" event while the
15170 * mouse is pressed. The interval between firings may be specified in the config but
15171 * defaults to 10 milliseconds.
15173 * Optionally, a CSS class may be applied to the element during the time it is pressed.
15175 * @cfg {String/HTMLElement/Element} el The element to act as a button.
15176 * @cfg {Number} delay The initial delay before the repeating event begins firing.
15177 * Similar to an autorepeat key delay.
15178 * @cfg {Number} interval The interval between firings of the "click" event. Default 10 ms.
15179 * @cfg {String} pressClass A CSS class name to be applied to the element while pressed.
15180 * @cfg {Boolean} accelerate True if autorepeating should start slowly and accelerate.
15181 * "interval" and "delay" are ignored. "immediate" is honored.
15182 * @cfg {Boolean} preventDefault True to prevent the default click event
15183 * @cfg {Boolean} stopDefault True to stop the default click event
15186 * 2007-02-02 jvs Original code contributed by Nige "Animal" White
15187 * 2007-02-02 jvs Renamed to ClickRepeater
15188 * 2007-02-03 jvs Modifications for FF Mac and Safari
15191 * @param {String/HTMLElement/Element} el The element to listen on
15192 * @param {Object} config
15194 Roo.util.ClickRepeater = function(el, config)
15196 this.el = Roo.get(el);
15197 this.el.unselectable();
15199 Roo.apply(this, config);
15204 * Fires when the mouse button is depressed.
15205 * @param {Roo.util.ClickRepeater} this
15207 "mousedown" : true,
15210 * Fires on a specified interval during the time the element is pressed.
15211 * @param {Roo.util.ClickRepeater} this
15216 * Fires when the mouse key is released.
15217 * @param {Roo.util.ClickRepeater} this
15222 this.el.on("mousedown", this.handleMouseDown, this);
15223 if(this.preventDefault || this.stopDefault){
15224 this.el.on("click", function(e){
15225 if(this.preventDefault){
15226 e.preventDefault();
15228 if(this.stopDefault){
15234 // allow inline handler
15236 this.on("click", this.handler, this.scope || this);
15239 Roo.util.ClickRepeater.superclass.constructor.call(this);
15242 Roo.extend(Roo.util.ClickRepeater, Roo.util.Observable, {
15245 preventDefault : true,
15246 stopDefault : false,
15250 handleMouseDown : function(){
15251 clearTimeout(this.timer);
15253 if(this.pressClass){
15254 this.el.addClass(this.pressClass);
15256 this.mousedownTime = new Date();
15258 Roo.get(document).on("mouseup", this.handleMouseUp, this);
15259 this.el.on("mouseout", this.handleMouseOut, this);
15261 this.fireEvent("mousedown", this);
15262 this.fireEvent("click", this);
15264 this.timer = this.click.defer(this.delay || this.interval, this);
15268 click : function(){
15269 this.fireEvent("click", this);
15270 this.timer = this.click.defer(this.getInterval(), this);
15274 getInterval: function(){
15275 if(!this.accelerate){
15276 return this.interval;
15278 var pressTime = this.mousedownTime.getElapsed();
15279 if(pressTime < 500){
15281 }else if(pressTime < 1700){
15283 }else if(pressTime < 2600){
15285 }else if(pressTime < 3500){
15287 }else if(pressTime < 4400){
15289 }else if(pressTime < 5300){
15291 }else if(pressTime < 6200){
15299 handleMouseOut : function(){
15300 clearTimeout(this.timer);
15301 if(this.pressClass){
15302 this.el.removeClass(this.pressClass);
15304 this.el.on("mouseover", this.handleMouseReturn, this);
15308 handleMouseReturn : function(){
15309 this.el.un("mouseover", this.handleMouseReturn);
15310 if(this.pressClass){
15311 this.el.addClass(this.pressClass);
15317 handleMouseUp : function(){
15318 clearTimeout(this.timer);
15319 this.el.un("mouseover", this.handleMouseReturn);
15320 this.el.un("mouseout", this.handleMouseOut);
15321 Roo.get(document).un("mouseup", this.handleMouseUp);
15322 this.el.removeClass(this.pressClass);
15323 this.fireEvent("mouseup", this);
15326 * @class Roo.util.Clipboard
15332 Roo.util.Clipboard = {
15334 * Writes a string to the clipboard - using the Clipboard API if https, otherwise using text area.
15335 * @param {String} text to copy to clipboard
15337 write : function(text) {
15338 // navigator clipboard api needs a secure context (https)
15339 if (navigator.clipboard && window.isSecureContext) {
15340 // navigator clipboard api method'
15341 navigator.clipboard.writeText(text);
15344 // text area method
15345 var ta = document.createElement("textarea");
15347 // make the textarea out of viewport
15348 ta.style.position = "fixed";
15349 ta.style.left = "-999999px";
15350 ta.style.top = "-999999px";
15351 document.body.appendChild(ta);
15354 document.execCommand('copy');
15364 * Ext JS Library 1.1.1
15365 * Copyright(c) 2006-2007, Ext JS, LLC.
15367 * Originally Released Under LGPL - original licence link has changed is not relivant.
15370 * <script type="text/javascript">
15375 * @class Roo.KeyNav
15376 * <p>Provides a convenient wrapper for normalized keyboard navigation. KeyNav allows you to bind
15377 * navigation keys to function calls that will get called when the keys are pressed, providing an easy
15378 * way to implement custom navigation schemes for any UI component.</p>
15379 * <p>The following are all of the possible keys that can be implemented: enter, left, right, up, down, tab, esc,
15380 * pageUp, pageDown, del, home, end. Usage:</p>
15382 var nav = new Roo.KeyNav("my-element", {
15383 "left" : function(e){
15384 this.moveLeft(e.ctrlKey);
15386 "right" : function(e){
15387 this.moveRight(e.ctrlKey);
15389 "enter" : function(e){
15396 * @param {String/HTMLElement/Roo.Element} el The element to bind to
15397 * @param {Object} config The config
15399 Roo.KeyNav = function(el, config){
15400 this.el = Roo.get(el);
15401 Roo.apply(this, config);
15402 if(!this.disabled){
15403 this.disabled = true;
15408 Roo.KeyNav.prototype = {
15410 * @cfg {Boolean} disabled
15411 * True to disable this KeyNav instance (defaults to false)
15415 * @cfg {String} defaultEventAction
15416 * The method to call on the {@link Roo.EventObject} after this KeyNav intercepts a key. Valid values are
15417 * {@link Roo.EventObject#stopEvent}, {@link Roo.EventObject#preventDefault} and
15418 * {@link Roo.EventObject#stopPropagation} (defaults to 'stopEvent')
15420 defaultEventAction: "stopEvent",
15422 * @cfg {Boolean} forceKeyDown
15423 * Handle the keydown event instead of keypress (defaults to false). KeyNav automatically does this for IE since
15424 * IE does not propagate special keys on keypress, but setting this to true will force other browsers to also
15425 * handle keydown instead of keypress.
15427 forceKeyDown : false,
15430 prepareEvent : function(e){
15431 var k = e.getKey();
15432 var h = this.keyToHandler[k];
15433 //if(h && this[h]){
15434 // e.stopPropagation();
15436 if(Roo.isSafari && h && k >= 37 && k <= 40){
15442 relay : function(e){
15443 var k = e.getKey();
15444 var h = this.keyToHandler[k];
15446 if(this.doRelay(e, this[h], h) !== true){
15447 e[this.defaultEventAction]();
15453 doRelay : function(e, h, hname){
15454 return h.call(this.scope || this, e);
15457 // possible handlers
15471 // quick lookup hash
15488 * Enable this KeyNav
15490 enable: function(){
15492 // ie won't do special keys on keypress, no one else will repeat keys with keydown
15493 // the EventObject will normalize Safari automatically
15494 if(this.forceKeyDown || Roo.isIE || Roo.isAir){
15495 this.el.on("keydown", this.relay, this);
15497 this.el.on("keydown", this.prepareEvent, this);
15498 this.el.on("keypress", this.relay, this);
15500 this.disabled = false;
15505 * Disable this KeyNav
15507 disable: function(){
15508 if(!this.disabled){
15509 if(this.forceKeyDown || Roo.isIE || Roo.isAir){
15510 this.el.un("keydown", this.relay);
15512 this.el.un("keydown", this.prepareEvent);
15513 this.el.un("keypress", this.relay);
15515 this.disabled = true;
15520 * Ext JS Library 1.1.1
15521 * Copyright(c) 2006-2007, Ext JS, LLC.
15523 * Originally Released Under LGPL - original licence link has changed is not relivant.
15526 * <script type="text/javascript">
15531 * @class Roo.KeyMap
15532 * Handles mapping keys to actions for an element. One key map can be used for multiple actions.
15533 * The constructor accepts the same config object as defined by {@link #addBinding}.
15534 * If you bind a callback function to a KeyMap, anytime the KeyMap handles an expected key
15535 * combination it will call the function with this signature (if the match is a multi-key
15536 * combination the callback will still be called only once): (String key, Roo.EventObject e)
15537 * A KeyMap can also handle a string representation of keys.<br />
15540 // map one key by key code
15541 var map = new Roo.KeyMap("my-element", {
15542 key: 13, // or Roo.EventObject.ENTER
15547 // map multiple keys to one action by string
15548 var map = new Roo.KeyMap("my-element", {
15554 // map multiple keys to multiple actions by strings and array of codes
15555 var map = new Roo.KeyMap("my-element", [
15558 fn: function(){ alert("Return was pressed"); }
15561 fn: function(){ alert('a, b or c was pressed'); }
15566 fn: function(){ alert('Control + shift + tab was pressed.'); }
15570 * <b>Note: A KeyMap starts enabled</b>
15572 * @param {String/HTMLElement/Roo.Element} el The element to bind to
15573 * @param {Object} config The config (see {@link #addBinding})
15574 * @param {String} eventName (optional) The event to bind to (defaults to "keydown")
15576 Roo.KeyMap = function(el, config, eventName){
15577 this.el = Roo.get(el);
15578 this.eventName = eventName || "keydown";
15579 this.bindings = [];
15581 this.addBinding(config);
15586 Roo.KeyMap.prototype = {
15588 * True to stop the event from bubbling and prevent the default browser action if the
15589 * key was handled by the KeyMap (defaults to false)
15595 * Add a new binding to this KeyMap. The following config object properties are supported:
15597 Property Type Description
15598 ---------- --------------- ----------------------------------------------------------------------
15599 key String/Array A single keycode or an array of keycodes to handle
15600 shift Boolean True to handle key only when shift is pressed (defaults to false)
15601 ctrl Boolean True to handle key only when ctrl is pressed (defaults to false)
15602 alt Boolean True to handle key only when alt is pressed (defaults to false)
15603 fn Function The function to call when KeyMap finds the expected key combination
15604 scope Object The scope of the callback function
15610 var map = new Roo.KeyMap(document, {
15611 key: Roo.EventObject.ENTER,
15616 //Add a new binding to the existing KeyMap later
15624 * @param {Object/Array} config A single KeyMap config or an array of configs
15626 addBinding : function(config){
15627 if(config instanceof Array){
15628 for(var i = 0, len = config.length; i < len; i++){
15629 this.addBinding(config[i]);
15633 var keyCode = config.key,
15634 shift = config.shift,
15635 ctrl = config.ctrl,
15638 scope = config.scope;
15639 if(typeof keyCode == "string"){
15641 var keyString = keyCode.toUpperCase();
15642 for(var j = 0, len = keyString.length; j < len; j++){
15643 ks.push(keyString.charCodeAt(j));
15647 var keyArray = keyCode instanceof Array;
15648 var handler = function(e){
15649 if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) && (!alt || e.altKey)){
15650 var k = e.getKey();
15652 for(var i = 0, len = keyCode.length; i < len; i++){
15653 if(keyCode[i] == k){
15654 if(this.stopEvent){
15657 fn.call(scope || window, k, e);
15663 if(this.stopEvent){
15666 fn.call(scope || window, k, e);
15671 this.bindings.push(handler);
15675 * Shorthand for adding a single key listener
15676 * @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the
15677 * following options:
15678 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
15679 * @param {Function} fn The function to call
15680 * @param {Object} scope (optional) The scope of the function
15682 on : function(key, fn, scope){
15683 var keyCode, shift, ctrl, alt;
15684 if(typeof key == "object" && !(key instanceof Array)){
15703 handleKeyDown : function(e){
15704 if(this.enabled){ //just in case
15705 var b = this.bindings;
15706 for(var i = 0, len = b.length; i < len; i++){
15707 b[i].call(this, e);
15713 * Returns true if this KeyMap is enabled
15714 * @return {Boolean}
15716 isEnabled : function(){
15717 return this.enabled;
15721 * Enables this KeyMap
15723 enable: function(){
15725 this.el.on(this.eventName, this.handleKeyDown, this);
15726 this.enabled = true;
15731 * Disable this KeyMap
15733 disable: function(){
15735 this.el.removeListener(this.eventName, this.handleKeyDown, this);
15736 this.enabled = false;
15741 * Ext JS Library 1.1.1
15742 * Copyright(c) 2006-2007, Ext JS, LLC.
15744 * Originally Released Under LGPL - original licence link has changed is not relivant.
15747 * <script type="text/javascript">
15752 * @class Roo.util.TextMetrics
15753 * Provides precise pixel measurements for blocks of text so that you can determine exactly how high and
15754 * wide, in pixels, a given block of text will be.
15757 Roo.util.TextMetrics = function(){
15761 * Measures the size of the specified text
15762 * @param {String/HTMLElement} el The element, dom node or id from which to copy existing CSS styles
15763 * that can affect the size of the rendered text
15764 * @param {String} text The text to measure
15765 * @param {Number} fixedWidth (optional) If the text will be multiline, you have to set a fixed width
15766 * in order to accurately measure the text height
15767 * @return {Object} An object containing the text's size {width: (width), height: (height)}
15769 measure : function(el, text, fixedWidth){
15771 shared = Roo.util.TextMetrics.Instance(el, fixedWidth);
15774 shared.setFixedWidth(fixedWidth || 'auto');
15775 return shared.getSize(text);
15779 * Return a unique TextMetrics instance that can be bound directly to an element and reused. This reduces
15780 * the overhead of multiple calls to initialize the style properties on each measurement.
15781 * @param {String/HTMLElement} el The element, dom node or id that the instance will be bound to
15782 * @param {Number} fixedWidth (optional) If the text will be multiline, you have to set a fixed width
15783 * in order to accurately measure the text height
15784 * @return {Roo.util.TextMetrics.Instance} instance The new instance
15786 createInstance : function(el, fixedWidth){
15787 return Roo.util.TextMetrics.Instance(el, fixedWidth);
15793 * @class Roo.util.TextMetrics.Instance
15794 * Instance of TextMetrics Calcuation
15796 * Create a new TextMetrics Instance
15797 * @param {Object} bindto
15798 * @param {Boolean} fixedWidth
15801 Roo.util.TextMetrics.Instance = function(bindTo, fixedWidth)
15803 var ml = new Roo.Element(document.createElement('div'));
15804 document.body.appendChild(ml.dom);
15805 ml.position('absolute');
15806 ml.setLeftTop(-1000, -1000);
15810 ml.setWidth(fixedWidth);
15815 * Returns the size of the specified text based on the internal element's style and width properties
15816 * @param {String} text The text to measure
15817 * @return {Object} An object containing the text's size {width: (width), height: (height)}
15819 getSize : function(text){
15821 var s = ml.getSize();
15827 * Binds this TextMetrics instance to an element from which to copy existing CSS styles
15828 * that can affect the size of the rendered text
15829 * @param {String/HTMLElement} el The element, dom node or id
15831 bind : function(el){
15833 Roo.fly(el).getStyles('font-size','font-style', 'font-weight', 'font-family','line-height')
15838 * Sets a fixed width on the internal measurement element. If the text will be multiline, you have
15839 * to set a fixed width in order to accurately measure the text height.
15840 * @param {Number} width The width to set on the element
15842 setFixedWidth : function(width){
15843 ml.setWidth(width);
15847 * Returns the measured width of the specified text
15848 * @param {String} text The text to measure
15849 * @return {Number} width The width in pixels
15851 getWidth : function(text){
15852 ml.dom.style.width = 'auto';
15853 return this.getSize(text).width;
15857 * Returns the measured height of the specified text. For multiline text, be sure to call
15858 * {@link #setFixedWidth} if necessary.
15859 * @param {String} text The text to measure
15860 * @return {Number} height The height in pixels
15862 getHeight : function(text){
15863 return this.getSize(text).height;
15867 instance.bind(bindTo);
15872 // backwards compat
15873 Roo.Element.measureText = Roo.util.TextMetrics.measure;/*
15875 * Ext JS Library 1.1.1
15876 * Copyright(c) 2006-2007, Ext JS, LLC.
15878 * Originally Released Under LGPL - original licence link has changed is not relivant.
15881 * <script type="text/javascript">
15885 * @class Roo.state.Provider
15886 * Abstract base class for state provider implementations. This class provides methods
15887 * for encoding and decoding <b>typed</b> variables including dates and defines the
15888 * Provider interface.
15890 Roo.state.Provider = function(){
15892 * @event statechange
15893 * Fires when a state change occurs.
15894 * @param {Provider} this This state provider
15895 * @param {String} key The state key which was changed
15896 * @param {String} value The encoded value for the state
15899 "statechange": true
15902 Roo.state.Provider.superclass.constructor.call(this);
15904 Roo.extend(Roo.state.Provider, Roo.util.Observable, {
15906 * Returns the current value for a key
15907 * @param {String} name The key name
15908 * @param {Mixed} defaultValue A default value to return if the key's value is not found
15909 * @return {Mixed} The state data
15911 get : function(name, defaultValue){
15912 return typeof this.state[name] == "undefined" ?
15913 defaultValue : this.state[name];
15917 * Clears a value from the state
15918 * @param {String} name The key name
15920 clear : function(name){
15921 delete this.state[name];
15922 this.fireEvent("statechange", this, name, null);
15926 * Sets the value for a key
15927 * @param {String} name The key name
15928 * @param {Mixed} value The value to set
15930 set : function(name, value){
15931 this.state[name] = value;
15932 this.fireEvent("statechange", this, name, value);
15936 * Decodes a string previously encoded with {@link #encodeValue}.
15937 * @param {String} value The value to decode
15938 * @return {Mixed} The decoded value
15940 decodeValue : function(cookie){
15941 var re = /^(a|n|d|b|s|o)\:(.*)$/;
15942 var matches = re.exec(unescape(cookie));
15943 if(!matches || !matches[1]) {
15944 return; // non state cookie
15946 var type = matches[1];
15947 var v = matches[2];
15950 return parseFloat(v);
15952 return new Date(Date.parse(v));
15957 var values = v.split("^");
15958 for(var i = 0, len = values.length; i < len; i++){
15959 all.push(this.decodeValue(values[i]));
15964 var values = v.split("^");
15965 for(var i = 0, len = values.length; i < len; i++){
15966 var kv = values[i].split("=");
15967 all[kv[0]] = this.decodeValue(kv[1]);
15976 * Encodes a value including type information. Decode with {@link #decodeValue}.
15977 * @param {Mixed} value The value to encode
15978 * @return {String} The encoded value
15980 encodeValue : function(v){
15982 if(typeof v == "number"){
15984 }else if(typeof v == "boolean"){
15985 enc = "b:" + (v ? "1" : "0");
15986 }else if(v instanceof Date){
15987 enc = "d:" + v.toGMTString();
15988 }else if(v instanceof Array){
15990 for(var i = 0, len = v.length; i < len; i++){
15991 flat += this.encodeValue(v[i]);
15997 }else if(typeof v == "object"){
16000 if(typeof v[key] != "function"){
16001 flat += key + "=" + this.encodeValue(v[key]) + "^";
16004 enc = "o:" + flat.substring(0, flat.length-1);
16008 return escape(enc);
16014 * Ext JS Library 1.1.1
16015 * Copyright(c) 2006-2007, Ext JS, LLC.
16017 * Originally Released Under LGPL - original licence link has changed is not relivant.
16020 * <script type="text/javascript">
16023 * @class Roo.state.Manager
16024 * This is the global state manager. By default all components that are "state aware" check this class
16025 * for state information if you don't pass them a custom state provider. In order for this class
16026 * to be useful, it must be initialized with a provider when your application initializes.
16028 // in your initialization function
16030 Roo.state.Manager.setProvider(new Roo.state.CookieProvider());
16032 // supposed you have a {@link Roo.BorderLayout}
16033 var layout = new Roo.BorderLayout(...);
16034 layout.restoreState();
16035 // or a {Roo.BasicDialog}
16036 var dialog = new Roo.BasicDialog(...);
16037 dialog.restoreState();
16041 Roo.state.Manager = function(){
16042 var provider = new Roo.state.Provider();
16046 * Configures the default state provider for your application
16047 * @param {Provider} stateProvider The state provider to set
16049 setProvider : function(stateProvider){
16050 provider = stateProvider;
16054 * Returns the current value for a key
16055 * @param {String} name The key name
16056 * @param {Mixed} defaultValue The default value to return if the key lookup does not match
16057 * @return {Mixed} The state data
16059 get : function(key, defaultValue){
16060 return provider.get(key, defaultValue);
16064 * Sets the value for a key
16065 * @param {String} name The key name
16066 * @param {Mixed} value The state data
16068 set : function(key, value){
16069 provider.set(key, value);
16073 * Clears a value from the state
16074 * @param {String} name The key name
16076 clear : function(key){
16077 provider.clear(key);
16081 * Gets the currently configured state provider
16082 * @return {Provider} The state provider
16084 getProvider : function(){
16091 * Ext JS Library 1.1.1
16092 * Copyright(c) 2006-2007, Ext JS, LLC.
16094 * Originally Released Under LGPL - original licence link has changed is not relivant.
16097 * <script type="text/javascript">
16100 * @class Roo.state.CookieProvider
16101 * @extends Roo.state.Provider
16102 * The default Provider implementation which saves state via cookies.
16105 var cp = new Roo.state.CookieProvider({
16107 expires: new Date(new Date().getTime()+(1000*60*60*24*30)); //30 days
16108 domain: "roojs.com"
16110 Roo.state.Manager.setProvider(cp);
16112 * @cfg {String} path The path for which the cookie is active (defaults to root '/' which makes it active for all pages in the site)
16113 * @cfg {Date} expires The cookie expiration date (defaults to 7 days from now)
16114 * @cfg {String} domain The domain to save the cookie for. Note that you cannot specify a different domain than
16115 * your page is on, but you can specify a sub-domain, or simply the domain itself like 'roojs.com' to include
16116 * all sub-domains if you need to access cookies across different sub-domains (defaults to null which uses the same
16117 * domain the page is running on including the 'www' like 'www.roojs.com')
16118 * @cfg {Boolean} secure True if the site is using SSL (defaults to false)
16120 * Create a new CookieProvider
16121 * @param {Object} config The configuration object
16123 Roo.state.CookieProvider = function(config){
16124 Roo.state.CookieProvider.superclass.constructor.call(this);
16126 this.expires = new Date(new Date().getTime()+(1000*60*60*24*7)); //7 days
16127 this.domain = null;
16128 this.secure = false;
16129 Roo.apply(this, config);
16130 this.state = this.readCookies();
16133 Roo.extend(Roo.state.CookieProvider, Roo.state.Provider, {
16135 set : function(name, value){
16136 if(typeof value == "undefined" || value === null){
16140 this.setCookie(name, value);
16141 Roo.state.CookieProvider.superclass.set.call(this, name, value);
16145 clear : function(name){
16146 this.clearCookie(name);
16147 Roo.state.CookieProvider.superclass.clear.call(this, name);
16151 readCookies : function(){
16153 var c = document.cookie + ";";
16154 var re = /\s?(.*?)=(.*?);/g;
16156 while((matches = re.exec(c)) != null){
16157 var name = matches[1];
16158 var value = matches[2];
16159 if(name && name.substring(0,3) == "ys-"){
16160 cookies[name.substr(3)] = this.decodeValue(value);
16167 setCookie : function(name, value){
16168 document.cookie = "ys-"+ name + "=" + this.encodeValue(value) +
16169 ((this.expires == null) ? "" : ("; expires=" + this.expires.toGMTString())) +
16170 ((this.path == null) ? "" : ("; path=" + this.path)) +
16171 ((this.domain == null) ? "" : ("; domain=" + this.domain)) +
16172 ((this.secure == true) ? "; secure" : "");
16176 clearCookie : function(name){
16177 document.cookie = "ys-" + name + "=null; expires=Thu, 01-Jan-70 00:00:01 GMT" +
16178 ((this.path == null) ? "" : ("; path=" + this.path)) +
16179 ((this.domain == null) ? "" : ("; domain=" + this.domain)) +
16180 ((this.secure == true) ? "; secure" : "");
16184 * Ext JS Library 1.1.1
16185 * Copyright(c) 2006-2007, Ext JS, LLC.
16187 * Originally Released Under LGPL - original licence link has changed is not relivant.
16190 * <script type="text/javascript">
16195 * @class Roo.ComponentMgr
16196 * Provides a common registry of all components on a page so that they can be easily accessed by component id (see {@link Roo.getCmp}).
16199 Roo.ComponentMgr = function(){
16200 var all = new Roo.util.MixedCollection();
16204 * Registers a component.
16205 * @param {Roo.Component} c The component
16207 register : function(c){
16212 * Unregisters a component.
16213 * @param {Roo.Component} c The component
16215 unregister : function(c){
16220 * Returns a component by id
16221 * @param {String} id The component id
16223 get : function(id){
16224 return all.get(id);
16228 * Registers a function that will be called when a specified component is added to ComponentMgr
16229 * @param {String} id The component id
16230 * @param {Funtction} fn The callback function
16231 * @param {Object} scope The scope of the callback
16233 onAvailable : function(id, fn, scope){
16234 all.on("add", function(index, o){
16236 fn.call(scope || o, o);
16237 all.un("add", fn, scope);
16244 * Ext JS Library 1.1.1
16245 * Copyright(c) 2006-2007, Ext JS, LLC.
16247 * Originally Released Under LGPL - original licence link has changed is not relivant.
16250 * <script type="text/javascript">
16254 * @class Roo.Component
16255 * @extends Roo.util.Observable
16256 * Base class for all major Roo components. All subclasses of Component can automatically participate in the standard
16257 * Roo component lifecycle of creation, rendering and destruction. They also have automatic support for basic hide/show
16258 * and enable/disable behavior. Component allows any subclass to be lazy-rendered into any {@link Roo.Container} and
16259 * to be automatically registered with the {@link Roo.ComponentMgr} so that it can be referenced at any time via {@link Roo.getCmp}.
16260 * All visual components (widgets) that require rendering into a layout should subclass Component.
16262 * @param {Roo.Element/String/Object} config The configuration options. If an element is passed, it is set as the internal
16263 * 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
16264 * and is used as the component id. Otherwise, it is assumed to be a standard config object and is applied to the component.
16266 Roo.Component = function(config){
16267 config = config || {};
16268 if(config.tagName || config.dom || typeof config == "string"){ // element object
16269 config = {el: config, id: config.id || config};
16271 this.initialConfig = config;
16273 Roo.apply(this, config);
16277 * Fires after the component is disabled.
16278 * @param {Roo.Component} this
16283 * Fires after the component is enabled.
16284 * @param {Roo.Component} this
16288 * @event beforeshow
16289 * Fires before the component is shown. Return false to stop the show.
16290 * @param {Roo.Component} this
16295 * Fires after the component is shown.
16296 * @param {Roo.Component} this
16300 * @event beforehide
16301 * Fires before the component is hidden. Return false to stop the hide.
16302 * @param {Roo.Component} this
16307 * Fires after the component is hidden.
16308 * @param {Roo.Component} this
16312 * @event beforerender
16313 * Fires before the component is rendered. Return false to stop the render.
16314 * @param {Roo.Component} this
16316 beforerender : true,
16319 * Fires after the component is rendered.
16320 * @param {Roo.Component} this
16324 * @event beforedestroy
16325 * Fires before the component is destroyed. Return false to stop the destroy.
16326 * @param {Roo.Component} this
16328 beforedestroy : true,
16331 * Fires after the component is destroyed.
16332 * @param {Roo.Component} this
16337 this.id = "roo-comp-" + (++Roo.Component.AUTO_ID);
16339 Roo.ComponentMgr.register(this);
16340 Roo.Component.superclass.constructor.call(this);
16341 this.initComponent();
16342 if(this.renderTo){ // not supported by all components yet. use at your own risk!
16343 this.render(this.renderTo);
16344 delete this.renderTo;
16349 Roo.Component.AUTO_ID = 1000;
16351 Roo.extend(Roo.Component, Roo.util.Observable, {
16353 * @scope Roo.Component.prototype
16355 * true if this component is hidden. Read-only.
16360 * true if this component is disabled. Read-only.
16365 * true if this component has been rendered. Read-only.
16369 /** @cfg {String} disableClass
16370 * CSS class added to the component when it is disabled (defaults to "x-item-disabled").
16372 disabledClass : "x-item-disabled",
16373 /** @cfg {Boolean} allowDomMove
16374 * Whether the component can move the Dom node when rendering (defaults to true).
16376 allowDomMove : true,
16377 /** @cfg {String} hideMode (display|visibility)
16378 * How this component should hidden. Supported values are
16379 * "visibility" (css visibility), "offsets" (negative offset position) and
16380 * "display" (css display) - defaults to "display".
16382 hideMode: 'display',
16385 ctype : "Roo.Component",
16388 * @cfg {String} actionMode
16389 * which property holds the element that used for hide() / show() / disable() / enable()
16390 * default is 'el' for forms you probably want to set this to fieldEl
16395 getActionEl : function(){
16396 return this[this.actionMode];
16399 initComponent : Roo.emptyFn,
16401 * If this is a lazy rendering component, render it to its container element.
16402 * @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.
16404 render : function(container, position){
16410 if(this.fireEvent("beforerender", this) === false){
16414 if(!container && this.el){
16415 this.el = Roo.get(this.el);
16416 container = this.el.dom.parentNode;
16417 this.allowDomMove = false;
16419 this.container = Roo.get(container);
16420 this.rendered = true;
16421 if(position !== undefined){
16422 if(typeof position == 'number'){
16423 position = this.container.dom.childNodes[position];
16425 position = Roo.getDom(position);
16428 this.onRender(this.container, position || null);
16430 this.el.addClass(this.cls);
16434 this.el.applyStyles(this.style);
16437 this.fireEvent("render", this);
16438 this.afterRender(this.container);
16451 // default function is not really useful
16452 onRender : function(ct, position){
16454 this.el = Roo.get(this.el);
16455 if(this.allowDomMove !== false){
16456 ct.dom.insertBefore(this.el.dom, position);
16462 getAutoCreate : function(){
16463 var cfg = typeof this.autoCreate == "object" ?
16464 this.autoCreate : Roo.apply({}, this.defaultAutoCreate);
16465 if(this.id && !cfg.id){
16472 afterRender : Roo.emptyFn,
16475 * Destroys this component by purging any event listeners, removing the component's element from the DOM,
16476 * removing the component from its {@link Roo.Container} (if applicable) and unregistering it from {@link Roo.ComponentMgr}.
16478 destroy : function(){
16479 if(this.fireEvent("beforedestroy", this) !== false){
16480 this.purgeListeners();
16481 this.beforeDestroy();
16483 this.el.removeAllListeners();
16485 if(this.actionMode == "container"){
16486 this.container.remove();
16490 Roo.ComponentMgr.unregister(this);
16491 this.fireEvent("destroy", this);
16496 beforeDestroy : function(){
16501 onDestroy : function(){
16506 * Returns the underlying {@link Roo.Element}.
16507 * @return {Roo.Element} The element
16509 getEl : function(){
16514 * Returns the id of this component.
16517 getId : function(){
16522 * Try to focus this component.
16523 * @param {Boolean} selectText True to also select the text in this component (if applicable)
16524 * @return {Roo.Component} this
16526 focus : function(selectText){
16529 if(selectText === true){
16530 this.el.dom.select();
16545 * Disable this component.
16546 * @return {Roo.Component} this
16548 disable : function(){
16552 this.disabled = true;
16553 this.fireEvent("disable", this);
16558 onDisable : function(){
16559 this.getActionEl().addClass(this.disabledClass);
16560 this.el.dom.disabled = true;
16564 * Enable this component.
16565 * @return {Roo.Component} this
16567 enable : function(){
16571 this.disabled = false;
16572 this.fireEvent("enable", this);
16577 onEnable : function(){
16578 this.getActionEl().removeClass(this.disabledClass);
16579 this.el.dom.disabled = false;
16583 * Convenience function for setting disabled/enabled by boolean.
16584 * @param {Boolean} disabled
16586 setDisabled : function(disabled){
16587 this[disabled ? "disable" : "enable"]();
16591 * Show this component.
16592 * @return {Roo.Component} this
16595 if(this.fireEvent("beforeshow", this) !== false){
16596 this.hidden = false;
16600 this.fireEvent("show", this);
16606 onShow : function(){
16607 var ae = this.getActionEl();
16608 if(this.hideMode == 'visibility'){
16609 ae.dom.style.visibility = "visible";
16610 }else if(this.hideMode == 'offsets'){
16611 ae.removeClass('x-hidden');
16613 ae.dom.style.display = "";
16618 * Hide this component.
16619 * @return {Roo.Component} this
16622 if(this.fireEvent("beforehide", this) !== false){
16623 this.hidden = true;
16627 this.fireEvent("hide", this);
16633 onHide : function(){
16634 var ae = this.getActionEl();
16635 if(this.hideMode == 'visibility'){
16636 ae.dom.style.visibility = "hidden";
16637 }else if(this.hideMode == 'offsets'){
16638 ae.addClass('x-hidden');
16640 ae.dom.style.display = "none";
16645 * Convenience function to hide or show this component by boolean.
16646 * @param {Boolean} visible True to show, false to hide
16647 * @return {Roo.Component} this
16649 setVisible: function(visible){
16659 * Returns true if this component is visible.
16661 isVisible : function(){
16662 return this.getActionEl().isVisible();
16665 cloneConfig : function(overrides){
16666 overrides = overrides || {};
16667 var id = overrides.id || Roo.id();
16668 var cfg = Roo.applyIf(overrides, this.initialConfig);
16669 cfg.id = id; // prevent dup id
16670 return new this.constructor(cfg);
16674 * Ext JS Library 1.1.1
16675 * Copyright(c) 2006-2007, Ext JS, LLC.
16677 * Originally Released Under LGPL - original licence link has changed is not relivant.
16680 * <script type="text/javascript">
16684 * @class Roo.BoxComponent
16685 * @extends Roo.Component
16686 * Base class for any visual {@link Roo.Component} that uses a box container. BoxComponent provides automatic box
16687 * model adjustments for sizing and positioning and will work correctly withnin the Component rendering model. All
16688 * container classes should subclass BoxComponent so that they will work consistently when nested within other Roo
16689 * layout containers.
16691 * @param {Roo.Element/String/Object} config The configuration options.
16693 Roo.BoxComponent = function(config){
16694 Roo.Component.call(this, config);
16698 * Fires after the component is resized.
16699 * @param {Roo.Component} this
16700 * @param {Number} adjWidth The box-adjusted width that was set
16701 * @param {Number} adjHeight The box-adjusted height that was set
16702 * @param {Number} rawWidth The width that was originally specified
16703 * @param {Number} rawHeight The height that was originally specified
16708 * Fires after the component is moved.
16709 * @param {Roo.Component} this
16710 * @param {Number} x The new x position
16711 * @param {Number} y The new y position
16717 Roo.extend(Roo.BoxComponent, Roo.Component, {
16718 // private, set in afterRender to signify that the component has been rendered
16720 // private, used to defer height settings to subclasses
16721 deferHeight: false,
16722 /** @cfg {Number} width
16723 * width (optional) size of component
16725 /** @cfg {Number} height
16726 * height (optional) size of component
16730 * Sets the width and height of the component. This method fires the resize event. This method can accept
16731 * either width and height as separate numeric arguments, or you can pass a size object like {width:10, height:20}.
16732 * @param {Number/Object} width The new width to set, or a size object in the format {width, height}
16733 * @param {Number} height The new height to set (not required if a size object is passed as the first arg)
16734 * @return {Roo.BoxComponent} this
16736 setSize : function(w, h){
16737 // support for standard size objects
16738 if(typeof w == 'object'){
16743 if(!this.boxReady){
16749 // prevent recalcs when not needed
16750 if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
16753 this.lastSize = {width: w, height: h};
16755 var adj = this.adjustSize(w, h);
16756 var aw = adj.width, ah = adj.height;
16757 if(aw !== undefined || ah !== undefined){ // this code is nasty but performs better with floaters
16758 var rz = this.getResizeEl();
16759 if(!this.deferHeight && aw !== undefined && ah !== undefined){
16760 rz.setSize(aw, ah);
16761 }else if(!this.deferHeight && ah !== undefined){
16763 }else if(aw !== undefined){
16766 this.onResize(aw, ah, w, h);
16767 this.fireEvent('resize', this, aw, ah, w, h);
16773 * Gets the current size of the component's underlying element.
16774 * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
16776 getSize : function(){
16777 return this.el.getSize();
16781 * Gets the current XY position of the component's underlying element.
16782 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
16783 * @return {Array} The XY position of the element (e.g., [100, 200])
16785 getPosition : function(local){
16786 if(local === true){
16787 return [this.el.getLeft(true), this.el.getTop(true)];
16789 return this.xy || this.el.getXY();
16793 * Gets the current box measurements of the component's underlying element.
16794 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
16795 * @returns {Object} box An object in the format {x, y, width, height}
16797 getBox : function(local){
16798 var s = this.el.getSize();
16800 s.x = this.el.getLeft(true);
16801 s.y = this.el.getTop(true);
16803 var xy = this.xy || this.el.getXY();
16811 * Sets the current box measurements of the component's underlying element.
16812 * @param {Object} box An object in the format {x, y, width, height}
16813 * @returns {Roo.BoxComponent} this
16815 updateBox : function(box){
16816 this.setSize(box.width, box.height);
16817 this.setPagePosition(box.x, box.y);
16822 getResizeEl : function(){
16823 return this.resizeEl || this.el;
16827 getPositionEl : function(){
16828 return this.positionEl || this.el;
16832 * Sets the left and top of the component. To set the page XY position instead, use {@link #setPagePosition}.
16833 * This method fires the move event.
16834 * @param {Number} left The new left
16835 * @param {Number} top The new top
16836 * @returns {Roo.BoxComponent} this
16838 setPosition : function(x, y){
16841 if(!this.boxReady){
16844 var adj = this.adjustPosition(x, y);
16845 var ax = adj.x, ay = adj.y;
16847 var el = this.getPositionEl();
16848 if(ax !== undefined || ay !== undefined){
16849 if(ax !== undefined && ay !== undefined){
16850 el.setLeftTop(ax, ay);
16851 }else if(ax !== undefined){
16853 }else if(ay !== undefined){
16856 this.onPosition(ax, ay);
16857 this.fireEvent('move', this, ax, ay);
16863 * Sets the page XY position of the component. To set the left and top instead, use {@link #setPosition}.
16864 * This method fires the move event.
16865 * @param {Number} x The new x position
16866 * @param {Number} y The new y position
16867 * @returns {Roo.BoxComponent} this
16869 setPagePosition : function(x, y){
16872 if(!this.boxReady){
16875 if(x === undefined || y === undefined){ // cannot translate undefined points
16878 var p = this.el.translatePoints(x, y);
16879 this.setPosition(p.left, p.top);
16884 onRender : function(ct, position){
16885 Roo.BoxComponent.superclass.onRender.call(this, ct, position);
16887 this.resizeEl = Roo.get(this.resizeEl);
16889 if(this.positionEl){
16890 this.positionEl = Roo.get(this.positionEl);
16895 afterRender : function(){
16896 Roo.BoxComponent.superclass.afterRender.call(this);
16897 this.boxReady = true;
16898 this.setSize(this.width, this.height);
16899 if(this.x || this.y){
16900 this.setPosition(this.x, this.y);
16902 if(this.pageX || this.pageY){
16903 this.setPagePosition(this.pageX, this.pageY);
16908 * Force the component's size to recalculate based on the underlying element's current height and width.
16909 * @returns {Roo.BoxComponent} this
16911 syncSize : function(){
16912 delete this.lastSize;
16913 this.setSize(this.el.getWidth(), this.el.getHeight());
16918 * Called after the component is resized, this method is empty by default but can be implemented by any
16919 * subclass that needs to perform custom logic after a resize occurs.
16920 * @param {Number} adjWidth The box-adjusted width that was set
16921 * @param {Number} adjHeight The box-adjusted height that was set
16922 * @param {Number} rawWidth The width that was originally specified
16923 * @param {Number} rawHeight The height that was originally specified
16925 onResize : function(adjWidth, adjHeight, rawWidth, rawHeight){
16930 * Called after the component is moved, this method is empty by default but can be implemented by any
16931 * subclass that needs to perform custom logic after a move occurs.
16932 * @param {Number} x The new x position
16933 * @param {Number} y The new y position
16935 onPosition : function(x, y){
16940 adjustSize : function(w, h){
16941 if(this.autoWidth){
16944 if(this.autoHeight){
16947 return {width : w, height: h};
16951 adjustPosition : function(x, y){
16952 return {x : x, y: y};
16956 * Ext JS Library 1.1.1
16957 * Copyright(c) 2006-2007, Ext JS, LLC.
16959 * Originally Released Under LGPL - original licence link has changed is not relivant.
16962 * <script type="text/javascript">
16967 * @extends Roo.Element
16968 * An extended {@link Roo.Element} object that supports a shadow and shim, constrain to viewport and
16969 * automatic maintaining of shadow/shim positions.
16970 * @cfg {Boolean} shim False to disable the iframe shim in browsers which need one (defaults to true)
16971 * @cfg {String/Boolean} shadow True to create a shadow element with default class "x-layer-shadow", or
16972 * you can pass a string with a CSS class name. False turns off the shadow.
16973 * @cfg {Object} dh DomHelper object config to create element with (defaults to {tag: "div", cls: "x-layer"}).
16974 * @cfg {Boolean} constrain False to disable constrain to viewport (defaults to true)
16975 * @cfg {String} cls CSS class to add to the element
16976 * @cfg {Number} zindex Starting z-index (defaults to 11000)
16977 * @cfg {Number} shadowOffset Number of pixels to offset the shadow (defaults to 3)
16979 * @param {Object} config An object with config options.
16980 * @param {String/HTMLElement} existingEl (optional) Uses an existing DOM element. If the element is not found it creates it.
16983 Roo.Layer = function(config, existingEl){
16984 config = config || {};
16985 var dh = Roo.DomHelper;
16986 var cp = config.parentEl, pel = cp ? Roo.getDom(cp) : document.body;
16988 this.dom = Roo.getDom(existingEl);
16991 var o = config.dh || {tag: "div", cls: "x-layer"};
16992 this.dom = dh.append(pel, o);
16995 this.addClass(config.cls);
16997 this.constrain = config.constrain !== false;
16998 this.visibilityMode = Roo.Element.VISIBILITY;
17000 this.id = this.dom.id = config.id;
17002 this.id = Roo.id(this.dom);
17004 this.zindex = config.zindex || this.getZIndex();
17005 this.position("absolute", this.zindex);
17007 this.shadowOffset = config.shadowOffset || 4;
17008 this.shadow = new Roo.Shadow({
17009 offset : this.shadowOffset,
17010 mode : config.shadow
17013 this.shadowOffset = 0;
17015 this.useShim = config.shim !== false && Roo.useShims;
17016 this.useDisplay = config.useDisplay;
17020 var supr = Roo.Element.prototype;
17022 // shims are shared among layer to keep from having 100 iframes
17025 Roo.extend(Roo.Layer, Roo.Element, {
17027 getZIndex : function(){
17028 return this.zindex || parseInt(this.getStyle("z-index"), 10) || 11000;
17031 getShim : function(){
17038 var shim = shims.shift();
17040 shim = this.createShim();
17041 shim.enableDisplayMode('block');
17042 shim.dom.style.display = 'none';
17043 shim.dom.style.visibility = 'visible';
17045 var pn = this.dom.parentNode;
17046 if(shim.dom.parentNode != pn){
17047 pn.insertBefore(shim.dom, this.dom);
17049 shim.setStyle('z-index', this.getZIndex()-2);
17054 hideShim : function(){
17056 this.shim.setDisplayed(false);
17057 shims.push(this.shim);
17062 disableShadow : function(){
17064 this.shadowDisabled = true;
17065 this.shadow.hide();
17066 this.lastShadowOffset = this.shadowOffset;
17067 this.shadowOffset = 0;
17071 enableShadow : function(show){
17073 this.shadowDisabled = false;
17074 this.shadowOffset = this.lastShadowOffset;
17075 delete this.lastShadowOffset;
17083 // this code can execute repeatedly in milliseconds (i.e. during a drag) so
17084 // code size was sacrificed for effeciency (e.g. no getBox/setBox, no XY calls)
17085 sync : function(doShow){
17086 var sw = this.shadow;
17087 if(!this.updating && this.isVisible() && (sw || this.useShim)){
17088 var sh = this.getShim();
17090 var w = this.getWidth(),
17091 h = this.getHeight();
17093 var l = this.getLeft(true),
17094 t = this.getTop(true);
17096 if(sw && !this.shadowDisabled){
17097 if(doShow && !sw.isVisible()){
17100 sw.realign(l, t, w, h);
17106 // fit the shim behind the shadow, so it is shimmed too
17107 var a = sw.adjusts, s = sh.dom.style;
17108 s.left = (Math.min(l, l+a.l))+"px";
17109 s.top = (Math.min(t, t+a.t))+"px";
17110 s.width = (w+a.w)+"px";
17111 s.height = (h+a.h)+"px";
17118 sh.setLeftTop(l, t);
17125 destroy : function(){
17128 this.shadow.hide();
17130 this.removeAllListeners();
17131 var pn = this.dom.parentNode;
17133 pn.removeChild(this.dom);
17135 Roo.Element.uncache(this.id);
17138 remove : function(){
17143 beginUpdate : function(){
17144 this.updating = true;
17148 endUpdate : function(){
17149 this.updating = false;
17154 hideUnders : function(negOffset){
17156 this.shadow.hide();
17162 constrainXY : function(){
17163 if(this.constrain){
17164 var vw = Roo.lib.Dom.getViewWidth(),
17165 vh = Roo.lib.Dom.getViewHeight();
17166 var s = Roo.get(document).getScroll();
17168 var xy = this.getXY();
17169 var x = xy[0], y = xy[1];
17170 var w = this.dom.offsetWidth+this.shadowOffset, h = this.dom.offsetHeight+this.shadowOffset;
17171 // only move it if it needs it
17173 // first validate right/bottom
17174 if((x + w) > vw+s.left){
17175 x = vw - w - this.shadowOffset;
17178 if((y + h) > vh+s.top){
17179 y = vh - h - this.shadowOffset;
17182 // then make sure top/left isn't negative
17193 var ay = this.avoidY;
17194 if(y <= ay && (y+h) >= ay){
17200 supr.setXY.call(this, xy);
17206 isVisible : function(){
17207 return this.visible;
17211 showAction : function(){
17212 this.visible = true; // track visibility to prevent getStyle calls
17213 if(this.useDisplay === true){
17214 this.setDisplayed("");
17215 }else if(this.lastXY){
17216 supr.setXY.call(this, this.lastXY);
17217 }else if(this.lastLT){
17218 supr.setLeftTop.call(this, this.lastLT[0], this.lastLT[1]);
17223 hideAction : function(){
17224 this.visible = false;
17225 if(this.useDisplay === true){
17226 this.setDisplayed(false);
17228 this.setLeftTop(-10000,-10000);
17232 // overridden Element method
17233 setVisible : function(v, a, d, c, e){
17238 var cb = function(){
17243 }.createDelegate(this);
17244 supr.setVisible.call(this, true, true, d, cb, e);
17247 this.hideUnders(true);
17256 }.createDelegate(this);
17258 supr.setVisible.call(this, v, a, d, cb, e);
17267 storeXY : function(xy){
17268 delete this.lastLT;
17272 storeLeftTop : function(left, top){
17273 delete this.lastXY;
17274 this.lastLT = [left, top];
17278 beforeFx : function(){
17279 this.beforeAction();
17280 return Roo.Layer.superclass.beforeFx.apply(this, arguments);
17284 afterFx : function(){
17285 Roo.Layer.superclass.afterFx.apply(this, arguments);
17286 this.sync(this.isVisible());
17290 beforeAction : function(){
17291 if(!this.updating && this.shadow){
17292 this.shadow.hide();
17296 // overridden Element method
17297 setLeft : function(left){
17298 this.storeLeftTop(left, this.getTop(true));
17299 supr.setLeft.apply(this, arguments);
17303 setTop : function(top){
17304 this.storeLeftTop(this.getLeft(true), top);
17305 supr.setTop.apply(this, arguments);
17309 setLeftTop : function(left, top){
17310 this.storeLeftTop(left, top);
17311 supr.setLeftTop.apply(this, arguments);
17315 setXY : function(xy, a, d, c, e){
17317 this.beforeAction();
17319 var cb = this.createCB(c);
17320 supr.setXY.call(this, xy, a, d, cb, e);
17327 createCB : function(c){
17338 // overridden Element method
17339 setX : function(x, a, d, c, e){
17340 this.setXY([x, this.getY()], a, d, c, e);
17343 // overridden Element method
17344 setY : function(y, a, d, c, e){
17345 this.setXY([this.getX(), y], a, d, c, e);
17348 // overridden Element method
17349 setSize : function(w, h, a, d, c, e){
17350 this.beforeAction();
17351 var cb = this.createCB(c);
17352 supr.setSize.call(this, w, h, a, d, cb, e);
17358 // overridden Element method
17359 setWidth : function(w, a, d, c, e){
17360 this.beforeAction();
17361 var cb = this.createCB(c);
17362 supr.setWidth.call(this, w, a, d, cb, e);
17368 // overridden Element method
17369 setHeight : function(h, a, d, c, e){
17370 this.beforeAction();
17371 var cb = this.createCB(c);
17372 supr.setHeight.call(this, h, a, d, cb, e);
17378 // overridden Element method
17379 setBounds : function(x, y, w, h, a, d, c, e){
17380 this.beforeAction();
17381 var cb = this.createCB(c);
17383 this.storeXY([x, y]);
17384 supr.setXY.call(this, [x, y]);
17385 supr.setSize.call(this, w, h, a, d, cb, e);
17388 supr.setBounds.call(this, x, y, w, h, a, d, cb, e);
17394 * Sets the z-index of this layer and adjusts any shadow and shim z-indexes. The layer z-index is automatically
17395 * incremented by two more than the value passed in so that it always shows above any shadow or shim (the shadow
17396 * element, if any, will be assigned z-index + 1, and the shim element, if any, will be assigned the unmodified z-index).
17397 * @param {Number} zindex The new z-index to set
17398 * @return {this} The Layer
17400 setZIndex : function(zindex){
17401 this.zindex = zindex;
17402 this.setStyle("z-index", zindex + 2);
17404 this.shadow.setZIndex(zindex + 1);
17407 this.shim.setStyle("z-index", zindex);
17412 * Original code for Roojs - LGPL
17413 * <script type="text/javascript">
17417 * @class Roo.XComponent
17418 * A delayed Element creator...
17419 * Or a way to group chunks of interface together.
17420 * technically this is a wrapper around a tree of Roo elements (which defines a 'module'),
17421 * used in conjunction with XComponent.build() it will create an instance of each element,
17422 * then call addxtype() to build the User interface.
17424 * Mypart.xyx = new Roo.XComponent({
17426 parent : 'Mypart.xyz', // empty == document.element.!!
17430 disabled : function() {}
17432 tree : function() { // return an tree of xtype declared components
17436 xtype : 'NestedLayoutPanel',
17443 * It can be used to build a big heiracy, with parent etc.
17444 * or you can just use this to render a single compoent to a dom element
17445 * MYPART.render(Roo.Element | String(id) | dom_element )
17452 * Roo is designed primarily as a single page application, so the UI build for a standard interface will
17453 * expect a single 'TOP' level module normally indicated by the 'parent' of the XComponent definition being defined as false.
17455 * Each sub module is expected to have a parent pointing to the class name of it's parent module.
17457 * When the top level is false, a 'Roo.BorderLayout' is created and the element is flagged as 'topModule'
17458 * - if mulitple topModules exist, the last one is defined as the top module.
17462 * When the top level or multiple modules are to embedded into a existing HTML page,
17463 * the parent element can container '#id' of the element where the module will be drawn.
17467 * Unlike classic Roo, the bootstrap tends not to be used as a single page.
17468 * it relies more on a include mechanism, where sub modules are included into an outer page.
17469 * This is normally managed by the builder tools using Roo.apply( options, Included.Sub.Module )
17471 * Bootstrap Roo Included elements
17473 * Our builder application needs the ability to preview these sub compoennts. They will normally have parent=false set,
17474 * hence confusing the component builder as it thinks there are multiple top level elements.
17476 * String Over-ride & Translations
17478 * Our builder application writes all the strings as _strings and _named_strings. This is to enable the translation of elements,
17479 * and also the 'overlaying of string values - needed when different versions of the same application with different text content
17480 * are needed. @see Roo.XComponent.overlayString
17484 * @extends Roo.util.Observable
17486 * @param cfg {Object} configuration of component
17489 Roo.XComponent = function(cfg) {
17490 Roo.apply(this, cfg);
17494 * Fires when this the componnt is built
17495 * @param {Roo.XComponent} c the component
17500 this.region = this.region || 'center'; // default..
17501 Roo.XComponent.register(this);
17502 this.modules = false;
17503 this.el = false; // where the layout goes..
17507 Roo.extend(Roo.XComponent, Roo.util.Observable, {
17510 * The created element (with Roo.factory())
17511 * @type {Roo.Layout}
17517 * for BC - use el in new code
17518 * @type {Roo.Layout}
17524 * for BC - use el in new code
17525 * @type {Roo.Layout}
17530 * @cfg {Function|boolean} disabled
17531 * If this module is disabled by some rule, return true from the funtion
17536 * @cfg {String} parent
17537 * Name of parent element which it get xtype added to..
17542 * @cfg {String} order
17543 * Used to set the order in which elements are created (usefull for multiple tabs)
17548 * @cfg {String} name
17549 * String to display while loading.
17553 * @cfg {String} region
17554 * Region to render component to (defaults to center)
17559 * @cfg {Array} items
17560 * A single item array - the first element is the root of the tree..
17561 * It's done this way to stay compatible with the Xtype system...
17567 * The method that retuns the tree of parts that make up this compoennt
17574 * render element to dom or tree
17575 * @param {Roo.Element|String|DomElement} optional render to if parent is not set.
17578 render : function(el)
17582 var hp = this.parent ? 1 : 0;
17583 Roo.debug && Roo.log(this);
17585 var tree = this._tree ? this._tree() : this.tree();
17588 if (!el && typeof(this.parent) == 'string' && this.parent.substring(0,1) == '#') {
17589 // if parent is a '#.....' string, then let's use that..
17590 var ename = this.parent.substr(1);
17591 this.parent = false;
17592 Roo.debug && Roo.log(ename);
17594 case 'bootstrap-body':
17595 if (typeof(tree.el) != 'undefined' && tree.el == document.body) {
17596 // this is the BorderLayout standard?
17597 this.parent = { el : true };
17600 if (["Nest", "Content", "Grid", "Tree"].indexOf(tree.xtype) > -1) {
17601 // need to insert stuff...
17603 el : new Roo.bootstrap.layout.Border({
17604 el : document.body,
17610 tabPosition: 'top',
17611 //resizeTabs: true,
17612 alwaysShowTabs: true,
17622 if (typeof(Roo.bootstrap.Body) != 'undefined' ) {
17623 this.parent = { el : new Roo.bootstrap.Body() };
17624 Roo.debug && Roo.log("setting el to doc body");
17627 throw "Container is bootstrap body, but Roo.bootstrap.Body is not defined";
17631 this.parent = { el : true};
17634 el = Roo.get(ename);
17635 if (typeof(Roo.bootstrap) != 'undefined' && tree['|xns'] == 'Roo.bootstrap') {
17636 this.parent = { el : true};
17643 if (!el && !this.parent) {
17644 Roo.debug && Roo.log("Warning - element can not be found :#" + ename );
17649 Roo.debug && Roo.log("EL:");
17650 Roo.debug && Roo.log(el);
17651 Roo.debug && Roo.log("this.parent.el:");
17652 Roo.debug && Roo.log(this.parent.el);
17655 // altertive root elements ??? - we need a better way to indicate these.
17656 var is_alt = Roo.XComponent.is_alt ||
17657 (typeof(tree.el) != 'undefined' && tree.el == document.body) ||
17658 (typeof(Roo.bootstrap) != 'undefined' && tree.xns == Roo.bootstrap) ||
17659 (typeof(Roo.mailer) != 'undefined' && tree.xns == Roo.mailer) ;
17663 if (!this.parent && is_alt) {
17664 //el = Roo.get(document.body);
17665 this.parent = { el : true };
17670 if (!this.parent) {
17672 Roo.debug && Roo.log("no parent - creating one");
17674 el = el ? Roo.get(el) : false;
17676 if (typeof(Roo.BorderLayout) == 'undefined' ) {
17679 el : new Roo.bootstrap.layout.Border({
17680 el: el || document.body,
17686 tabPosition: 'top',
17687 //resizeTabs: true,
17688 alwaysShowTabs: false,
17691 overflow: 'visible'
17697 // it's a top level one..
17699 el : new Roo.BorderLayout(el || document.body, {
17704 tabPosition: 'top',
17705 //resizeTabs: true,
17706 alwaysShowTabs: el && hp? false : true,
17707 hideTabs: el || !hp ? true : false,
17715 if (!this.parent.el) {
17716 // probably an old style ctor, which has been disabled.
17720 // The 'tree' method is '_tree now'
17722 tree.region = tree.region || this.region;
17723 var is_body = false;
17724 if (this.parent.el === true) {
17725 // bootstrap... - body..
17729 this.parent.el = Roo.factory(tree);
17733 this.el = this.parent.el.addxtype(tree, undefined, is_body);
17734 this.fireEvent('built', this);
17736 this.panel = this.el;
17737 this.layout = this.panel.layout;
17738 this.parentLayout = this.parent.layout || false;
17744 Roo.apply(Roo.XComponent, {
17746 * @property hideProgress
17747 * true to disable the building progress bar.. usefull on single page renders.
17750 hideProgress : false,
17752 * @property buildCompleted
17753 * True when the builder has completed building the interface.
17756 buildCompleted : false,
17759 * @property topModule
17760 * the upper most module - uses document.element as it's constructor.
17767 * @property modules
17768 * array of modules to be created by registration system.
17769 * @type {Array} of Roo.XComponent
17774 * @property elmodules
17775 * array of modules to be created by which use #ID
17776 * @type {Array} of Roo.XComponent
17783 * Is an alternative Root - normally used by bootstrap or other systems,
17784 * where the top element in the tree can wrap 'body'
17785 * @type {boolean} (default false)
17790 * @property build_from_html
17791 * Build elements from html - used by bootstrap HTML stuff
17792 * - this is cleared after build is completed
17793 * @type {boolean} (default false)
17796 build_from_html : false,
17798 * Register components to be built later.
17800 * This solves the following issues
17801 * - Building is not done on page load, but after an authentication process has occured.
17802 * - Interface elements are registered on page load
17803 * - Parent Interface elements may not be loaded before child, so this handles that..
17810 module : 'Pman.Tab.projectMgr',
17812 parent : 'Pman.layout',
17813 disabled : false, // or use a function..
17816 * * @param {Object} details about module
17818 register : function(obj) {
17820 Roo.XComponent.event.fireEvent('register', obj);
17821 switch(typeof(obj.disabled) ) {
17827 if ( obj.disabled() ) {
17833 if (obj.disabled || obj.region == '#disabled') {
17839 this.modules.push(obj);
17843 * convert a string to an object..
17844 * eg. 'AAA.BBB' -> finds AAA.BBB
17848 toObject : function(str)
17850 if (!str || typeof(str) == 'object') {
17853 if (str.substring(0,1) == '#') {
17857 var ar = str.split('.');
17862 eval('if (typeof ' + rt + ' == "undefined"){ o = false;} o = ' + rt + ';');
17864 throw "Module not found : " + str;
17868 throw "Module not found : " + str;
17870 Roo.each(ar, function(e) {
17871 if (typeof(o[e]) == 'undefined') {
17872 throw "Module not found : " + str;
17883 * move modules into their correct place in the tree..
17886 preBuild : function ()
17889 Roo.each(this.modules , function (obj)
17891 Roo.XComponent.event.fireEvent('beforebuild', obj);
17893 var opar = obj.parent;
17895 obj.parent = this.toObject(opar);
17897 Roo.debug && Roo.log("parent:toObject failed: " + e.toString());
17902 Roo.debug && Roo.log("GOT top level module");
17903 Roo.debug && Roo.log(obj);
17904 obj.modules = new Roo.util.MixedCollection(false,
17905 function(o) { return o.order + '' }
17907 this.topModule = obj;
17910 // parent is a string (usually a dom element name..)
17911 if (typeof(obj.parent) == 'string') {
17912 this.elmodules.push(obj);
17915 if (obj.parent.constructor != Roo.XComponent) {
17916 Roo.debug && Roo.log("Warning : Object Parent is not instance of XComponent:" + obj.name)
17918 if (!obj.parent.modules) {
17919 obj.parent.modules = new Roo.util.MixedCollection(false,
17920 function(o) { return o.order + '' }
17923 if (obj.parent.disabled) {
17924 obj.disabled = true;
17926 obj.parent.modules.add(obj);
17931 * make a list of modules to build.
17932 * @return {Array} list of modules.
17935 buildOrder : function()
17938 var cmp = function(a,b) {
17939 return String(a).toUpperCase() > String(b).toUpperCase() ? 1 : -1;
17941 if ((!this.topModule || !this.topModule.modules) && !this.elmodules.length) {
17942 throw "No top level modules to build";
17945 // make a flat list in order of modules to build.
17946 var mods = this.topModule ? [ this.topModule ] : [];
17949 // elmodules (is a list of DOM based modules )
17950 Roo.each(this.elmodules, function(e) {
17952 if (!this.topModule &&
17953 typeof(e.parent) == 'string' &&
17954 e.parent.substring(0,1) == '#' &&
17955 Roo.get(e.parent.substr(1))
17958 _this.topModule = e;
17964 // add modules to their parents..
17965 var addMod = function(m) {
17966 Roo.debug && Roo.log("build Order: add: " + m.name);
17969 if (m.modules && !m.disabled) {
17970 Roo.debug && Roo.log("build Order: " + m.modules.length + " child modules");
17971 m.modules.keySort('ASC', cmp );
17972 Roo.debug && Roo.log("build Order: " + m.modules.length + " child modules (after sort)");
17974 m.modules.each(addMod);
17976 Roo.debug && Roo.log("build Order: no child modules");
17978 // not sure if this is used any more..
17980 m.finalize.name = m.name + " (clean up) ";
17981 mods.push(m.finalize);
17985 if (this.topModule && this.topModule.modules) {
17986 this.topModule.modules.keySort('ASC', cmp );
17987 this.topModule.modules.each(addMod);
17993 * Build the registered modules.
17994 * @param {Object} parent element.
17995 * @param {Function} optional method to call after module has been added.
17999 build : function(opts)
18002 if (typeof(opts) != 'undefined') {
18003 Roo.apply(this,opts);
18007 var mods = this.buildOrder();
18009 //this.allmods = mods;
18010 //Roo.debug && Roo.log(mods);
18012 if (!mods.length) { // should not happen
18013 throw "NO modules!!!";
18017 var msg = "Building Interface...";
18018 // flash it up as modal - so we store the mask!?
18019 if (!this.hideProgress && Roo.MessageBox) {
18020 Roo.MessageBox.show({ title: 'loading' });
18021 Roo.MessageBox.show({
18022 title: "Please wait...",
18032 var total = mods.length;
18035 var progressRun = function() {
18036 if (!mods.length) {
18037 Roo.debug && Roo.log('hide?');
18038 if (!this.hideProgress && Roo.MessageBox) {
18039 Roo.MessageBox.hide();
18041 Roo.XComponent.build_from_html = false; // reset, so dialogs will be build from javascript
18043 Roo.XComponent.event.fireEvent('buildcomplete', _this.topModule);
18049 var m = mods.shift();
18052 Roo.debug && Roo.log(m);
18053 // not sure if this is supported any more.. - modules that are are just function
18054 if (typeof(m) == 'function') {
18056 return progressRun.defer(10, _this);
18060 msg = "Building Interface " + (total - mods.length) +
18062 (m.name ? (' - ' + m.name) : '');
18063 Roo.debug && Roo.log(msg);
18064 if (!_this.hideProgress && Roo.MessageBox) {
18065 Roo.MessageBox.updateProgress( (total - mods.length)/total, msg );
18069 // is the module disabled?
18070 var disabled = (typeof(m.disabled) == 'function') ?
18071 m.disabled.call(m.module.disabled) : m.disabled;
18075 return progressRun(); // we do not update the display!
18083 // it's 10 on top level, and 1 on others??? why...
18084 return progressRun.defer(10, _this);
18087 progressRun.defer(1, _this);
18093 * Overlay a set of modified strings onto a component
18094 * This is dependant on our builder exporting the strings and 'named strings' elements.
18096 * @param {Object} element to overlay on - eg. Pman.Dialog.Login
18097 * @param {Object} associative array of 'named' string and it's new value.
18100 overlayStrings : function( component, strings )
18102 if (typeof(component['_named_strings']) == 'undefined') {
18103 throw "ERROR: component does not have _named_strings";
18105 for ( var k in strings ) {
18106 var md = typeof(component['_named_strings'][k]) == 'undefined' ? false : component['_named_strings'][k];
18107 if (md !== false) {
18108 component['_strings'][md] = strings[k];
18110 Roo.log('could not find named string: ' + k + ' in');
18111 Roo.log(component);
18126 * wrapper for event.on - aliased later..
18127 * Typically use to register a event handler for register:
18129 * eg. Roo.XComponent.on('register', function(comp) { comp.disable = true } );
18138 Roo.XComponent.event = new Roo.util.Observable({
18142 * Fires when an Component is registered,
18143 * set the disable property on the Component to stop registration.
18144 * @param {Roo.XComponent} c the component being registerd.
18149 * @event beforebuild
18150 * Fires before each Component is built
18151 * can be used to apply permissions.
18152 * @param {Roo.XComponent} c the component being registerd.
18155 'beforebuild' : true,
18157 * @event buildcomplete
18158 * Fires on the top level element when all elements have been built
18159 * @param {Roo.XComponent} the top level component.
18161 'buildcomplete' : true
18166 Roo.XComponent.on = Roo.XComponent.event.on.createDelegate(Roo.XComponent.event);
18169 * marked - a markdown parser
18170 * Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed)
18171 * https://github.com/chjj/marked
18177 * Roo.Markdown - is a very crude wrapper around marked..
18181 * alert( Roo.Markdown.toHtml("Markdown *rocks*.") );
18183 * Note: move the sample code to the bottom of this
18184 * file before uncommenting it.
18189 Roo.Markdown.toHtml = function(text) {
18191 var c = new Roo.Markdown.marked.setOptions({
18192 renderer: new Roo.Markdown.marked.Renderer(),
18203 text = text.replace(/\\\n/g,' ');
18204 return Roo.Markdown.marked(text);
18209 // Wraps all "globals" so that the only thing
18210 // exposed is makeHtml().
18216 * eval:var:unescape
18224 var escape = function (html, encode) {
18226 .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&')
18227 .replace(/</g, '<')
18228 .replace(/>/g, '>')
18229 .replace(/"/g, '"')
18230 .replace(/'/g, ''');
18233 var unescape = function (html) {
18234 // explicitly match decimal, hex, and named HTML entities
18235 return html.replace(/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/g, function(_, n) {
18236 n = n.toLowerCase();
18237 if (n === 'colon') { return ':'; }
18238 if (n.charAt(0) === '#') {
18239 return n.charAt(1) === 'x'
18240 ? String.fromCharCode(parseInt(n.substring(2), 16))
18241 : String.fromCharCode(+n.substring(1));
18247 var replace = function (regex, opt) {
18248 regex = regex.source;
18250 return function self(name, val) {
18251 if (!name) { return new RegExp(regex, opt); }
18252 val = val.source || val;
18253 val = val.replace(/(^|[^\[])\^/g, '$1');
18254 regex = regex.replace(name, val);
18263 var noop = function () {}
18269 var merge = function (obj) {
18274 for (; i < arguments.length; i++) {
18275 target = arguments[i];
18276 for (key in target) {
18277 if (Object.prototype.hasOwnProperty.call(target, key)) {
18278 obj[key] = target[key];
18288 * Block-Level Grammar
18296 code: /^( {4}[^\n]+\n*)+/,
18298 hr: /^( *[-*_]){3,} *(?:\n+|$)/,
18299 heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,
18301 lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,
18302 blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/,
18303 list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,
18304 html: /^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/,
18305 def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,
18307 paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,
18311 block.bullet = /(?:[*+-]|\d+\.)/;
18312 block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/;
18313 block.item = replace(block.item, 'gm')
18314 (/bull/g, block.bullet)
18317 block.list = replace(block.list)
18318 (/bull/g, block.bullet)
18319 ('hr', '\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))')
18320 ('def', '\\n+(?=' + block.def.source + ')')
18323 block.blockquote = replace(block.blockquote)
18327 block._tag = '(?!(?:'
18328 + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code'
18329 + '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo'
18330 + '|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b';
18332 block.html = replace(block.html)
18333 ('comment', /<!--[\s\S]*?-->/)
18334 ('closed', /<(tag)[\s\S]+?<\/\1>/)
18335 ('closing', /<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)
18336 (/tag/g, block._tag)
18339 block.paragraph = replace(block.paragraph)
18341 ('heading', block.heading)
18342 ('lheading', block.lheading)
18343 ('blockquote', block.blockquote)
18344 ('tag', '<' + block._tag)
18349 * Normal Block Grammar
18352 block.normal = merge({}, block);
18355 * GFM Block Grammar
18358 block.gfm = merge({}, block.normal, {
18359 fences: /^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/,
18361 heading: /^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/
18364 block.gfm.paragraph = replace(block.paragraph)
18366 + block.gfm.fences.source.replace('\\1', '\\2') + '|'
18367 + block.list.source.replace('\\1', '\\3') + '|')
18371 * GFM + Tables Block Grammar
18374 block.tables = merge({}, block.gfm, {
18375 nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,
18376 table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/
18383 var Lexer = function (options) {
18385 this.tokens.links = {};
18386 this.options = options || marked.defaults;
18387 this.rules = block.normal;
18389 if (this.options.gfm) {
18390 if (this.options.tables) {
18391 this.rules = block.tables;
18393 this.rules = block.gfm;
18399 * Expose Block Rules
18402 Lexer.rules = block;
18405 * Static Lex Method
18408 Lexer.lex = function(src, options) {
18409 var lexer = new Lexer(options);
18410 return lexer.lex(src);
18417 Lexer.prototype.lex = function(src) {
18419 .replace(/\r\n|\r/g, '\n')
18420 .replace(/\t/g, ' ')
18421 .replace(/\u00a0/g, ' ')
18422 .replace(/\u2424/g, '\n');
18424 return this.token(src, true);
18431 Lexer.prototype.token = function(src, top, bq) {
18432 var src = src.replace(/^ +$/gm, '')
18445 if (cap = this.rules.newline.exec(src)) {
18446 src = src.substring(cap[0].length);
18447 if (cap[0].length > 1) {
18455 if (cap = this.rules.code.exec(src)) {
18456 src = src.substring(cap[0].length);
18457 cap = cap[0].replace(/^ {4}/gm, '');
18460 text: !this.options.pedantic
18461 ? cap.replace(/\n+$/, '')
18468 if (cap = this.rules.fences.exec(src)) {
18469 src = src.substring(cap[0].length);
18479 if (cap = this.rules.heading.exec(src)) {
18480 src = src.substring(cap[0].length);
18483 depth: cap[1].length,
18489 // table no leading pipe (gfm)
18490 if (top && (cap = this.rules.nptable.exec(src))) {
18491 src = src.substring(cap[0].length);
18495 header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
18496 align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
18497 cells: cap[3].replace(/\n$/, '').split('\n')
18500 for (i = 0; i < item.align.length; i++) {
18501 if (/^ *-+: *$/.test(item.align[i])) {
18502 item.align[i] = 'right';
18503 } else if (/^ *:-+: *$/.test(item.align[i])) {
18504 item.align[i] = 'center';
18505 } else if (/^ *:-+ *$/.test(item.align[i])) {
18506 item.align[i] = 'left';
18508 item.align[i] = null;
18512 for (i = 0; i < item.cells.length; i++) {
18513 item.cells[i] = item.cells[i].split(/ *\| */);
18516 this.tokens.push(item);
18522 if (cap = this.rules.lheading.exec(src)) {
18523 src = src.substring(cap[0].length);
18526 depth: cap[2] === '=' ? 1 : 2,
18533 if (cap = this.rules.hr.exec(src)) {
18534 src = src.substring(cap[0].length);
18542 if (cap = this.rules.blockquote.exec(src)) {
18543 src = src.substring(cap[0].length);
18546 type: 'blockquote_start'
18549 cap = cap[0].replace(/^ *> ?/gm, '');
18551 // Pass `top` to keep the current
18552 // "toplevel" state. This is exactly
18553 // how markdown.pl works.
18554 this.token(cap, top, true);
18557 type: 'blockquote_end'
18564 if (cap = this.rules.list.exec(src)) {
18565 src = src.substring(cap[0].length);
18569 type: 'list_start',
18570 ordered: bull.length > 1
18573 // Get each top-level item.
18574 cap = cap[0].match(this.rules.item);
18580 for (; i < l; i++) {
18583 // Remove the list item's bullet
18584 // so it is seen as the next token.
18585 space = item.length;
18586 item = item.replace(/^ *([*+-]|\d+\.) +/, '');
18588 // Outdent whatever the
18589 // list item contains. Hacky.
18590 if (~item.indexOf('\n ')) {
18591 space -= item.length;
18592 item = !this.options.pedantic
18593 ? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '')
18594 : item.replace(/^ {1,4}/gm, '');
18597 // Determine whether the next list item belongs here.
18598 // Backpedal if it does not belong in this list.
18599 if (this.options.smartLists && i !== l - 1) {
18600 b = block.bullet.exec(cap[i + 1])[0];
18601 if (bull !== b && !(bull.length > 1 && b.length > 1)) {
18602 src = cap.slice(i + 1).join('\n') + src;
18607 // Determine whether item is loose or not.
18608 // Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/
18609 // for discount behavior.
18610 loose = next || /\n\n(?!\s*$)/.test(item);
18612 next = item.charAt(item.length - 1) === '\n';
18613 if (!loose) { loose = next; }
18618 ? 'loose_item_start'
18619 : 'list_item_start'
18623 this.token(item, false, bq);
18626 type: 'list_item_end'
18638 if (cap = this.rules.html.exec(src)) {
18639 src = src.substring(cap[0].length);
18641 type: this.options.sanitize
18644 pre: !this.options.sanitizer
18645 && (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'),
18652 if ((!bq && top) && (cap = this.rules.def.exec(src))) {
18653 src = src.substring(cap[0].length);
18654 this.tokens.links[cap[1].toLowerCase()] = {
18662 if (top && (cap = this.rules.table.exec(src))) {
18663 src = src.substring(cap[0].length);
18667 header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
18668 align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
18669 cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n')
18672 for (i = 0; i < item.align.length; i++) {
18673 if (/^ *-+: *$/.test(item.align[i])) {
18674 item.align[i] = 'right';
18675 } else if (/^ *:-+: *$/.test(item.align[i])) {
18676 item.align[i] = 'center';
18677 } else if (/^ *:-+ *$/.test(item.align[i])) {
18678 item.align[i] = 'left';
18680 item.align[i] = null;
18684 for (i = 0; i < item.cells.length; i++) {
18685 item.cells[i] = item.cells[i]
18686 .replace(/^ *\| *| *\| *$/g, '')
18690 this.tokens.push(item);
18695 // top-level paragraph
18696 if (top && (cap = this.rules.paragraph.exec(src))) {
18697 src = src.substring(cap[0].length);
18700 text: cap[1].charAt(cap[1].length - 1) === '\n'
18701 ? cap[1].slice(0, -1)
18708 if (cap = this.rules.text.exec(src)) {
18709 // Top-level should never reach here.
18710 src = src.substring(cap[0].length);
18720 Error('Infinite loop on byte: ' + src.charCodeAt(0));
18724 return this.tokens;
18728 * Inline-Level Grammar
18732 escape: /^\\([\\`*{}\[\]()#+\-.!_>])/,
18733 autolink: /^<([^ >]+(@|:\/)[^ >]+)>/,
18735 tag: /^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,
18736 link: /^!?\[(inside)\]\(href\)/,
18737 reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/,
18738 nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,
18739 strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,
18740 em: /^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,
18741 code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,
18742 br: /^ {2,}\n(?!\s*$)/,
18744 text: /^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/
18747 inline._inside = /(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/;
18748 inline._href = /\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/;
18750 inline.link = replace(inline.link)
18751 ('inside', inline._inside)
18752 ('href', inline._href)
18755 inline.reflink = replace(inline.reflink)
18756 ('inside', inline._inside)
18760 * Normal Inline Grammar
18763 inline.normal = merge({}, inline);
18766 * Pedantic Inline Grammar
18769 inline.pedantic = merge({}, inline.normal, {
18770 strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
18771 em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/
18775 * GFM Inline Grammar
18778 inline.gfm = merge({}, inline.normal, {
18779 escape: replace(inline.escape)('])', '~|])')(),
18780 url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,
18781 del: /^~~(?=\S)([\s\S]*?\S)~~/,
18782 text: replace(inline.text)
18784 ('|', '|https?://|')
18789 * GFM + Line Breaks Inline Grammar
18792 inline.breaks = merge({}, inline.gfm, {
18793 br: replace(inline.br)('{2,}', '*')(),
18794 text: replace(inline.gfm.text)('{2,}', '*')()
18798 * Inline Lexer & Compiler
18801 var InlineLexer = function (links, options) {
18802 this.options = options || marked.defaults;
18803 this.links = links;
18804 this.rules = inline.normal;
18805 this.renderer = this.options.renderer || new Renderer;
18806 this.renderer.options = this.options;
18810 Error('Tokens array requires a `links` property.');
18813 if (this.options.gfm) {
18814 if (this.options.breaks) {
18815 this.rules = inline.breaks;
18817 this.rules = inline.gfm;
18819 } else if (this.options.pedantic) {
18820 this.rules = inline.pedantic;
18825 * Expose Inline Rules
18828 InlineLexer.rules = inline;
18831 * Static Lexing/Compiling Method
18834 InlineLexer.output = function(src, links, options) {
18835 var inline = new InlineLexer(links, options);
18836 return inline.output(src);
18843 InlineLexer.prototype.output = function(src) {
18852 if (cap = this.rules.escape.exec(src)) {
18853 src = src.substring(cap[0].length);
18859 if (cap = this.rules.autolink.exec(src)) {
18860 src = src.substring(cap[0].length);
18861 if (cap[2] === '@') {
18862 text = cap[1].charAt(6) === ':'
18863 ? this.mangle(cap[1].substring(7))
18864 : this.mangle(cap[1]);
18865 href = this.mangle('mailto:') + text;
18867 text = escape(cap[1]);
18870 out += this.renderer.link(href, null, text);
18875 if (!this.inLink && (cap = this.rules.url.exec(src))) {
18876 src = src.substring(cap[0].length);
18877 text = escape(cap[1]);
18879 out += this.renderer.link(href, null, text);
18884 if (cap = this.rules.tag.exec(src)) {
18885 if (!this.inLink && /^<a /i.test(cap[0])) {
18886 this.inLink = true;
18887 } else if (this.inLink && /^<\/a>/i.test(cap[0])) {
18888 this.inLink = false;
18890 src = src.substring(cap[0].length);
18891 out += this.options.sanitize
18892 ? this.options.sanitizer
18893 ? this.options.sanitizer(cap[0])
18900 if (cap = this.rules.link.exec(src)) {
18901 src = src.substring(cap[0].length);
18902 this.inLink = true;
18903 out += this.outputLink(cap, {
18907 this.inLink = false;
18912 if ((cap = this.rules.reflink.exec(src))
18913 || (cap = this.rules.nolink.exec(src))) {
18914 src = src.substring(cap[0].length);
18915 link = (cap[2] || cap[1]).replace(/\s+/g, ' ');
18916 link = this.links[link.toLowerCase()];
18917 if (!link || !link.href) {
18918 out += cap[0].charAt(0);
18919 src = cap[0].substring(1) + src;
18922 this.inLink = true;
18923 out += this.outputLink(cap, link);
18924 this.inLink = false;
18929 if (cap = this.rules.strong.exec(src)) {
18930 src = src.substring(cap[0].length);
18931 out += this.renderer.strong(this.output(cap[2] || cap[1]));
18936 if (cap = this.rules.em.exec(src)) {
18937 src = src.substring(cap[0].length);
18938 out += this.renderer.em(this.output(cap[2] || cap[1]));
18943 if (cap = this.rules.code.exec(src)) {
18944 src = src.substring(cap[0].length);
18945 out += this.renderer.codespan(escape(cap[2], true));
18950 if (cap = this.rules.br.exec(src)) {
18951 src = src.substring(cap[0].length);
18952 out += this.renderer.br();
18957 if (cap = this.rules.del.exec(src)) {
18958 src = src.substring(cap[0].length);
18959 out += this.renderer.del(this.output(cap[1]));
18964 if (cap = this.rules.text.exec(src)) {
18965 src = src.substring(cap[0].length);
18966 out += this.renderer.text(escape(this.smartypants(cap[0])));
18972 Error('Infinite loop on byte: ' + src.charCodeAt(0));
18983 InlineLexer.prototype.outputLink = function(cap, link) {
18984 var href = escape(link.href)
18985 , title = link.title ? escape(link.title) : null;
18987 return cap[0].charAt(0) !== '!'
18988 ? this.renderer.link(href, title, this.output(cap[1]))
18989 : this.renderer.image(href, title, escape(cap[1]));
18993 * Smartypants Transformations
18996 InlineLexer.prototype.smartypants = function(text) {
18997 if (!this.options.smartypants) { return text; }
19000 .replace(/---/g, '\u2014')
19002 .replace(/--/g, '\u2013')
19004 .replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018')
19005 // closing singles & apostrophes
19006 .replace(/'/g, '\u2019')
19008 .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c')
19010 .replace(/"/g, '\u201d')
19012 .replace(/\.{3}/g, '\u2026');
19019 InlineLexer.prototype.mangle = function(text) {
19020 if (!this.options.mangle) { return text; }
19026 for (; i < l; i++) {
19027 ch = text.charCodeAt(i);
19028 if (Math.random() > 0.5) {
19029 ch = 'x' + ch.toString(16);
19031 out += '&#' + ch + ';';
19042 * eval:var:Renderer
19045 var Renderer = function (options) {
19046 this.options = options || {};
19049 Renderer.prototype.code = function(code, lang, escaped) {
19050 if (this.options.highlight) {
19051 var out = this.options.highlight(code, lang);
19052 if (out != null && out !== code) {
19057 // hack!!! - it's already escapeD?
19062 return '<pre><code>'
19063 + (escaped ? code : escape(code, true))
19064 + '\n</code></pre>';
19067 return '<pre><code class="'
19068 + this.options.langPrefix
19069 + escape(lang, true)
19071 + (escaped ? code : escape(code, true))
19072 + '\n</code></pre>\n';
19075 Renderer.prototype.blockquote = function(quote) {
19076 return '<blockquote>\n' + quote + '</blockquote>\n';
19079 Renderer.prototype.html = function(html) {
19083 Renderer.prototype.heading = function(text, level, raw) {
19087 + this.options.headerPrefix
19088 + raw.toLowerCase().replace(/[^\w]+/g, '-')
19096 Renderer.prototype.hr = function() {
19097 return this.options.xhtml ? '<hr/>\n' : '<hr>\n';
19100 Renderer.prototype.list = function(body, ordered) {
19101 var type = ordered ? 'ol' : 'ul';
19102 return '<' + type + '>\n' + body + '</' + type + '>\n';
19105 Renderer.prototype.listitem = function(text) {
19106 return '<li>' + text + '</li>\n';
19109 Renderer.prototype.paragraph = function(text) {
19110 return '<p>' + text + '</p>\n';
19113 Renderer.prototype.table = function(header, body) {
19114 return '<table class="table table-striped">\n'
19124 Renderer.prototype.tablerow = function(content) {
19125 return '<tr>\n' + content + '</tr>\n';
19128 Renderer.prototype.tablecell = function(content, flags) {
19129 var type = flags.header ? 'th' : 'td';
19130 var tag = flags.align
19131 ? '<' + type + ' style="text-align:' + flags.align + '">'
19132 : '<' + type + '>';
19133 return tag + content + '</' + type + '>\n';
19136 // span level renderer
19137 Renderer.prototype.strong = function(text) {
19138 return '<strong>' + text + '</strong>';
19141 Renderer.prototype.em = function(text) {
19142 return '<em>' + text + '</em>';
19145 Renderer.prototype.codespan = function(text) {
19146 return '<code>' + text + '</code>';
19149 Renderer.prototype.br = function() {
19150 return this.options.xhtml ? '<br/>' : '<br>';
19153 Renderer.prototype.del = function(text) {
19154 return '<del>' + text + '</del>';
19157 Renderer.prototype.link = function(href, title, text) {
19158 if (this.options.sanitize) {
19160 var prot = decodeURIComponent(unescape(href))
19161 .replace(/[^\w:]/g, '')
19166 if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0) {
19170 var out = '<a href="' + href + '"';
19172 out += ' title="' + title + '"';
19174 out += '>' + text + '</a>';
19178 Renderer.prototype.image = function(href, title, text) {
19179 var out = '<img src="' + href + '" alt="' + text + '"';
19181 out += ' title="' + title + '"';
19183 out += this.options.xhtml ? '/>' : '>';
19187 Renderer.prototype.text = function(text) {
19192 * Parsing & Compiling
19198 var Parser= function (options) {
19201 this.options = options || marked.defaults;
19202 this.options.renderer = this.options.renderer || new Renderer;
19203 this.renderer = this.options.renderer;
19204 this.renderer.options = this.options;
19208 * Static Parse Method
19211 Parser.parse = function(src, options, renderer) {
19212 var parser = new Parser(options, renderer);
19213 return parser.parse(src);
19220 Parser.prototype.parse = function(src) {
19221 this.inline = new InlineLexer(src.links, this.options, this.renderer);
19222 this.tokens = src.reverse();
19225 while (this.next()) {
19236 Parser.prototype.next = function() {
19237 return this.token = this.tokens.pop();
19241 * Preview Next Token
19244 Parser.prototype.peek = function() {
19245 return this.tokens[this.tokens.length - 1] || 0;
19249 * Parse Text Tokens
19252 Parser.prototype.parseText = function() {
19253 var body = this.token.text;
19255 while (this.peek().type === 'text') {
19256 body += '\n' + this.next().text;
19259 return this.inline.output(body);
19263 * Parse Current Token
19266 Parser.prototype.tok = function() {
19267 switch (this.token.type) {
19272 return this.renderer.hr();
19275 return this.renderer.heading(
19276 this.inline.output(this.token.text),
19281 return this.renderer.code(this.token.text,
19283 this.token.escaped);
19296 for (i = 0; i < this.token.header.length; i++) {
19297 flags = { header: true, align: this.token.align[i] };
19298 cell += this.renderer.tablecell(
19299 this.inline.output(this.token.header[i]),
19300 { header: true, align: this.token.align[i] }
19303 header += this.renderer.tablerow(cell);
19305 for (i = 0; i < this.token.cells.length; i++) {
19306 row = this.token.cells[i];
19309 for (j = 0; j < row.length; j++) {
19310 cell += this.renderer.tablecell(
19311 this.inline.output(row[j]),
19312 { header: false, align: this.token.align[j] }
19316 body += this.renderer.tablerow(cell);
19318 return this.renderer.table(header, body);
19320 case 'blockquote_start': {
19323 while (this.next().type !== 'blockquote_end') {
19324 body += this.tok();
19327 return this.renderer.blockquote(body);
19329 case 'list_start': {
19331 , ordered = this.token.ordered;
19333 while (this.next().type !== 'list_end') {
19334 body += this.tok();
19337 return this.renderer.list(body, ordered);
19339 case 'list_item_start': {
19342 while (this.next().type !== 'list_item_end') {
19343 body += this.token.type === 'text'
19348 return this.renderer.listitem(body);
19350 case 'loose_item_start': {
19353 while (this.next().type !== 'list_item_end') {
19354 body += this.tok();
19357 return this.renderer.listitem(body);
19360 var html = !this.token.pre && !this.options.pedantic
19361 ? this.inline.output(this.token.text)
19363 return this.renderer.html(html);
19365 case 'paragraph': {
19366 return this.renderer.paragraph(this.inline.output(this.token.text));
19369 return this.renderer.paragraph(this.parseText());
19381 var marked = function (src, opt, callback) {
19382 if (callback || typeof opt === 'function') {
19388 opt = merge({}, marked.defaults, opt || {});
19390 var highlight = opt.highlight
19396 tokens = Lexer.lex(src, opt)
19398 return callback(e);
19401 pending = tokens.length;
19405 var done = function(err) {
19407 opt.highlight = highlight;
19408 return callback(err);
19414 out = Parser.parse(tokens, opt);
19419 opt.highlight = highlight;
19423 : callback(null, out);
19426 if (!highlight || highlight.length < 3) {
19430 delete opt.highlight;
19432 if (!pending) { return done(); }
19434 for (; i < tokens.length; i++) {
19436 if (token.type !== 'code') {
19437 return --pending || done();
19439 return highlight(token.text, token.lang, function(err, code) {
19440 if (err) { return done(err); }
19441 if (code == null || code === token.text) {
19442 return --pending || done();
19445 token.escaped = true;
19446 --pending || done();
19454 if (opt) { opt = merge({}, marked.defaults, opt); }
19455 return Parser.parse(Lexer.lex(src, opt), opt);
19457 e.message += '\nPlease report this to https://github.com/chjj/marked.';
19458 if ((opt || marked.defaults).silent) {
19459 return '<p>An error occured:</p><pre>'
19460 + escape(e.message + '', true)
19472 marked.setOptions = function(opt) {
19473 merge(marked.defaults, opt);
19477 marked.defaults = {
19488 langPrefix: 'lang-',
19489 smartypants: false,
19491 renderer: new Renderer,
19499 marked.Parser = Parser;
19500 marked.parser = Parser.parse;
19502 marked.Renderer = Renderer;
19504 marked.Lexer = Lexer;
19505 marked.lexer = Lexer.lex;
19507 marked.InlineLexer = InlineLexer;
19508 marked.inlineLexer = InlineLexer.output;
19510 marked.parse = marked;
19512 Roo.Markdown.marked = marked;
19516 * Ext JS Library 1.1.1
19517 * Copyright(c) 2006-2007, Ext JS, LLC.
19519 * Originally Released Under LGPL - original licence link has changed is not relivant.
19522 * <script type="text/javascript">
19528 * These classes are derivatives of the similarly named classes in the YUI Library.
19529 * The original license:
19530 * Copyright (c) 2006, Yahoo! Inc. All rights reserved.
19531 * Code licensed under the BSD License:
19532 * http://developer.yahoo.net/yui/license.txt
19537 var Event=Roo.EventManager;
19538 var Dom=Roo.lib.Dom;
19541 * @class Roo.dd.DragDrop
19542 * @extends Roo.util.Observable
19543 * Defines the interface and base operation of items that that can be
19544 * dragged or can be drop targets. It was designed to be extended, overriding
19545 * the event handlers for startDrag, onDrag, onDragOver and onDragOut.
19546 * Up to three html elements can be associated with a DragDrop instance:
19548 * <li>linked element: the element that is passed into the constructor.
19549 * This is the element which defines the boundaries for interaction with
19550 * other DragDrop objects.</li>
19551 * <li>handle element(s): The drag operation only occurs if the element that
19552 * was clicked matches a handle element. By default this is the linked
19553 * element, but there are times that you will want only a portion of the
19554 * linked element to initiate the drag operation, and the setHandleElId()
19555 * method provides a way to define this.</li>
19556 * <li>drag element: this represents the element that would be moved along
19557 * with the cursor during a drag operation. By default, this is the linked
19558 * element itself as in {@link Roo.dd.DD}. setDragElId() lets you define
19559 * a separate element that would be moved, as in {@link Roo.dd.DDProxy}.
19562 * This class should not be instantiated until the onload event to ensure that
19563 * the associated elements are available.
19564 * The following would define a DragDrop obj that would interact with any
19565 * other DragDrop obj in the "group1" group:
19567 * dd = new Roo.dd.DragDrop("div1", "group1");
19569 * Since none of the event handlers have been implemented, nothing would
19570 * actually happen if you were to run the code above. Normally you would
19571 * override this class or one of the default implementations, but you can
19572 * also override the methods you want on an instance of the class...
19574 * dd.onDragDrop = function(e, id) {
19575 * alert("dd was dropped on " + id);
19579 * @param {String} id of the element that is linked to this instance
19580 * @param {String} sGroup the group of related DragDrop objects
19581 * @param {object} config an object containing configurable attributes
19582 * Valid properties for DragDrop:
19583 * padding, isTarget, maintainOffset, primaryButtonOnly
19585 Roo.dd.DragDrop = function(id, sGroup, config) {
19587 this.init(id, sGroup, config);
19592 Roo.extend(Roo.dd.DragDrop, Roo.util.Observable , {
19595 * The id of the element associated with this object. This is what we
19596 * refer to as the "linked element" because the size and position of
19597 * this element is used to determine when the drag and drop objects have
19605 * Configuration attributes passed into the constructor
19612 * The id of the element that will be dragged. By default this is same
19613 * as the linked element , but could be changed to another element. Ex:
19615 * @property dragElId
19622 * the id of the element that initiates the drag operation. By default
19623 * this is the linked element, but could be changed to be a child of this
19624 * element. This lets us do things like only starting the drag when the
19625 * header element within the linked html element is clicked.
19626 * @property handleElId
19633 * An associative array of HTML tags that will be ignored if clicked.
19634 * @property invalidHandleTypes
19635 * @type {string: string}
19637 invalidHandleTypes: null,
19640 * An associative array of ids for elements that will be ignored if clicked
19641 * @property invalidHandleIds
19642 * @type {string: string}
19644 invalidHandleIds: null,
19647 * An indexted array of css class names for elements that will be ignored
19649 * @property invalidHandleClasses
19652 invalidHandleClasses: null,
19655 * The linked element's absolute X position at the time the drag was
19657 * @property startPageX
19664 * The linked element's absolute X position at the time the drag was
19666 * @property startPageY
19673 * The group defines a logical collection of DragDrop objects that are
19674 * related. Instances only get events when interacting with other
19675 * DragDrop object in the same group. This lets us define multiple
19676 * groups using a single DragDrop subclass if we want.
19678 * @type {string: string}
19683 * Individual drag/drop instances can be locked. This will prevent
19684 * onmousedown start drag.
19692 * Lock this instance
19695 lock: function() { this.locked = true; },
19698 * Unlock this instace
19701 unlock: function() { this.locked = false; },
19704 * By default, all insances can be a drop target. This can be disabled by
19705 * setting isTarget to false.
19712 * The padding configured for this drag and drop object for calculating
19713 * the drop zone intersection with this object.
19720 * Cached reference to the linked element
19721 * @property _domRef
19727 * Internal typeof flag
19728 * @property __ygDragDrop
19731 __ygDragDrop: true,
19734 * Set to true when horizontal contraints are applied
19735 * @property constrainX
19742 * Set to true when vertical contraints are applied
19743 * @property constrainY
19750 * The left constraint
19758 * The right constraint
19766 * The up constraint
19775 * The down constraint
19783 * Maintain offsets when we resetconstraints. Set to true when you want
19784 * the position of the element relative to its parent to stay the same
19785 * when the page changes
19787 * @property maintainOffset
19790 maintainOffset: false,
19793 * Array of pixel locations the element will snap to if we specified a
19794 * horizontal graduation/interval. This array is generated automatically
19795 * when you define a tick interval.
19802 * Array of pixel locations the element will snap to if we specified a
19803 * vertical graduation/interval. This array is generated automatically
19804 * when you define a tick interval.
19811 * By default the drag and drop instance will only respond to the primary
19812 * button click (left button for a right-handed mouse). Set to true to
19813 * allow drag and drop to start with any mouse click that is propogated
19815 * @property primaryButtonOnly
19818 primaryButtonOnly: true,
19821 * The availabe property is false until the linked dom element is accessible.
19822 * @property available
19828 * By default, drags can only be initiated if the mousedown occurs in the
19829 * region the linked element is. This is done in part to work around a
19830 * bug in some browsers that mis-report the mousedown if the previous
19831 * mouseup happened outside of the window. This property is set to true
19832 * if outer handles are defined.
19834 * @property hasOuterHandles
19838 hasOuterHandles: false,
19841 * Code that executes immediately before the startDrag event
19842 * @method b4StartDrag
19845 b4StartDrag: function(x, y) { },
19848 * Abstract method called after a drag/drop object is clicked
19849 * and the drag or mousedown time thresholds have beeen met.
19850 * @method startDrag
19851 * @param {int} X click location
19852 * @param {int} Y click location
19854 startDrag: function(x, y) { /* override this */ },
19857 * Code that executes immediately before the onDrag event
19861 b4Drag: function(e) { },
19864 * Abstract method called during the onMouseMove event while dragging an
19867 * @param {Event} e the mousemove event
19869 onDrag: function(e) { /* override this */ },
19872 * Abstract method called when this element fist begins hovering over
19873 * another DragDrop obj
19874 * @method onDragEnter
19875 * @param {Event} e the mousemove event
19876 * @param {String|DragDrop[]} id In POINT mode, the element
19877 * id this is hovering over. In INTERSECT mode, an array of one or more
19878 * dragdrop items being hovered over.
19880 onDragEnter: function(e, id) { /* override this */ },
19883 * Code that executes immediately before the onDragOver event
19884 * @method b4DragOver
19887 b4DragOver: function(e) { },
19890 * Abstract method called when this element is hovering over another
19892 * @method onDragOver
19893 * @param {Event} e the mousemove event
19894 * @param {String|DragDrop[]} id In POINT mode, the element
19895 * id this is hovering over. In INTERSECT mode, an array of dd items
19896 * being hovered over.
19898 onDragOver: function(e, id) { /* override this */ },
19901 * Code that executes immediately before the onDragOut event
19902 * @method b4DragOut
19905 b4DragOut: function(e) { },
19908 * Abstract method called when we are no longer hovering over an element
19909 * @method onDragOut
19910 * @param {Event} e the mousemove event
19911 * @param {String|DragDrop[]} id In POINT mode, the element
19912 * id this was hovering over. In INTERSECT mode, an array of dd items
19913 * that the mouse is no longer over.
19915 onDragOut: function(e, id) { /* override this */ },
19918 * Code that executes immediately before the onDragDrop event
19919 * @method b4DragDrop
19922 b4DragDrop: function(e) { },
19925 * Abstract method called when this item is dropped on another DragDrop
19927 * @method onDragDrop
19928 * @param {Event} e the mouseup event
19929 * @param {String|DragDrop[]} id In POINT mode, the element
19930 * id this was dropped on. In INTERSECT mode, an array of dd items this
19933 onDragDrop: function(e, id) { /* override this */ },
19936 * Abstract method called when this item is dropped on an area with no
19938 * @method onInvalidDrop
19939 * @param {Event} e the mouseup event
19941 onInvalidDrop: function(e) { /* override this */ },
19944 * Code that executes immediately before the endDrag event
19945 * @method b4EndDrag
19948 b4EndDrag: function(e) { },
19951 * Fired when we are done dragging the object
19953 * @param {Event} e the mouseup event
19955 endDrag: function(e) { /* override this */ },
19958 * Code executed immediately before the onMouseDown event
19959 * @method b4MouseDown
19960 * @param {Event} e the mousedown event
19963 b4MouseDown: function(e) { },
19966 * Event handler that fires when a drag/drop obj gets a mousedown
19967 * @method onMouseDown
19968 * @param {Event} e the mousedown event
19970 onMouseDown: function(e) { /* override this */ },
19973 * Event handler that fires when a drag/drop obj gets a mouseup
19974 * @method onMouseUp
19975 * @param {Event} e the mouseup event
19977 onMouseUp: function(e) { /* override this */ },
19980 * Override the onAvailable method to do what is needed after the initial
19981 * position was determined.
19982 * @method onAvailable
19984 onAvailable: function () {
19988 * Provides default constraint padding to "constrainTo" elements (defaults to {left: 0, right:0, top:0, bottom:0}).
19991 defaultPadding : {left:0, right:0, top:0, bottom:0},
19994 * Initializes the drag drop object's constraints to restrict movement to a certain element.
19998 var dd = new Roo.dd.DDProxy("dragDiv1", "proxytest",
19999 { dragElId: "existingProxyDiv" });
20000 dd.startDrag = function(){
20001 this.constrainTo("parent-id");
20004 * Or you can initalize it using the {@link Roo.Element} object:
20006 Roo.get("dragDiv1").initDDProxy("proxytest", {dragElId: "existingProxyDiv"}, {
20007 startDrag : function(){
20008 this.constrainTo("parent-id");
20012 * @param {String/HTMLElement/Element} constrainTo The element to constrain to.
20013 * @param {Object/Number} pad (optional) Pad provides a way to specify "padding" of the constraints,
20014 * and can be either a number for symmetrical padding (4 would be equal to {left:4, right:4, top:4, bottom:4}) or
20015 * an object containing the sides to pad. For example: {right:10, bottom:10}
20016 * @param {Boolean} inContent (optional) Constrain the draggable in the content box of the element (inside padding and borders)
20018 constrainTo : function(constrainTo, pad, inContent){
20019 if(typeof pad == "number"){
20020 pad = {left: pad, right:pad, top:pad, bottom:pad};
20022 pad = pad || this.defaultPadding;
20023 var b = Roo.get(this.getEl()).getBox();
20024 var ce = Roo.get(constrainTo);
20025 var s = ce.getScroll();
20026 var c, cd = ce.dom;
20027 if(cd == document.body){
20028 c = { x: s.left, y: s.top, width: Roo.lib.Dom.getViewWidth(), height: Roo.lib.Dom.getViewHeight()};
20031 c = {x : xy[0]+s.left, y: xy[1]+s.top, width: cd.clientWidth, height: cd.clientHeight};
20035 var topSpace = b.y - c.y;
20036 var leftSpace = b.x - c.x;
20038 this.resetConstraints();
20039 this.setXConstraint(leftSpace - (pad.left||0), // left
20040 c.width - leftSpace - b.width - (pad.right||0) //right
20042 this.setYConstraint(topSpace - (pad.top||0), //top
20043 c.height - topSpace - b.height - (pad.bottom||0) //bottom
20048 * Returns a reference to the linked element
20050 * @return {HTMLElement} the html element
20052 getEl: function() {
20053 if (!this._domRef) {
20054 this._domRef = Roo.getDom(this.id);
20057 return this._domRef;
20061 * Returns a reference to the actual element to drag. By default this is
20062 * the same as the html element, but it can be assigned to another
20063 * element. An example of this can be found in Roo.dd.DDProxy
20064 * @method getDragEl
20065 * @return {HTMLElement} the html element
20067 getDragEl: function() {
20068 return Roo.getDom(this.dragElId);
20072 * Sets up the DragDrop object. Must be called in the constructor of any
20073 * Roo.dd.DragDrop subclass
20075 * @param id the id of the linked element
20076 * @param {String} sGroup the group of related items
20077 * @param {object} config configuration attributes
20079 init: function(id, sGroup, config) {
20080 this.initTarget(id, sGroup, config);
20081 if (!Roo.isTouch) {
20082 Event.on(this.id, "mousedown", this.handleMouseDown, this);
20084 Event.on(this.id, "touchstart", this.handleMouseDown, this);
20085 // Event.on(this.id, "selectstart", Event.preventDefault);
20089 * Initializes Targeting functionality only... the object does not
20090 * get a mousedown handler.
20091 * @method initTarget
20092 * @param id the id of the linked element
20093 * @param {String} sGroup the group of related items
20094 * @param {object} config configuration attributes
20096 initTarget: function(id, sGroup, config) {
20098 // configuration attributes
20099 this.config = config || {};
20101 // create a local reference to the drag and drop manager
20102 this.DDM = Roo.dd.DDM;
20103 // initialize the groups array
20106 // assume that we have an element reference instead of an id if the
20107 // parameter is not a string
20108 if (typeof id !== "string") {
20115 // add to an interaction group
20116 this.addToGroup((sGroup) ? sGroup : "default");
20118 // We don't want to register this as the handle with the manager
20119 // so we just set the id rather than calling the setter.
20120 this.handleElId = id;
20122 // the linked element is the element that gets dragged by default
20123 this.setDragElId(id);
20125 // by default, clicked anchors will not start drag operations.
20126 this.invalidHandleTypes = { A: "A" };
20127 this.invalidHandleIds = {};
20128 this.invalidHandleClasses = [];
20130 this.applyConfig();
20132 this.handleOnAvailable();
20136 * Applies the configuration parameters that were passed into the constructor.
20137 * This is supposed to happen at each level through the inheritance chain. So
20138 * a DDProxy implentation will execute apply config on DDProxy, DD, and
20139 * DragDrop in order to get all of the parameters that are available in
20141 * @method applyConfig
20143 applyConfig: function() {
20145 // configurable properties:
20146 // padding, isTarget, maintainOffset, primaryButtonOnly
20147 this.padding = this.config.padding || [0, 0, 0, 0];
20148 this.isTarget = (this.config.isTarget !== false);
20149 this.maintainOffset = (this.config.maintainOffset);
20150 this.primaryButtonOnly = (this.config.primaryButtonOnly !== false);
20155 * Executed when the linked element is available
20156 * @method handleOnAvailable
20159 handleOnAvailable: function() {
20160 this.available = true;
20161 this.resetConstraints();
20162 this.onAvailable();
20166 * Configures the padding for the target zone in px. Effectively expands
20167 * (or reduces) the virtual object size for targeting calculations.
20168 * Supports css-style shorthand; if only one parameter is passed, all sides
20169 * will have that padding, and if only two are passed, the top and bottom
20170 * will have the first param, the left and right the second.
20171 * @method setPadding
20172 * @param {int} iTop Top pad
20173 * @param {int} iRight Right pad
20174 * @param {int} iBot Bot pad
20175 * @param {int} iLeft Left pad
20177 setPadding: function(iTop, iRight, iBot, iLeft) {
20178 // this.padding = [iLeft, iRight, iTop, iBot];
20179 if (!iRight && 0 !== iRight) {
20180 this.padding = [iTop, iTop, iTop, iTop];
20181 } else if (!iBot && 0 !== iBot) {
20182 this.padding = [iTop, iRight, iTop, iRight];
20184 this.padding = [iTop, iRight, iBot, iLeft];
20189 * Stores the initial placement of the linked element.
20190 * @method setInitialPosition
20191 * @param {int} diffX the X offset, default 0
20192 * @param {int} diffY the Y offset, default 0
20194 setInitPosition: function(diffX, diffY) {
20195 var el = this.getEl();
20197 if (!this.DDM.verifyEl(el)) {
20201 var dx = diffX || 0;
20202 var dy = diffY || 0;
20204 var p = Dom.getXY( el );
20206 this.initPageX = p[0] - dx;
20207 this.initPageY = p[1] - dy;
20209 this.lastPageX = p[0];
20210 this.lastPageY = p[1];
20213 this.setStartPosition(p);
20217 * Sets the start position of the element. This is set when the obj
20218 * is initialized, the reset when a drag is started.
20219 * @method setStartPosition
20220 * @param pos current position (from previous lookup)
20223 setStartPosition: function(pos) {
20224 var p = pos || Dom.getXY( this.getEl() );
20225 this.deltaSetXY = null;
20227 this.startPageX = p[0];
20228 this.startPageY = p[1];
20232 * Add this instance to a group of related drag/drop objects. All
20233 * instances belong to at least one group, and can belong to as many
20234 * groups as needed.
20235 * @method addToGroup
20236 * @param sGroup {string} the name of the group
20238 addToGroup: function(sGroup) {
20239 this.groups[sGroup] = true;
20240 this.DDM.regDragDrop(this, sGroup);
20244 * Remove's this instance from the supplied interaction group
20245 * @method removeFromGroup
20246 * @param {string} sGroup The group to drop
20248 removeFromGroup: function(sGroup) {
20249 if (this.groups[sGroup]) {
20250 delete this.groups[sGroup];
20253 this.DDM.removeDDFromGroup(this, sGroup);
20257 * Allows you to specify that an element other than the linked element
20258 * will be moved with the cursor during a drag
20259 * @method setDragElId
20260 * @param id {string} the id of the element that will be used to initiate the drag
20262 setDragElId: function(id) {
20263 this.dragElId = id;
20267 * Allows you to specify a child of the linked element that should be
20268 * used to initiate the drag operation. An example of this would be if
20269 * you have a content div with text and links. Clicking anywhere in the
20270 * content area would normally start the drag operation. Use this method
20271 * to specify that an element inside of the content div is the element
20272 * that starts the drag operation.
20273 * @method setHandleElId
20274 * @param id {string} the id of the element that will be used to
20275 * initiate the drag.
20277 setHandleElId: function(id) {
20278 if (typeof id !== "string") {
20281 this.handleElId = id;
20282 this.DDM.regHandle(this.id, id);
20286 * Allows you to set an element outside of the linked element as a drag
20288 * @method setOuterHandleElId
20289 * @param id the id of the element that will be used to initiate the drag
20291 setOuterHandleElId: function(id) {
20292 if (typeof id !== "string") {
20295 Event.on(id, "mousedown",
20296 this.handleMouseDown, this);
20297 this.setHandleElId(id);
20299 this.hasOuterHandles = true;
20303 * Remove all drag and drop hooks for this element
20306 unreg: function() {
20307 Event.un(this.id, "mousedown",
20308 this.handleMouseDown);
20309 Event.un(this.id, "touchstart",
20310 this.handleMouseDown);
20311 this._domRef = null;
20312 this.DDM._remove(this);
20315 destroy : function(){
20320 * Returns true if this instance is locked, or the drag drop mgr is locked
20321 * (meaning that all drag/drop is disabled on the page.)
20323 * @return {boolean} true if this obj or all drag/drop is locked, else
20326 isLocked: function() {
20327 return (this.DDM.isLocked() || this.locked);
20331 * Fired when this object is clicked
20332 * @method handleMouseDown
20334 * @param {Roo.dd.DragDrop} oDD the clicked dd object (this dd obj)
20337 handleMouseDown: function(e, oDD){
20339 if (!Roo.isTouch && this.primaryButtonOnly && e.button != 0) {
20340 //Roo.log('not touch/ button !=0');
20343 if (e.browserEvent.touches && e.browserEvent.touches.length != 1) {
20344 return; // double touch..
20348 if (this.isLocked()) {
20349 //Roo.log('locked');
20353 this.DDM.refreshCache(this.groups);
20354 // Roo.log([Roo.lib.Event.getPageX(e), Roo.lib.Event.getPageY(e)]);
20355 var pt = new Roo.lib.Point(Roo.lib.Event.getPageX(e), Roo.lib.Event.getPageY(e));
20356 if (!this.hasOuterHandles && !this.DDM.isOverTarget(pt, this) ) {
20357 //Roo.log('no outer handes or not over target');
20360 // Roo.log('check validator');
20361 if (this.clickValidator(e)) {
20362 // Roo.log('validate success');
20363 // set the initial element position
20364 this.setStartPosition();
20367 this.b4MouseDown(e);
20368 this.onMouseDown(e);
20370 this.DDM.handleMouseDown(e, this);
20372 this.DDM.stopEvent(e);
20380 clickValidator: function(e) {
20381 var target = e.getTarget();
20382 return ( this.isValidHandleChild(target) &&
20383 (this.id == this.handleElId ||
20384 this.DDM.handleWasClicked(target, this.id)) );
20388 * Allows you to specify a tag name that should not start a drag operation
20389 * when clicked. This is designed to facilitate embedding links within a
20390 * drag handle that do something other than start the drag.
20391 * @method addInvalidHandleType
20392 * @param {string} tagName the type of element to exclude
20394 addInvalidHandleType: function(tagName) {
20395 var type = tagName.toUpperCase();
20396 this.invalidHandleTypes[type] = type;
20400 * Lets you to specify an element id for a child of a drag handle
20401 * that should not initiate a drag
20402 * @method addInvalidHandleId
20403 * @param {string} id the element id of the element you wish to ignore
20405 addInvalidHandleId: function(id) {
20406 if (typeof id !== "string") {
20409 this.invalidHandleIds[id] = id;
20413 * Lets you specify a css class of elements that will not initiate a drag
20414 * @method addInvalidHandleClass
20415 * @param {string} cssClass the class of the elements you wish to ignore
20417 addInvalidHandleClass: function(cssClass) {
20418 this.invalidHandleClasses.push(cssClass);
20422 * Unsets an excluded tag name set by addInvalidHandleType
20423 * @method removeInvalidHandleType
20424 * @param {string} tagName the type of element to unexclude
20426 removeInvalidHandleType: function(tagName) {
20427 var type = tagName.toUpperCase();
20428 // this.invalidHandleTypes[type] = null;
20429 delete this.invalidHandleTypes[type];
20433 * Unsets an invalid handle id
20434 * @method removeInvalidHandleId
20435 * @param {string} id the id of the element to re-enable
20437 removeInvalidHandleId: function(id) {
20438 if (typeof id !== "string") {
20441 delete this.invalidHandleIds[id];
20445 * Unsets an invalid css class
20446 * @method removeInvalidHandleClass
20447 * @param {string} cssClass the class of the element(s) you wish to
20450 removeInvalidHandleClass: function(cssClass) {
20451 for (var i=0, len=this.invalidHandleClasses.length; i<len; ++i) {
20452 if (this.invalidHandleClasses[i] == cssClass) {
20453 delete this.invalidHandleClasses[i];
20459 * Checks the tag exclusion list to see if this click should be ignored
20460 * @method isValidHandleChild
20461 * @param {HTMLElement} node the HTMLElement to evaluate
20462 * @return {boolean} true if this is a valid tag type, false if not
20464 isValidHandleChild: function(node) {
20467 // var n = (node.nodeName == "#text") ? node.parentNode : node;
20470 nodeName = node.nodeName.toUpperCase();
20472 nodeName = node.nodeName;
20474 valid = valid && !this.invalidHandleTypes[nodeName];
20475 valid = valid && !this.invalidHandleIds[node.id];
20477 for (var i=0, len=this.invalidHandleClasses.length; valid && i<len; ++i) {
20478 valid = !Dom.hasClass(node, this.invalidHandleClasses[i]);
20487 * Create the array of horizontal tick marks if an interval was specified
20488 * in setXConstraint().
20489 * @method setXTicks
20492 setXTicks: function(iStartX, iTickSize) {
20494 this.xTickSize = iTickSize;
20498 for (var i = this.initPageX; i >= this.minX; i = i - iTickSize) {
20500 this.xTicks[this.xTicks.length] = i;
20505 for (i = this.initPageX; i <= this.maxX; i = i + iTickSize) {
20507 this.xTicks[this.xTicks.length] = i;
20512 this.xTicks.sort(this.DDM.numericSort) ;
20516 * Create the array of vertical tick marks if an interval was specified in
20517 * setYConstraint().
20518 * @method setYTicks
20521 setYTicks: function(iStartY, iTickSize) {
20523 this.yTickSize = iTickSize;
20527 for (var i = this.initPageY; i >= this.minY; i = i - iTickSize) {
20529 this.yTicks[this.yTicks.length] = i;
20534 for (i = this.initPageY; i <= this.maxY; i = i + iTickSize) {
20536 this.yTicks[this.yTicks.length] = i;
20541 this.yTicks.sort(this.DDM.numericSort) ;
20545 * By default, the element can be dragged any place on the screen. Use
20546 * this method to limit the horizontal travel of the element. Pass in
20547 * 0,0 for the parameters if you want to lock the drag to the y axis.
20548 * @method setXConstraint
20549 * @param {int} iLeft the number of pixels the element can move to the left
20550 * @param {int} iRight the number of pixels the element can move to the
20552 * @param {int} iTickSize optional parameter for specifying that the
20554 * should move iTickSize pixels at a time.
20556 setXConstraint: function(iLeft, iRight, iTickSize) {
20557 this.leftConstraint = iLeft;
20558 this.rightConstraint = iRight;
20560 this.minX = this.initPageX - iLeft;
20561 this.maxX = this.initPageX + iRight;
20562 if (iTickSize) { this.setXTicks(this.initPageX, iTickSize); }
20564 this.constrainX = true;
20568 * Clears any constraints applied to this instance. Also clears ticks
20569 * since they can't exist independent of a constraint at this time.
20570 * @method clearConstraints
20572 clearConstraints: function() {
20573 this.constrainX = false;
20574 this.constrainY = false;
20579 * Clears any tick interval defined for this instance
20580 * @method clearTicks
20582 clearTicks: function() {
20583 this.xTicks = null;
20584 this.yTicks = null;
20585 this.xTickSize = 0;
20586 this.yTickSize = 0;
20590 * By default, the element can be dragged any place on the screen. Set
20591 * this to limit the vertical travel of the element. Pass in 0,0 for the
20592 * parameters if you want to lock the drag to the x axis.
20593 * @method setYConstraint
20594 * @param {int} iUp the number of pixels the element can move up
20595 * @param {int} iDown the number of pixels the element can move down
20596 * @param {int} iTickSize optional parameter for specifying that the
20597 * element should move iTickSize pixels at a time.
20599 setYConstraint: function(iUp, iDown, iTickSize) {
20600 this.topConstraint = iUp;
20601 this.bottomConstraint = iDown;
20603 this.minY = this.initPageY - iUp;
20604 this.maxY = this.initPageY + iDown;
20605 if (iTickSize) { this.setYTicks(this.initPageY, iTickSize); }
20607 this.constrainY = true;
20612 * resetConstraints must be called if you manually reposition a dd element.
20613 * @method resetConstraints
20614 * @param {boolean} maintainOffset
20616 resetConstraints: function() {
20619 // Maintain offsets if necessary
20620 if (this.initPageX || this.initPageX === 0) {
20621 // figure out how much this thing has moved
20622 var dx = (this.maintainOffset) ? this.lastPageX - this.initPageX : 0;
20623 var dy = (this.maintainOffset) ? this.lastPageY - this.initPageY : 0;
20625 this.setInitPosition(dx, dy);
20627 // This is the first time we have detected the element's position
20629 this.setInitPosition();
20632 if (this.constrainX) {
20633 this.setXConstraint( this.leftConstraint,
20634 this.rightConstraint,
20638 if (this.constrainY) {
20639 this.setYConstraint( this.topConstraint,
20640 this.bottomConstraint,
20646 * Normally the drag element is moved pixel by pixel, but we can specify
20647 * that it move a number of pixels at a time. This method resolves the
20648 * location when we have it set up like this.
20650 * @param {int} val where we want to place the object
20651 * @param {int[]} tickArray sorted array of valid points
20652 * @return {int} the closest tick
20655 getTick: function(val, tickArray) {
20658 // If tick interval is not defined, it is effectively 1 pixel,
20659 // so we return the value passed to us.
20661 } else if (tickArray[0] >= val) {
20662 // The value is lower than the first tick, so we return the first
20664 return tickArray[0];
20666 for (var i=0, len=tickArray.length; i<len; ++i) {
20668 if (tickArray[next] && tickArray[next] >= val) {
20669 var diff1 = val - tickArray[i];
20670 var diff2 = tickArray[next] - val;
20671 return (diff2 > diff1) ? tickArray[i] : tickArray[next];
20675 // The value is larger than the last tick, so we return the last
20677 return tickArray[tickArray.length - 1];
20684 * @return {string} string representation of the dd obj
20686 toString: function() {
20687 return ("DragDrop " + this.id);
20695 * Ext JS Library 1.1.1
20696 * Copyright(c) 2006-2007, Ext JS, LLC.
20698 * Originally Released Under LGPL - original licence link has changed is not relivant.
20701 * <script type="text/javascript">
20706 * The drag and drop utility provides a framework for building drag and drop
20707 * applications. In addition to enabling drag and drop for specific elements,
20708 * the drag and drop elements are tracked by the manager class, and the
20709 * interactions between the various elements are tracked during the drag and
20710 * the implementing code is notified about these important moments.
20713 // Only load the library once. Rewriting the manager class would orphan
20714 // existing drag and drop instances.
20715 if (!Roo.dd.DragDropMgr) {
20718 * @class Roo.dd.DragDropMgr
20719 * DragDropMgr is a singleton that tracks the element interaction for
20720 * all DragDrop items in the window. Generally, you will not call
20721 * this class directly, but it does have helper methods that could
20722 * be useful in your DragDrop implementations.
20725 Roo.dd.DragDropMgr = function() {
20727 var Event = Roo.EventManager;
20732 * Two dimensional Array of registered DragDrop objects. The first
20733 * dimension is the DragDrop item group, the second the DragDrop
20736 * @type {string: string}
20743 * Array of element ids defined as drag handles. Used to determine
20744 * if the element that generated the mousedown event is actually the
20745 * handle and not the html element itself.
20746 * @property handleIds
20747 * @type {string: string}
20754 * the DragDrop object that is currently being dragged
20755 * @property dragCurrent
20763 * the DragDrop object(s) that are being hovered over
20764 * @property dragOvers
20772 * the X distance between the cursor and the object being dragged
20781 * the Y distance between the cursor and the object being dragged
20790 * Flag to determine if we should prevent the default behavior of the
20791 * events we define. By default this is true, but this can be set to
20792 * false if you need the default behavior (not recommended)
20793 * @property preventDefault
20797 preventDefault: true,
20800 * Flag to determine if we should stop the propagation of the events
20801 * we generate. This is true by default but you may want to set it to
20802 * false if the html element contains other features that require the
20804 * @property stopPropagation
20808 stopPropagation: true,
20811 * Internal flag that is set to true when drag and drop has been
20813 * @property initialized
20820 * All drag and drop can be disabled.
20828 * Called the first time an element is registered.
20834 this.initialized = true;
20838 * In point mode, drag and drop interaction is defined by the
20839 * location of the cursor during the drag/drop
20847 * In intersect mode, drag and drop interactio nis defined by the
20848 * overlap of two or more drag and drop objects.
20849 * @property INTERSECT
20856 * The current drag and drop mode. Default: POINT
20864 * Runs method on all drag and drop objects
20865 * @method _execOnAll
20869 _execOnAll: function(sMethod, args) {
20870 for (var i in this.ids) {
20871 for (var j in this.ids[i]) {
20872 var oDD = this.ids[i][j];
20873 if (! this.isTypeOfDD(oDD)) {
20876 oDD[sMethod].apply(oDD, args);
20882 * Drag and drop initialization. Sets up the global event handlers
20887 _onLoad: function() {
20891 if (!Roo.isTouch) {
20892 Event.on(document, "mouseup", this.handleMouseUp, this, true);
20893 Event.on(document, "mousemove", this.handleMouseMove, this, true);
20895 Event.on(document, "touchend", this.handleMouseUp, this, true);
20896 Event.on(document, "touchmove", this.handleMouseMove, this, true);
20898 Event.on(window, "unload", this._onUnload, this, true);
20899 Event.on(window, "resize", this._onResize, this, true);
20900 // Event.on(window, "mouseout", this._test);
20905 * Reset constraints on all drag and drop objs
20906 * @method _onResize
20910 _onResize: function(e) {
20911 this._execOnAll("resetConstraints", []);
20915 * Lock all drag and drop functionality
20919 lock: function() { this.locked = true; },
20922 * Unlock all drag and drop functionality
20926 unlock: function() { this.locked = false; },
20929 * Is drag and drop locked?
20931 * @return {boolean} True if drag and drop is locked, false otherwise.
20934 isLocked: function() { return this.locked; },
20937 * Location cache that is set for all drag drop objects when a drag is
20938 * initiated, cleared when the drag is finished.
20939 * @property locationCache
20946 * Set useCache to false if you want to force object the lookup of each
20947 * drag and drop linked element constantly during a drag.
20948 * @property useCache
20955 * The number of pixels that the mouse needs to move after the
20956 * mousedown before the drag is initiated. Default=3;
20957 * @property clickPixelThresh
20961 clickPixelThresh: 3,
20964 * The number of milliseconds after the mousedown event to initiate the
20965 * drag if we don't get a mouseup event. Default=1000
20966 * @property clickTimeThresh
20970 clickTimeThresh: 350,
20973 * Flag that indicates that either the drag pixel threshold or the
20974 * mousdown time threshold has been met
20975 * @property dragThreshMet
20980 dragThreshMet: false,
20983 * Timeout used for the click time threshold
20984 * @property clickTimeout
20989 clickTimeout: null,
20992 * The X position of the mousedown event stored for later use when a
20993 * drag threshold is met.
21002 * The Y position of the mousedown event stored for later use when a
21003 * drag threshold is met.
21012 * Each DragDrop instance must be registered with the DragDropMgr.
21013 * This is executed in DragDrop.init()
21014 * @method regDragDrop
21015 * @param {DragDrop} oDD the DragDrop object to register
21016 * @param {String} sGroup the name of the group this element belongs to
21019 regDragDrop: function(oDD, sGroup) {
21020 if (!this.initialized) { this.init(); }
21022 if (!this.ids[sGroup]) {
21023 this.ids[sGroup] = {};
21025 this.ids[sGroup][oDD.id] = oDD;
21029 * Removes the supplied dd instance from the supplied group. Executed
21030 * by DragDrop.removeFromGroup, so don't call this function directly.
21031 * @method removeDDFromGroup
21035 removeDDFromGroup: function(oDD, sGroup) {
21036 if (!this.ids[sGroup]) {
21037 this.ids[sGroup] = {};
21040 var obj = this.ids[sGroup];
21041 if (obj && obj[oDD.id]) {
21042 delete obj[oDD.id];
21047 * Unregisters a drag and drop item. This is executed in
21048 * DragDrop.unreg, use that method instead of calling this directly.
21053 _remove: function(oDD) {
21054 for (var g in oDD.groups) {
21055 if (g && this.ids[g][oDD.id]) {
21056 delete this.ids[g][oDD.id];
21059 delete this.handleIds[oDD.id];
21063 * Each DragDrop handle element must be registered. This is done
21064 * automatically when executing DragDrop.setHandleElId()
21065 * @method regHandle
21066 * @param {String} sDDId the DragDrop id this element is a handle for
21067 * @param {String} sHandleId the id of the element that is the drag
21071 regHandle: function(sDDId, sHandleId) {
21072 if (!this.handleIds[sDDId]) {
21073 this.handleIds[sDDId] = {};
21075 this.handleIds[sDDId][sHandleId] = sHandleId;
21079 * Utility function to determine if a given element has been
21080 * registered as a drag drop item.
21081 * @method isDragDrop
21082 * @param {String} id the element id to check
21083 * @return {boolean} true if this element is a DragDrop item,
21087 isDragDrop: function(id) {
21088 return ( this.getDDById(id) ) ? true : false;
21092 * Returns the drag and drop instances that are in all groups the
21093 * passed in instance belongs to.
21094 * @method getRelated
21095 * @param {DragDrop} p_oDD the obj to get related data for
21096 * @param {boolean} bTargetsOnly if true, only return targetable objs
21097 * @return {DragDrop[]} the related instances
21100 getRelated: function(p_oDD, bTargetsOnly) {
21102 for (var i in p_oDD.groups) {
21103 for (j in this.ids[i]) {
21104 var dd = this.ids[i][j];
21105 if (! this.isTypeOfDD(dd)) {
21108 if (!bTargetsOnly || dd.isTarget) {
21109 oDDs[oDDs.length] = dd;
21118 * Returns true if the specified dd target is a legal target for
21119 * the specifice drag obj
21120 * @method isLegalTarget
21121 * @param {DragDrop} the drag obj
21122 * @param {DragDrop} the target
21123 * @return {boolean} true if the target is a legal target for the
21127 isLegalTarget: function (oDD, oTargetDD) {
21128 var targets = this.getRelated(oDD, true);
21129 for (var i=0, len=targets.length;i<len;++i) {
21130 if (targets[i].id == oTargetDD.id) {
21139 * My goal is to be able to transparently determine if an object is
21140 * typeof DragDrop, and the exact subclass of DragDrop. typeof
21141 * returns "object", oDD.constructor.toString() always returns
21142 * "DragDrop" and not the name of the subclass. So for now it just
21143 * evaluates a well-known variable in DragDrop.
21144 * @method isTypeOfDD
21145 * @param {Object} the object to evaluate
21146 * @return {boolean} true if typeof oDD = DragDrop
21149 isTypeOfDD: function (oDD) {
21150 return (oDD && oDD.__ygDragDrop);
21154 * Utility function to determine if a given element has been
21155 * registered as a drag drop handle for the given Drag Drop object.
21157 * @param {String} id the element id to check
21158 * @return {boolean} true if this element is a DragDrop handle, false
21162 isHandle: function(sDDId, sHandleId) {
21163 return ( this.handleIds[sDDId] &&
21164 this.handleIds[sDDId][sHandleId] );
21168 * Returns the DragDrop instance for a given id
21169 * @method getDDById
21170 * @param {String} id the id of the DragDrop object
21171 * @return {DragDrop} the drag drop object, null if it is not found
21174 getDDById: function(id) {
21175 for (var i in this.ids) {
21176 if (this.ids[i][id]) {
21177 return this.ids[i][id];
21184 * Fired after a registered DragDrop object gets the mousedown event.
21185 * Sets up the events required to track the object being dragged
21186 * @method handleMouseDown
21187 * @param {Event} e the event
21188 * @param oDD the DragDrop object being dragged
21192 handleMouseDown: function(e, oDD) {
21194 Roo.QuickTips.disable();
21196 this.currentTarget = e.getTarget();
21198 this.dragCurrent = oDD;
21200 var el = oDD.getEl();
21202 // track start position
21203 this.startX = e.getPageX();
21204 this.startY = e.getPageY();
21206 this.deltaX = this.startX - el.offsetLeft;
21207 this.deltaY = this.startY - el.offsetTop;
21209 this.dragThreshMet = false;
21211 this.clickTimeout = setTimeout(
21213 var DDM = Roo.dd.DDM;
21214 DDM.startDrag(DDM.startX, DDM.startY);
21216 this.clickTimeThresh );
21220 * Fired when either the drag pixel threshol or the mousedown hold
21221 * time threshold has been met.
21222 * @method startDrag
21223 * @param x {int} the X position of the original mousedown
21224 * @param y {int} the Y position of the original mousedown
21227 startDrag: function(x, y) {
21228 clearTimeout(this.clickTimeout);
21229 if (this.dragCurrent) {
21230 this.dragCurrent.b4StartDrag(x, y);
21231 this.dragCurrent.startDrag(x, y);
21233 this.dragThreshMet = true;
21237 * Internal function to handle the mouseup event. Will be invoked
21238 * from the context of the document.
21239 * @method handleMouseUp
21240 * @param {Event} e the event
21244 handleMouseUp: function(e) {
21247 Roo.QuickTips.enable();
21249 if (! this.dragCurrent) {
21253 clearTimeout(this.clickTimeout);
21255 if (this.dragThreshMet) {
21256 this.fireEvents(e, true);
21266 * Utility to stop event propagation and event default, if these
21267 * features are turned on.
21268 * @method stopEvent
21269 * @param {Event} e the event as returned by this.getEvent()
21272 stopEvent: function(e){
21273 if(this.stopPropagation) {
21274 e.stopPropagation();
21277 if (this.preventDefault) {
21278 e.preventDefault();
21283 * Internal function to clean up event handlers after the drag
21284 * operation is complete
21286 * @param {Event} e the event
21290 stopDrag: function(e) {
21291 // Fire the drag end event for the item that was dragged
21292 if (this.dragCurrent) {
21293 if (this.dragThreshMet) {
21294 this.dragCurrent.b4EndDrag(e);
21295 this.dragCurrent.endDrag(e);
21298 this.dragCurrent.onMouseUp(e);
21301 this.dragCurrent = null;
21302 this.dragOvers = {};
21306 * Internal function to handle the mousemove event. Will be invoked
21307 * from the context of the html element.
21309 * @TODO figure out what we can do about mouse events lost when the
21310 * user drags objects beyond the window boundary. Currently we can
21311 * detect this in internet explorer by verifying that the mouse is
21312 * down during the mousemove event. Firefox doesn't give us the
21313 * button state on the mousemove event.
21314 * @method handleMouseMove
21315 * @param {Event} e the event
21319 handleMouseMove: function(e) {
21320 if (! this.dragCurrent) {
21324 // var button = e.which || e.button;
21326 // check for IE mouseup outside of page boundary
21327 if (Roo.isIE && (e.button !== 0 && e.button !== 1 && e.button !== 2)) {
21329 return this.handleMouseUp(e);
21332 if (!this.dragThreshMet) {
21333 var diffX = Math.abs(this.startX - e.getPageX());
21334 var diffY = Math.abs(this.startY - e.getPageY());
21335 if (diffX > this.clickPixelThresh ||
21336 diffY > this.clickPixelThresh) {
21337 this.startDrag(this.startX, this.startY);
21341 if (this.dragThreshMet) {
21342 this.dragCurrent.b4Drag(e);
21343 this.dragCurrent.onDrag(e);
21344 if(!this.dragCurrent.moveOnly){
21345 this.fireEvents(e, false);
21355 * Iterates over all of the DragDrop elements to find ones we are
21356 * hovering over or dropping on
21357 * @method fireEvents
21358 * @param {Event} e the event
21359 * @param {boolean} isDrop is this a drop op or a mouseover op?
21363 fireEvents: function(e, isDrop) {
21364 var dc = this.dragCurrent;
21366 // If the user did the mouse up outside of the window, we could
21367 // get here even though we have ended the drag.
21368 if (!dc || dc.isLocked()) {
21372 var pt = e.getPoint();
21374 // cache the previous dragOver array
21380 var enterEvts = [];
21382 // Check to see if the object(s) we were hovering over is no longer
21383 // being hovered over so we can fire the onDragOut event
21384 for (var i in this.dragOvers) {
21386 var ddo = this.dragOvers[i];
21388 if (! this.isTypeOfDD(ddo)) {
21392 if (! this.isOverTarget(pt, ddo, this.mode)) {
21393 outEvts.push( ddo );
21396 oldOvers[i] = true;
21397 delete this.dragOvers[i];
21400 for (var sGroup in dc.groups) {
21402 if ("string" != typeof sGroup) {
21406 for (i in this.ids[sGroup]) {
21407 var oDD = this.ids[sGroup][i];
21408 if (! this.isTypeOfDD(oDD)) {
21412 if (oDD.isTarget && !oDD.isLocked() && oDD != dc) {
21413 if (this.isOverTarget(pt, oDD, this.mode)) {
21414 // look for drop interactions
21416 dropEvts.push( oDD );
21417 // look for drag enter and drag over interactions
21420 // initial drag over: dragEnter fires
21421 if (!oldOvers[oDD.id]) {
21422 enterEvts.push( oDD );
21423 // subsequent drag overs: dragOver fires
21425 overEvts.push( oDD );
21428 this.dragOvers[oDD.id] = oDD;
21436 if (outEvts.length) {
21437 dc.b4DragOut(e, outEvts);
21438 dc.onDragOut(e, outEvts);
21441 if (enterEvts.length) {
21442 dc.onDragEnter(e, enterEvts);
21445 if (overEvts.length) {
21446 dc.b4DragOver(e, overEvts);
21447 dc.onDragOver(e, overEvts);
21450 if (dropEvts.length) {
21451 dc.b4DragDrop(e, dropEvts);
21452 dc.onDragDrop(e, dropEvts);
21456 // fire dragout events
21458 for (i=0, len=outEvts.length; i<len; ++i) {
21459 dc.b4DragOut(e, outEvts[i].id);
21460 dc.onDragOut(e, outEvts[i].id);
21463 // fire enter events
21464 for (i=0,len=enterEvts.length; i<len; ++i) {
21465 // dc.b4DragEnter(e, oDD.id);
21466 dc.onDragEnter(e, enterEvts[i].id);
21469 // fire over events
21470 for (i=0,len=overEvts.length; i<len; ++i) {
21471 dc.b4DragOver(e, overEvts[i].id);
21472 dc.onDragOver(e, overEvts[i].id);
21475 // fire drop events
21476 for (i=0, len=dropEvts.length; i<len; ++i) {
21477 dc.b4DragDrop(e, dropEvts[i].id);
21478 dc.onDragDrop(e, dropEvts[i].id);
21483 // notify about a drop that did not find a target
21484 if (isDrop && !dropEvts.length) {
21485 dc.onInvalidDrop(e);
21491 * Helper function for getting the best match from the list of drag
21492 * and drop objects returned by the drag and drop events when we are
21493 * in INTERSECT mode. It returns either the first object that the
21494 * cursor is over, or the object that has the greatest overlap with
21495 * the dragged element.
21496 * @method getBestMatch
21497 * @param {DragDrop[]} dds The array of drag and drop objects
21499 * @return {DragDrop} The best single match
21502 getBestMatch: function(dds) {
21504 // Return null if the input is not what we expect
21505 //if (!dds || !dds.length || dds.length == 0) {
21507 // If there is only one item, it wins
21508 //} else if (dds.length == 1) {
21510 var len = dds.length;
21515 // Loop through the targeted items
21516 for (var i=0; i<len; ++i) {
21518 // If the cursor is over the object, it wins. If the
21519 // cursor is over multiple matches, the first one we come
21521 if (dd.cursorIsOver) {
21524 // Otherwise the object with the most overlap wins
21527 winner.overlap.getArea() < dd.overlap.getArea()) {
21538 * Refreshes the cache of the top-left and bottom-right points of the
21539 * drag and drop objects in the specified group(s). This is in the
21540 * format that is stored in the drag and drop instance, so typical
21543 * Roo.dd.DragDropMgr.refreshCache(ddinstance.groups);
21547 * Roo.dd.DragDropMgr.refreshCache({group1:true, group2:true});
21549 * @TODO this really should be an indexed array. Alternatively this
21550 * method could accept both.
21551 * @method refreshCache
21552 * @param {Object} groups an associative array of groups to refresh
21555 refreshCache: function(groups) {
21556 for (var sGroup in groups) {
21557 if ("string" != typeof sGroup) {
21560 for (var i in this.ids[sGroup]) {
21561 var oDD = this.ids[sGroup][i];
21563 if (this.isTypeOfDD(oDD)) {
21564 // if (this.isTypeOfDD(oDD) && oDD.isTarget) {
21565 var loc = this.getLocation(oDD);
21567 this.locationCache[oDD.id] = loc;
21569 delete this.locationCache[oDD.id];
21570 // this will unregister the drag and drop object if
21571 // the element is not in a usable state
21580 * This checks to make sure an element exists and is in the DOM. The
21581 * main purpose is to handle cases where innerHTML is used to remove
21582 * drag and drop objects from the DOM. IE provides an 'unspecified
21583 * error' when trying to access the offsetParent of such an element
21585 * @param {HTMLElement} el the element to check
21586 * @return {boolean} true if the element looks usable
21589 verifyEl: function(el) {
21594 parent = el.offsetParent;
21597 parent = el.offsetParent;
21608 * Returns a Region object containing the drag and drop element's position
21609 * and size, including the padding configured for it
21610 * @method getLocation
21611 * @param {DragDrop} oDD the drag and drop object to get the
21613 * @return {Roo.lib.Region} a Region object representing the total area
21614 * the element occupies, including any padding
21615 * the instance is configured for.
21618 getLocation: function(oDD) {
21619 if (! this.isTypeOfDD(oDD)) {
21623 var el = oDD.getEl(), pos, x1, x2, y1, y2, t, r, b, l;
21626 pos= Roo.lib.Dom.getXY(el);
21634 x2 = x1 + el.offsetWidth;
21636 y2 = y1 + el.offsetHeight;
21638 t = y1 - oDD.padding[0];
21639 r = x2 + oDD.padding[1];
21640 b = y2 + oDD.padding[2];
21641 l = x1 - oDD.padding[3];
21643 return new Roo.lib.Region( t, r, b, l );
21647 * Checks the cursor location to see if it over the target
21648 * @method isOverTarget
21649 * @param {Roo.lib.Point} pt The point to evaluate
21650 * @param {DragDrop} oTarget the DragDrop object we are inspecting
21651 * @return {boolean} true if the mouse is over the target
21655 isOverTarget: function(pt, oTarget, intersect) {
21656 // use cache if available
21657 var loc = this.locationCache[oTarget.id];
21658 if (!loc || !this.useCache) {
21659 loc = this.getLocation(oTarget);
21660 this.locationCache[oTarget.id] = loc;
21668 oTarget.cursorIsOver = loc.contains( pt );
21670 // DragDrop is using this as a sanity check for the initial mousedown
21671 // in this case we are done. In POINT mode, if the drag obj has no
21672 // contraints, we are also done. Otherwise we need to evaluate the
21673 // location of the target as related to the actual location of the
21674 // dragged element.
21675 var dc = this.dragCurrent;
21676 if (!dc || !dc.getTargetCoord ||
21677 (!intersect && !dc.constrainX && !dc.constrainY)) {
21678 return oTarget.cursorIsOver;
21681 oTarget.overlap = null;
21683 // Get the current location of the drag element, this is the
21684 // location of the mouse event less the delta that represents
21685 // where the original mousedown happened on the element. We
21686 // need to consider constraints and ticks as well.
21687 var pos = dc.getTargetCoord(pt.x, pt.y);
21689 var el = dc.getDragEl();
21690 var curRegion = new Roo.lib.Region( pos.y,
21691 pos.x + el.offsetWidth,
21692 pos.y + el.offsetHeight,
21695 var overlap = curRegion.intersect(loc);
21698 oTarget.overlap = overlap;
21699 return (intersect) ? true : oTarget.cursorIsOver;
21706 * unload event handler
21707 * @method _onUnload
21711 _onUnload: function(e, me) {
21712 Roo.dd.DragDropMgr.unregAll();
21716 * Cleans up the drag and drop events and objects.
21721 unregAll: function() {
21723 if (this.dragCurrent) {
21725 this.dragCurrent = null;
21728 this._execOnAll("unreg", []);
21730 for (i in this.elementCache) {
21731 delete this.elementCache[i];
21734 this.elementCache = {};
21739 * A cache of DOM elements
21740 * @property elementCache
21747 * Get the wrapper for the DOM element specified
21748 * @method getElWrapper
21749 * @param {String} id the id of the element to get
21750 * @return {Roo.dd.DDM.ElementWrapper} the wrapped element
21752 * @deprecated This wrapper isn't that useful
21755 getElWrapper: function(id) {
21756 var oWrapper = this.elementCache[id];
21757 if (!oWrapper || !oWrapper.el) {
21758 oWrapper = this.elementCache[id] =
21759 new this.ElementWrapper(Roo.getDom(id));
21765 * Returns the actual DOM element
21766 * @method getElement
21767 * @param {String} id the id of the elment to get
21768 * @return {Object} The element
21769 * @deprecated use Roo.getDom instead
21772 getElement: function(id) {
21773 return Roo.getDom(id);
21777 * Returns the style property for the DOM element (i.e.,
21778 * document.getElById(id).style)
21780 * @param {String} id the id of the elment to get
21781 * @return {Object} The style property of the element
21782 * @deprecated use Roo.getDom instead
21785 getCss: function(id) {
21786 var el = Roo.getDom(id);
21787 return (el) ? el.style : null;
21791 * Inner class for cached elements
21792 * @class DragDropMgr.ElementWrapper
21797 ElementWrapper: function(el) {
21802 this.el = el || null;
21807 this.id = this.el && el.id;
21809 * A reference to the style property
21812 this.css = this.el && el.style;
21816 * Returns the X position of an html element
21818 * @param el the element for which to get the position
21819 * @return {int} the X coordinate
21821 * @deprecated use Roo.lib.Dom.getX instead
21824 getPosX: function(el) {
21825 return Roo.lib.Dom.getX(el);
21829 * Returns the Y position of an html element
21831 * @param el the element for which to get the position
21832 * @return {int} the Y coordinate
21833 * @deprecated use Roo.lib.Dom.getY instead
21836 getPosY: function(el) {
21837 return Roo.lib.Dom.getY(el);
21841 * Swap two nodes. In IE, we use the native method, for others we
21842 * emulate the IE behavior
21844 * @param n1 the first node to swap
21845 * @param n2 the other node to swap
21848 swapNode: function(n1, n2) {
21852 var p = n2.parentNode;
21853 var s = n2.nextSibling;
21856 p.insertBefore(n1, n2);
21857 } else if (n2 == n1.nextSibling) {
21858 p.insertBefore(n2, n1);
21860 n1.parentNode.replaceChild(n2, n1);
21861 p.insertBefore(n1, s);
21867 * Returns the current scroll position
21868 * @method getScroll
21872 getScroll: function () {
21873 var t, l, dde=document.documentElement, db=document.body;
21874 if (dde && (dde.scrollTop || dde.scrollLeft)) {
21876 l = dde.scrollLeft;
21883 return { top: t, left: l };
21887 * Returns the specified element style property
21889 * @param {HTMLElement} el the element
21890 * @param {string} styleProp the style property
21891 * @return {string} The value of the style property
21892 * @deprecated use Roo.lib.Dom.getStyle
21895 getStyle: function(el, styleProp) {
21896 return Roo.fly(el).getStyle(styleProp);
21900 * Gets the scrollTop
21901 * @method getScrollTop
21902 * @return {int} the document's scrollTop
21905 getScrollTop: function () { return this.getScroll().top; },
21908 * Gets the scrollLeft
21909 * @method getScrollLeft
21910 * @return {int} the document's scrollTop
21913 getScrollLeft: function () { return this.getScroll().left; },
21916 * Sets the x/y position of an element to the location of the
21919 * @param {HTMLElement} moveEl The element to move
21920 * @param {HTMLElement} targetEl The position reference element
21923 moveToEl: function (moveEl, targetEl) {
21924 var aCoord = Roo.lib.Dom.getXY(targetEl);
21925 Roo.lib.Dom.setXY(moveEl, aCoord);
21929 * Numeric array sort function
21930 * @method numericSort
21933 numericSort: function(a, b) { return (a - b); },
21937 * @property _timeoutCount
21944 * Trying to make the load order less important. Without this we get
21945 * an error if this file is loaded before the Event Utility.
21946 * @method _addListeners
21950 _addListeners: function() {
21951 var DDM = Roo.dd.DDM;
21952 if ( Roo.lib.Event && document ) {
21955 if (DDM._timeoutCount > 2000) {
21957 setTimeout(DDM._addListeners, 10);
21958 if (document && document.body) {
21959 DDM._timeoutCount += 1;
21966 * Recursively searches the immediate parent and all child nodes for
21967 * the handle element in order to determine wheter or not it was
21969 * @method handleWasClicked
21970 * @param node the html element to inspect
21973 handleWasClicked: function(node, id) {
21974 if (this.isHandle(id, node.id)) {
21977 // check to see if this is a text node child of the one we want
21978 var p = node.parentNode;
21981 if (this.isHandle(id, p.id)) {
21996 // shorter alias, save a few bytes
21997 Roo.dd.DDM = Roo.dd.DragDropMgr;
21998 Roo.dd.DDM._addListeners();
22002 * Ext JS Library 1.1.1
22003 * Copyright(c) 2006-2007, Ext JS, LLC.
22005 * Originally Released Under LGPL - original licence link has changed is not relivant.
22008 * <script type="text/javascript">
22013 * A DragDrop implementation where the linked element follows the
22014 * mouse cursor during a drag.
22015 * @extends Roo.dd.DragDrop
22017 * @param {String} id the id of the linked element
22018 * @param {String} sGroup the group of related DragDrop items
22019 * @param {object} config an object containing configurable attributes
22020 * Valid properties for DD:
22023 Roo.dd.DD = function(id, sGroup, config) {
22025 this.init(id, sGroup, config);
22029 Roo.extend(Roo.dd.DD, Roo.dd.DragDrop, {
22032 * When set to true, the utility automatically tries to scroll the browser
22033 * window wehn a drag and drop element is dragged near the viewport boundary.
22034 * Defaults to true.
22041 * Sets the pointer offset to the distance between the linked element's top
22042 * left corner and the location the element was clicked
22043 * @method autoOffset
22044 * @param {int} iPageX the X coordinate of the click
22045 * @param {int} iPageY the Y coordinate of the click
22047 autoOffset: function(iPageX, iPageY) {
22048 var x = iPageX - this.startPageX;
22049 var y = iPageY - this.startPageY;
22050 this.setDelta(x, y);
22054 * Sets the pointer offset. You can call this directly to force the
22055 * offset to be in a particular location (e.g., pass in 0,0 to set it
22056 * to the center of the object)
22058 * @param {int} iDeltaX the distance from the left
22059 * @param {int} iDeltaY the distance from the top
22061 setDelta: function(iDeltaX, iDeltaY) {
22062 this.deltaX = iDeltaX;
22063 this.deltaY = iDeltaY;
22067 * Sets the drag element to the location of the mousedown or click event,
22068 * maintaining the cursor location relative to the location on the element
22069 * that was clicked. Override this if you want to place the element in a
22070 * location other than where the cursor is.
22071 * @method setDragElPos
22072 * @param {int} iPageX the X coordinate of the mousedown or drag event
22073 * @param {int} iPageY the Y coordinate of the mousedown or drag event
22075 setDragElPos: function(iPageX, iPageY) {
22076 // the first time we do this, we are going to check to make sure
22077 // the element has css positioning
22079 var el = this.getDragEl();
22080 this.alignElWithMouse(el, iPageX, iPageY);
22084 * Sets the element to the location of the mousedown or click event,
22085 * maintaining the cursor location relative to the location on the element
22086 * that was clicked. Override this if you want to place the element in a
22087 * location other than where the cursor is.
22088 * @method alignElWithMouse
22089 * @param {HTMLElement} el the element to move
22090 * @param {int} iPageX the X coordinate of the mousedown or drag event
22091 * @param {int} iPageY the Y coordinate of the mousedown or drag event
22093 alignElWithMouse: function(el, iPageX, iPageY) {
22094 var oCoord = this.getTargetCoord(iPageX, iPageY);
22095 var fly = el.dom ? el : Roo.fly(el);
22096 if (!this.deltaSetXY) {
22097 var aCoord = [oCoord.x, oCoord.y];
22099 var newLeft = fly.getLeft(true);
22100 var newTop = fly.getTop(true);
22101 this.deltaSetXY = [ newLeft - oCoord.x, newTop - oCoord.y ];
22103 fly.setLeftTop(oCoord.x + this.deltaSetXY[0], oCoord.y + this.deltaSetXY[1]);
22106 this.cachePosition(oCoord.x, oCoord.y);
22107 this.autoScroll(oCoord.x, oCoord.y, el.offsetHeight, el.offsetWidth);
22112 * Saves the most recent position so that we can reset the constraints and
22113 * tick marks on-demand. We need to know this so that we can calculate the
22114 * number of pixels the element is offset from its original position.
22115 * @method cachePosition
22116 * @param iPageX the current x position (optional, this just makes it so we
22117 * don't have to look it up again)
22118 * @param iPageY the current y position (optional, this just makes it so we
22119 * don't have to look it up again)
22121 cachePosition: function(iPageX, iPageY) {
22123 this.lastPageX = iPageX;
22124 this.lastPageY = iPageY;
22126 var aCoord = Roo.lib.Dom.getXY(this.getEl());
22127 this.lastPageX = aCoord[0];
22128 this.lastPageY = aCoord[1];
22133 * Auto-scroll the window if the dragged object has been moved beyond the
22134 * visible window boundary.
22135 * @method autoScroll
22136 * @param {int} x the drag element's x position
22137 * @param {int} y the drag element's y position
22138 * @param {int} h the height of the drag element
22139 * @param {int} w the width of the drag element
22142 autoScroll: function(x, y, h, w) {
22145 // The client height
22146 var clientH = Roo.lib.Dom.getViewWidth();
22148 // The client width
22149 var clientW = Roo.lib.Dom.getViewHeight();
22151 // The amt scrolled down
22152 var st = this.DDM.getScrollTop();
22154 // The amt scrolled right
22155 var sl = this.DDM.getScrollLeft();
22157 // Location of the bottom of the element
22160 // Location of the right of the element
22163 // The distance from the cursor to the bottom of the visible area,
22164 // adjusted so that we don't scroll if the cursor is beyond the
22165 // element drag constraints
22166 var toBot = (clientH + st - y - this.deltaY);
22168 // The distance from the cursor to the right of the visible area
22169 var toRight = (clientW + sl - x - this.deltaX);
22172 // How close to the edge the cursor must be before we scroll
22173 // var thresh = (document.all) ? 100 : 40;
22176 // How many pixels to scroll per autoscroll op. This helps to reduce
22177 // clunky scrolling. IE is more sensitive about this ... it needs this
22178 // value to be higher.
22179 var scrAmt = (document.all) ? 80 : 30;
22181 // Scroll down if we are near the bottom of the visible page and the
22182 // obj extends below the crease
22183 if ( bot > clientH && toBot < thresh ) {
22184 window.scrollTo(sl, st + scrAmt);
22187 // Scroll up if the window is scrolled down and the top of the object
22188 // goes above the top border
22189 if ( y < st && st > 0 && y - st < thresh ) {
22190 window.scrollTo(sl, st - scrAmt);
22193 // Scroll right if the obj is beyond the right border and the cursor is
22194 // near the border.
22195 if ( right > clientW && toRight < thresh ) {
22196 window.scrollTo(sl + scrAmt, st);
22199 // Scroll left if the window has been scrolled to the right and the obj
22200 // extends past the left border
22201 if ( x < sl && sl > 0 && x - sl < thresh ) {
22202 window.scrollTo(sl - scrAmt, st);
22208 * Finds the location the element should be placed if we want to move
22209 * it to where the mouse location less the click offset would place us.
22210 * @method getTargetCoord
22211 * @param {int} iPageX the X coordinate of the click
22212 * @param {int} iPageY the Y coordinate of the click
22213 * @return an object that contains the coordinates (Object.x and Object.y)
22216 getTargetCoord: function(iPageX, iPageY) {
22219 var x = iPageX - this.deltaX;
22220 var y = iPageY - this.deltaY;
22222 if (this.constrainX) {
22223 if (x < this.minX) { x = this.minX; }
22224 if (x > this.maxX) { x = this.maxX; }
22227 if (this.constrainY) {
22228 if (y < this.minY) { y = this.minY; }
22229 if (y > this.maxY) { y = this.maxY; }
22232 x = this.getTick(x, this.xTicks);
22233 y = this.getTick(y, this.yTicks);
22240 * Sets up config options specific to this class. Overrides
22241 * Roo.dd.DragDrop, but all versions of this method through the
22242 * inheritance chain are called
22244 applyConfig: function() {
22245 Roo.dd.DD.superclass.applyConfig.call(this);
22246 this.scroll = (this.config.scroll !== false);
22250 * Event that fires prior to the onMouseDown event. Overrides
22253 b4MouseDown: function(e) {
22254 // this.resetConstraints();
22255 this.autoOffset(e.getPageX(),
22260 * Event that fires prior to the onDrag event. Overrides
22263 b4Drag: function(e) {
22264 this.setDragElPos(e.getPageX(),
22268 toString: function() {
22269 return ("DD " + this.id);
22272 //////////////////////////////////////////////////////////////////////////
22273 // Debugging ygDragDrop events that can be overridden
22274 //////////////////////////////////////////////////////////////////////////
22276 startDrag: function(x, y) {
22279 onDrag: function(e) {
22282 onDragEnter: function(e, id) {
22285 onDragOver: function(e, id) {
22288 onDragOut: function(e, id) {
22291 onDragDrop: function(e, id) {
22294 endDrag: function(e) {
22301 * Ext JS Library 1.1.1
22302 * Copyright(c) 2006-2007, Ext JS, LLC.
22304 * Originally Released Under LGPL - original licence link has changed is not relivant.
22307 * <script type="text/javascript">
22311 * @class Roo.dd.DDProxy
22312 * A DragDrop implementation that inserts an empty, bordered div into
22313 * the document that follows the cursor during drag operations. At the time of
22314 * the click, the frame div is resized to the dimensions of the linked html
22315 * element, and moved to the exact location of the linked element.
22317 * References to the "frame" element refer to the single proxy element that
22318 * was created to be dragged in place of all DDProxy elements on the
22321 * @extends Roo.dd.DD
22323 * @param {String} id the id of the linked html element
22324 * @param {String} sGroup the group of related DragDrop objects
22325 * @param {object} config an object containing configurable attributes
22326 * Valid properties for DDProxy in addition to those in DragDrop:
22327 * resizeFrame, centerFrame, dragElId
22329 Roo.dd.DDProxy = function(id, sGroup, config) {
22331 this.init(id, sGroup, config);
22337 * The default drag frame div id
22338 * @property Roo.dd.DDProxy.dragElId
22342 Roo.dd.DDProxy.dragElId = "ygddfdiv";
22344 Roo.extend(Roo.dd.DDProxy, Roo.dd.DD, {
22347 * By default we resize the drag frame to be the same size as the element
22348 * we want to drag (this is to get the frame effect). We can turn it off
22349 * if we want a different behavior.
22350 * @property resizeFrame
22356 * By default the frame is positioned exactly where the drag element is, so
22357 * we use the cursor offset provided by Roo.dd.DD. Another option that works only if
22358 * you do not have constraints on the obj is to have the drag frame centered
22359 * around the cursor. Set centerFrame to true for this effect.
22360 * @property centerFrame
22363 centerFrame: false,
22366 * Creates the proxy element if it does not yet exist
22367 * @method createFrame
22369 createFrame: function() {
22371 var body = document.body;
22373 if (!body || !body.firstChild) {
22374 setTimeout( function() { self.createFrame(); }, 50 );
22378 var div = this.getDragEl();
22381 div = document.createElement("div");
22382 div.id = this.dragElId;
22385 s.position = "absolute";
22386 s.visibility = "hidden";
22388 s.border = "2px solid #aaa";
22391 // appendChild can blow up IE if invoked prior to the window load event
22392 // while rendering a table. It is possible there are other scenarios
22393 // that would cause this to happen as well.
22394 body.insertBefore(div, body.firstChild);
22399 * Initialization for the drag frame element. Must be called in the
22400 * constructor of all subclasses
22401 * @method initFrame
22403 initFrame: function() {
22404 this.createFrame();
22407 applyConfig: function() {
22408 Roo.dd.DDProxy.superclass.applyConfig.call(this);
22410 this.resizeFrame = (this.config.resizeFrame !== false);
22411 this.centerFrame = (this.config.centerFrame);
22412 this.setDragElId(this.config.dragElId || Roo.dd.DDProxy.dragElId);
22416 * Resizes the drag frame to the dimensions of the clicked object, positions
22417 * it over the object, and finally displays it
22418 * @method showFrame
22419 * @param {int} iPageX X click position
22420 * @param {int} iPageY Y click position
22423 showFrame: function(iPageX, iPageY) {
22424 var el = this.getEl();
22425 var dragEl = this.getDragEl();
22426 var s = dragEl.style;
22428 this._resizeProxy();
22430 if (this.centerFrame) {
22431 this.setDelta( Math.round(parseInt(s.width, 10)/2),
22432 Math.round(parseInt(s.height, 10)/2) );
22435 this.setDragElPos(iPageX, iPageY);
22437 Roo.fly(dragEl).show();
22441 * The proxy is automatically resized to the dimensions of the linked
22442 * element when a drag is initiated, unless resizeFrame is set to false
22443 * @method _resizeProxy
22446 _resizeProxy: function() {
22447 if (this.resizeFrame) {
22448 var el = this.getEl();
22449 Roo.fly(this.getDragEl()).setSize(el.offsetWidth, el.offsetHeight);
22453 // overrides Roo.dd.DragDrop
22454 b4MouseDown: function(e) {
22455 var x = e.getPageX();
22456 var y = e.getPageY();
22457 this.autoOffset(x, y);
22458 this.setDragElPos(x, y);
22461 // overrides Roo.dd.DragDrop
22462 b4StartDrag: function(x, y) {
22463 // show the drag frame
22464 this.showFrame(x, y);
22467 // overrides Roo.dd.DragDrop
22468 b4EndDrag: function(e) {
22469 Roo.fly(this.getDragEl()).hide();
22472 // overrides Roo.dd.DragDrop
22473 // By default we try to move the element to the last location of the frame.
22474 // This is so that the default behavior mirrors that of Roo.dd.DD.
22475 endDrag: function(e) {
22477 var lel = this.getEl();
22478 var del = this.getDragEl();
22480 // Show the drag frame briefly so we can get its position
22481 del.style.visibility = "";
22484 // Hide the linked element before the move to get around a Safari
22486 lel.style.visibility = "hidden";
22487 Roo.dd.DDM.moveToEl(lel, del);
22488 del.style.visibility = "hidden";
22489 lel.style.visibility = "";
22494 beforeMove : function(){
22498 afterDrag : function(){
22502 toString: function() {
22503 return ("DDProxy " + this.id);
22509 * Ext JS Library 1.1.1
22510 * Copyright(c) 2006-2007, Ext JS, LLC.
22512 * Originally Released Under LGPL - original licence link has changed is not relivant.
22515 * <script type="text/javascript">
22519 * @class Roo.dd.DDTarget
22520 * A DragDrop implementation that does not move, but can be a drop
22521 * target. You would get the same result by simply omitting implementation
22522 * for the event callbacks, but this way we reduce the processing cost of the
22523 * event listener and the callbacks.
22524 * @extends Roo.dd.DragDrop
22526 * @param {String} id the id of the element that is a drop target
22527 * @param {String} sGroup the group of related DragDrop objects
22528 * @param {object} config an object containing configurable attributes
22529 * Valid properties for DDTarget in addition to those in
22533 Roo.dd.DDTarget = function(id, sGroup, config) {
22535 this.initTarget(id, sGroup, config);
22537 if (config && (config.listeners || config.events)) {
22538 Roo.dd.DragDrop.superclass.constructor.call(this, {
22539 listeners : config.listeners || {},
22540 events : config.events || {}
22545 // Roo.dd.DDTarget.prototype = new Roo.dd.DragDrop();
22546 Roo.extend(Roo.dd.DDTarget, Roo.dd.DragDrop, {
22547 toString: function() {
22548 return ("DDTarget " + this.id);
22553 * Ext JS Library 1.1.1
22554 * Copyright(c) 2006-2007, Ext JS, LLC.
22556 * Originally Released Under LGPL - original licence link has changed is not relivant.
22559 * <script type="text/javascript">
22564 * @class Roo.dd.ScrollManager
22565 * Provides automatic scrolling of overflow regions in the page during drag operations.<br><br>
22566 * <b>Note: This class uses "Point Mode" and is untested in "Intersect Mode".</b>
22569 Roo.dd.ScrollManager = function(){
22570 var ddm = Roo.dd.DragDropMgr;
22577 var onStop = function(e){
22582 var triggerRefresh = function(){
22583 if(ddm.dragCurrent){
22584 ddm.refreshCache(ddm.dragCurrent.groups);
22588 var doScroll = function(){
22589 if(ddm.dragCurrent){
22590 var dds = Roo.dd.ScrollManager;
22592 if(proc.el.scroll(proc.dir, dds.increment)){
22596 proc.el.scroll(proc.dir, dds.increment, true, dds.animDuration, triggerRefresh);
22601 var clearProc = function(){
22603 clearInterval(proc.id);
22610 var startProc = function(el, dir){
22611 Roo.log('scroll startproc');
22615 proc.id = setInterval(doScroll, Roo.dd.ScrollManager.frequency);
22618 var onFire = function(e, isDrop){
22620 if(isDrop || !ddm.dragCurrent){ return; }
22621 var dds = Roo.dd.ScrollManager;
22622 if(!dragEl || dragEl != ddm.dragCurrent){
22623 dragEl = ddm.dragCurrent;
22624 // refresh regions on drag start
22625 dds.refreshCache();
22628 var xy = Roo.lib.Event.getXY(e);
22629 var pt = new Roo.lib.Point(xy[0], xy[1]);
22630 for(var id in els){
22631 var el = els[id], r = el._region;
22632 if(r && r.contains(pt) && el.isScrollable()){
22633 if(r.bottom - pt.y <= dds.thresh){
22635 startProc(el, "down");
22638 }else if(r.right - pt.x <= dds.thresh){
22640 startProc(el, "left");
22643 }else if(pt.y - r.top <= dds.thresh){
22645 startProc(el, "up");
22648 }else if(pt.x - r.left <= dds.thresh){
22650 startProc(el, "right");
22659 ddm.fireEvents = ddm.fireEvents.createSequence(onFire, ddm);
22660 ddm.stopDrag = ddm.stopDrag.createSequence(onStop, ddm);
22664 * Registers new overflow element(s) to auto scroll
22665 * @param {String/HTMLElement/Element/Array} el The id of or the element to be scrolled or an array of either
22667 register : function(el){
22668 if(el instanceof Array){
22669 for(var i = 0, len = el.length; i < len; i++) {
22670 this.register(el[i]);
22676 Roo.dd.ScrollManager.els = els;
22680 * Unregisters overflow element(s) so they are no longer scrolled
22681 * @param {String/HTMLElement/Element/Array} el The id of or the element to be removed or an array of either
22683 unregister : function(el){
22684 if(el instanceof Array){
22685 for(var i = 0, len = el.length; i < len; i++) {
22686 this.unregister(el[i]);
22695 * The number of pixels from the edge of a container the pointer needs to be to
22696 * trigger scrolling (defaults to 25)
22702 * The number of pixels to scroll in each scroll increment (defaults to 50)
22708 * The frequency of scrolls in milliseconds (defaults to 500)
22714 * True to animate the scroll (defaults to true)
22720 * The animation duration in seconds -
22721 * MUST BE less than Roo.dd.ScrollManager.frequency! (defaults to .4)
22727 * Manually trigger a cache refresh.
22729 refreshCache : function(){
22730 for(var id in els){
22731 if(typeof els[id] == 'object'){ // for people extending the object prototype
22732 els[id]._region = els[id].getRegion();
22739 * Ext JS Library 1.1.1
22740 * Copyright(c) 2006-2007, Ext JS, LLC.
22742 * Originally Released Under LGPL - original licence link has changed is not relivant.
22745 * <script type="text/javascript">
22750 * @class Roo.dd.Registry
22751 * Provides easy access to all drag drop components that are registered on a page. Items can be retrieved either
22752 * directly by DOM node id, or by passing in the drag drop event that occurred and looking up the event target.
22755 Roo.dd.Registry = function(){
22758 var autoIdSeed = 0;
22760 var getId = function(el, autogen){
22761 if(typeof el == "string"){
22765 if(!id && autogen !== false){
22766 id = "roodd-" + (++autoIdSeed);
22774 * Register a drag drop element
22775 * @param {String|HTMLElement} element The id or DOM node to register
22776 * @param {Object} data (optional) A custom data object that will be passed between the elements that are involved
22777 * in drag drop operations. You can populate this object with any arbitrary properties that your own code
22778 * knows how to interpret, plus there are some specific properties known to the Registry that should be
22779 * populated in the data object (if applicable):
22781 Value Description<br />
22782 --------- ------------------------------------------<br />
22783 handles Array of DOM nodes that trigger dragging<br />
22784 for the element being registered<br />
22785 isHandle True if the element passed in triggers<br />
22786 dragging itself, else false
22789 register : function(el, data){
22791 if(typeof el == "string"){
22792 el = document.getElementById(el);
22795 elements[getId(el)] = data;
22796 if(data.isHandle !== false){
22797 handles[data.ddel.id] = data;
22800 var hs = data.handles;
22801 for(var i = 0, len = hs.length; i < len; i++){
22802 handles[getId(hs[i])] = data;
22808 * Unregister a drag drop element
22809 * @param {String|HTMLElement} element The id or DOM node to unregister
22811 unregister : function(el){
22812 var id = getId(el, false);
22813 var data = elements[id];
22815 delete elements[id];
22817 var hs = data.handles;
22818 for(var i = 0, len = hs.length; i < len; i++){
22819 delete handles[getId(hs[i], false)];
22826 * Returns the handle registered for a DOM Node by id
22827 * @param {String|HTMLElement} id The DOM node or id to look up
22828 * @return {Object} handle The custom handle data
22830 getHandle : function(id){
22831 if(typeof id != "string"){ // must be element?
22834 return handles[id];
22838 * Returns the handle that is registered for the DOM node that is the target of the event
22839 * @param {Event} e The event
22840 * @return {Object} handle The custom handle data
22842 getHandleFromEvent : function(e){
22843 var t = Roo.lib.Event.getTarget(e);
22844 return t ? handles[t.id] : null;
22848 * Returns a custom data object that is registered for a DOM node by id
22849 * @param {String|HTMLElement} id The DOM node or id to look up
22850 * @return {Object} data The custom data
22852 getTarget : function(id){
22853 if(typeof id != "string"){ // must be element?
22856 return elements[id];
22860 * Returns a custom data object that is registered for the DOM node that is the target of the event
22861 * @param {Event} e The event
22862 * @return {Object} data The custom data
22864 getTargetFromEvent : function(e){
22865 var t = Roo.lib.Event.getTarget(e);
22866 return t ? elements[t.id] || handles[t.id] : null;
22871 * Ext JS Library 1.1.1
22872 * Copyright(c) 2006-2007, Ext JS, LLC.
22874 * Originally Released Under LGPL - original licence link has changed is not relivant.
22877 * <script type="text/javascript">
22882 * @class Roo.dd.StatusProxy
22883 * A specialized drag proxy that supports a drop status icon, {@link Roo.Layer} styles and auto-repair. This is the
22884 * default drag proxy used by all Roo.dd components.
22886 * @param {Object} config
22888 Roo.dd.StatusProxy = function(config){
22889 Roo.apply(this, config);
22890 this.id = this.id || Roo.id();
22891 this.el = new Roo.Layer({
22893 id: this.id, tag: "div", cls: "x-dd-drag-proxy "+this.dropNotAllowed, children: [
22894 {tag: "div", cls: "x-dd-drop-icon"},
22895 {tag: "div", cls: "x-dd-drag-ghost"}
22898 shadow: !config || config.shadow !== false
22900 this.ghost = Roo.get(this.el.dom.childNodes[1]);
22901 this.dropStatus = this.dropNotAllowed;
22904 Roo.dd.StatusProxy.prototype = {
22906 * @cfg {String} dropAllowed
22907 * The CSS class to apply to the status element when drop is allowed (defaults to "x-dd-drop-ok").
22909 dropAllowed : "x-dd-drop-ok",
22911 * @cfg {String} dropNotAllowed
22912 * The CSS class to apply to the status element when drop is not allowed (defaults to "x-dd-drop-nodrop").
22914 dropNotAllowed : "x-dd-drop-nodrop",
22917 * Updates the proxy's visual element to indicate the status of whether or not drop is allowed
22918 * over the current target element.
22919 * @param {String} cssClass The css class for the new drop status indicator image
22921 setStatus : function(cssClass){
22922 cssClass = cssClass || this.dropNotAllowed;
22923 if(this.dropStatus != cssClass){
22924 this.el.replaceClass(this.dropStatus, cssClass);
22925 this.dropStatus = cssClass;
22930 * Resets the status indicator to the default dropNotAllowed value
22931 * @param {Boolean} clearGhost True to also remove all content from the ghost, false to preserve it
22933 reset : function(clearGhost){
22934 this.el.dom.className = "x-dd-drag-proxy " + this.dropNotAllowed;
22935 this.dropStatus = this.dropNotAllowed;
22937 this.ghost.update("");
22942 * Updates the contents of the ghost element
22943 * @param {String} html The html that will replace the current innerHTML of the ghost element
22945 update : function(html){
22946 if(typeof html == "string"){
22947 this.ghost.update(html);
22949 this.ghost.update("");
22950 html.style.margin = "0";
22951 this.ghost.dom.appendChild(html);
22953 // ensure float = none set?? cant remember why though.
22954 var el = this.ghost.dom.firstChild;
22956 Roo.fly(el).setStyle('float', 'none');
22961 * Returns the underlying proxy {@link Roo.Layer}
22962 * @return {Roo.Layer} el
22964 getEl : function(){
22969 * Returns the ghost element
22970 * @return {Roo.Element} el
22972 getGhost : function(){
22978 * @param {Boolean} clear True to reset the status and clear the ghost contents, false to preserve them
22980 hide : function(clear){
22988 * Stops the repair animation if it's currently running
22991 if(this.anim && this.anim.isAnimated && this.anim.isAnimated()){
22997 * Displays this proxy
23004 * Force the Layer to sync its shadow and shim positions to the element
23011 * Causes the proxy to return to its position of origin via an animation. Should be called after an
23012 * invalid drop operation by the item being dragged.
23013 * @param {Array} xy The XY position of the element ([x, y])
23014 * @param {Function} callback The function to call after the repair is complete
23015 * @param {Object} scope The scope in which to execute the callback
23017 repair : function(xy, callback, scope){
23018 this.callback = callback;
23019 this.scope = scope;
23020 if(xy && this.animRepair !== false){
23021 this.el.addClass("x-dd-drag-repair");
23022 this.el.hideUnders(true);
23023 this.anim = this.el.shift({
23024 duration: this.repairDuration || .5,
23028 callback: this.afterRepair,
23032 this.afterRepair();
23037 afterRepair : function(){
23039 if(typeof this.callback == "function"){
23040 this.callback.call(this.scope || this);
23042 this.callback = null;
23047 * Ext JS Library 1.1.1
23048 * Copyright(c) 2006-2007, Ext JS, LLC.
23050 * Originally Released Under LGPL - original licence link has changed is not relivant.
23053 * <script type="text/javascript">
23057 * @class Roo.dd.DragSource
23058 * @extends Roo.dd.DDProxy
23059 * A simple class that provides the basic implementation needed to make any element draggable.
23061 * @param {String/HTMLElement/Element} el The container element
23062 * @param {Object} config
23064 Roo.dd.DragSource = function(el, config){
23065 this.el = Roo.get(el);
23066 this.dragData = {};
23068 Roo.apply(this, config);
23071 this.proxy = new Roo.dd.StatusProxy();
23074 Roo.dd.DragSource.superclass.constructor.call(this, this.el.dom, this.ddGroup || this.group,
23075 {dragElId : this.proxy.id, resizeFrame: false, isTarget: false, scroll: this.scroll === true});
23077 this.dragging = false;
23080 Roo.extend(Roo.dd.DragSource, Roo.dd.DDProxy, {
23082 * @cfg {String} dropAllowed
23083 * The CSS class returned to the drag source when drop is allowed (defaults to "x-dd-drop-ok").
23085 dropAllowed : "x-dd-drop-ok",
23087 * @cfg {String} dropNotAllowed
23088 * The CSS class returned to the drag source when drop is not allowed (defaults to "x-dd-drop-nodrop").
23090 dropNotAllowed : "x-dd-drop-nodrop",
23093 * Returns the data object associated with this drag source
23094 * @return {Object} data An object containing arbitrary data
23096 getDragData : function(e){
23097 return this.dragData;
23101 onDragEnter : function(e, id){
23102 var target = Roo.dd.DragDropMgr.getDDById(id);
23103 this.cachedTarget = target;
23104 if(this.beforeDragEnter(target, e, id) !== false){
23105 if(target.isNotifyTarget){
23106 var status = target.notifyEnter(this, e, this.dragData);
23107 this.proxy.setStatus(status);
23109 this.proxy.setStatus(this.dropAllowed);
23112 if(this.afterDragEnter){
23114 * An empty function by default, but provided so that you can perform a custom action
23115 * when the dragged item enters the drop target by providing an implementation.
23116 * @param {Roo.dd.DragDrop} target The drop target
23117 * @param {Event} e The event object
23118 * @param {String} id The id of the dragged element
23119 * @method afterDragEnter
23121 this.afterDragEnter(target, e, id);
23127 * An empty function by default, but provided so that you can perform a custom action
23128 * before the dragged item enters the drop target and optionally cancel the onDragEnter.
23129 * @param {Roo.dd.DragDrop} target The drop target
23130 * @param {Event} e The event object
23131 * @param {String} id The id of the dragged element
23132 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
23134 beforeDragEnter : function(target, e, id){
23139 alignElWithMouse: function() {
23140 Roo.dd.DragSource.superclass.alignElWithMouse.apply(this, arguments);
23145 onDragOver : function(e, id){
23146 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
23147 if(this.beforeDragOver(target, e, id) !== false){
23148 if(target.isNotifyTarget){
23149 var status = target.notifyOver(this, e, this.dragData);
23150 this.proxy.setStatus(status);
23153 if(this.afterDragOver){
23155 * An empty function by default, but provided so that you can perform a custom action
23156 * while the dragged item is over the drop target by providing an implementation.
23157 * @param {Roo.dd.DragDrop} target The drop target
23158 * @param {Event} e The event object
23159 * @param {String} id The id of the dragged element
23160 * @method afterDragOver
23162 this.afterDragOver(target, e, id);
23168 * An empty function by default, but provided so that you can perform a custom action
23169 * while the dragged item is over the drop target and optionally cancel the onDragOver.
23170 * @param {Roo.dd.DragDrop} target The drop target
23171 * @param {Event} e The event object
23172 * @param {String} id The id of the dragged element
23173 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
23175 beforeDragOver : function(target, e, id){
23180 onDragOut : function(e, id){
23181 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
23182 if(this.beforeDragOut(target, e, id) !== false){
23183 if(target.isNotifyTarget){
23184 target.notifyOut(this, e, this.dragData);
23186 this.proxy.reset();
23187 if(this.afterDragOut){
23189 * An empty function by default, but provided so that you can perform a custom action
23190 * after the dragged item is dragged out of the target without dropping.
23191 * @param {Roo.dd.DragDrop} target The drop target
23192 * @param {Event} e The event object
23193 * @param {String} id The id of the dragged element
23194 * @method afterDragOut
23196 this.afterDragOut(target, e, id);
23199 this.cachedTarget = null;
23203 * An empty function by default, but provided so that you can perform a custom action before the dragged
23204 * item is dragged out of the target without dropping, and optionally cancel the onDragOut.
23205 * @param {Roo.dd.DragDrop} target The drop target
23206 * @param {Event} e The event object
23207 * @param {String} id The id of the dragged element
23208 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
23210 beforeDragOut : function(target, e, id){
23215 onDragDrop : function(e, id){
23216 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
23217 if(this.beforeDragDrop(target, e, id) !== false){
23218 if(target.isNotifyTarget){
23219 if(target.notifyDrop(this, e, this.dragData)){ // valid drop?
23220 this.onValidDrop(target, e, id);
23222 this.onInvalidDrop(target, e, id);
23225 this.onValidDrop(target, e, id);
23228 if(this.afterDragDrop){
23230 * An empty function by default, but provided so that you can perform a custom action
23231 * after a valid drag drop has occurred by providing an implementation.
23232 * @param {Roo.dd.DragDrop} target The drop target
23233 * @param {Event} e The event object
23234 * @param {String} id The id of the dropped element
23235 * @method afterDragDrop
23237 this.afterDragDrop(target, e, id);
23240 delete this.cachedTarget;
23244 * An empty function by default, but provided so that you can perform a custom action before the dragged
23245 * item is dropped onto the target and optionally cancel the onDragDrop.
23246 * @param {Roo.dd.DragDrop} target The drop target
23247 * @param {Event} e The event object
23248 * @param {String} id The id of the dragged element
23249 * @return {Boolean} isValid True if the drag drop event is valid, else false to cancel
23251 beforeDragDrop : function(target, e, id){
23256 onValidDrop : function(target, e, id){
23258 if(this.afterValidDrop){
23260 * An empty function by default, but provided so that you can perform a custom action
23261 * after a valid drop has occurred by providing an implementation.
23262 * @param {Object} target The target DD
23263 * @param {Event} e The event object
23264 * @param {String} id The id of the dropped element
23265 * @method afterInvalidDrop
23267 this.afterValidDrop(target, e, id);
23272 getRepairXY : function(e, data){
23273 return this.el.getXY();
23277 onInvalidDrop : function(target, e, id){
23278 this.beforeInvalidDrop(target, e, id);
23279 if(this.cachedTarget){
23280 if(this.cachedTarget.isNotifyTarget){
23281 this.cachedTarget.notifyOut(this, e, this.dragData);
23283 this.cacheTarget = null;
23285 this.proxy.repair(this.getRepairXY(e, this.dragData), this.afterRepair, this);
23287 if(this.afterInvalidDrop){
23289 * An empty function by default, but provided so that you can perform a custom action
23290 * after an invalid drop has occurred by providing an implementation.
23291 * @param {Event} e The event object
23292 * @param {String} id The id of the dropped element
23293 * @method afterInvalidDrop
23295 this.afterInvalidDrop(e, id);
23300 afterRepair : function(){
23302 this.el.highlight(this.hlColor || "c3daf9");
23304 this.dragging = false;
23308 * An empty function by default, but provided so that you can perform a custom action after an invalid
23309 * drop has occurred.
23310 * @param {Roo.dd.DragDrop} target The drop target
23311 * @param {Event} e The event object
23312 * @param {String} id The id of the dragged element
23313 * @return {Boolean} isValid True if the invalid drop should proceed, else false to cancel
23315 beforeInvalidDrop : function(target, e, id){
23320 handleMouseDown : function(e){
23321 if(this.dragging) {
23324 var data = this.getDragData(e);
23325 if(data && this.onBeforeDrag(data, e) !== false){
23326 this.dragData = data;
23328 Roo.dd.DragSource.superclass.handleMouseDown.apply(this, arguments);
23333 * An empty function by default, but provided so that you can perform a custom action before the initial
23334 * drag event begins and optionally cancel it.
23335 * @param {Object} data An object containing arbitrary data to be shared with drop targets
23336 * @param {Event} e The event object
23337 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
23339 onBeforeDrag : function(data, e){
23344 * An empty function by default, but provided so that you can perform a custom action once the initial
23345 * drag event has begun. The drag cannot be canceled from this function.
23346 * @param {Number} x The x position of the click on the dragged object
23347 * @param {Number} y The y position of the click on the dragged object
23349 onStartDrag : Roo.emptyFn,
23351 // private - YUI override
23352 startDrag : function(x, y){
23353 this.proxy.reset();
23354 this.dragging = true;
23355 this.proxy.update("");
23356 this.onInitDrag(x, y);
23361 onInitDrag : function(x, y){
23362 var clone = this.el.dom.cloneNode(true);
23363 clone.id = Roo.id(); // prevent duplicate ids
23364 this.proxy.update(clone);
23365 this.onStartDrag(x, y);
23370 * Returns the drag source's underlying {@link Roo.dd.StatusProxy}
23371 * @return {Roo.dd.StatusProxy} proxy The StatusProxy
23373 getProxy : function(){
23378 * Hides the drag source's {@link Roo.dd.StatusProxy}
23380 hideProxy : function(){
23382 this.proxy.reset(true);
23383 this.dragging = false;
23387 triggerCacheRefresh : function(){
23388 Roo.dd.DDM.refreshCache(this.groups);
23391 // private - override to prevent hiding
23392 b4EndDrag: function(e) {
23395 // private - override to prevent moving
23396 endDrag : function(e){
23397 this.onEndDrag(this.dragData, e);
23401 onEndDrag : function(data, e){
23404 // private - pin to cursor
23405 autoOffset : function(x, y) {
23406 this.setDelta(-12, -20);
23410 * Ext JS Library 1.1.1
23411 * Copyright(c) 2006-2007, Ext JS, LLC.
23413 * Originally Released Under LGPL - original licence link has changed is not relivant.
23416 * <script type="text/javascript">
23421 * @class Roo.dd.DropTarget
23422 * @extends Roo.dd.DDTarget
23423 * A simple class that provides the basic implementation needed to make any element a drop target that can have
23424 * draggable items dropped onto it. The drop has no effect until an implementation of notifyDrop is provided.
23426 * @param {String/HTMLElement/Element} el The container element
23427 * @param {Object} config
23429 Roo.dd.DropTarget = function(el, config){
23430 this.el = Roo.get(el);
23432 var listeners = false; ;
23433 if (config && config.listeners) {
23434 listeners= config.listeners;
23435 delete config.listeners;
23437 Roo.apply(this, config);
23439 if(this.containerScroll){
23440 Roo.dd.ScrollManager.register(this.el);
23444 * @scope Roo.dd.DropTarget
23449 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the source is now over the
23450 * target. This default implementation adds the CSS class specified by overClass (if any) to the drop element
23451 * and returns the dropAllowed config value. This method should be overridden if drop validation is required.
23453 * IMPORTANT : it should set this.valid to true|false
23455 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
23456 * @param {Event} e The event
23457 * @param {Object} data An object containing arbitrary data supplied by the drag source
23463 * The function a {@link Roo.dd.DragSource} calls continuously while it is being dragged over the target.
23464 * This method will be called on every mouse movement while the drag source is over the drop target.
23465 * This default implementation simply returns the dropAllowed config value.
23467 * IMPORTANT : it should set this.valid to true|false
23469 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
23470 * @param {Event} e The event
23471 * @param {Object} data An object containing arbitrary data supplied by the drag source
23477 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the source has been dragged
23478 * out of the target without dropping. This default implementation simply removes the CSS class specified by
23479 * overClass (if any) from the drop element.
23482 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
23483 * @param {Event} e The event
23484 * @param {Object} data An object containing arbitrary data supplied by the drag source
23490 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the dragged item has
23491 * been dropped on it. This method has no default implementation and returns false, so you must provide an
23492 * implementation that does something to process the drop event and returns true so that the drag source's
23493 * repair action does not run.
23495 * IMPORTANT : it should set this.success
23497 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
23498 * @param {Event} e The event
23499 * @param {Object} data An object containing arbitrary data supplied by the drag source
23505 Roo.dd.DropTarget.superclass.constructor.call( this,
23507 this.ddGroup || this.group,
23510 listeners : listeners || {}
23518 Roo.extend(Roo.dd.DropTarget, Roo.dd.DDTarget, {
23520 * @cfg {String} overClass
23521 * The CSS class applied to the drop target element while the drag source is over it (defaults to "").
23524 * @cfg {String} ddGroup
23525 * The drag drop group to handle drop events for
23529 * @cfg {String} dropAllowed
23530 * The CSS class returned to the drag source when drop is allowed (defaults to "x-dd-drop-ok").
23532 dropAllowed : "x-dd-drop-ok",
23534 * @cfg {String} dropNotAllowed
23535 * The CSS class returned to the drag source when drop is not allowed (defaults to "x-dd-drop-nodrop").
23537 dropNotAllowed : "x-dd-drop-nodrop",
23539 * @cfg {boolean} success
23540 * set this after drop listener..
23544 * @cfg {boolean|String} valid true/false or string (ok-add/ok-sub/ok/nodrop)
23545 * if the drop point is valid for over/enter..
23552 isNotifyTarget : true,
23557 notifyEnter : function(dd, e, data)
23560 this.fireEvent('enter', dd, e, data);
23561 if(this.overClass){
23562 this.el.addClass(this.overClass);
23564 return typeof(this.valid) == 'string' ? 'x-dd-drop-' + this.valid : (
23565 this.valid ? this.dropAllowed : this.dropNotAllowed
23572 notifyOver : function(dd, e, data)
23575 this.fireEvent('over', dd, e, data);
23576 return typeof(this.valid) == 'string' ? 'x-dd-drop-' + this.valid : (
23577 this.valid ? this.dropAllowed : this.dropNotAllowed
23584 notifyOut : function(dd, e, data)
23586 this.fireEvent('out', dd, e, data);
23587 if(this.overClass){
23588 this.el.removeClass(this.overClass);
23595 notifyDrop : function(dd, e, data)
23597 this.success = false;
23598 this.fireEvent('drop', dd, e, data);
23599 return this.success;
23603 * Ext JS Library 1.1.1
23604 * Copyright(c) 2006-2007, Ext JS, LLC.
23606 * Originally Released Under LGPL - original licence link has changed is not relivant.
23609 * <script type="text/javascript">
23614 * @class Roo.dd.DragZone
23615 * @extends Roo.dd.DragSource
23616 * This class provides a container DD instance that proxies for multiple child node sources.<br />
23617 * By default, this class requires that draggable child nodes are registered with {@link Roo.dd.Registry}.
23619 * @param {String/HTMLElement/Element} el The container element
23620 * @param {Object} config
23622 Roo.dd.DragZone = function(el, config){
23623 Roo.dd.DragZone.superclass.constructor.call(this, el, config);
23624 if(this.containerScroll){
23625 Roo.dd.ScrollManager.register(this.el);
23629 Roo.extend(Roo.dd.DragZone, Roo.dd.DragSource, {
23631 * @cfg {Boolean} containerScroll True to register this container with the Scrollmanager
23632 * for auto scrolling during drag operations.
23635 * @cfg {String} hlColor The color to use when visually highlighting the drag source in the afterRepair
23636 * method after a failed drop (defaults to "c3daf9" - light blue)
23640 * Called when a mousedown occurs in this container. Looks in {@link Roo.dd.Registry}
23641 * for a valid target to drag based on the mouse down. Override this method
23642 * to provide your own lookup logic (e.g. finding a child by class name). Make sure your returned
23643 * object has a "ddel" attribute (with an HTML Element) for other functions to work.
23644 * @param {EventObject} e The mouse down event
23645 * @return {Object} The dragData
23647 getDragData : function(e){
23648 return Roo.dd.Registry.getHandleFromEvent(e);
23652 * Called once drag threshold has been reached to initialize the proxy element. By default, it clones the
23653 * this.dragData.ddel
23654 * @param {Number} x The x position of the click on the dragged object
23655 * @param {Number} y The y position of the click on the dragged object
23656 * @return {Boolean} true to continue the drag, false to cancel
23658 onInitDrag : function(x, y){
23659 this.proxy.update(this.dragData.ddel.cloneNode(true));
23660 this.onStartDrag(x, y);
23665 * Called after a repair of an invalid drop. By default, highlights this.dragData.ddel
23667 afterRepair : function(){
23669 Roo.Element.fly(this.dragData.ddel).highlight(this.hlColor || "c3daf9");
23671 this.dragging = false;
23675 * Called before a repair of an invalid drop to get the XY to animate to. By default returns
23676 * the XY of this.dragData.ddel
23677 * @param {EventObject} e The mouse up event
23678 * @return {Array} The xy location (e.g. [100, 200])
23680 getRepairXY : function(e){
23681 return Roo.Element.fly(this.dragData.ddel).getXY();
23685 * Ext JS Library 1.1.1
23686 * Copyright(c) 2006-2007, Ext JS, LLC.
23688 * Originally Released Under LGPL - original licence link has changed is not relivant.
23691 * <script type="text/javascript">
23694 * @class Roo.dd.DropZone
23695 * @extends Roo.dd.DropTarget
23696 * This class provides a container DD instance that proxies for multiple child node targets.<br />
23697 * By default, this class requires that child nodes accepting drop are registered with {@link Roo.dd.Registry}.
23699 * @param {String/HTMLElement/Element} el The container element
23700 * @param {Object} config
23702 Roo.dd.DropZone = function(el, config){
23703 Roo.dd.DropZone.superclass.constructor.call(this, el, config);
23706 Roo.extend(Roo.dd.DropZone, Roo.dd.DropTarget, {
23708 * Returns a custom data object associated with the DOM node that is the target of the event. By default
23709 * this looks up the event target in the {@link Roo.dd.Registry}, although you can override this method to
23710 * provide your own custom lookup.
23711 * @param {Event} e The event
23712 * @return {Object} data The custom data
23714 getTargetFromEvent : function(e){
23715 return Roo.dd.Registry.getTargetFromEvent(e);
23719 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has entered a drop node
23720 * that it has registered. This method has no default implementation and should be overridden to provide
23721 * node-specific processing if necessary.
23722 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
23723 * {@link #getTargetFromEvent} for this node)
23724 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23725 * @param {Event} e The event
23726 * @param {Object} data An object containing arbitrary data supplied by the drag source
23728 onNodeEnter : function(n, dd, e, data){
23733 * Called internally while the DropZone determines that a {@link Roo.dd.DragSource} is over a drop node
23734 * that it has registered. The default implementation returns this.dropNotAllowed, so it should be
23735 * overridden to provide the proper feedback.
23736 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
23737 * {@link #getTargetFromEvent} for this node)
23738 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23739 * @param {Event} e The event
23740 * @param {Object} data An object containing arbitrary data supplied by the drag source
23741 * @return {String} status The CSS class that communicates the drop status back to the source so that the
23742 * underlying {@link Roo.dd.StatusProxy} can be updated
23744 onNodeOver : function(n, dd, e, data){
23745 return this.dropAllowed;
23749 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dragged out of
23750 * the drop node without dropping. This method has no default implementation and should be overridden to provide
23751 * node-specific processing if necessary.
23752 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
23753 * {@link #getTargetFromEvent} for this node)
23754 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23755 * @param {Event} e The event
23756 * @param {Object} data An object containing arbitrary data supplied by the drag source
23758 onNodeOut : function(n, dd, e, data){
23763 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dropped onto
23764 * the drop node. The default implementation returns false, so it should be overridden to provide the
23765 * appropriate processing of the drop event and return true so that the drag source's repair action does not run.
23766 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
23767 * {@link #getTargetFromEvent} for this node)
23768 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23769 * @param {Event} e The event
23770 * @param {Object} data An object containing arbitrary data supplied by the drag source
23771 * @return {Boolean} True if the drop was valid, else false
23773 onNodeDrop : function(n, dd, e, data){
23778 * Called internally while the DropZone determines that a {@link Roo.dd.DragSource} is being dragged over it,
23779 * but not over any of its registered drop nodes. The default implementation returns this.dropNotAllowed, so
23780 * it should be overridden to provide the proper feedback if necessary.
23781 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23782 * @param {Event} e The event
23783 * @param {Object} data An object containing arbitrary data supplied by the drag source
23784 * @return {String} status The CSS class that communicates the drop status back to the source so that the
23785 * underlying {@link Roo.dd.StatusProxy} can be updated
23787 onContainerOver : function(dd, e, data){
23788 return this.dropNotAllowed;
23792 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dropped on it,
23793 * but not on any of its registered drop nodes. The default implementation returns false, so it should be
23794 * overridden to provide the appropriate processing of the drop event if you need the drop zone itself to
23795 * be able to accept drops. It should return true when valid so that the drag source's repair action does not run.
23796 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23797 * @param {Event} e The event
23798 * @param {Object} data An object containing arbitrary data supplied by the drag source
23799 * @return {Boolean} True if the drop was valid, else false
23801 onContainerDrop : function(dd, e, data){
23806 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the source is now over
23807 * the zone. The default implementation returns this.dropNotAllowed and expects that only registered drop
23808 * nodes can process drag drop operations, so if you need the drop zone itself to be able to process drops
23809 * you should override this method and provide a custom implementation.
23810 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23811 * @param {Event} e The event
23812 * @param {Object} data An object containing arbitrary data supplied by the drag source
23813 * @return {String} status The CSS class that communicates the drop status back to the source so that the
23814 * underlying {@link Roo.dd.StatusProxy} can be updated
23816 notifyEnter : function(dd, e, data){
23817 return this.dropNotAllowed;
23821 * The function a {@link Roo.dd.DragSource} calls continuously while it is being dragged over the drop zone.
23822 * This method will be called on every mouse movement while the drag source is over the drop zone.
23823 * It will call {@link #onNodeOver} while the drag source is over a registered node, and will also automatically
23824 * delegate to the appropriate node-specific methods as necessary when the drag source enters and exits
23825 * registered nodes ({@link #onNodeEnter}, {@link #onNodeOut}). If the drag source is not currently over a
23826 * registered node, it will call {@link #onContainerOver}.
23827 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23828 * @param {Event} e The event
23829 * @param {Object} data An object containing arbitrary data supplied by the drag source
23830 * @return {String} status The CSS class that communicates the drop status back to the source so that the
23831 * underlying {@link Roo.dd.StatusProxy} can be updated
23833 notifyOver : function(dd, e, data){
23834 var n = this.getTargetFromEvent(e);
23835 if(!n){ // not over valid drop target
23836 if(this.lastOverNode){
23837 this.onNodeOut(this.lastOverNode, dd, e, data);
23838 this.lastOverNode = null;
23840 return this.onContainerOver(dd, e, data);
23842 if(this.lastOverNode != n){
23843 if(this.lastOverNode){
23844 this.onNodeOut(this.lastOverNode, dd, e, data);
23846 this.onNodeEnter(n, dd, e, data);
23847 this.lastOverNode = n;
23849 return this.onNodeOver(n, dd, e, data);
23853 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the source has been dragged
23854 * out of the zone without dropping. If the drag source is currently over a registered node, the notification
23855 * will be delegated to {@link #onNodeOut} for node-specific handling, otherwise it will be ignored.
23856 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
23857 * @param {Event} e The event
23858 * @param {Object} data An object containing arbitrary data supplied by the drag zone
23860 notifyOut : function(dd, e, data){
23861 if(this.lastOverNode){
23862 this.onNodeOut(this.lastOverNode, dd, e, data);
23863 this.lastOverNode = null;
23868 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the dragged item has
23869 * been dropped on it. The drag zone will look up the target node based on the event passed in, and if there
23870 * is a node registered for that event, it will delegate to {@link #onNodeDrop} for node-specific handling,
23871 * otherwise it will call {@link #onContainerDrop}.
23872 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23873 * @param {Event} e The event
23874 * @param {Object} data An object containing arbitrary data supplied by the drag source
23875 * @return {Boolean} True if the drop was valid, else false
23877 notifyDrop : function(dd, e, data){
23878 if(this.lastOverNode){
23879 this.onNodeOut(this.lastOverNode, dd, e, data);
23880 this.lastOverNode = null;
23882 var n = this.getTargetFromEvent(e);
23884 this.onNodeDrop(n, dd, e, data) :
23885 this.onContainerDrop(dd, e, data);
23889 triggerCacheRefresh : function(){
23890 Roo.dd.DDM.refreshCache(this.groups);