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",
707 * Ext JS Library 1.1.1
708 * Copyright(c) 2006-2007, Ext JS, LLC.
710 * Originally Released Under LGPL - original licence link has changed is not relivant.
713 * <script type="text/javascript">
717 // wrappedn so fnCleanup is not in global scope...
719 function fnCleanUp() {
720 var p = Function.prototype;
721 delete p.createSequence;
723 delete p.createDelegate;
724 delete p.createCallback;
725 delete p.createInterceptor;
727 window.detachEvent("onunload", fnCleanUp);
729 window.attachEvent("onunload", fnCleanUp);
736 * These functions are available on every Function object (any JavaScript function).
738 Roo.apply(Function.prototype, {
740 * Creates a callback that passes arguments[0], arguments[1], arguments[2], ...
741 * Call directly on any function. Example: <code>myFunction.createCallback(myarg, myarg2)</code>
742 * Will create a function that is bound to those 2 args.
743 * @return {Function} The new function
745 createCallback : function(/*args...*/){
746 // make args available, in function below
747 var args = arguments;
750 return method.apply(window, args);
755 * Creates a delegate (callback) that sets the scope to obj.
756 * Call directly on any function. Example: <code>this.myFunction.createDelegate(this)</code>
757 * Will create a function that is automatically scoped to this.
758 * @param {Object} obj (optional) The object for which the scope is set
759 * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
760 * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
761 * if a number the args are inserted at the specified position
762 * @return {Function} The new function
764 createDelegate : function(obj, args, appendArgs){
767 var callArgs = args || arguments;
768 if(appendArgs === true){
769 callArgs = Array.prototype.slice.call(arguments, 0);
770 callArgs = callArgs.concat(args);
771 }else if(typeof appendArgs == "number"){
772 callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first
773 var applyArgs = [appendArgs, 0].concat(args); // create method call params
774 Array.prototype.splice.apply(callArgs, applyArgs); // splice them in
776 return method.apply(obj || window, callArgs);
781 * Calls this function after the number of millseconds specified.
782 * @param {Number} millis The number of milliseconds for the setTimeout call (if 0 the function is executed immediately)
783 * @param {Object} obj (optional) The object for which the scope is set
784 * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
785 * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
786 * if a number the args are inserted at the specified position
787 * @return {Number} The timeout id that can be used with clearTimeout
789 defer : function(millis, obj, args, appendArgs){
790 var fn = this.createDelegate(obj, args, appendArgs);
792 return setTimeout(fn, millis);
798 * Create a combined function call sequence of the original function + the passed function.
799 * The resulting function returns the results of the original function.
800 * The passed fcn is called with the parameters of the original function
801 * @param {Function} fcn The function to sequence
802 * @param {Object} scope (optional) The scope of the passed fcn (Defaults to scope of original function or window)
803 * @return {Function} The new function
805 createSequence : function(fcn, scope){
806 if(typeof fcn != "function"){
811 var retval = method.apply(this || window, arguments);
812 fcn.apply(scope || this || window, arguments);
818 * Creates an interceptor function. The passed fcn is called before the original one. If it returns false, the original one is not called.
819 * The resulting function returns the results of the original function.
820 * The passed fcn is called with the parameters of the original function.
822 * @param {Function} fcn The function to call before the original
823 * @param {Object} scope (optional) The scope of the passed fcn (Defaults to scope of original function or window)
824 * @return {Function} The new function
826 createInterceptor : function(fcn, scope){
827 if(typeof fcn != "function"){
834 if(fcn.apply(scope || this || window, arguments) === false){
837 return method.apply(this || window, arguments);
843 * Ext JS Library 1.1.1
844 * Copyright(c) 2006-2007, Ext JS, LLC.
846 * Originally Released Under LGPL - original licence link has changed is not relivant.
849 * <script type="text/javascript">
852 Roo.applyIf(String, {
857 * Escapes the passed string for ' and \
858 * @param {String} string The string to escape
859 * @return {String} The escaped string
862 escape : function(string) {
863 return string.replace(/('|\\)/g, "\\$1");
867 * Pads the left side of a string with a specified character. This is especially useful
868 * for normalizing number and date strings. Example usage:
870 var s = String.leftPad('123', 5, '0');
871 // s now contains the string: '00123'
873 * @param {String} string The original string
874 * @param {Number} size The total length of the output string
875 * @param {String} char (optional) The character with which to pad the original string (defaults to empty string " ")
876 * @return {String} The padded string
879 leftPad : function (val, size, ch) {
880 var result = new String(val);
881 if(ch === null || ch === undefined || ch === '') {
884 while (result.length < size) {
885 result = ch + result;
891 * Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens. Each
892 * token must be unique, and must increment in the format {0}, {1}, etc. Example usage:
894 var cls = 'my-class', text = 'Some text';
895 var s = String.format('<div class="{0}">{1}</div>', cls, text);
896 // s now contains the string: '<div class="my-class">Some text</div>'
898 * @param {String} string The tokenized string to be formatted
899 * @param {String} value1 The value to replace token {0}
900 * @param {String} value2 Etc...
901 * @return {String} The formatted string
904 format : function(format){
905 var args = Array.prototype.slice.call(arguments, 1);
906 return format.replace(/\{(\d+)\}/g, function(m, i){
907 return Roo.util.Format.htmlEncode(args[i]);
915 * Utility function that allows you to easily switch a string between two alternating values. The passed value
916 * is compared to the current string, and if they are equal, the other value that was passed in is returned. If
917 * they are already different, the first value passed in is returned. Note that this method returns the new value
918 * but does not change the current string.
920 // alternate sort directions
921 sort = sort.toggle('ASC', 'DESC');
923 // instead of conditional logic:
924 sort = (sort == 'ASC' ? 'DESC' : 'ASC');
926 * @param {String} value The value to compare to the current string
927 * @param {String} other The new value to use if the string already equals the first value passed in
928 * @return {String} The new value
931 String.prototype.toggle = function(value, other){
932 return this == value ? other : value;
937 * Remove invalid unicode characters from a string
939 * @return {String} The clean string
941 String.prototype.unicodeClean = function () {
942 return this.replace(/[\s\S]/g,
943 function(character) {
944 if (character.charCodeAt()< 256) {
948 encodeURIComponent(character);
959 * Make the first letter of a string uppercase
961 * @return {String} The new string.
963 String.prototype.toUpperCaseFirst = function () {
964 return this.charAt(0).toUpperCase() + this.slice(1);
969 * Ext JS Library 1.1.1
970 * Copyright(c) 2006-2007, Ext JS, LLC.
972 * Originally Released Under LGPL - original licence link has changed is not relivant.
975 * <script type="text/javascript">
981 Roo.applyIf(Number.prototype, {
983 * Checks whether or not the current number is within a desired range. If the number is already within the
984 * range it is returned, otherwise the min or max value is returned depending on which side of the range is
985 * exceeded. Note that this method returns the constrained value but does not change the current number.
986 * @param {Number} min The minimum number in the range
987 * @param {Number} max The maximum number in the range
988 * @return {Number} The constrained value if outside the range, otherwise the current value
990 constrain : function(min, max){
991 return Math.min(Math.max(this, min), max);
995 * Ext JS Library 1.1.1
996 * Copyright(c) 2006-2007, Ext JS, LLC.
998 * Originally Released Under LGPL - original licence link has changed is not relivant.
1001 * <script type="text/javascript">
1006 Roo.applyIf(Array.prototype, {
1009 * Checks whether or not the specified object exists in the array.
1010 * @param {Object} o The object to check for
1011 * @return {Number} The index of o in the array (or -1 if it is not found)
1013 indexOf : function(o){
1014 for (var i = 0, len = this.length; i < len; i++){
1015 if(this[i] == o) { return i; }
1021 * Removes the specified object from the array. If the object is not found nothing happens.
1022 * @param {Object} o The object to remove
1024 remove : function(o){
1025 var index = this.indexOf(o);
1027 this.splice(index, 1);
1031 * Map (JS 1.6 compatibility)
1032 * @param {Function} function to call
1034 map : function(fun )
1036 var len = this.length >>> 0;
1037 if (typeof fun != "function") {
1038 throw new TypeError();
1040 var res = new Array(len);
1041 var thisp = arguments[1];
1042 for (var i = 0; i < len; i++)
1045 res[i] = fun.call(thisp, this[i], i, this);
1053 * @param {Array} o The array to compare to
1054 * @returns {Boolean} true if the same
1056 equals : function(b)
1058 // https://stackoverflow.com/questions/3115982/how-to-check-if-two-arrays-are-equal-with-javascript
1065 if (this.length !== b.length) {
1069 // sort?? a.sort().equals(b.sort());
1071 for (var i = 0; i < this.length; ++i) {
1072 if (this[i] !== b[i]) {
1084 Roo.applyIf(Array, {
1088 * @param {Array} o Or Array like object (eg. nodelist)
1095 for (var i =0; i < o.length; i++) {
1104 * Ext JS Library 1.1.1
1105 * Copyright(c) 2006-2007, Ext JS, LLC.
1107 * Originally Released Under LGPL - original licence link has changed is not relivant.
1110 * <script type="text/javascript">
1116 * The date parsing and format syntax is a subset of
1117 * <a href="http://www.php.net/date">PHP's date() function</a>, and the formats that are
1118 * supported will provide results equivalent to their PHP versions.
1120 * Following is the list of all currently supported formats:
1123 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'
1125 Format Output Description
1126 ------ ---------- --------------------------------------------------------------
1127 d 10 Day of the month, 2 digits with leading zeros
1128 D Wed A textual representation of a day, three letters
1129 j 10 Day of the month without leading zeros
1130 l Wednesday A full textual representation of the day of the week
1131 S th English ordinal day of month suffix, 2 chars (use with j)
1132 w 3 Numeric representation of the day of the week
1133 z 9 The julian date, or day of the year (0-365)
1134 W 01 ISO-8601 2-digit week number of year, weeks starting on Monday (00-52)
1135 F January A full textual representation of the month
1136 m 01 Numeric representation of a month, with leading zeros
1137 M Jan Month name abbreviation, three letters
1138 n 1 Numeric representation of a month, without leading zeros
1139 t 31 Number of days in the given month
1140 L 0 Whether it's a leap year (1 if it is a leap year, else 0)
1141 Y 2007 A full numeric representation of a year, 4 digits
1142 y 07 A two digit representation of a year
1143 a pm Lowercase Ante meridiem and Post meridiem
1144 A PM Uppercase Ante meridiem and Post meridiem
1145 g 3 12-hour format of an hour without leading zeros
1146 G 15 24-hour format of an hour without leading zeros
1147 h 03 12-hour format of an hour with leading zeros
1148 H 15 24-hour format of an hour with leading zeros
1149 i 05 Minutes with leading zeros
1150 s 01 Seconds, with leading zeros
1151 O -0600 Difference to Greenwich time (GMT) in hours (Allows +08, without minutes)
1152 P -06:00 Difference to Greenwich time (GMT) with colon between hours and minutes
1153 T CST Timezone setting of the machine running the code
1154 Z -21600 Timezone offset in seconds (negative if west of UTC, positive if east)
1157 * Example usage (note that you must escape format specifiers with '\\' to render them as character literals):
1159 var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
1160 document.write(dt.format('Y-m-d')); //2007-01-10
1161 document.write(dt.format('F j, Y, g:i a')); //January 10, 2007, 3:05 pm
1162 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
1165 * Here are some standard date/time patterns that you might find helpful. They
1166 * are not part of the source of Date.js, but to use them you can simply copy this
1167 * block of code into any script that is included after Date.js and they will also become
1168 * globally available on the Date object. Feel free to add or remove patterns as needed in your code.
1171 ISO8601Long:"Y-m-d H:i:s",
1172 ISO8601Short:"Y-m-d",
1174 LongDate: "l, F d, Y",
1175 FullDateTime: "l, F d, Y g:i:s A",
1178 LongTime: "g:i:s A",
1179 SortableDateTime: "Y-m-d\\TH:i:s",
1180 UniversalSortableDateTime: "Y-m-d H:i:sO",
1187 var dt = new Date();
1188 document.write(dt.format(Date.patterns.ShortDate));
1193 * Most of the date-formatting functions below are the excellent work of Baron Schwartz.
1194 * They generate precompiled functions from date formats instead of parsing and
1195 * processing the pattern every time you format a date. These functions are available
1196 * on every Date object (any javascript function).
1198 * The original article and download are here:
1199 * http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/
1206 Returns the number of milliseconds between this date and date
1207 @param {Date} date (optional) Defaults to now
1208 @return {Number} The diff in milliseconds
1209 @member Date getElapsed
1211 Date.prototype.getElapsed = function(date) {
1212 return Math.abs((date || new Date()).getTime()-this.getTime());
1214 // was in date file..
1218 Date.parseFunctions = {count:0};
1220 Date.parseRegexes = [];
1222 Date.formatFunctions = {count:0};
1225 Date.prototype.dateFormat = function(format) {
1226 if (Date.formatFunctions[format] == null) {
1227 Date.createNewFormat(format);
1229 var func = Date.formatFunctions[format];
1230 return this[func]();
1235 * Formats a date given the supplied format string
1236 * @param {String} format The format string
1237 * @return {String} The formatted date
1240 Date.prototype.format = Date.prototype.dateFormat;
1243 Date.createNewFormat = function(format) {
1244 var funcName = "format" + Date.formatFunctions.count++;
1245 Date.formatFunctions[format] = funcName;
1246 var code = "Date.prototype." + funcName + " = function(){return ";
1247 var special = false;
1249 for (var i = 0; i < format.length; ++i) {
1250 ch = format.charAt(i);
1251 if (!special && ch == "\\") {
1256 code += "'" + String.escape(ch) + "' + ";
1259 code += Date.getFormatCode(ch);
1262 /** eval:var:zzzzzzzzzzzzz */
1263 eval(code.substring(0, code.length - 3) + ";}");
1267 Date.getFormatCode = function(character) {
1268 switch (character) {
1270 return "String.leftPad(this.getDate(), 2, '0') + ";
1272 return "Date.dayNames[this.getDay()].substring(0, 3) + ";
1274 return "this.getDate() + ";
1276 return "Date.dayNames[this.getDay()] + ";
1278 return "this.getSuffix() + ";
1280 return "this.getDay() + ";
1282 return "this.getDayOfYear() + ";
1284 return "this.getWeekOfYear() + ";
1286 return "Date.monthNames[this.getMonth()] + ";
1288 return "String.leftPad(this.getMonth() + 1, 2, '0') + ";
1290 return "Date.monthNames[this.getMonth()].substring(0, 3) + ";
1292 return "(this.getMonth() + 1) + ";
1294 return "this.getDaysInMonth() + ";
1296 return "(this.isLeapYear() ? 1 : 0) + ";
1298 return "this.getFullYear() + ";
1300 return "('' + this.getFullYear()).substring(2, 4) + ";
1302 return "(this.getHours() < 12 ? 'am' : 'pm') + ";
1304 return "(this.getHours() < 12 ? 'AM' : 'PM') + ";
1306 return "((this.getHours() % 12) ? this.getHours() % 12 : 12) + ";
1308 return "this.getHours() + ";
1310 return "String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0') + ";
1312 return "String.leftPad(this.getHours(), 2, '0') + ";
1314 return "String.leftPad(this.getMinutes(), 2, '0') + ";
1316 return "String.leftPad(this.getSeconds(), 2, '0') + ";
1318 return "this.getGMTOffset() + ";
1320 return "this.getGMTColonOffset() + ";
1322 return "this.getTimezone() + ";
1324 return "(this.getTimezoneOffset() * -60) + ";
1326 return "'" + String.escape(character) + "' + ";
1331 * Parses the passed string using the specified format. Note that this function expects dates in normal calendar
1332 * format, meaning that months are 1-based (1 = January) and not zero-based like in JavaScript dates. Any part of
1333 * the date format that is not specified will default to the current date value for that part. Time parts can also
1334 * be specified, but default to 0. Keep in mind that the input date string must precisely match the specified format
1335 * string or the parse operation will fail.
1338 //dt = Fri May 25 2007 (current date)
1339 var dt = new Date();
1341 //dt = Thu May 25 2006 (today's month/day in 2006)
1342 dt = Date.parseDate("2006", "Y");
1344 //dt = Sun Jan 15 2006 (all date parts specified)
1345 dt = Date.parseDate("2006-1-15", "Y-m-d");
1347 //dt = Sun Jan 15 2006 15:20:01 GMT-0600 (CST)
1348 dt = Date.parseDate("2006-1-15 3:20:01 PM", "Y-m-d h:i:s A" );
1350 * @param {String} input The unparsed date as a string
1351 * @param {String} format The format the date is in
1352 * @return {Date} The parsed date
1355 Date.parseDate = function(input, format) {
1356 if (Date.parseFunctions[format] == null) {
1357 Date.createParser(format);
1359 var func = Date.parseFunctions[format];
1360 return Date[func](input);
1366 Date.createParser = function(format) {
1367 var funcName = "parse" + Date.parseFunctions.count++;
1368 var regexNum = Date.parseRegexes.length;
1369 var currentGroup = 1;
1370 Date.parseFunctions[format] = funcName;
1372 var code = "Date." + funcName + " = function(input){\n"
1373 + "var y = -1, m = -1, d = -1, h = -1, i = -1, s = -1, o, z, v;\n"
1374 + "var d = new Date();\n"
1375 + "y = d.getFullYear();\n"
1376 + "m = d.getMonth();\n"
1377 + "d = d.getDate();\n"
1378 + "if (typeof(input) !== 'string') { input = input.toString(); }\n"
1379 + "var results = input.match(Date.parseRegexes[" + regexNum + "]);\n"
1380 + "if (results && results.length > 0) {";
1383 var special = false;
1385 for (var i = 0; i < format.length; ++i) {
1386 ch = format.charAt(i);
1387 if (!special && ch == "\\") {
1392 regex += String.escape(ch);
1395 var obj = Date.formatCodeToRegex(ch, currentGroup);
1396 currentGroup += obj.g;
1398 if (obj.g && obj.c) {
1404 code += "if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0)\n"
1405 + "{v = new Date(y, m, d, h, i, s); v.setFullYear(y);}\n"
1406 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0)\n"
1407 + "{v = new Date(y, m, d, h, i); v.setFullYear(y);}\n"
1408 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0)\n"
1409 + "{v = new Date(y, m, d, h); v.setFullYear(y);}\n"
1410 + "else if (y >= 0 && m >= 0 && d > 0)\n"
1411 + "{v = new Date(y, m, d); v.setFullYear(y);}\n"
1412 + "else if (y >= 0 && m >= 0)\n"
1413 + "{v = new Date(y, m); v.setFullYear(y);}\n"
1414 + "else if (y >= 0)\n"
1415 + "{v = new Date(y); v.setFullYear(y);}\n"
1416 + "}return (v && (z || o))?\n" // favour UTC offset over GMT offset
1417 + " ((z)? v.add(Date.SECOND, (v.getTimezoneOffset() * 60) + (z*1)) :\n" // reset to UTC, then add offset
1418 + " v.add(Date.HOUR, (v.getGMTOffset() / 100) + (o / -100))) : v\n" // reset to GMT, then add offset
1421 Date.parseRegexes[regexNum] = new RegExp("^" + regex + "$");
1422 /** eval:var:zzzzzzzzzzzzz */
1427 Date.formatCodeToRegex = function(character, currentGroup) {
1428 switch (character) {
1432 s:"(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)"};
1435 c:"d = parseInt(results[" + currentGroup + "], 10);\n",
1436 s:"(\\d{1,2})"}; // day of month without leading zeroes
1439 c:"d = parseInt(results[" + currentGroup + "], 10);\n",
1440 s:"(\\d{2})"}; // day of month with leading zeroes
1444 s:"(?:" + Date.dayNames.join("|") + ")"};
1448 s:"(?:st|nd|rd|th)"};
1463 c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "].substring(0, 3)], 10);\n",
1464 s:"(" + Date.monthNames.join("|") + ")"};
1467 c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "]], 10);\n",
1468 s:"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)"};
1471 c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
1472 s:"(\\d{1,2})"}; // Numeric representation of a month, without leading zeros
1475 c:"m = Math.max(0,parseInt(results[" + currentGroup + "], 10) - 1);\n",
1476 s:"(\\d{2})"}; // Numeric representation of a month, with leading zeros
1487 c:"y = parseInt(results[" + currentGroup + "], 10);\n",
1491 c:"var ty = parseInt(results[" + currentGroup + "], 10);\n"
1492 + "y = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n",
1496 c:"if (results[" + currentGroup + "] == 'am') {\n"
1497 + "if (h == 12) { h = 0; }\n"
1498 + "} else { if (h < 12) { h += 12; }}",
1502 c:"if (results[" + currentGroup + "] == 'AM') {\n"
1503 + "if (h == 12) { h = 0; }\n"
1504 + "} else { if (h < 12) { h += 12; }}",
1509 c:"h = parseInt(results[" + currentGroup + "], 10);\n",
1510 s:"(\\d{1,2})"}; // 12/24-hr format format of an hour without leading zeroes
1514 c:"h = parseInt(results[" + currentGroup + "], 10);\n",
1515 s:"(\\d{2})"}; // 12/24-hr format format of an hour with leading zeroes
1518 c:"i = parseInt(results[" + currentGroup + "], 10);\n",
1522 c:"s = parseInt(results[" + currentGroup + "], 10);\n",
1527 "o = results[", currentGroup, "];\n",
1528 "var sn = o.substring(0,1);\n", // get + / - sign
1529 "var hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60);\n", // get hours (performs minutes-to-hour conversion also)
1530 "var mn = o.substring(3,5) % 60;\n", // get minutes
1531 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n", // -12hrs <= GMT offset <= 14hrs
1532 " (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"
1534 s:"([+\-]\\d{2,4})"};
1540 "o = results[", currentGroup, "];\n",
1541 "var sn = o.substring(0,1);\n",
1542 "var hr = o.substring(1,3)*1 + Math.floor(o.substring(4,6) / 60);\n",
1543 "var mn = o.substring(4,6) % 60;\n",
1544 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n",
1545 " (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"
1551 s:"[A-Z]{1,4}"}; // timezone abbrev. may be between 1 - 4 chars
1554 c:"z = results[" + currentGroup + "];\n" // -43200 <= UTC offset <= 50400
1555 + "z = (-43200 <= z*1 && z*1 <= 50400)? z : null;\n",
1556 s:"([+\-]?\\d{1,5})"}; // leading '+' sign is optional for UTC offset
1560 s:String.escape(character)};
1565 * Get the timezone abbreviation of the current date (equivalent to the format specifier 'T').
1566 * @return {String} The abbreviated timezone name (e.g. 'CST')
1568 Date.prototype.getTimezone = function() {
1569 return this.toString().replace(/^.*? ([A-Z]{1,4})[\-+][0-9]{4} .*$/, "$1");
1573 * Get the offset from GMT of the current date (equivalent to the format specifier 'O').
1574 * @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600')
1576 Date.prototype.getGMTOffset = function() {
1577 return (this.getTimezoneOffset() > 0 ? "-" : "+")
1578 + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
1579 + String.leftPad(this.getTimezoneOffset() % 60, 2, "0");
1583 * Get the offset from GMT of the current date (equivalent to the format specifier 'P').
1584 * @return {String} 2-characters representing hours and 2-characters representing minutes
1585 * seperated by a colon and prefixed with + or - (e.g. '-06:00')
1587 Date.prototype.getGMTColonOffset = function() {
1588 return (this.getTimezoneOffset() > 0 ? "-" : "+")
1589 + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
1591 + String.leftPad(this.getTimezoneOffset() %60, 2, "0");
1595 * Get the numeric day number of the year, adjusted for leap year.
1596 * @return {Number} 0 through 364 (365 in leap years)
1598 Date.prototype.getDayOfYear = function() {
1600 Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
1601 for (var i = 0; i < this.getMonth(); ++i) {
1602 num += Date.daysInMonth[i];
1604 return num + this.getDate() - 1;
1608 * Get the string representation of the numeric week number of the year
1609 * (equivalent to the format specifier 'W').
1610 * @return {String} '00' through '52'
1612 Date.prototype.getWeekOfYear = function() {
1613 // Skip to Thursday of this week
1614 var now = this.getDayOfYear() + (4 - this.getDay());
1615 // Find the first Thursday of the year
1616 var jan1 = new Date(this.getFullYear(), 0, 1);
1617 var then = (7 - jan1.getDay() + 4);
1618 return String.leftPad(((now - then) / 7) + 1, 2, "0");
1622 * Whether or not the current date is in a leap year.
1623 * @return {Boolean} True if the current date is in a leap year, else false
1625 Date.prototype.isLeapYear = function() {
1626 var year = this.getFullYear();
1627 return ((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
1631 * Get the first day of the current month, adjusted for leap year. The returned value
1632 * is the numeric day index within the week (0-6) which can be used in conjunction with
1633 * the {@link #monthNames} array to retrieve the textual day name.
1636 var dt = new Date('1/10/2007');
1637 document.write(Date.dayNames[dt.getFirstDayOfMonth()]); //output: 'Monday'
1639 * @return {Number} The day number (0-6)
1641 Date.prototype.getFirstDayOfMonth = function() {
1642 var day = (this.getDay() - (this.getDate() - 1)) % 7;
1643 return (day < 0) ? (day + 7) : day;
1647 * Get the last day of the current month, adjusted for leap year. The returned value
1648 * is the numeric day index within the week (0-6) which can be used in conjunction with
1649 * the {@link #monthNames} array to retrieve the textual day name.
1652 var dt = new Date('1/10/2007');
1653 document.write(Date.dayNames[dt.getLastDayOfMonth()]); //output: 'Wednesday'
1655 * @return {Number} The day number (0-6)
1657 Date.prototype.getLastDayOfMonth = function() {
1658 var day = (this.getDay() + (Date.daysInMonth[this.getMonth()] - this.getDate())) % 7;
1659 return (day < 0) ? (day + 7) : day;
1664 * Get the first date of this date's month
1667 Date.prototype.getFirstDateOfMonth = function() {
1668 return new Date(this.getFullYear(), this.getMonth(), 1);
1672 * Get the last date of this date's month
1675 Date.prototype.getLastDateOfMonth = function() {
1676 return new Date(this.getFullYear(), this.getMonth(), this.getDaysInMonth());
1679 * Get the number of days in the current month, adjusted for leap year.
1680 * @return {Number} The number of days in the month
1682 Date.prototype.getDaysInMonth = function() {
1683 Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
1684 return Date.daysInMonth[this.getMonth()];
1688 * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S').
1689 * @return {String} 'st, 'nd', 'rd' or 'th'
1691 Date.prototype.getSuffix = function() {
1692 switch (this.getDate()) {
1709 Date.daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
1712 * An array of textual month names.
1713 * Override these values for international dates, for example...
1714 * Date.monthNames = ['JanInYourLang', 'FebInYourLang', ...];
1733 * An array of textual day names.
1734 * Override these values for international dates, for example...
1735 * Date.dayNames = ['SundayInYourLang', 'MondayInYourLang', ...];
1751 Date.monthNumbers = {
1766 * Creates and returns a new Date instance with the exact same date value as the called instance.
1767 * Dates are copied and passed by reference, so if a copied date variable is modified later, the original
1768 * variable will also be changed. When the intention is to create a new variable that will not
1769 * modify the original instance, you should create a clone.
1771 * Example of correctly cloning a date:
1774 var orig = new Date('10/1/2006');
1777 document.write(orig); //returns 'Thu Oct 05 2006'!
1780 var orig = new Date('10/1/2006');
1781 var copy = orig.clone();
1783 document.write(orig); //returns 'Thu Oct 01 2006'
1785 * @return {Date} The new Date instance
1787 Date.prototype.clone = function() {
1788 return new Date(this.getTime());
1792 * Clears any time information from this date
1793 @param {Boolean} clone true to create a clone of this date, clear the time and return it
1794 @return {Date} this or the clone
1796 Date.prototype.clearTime = function(clone){
1798 return this.clone().clearTime();
1803 this.setMilliseconds(0);
1808 // safari setMonth is broken -- check that this is only donw once...
1809 if(Roo.isSafari && typeof(Date.brokenSetMonth) == 'undefined'){
1810 Date.brokenSetMonth = Date.prototype.setMonth;
1811 Date.prototype.setMonth = function(num){
1813 var n = Math.ceil(-num);
1814 var back_year = Math.ceil(n/12);
1815 var month = (n % 12) ? 12 - n % 12 : 0 ;
1816 this.setFullYear(this.getFullYear() - back_year);
1817 return Date.brokenSetMonth.call(this, month);
1819 return Date.brokenSetMonth.apply(this, arguments);
1824 /** Date interval constant
1828 /** Date interval constant
1832 /** Date interval constant
1836 /** Date interval constant
1840 /** Date interval constant
1844 /** Date interval constant
1848 /** Date interval constant
1854 * Provides a convenient method of performing basic date arithmetic. This method
1855 * does not modify the Date instance being called - it creates and returns
1856 * a new Date instance containing the resulting date value.
1861 var dt = new Date('10/29/2006').add(Date.DAY, 5);
1862 document.write(dt); //returns 'Fri Oct 06 2006 00:00:00'
1864 //Negative values will subtract correctly:
1865 var dt2 = new Date('10/1/2006').add(Date.DAY, -5);
1866 document.write(dt2); //returns 'Tue Sep 26 2006 00:00:00'
1868 //You can even chain several calls together in one line!
1869 var dt3 = new Date('10/1/2006').add(Date.DAY, 5).add(Date.HOUR, 8).add(Date.MINUTE, -30);
1870 document.write(dt3); //returns 'Fri Oct 06 2006 07:30:00'
1873 * @param {String} interval A valid date interval enum value
1874 * @param {Number} value The amount to add to the current date
1875 * @return {Date} The new Date instance
1877 Date.prototype.add = function(interval, value){
1878 var d = this.clone();
1879 if (!interval || value === 0) { return d; }
1880 switch(interval.toLowerCase()){
1882 d.setMilliseconds(this.getMilliseconds() + value);
1885 d.setSeconds(this.getSeconds() + value);
1888 d.setMinutes(this.getMinutes() + value);
1891 d.setHours(this.getHours() + value);
1894 d.setDate(this.getDate() + value);
1897 var day = this.getDate();
1899 day = Math.min(day, this.getFirstDateOfMonth().add('mo', value).getLastDateOfMonth().getDate());
1902 d.setMonth(this.getMonth() + value);
1905 d.setFullYear(this.getFullYear() + value);
1911 * @class Roo.lib.Dom
1915 * Dom utils (from YIU afaik)
1921 * Get the view width
1922 * @param {Boolean} full True will get the full document, otherwise it's the view width
1923 * @return {Number} The width
1926 getViewWidth : function(full) {
1927 return full ? this.getDocumentWidth() : this.getViewportWidth();
1930 * Get the view height
1931 * @param {Boolean} full True will get the full document, otherwise it's the view height
1932 * @return {Number} The height
1934 getViewHeight : function(full) {
1935 return full ? this.getDocumentHeight() : this.getViewportHeight();
1938 * Get the Full Document height
1939 * @return {Number} The height
1941 getDocumentHeight: function() {
1942 var scrollHeight = (document.compatMode != "CSS1Compat") ? document.body.scrollHeight : document.documentElement.scrollHeight;
1943 return Math.max(scrollHeight, this.getViewportHeight());
1946 * Get the Full Document width
1947 * @return {Number} The width
1949 getDocumentWidth: function() {
1950 var scrollWidth = (document.compatMode != "CSS1Compat") ? document.body.scrollWidth : document.documentElement.scrollWidth;
1951 return Math.max(scrollWidth, this.getViewportWidth());
1954 * Get the Window Viewport height
1955 * @return {Number} The height
1957 getViewportHeight: function() {
1958 var height = self.innerHeight;
1959 var mode = document.compatMode;
1961 if ((mode || Roo.isIE) && !Roo.isOpera) {
1962 height = (mode == "CSS1Compat") ?
1963 document.documentElement.clientHeight :
1964 document.body.clientHeight;
1970 * Get the Window Viewport width
1971 * @return {Number} The width
1973 getViewportWidth: function() {
1974 var width = self.innerWidth;
1975 var mode = document.compatMode;
1977 if (mode || Roo.isIE) {
1978 width = (mode == "CSS1Compat") ?
1979 document.documentElement.clientWidth :
1980 document.body.clientWidth;
1985 isAncestor : function(p, c) {
1992 if (p.contains && !Roo.isSafari) {
1993 return p.contains(c);
1994 } else if (p.compareDocumentPosition) {
1995 return !!(p.compareDocumentPosition(c) & 16);
1997 var parent = c.parentNode;
2002 else if (!parent.tagName || parent.tagName.toUpperCase() == "HTML") {
2005 parent = parent.parentNode;
2011 getRegion : function(el) {
2012 return Roo.lib.Region.getRegion(el);
2015 getY : function(el) {
2016 return this.getXY(el)[1];
2019 getX : function(el) {
2020 return this.getXY(el)[0];
2023 getXY : function(el) {
2024 var p, pe, b, scroll, bd = document.body;
2025 el = Roo.getDom(el);
2026 var fly = Roo.lib.AnimBase.fly;
2027 if (el.getBoundingClientRect) {
2028 b = el.getBoundingClientRect();
2029 scroll = fly(document).getScroll();
2030 return [b.left + scroll.left, b.top + scroll.top];
2036 var hasAbsolute = fly(el).getStyle("position") == "absolute";
2043 if (!hasAbsolute && fly(p).getStyle("position") == "absolute") {
2050 var bt = parseInt(pe.getStyle("borderTopWidth"), 10) || 0;
2051 var bl = parseInt(pe.getStyle("borderLeftWidth"), 10) || 0;
2058 if (p != el && pe.getStyle('overflow') != 'visible') {
2066 if (Roo.isSafari && hasAbsolute) {
2071 if (Roo.isGecko && !hasAbsolute) {
2073 x += parseInt(dbd.getStyle("borderLeftWidth"), 10) || 0;
2074 y += parseInt(dbd.getStyle("borderTopWidth"), 10) || 0;
2078 while (p && p != bd) {
2079 if (!Roo.isOpera || (p.tagName != 'TR' && fly(p).getStyle("display") != "inline")) {
2091 setXY : function(el, xy) {
2092 el = Roo.fly(el, '_setXY');
2094 var pts = el.translatePoints(xy);
2095 if (xy[0] !== false) {
2096 el.dom.style.left = pts.left + "px";
2098 if (xy[1] !== false) {
2099 el.dom.style.top = pts.top + "px";
2103 setX : function(el, x) {
2104 this.setXY(el, [x, false]);
2107 setY : function(el, y) {
2108 this.setXY(el, [false, y]);
2112 * Portions of this file are based on pieces of Yahoo User Interface Library
2113 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
2114 * YUI licensed under the BSD License:
2115 * http://developer.yahoo.net/yui/license.txt
2116 * <script type="text/javascript">
2120 Roo.lib.Event = function() {
2121 var loadComplete = false;
2123 var unloadListeners = [];
2125 var onAvailStack = [];
2127 var lastError = null;
2140 startInterval: function() {
2141 if (!this._interval) {
2143 var callback = function() {
2144 self._tryPreloadAttach();
2146 this._interval = setInterval(callback, this.POLL_INTERVAL);
2151 onAvailable: function(p_id, p_fn, p_obj, p_override) {
2152 onAvailStack.push({ id: p_id,
2155 override: p_override,
2156 checkReady: false });
2158 retryCount = this.POLL_RETRYS;
2159 this.startInterval();
2163 addListener: function(el, eventName, fn) {
2164 el = Roo.getDom(el);
2169 if ("unload" == eventName) {
2170 unloadListeners[unloadListeners.length] =
2171 [el, eventName, fn];
2175 var wrappedFn = function(e) {
2176 return fn(Roo.lib.Event.getEvent(e));
2179 var li = [el, eventName, fn, wrappedFn];
2181 var index = listeners.length;
2182 listeners[index] = li;
2184 this.doAdd(el, eventName, wrappedFn, false);
2190 removeListener: function(el, eventName, fn) {
2193 el = Roo.getDom(el);
2196 return this.purgeElement(el, false, eventName);
2200 if ("unload" == eventName) {
2202 for (i = 0,len = unloadListeners.length; i < len; i++) {
2203 var li = unloadListeners[i];
2206 li[1] == eventName &&
2208 unloadListeners.splice(i, 1);
2216 var cacheItem = null;
2219 var index = arguments[3];
2221 if ("undefined" == typeof index) {
2222 index = this._getCacheIndex(el, eventName, fn);
2226 cacheItem = listeners[index];
2229 if (!el || !cacheItem) {
2233 this.doRemove(el, eventName, cacheItem[this.WFN], false);
2235 delete listeners[index][this.WFN];
2236 delete listeners[index][this.FN];
2237 listeners.splice(index, 1);
2244 getTarget: function(ev, resolveTextNode) {
2245 ev = ev.browserEvent || ev;
2246 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2247 var t = ev.target || ev.srcElement;
2248 return this.resolveTextNode(t);
2252 resolveTextNode: function(node) {
2253 if (Roo.isSafari && node && 3 == node.nodeType) {
2254 return node.parentNode;
2261 getPageX: function(ev) {
2262 ev = ev.browserEvent || ev;
2263 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2265 if (!x && 0 !== x) {
2266 x = ev.clientX || 0;
2269 x += this.getScroll()[1];
2277 getPageY: function(ev) {
2278 ev = ev.browserEvent || ev;
2279 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2281 if (!y && 0 !== y) {
2282 y = ev.clientY || 0;
2285 y += this.getScroll()[0];
2294 getXY: function(ev) {
2295 ev = ev.browserEvent || ev;
2296 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2297 return [this.getPageX(ev), this.getPageY(ev)];
2301 getRelatedTarget: function(ev) {
2302 ev = ev.browserEvent || ev;
2303 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2304 var t = ev.relatedTarget;
2306 if (ev.type == "mouseout") {
2308 } else if (ev.type == "mouseover") {
2313 return this.resolveTextNode(t);
2317 getTime: function(ev) {
2318 ev = ev.browserEvent || ev;
2319 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2321 var t = new Date().getTime();
2325 this.lastError = ex;
2334 stopEvent: function(ev) {
2335 this.stopPropagation(ev);
2336 this.preventDefault(ev);
2340 stopPropagation: function(ev) {
2341 ev = ev.browserEvent || ev;
2342 if (ev.stopPropagation) {
2343 ev.stopPropagation();
2345 ev.cancelBubble = true;
2350 preventDefault: function(ev) {
2351 ev = ev.browserEvent || ev;
2352 if(ev.preventDefault) {
2353 ev.preventDefault();
2355 ev.returnValue = false;
2360 getEvent: function(e) {
2361 var ev = e || window.event;
2363 var c = this.getEvent.caller;
2365 ev = c.arguments[0];
2366 if (ev && Event == ev.constructor) {
2376 getCharCode: function(ev) {
2377 ev = ev.browserEvent || ev;
2378 return ev.charCode || ev.keyCode || 0;
2382 _getCacheIndex: function(el, eventName, fn) {
2383 for (var i = 0,len = listeners.length; i < len; ++i) {
2384 var li = listeners[i];
2386 li[this.FN] == fn &&
2387 li[this.EL] == el &&
2388 li[this.TYPE] == eventName) {
2400 getEl: function(id) {
2401 return document.getElementById(id);
2405 clearCache: function() {
2409 _load: function(e) {
2410 loadComplete = true;
2411 var EU = Roo.lib.Event;
2415 EU.doRemove(window, "load", EU._load);
2420 _tryPreloadAttach: function() {
2429 var tryAgain = !loadComplete;
2431 tryAgain = (retryCount > 0);
2436 for (var i = 0,len = onAvailStack.length; i < len; ++i) {
2437 var item = onAvailStack[i];
2439 var el = this.getEl(item.id);
2442 if (!item.checkReady ||
2445 (document && document.body)) {
2448 if (item.override) {
2449 if (item.override === true) {
2452 scope = item.override;
2455 item.fn.call(scope, item.obj);
2456 onAvailStack[i] = null;
2459 notAvail.push(item);
2464 retryCount = (notAvail.length === 0) ? 0 : retryCount - 1;
2468 this.startInterval();
2470 clearInterval(this._interval);
2471 this._interval = null;
2474 this.locked = false;
2481 purgeElement: function(el, recurse, eventName) {
2482 var elListeners = this.getListeners(el, eventName);
2484 for (var i = 0,len = elListeners.length; i < len; ++i) {
2485 var l = elListeners[i];
2486 this.removeListener(el, l.type, l.fn);
2490 if (recurse && el && el.childNodes) {
2491 for (i = 0,len = el.childNodes.length; i < len; ++i) {
2492 this.purgeElement(el.childNodes[i], recurse, eventName);
2498 getListeners: function(el, eventName) {
2499 var results = [], searchLists;
2501 searchLists = [listeners, unloadListeners];
2502 } else if (eventName == "unload") {
2503 searchLists = [unloadListeners];
2505 searchLists = [listeners];
2508 for (var j = 0; j < searchLists.length; ++j) {
2509 var searchList = searchLists[j];
2510 if (searchList && searchList.length > 0) {
2511 for (var i = 0,len = searchList.length; i < len; ++i) {
2512 var l = searchList[i];
2513 if (l && l[this.EL] === el &&
2514 (!eventName || eventName === l[this.TYPE])) {
2519 adjust: l[this.ADJ_SCOPE],
2527 return (results.length) ? results : null;
2531 _unload: function(e) {
2533 var EU = Roo.lib.Event, i, j, l, len, index;
2535 for (i = 0,len = unloadListeners.length; i < len; ++i) {
2536 l = unloadListeners[i];
2539 if (l[EU.ADJ_SCOPE]) {
2540 if (l[EU.ADJ_SCOPE] === true) {
2543 scope = l[EU.ADJ_SCOPE];
2546 l[EU.FN].call(scope, EU.getEvent(e), l[EU.OBJ]);
2547 unloadListeners[i] = null;
2553 unloadListeners = null;
2555 if (listeners && listeners.length > 0) {
2556 j = listeners.length;
2559 l = listeners[index];
2561 EU.removeListener(l[EU.EL], l[EU.TYPE],
2571 EU.doRemove(window, "unload", EU._unload);
2576 getScroll: function() {
2577 var dd = document.documentElement, db = document.body;
2578 if (dd && (dd.scrollTop || dd.scrollLeft)) {
2579 return [dd.scrollTop, dd.scrollLeft];
2581 return [db.scrollTop, db.scrollLeft];
2588 doAdd: function () {
2589 if (window.addEventListener) {
2590 return function(el, eventName, fn, capture) {
2591 el.addEventListener(eventName, fn, (capture));
2593 } else if (window.attachEvent) {
2594 return function(el, eventName, fn, capture) {
2595 el.attachEvent("on" + eventName, fn);
2604 doRemove: function() {
2605 if (window.removeEventListener) {
2606 return function (el, eventName, fn, capture) {
2607 el.removeEventListener(eventName, fn, (capture));
2609 } else if (window.detachEvent) {
2610 return function (el, eventName, fn) {
2611 el.detachEvent("on" + eventName, fn);
2623 var E = Roo.lib.Event;
2624 E.on = E.addListener;
2625 E.un = E.removeListener;
2627 if (document && document.body) {
2630 E.doAdd(window, "load", E._load);
2632 E.doAdd(window, "unload", E._unload);
2633 E._tryPreloadAttach();
2640 * @class Roo.lib.Ajax
2642 * provide a simple Ajax request utility functions
2644 * Portions of this file are based on pieces of Yahoo User Interface Library
2645 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
2646 * YUI licensed under the BSD License:
2647 * http://developer.yahoo.net/yui/license.txt
2648 * <script type="text/javascript">
2656 request : function(method, uri, cb, data, options) {
2658 var hs = options.headers;
2661 if(hs.hasOwnProperty(h)){
2662 this.initHeader(h, hs[h], false);
2666 if(options.xmlData){
2667 this.initHeader('Content-Type', 'text/xml', false);
2669 data = options.xmlData;
2673 return this.asyncRequest(method, uri, cb, data);
2679 * @param {DomForm} form element
2680 * @return {String} urlencode form output.
2682 serializeForm : function(form) {
2683 if(typeof form == 'string') {
2684 form = (document.getElementById(form) || document.forms[form]);
2687 var el, name, val, disabled, data = '', hasSubmit = false;
2688 for (var i = 0; i < form.elements.length; i++) {
2689 el = form.elements[i];
2690 disabled = form.elements[i].disabled;
2691 name = form.elements[i].name;
2692 val = form.elements[i].value;
2694 if (!disabled && name){
2698 case 'select-multiple':
2699 for (var j = 0; j < el.options.length; j++) {
2700 if (el.options[j].selected) {
2702 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(el.options[j].attributes['value'].specified ? el.options[j].value : el.options[j].text) + '&';
2705 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(el.options[j].hasAttribute('value') ? el.options[j].value : el.options[j].text) + '&';
2713 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2726 if(hasSubmit == false) {
2727 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2732 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2737 data = data.substr(0, data.length - 1);
2745 useDefaultHeader:true,
2747 defaultPostHeader:'application/x-www-form-urlencoded',
2749 useDefaultXhrHeader:true,
2751 defaultXhrHeader:'XMLHttpRequest',
2753 hasDefaultHeaders:true,
2765 setProgId:function(id)
2767 this.activeX.unshift(id);
2770 setDefaultPostHeader:function(b)
2772 this.useDefaultHeader = b;
2775 setDefaultXhrHeader:function(b)
2777 this.useDefaultXhrHeader = b;
2780 setPollingInterval:function(i)
2782 if (typeof i == 'number' && isFinite(i)) {
2783 this.pollInterval = i;
2787 createXhrObject:function(transactionId)
2793 http = new XMLHttpRequest();
2795 obj = { conn:http, tId:transactionId };
2799 for (var i = 0; i < this.activeX.length; ++i) {
2803 http = new ActiveXObject(this.activeX[i]);
2805 obj = { conn:http, tId:transactionId };
2818 getConnectionObject:function()
2821 var tId = this.transactionId;
2825 o = this.createXhrObject(tId);
2827 this.transactionId++;
2838 asyncRequest:function(method, uri, callback, postData)
2840 var o = this.getConnectionObject();
2846 o.conn.open(method, uri, true);
2848 if (this.useDefaultXhrHeader) {
2849 if (!this.defaultHeaders['X-Requested-With']) {
2850 this.initHeader('X-Requested-With', this.defaultXhrHeader, true);
2854 if(postData && this.useDefaultHeader){
2855 this.initHeader('Content-Type', this.defaultPostHeader);
2858 if (this.hasDefaultHeaders || this.hasHeaders) {
2862 this.handleReadyState(o, callback);
2863 o.conn.send(postData || null);
2869 handleReadyState:function(o, callback)
2873 if (callback && callback.timeout) {
2875 this.timeout[o.tId] = window.setTimeout(function() {
2876 oConn.abort(o, callback, true);
2877 }, callback.timeout);
2880 this.poll[o.tId] = window.setInterval(
2882 if (o.conn && o.conn.readyState == 4) {
2883 window.clearInterval(oConn.poll[o.tId]);
2884 delete oConn.poll[o.tId];
2886 if(callback && callback.timeout) {
2887 window.clearTimeout(oConn.timeout[o.tId]);
2888 delete oConn.timeout[o.tId];
2891 oConn.handleTransactionResponse(o, callback);
2894 , this.pollInterval);
2897 handleTransactionResponse:function(o, callback, isAbort)
2901 this.releaseObject(o);
2905 var httpStatus, responseObject;
2909 if (o.conn.status !== undefined && o.conn.status != 0) {
2910 httpStatus = o.conn.status;
2922 if (httpStatus >= 200 && httpStatus < 300) {
2923 responseObject = this.createResponseObject(o, callback.argument);
2924 if (callback.success) {
2925 if (!callback.scope) {
2926 callback.success(responseObject);
2931 callback.success.apply(callback.scope, [responseObject]);
2936 switch (httpStatus) {
2944 responseObject = this.createExceptionObject(o.tId, callback.argument, (isAbort ? isAbort : false));
2945 if (callback.failure) {
2946 if (!callback.scope) {
2947 callback.failure(responseObject);
2950 callback.failure.apply(callback.scope, [responseObject]);
2955 responseObject = this.createResponseObject(o, callback.argument);
2956 if (callback.failure) {
2957 if (!callback.scope) {
2958 callback.failure(responseObject);
2961 callback.failure.apply(callback.scope, [responseObject]);
2967 this.releaseObject(o);
2968 responseObject = null;
2971 createResponseObject:function(o, callbackArg)
2978 var headerStr = o.conn.getAllResponseHeaders();
2979 var header = headerStr.split('\n');
2980 for (var i = 0; i < header.length; i++) {
2981 var delimitPos = header[i].indexOf(':');
2982 if (delimitPos != -1) {
2983 headerObj[header[i].substring(0, delimitPos)] = header[i].substring(delimitPos + 2);
2991 obj.status = o.conn.status;
2992 obj.statusText = o.conn.statusText;
2993 obj.getResponseHeader = headerObj;
2994 obj.getAllResponseHeaders = headerStr;
2995 obj.responseText = o.conn.responseText;
2996 obj.responseXML = o.conn.responseXML;
2998 if (typeof callbackArg !== undefined) {
2999 obj.argument = callbackArg;
3005 createExceptionObject:function(tId, callbackArg, isAbort)
3008 var COMM_ERROR = 'communication failure';
3009 var ABORT_CODE = -1;
3010 var ABORT_ERROR = 'transaction aborted';
3016 obj.status = ABORT_CODE;
3017 obj.statusText = ABORT_ERROR;
3020 obj.status = COMM_CODE;
3021 obj.statusText = COMM_ERROR;
3025 obj.argument = callbackArg;
3031 initHeader:function(label, value, isDefault)
3033 var headerObj = (isDefault) ? this.defaultHeaders : this.headers;
3035 if (headerObj[label] === undefined) {
3036 headerObj[label] = value;
3041 headerObj[label] = value + "," + headerObj[label];
3045 this.hasDefaultHeaders = true;
3048 this.hasHeaders = true;
3053 setHeader:function(o)
3055 if (this.hasDefaultHeaders) {
3056 for (var prop in this.defaultHeaders) {
3057 if (this.defaultHeaders.hasOwnProperty(prop)) {
3058 o.conn.setRequestHeader(prop, this.defaultHeaders[prop]);
3063 if (this.hasHeaders) {
3064 for (var prop in this.headers) {
3065 if (this.headers.hasOwnProperty(prop)) {
3066 o.conn.setRequestHeader(prop, this.headers[prop]);
3070 this.hasHeaders = false;
3074 resetDefaultHeaders:function() {
3075 delete this.defaultHeaders;
3076 this.defaultHeaders = {};
3077 this.hasDefaultHeaders = false;
3080 abort:function(o, callback, isTimeout)
3082 if(this.isCallInProgress(o)) {
3084 window.clearInterval(this.poll[o.tId]);
3085 delete this.poll[o.tId];
3087 delete this.timeout[o.tId];
3090 this.handleTransactionResponse(o, callback, true);
3100 isCallInProgress:function(o)
3103 return o.conn.readyState != 4 && o.conn.readyState != 0;
3112 releaseObject:function(o)
3121 'MSXML2.XMLHTTP.3.0',
3129 * Portions of this file are based on pieces of Yahoo User Interface Library
3130 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3131 * YUI licensed under the BSD License:
3132 * http://developer.yahoo.net/yui/license.txt
3133 * <script type="text/javascript">
3137 Roo.lib.Region = function(t, r, b, l) {
3147 Roo.lib.Region.prototype = {
3148 contains : function(region) {
3149 return ( region.left >= this.left &&
3150 region.right <= this.right &&
3151 region.top >= this.top &&
3152 region.bottom <= this.bottom );
3156 getArea : function() {
3157 return ( (this.bottom - this.top) * (this.right - this.left) );
3160 intersect : function(region) {
3161 var t = Math.max(this.top, region.top);
3162 var r = Math.min(this.right, region.right);
3163 var b = Math.min(this.bottom, region.bottom);
3164 var l = Math.max(this.left, region.left);
3166 if (b >= t && r >= l) {
3167 return new Roo.lib.Region(t, r, b, l);
3172 union : function(region) {
3173 var t = Math.min(this.top, region.top);
3174 var r = Math.max(this.right, region.right);
3175 var b = Math.max(this.bottom, region.bottom);
3176 var l = Math.min(this.left, region.left);
3178 return new Roo.lib.Region(t, r, b, l);
3181 adjust : function(t, l, b, r) {
3190 Roo.lib.Region.getRegion = function(el) {
3191 var p = Roo.lib.Dom.getXY(el);
3194 var r = p[0] + el.offsetWidth;
3195 var b = p[1] + el.offsetHeight;
3198 return new Roo.lib.Region(t, r, b, l);
3201 * Portions of this file are based on pieces of Yahoo User Interface Library
3202 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3203 * YUI licensed under the BSD License:
3204 * http://developer.yahoo.net/yui/license.txt
3205 * <script type="text/javascript">
3208 //@@dep Roo.lib.Region
3211 Roo.lib.Point = function(x, y) {
3212 if (x instanceof Array) {
3216 this.x = this.right = this.left = this[0] = x;
3217 this.y = this.top = this.bottom = this[1] = y;
3220 Roo.lib.Point.prototype = new Roo.lib.Region();
3222 * Portions of this file are based on pieces of Yahoo User Interface Library
3223 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3224 * YUI licensed under the BSD License:
3225 * http://developer.yahoo.net/yui/license.txt
3226 * <script type="text/javascript">
3233 scroll : function(el, args, duration, easing, cb, scope) {
3234 this.run(el, args, duration, easing, cb, scope, Roo.lib.Scroll);
3237 motion : function(el, args, duration, easing, cb, scope) {
3238 this.run(el, args, duration, easing, cb, scope, Roo.lib.Motion);
3241 color : function(el, args, duration, easing, cb, scope) {
3242 this.run(el, args, duration, easing, cb, scope, Roo.lib.ColorAnim);
3245 run : function(el, args, duration, easing, cb, scope, type) {
3246 type = type || Roo.lib.AnimBase;
3247 if (typeof easing == "string") {
3248 easing = Roo.lib.Easing[easing];
3250 var anim = new type(el, args, duration, easing);
3251 anim.animateX(function() {
3252 Roo.callback(cb, scope);
3258 * Portions of this file are based on pieces of Yahoo User Interface Library
3259 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3260 * YUI licensed under the BSD License:
3261 * http://developer.yahoo.net/yui/license.txt
3262 * <script type="text/javascript">
3270 if (!libFlyweight) {
3271 libFlyweight = new Roo.Element.Flyweight();
3273 libFlyweight.dom = el;
3274 return libFlyweight;
3277 // since this uses fly! - it cant be in DOM (which does not have fly yet..)
3281 Roo.lib.AnimBase = function(el, attributes, duration, method) {
3283 this.init(el, attributes, duration, method);
3287 Roo.lib.AnimBase.fly = fly;
3291 Roo.lib.AnimBase.prototype = {
3293 toString: function() {
3294 var el = this.getEl();
3295 var id = el.id || el.tagName;
3296 return ("Anim " + id);
3300 noNegatives: /width|height|opacity|padding/i,
3301 offsetAttribute: /^((width|height)|(top|left))$/,
3302 defaultUnit: /width|height|top$|bottom$|left$|right$/i,
3303 offsetUnit: /\d+(em|%|en|ex|pt|in|cm|mm|pc)$/i
3307 doMethod: function(attr, start, end) {
3308 return this.method(this.currentFrame, start, end - start, this.totalFrames);
3312 setAttribute: function(attr, val, unit) {
3313 if (this.patterns.noNegatives.test(attr)) {
3314 val = (val > 0) ? val : 0;
3317 Roo.fly(this.getEl(), '_anim').setStyle(attr, val + unit);
3321 getAttribute: function(attr) {
3322 var el = this.getEl();
3323 var val = fly(el).getStyle(attr);
3325 if (val !== 'auto' && !this.patterns.offsetUnit.test(val)) {
3326 return parseFloat(val);
3329 var a = this.patterns.offsetAttribute.exec(attr) || [];
3330 var pos = !!( a[3] );
3331 var box = !!( a[2] );
3334 if (box || (fly(el).getStyle('position') == 'absolute' && pos)) {
3335 val = el['offset' + a[0].charAt(0).toUpperCase() + a[0].substr(1)];
3344 getDefaultUnit: function(attr) {
3345 if (this.patterns.defaultUnit.test(attr)) {
3352 animateX : function(callback, scope) {
3353 var f = function() {
3354 this.onComplete.removeListener(f);
3355 if (typeof callback == "function") {
3356 callback.call(scope || this, this);
3359 this.onComplete.addListener(f, this);
3364 setRuntimeAttribute: function(attr) {
3367 var attributes = this.attributes;
3369 this.runtimeAttributes[attr] = {};
3371 var isset = function(prop) {
3372 return (typeof prop !== 'undefined');
3375 if (!isset(attributes[attr]['to']) && !isset(attributes[attr]['by'])) {
3379 start = ( isset(attributes[attr]['from']) ) ? attributes[attr]['from'] : this.getAttribute(attr);
3382 if (isset(attributes[attr]['to'])) {
3383 end = attributes[attr]['to'];
3384 } else if (isset(attributes[attr]['by'])) {
3385 if (start.constructor == Array) {
3387 for (var i = 0, len = start.length; i < len; ++i) {
3388 end[i] = start[i] + attributes[attr]['by'][i];
3391 end = start + attributes[attr]['by'];
3395 this.runtimeAttributes[attr].start = start;
3396 this.runtimeAttributes[attr].end = end;
3399 this.runtimeAttributes[attr].unit = ( isset(attributes[attr].unit) ) ? attributes[attr]['unit'] : this.getDefaultUnit(attr);
3403 init: function(el, attributes, duration, method) {
3405 var isAnimated = false;
3408 var startTime = null;
3411 var actualFrames = 0;
3414 el = Roo.getDom(el);
3417 this.attributes = attributes || {};
3420 this.duration = duration || 1;
3423 this.method = method || Roo.lib.Easing.easeNone;
3426 this.useSeconds = true;
3429 this.currentFrame = 0;
3432 this.totalFrames = Roo.lib.AnimMgr.fps;
3435 this.getEl = function() {
3440 this.isAnimated = function() {
3445 this.getStartTime = function() {
3449 this.runtimeAttributes = {};
3452 this.animate = function() {
3453 if (this.isAnimated()) {
3457 this.currentFrame = 0;
3459 this.totalFrames = ( this.useSeconds ) ? Math.ceil(Roo.lib.AnimMgr.fps * this.duration) : this.duration;
3461 Roo.lib.AnimMgr.registerElement(this);
3465 this.stop = function(finish) {
3467 this.currentFrame = this.totalFrames;
3468 this._onTween.fire();
3470 Roo.lib.AnimMgr.stop(this);
3473 var onStart = function() {
3474 this.onStart.fire();
3476 this.runtimeAttributes = {};
3477 for (var attr in this.attributes) {
3478 this.setRuntimeAttribute(attr);
3483 startTime = new Date();
3487 var onTween = function() {
3489 duration: new Date() - this.getStartTime(),
3490 currentFrame: this.currentFrame
3493 data.toString = function() {
3495 'duration: ' + data.duration +
3496 ', currentFrame: ' + data.currentFrame
3500 this.onTween.fire(data);
3502 var runtimeAttributes = this.runtimeAttributes;
3504 for (var attr in runtimeAttributes) {
3505 this.setAttribute(attr, this.doMethod(attr, runtimeAttributes[attr].start, runtimeAttributes[attr].end), runtimeAttributes[attr].unit);
3511 var onComplete = function() {
3512 var actual_duration = (new Date() - startTime) / 1000 ;
3515 duration: actual_duration,
3516 frames: actualFrames,
3517 fps: actualFrames / actual_duration
3520 data.toString = function() {
3522 'duration: ' + data.duration +
3523 ', frames: ' + data.frames +
3524 ', fps: ' + data.fps
3530 this.onComplete.fire(data);
3534 this._onStart = new Roo.util.Event(this);
3535 this.onStart = new Roo.util.Event(this);
3536 this.onTween = new Roo.util.Event(this);
3537 this._onTween = new Roo.util.Event(this);
3538 this.onComplete = new Roo.util.Event(this);
3539 this._onComplete = new Roo.util.Event(this);
3540 this._onStart.addListener(onStart);
3541 this._onTween.addListener(onTween);
3542 this._onComplete.addListener(onComplete);
3547 * Portions of this file are based on pieces of Yahoo User Interface Library
3548 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3549 * YUI licensed under the BSD License:
3550 * http://developer.yahoo.net/yui/license.txt
3551 * <script type="text/javascript">
3555 Roo.lib.AnimMgr = new function() {
3572 this.registerElement = function(tween) {
3573 queue[queue.length] = tween;
3575 tween._onStart.fire();
3580 this.unRegister = function(tween, index) {
3581 tween._onComplete.fire();
3582 index = index || getIndex(tween);
3584 queue.splice(index, 1);
3588 if (tweenCount <= 0) {
3594 this.start = function() {
3595 if (thread === null) {
3596 thread = setInterval(this.run, this.delay);
3601 this.stop = function(tween) {
3603 clearInterval(thread);
3605 for (var i = 0, len = queue.length; i < len; ++i) {
3606 if (queue[0].isAnimated()) {
3607 this.unRegister(queue[0], 0);
3616 this.unRegister(tween);
3621 this.run = function() {
3622 for (var i = 0, len = queue.length; i < len; ++i) {
3623 var tween = queue[i];
3624 if (!tween || !tween.isAnimated()) {
3628 if (tween.currentFrame < tween.totalFrames || tween.totalFrames === null)
3630 tween.currentFrame += 1;
3632 if (tween.useSeconds) {
3633 correctFrame(tween);
3635 tween._onTween.fire();
3638 Roo.lib.AnimMgr.stop(tween, i);
3643 var getIndex = function(anim) {
3644 for (var i = 0, len = queue.length; i < len; ++i) {
3645 if (queue[i] == anim) {
3653 var correctFrame = function(tween) {
3654 var frames = tween.totalFrames;
3655 var frame = tween.currentFrame;
3656 var expected = (tween.currentFrame * tween.duration * 1000 / tween.totalFrames);
3657 var elapsed = (new Date() - tween.getStartTime());
3660 if (elapsed < tween.duration * 1000) {
3661 tweak = Math.round((elapsed / expected - 1) * tween.currentFrame);
3663 tweak = frames - (frame + 1);
3665 if (tweak > 0 && isFinite(tweak)) {
3666 if (tween.currentFrame + tweak >= frames) {
3667 tweak = frames - (frame + 1);
3670 tween.currentFrame += tweak;
3676 * Portions of this file are based on pieces of Yahoo User Interface Library
3677 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3678 * YUI licensed under the BSD License:
3679 * http://developer.yahoo.net/yui/license.txt
3680 * <script type="text/javascript">
3683 Roo.lib.Bezier = new function() {
3685 this.getPosition = function(points, t) {
3686 var n = points.length;
3689 for (var i = 0; i < n; ++i) {
3690 tmp[i] = [points[i][0], points[i][1]];
3693 for (var j = 1; j < n; ++j) {
3694 for (i = 0; i < n - j; ++i) {
3695 tmp[i][0] = (1 - t) * tmp[i][0] + t * tmp[parseInt(i + 1, 10)][0];
3696 tmp[i][1] = (1 - t) * tmp[i][1] + t * tmp[parseInt(i + 1, 10)][1];
3700 return [ tmp[0][0], tmp[0][1] ];
3706 * @class Roo.lib.Color
3708 * An abstract Color implementation. Concrete Color implementations should use
3709 * an instance of this function as their prototype, and implement the getRGB and
3710 * getHSL functions. getRGB should return an object representing the RGB
3711 * components of this Color, with the red, green, and blue components in the
3712 * range [0,255] and the alpha component in the range [0,100]. getHSL should
3713 * return an object representing the HSL components of this Color, with the hue
3714 * component in the range [0,360), the saturation and lightness components in
3715 * the range [0,100], and the alpha component in the range [0,1].
3720 * Functions for Color handling and processing.
3722 * http://www.safalra.com/web-design/javascript/Color-handling-and-processing/
3724 * The author of this program, Safalra (Stephen Morley), irrevocably releases all
3725 * rights to this program, with the intention of it becoming part of the public
3726 * domain. Because this program is released into the public domain, it comes with
3727 * no warranty either expressed or implied, to the extent permitted by law.
3729 * For more free and public domain JavaScript code by the same author, visit:
3730 * http://www.safalra.com/web-design/javascript/
3733 Roo.lib.Color = function() { }
3736 Roo.apply(Roo.lib.Color.prototype, {
3744 * @return {Object} an object representing the RGBA components of this Color. The red,
3745 * green, and blue components are converted to integers in the range [0,255].
3746 * The alpha is a value in the range [0,1].
3748 getIntegerRGB : function(){
3750 // get the RGB components of this Color
3751 var rgb = this.getRGB();
3753 // return the integer components
3755 'r' : Math.round(rgb.r),
3756 'g' : Math.round(rgb.g),
3757 'b' : Math.round(rgb.b),
3765 * @return {Object} an object representing the RGBA components of this Color. The red,
3766 * green, and blue components are converted to numbers in the range [0,100].
3767 * The alpha is a value in the range [0,1].
3769 getPercentageRGB : function(){
3771 // get the RGB components of this Color
3772 var rgb = this.getRGB();
3774 // return the percentage components
3776 'r' : 100 * rgb.r / 255,
3777 'g' : 100 * rgb.g / 255,
3778 'b' : 100 * rgb.b / 255,
3785 * getCSSHexadecimalRGB
3786 * @return {String} a string representing this Color as a CSS hexadecimal RGB Color
3787 * value - that is, a string of the form #RRGGBB where each of RR, GG, and BB
3788 * are two-digit hexadecimal numbers.
3790 getCSSHexadecimalRGB : function()
3793 // get the integer RGB components
3794 var rgb = this.getIntegerRGB();
3796 // determine the hexadecimal equivalents
3797 var r16 = rgb.r.toString(16);
3798 var g16 = rgb.g.toString(16);
3799 var b16 = rgb.b.toString(16);
3801 // return the CSS RGB Color value
3803 + (r16.length == 2 ? r16 : '0' + r16)
3804 + (g16.length == 2 ? g16 : '0' + g16)
3805 + (b16.length == 2 ? b16 : '0' + b16);
3811 * @return {String} a string representing this Color as a CSS integer RGB Color
3812 * value - that is, a string of the form rgb(r,g,b) where each of r, g, and b
3813 * are integers in the range [0,255].
3815 getCSSIntegerRGB : function(){
3817 // get the integer RGB components
3818 var rgb = this.getIntegerRGB();
3820 // return the CSS RGB Color value
3821 return 'rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ')';
3827 * @return {String} Returns a string representing this Color as a CSS integer RGBA Color
3828 * value - that is, a string of the form rgba(r,g,b,a) where each of r, g, and
3829 * b are integers in the range [0,255] and a is in the range [0,1].
3831 getCSSIntegerRGBA : function(){
3833 // get the integer RGB components
3834 var rgb = this.getIntegerRGB();
3836 // return the CSS integer RGBA Color value
3837 return 'rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + rgb.a + ')';
3842 * getCSSPercentageRGB
3843 * @return {String} a string representing this Color as a CSS percentage RGB Color
3844 * value - that is, a string of the form rgb(r%,g%,b%) where each of r, g, and
3845 * b are in the range [0,100].
3847 getCSSPercentageRGB : function(){
3849 // get the percentage RGB components
3850 var rgb = this.getPercentageRGB();
3852 // return the CSS RGB Color value
3853 return 'rgb(' + rgb.r + '%,' + rgb.g + '%,' + rgb.b + '%)';
3858 * getCSSPercentageRGBA
3859 * @return {String} a string representing this Color as a CSS percentage RGBA Color
3860 * value - that is, a string of the form rgba(r%,g%,b%,a) where each of r, g,
3861 * and b are in the range [0,100] and a is in the range [0,1].
3863 getCSSPercentageRGBA : function(){
3865 // get the percentage RGB components
3866 var rgb = this.getPercentageRGB();
3868 // return the CSS percentage RGBA Color value
3869 return 'rgb(' + rgb.r + '%,' + rgb.g + '%,' + rgb.b + '%,' + rgb.a + ')';
3875 * @return {String} a string representing this Color as a CSS HSL Color value - that
3876 * is, a string of the form hsl(h,s%,l%) where h is in the range [0,100] and
3877 * s and l are in the range [0,100].
3879 getCSSHSL : function(){
3881 // get the HSL components
3882 var hsl = this.getHSL();
3884 // return the CSS HSL Color value
3885 return 'hsl(' + hsl.h + ',' + hsl.s + '%,' + hsl.l + '%)';
3891 * @return {String} a string representing this Color as a CSS HSLA Color value - that
3892 * is, a string of the form hsla(h,s%,l%,a) where h is in the range [0,100],
3893 * s and l are in the range [0,100], and a is in the range [0,1].
3895 getCSSHSLA : function(){
3897 // get the HSL components
3898 var hsl = this.getHSL();
3900 // return the CSS HSL Color value
3901 return 'hsl(' + hsl.h + ',' + hsl.s + '%,' + hsl.l + '%,' + hsl.a + ')';
3906 * Sets the Color of the specified node to this Color. This functions sets
3907 * the CSS 'color' property for the node. The parameter is:
3909 * @param {DomElement} node - the node whose Color should be set
3911 setNodeColor : function(node){
3913 // set the Color of the node
3914 node.style.color = this.getCSSHexadecimalRGB();
3919 * Sets the background Color of the specified node to this Color. This
3920 * functions sets the CSS 'background-color' property for the node. The
3923 * @param {DomElement} node - the node whose background Color should be set
3925 setNodeBackgroundColor : function(node){
3927 // set the background Color of the node
3928 node.style.backgroundColor = this.getCSSHexadecimalRGB();
3931 // convert between formats..
3934 var r = this.getIntegerRGB();
3935 return new Roo.lib.RGBColor(r.r,r.g,r.b,r.a);
3940 var hsl = this.getHSL();
3941 // return the CSS HSL Color value
3942 return new Roo.lib.HSLColor(hsl.h, hsl.s, hsl.l , hsl.a );
3948 var rgb = this.toRGB();
3949 var hsv = rgb.getHSV();
3950 // return the CSS HSL Color value
3951 return new Roo.lib.HSVColor(hsv.h, hsv.s, hsv.v , hsv.a );
3955 // modify v = 0 ... 1 (eg. 0.5)
3956 saturate : function(v)
3958 var rgb = this.toRGB();
3959 var hsv = rgb.getHSV();
3960 return new Roo.lib.HSVColor(hsv.h, hsv.s * v, hsv.v , hsv.a );
3968 * @return {Object} the RGB and alpha components of this Color as an object with r,
3969 * g, b, and a properties. r, g, and b are in the range [0,255] and a is in
3974 // return the RGB components
3986 * @return {Object} the HSV and alpha components of this Color as an object with h,
3987 * s, v, and a properties. h is in the range [0,360), s and v are in the range
3988 * [0,100], and a is in the range [0,1].
3993 // calculate the HSV components if necessary
3994 if (this.hsv == null) {
3995 this.calculateHSV();
3998 // return the HSV components
4010 * @return {Object} the HSL and alpha components of this Color as an object with h,
4011 * s, l, and a properties. h is in the range [0,360), s and l are in the range
4012 * [0,100], and a is in the range [0,1].
4014 getHSL : function(){
4017 // calculate the HSV components if necessary
4018 if (this.hsl == null) { this.calculateHSL(); }
4020 // return the HSL components
4035 * @class Roo.lib.RGBColor
4036 * @extends Roo.lib.Color
4037 * Creates a Color specified in the RGB Color space, with an optional alpha
4038 * component. The parameters are:
4042 * @param {Number} r - the red component, clipped to the range [0,255]
4043 * @param {Number} g - the green component, clipped to the range [0,255]
4044 * @param {Number} b - the blue component, clipped to the range [0,255]
4045 * @param {Number} a - the alpha component, clipped to the range [0,1] - this parameter is
4046 * optional and defaults to 1
4048 Roo.lib.RGBColor = function (r, g, b, a){
4050 // store the alpha component after clipping it if necessary
4051 this.alpha = (a === undefined ? 1 : Math.max(0, Math.min(1, a)));
4053 // store the RGB components after clipping them if necessary
4056 'r' : Math.max(0, Math.min(255, r)),
4057 'g' : Math.max(0, Math.min(255, g)),
4058 'b' : Math.max(0, Math.min(255, b))
4061 // initialise the HSV and HSL components to null
4065 * //private returns the HSV or HSL hue component of this RGBColor. The hue is in the
4066 * range [0,360). The parameters are:
4068 * maximum - the maximum of the RGB component values
4069 * range - the range of the RGB component values
4074 // this does an 'exteds'
4075 Roo.extend(Roo.lib.RGBColor, Roo.lib.Color, {
4078 getHue : function(maximum, range)
4082 // check whether the range is zero
4085 // set the hue to zero (any hue is acceptable as the Color is grey)
4090 // determine which of the components has the highest value and set the hue
4093 // red has the highest value
4095 var hue = (rgb.g - rgb.b) / range * 60;
4096 if (hue < 0) { hue += 360; }
4099 // green has the highest value
4101 var hue = (rgb.b - rgb.r) / range * 60 + 120;
4104 // blue has the highest value
4106 var hue = (rgb.r - rgb.g) / range * 60 + 240;
4118 /* //private Calculates and stores the HSV components of this RGBColor so that they can
4119 * be returned be the getHSV function.
4121 calculateHSV : function(){
4123 // get the maximum and range of the RGB component values
4124 var maximum = Math.max(rgb.r, rgb.g, rgb.b);
4125 var range = maximum - Math.min(rgb.r, rgb.g, rgb.b);
4127 // store the HSV components
4130 'h' : this.getHue(maximum, range),
4131 's' : (maximum == 0 ? 0 : 100 * range / maximum),
4132 'v' : maximum / 2.55
4137 /* //private Calculates and stores the HSL components of this RGBColor so that they can
4138 * be returned be the getHSL function.
4140 calculateHSL : function(){
4142 // get the maximum and range of the RGB component values
4143 var maximum = Math.max(rgb.r, rgb.g, rgb.b);
4144 var range = maximum - Math.min(rgb.r, rgb.g, rgb.b);
4146 // determine the lightness in the range [0,1]
4147 var l = maximum / 255 - range / 510;
4149 // store the HSL components
4152 'h' : this.getHue(maximum, range),
4153 's' : (range == 0 ? 0 : range / 2.55 / (l < 0.5 ? l * 2 : 2 - l * 2)),
4162 * @class Roo.lib.HSVColor
4163 * @extends Roo.lib.Color
4164 * Creates a Color specified in the HSV Color space, with an optional alpha
4165 * component. The parameters are:
4168 * @param {Number} h - the hue component, wrapped to the range [0,360)
4169 * @param {Number} s - the saturation component, clipped to the range [0,100]
4170 * @param {Number} v - the value component, clipped to the range [0,100]
4171 * @param {Number} a - the alpha component, clipped to the range [0,1] - this parameter is
4172 * optional and defaults to 1
4174 Roo.lib.HSVColor = function (h, s, v, a){
4176 // store the alpha component after clipping it if necessary
4177 this.alpha = (a === undefined ? 1 : Math.max(0, Math.min(1, a)));
4179 // store the HSV components after clipping or wrapping them if necessary
4182 'h' : (h % 360 + 360) % 360,
4183 's' : Math.max(0, Math.min(100, s)),
4184 'v' : Math.max(0, Math.min(100, v))
4187 // initialise the RGB and HSL components to null
4192 Roo.extend(Roo.lib.HSVColor, Roo.lib.Color, {
4193 /* Calculates and stores the RGB components of this HSVColor so that they can
4194 * be returned be the getRGB function.
4196 calculateRGB: function ()
4199 // check whether the saturation is zero
4202 // set the Color to the appropriate shade of grey
4209 // set some temporary values
4210 var f = hsv.h / 60 - Math.floor(hsv.h / 60);
4211 var p = hsv.v * (1 - hsv.s / 100);
4212 var q = hsv.v * (1 - hsv.s / 100 * f);
4213 var t = hsv.v * (1 - hsv.s / 100 * (1 - f));
4215 // set the RGB Color components to their temporary values
4216 switch (Math.floor(hsv.h / 60)){
4217 case 0: var r = hsv.v; var g = t; var b = p; break;
4218 case 1: var r = q; var g = hsv.v; var b = p; break;
4219 case 2: var r = p; var g = hsv.v; var b = t; break;
4220 case 3: var r = p; var g = q; var b = hsv.v; break;
4221 case 4: var r = t; var g = p; var b = hsv.v; break;
4222 case 5: var r = hsv.v; var g = p; var b = q; break;
4227 // store the RGB components
4237 /* Calculates and stores the HSL components of this HSVColor so that they can
4238 * be returned be the getHSL function.
4240 calculateHSL : function (){
4243 // determine the lightness in the range [0,100]
4244 var l = (2 - hsv.s / 100) * hsv.v / 2;
4246 // store the HSL components
4250 's' : hsv.s * hsv.v / (l < 50 ? l * 2 : 200 - l * 2),
4254 // correct a division-by-zero error
4255 if (isNaN(hsl.s)) { hsl.s = 0; }
4264 * @class Roo.lib.HSLColor
4265 * @extends Roo.lib.Color
4268 * Creates a Color specified in the HSL Color space, with an optional alpha
4269 * component. The parameters are:
4271 * @param {Number} h - the hue component, wrapped to the range [0,360)
4272 * @param {Number} s - the saturation component, clipped to the range [0,100]
4273 * @param {Number} l - the lightness component, clipped to the range [0,100]
4274 * @param {Number} a - the alpha component, clipped to the range [0,1] - this parameter is
4275 * optional and defaults to 1
4278 Roo.lib.HSLColor = function(h, s, l, a){
4280 // store the alpha component after clipping it if necessary
4281 this.alpha = (a === undefined ? 1 : Math.max(0, Math.min(1, a)));
4283 // store the HSL components after clipping or wrapping them if necessary
4286 'h' : (h % 360 + 360) % 360,
4287 's' : Math.max(0, Math.min(100, s)),
4288 'l' : Math.max(0, Math.min(100, l))
4291 // initialise the RGB and HSV components to null
4294 Roo.extend(Roo.lib.HSLColor, Roo.lib.Color, {
4296 /* Calculates and stores the RGB components of this HSLColor so that they can
4297 * be returned be the getRGB function.
4299 calculateRGB: function (){
4301 // check whether the saturation is zero
4302 if (this.hsl.s == 0){
4304 // store the RGB components representing the appropriate shade of grey
4307 'r' : this.hsl.l * 2.55,
4308 'g' : this.hsl.l * 2.55,
4309 'b' : this.hsl.l * 2.55
4314 // set some temporary values
4315 var p = this.hsl.l < 50
4316 ? this.hsl.l * (1 + hsl.s / 100)
4317 : this.hsl.l + hsl.s - hsl.l * hsl.s / 100;
4318 var q = 2 * hsl.l - p;
4320 // initialise the RGB components
4323 'r' : (h + 120) / 60 % 6,
4325 'b' : (h + 240) / 60 % 6
4328 // loop over the RGB components
4329 for (var key in this.rgb){
4331 // ensure that the property is not inherited from the root object
4332 if (this.rgb.hasOwnProperty(key)){
4334 // set the component to its value in the range [0,100]
4335 if (this.rgb[key] < 1){
4336 this.rgb[key] = q + (p - q) * this.rgb[key];
4337 }else if (this.rgb[key] < 3){
4339 }else if (this.rgb[key] < 4){
4340 this.rgb[key] = q + (p - q) * (4 - this.rgb[key]);
4345 // set the component to its value in the range [0,255]
4346 this.rgb[key] *= 2.55;
4356 /* Calculates and stores the HSV components of this HSLColor so that they can
4357 * be returned be the getHSL function.
4359 calculateHSV : function(){
4361 // set a temporary value
4362 var t = this.hsl.s * (this.hsl.l < 50 ? this.hsl.l : 100 - this.hsl.l) / 100;
4364 // store the HSV components
4368 's' : 200 * t / (this.hsl.l + t),
4369 'v' : t + this.hsl.l
4372 // correct a division-by-zero error
4373 if (isNaN(this.hsv.s)) { this.hsv.s = 0; }
4380 * Portions of this file are based on pieces of Yahoo User Interface Library
4381 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
4382 * YUI licensed under the BSD License:
4383 * http://developer.yahoo.net/yui/license.txt
4384 * <script type="text/javascript">
4389 Roo.lib.ColorAnim = function(el, attributes, duration, method) {
4390 Roo.lib.ColorAnim.superclass.constructor.call(this, el, attributes, duration, method);
4393 Roo.extend(Roo.lib.ColorAnim, Roo.lib.AnimBase);
4395 var fly = Roo.lib.AnimBase.fly;
4397 var superclass = Y.ColorAnim.superclass;
4398 var proto = Y.ColorAnim.prototype;
4400 proto.toString = function() {
4401 var el = this.getEl();
4402 var id = el.id || el.tagName;
4403 return ("ColorAnim " + id);
4406 proto.patterns.color = /color$/i;
4407 proto.patterns.rgb = /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i;
4408 proto.patterns.hex = /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i;
4409 proto.patterns.hex3 = /^#?([0-9A-F]{1})([0-9A-F]{1})([0-9A-F]{1})$/i;
4410 proto.patterns.transparent = /^transparent|rgba\(0, 0, 0, 0\)$/;
4413 proto.parseColor = function(s) {
4414 if (s.length == 3) {
4418 var c = this.patterns.hex.exec(s);
4419 if (c && c.length == 4) {
4420 return [ parseInt(c[1], 16), parseInt(c[2], 16), parseInt(c[3], 16) ];
4423 c = this.patterns.rgb.exec(s);
4424 if (c && c.length == 4) {
4425 return [ parseInt(c[1], 10), parseInt(c[2], 10), parseInt(c[3], 10) ];
4428 c = this.patterns.hex3.exec(s);
4429 if (c && c.length == 4) {
4430 return [ parseInt(c[1] + c[1], 16), parseInt(c[2] + c[2], 16), parseInt(c[3] + c[3], 16) ];
4435 // since this uses fly! - it cant be in ColorAnim (which does not have fly yet..)
4436 proto.getAttribute = function(attr) {
4437 var el = this.getEl();
4438 if (this.patterns.color.test(attr)) {
4439 var val = fly(el).getStyle(attr);
4441 if (this.patterns.transparent.test(val)) {
4442 var parent = el.parentNode;
4443 val = fly(parent).getStyle(attr);
4445 while (parent && this.patterns.transparent.test(val)) {
4446 parent = parent.parentNode;
4447 val = fly(parent).getStyle(attr);
4448 if (parent.tagName.toUpperCase() == 'HTML') {
4454 val = superclass.getAttribute.call(this, attr);
4459 proto.getAttribute = function(attr) {
4460 var el = this.getEl();
4461 if (this.patterns.color.test(attr)) {
4462 var val = fly(el).getStyle(attr);
4464 if (this.patterns.transparent.test(val)) {
4465 var parent = el.parentNode;
4466 val = fly(parent).getStyle(attr);
4468 while (parent && this.patterns.transparent.test(val)) {
4469 parent = parent.parentNode;
4470 val = fly(parent).getStyle(attr);
4471 if (parent.tagName.toUpperCase() == 'HTML') {
4477 val = superclass.getAttribute.call(this, attr);
4483 proto.doMethod = function(attr, start, end) {
4486 if (this.patterns.color.test(attr)) {
4488 for (var i = 0, len = start.length; i < len; ++i) {
4489 val[i] = superclass.doMethod.call(this, attr, start[i], end[i]);
4492 val = 'rgb(' + Math.floor(val[0]) + ',' + Math.floor(val[1]) + ',' + Math.floor(val[2]) + ')';
4495 val = superclass.doMethod.call(this, attr, start, end);
4501 proto.setRuntimeAttribute = function(attr) {
4502 superclass.setRuntimeAttribute.call(this, attr);
4504 if (this.patterns.color.test(attr)) {
4505 var attributes = this.attributes;
4506 var start = this.parseColor(this.runtimeAttributes[attr].start);
4507 var end = this.parseColor(this.runtimeAttributes[attr].end);
4509 if (typeof attributes[attr]['to'] === 'undefined' && typeof attributes[attr]['by'] !== 'undefined') {
4510 end = this.parseColor(attributes[attr].by);
4512 for (var i = 0, len = start.length; i < len; ++i) {
4513 end[i] = start[i] + end[i];
4517 this.runtimeAttributes[attr].start = start;
4518 this.runtimeAttributes[attr].end = end;
4524 * Portions of this file are based on pieces of Yahoo User Interface Library
4525 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
4526 * YUI licensed under the BSD License:
4527 * http://developer.yahoo.net/yui/license.txt
4528 * <script type="text/javascript">
4534 easeNone: function (t, b, c, d) {
4535 return c * t / d + b;
4539 easeIn: function (t, b, c, d) {
4540 return c * (t /= d) * t + b;
4544 easeOut: function (t, b, c, d) {
4545 return -c * (t /= d) * (t - 2) + b;
4549 easeBoth: function (t, b, c, d) {
4550 if ((t /= d / 2) < 1) {
4551 return c / 2 * t * t + b;
4554 return -c / 2 * ((--t) * (t - 2) - 1) + b;
4558 easeInStrong: function (t, b, c, d) {
4559 return c * (t /= d) * t * t * t + b;
4563 easeOutStrong: function (t, b, c, d) {
4564 return -c * ((t = t / d - 1) * t * t * t - 1) + b;
4568 easeBothStrong: function (t, b, c, d) {
4569 if ((t /= d / 2) < 1) {
4570 return c / 2 * t * t * t * t + b;
4573 return -c / 2 * ((t -= 2) * t * t * t - 2) + b;
4578 elasticIn: function (t, b, c, d, a, p) {
4582 if ((t /= d) == 1) {
4589 if (!a || a < Math.abs(c)) {
4594 var s = p / (2 * Math.PI) * Math.asin(c / a);
4597 return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
4601 elasticOut: function (t, b, c, d, a, p) {
4605 if ((t /= d) == 1) {
4612 if (!a || a < Math.abs(c)) {
4617 var s = p / (2 * Math.PI) * Math.asin(c / a);
4620 return a * Math.pow(2, -10 * t) * Math.sin((t * d - s) * (2 * Math.PI) / p) + c + b;
4624 elasticBoth: function (t, b, c, d, a, p) {
4629 if ((t /= d / 2) == 2) {
4637 if (!a || a < Math.abs(c)) {
4642 var s = p / (2 * Math.PI) * Math.asin(c / a);
4646 return -.5 * (a * Math.pow(2, 10 * (t -= 1)) *
4647 Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
4649 return a * Math.pow(2, -10 * (t -= 1)) *
4650 Math.sin((t * d - s) * (2 * Math.PI) / p) * .5 + c + b;
4655 backIn: function (t, b, c, d, s) {
4656 if (typeof s == 'undefined') {
4659 return c * (t /= d) * t * ((s + 1) * t - s) + b;
4663 backOut: function (t, b, c, d, s) {
4664 if (typeof s == 'undefined') {
4667 return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
4671 backBoth: function (t, b, c, d, s) {
4672 if (typeof s == 'undefined') {
4676 if ((t /= d / 2 ) < 1) {
4677 return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b;
4679 return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;
4683 bounceIn: function (t, b, c, d) {
4684 return c - Roo.lib.Easing.bounceOut(d - t, 0, c, d) + b;
4688 bounceOut: function (t, b, c, d) {
4689 if ((t /= d) < (1 / 2.75)) {
4690 return c * (7.5625 * t * t) + b;
4691 } else if (t < (2 / 2.75)) {
4692 return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b;
4693 } else if (t < (2.5 / 2.75)) {
4694 return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b;
4696 return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b;
4700 bounceBoth: function (t, b, c, d) {
4702 return Roo.lib.Easing.bounceIn(t * 2, 0, c, d) * .5 + b;
4704 return Roo.lib.Easing.bounceOut(t * 2 - d, 0, c, d) * .5 + c * .5 + b;
4707 * Portions of this file are based on pieces of Yahoo User Interface Library
4708 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
4709 * YUI licensed under the BSD License:
4710 * http://developer.yahoo.net/yui/license.txt
4711 * <script type="text/javascript">
4715 Roo.lib.Motion = function(el, attributes, duration, method) {
4717 Roo.lib.Motion.superclass.constructor.call(this, el, attributes, duration, method);
4721 Roo.extend(Roo.lib.Motion, Roo.lib.ColorAnim);
4725 var superclass = Y.Motion.superclass;
4726 var proto = Y.Motion.prototype;
4728 proto.toString = function() {
4729 var el = this.getEl();
4730 var id = el.id || el.tagName;
4731 return ("Motion " + id);
4734 proto.patterns.points = /^points$/i;
4736 proto.setAttribute = function(attr, val, unit) {
4737 if (this.patterns.points.test(attr)) {
4738 unit = unit || 'px';
4739 superclass.setAttribute.call(this, 'left', val[0], unit);
4740 superclass.setAttribute.call(this, 'top', val[1], unit);
4742 superclass.setAttribute.call(this, attr, val, unit);
4746 proto.getAttribute = function(attr) {
4747 if (this.patterns.points.test(attr)) {
4749 superclass.getAttribute.call(this, 'left'),
4750 superclass.getAttribute.call(this, 'top')
4753 val = superclass.getAttribute.call(this, attr);
4759 proto.doMethod = function(attr, start, end) {
4762 if (this.patterns.points.test(attr)) {
4763 var t = this.method(this.currentFrame, 0, 100, this.totalFrames) / 100;
4764 val = Y.Bezier.getPosition(this.runtimeAttributes[attr], t);
4766 val = superclass.doMethod.call(this, attr, start, end);
4771 proto.setRuntimeAttribute = function(attr) {
4772 if (this.patterns.points.test(attr)) {
4773 var el = this.getEl();
4774 var attributes = this.attributes;
4776 var control = attributes['points']['control'] || [];
4780 if (control.length > 0 && !(control[0] instanceof Array)) {
4781 control = [control];
4784 for (i = 0,len = control.length; i < len; ++i) {
4785 tmp[i] = control[i];
4790 Roo.fly(el).position();
4792 if (isset(attributes['points']['from'])) {
4793 Roo.lib.Dom.setXY(el, attributes['points']['from']);
4796 Roo.lib.Dom.setXY(el, Roo.lib.Dom.getXY(el));
4799 start = this.getAttribute('points');
4802 if (isset(attributes['points']['to'])) {
4803 end = translateValues.call(this, attributes['points']['to'], start);
4805 var pageXY = Roo.lib.Dom.getXY(this.getEl());
4806 for (i = 0,len = control.length; i < len; ++i) {
4807 control[i] = translateValues.call(this, control[i], start);
4811 } else if (isset(attributes['points']['by'])) {
4812 end = [ start[0] + attributes['points']['by'][0], start[1] + attributes['points']['by'][1] ];
4814 for (i = 0,len = control.length; i < len; ++i) {
4815 control[i] = [ start[0] + control[i][0], start[1] + control[i][1] ];
4819 this.runtimeAttributes[attr] = [start];
4821 if (control.length > 0) {
4822 this.runtimeAttributes[attr] = this.runtimeAttributes[attr].concat(control);
4825 this.runtimeAttributes[attr][this.runtimeAttributes[attr].length] = end;
4828 superclass.setRuntimeAttribute.call(this, attr);
4832 var translateValues = function(val, start) {
4833 var pageXY = Roo.lib.Dom.getXY(this.getEl());
4834 val = [ val[0] - pageXY[0] + start[0], val[1] - pageXY[1] + start[1] ];
4839 var isset = function(prop) {
4840 return (typeof prop !== 'undefined');
4844 * Portions of this file are based on pieces of Yahoo User Interface Library
4845 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
4846 * YUI licensed under the BSD License:
4847 * http://developer.yahoo.net/yui/license.txt
4848 * <script type="text/javascript">
4852 Roo.lib.Scroll = function(el, attributes, duration, method) {
4854 Roo.lib.Scroll.superclass.constructor.call(this, el, attributes, duration, method);
4858 Roo.extend(Roo.lib.Scroll, Roo.lib.ColorAnim);
4862 var superclass = Y.Scroll.superclass;
4863 var proto = Y.Scroll.prototype;
4865 proto.toString = function() {
4866 var el = this.getEl();
4867 var id = el.id || el.tagName;
4868 return ("Scroll " + id);
4871 proto.doMethod = function(attr, start, end) {
4874 if (attr == 'scroll') {
4876 this.method(this.currentFrame, start[0], end[0] - start[0], this.totalFrames),
4877 this.method(this.currentFrame, start[1], end[1] - start[1], this.totalFrames)
4881 val = superclass.doMethod.call(this, attr, start, end);
4886 proto.getAttribute = function(attr) {
4888 var el = this.getEl();
4890 if (attr == 'scroll') {
4891 val = [ el.scrollLeft, el.scrollTop ];
4893 val = superclass.getAttribute.call(this, attr);
4899 proto.setAttribute = function(attr, val, unit) {
4900 var el = this.getEl();
4902 if (attr == 'scroll') {
4903 el.scrollLeft = val[0];
4904 el.scrollTop = val[1];
4906 superclass.setAttribute.call(this, attr, val, unit);
4911 * Originally based of this code... - refactored for Roo...
4912 * https://github.com/aaalsaleh/undo-manager
4915 * @author Abdulrahman Alsaleh
4916 * @copyright 2015 Abdulrahman Alsaleh
4917 * @license MIT License (c)
4919 * Hackily modifyed by alan@roojs.com
4924 * TOTALLY UNTESTED...
4926 * Documentation to be done....
4931 * @class Roo.lib.UndoManager
4932 * An undo manager implementation in JavaScript. It follows the W3C UndoManager and DOM Transaction
4933 * Draft and the undocumented and disabled Mozilla Firefox's UndoManager implementation.
4939 editor.undoManager = new Roo.lib.UndoManager(1000, editor);
4943 * For more information see this blog post with examples:
4944 * <a href="http://www.cnitblog.com/seeyeah/archive/2011/12/30/38728.html/">DomHelper
4945 - Create Elements using DOM, HTML fragments and Templates</a>.
4947 * @param {Number} limit how far back to go ... use 1000?
4948 * @param {Object} scope usually use document..
4951 Roo.lib.UndoManager = function (limit, undoScopeHost)
4955 this.scope = undoScopeHost;
4956 this.fireEvent = typeof CustomEvent != 'undefined' && undoScopeHost && undoScopeHost.dispatchEvent;
4957 if (this.fireEvent) {
4964 Roo.lib.UndoManager.prototype = {
4975 * To push and execute a transaction, the method undoManager.transact
4976 * must be called by passing a transaction object as the first argument, and a merge
4977 * flag as the second argument. A transaction object has the following properties:
4981 undoManager.transact({
4983 execute: function() { ... },
4984 undo: function() { ... },
4985 // redo same as execute
4986 redo: function() { this.execute(); }
4989 // merge transaction
4990 undoManager.transact({
4992 execute: function() { ... }, // this will be run...
4993 undo: function() { ... }, // what to do when undo is run.
4994 // redo same as execute
4995 redo: function() { this.execute(); }
5000 * @param {Object} transaction The transaction to add to the stack.
5001 * @return {String} The HTML fragment
5005 transact : function (transaction, merge)
5007 if (arguments.length < 2) {
5008 throw new TypeError('Not enough arguments to UndoManager.transact.');
5011 transaction.execute();
5013 this.stack.splice(0, this.position);
5014 if (merge && this.length) {
5015 this.stack[0].push(transaction);
5017 this.stack.unshift([transaction]);
5022 if (this.limit && this.stack.length > this.limit) {
5023 this.length = this.stack.length = this.limit;
5025 this.length = this.stack.length;
5028 if (this.fireEvent) {
5029 this.scope.dispatchEvent(
5030 new CustomEvent('DOMTransaction', {
5032 transactions: this.stack[0].slice()
5040 //Roo.log("transaction: pos:" + this.position + " len: " + this.length + " slen:" + this.stack.length);
5047 //Roo.log("undo: pos:" + this.position + " len: " + this.length + " slen:" + this.stack.length);
5049 if (this.position < this.length) {
5050 for (var i = this.stack[this.position].length - 1; i >= 0; i--) {
5051 this.stack[this.position][i].undo();
5055 if (this.fireEvent) {
5056 this.scope.dispatchEvent(
5057 new CustomEvent('undo', {
5059 transactions: this.stack[this.position - 1].slice()
5071 if (this.position > 0) {
5072 for (var i = 0, n = this.stack[this.position - 1].length; i < n; i++) {
5073 this.stack[this.position - 1][i].redo();
5077 if (this.fireEvent) {
5078 this.scope.dispatchEvent(
5079 new CustomEvent('redo', {
5081 transactions: this.stack[this.position].slice()
5091 item : function (index)
5093 if (index >= 0 && index < this.length) {
5094 return this.stack[index].slice();
5099 clearUndo : function () {
5100 this.stack.length = this.length = this.position;
5103 clearRedo : function () {
5104 this.stack.splice(0, this.position);
5106 this.length = this.stack.length;
5109 * Reset the undo - probaly done on load to clear all history.
5116 this.current_html = this.scope.innerHTML;
5117 if (this.timer !== false) {
5118 clearTimeout(this.timer);
5130 // this will handle the undo/redo on the element.?
5131 bindEvents : function()
5133 var el = this.scope;
5134 el.undoManager = this;
5137 this.scope.addEventListener('keydown', function(e) {
5138 if ((e.ctrlKey || e.metaKey) && e.keyCode === 90) {
5140 el.undoManager.redo(); // Ctrl/Command + Shift + Z
5142 el.undoManager.undo(); // Ctrl/Command + Z
5149 this.scope.addEventListener('keyup', function(e) {
5150 if ((e.ctrlKey || e.metaKey) && e.keyCode === 90) {
5159 el.addEventListener('input', function(e) {
5160 if(el.innerHTML == t.current_html) {
5163 // only record events every second.
5164 if (t.timer !== false) {
5165 clearTimeout(t.timer);
5168 t.timer = setTimeout(function() { t.merge = false; }, 1000);
5170 t.addEvent(t.merge);
5171 t.merge = true; // ignore changes happening every second..
5175 * Manually add an event.
5176 * Normall called without arguements - and it will just get added to the stack.
5180 addEvent : function(merge)
5182 //Roo.log("undomanager +" + (merge ? 'Y':'n'));
5183 // not sure if this should clear the timer
5184 merge = typeof(merge) == 'undefined' ? false : merge;
5186 this.scope.undoManager.transact({
5188 oldHTML: this.current_html,
5189 newHTML: this.scope.innerHTML,
5190 // nothing to execute (content already changed when input is fired)
5191 execute: function() { },
5193 this.scope.innerHTML = this.current_html = this.oldHTML;
5196 this.scope.innerHTML = this.current_html = this.newHTML;
5198 }, false); //merge);
5202 this.current_html = this.scope.innerHTML;
5213 * Ext JS Library 1.1.1
5214 * Copyright(c) 2006-2007, Ext JS, LLC.
5216 * Originally Released Under LGPL - original licence link has changed is not relivant.
5219 * <script type="text/javascript">
5223 // nasty IE9 hack - what a pile of crap that is..
5225 if (typeof Range != "undefined" && typeof Range.prototype.createContextualFragment == "undefined") {
5226 Range.prototype.createContextualFragment = function (html) {
5227 var doc = window.document;
5228 var container = doc.createElement("div");
5229 container.innerHTML = html;
5230 var frag = doc.createDocumentFragment(), n;
5231 while ((n = container.firstChild)) {
5232 frag.appendChild(n);
5239 * @class Roo.DomHelper
5240 * Utility class for working with DOM and/or Templates. It transparently supports using HTML fragments or DOM.
5241 * 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>.
5244 Roo.DomHelper = function(){
5245 var tempTableEl = null;
5246 var emptyTags = /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i;
5247 var tableRe = /^table|tbody|tr|td$/i;
5249 // build as innerHTML where available
5251 var createHtml = function(o){
5252 if(typeof o == 'string'){
5261 if(attr == "tag" || attr == "children" || attr == "cn" || attr == "html" || typeof o[attr] == "function") { continue; }
5262 if(attr == "style"){
5264 if(typeof s == "function"){
5267 if(typeof s == "string"){
5268 b += ' style="' + s + '"';
5269 }else if(typeof s == "object"){
5272 if(typeof s[key] != "function"){
5273 b += key + ":" + s[key] + ";";
5280 b += ' class="' + o["cls"] + '"';
5281 }else if(attr == "htmlFor"){
5282 b += ' for="' + o["htmlFor"] + '"';
5284 b += " " + attr + '="' + o[attr] + '"';
5288 if(emptyTags.test(o.tag)){
5292 var cn = o.children || o.cn;
5294 //http://bugs.kde.org/show_bug.cgi?id=71506
5295 if((cn instanceof Array) || (Roo.isSafari && typeof(cn.join) == "function")){
5296 for(var i = 0, len = cn.length; i < len; i++) {
5297 b += createHtml(cn[i], b);
5300 b += createHtml(cn, b);
5306 b += "</" + o.tag + ">";
5313 var createDom = function(o, parentNode){
5315 // defininition craeted..
5317 if (o.ns && o.ns != 'html') {
5319 if (o.xmlns && typeof(xmlns[o.ns]) == 'undefined') {
5320 xmlns[o.ns] = o.xmlns;
5323 if (typeof(xmlns[o.ns]) == 'undefined') {
5324 console.log("Trying to create namespace element " + o.ns + ", however no xmlns was sent to builder previously");
5330 if (typeof(o) == 'string') {
5331 return parentNode.appendChild(document.createTextNode(o));
5333 o.tag = o.tag || div;
5334 if (o.ns && Roo.isIE) {
5336 o.tag = o.ns + ':' + o.tag;
5339 var el = ns ? document.createElementNS( ns, o.tag||'div') : document.createElement(o.tag||'div');
5340 var useSet = el.setAttribute ? true : false; // In IE some elements don't have setAttribute
5343 if(attr == "tag" || attr == "ns" ||attr == "xmlns" ||attr == "children" || attr == "cn" || attr == "html" ||
5344 attr == "style" || typeof o[attr] == "function") { continue; }
5346 if(attr=="cls" && Roo.isIE){
5347 el.className = o["cls"];
5349 if(useSet) { el.setAttribute(attr=="cls" ? 'class' : attr, o[attr]);}
5355 Roo.DomHelper.applyStyles(el, o.style);
5356 var cn = o.children || o.cn;
5358 //http://bugs.kde.org/show_bug.cgi?id=71506
5359 if((cn instanceof Array) || (Roo.isSafari && typeof(cn.join) == "function")){
5360 for(var i = 0, len = cn.length; i < len; i++) {
5361 createDom(cn[i], el);
5368 el.innerHTML = o.html;
5371 parentNode.appendChild(el);
5376 var ieTable = function(depth, s, h, e){
5377 tempTableEl.innerHTML = [s, h, e].join('');
5378 var i = -1, el = tempTableEl;
5379 while(++i < depth && el.firstChild){
5385 // kill repeat to save bytes
5389 tbe = '</tbody>'+te,
5395 * Nasty code for IE's broken table implementation
5397 var insertIntoTable = function(tag, where, el, html){
5399 tempTableEl = document.createElement('div');
5404 if(where == 'afterbegin' || where == 'beforeend'){ // INTO a TD
5407 if(where == 'beforebegin'){
5411 before = el.nextSibling;
5414 node = ieTable(4, trs, html, tre);
5416 else if(tag == 'tr'){
5417 if(where == 'beforebegin'){
5420 node = ieTable(3, tbs, html, tbe);
5421 } else if(where == 'afterend'){
5422 before = el.nextSibling;
5424 node = ieTable(3, tbs, html, tbe);
5425 } else{ // INTO a TR
5426 if(where == 'afterbegin'){
5427 before = el.firstChild;
5429 node = ieTable(4, trs, html, tre);
5431 } else if(tag == 'tbody'){
5432 if(where == 'beforebegin'){
5435 node = ieTable(2, ts, html, te);
5436 } else if(where == 'afterend'){
5437 before = el.nextSibling;
5439 node = ieTable(2, ts, html, te);
5441 if(where == 'afterbegin'){
5442 before = el.firstChild;
5444 node = ieTable(3, tbs, html, tbe);
5447 if(where == 'beforebegin' || where == 'afterend'){ // OUTSIDE the table
5450 if(where == 'afterbegin'){
5451 before = el.firstChild;
5453 node = ieTable(2, ts, html, te);
5455 el.insertBefore(node, before);
5459 // this is a bit like the react update code...
5462 var updateNode = function(from, to)
5464 // should we handle non-standard elements?
5465 Roo.log(["UpdateNode" , from, to]);
5466 if (from.nodeType != to.nodeType) {
5467 Roo.log(["ReplaceChild - mismatch notType" , to, from ]);
5468 from.parentNode.replaceChild(to, from);
5471 if (from.nodeType == 3) {
5472 // assume it's text?!
5473 if (from.data == to.data) {
5476 from.data = to.data;
5480 // assume 'to' doesnt have '1/3 nodetypes!
5481 if (from.nodeType !=1 || from.tagName != to.tagName) {
5482 Roo.log(["ReplaceChild" , from, to ]);
5483 from.parentNode.replaceChild(to, from);
5486 // compare attributes
5487 var ar = Array.from(from.attributes);
5488 for(var i = 0; i< ar.length;i++) {
5489 if (to.hasAttribute(ar[i].name)) {
5492 if (ar[i].name == 'id') { // always keep ids?
5495 //if (ar[i].name == 'style') {
5496 // throw "style removed?";
5498 Roo.log("removeAttribute" + ar[i].name);
5499 from.removeAttribute(ar[i].name);
5502 for(var i = 0; i< ar.length;i++) {
5503 if (from.getAttribute(ar[i].name) == to.getAttribute(ar[i].name)) {
5504 Roo.log("skipAttribute " + ar[i].name + '=' + to.getAttribute(ar[i].name));
5507 Roo.log("updateAttribute " + ar[i].name + '=>' + to.getAttribute(ar[i].name));
5508 from.setAttribute(ar[i].name, to.getAttribute(ar[i].name));
5511 var far = Array.from(from.childNodes);
5512 var tar = Array.from(to.childNodes);
5513 // if the lengths are different.. then it's probably a editable content change, rather than
5514 // a change of the block definition..
5516 // this did notwork , as our rebuilt nodes did not include ID's so did not match at all.
5517 /*if (from.innerHTML == to.innerHTML) {
5520 if (far.length != tar.length) {
5521 from.innerHTML = to.innerHTML;
5526 for(var i = 0; i < Math.max(tar.length, far.length); i++) {
5527 if (i >= far.length) {
5528 from.appendChild(tar[i]);
5529 Roo.log(["add", tar[i]]);
5531 } else if ( i >= tar.length) {
5532 from.removeChild(far[i]);
5533 Roo.log(["remove", far[i]]);
5536 updateNode(far[i], tar[i]);
5548 /** True to force the use of DOM instead of html fragments @type Boolean */
5552 * Returns the markup for the passed Element(s) config
5553 * @param {Object} o The Dom object spec (and children)
5556 markup : function(o){
5557 return createHtml(o);
5561 * Applies a style specification to an element
5562 * @param {String/HTMLElement} el The element to apply styles to
5563 * @param {String/Object/Function} styles A style specification string eg "width:100px", or object in the form {width:"100px"}, or
5564 * a function which returns such a specification.
5566 applyStyles : function(el, styles){
5569 if(typeof styles == "string"){
5570 var re = /\s?([a-z\-]*)\:\s?([^;]*);?/gi;
5572 while ((matches = re.exec(styles)) != null){
5573 el.setStyle(matches[1], matches[2]);
5575 }else if (typeof styles == "object"){
5576 for (var style in styles){
5577 el.setStyle(style, styles[style]);
5579 }else if (typeof styles == "function"){
5580 Roo.DomHelper.applyStyles(el, styles.call());
5586 * Inserts an HTML fragment into the Dom
5587 * @param {String} where Where to insert the html in relation to el - beforeBegin, afterBegin, beforeEnd, afterEnd.
5588 * @param {HTMLElement} el The context element
5589 * @param {String} html The HTML fragmenet
5590 * @return {HTMLElement} The new node
5592 insertHtml : function(where, el, html){
5593 where = where.toLowerCase();
5594 if(el.insertAdjacentHTML){
5595 if(tableRe.test(el.tagName)){
5597 if(rs = insertIntoTable(el.tagName.toLowerCase(), where, el, html)){
5603 el.insertAdjacentHTML('BeforeBegin', html);
5604 return el.previousSibling;
5606 el.insertAdjacentHTML('AfterBegin', html);
5607 return el.firstChild;
5609 el.insertAdjacentHTML('BeforeEnd', html);
5610 return el.lastChild;
5612 el.insertAdjacentHTML('AfterEnd', html);
5613 return el.nextSibling;
5615 throw 'Illegal insertion point -> "' + where + '"';
5617 var range = el.ownerDocument.createRange();
5621 range.setStartBefore(el);
5622 frag = range.createContextualFragment(html);
5623 el.parentNode.insertBefore(frag, el);
5624 return el.previousSibling;
5627 range.setStartBefore(el.firstChild);
5628 frag = range.createContextualFragment(html);
5629 el.insertBefore(frag, el.firstChild);
5630 return el.firstChild;
5632 el.innerHTML = html;
5633 return el.firstChild;
5637 range.setStartAfter(el.lastChild);
5638 frag = range.createContextualFragment(html);
5639 el.appendChild(frag);
5640 return el.lastChild;
5642 el.innerHTML = html;
5643 return el.lastChild;
5646 range.setStartAfter(el);
5647 frag = range.createContextualFragment(html);
5648 el.parentNode.insertBefore(frag, el.nextSibling);
5649 return el.nextSibling;
5651 throw 'Illegal insertion point -> "' + where + '"';
5655 * Creates new Dom element(s) and inserts them before el
5656 * @param {String/HTMLElement/Element} el The context element
5657 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5658 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5659 * @return {HTMLElement/Roo.Element} The new node
5661 insertBefore : function(el, o, returnElement){
5662 return this.doInsert(el, o, returnElement, "beforeBegin");
5666 * Creates new Dom element(s) and inserts them after el
5667 * @param {String/HTMLElement/Element} el The context element
5668 * @param {Object} o The Dom object spec (and children)
5669 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5670 * @return {HTMLElement/Roo.Element} The new node
5672 insertAfter : function(el, o, returnElement){
5673 return this.doInsert(el, o, returnElement, "afterEnd", "nextSibling");
5677 * Creates new Dom element(s) and inserts them as the first child of el
5678 * @param {String/HTMLElement/Element} el The context element
5679 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5680 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5681 * @return {HTMLElement/Roo.Element} The new node
5683 insertFirst : function(el, o, returnElement){
5684 return this.doInsert(el, o, returnElement, "afterBegin");
5688 doInsert : function(el, o, returnElement, pos, sibling){
5689 el = Roo.getDom(el);
5691 if(this.useDom || o.ns){
5692 newNode = createDom(o, null);
5693 el.parentNode.insertBefore(newNode, sibling ? el[sibling] : el);
5695 var html = createHtml(o);
5696 newNode = this.insertHtml(pos, el, html);
5698 return returnElement ? Roo.get(newNode, true) : newNode;
5702 * Creates new Dom element(s) and appends them to el
5703 * @param {String/HTMLElement/Element} el The context element
5704 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5705 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5706 * @return {HTMLElement/Roo.Element} The new node
5708 append : function(el, o, returnElement){
5709 el = Roo.getDom(el);
5711 if(this.useDom || o.ns){
5712 newNode = createDom(o, null);
5713 el.appendChild(newNode);
5715 var html = createHtml(o);
5716 newNode = this.insertHtml("beforeEnd", el, html);
5718 return returnElement ? Roo.get(newNode, true) : newNode;
5722 * Creates new Dom element(s) and overwrites the contents of el with them
5723 * @param {String/HTMLElement/Element} el The context element
5724 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5725 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5726 * @return {HTMLElement/Roo.Element} The new node
5728 overwrite : function(el, o, returnElement)
5730 el = Roo.getDom(el);
5733 while (el.childNodes.length) {
5734 el.removeChild(el.firstChild);
5738 el.innerHTML = createHtml(o);
5741 return returnElement ? Roo.get(el.firstChild, true) : el.firstChild;
5745 * Creates a new Roo.DomHelper.Template from the Dom object spec
5746 * @param {Object} o The Dom object spec (and children)
5747 * @return {Roo.DomHelper.Template} The new template
5749 createTemplate : function(o){
5750 var html = createHtml(o);
5751 return new Roo.Template(html);
5754 * Updates the first element with the spec from the o (replacing if necessary)
5755 * This iterates through the children, and updates attributes / children etc..
5756 * @param {String/HTMLElement/Element} el The context element
5757 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5760 update : function(el, o)
5762 updateNode(Roo.getDom(el), createDom(o));
5771 * Ext JS Library 1.1.1
5772 * Copyright(c) 2006-2007, Ext JS, LLC.
5774 * Originally Released Under LGPL - original licence link has changed is not relivant.
5777 * <script type="text/javascript">
5781 * @class Roo.Template
5782 * Represents an HTML fragment template. Templates can be precompiled for greater performance.
5783 * For a list of available format functions, see {@link Roo.util.Format}.<br />
5786 var t = new Roo.Template({
5787 html : '<div name="{id}">' +
5788 '<span class="{cls}">{name:trim} {someval:this.myformat}{value:ellipsis(10)}</span>' +
5790 myformat: function (value, allValues) {
5791 return 'XX' + value;
5794 t.append('some-element', {id: 'myid', cls: 'myclass', name: 'foo', value: 'bar'});
5796 * For more information see this blog post with examples:
5797 * <a href="http://www.cnitblog.com/seeyeah/archive/2011/12/30/38728.html/">DomHelper
5798 - Create Elements using DOM, HTML fragments and Templates</a>.
5800 * @param {Object} cfg - Configuration object.
5802 Roo.Template = function(cfg){
5804 if(cfg instanceof Array){
5806 }else if(arguments.length > 1){
5807 cfg = Array.prototype.join.call(arguments, "");
5811 if (typeof(cfg) == 'object') {
5822 Roo.Template.prototype = {
5825 * @cfg {Function} onLoad Called after the template has been loaded and complied (usually from a remove source)
5831 * @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..
5832 * it should be fixed so that template is observable...
5836 * @cfg {String} html The HTML fragment or an array of fragments to join("") or multiple arguments to join("")
5844 * Returns an HTML fragment of this template with the specified values applied.
5845 * @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'})
5846 * @return {String} The HTML fragment
5851 applyTemplate : function(values){
5852 //Roo.log(["applyTemplate", values]);
5856 return this.compiled(values);
5858 var useF = this.disableFormats !== true;
5859 var fm = Roo.util.Format, tpl = this;
5860 var fn = function(m, name, format, args){
5862 if(format.substr(0, 5) == "this."){
5863 return tpl.call(format.substr(5), values[name], values);
5866 // quoted values are required for strings in compiled templates,
5867 // but for non compiled we need to strip them
5868 // quoted reversed for jsmin
5869 var re = /^\s*['"](.*)["']\s*$/;
5870 args = args.split(',');
5871 for(var i = 0, len = args.length; i < len; i++){
5872 args[i] = args[i].replace(re, "$1");
5874 args = [values[name]].concat(args);
5876 args = [values[name]];
5878 return fm[format].apply(fm, args);
5881 return values[name] !== undefined ? values[name] : "";
5884 return this.html.replace(this.re, fn);
5902 this.loading = true;
5903 this.compiled = false;
5905 var cx = new Roo.data.Connection();
5909 success : function (response) {
5913 _t.set(response.responseText,true);
5919 failure : function(response) {
5920 Roo.log("Template failed to load from " + _t.url);
5927 * Sets the HTML used as the template and optionally compiles it.
5928 * @param {String} html
5929 * @param {Boolean} compile (optional) True to compile the template (defaults to undefined)
5930 * @return {Roo.Template} this
5932 set : function(html, compile){
5934 this.compiled = false;
5942 * True to disable format functions (defaults to false)
5945 disableFormats : false,
5948 * The regular expression used to match template variables
5952 re : /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
5955 * Compiles the template into an internal function, eliminating the RegEx overhead.
5956 * @return {Roo.Template} this
5958 compile : function(){
5959 var fm = Roo.util.Format;
5960 var useF = this.disableFormats !== true;
5961 var sep = Roo.isGecko ? "+" : ",";
5962 var fn = function(m, name, format, args){
5964 args = args ? ',' + args : "";
5965 if(format.substr(0, 5) != "this."){
5966 format = "fm." + format + '(';
5968 format = 'this.call("'+ format.substr(5) + '", ';
5972 args= ''; format = "(values['" + name + "'] == undefined ? '' : ";
5974 return "'"+ sep + format + "values['" + name + "']" + args + ")"+sep+"'";
5977 // branched to use + in gecko and [].join() in others
5979 body = "this.compiled = function(values){ return '" +
5980 this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
5983 body = ["this.compiled = function(values){ return ['"];
5984 body.push(this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn));
5985 body.push("'].join('');};");
5986 body = body.join('');
5996 // private function used to call members
5997 call : function(fnName, value, allValues){
5998 return this[fnName](value, allValues);
6002 * Applies the supplied values to the template and inserts the new node(s) as the first child of el.
6003 * @param {String/HTMLElement/Roo.Element} el The context element
6004 * @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'})
6005 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
6006 * @return {HTMLElement/Roo.Element} The new node or Element
6008 insertFirst: function(el, values, returnElement){
6009 return this.doInsert('afterBegin', el, values, returnElement);
6013 * Applies the supplied values to the template and inserts the new node(s) before el.
6014 * @param {String/HTMLElement/Roo.Element} el The context element
6015 * @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'})
6016 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
6017 * @return {HTMLElement/Roo.Element} The new node or Element
6019 insertBefore: function(el, values, returnElement){
6020 return this.doInsert('beforeBegin', el, values, returnElement);
6024 * Applies the supplied values to the template and inserts the new node(s) after el.
6025 * @param {String/HTMLElement/Roo.Element} el The context element
6026 * @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'})
6027 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
6028 * @return {HTMLElement/Roo.Element} The new node or Element
6030 insertAfter : function(el, values, returnElement){
6031 return this.doInsert('afterEnd', el, values, returnElement);
6035 * Applies the supplied values to the template and appends the new node(s) to el.
6036 * @param {String/HTMLElement/Roo.Element} el The context element
6037 * @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'})
6038 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
6039 * @return {HTMLElement/Roo.Element} The new node or Element
6041 append : function(el, values, returnElement){
6042 return this.doInsert('beforeEnd', el, values, returnElement);
6045 doInsert : function(where, el, values, returnEl){
6046 el = Roo.getDom(el);
6047 var newNode = Roo.DomHelper.insertHtml(where, el, this.applyTemplate(values));
6048 return returnEl ? Roo.get(newNode, true) : newNode;
6052 * Applies the supplied values to the template and overwrites the content of el with the new node(s).
6053 * @param {String/HTMLElement/Roo.Element} el The context element
6054 * @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'})
6055 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
6056 * @return {HTMLElement/Roo.Element} The new node or Element
6058 overwrite : function(el, values, returnElement){
6059 el = Roo.getDom(el);
6060 el.innerHTML = this.applyTemplate(values);
6061 return returnElement ? Roo.get(el.firstChild, true) : el.firstChild;
6065 * Alias for {@link #applyTemplate}
6068 Roo.Template.prototype.apply = Roo.Template.prototype.applyTemplate;
6071 Roo.DomHelper.Template = Roo.Template;
6074 * Creates a template from the passed element's value (<i>display:none</i> textarea, preferred) or innerHTML.
6075 * @param {String/HTMLElement} el A DOM element or its id
6076 * @returns {Roo.Template} The created template
6079 Roo.Template.from = function(el){
6080 el = Roo.getDom(el);
6081 return new Roo.Template(el.value || el.innerHTML);
6084 * Ext JS Library 1.1.1
6085 * Copyright(c) 2006-2007, Ext JS, LLC.
6087 * Originally Released Under LGPL - original licence link has changed is not relivant.
6090 * <script type="text/javascript">
6095 * This is code is also distributed under MIT license for use
6096 * with jQuery and prototype JavaScript libraries.
6099 * @class Roo.DomQuery
6100 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).
6102 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>
6105 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.
6107 <h4>Element Selectors:</h4>
6109 <li> <b>*</b> any element</li>
6110 <li> <b>E</b> an element with the tag E</li>
6111 <li> <b>E F</b> All descendent elements of E that have the tag F</li>
6112 <li> <b>E > F</b> or <b>E/F</b> all direct children elements of E that have the tag F</li>
6113 <li> <b>E + F</b> all elements with the tag F that are immediately preceded by an element with the tag E</li>
6114 <li> <b>E ~ F</b> all elements with the tag F that are preceded by a sibling element with the tag E</li>
6116 <h4>Attribute Selectors:</h4>
6117 <p>The use of @ and quotes are optional. For example, div[@foo='bar'] is also a valid attribute selector.</p>
6119 <li> <b>E[foo]</b> has an attribute "foo"</li>
6120 <li> <b>E[foo=bar]</b> has an attribute "foo" that equals "bar"</li>
6121 <li> <b>E[foo^=bar]</b> has an attribute "foo" that starts with "bar"</li>
6122 <li> <b>E[foo$=bar]</b> has an attribute "foo" that ends with "bar"</li>
6123 <li> <b>E[foo*=bar]</b> has an attribute "foo" that contains the substring "bar"</li>
6124 <li> <b>E[foo%=2]</b> has an attribute "foo" that is evenly divisible by 2</li>
6125 <li> <b>E[foo!=bar]</b> has an attribute "foo" that does not equal "bar"</li>
6127 <h4>Pseudo Classes:</h4>
6129 <li> <b>E:first-child</b> E is the first child of its parent</li>
6130 <li> <b>E:last-child</b> E is the last child of its parent</li>
6131 <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>
6132 <li> <b>E:nth-child(odd)</b> E is an odd child of its parent</li>
6133 <li> <b>E:nth-child(even)</b> E is an even child of its parent</li>
6134 <li> <b>E:only-child</b> E is the only child of its parent</li>
6135 <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>
6136 <li> <b>E:first</b> the first E in the resultset</li>
6137 <li> <b>E:last</b> the last E in the resultset</li>
6138 <li> <b>E:nth(<i>n</i>)</b> the <i>n</i>th E in the resultset (1 based)</li>
6139 <li> <b>E:odd</b> shortcut for :nth-child(odd)</li>
6140 <li> <b>E:even</b> shortcut for :nth-child(even)</li>
6141 <li> <b>E:contains(foo)</b> E's innerHTML contains the substring "foo"</li>
6142 <li> <b>E:nodeValue(foo)</b> E contains a textNode with a nodeValue that equals "foo"</li>
6143 <li> <b>E:not(S)</b> an E element that does not match simple selector S</li>
6144 <li> <b>E:has(S)</b> an E element that has a descendent that matches simple selector S</li>
6145 <li> <b>E:next(S)</b> an E element whose next sibling matches simple selector S</li>
6146 <li> <b>E:prev(S)</b> an E element whose previous sibling matches simple selector S</li>
6148 <h4>CSS Value Selectors:</h4>
6150 <li> <b>E{display=none}</b> css value "display" that equals "none"</li>
6151 <li> <b>E{display^=none}</b> css value "display" that starts with "none"</li>
6152 <li> <b>E{display$=none}</b> css value "display" that ends with "none"</li>
6153 <li> <b>E{display*=none}</b> css value "display" that contains the substring "none"</li>
6154 <li> <b>E{display%=2}</b> css value "display" that is evenly divisible by 2</li>
6155 <li> <b>E{display!=none}</b> css value "display" that does not equal "none"</li>
6159 Roo.DomQuery = function(){
6160 var cache = {}, simpleCache = {}, valueCache = {};
6161 var nonSpace = /\S/;
6162 var trimRe = /^\s+|\s+$/g;
6163 var tplRe = /\{(\d+)\}/g;
6164 var modeRe = /^(\s?[\/>+~]\s?|\s|$)/;
6165 var tagTokenRe = /^(#)?([\w-\*]+)/;
6166 var nthRe = /(\d*)n\+?(\d*)/, nthRe2 = /\D/;
6168 function child(p, index){
6170 var n = p.firstChild;
6172 if(n.nodeType == 1){
6183 while((n = n.nextSibling) && n.nodeType != 1);
6188 while((n = n.previousSibling) && n.nodeType != 1);
6192 function children(d){
6193 var n = d.firstChild, ni = -1;
6195 var nx = n.nextSibling;
6196 if(n.nodeType == 3 && !nonSpace.test(n.nodeValue)){
6206 function byClassName(c, a, v){
6210 var r = [], ri = -1, cn;
6211 for(var i = 0, ci; ci = c[i]; i++){
6215 ( (ci instanceof SVGElement) ? ci.className.baseVal : ci.className)
6216 +' ').indexOf(v) != -1){
6223 function attrValue(n, attr){
6224 if(!n.tagName && typeof n.length != "undefined"){
6233 if(attr == "class" || attr == "className"){
6234 return (n instanceof SVGElement) ? n.className.baseVal : n.className;
6236 return n.getAttribute(attr) || n[attr];
6240 function getNodes(ns, mode, tagName){
6241 var result = [], ri = -1, cs;
6245 tagName = tagName || "*";
6246 if(typeof ns.getElementsByTagName != "undefined"){
6250 for(var i = 0, ni; ni = ns[i]; i++){
6251 cs = ni.getElementsByTagName(tagName);
6252 for(var j = 0, ci; ci = cs[j]; j++){
6256 }else if(mode == "/" || mode == ">"){
6257 var utag = tagName.toUpperCase();
6258 for(var i = 0, ni, cn; ni = ns[i]; i++){
6259 cn = ni.children || ni.childNodes;
6260 for(var j = 0, cj; cj = cn[j]; j++){
6261 if(cj.nodeName == utag || cj.nodeName == tagName || tagName == '*'){
6266 }else if(mode == "+"){
6267 var utag = tagName.toUpperCase();
6268 for(var i = 0, n; n = ns[i]; i++){
6269 while((n = n.nextSibling) && n.nodeType != 1);
6270 if(n && (n.nodeName == utag || n.nodeName == tagName || tagName == '*')){
6274 }else if(mode == "~"){
6275 for(var i = 0, n; n = ns[i]; i++){
6276 while((n = n.nextSibling) && (n.nodeType != 1 || (tagName == '*' || n.tagName.toLowerCase()!=tagName)));
6285 function concat(a, b){
6289 for(var i = 0, l = b.length; i < l; i++){
6295 function byTag(cs, tagName){
6296 if(cs.tagName || cs == document){
6302 var r = [], ri = -1;
6303 tagName = tagName.toLowerCase();
6304 for(var i = 0, ci; ci = cs[i]; i++){
6305 if(ci.nodeType == 1 && ci.tagName.toLowerCase()==tagName){
6312 function byId(cs, attr, id){
6313 if(cs.tagName || cs == document){
6319 var r = [], ri = -1;
6320 for(var i = 0,ci; ci = cs[i]; i++){
6321 if(ci && ci.id == id){
6329 function byAttribute(cs, attr, value, op, custom){
6330 var r = [], ri = -1, st = custom=="{";
6331 var f = Roo.DomQuery.operators[op];
6332 for(var i = 0, ci; ci = cs[i]; i++){
6335 a = Roo.DomQuery.getStyle(ci, attr);
6337 else if(attr == "class" || attr == "className"){
6338 a = (ci instanceof SVGElement) ? ci.className.baseVal : ci.className;
6339 }else if(attr == "for"){
6341 }else if(attr == "href"){
6342 a = ci.getAttribute("href", 2);
6344 a = ci.getAttribute(attr);
6346 if((f && f(a, value)) || (!f && a)){
6353 function byPseudo(cs, name, value){
6354 return Roo.DomQuery.pseudos[name](cs, value);
6357 // This is for IE MSXML which does not support expandos.
6358 // IE runs the same speed using setAttribute, however FF slows way down
6359 // and Safari completely fails so they need to continue to use expandos.
6360 var isIE = window.ActiveXObject ? true : false;
6362 // this eval is stop the compressor from
6363 // renaming the variable to something shorter
6365 /** eval:var:batch */
6370 function nodupIEXml(cs){
6372 cs[0].setAttribute("_nodup", d);
6374 for(var i = 1, len = cs.length; i < len; i++){
6376 if(!c.getAttribute("_nodup") != d){
6377 c.setAttribute("_nodup", d);
6381 for(var i = 0, len = cs.length; i < len; i++){
6382 cs[i].removeAttribute("_nodup");
6391 var len = cs.length, c, i, r = cs, cj, ri = -1;
6392 if(!len || typeof cs.nodeType != "undefined" || len == 1){
6395 if(isIE && typeof cs[0].selectSingleNode != "undefined"){
6396 return nodupIEXml(cs);
6400 for(i = 1; c = cs[i]; i++){
6405 for(var j = 0; j < i; j++){
6408 for(j = i+1; cj = cs[j]; j++){
6420 function quickDiffIEXml(c1, c2){
6422 for(var i = 0, len = c1.length; i < len; i++){
6423 c1[i].setAttribute("_qdiff", d);
6426 for(var i = 0, len = c2.length; i < len; i++){
6427 if(c2[i].getAttribute("_qdiff") != d){
6428 r[r.length] = c2[i];
6431 for(var i = 0, len = c1.length; i < len; i++){
6432 c1[i].removeAttribute("_qdiff");
6437 function quickDiff(c1, c2){
6438 var len1 = c1.length;
6442 if(isIE && c1[0].selectSingleNode){
6443 return quickDiffIEXml(c1, c2);
6446 for(var i = 0; i < len1; i++){
6450 for(var i = 0, len = c2.length; i < len; i++){
6451 if(c2[i]._qdiff != d){
6452 r[r.length] = c2[i];
6458 function quickId(ns, mode, root, id){
6460 var d = root.ownerDocument || root;
6461 return d.getElementById(id);
6463 ns = getNodes(ns, mode, "*");
6464 return byId(ns, null, id);
6468 getStyle : function(el, name){
6469 return Roo.fly(el).getStyle(name);
6472 * Compiles a selector/xpath query into a reusable function. The returned function
6473 * takes one parameter "root" (optional), which is the context node from where the query should start.
6474 * @param {String} selector The selector/xpath query
6475 * @param {String} type (optional) Either "select" (the default) or "simple" for a simple selector match
6476 * @return {Function}
6478 compile : function(path, type){
6479 type = type || "select";
6481 var fn = ["var f = function(root){\n var mode; ++batch; var n = root || document;\n"];
6482 var q = path, mode, lq;
6483 var tk = Roo.DomQuery.matchers;
6484 var tklen = tk.length;
6487 // accept leading mode switch
6488 var lmode = q.match(modeRe);
6489 if(lmode && lmode[1]){
6490 fn[fn.length] = 'mode="'+lmode[1].replace(trimRe, "")+'";';
6491 q = q.replace(lmode[1], "");
6493 // strip leading slashes
6494 while(path.substr(0, 1)=="/"){
6495 path = path.substr(1);
6498 while(q && lq != q){
6500 var tm = q.match(tagTokenRe);
6501 if(type == "select"){
6504 fn[fn.length] = 'n = quickId(n, mode, root, "'+tm[2]+'");';
6506 fn[fn.length] = 'n = getNodes(n, mode, "'+tm[2]+'");';
6508 q = q.replace(tm[0], "");
6509 }else if(q.substr(0, 1) != '@'){
6510 fn[fn.length] = 'n = getNodes(n, mode, "*");';
6515 fn[fn.length] = 'n = byId(n, null, "'+tm[2]+'");';
6517 fn[fn.length] = 'n = byTag(n, "'+tm[2]+'");';
6519 q = q.replace(tm[0], "");
6522 while(!(mm = q.match(modeRe))){
6523 var matched = false;
6524 for(var j = 0; j < tklen; j++){
6526 var m = q.match(t.re);
6528 fn[fn.length] = t.select.replace(tplRe, function(x, i){
6531 q = q.replace(m[0], "");
6536 // prevent infinite loop on bad selector
6538 throw 'Error parsing selector, parsing failed at "' + q + '"';
6542 fn[fn.length] = 'mode="'+mm[1].replace(trimRe, "")+'";';
6543 q = q.replace(mm[1], "");
6546 fn[fn.length] = "return nodup(n);\n}";
6549 * list of variables that need from compression as they are used by eval.
6559 * eval:var:byClassName
6561 * eval:var:byAttribute
6562 * eval:var:attrValue
6570 * Selects a group of elements.
6571 * @param {String} selector The selector/xpath query (can be a comma separated list of selectors)
6572 * @param {Node} root (optional) The start of the query (defaults to document).
6575 select : function(path, root, type){
6576 if(!root || root == document){
6579 if(typeof root == "string"){
6580 root = document.getElementById(root);
6582 var paths = path.split(",");
6584 for(var i = 0, len = paths.length; i < len; i++){
6585 var p = paths[i].replace(trimRe, "");
6587 cache[p] = Roo.DomQuery.compile(p);
6589 throw p + " is not a valid selector";
6592 var result = cache[p](root);
6593 if(result && result != document){
6594 results = results.concat(result);
6597 if(paths.length > 1){
6598 return nodup(results);
6604 * Selects a single element.
6605 * @param {String} selector The selector/xpath query
6606 * @param {Node} root (optional) The start of the query (defaults to document).
6609 selectNode : function(path, root){
6610 return Roo.DomQuery.select(path, root)[0];
6614 * Selects the value of a node, optionally replacing null with the defaultValue.
6615 * @param {String} selector The selector/xpath query
6616 * @param {Node} root (optional) The start of the query (defaults to document).
6617 * @param {String} defaultValue
6619 selectValue : function(path, root, defaultValue){
6620 path = path.replace(trimRe, "");
6621 if(!valueCache[path]){
6622 valueCache[path] = Roo.DomQuery.compile(path, "select");
6624 var n = valueCache[path](root);
6625 n = n[0] ? n[0] : n;
6626 var v = (n && n.firstChild ? n.firstChild.nodeValue : null);
6627 return ((v === null||v === undefined||v==='') ? defaultValue : v);
6631 * Selects the value of a node, parsing integers and floats.
6632 * @param {String} selector The selector/xpath query
6633 * @param {Node} root (optional) The start of the query (defaults to document).
6634 * @param {Number} defaultValue
6637 selectNumber : function(path, root, defaultValue){
6638 var v = Roo.DomQuery.selectValue(path, root, defaultValue || 0);
6639 return parseFloat(v);
6643 * Returns true if the passed element(s) match the passed simple selector (e.g. div.some-class or span:first-child)
6644 * @param {String/HTMLElement/Array} el An element id, element or array of elements
6645 * @param {String} selector The simple selector to test
6648 is : function(el, ss){
6649 if(typeof el == "string"){
6650 el = document.getElementById(el);
6652 var isArray = (el instanceof Array);
6653 var result = Roo.DomQuery.filter(isArray ? el : [el], ss);
6654 return isArray ? (result.length == el.length) : (result.length > 0);
6658 * Filters an array of elements to only include matches of a simple selector (e.g. div.some-class or span:first-child)
6659 * @param {Array} el An array of elements to filter
6660 * @param {String} selector The simple selector to test
6661 * @param {Boolean} nonMatches If true, it returns the elements that DON'T match
6662 * the selector instead of the ones that match
6665 filter : function(els, ss, nonMatches){
6666 ss = ss.replace(trimRe, "");
6667 if(!simpleCache[ss]){
6668 simpleCache[ss] = Roo.DomQuery.compile(ss, "simple");
6670 var result = simpleCache[ss](els);
6671 return nonMatches ? quickDiff(result, els) : result;
6675 * Collection of matching regular expressions and code snippets.
6679 select: 'n = byClassName(n, null, " {1} ");'
6681 re: /^\:([\w-]+)(?:\(((?:[^\s>\/]*|.*?))\))?/,
6682 select: 'n = byPseudo(n, "{1}", "{2}");'
6684 re: /^(?:([\[\{])(?:@)?([\w-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]\}])/,
6685 select: 'n = byAttribute(n, "{2}", "{4}", "{3}", "{1}");'
6688 select: 'n = byId(n, null, "{1}");'
6691 select: 'return {firstChild:{nodeValue:attrValue(n, "{1}")}};'
6696 * Collection of operator comparison functions. The default operators are =, !=, ^=, $=, *=, %=, |= and ~=.
6697 * 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, > <.
6700 "=" : function(a, v){
6703 "!=" : function(a, v){
6706 "^=" : function(a, v){
6707 return a && a.substr(0, v.length) == v;
6709 "$=" : function(a, v){
6710 return a && a.substr(a.length-v.length) == v;
6712 "*=" : function(a, v){
6713 return a && a.indexOf(v) !== -1;
6715 "%=" : function(a, v){
6716 return (a % v) == 0;
6718 "|=" : function(a, v){
6719 return a && (a == v || a.substr(0, v.length+1) == v+'-');
6721 "~=" : function(a, v){
6722 return a && (' '+a+' ').indexOf(' '+v+' ') != -1;
6727 * Collection of "pseudo class" processors. Each processor is passed the current nodeset (array)
6728 * and the argument (if any) supplied in the selector.
6731 "first-child" : function(c){
6732 var r = [], ri = -1, n;
6733 for(var i = 0, ci; ci = n = c[i]; i++){
6734 while((n = n.previousSibling) && n.nodeType != 1);
6742 "last-child" : function(c){
6743 var r = [], ri = -1, n;
6744 for(var i = 0, ci; ci = n = c[i]; i++){
6745 while((n = n.nextSibling) && n.nodeType != 1);
6753 "nth-child" : function(c, a) {
6754 var r = [], ri = -1;
6755 var m = nthRe.exec(a == "even" && "2n" || a == "odd" && "2n+1" || !nthRe2.test(a) && "n+" + a || a);
6756 var f = (m[1] || 1) - 0, l = m[2] - 0;
6757 for(var i = 0, n; n = c[i]; i++){
6758 var pn = n.parentNode;
6759 if (batch != pn._batch) {
6761 for(var cn = pn.firstChild; cn; cn = cn.nextSibling){
6762 if(cn.nodeType == 1){
6769 if (l == 0 || n.nodeIndex == l){
6772 } else if ((n.nodeIndex + l) % f == 0){
6780 "only-child" : function(c){
6781 var r = [], ri = -1;;
6782 for(var i = 0, ci; ci = c[i]; i++){
6783 if(!prev(ci) && !next(ci)){
6790 "empty" : function(c){
6791 var r = [], ri = -1;
6792 for(var i = 0, ci; ci = c[i]; i++){
6793 var cns = ci.childNodes, j = 0, cn, empty = true;
6796 if(cn.nodeType == 1 || cn.nodeType == 3){
6808 "contains" : function(c, v){
6809 var r = [], ri = -1;
6810 for(var i = 0, ci; ci = c[i]; i++){
6811 if((ci.textContent||ci.innerText||'').indexOf(v) != -1){
6818 "nodeValue" : function(c, v){
6819 var r = [], ri = -1;
6820 for(var i = 0, ci; ci = c[i]; i++){
6821 if(ci.firstChild && ci.firstChild.nodeValue == v){
6828 "checked" : function(c){
6829 var r = [], ri = -1;
6830 for(var i = 0, ci; ci = c[i]; i++){
6831 if(ci.checked == true){
6838 "not" : function(c, ss){
6839 return Roo.DomQuery.filter(c, ss, true);
6842 "odd" : function(c){
6843 return this["nth-child"](c, "odd");
6846 "even" : function(c){
6847 return this["nth-child"](c, "even");
6850 "nth" : function(c, a){
6851 return c[a-1] || [];
6854 "first" : function(c){
6858 "last" : function(c){
6859 return c[c.length-1] || [];
6862 "has" : function(c, ss){
6863 var s = Roo.DomQuery.select;
6864 var r = [], ri = -1;
6865 for(var i = 0, ci; ci = c[i]; i++){
6866 if(s(ss, ci).length > 0){
6873 "next" : function(c, ss){
6874 var is = Roo.DomQuery.is;
6875 var r = [], ri = -1;
6876 for(var i = 0, ci; ci = c[i]; i++){
6885 "prev" : function(c, ss){
6886 var is = Roo.DomQuery.is;
6887 var r = [], ri = -1;
6888 for(var i = 0, ci; ci = c[i]; i++){
6901 * Selects an array of DOM nodes by CSS/XPath selector. Shorthand of {@link Roo.DomQuery#select}
6902 * @param {String} path The selector/xpath query
6903 * @param {Node} root (optional) The start of the query (defaults to document).
6908 Roo.query = Roo.DomQuery.select;
6911 * Ext JS Library 1.1.1
6912 * Copyright(c) 2006-2007, Ext JS, LLC.
6914 * Originally Released Under LGPL - original licence link has changed is not relivant.
6917 * <script type="text/javascript">
6921 * @class Roo.util.Observable
6922 * Base class that provides a common interface for publishing events. Subclasses are expected to
6923 * to have a property "events" with all the events defined.<br>
6926 Employee = function(name){
6933 Roo.extend(Employee, Roo.util.Observable);
6935 * @param {Object} config properties to use (incuding events / listeners)
6938 Roo.util.Observable = function(cfg){
6941 this.addEvents(cfg.events || {});
6943 delete cfg.events; // make sure
6946 Roo.apply(this, cfg);
6949 this.on(this.listeners);
6950 delete this.listeners;
6953 Roo.util.Observable.prototype = {
6955 * @cfg {Object} listeners list of events and functions to call for this object,
6959 'click' : function(e) {
6969 * Fires the specified event with the passed parameters (minus the event name).
6970 * @param {String} eventName
6971 * @param {Object...} args Variable number of parameters are passed to handlers
6972 * @return {Boolean} returns false if any of the handlers return false otherwise it returns true
6974 fireEvent : function(){
6975 var ce = this.events[arguments[0].toLowerCase()];
6976 if(typeof ce == "object"){
6977 return ce.fire.apply(ce, Array.prototype.slice.call(arguments, 1));
6984 filterOptRe : /^(?:scope|delay|buffer|single)$/,
6987 * Appends an event handler to this component
6988 * @param {String} eventName The type of event to listen for
6989 * @param {Function} handler The method the event invokes
6990 * @param {Object} scope (optional) The scope in which to execute the handler
6991 * function. The handler function's "this" context.
6992 * @param {Object} options (optional) An object containing handler configuration
6993 * properties. This may contain any of the following properties:<ul>
6994 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
6995 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
6996 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
6997 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
6998 * by the specified number of milliseconds. If the event fires again within that time, the original
6999 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
7002 * <b>Combining Options</b><br>
7003 * Using the options argument, it is possible to combine different types of listeners:<br>
7005 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)
7007 el.on('click', this.onClick, this, {
7014 * <b>Attaching multiple handlers in 1 call</b><br>
7015 * The method also allows for a single argument to be passed which is a config object containing properties
7016 * which specify multiple handlers.
7025 fn: this.onMouseOver,
7029 fn: this.onMouseOut,
7035 * Or a shorthand syntax which passes the same scope object to all handlers:
7038 'click': this.onClick,
7039 'mouseover': this.onMouseOver,
7040 'mouseout': this.onMouseOut,
7045 addListener : function(eventName, fn, scope, o){
7046 if(typeof eventName == "object"){
7049 if(this.filterOptRe.test(e)){
7052 if(typeof o[e] == "function"){
7054 this.addListener(e, o[e], o.scope, o);
7056 // individual options
7057 this.addListener(e, o[e].fn, o[e].scope, o[e]);
7062 o = (!o || typeof o == "boolean") ? {} : o;
7063 eventName = eventName.toLowerCase();
7064 var ce = this.events[eventName] || true;
7065 if(typeof ce == "boolean"){
7066 ce = new Roo.util.Event(this, eventName);
7067 this.events[eventName] = ce;
7069 ce.addListener(fn, scope, o);
7073 * Removes a listener
7074 * @param {String} eventName The type of event to listen for
7075 * @param {Function} handler The handler to remove
7076 * @param {Object} scope (optional) The scope (this object) for the handler
7078 removeListener : function(eventName, fn, scope){
7079 var ce = this.events[eventName.toLowerCase()];
7080 if(typeof ce == "object"){
7081 ce.removeListener(fn, scope);
7086 * Removes all listeners for this object
7088 purgeListeners : function(){
7089 for(var evt in this.events){
7090 if(typeof this.events[evt] == "object"){
7091 this.events[evt].clearListeners();
7096 relayEvents : function(o, events){
7097 var createHandler = function(ename){
7100 return this.fireEvent.apply(this, Roo.combine(ename, Array.prototype.slice.call(arguments, 0)));
7103 for(var i = 0, len = events.length; i < len; i++){
7104 var ename = events[i];
7105 if(!this.events[ename]){
7106 this.events[ename] = true;
7108 o.on(ename, createHandler(ename), this);
7113 * Used to define events on this Observable
7114 * @param {Object} object The object with the events defined
7116 addEvents : function(o){
7120 Roo.applyIf(this.events, o);
7124 * Checks to see if this object has any listeners for a specified event
7125 * @param {String} eventName The name of the event to check for
7126 * @return {Boolean} True if the event is being listened for, else false
7128 hasListener : function(eventName){
7129 var e = this.events[eventName];
7130 return typeof e == "object" && e.listeners.length > 0;
7134 * Appends an event handler to this element (shorthand for addListener)
7135 * @param {String} eventName The type of event to listen for
7136 * @param {Function} handler The method the event invokes
7137 * @param {Object} scope (optional) The scope in which to execute the handler
7138 * function. The handler function's "this" context.
7139 * @param {Object} options (optional)
7142 Roo.util.Observable.prototype.on = Roo.util.Observable.prototype.addListener;
7144 * Removes a listener (shorthand for removeListener)
7145 * @param {String} eventName The type of event to listen for
7146 * @param {Function} handler The handler to remove
7147 * @param {Object} scope (optional) The scope (this object) for the handler
7150 Roo.util.Observable.prototype.un = Roo.util.Observable.prototype.removeListener;
7153 * Starts capture on the specified Observable. All events will be passed
7154 * to the supplied function with the event name + standard signature of the event
7155 * <b>before</b> the event is fired. If the supplied function returns false,
7156 * the event will not fire.
7157 * @param {Observable} o The Observable to capture
7158 * @param {Function} fn The function to call
7159 * @param {Object} scope (optional) The scope (this object) for the fn
7162 Roo.util.Observable.capture = function(o, fn, scope){
7163 o.fireEvent = o.fireEvent.createInterceptor(fn, scope);
7167 * Removes <b>all</b> added captures from the Observable.
7168 * @param {Observable} o The Observable to release
7171 Roo.util.Observable.releaseCapture = function(o){
7172 o.fireEvent = Roo.util.Observable.prototype.fireEvent;
7177 var createBuffered = function(h, o, scope){
7178 var task = new Roo.util.DelayedTask();
7180 task.delay(o.buffer, h, scope, Array.prototype.slice.call(arguments, 0));
7184 var createSingle = function(h, e, fn, scope){
7186 e.removeListener(fn, scope);
7187 return h.apply(scope, arguments);
7191 var createDelayed = function(h, o, scope){
7193 var args = Array.prototype.slice.call(arguments, 0);
7194 setTimeout(function(){
7195 h.apply(scope, args);
7200 Roo.util.Event = function(obj, name){
7203 this.listeners = [];
7206 Roo.util.Event.prototype = {
7207 addListener : function(fn, scope, options){
7208 var o = options || {};
7209 scope = scope || this.obj;
7210 if(!this.isListening(fn, scope)){
7211 var l = {fn: fn, scope: scope, options: o};
7214 h = createDelayed(h, o, scope);
7217 h = createSingle(h, this, fn, scope);
7220 h = createBuffered(h, o, scope);
7223 if(!this.firing){ // if we are currently firing this event, don't disturb the listener loop
7224 this.listeners.push(l);
7226 this.listeners = this.listeners.slice(0);
7227 this.listeners.push(l);
7232 findListener : function(fn, scope){
7233 scope = scope || this.obj;
7234 var ls = this.listeners;
7235 for(var i = 0, len = ls.length; i < len; i++){
7237 if(l.fn == fn && l.scope == scope){
7244 isListening : function(fn, scope){
7245 return this.findListener(fn, scope) != -1;
7248 removeListener : function(fn, scope){
7250 if((index = this.findListener(fn, scope)) != -1){
7252 this.listeners.splice(index, 1);
7254 this.listeners = this.listeners.slice(0);
7255 this.listeners.splice(index, 1);
7262 clearListeners : function(){
7263 this.listeners = [];
7267 var ls = this.listeners, scope, len = ls.length;
7270 var args = Array.prototype.slice.call(arguments, 0);
7271 for(var i = 0; i < len; i++){
7273 if(l.fireFn.apply(l.scope||this.obj||window, args) === false){
7274 this.firing = false;
7278 this.firing = false;
7285 * Copyright(c) 2007-2017, Roo J Solutions Ltd
7292 * @class Roo.Document
7293 * @extends Roo.util.Observable
7294 * This is a convience class to wrap up the main document loading code.. , rather than adding Roo.onReady(......)
7296 * @param {Object} config the methods and properties of the 'base' class for the application.
7298 * Generic Page handler - implement this to start your app..
7301 * MyProject = new Roo.Document({
7303 'load' : true // your events..
7306 'ready' : function() {
7307 // fired on Roo.onReady()
7312 Roo.Document = function(cfg) {
7317 Roo.util.Observable.call(this,cfg);
7321 Roo.onReady(function() {
7322 _this.fireEvent('ready');
7328 Roo.extend(Roo.Document, Roo.util.Observable, {});/*
7330 * Ext JS Library 1.1.1
7331 * Copyright(c) 2006-2007, Ext JS, LLC.
7333 * Originally Released Under LGPL - original licence link has changed is not relivant.
7336 * <script type="text/javascript">
7340 * @class Roo.EventManager
7341 * Registers event handlers that want to receive a normalized EventObject instead of the standard browser event and provides
7342 * several useful events directly.
7343 * See {@link Roo.EventObject} for more details on normalized event objects.
7346 Roo.EventManager = function(){
7347 var docReadyEvent, docReadyProcId, docReadyState = false;
7348 var resizeEvent, resizeTask, textEvent, textSize;
7349 var E = Roo.lib.Event;
7350 var D = Roo.lib.Dom;
7355 var fireDocReady = function(){
7357 docReadyState = true;
7360 clearInterval(docReadyProcId);
7362 if(Roo.isGecko || Roo.isOpera) {
7363 document.removeEventListener("DOMContentLoaded", fireDocReady, false);
7366 var defer = document.getElementById("ie-deferred-loader");
7368 defer.onreadystatechange = null;
7369 defer.parentNode.removeChild(defer);
7373 docReadyEvent.fire();
7374 docReadyEvent.clearListeners();
7379 var initDocReady = function(){
7380 docReadyEvent = new Roo.util.Event();
7381 if(Roo.isGecko || Roo.isOpera) {
7382 document.addEventListener("DOMContentLoaded", fireDocReady, false);
7384 document.write("<s"+'cript id="ie-deferred-loader" defer="defer" src="/'+'/:"></s'+"cript>");
7385 var defer = document.getElementById("ie-deferred-loader");
7386 defer.onreadystatechange = function(){
7387 if(this.readyState == "complete"){
7391 }else if(Roo.isSafari){
7392 docReadyProcId = setInterval(function(){
7393 var rs = document.readyState;
7394 if(rs == "complete") {
7399 // no matter what, make sure it fires on load
7400 E.on(window, "load", fireDocReady);
7403 var createBuffered = function(h, o){
7404 var task = new Roo.util.DelayedTask(h);
7406 // create new event object impl so new events don't wipe out properties
7407 e = new Roo.EventObjectImpl(e);
7408 task.delay(o.buffer, h, null, [e]);
7412 var createSingle = function(h, el, ename, fn){
7414 Roo.EventManager.removeListener(el, ename, fn);
7419 var createDelayed = function(h, o){
7421 // create new event object impl so new events don't wipe out properties
7422 e = new Roo.EventObjectImpl(e);
7423 setTimeout(function(){
7428 var transitionEndVal = false;
7430 var transitionEnd = function()
7432 if (transitionEndVal) {
7433 return transitionEndVal;
7435 var el = document.createElement('div');
7437 var transEndEventNames = {
7438 WebkitTransition : 'webkitTransitionEnd',
7439 MozTransition : 'transitionend',
7440 OTransition : 'oTransitionEnd otransitionend',
7441 transition : 'transitionend'
7444 for (var name in transEndEventNames) {
7445 if (el.style[name] !== undefined) {
7446 transitionEndVal = transEndEventNames[name];
7447 return transitionEndVal ;
7454 var listen = function(element, ename, opt, fn, scope)
7456 var o = (!opt || typeof opt == "boolean") ? {} : opt;
7457 fn = fn || o.fn; scope = scope || o.scope;
7458 var el = Roo.getDom(element);
7462 throw "Error listening for \"" + ename + '\". Element "' + element + '" doesn\'t exist.';
7465 if (ename == 'transitionend') {
7466 ename = transitionEnd();
7468 var h = function(e){
7469 e = Roo.EventObject.setEvent(e);
7472 t = e.getTarget(o.delegate, el);
7479 if(o.stopEvent === true){
7482 if(o.preventDefault === true){
7485 if(o.stopPropagation === true){
7486 e.stopPropagation();
7489 if(o.normalized === false){
7493 fn.call(scope || el, e, t, o);
7496 h = createDelayed(h, o);
7499 h = createSingle(h, el, ename, fn);
7502 h = createBuffered(h, o);
7505 fn._handlers = fn._handlers || [];
7508 fn._handlers.push([Roo.id(el), ename, h]);
7512 E.on(el, ename, h); // this adds the actuall listener to the object..
7515 if(ename == "mousewheel" && el.addEventListener){ // workaround for jQuery
7516 el.addEventListener("DOMMouseScroll", h, false);
7517 E.on(window, 'unload', function(){
7518 el.removeEventListener("DOMMouseScroll", h, false);
7521 if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
7522 Roo.EventManager.stoppedMouseDownEvent.addListener(h);
7527 var stopListening = function(el, ename, fn){
7528 var id = Roo.id(el), hds = fn._handlers, hd = fn;
7530 for(var i = 0, len = hds.length; i < len; i++){
7532 if(h[0] == id && h[1] == ename){
7539 E.un(el, ename, hd);
7540 el = Roo.getDom(el);
7541 if(ename == "mousewheel" && el.addEventListener){
7542 el.removeEventListener("DOMMouseScroll", hd, false);
7544 if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
7545 Roo.EventManager.stoppedMouseDownEvent.removeListener(hd);
7549 var propRe = /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/;
7556 * @scope Roo.EventManager
7561 * This is no longer needed and is deprecated. Places a simple wrapper around an event handler to override the browser event
7562 * object with a Roo.EventObject
7563 * @param {Function} fn The method the event invokes
7564 * @param {Object} scope An object that becomes the scope of the handler
7565 * @param {boolean} override If true, the obj passed in becomes
7566 * the execution scope of the listener
7567 * @return {Function} The wrapped function
7570 wrap : function(fn, scope, override){
7572 Roo.EventObject.setEvent(e);
7573 fn.call(override ? scope || window : window, Roo.EventObject, scope);
7578 * Appends an event handler to an element (shorthand for addListener)
7579 * @param {String/HTMLElement} element The html element or id to assign the
7580 * @param {String} eventName The type of event to listen for
7581 * @param {Function} handler The method the event invokes
7582 * @param {Object} scope (optional) The scope in which to execute the handler
7583 * function. The handler function's "this" context.
7584 * @param {Object} options (optional) An object containing handler configuration
7585 * properties. This may contain any of the following properties:<ul>
7586 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
7587 * <li>delegate {String} A simple selector to filter the target or look for a descendant of the target</li>
7588 * <li>stopEvent {Boolean} True to stop the event. That is stop propagation, and prevent the default action.</li>
7589 * <li>preventDefault {Boolean} True to prevent the default action</li>
7590 * <li>stopPropagation {Boolean} True to prevent event propagation</li>
7591 * <li>normalized {Boolean} False to pass a browser event to the handler function instead of an Roo.EventObject</li>
7592 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
7593 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
7594 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
7595 * by the specified number of milliseconds. If the event fires again within that time, the original
7596 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
7599 * <b>Combining Options</b><br>
7600 * Using the options argument, it is possible to combine different types of listeners:<br>
7602 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)<div style="margin: 5px 20px 20px;">
7604 el.on('click', this.onClick, this, {
7611 * <b>Attaching multiple handlers in 1 call</b><br>
7612 * The method also allows for a single argument to be passed which is a config object containing properties
7613 * which specify multiple handlers.
7623 fn: this.onMouseOver
7632 * Or a shorthand syntax:<br>
7635 'click' : this.onClick,
7636 'mouseover' : this.onMouseOver,
7637 'mouseout' : this.onMouseOut
7641 addListener : function(element, eventName, fn, scope, options){
7642 if(typeof eventName == "object"){
7648 if(typeof o[e] == "function"){
7650 listen(element, e, o, o[e], o.scope);
7652 // individual options
7653 listen(element, e, o[e]);
7658 return listen(element, eventName, options, fn, scope);
7662 * Removes an event handler
7664 * @param {String/HTMLElement} element The id or html element to remove the
7666 * @param {String} eventName The type of event
7667 * @param {Function} fn
7668 * @return {Boolean} True if a listener was actually removed
7670 removeListener : function(element, eventName, fn){
7671 return stopListening(element, eventName, fn);
7675 * Fires when the document is ready (before onload and before images are loaded). Can be
7676 * accessed shorthanded Roo.onReady().
7677 * @param {Function} fn The method the event invokes
7678 * @param {Object} scope An object that becomes the scope of the handler
7679 * @param {boolean} options
7681 onDocumentReady : function(fn, scope, options){
7682 if(docReadyState){ // if it already fired
7683 docReadyEvent.addListener(fn, scope, options);
7684 docReadyEvent.fire();
7685 docReadyEvent.clearListeners();
7691 docReadyEvent.addListener(fn, scope, options);
7695 * Fires when the window is resized and provides resize event buffering (50 milliseconds), passes new viewport width and height to handlers.
7696 * @param {Function} fn The method the event invokes
7697 * @param {Object} scope An object that becomes the scope of the handler
7698 * @param {boolean} options
7700 onWindowResize : function(fn, scope, options)
7703 resizeEvent = new Roo.util.Event();
7704 resizeTask = new Roo.util.DelayedTask(function(){
7705 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
7707 E.on(window, "resize", function()
7710 resizeTask.delay(50);
7712 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
7716 resizeEvent.addListener(fn, scope, options);
7720 * Fires when the user changes the active text size. Handler gets called with 2 params, the old size and the new size.
7721 * @param {Function} fn The method the event invokes
7722 * @param {Object} scope An object that becomes the scope of the handler
7723 * @param {boolean} options
7725 onTextResize : function(fn, scope, options){
7727 textEvent = new Roo.util.Event();
7728 var textEl = new Roo.Element(document.createElement('div'));
7729 textEl.dom.className = 'x-text-resize';
7730 textEl.dom.innerHTML = 'X';
7731 textEl.appendTo(document.body);
7732 textSize = textEl.dom.offsetHeight;
7733 setInterval(function(){
7734 if(textEl.dom.offsetHeight != textSize){
7735 textEvent.fire(textSize, textSize = textEl.dom.offsetHeight);
7737 }, this.textResizeInterval);
7739 textEvent.addListener(fn, scope, options);
7743 * Removes the passed window resize listener.
7744 * @param {Function} fn The method the event invokes
7745 * @param {Object} scope The scope of handler
7747 removeResizeListener : function(fn, scope){
7749 resizeEvent.removeListener(fn, scope);
7754 fireResize : function(){
7756 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
7760 * Url used for onDocumentReady with using SSL (defaults to Roo.SSL_SECURE_URL)
7764 * The frequency, in milliseconds, to check for text resize events (defaults to 50)
7766 textResizeInterval : 50
7771 * @scopeAlias pub=Roo.EventManager
7775 * Appends an event handler to an element (shorthand for addListener)
7776 * @param {String/HTMLElement} element The html element or id to assign the
7777 * @param {String} eventName The type of event to listen for
7778 * @param {Function} handler The method the event invokes
7779 * @param {Object} scope (optional) The scope in which to execute the handler
7780 * function. The handler function's "this" context.
7781 * @param {Object} options (optional) An object containing handler configuration
7782 * properties. This may contain any of the following properties:<ul>
7783 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
7784 * <li>delegate {String} A simple selector to filter the target or look for a descendant of the target</li>
7785 * <li>stopEvent {Boolean} True to stop the event. That is stop propagation, and prevent the default action.</li>
7786 * <li>preventDefault {Boolean} True to prevent the default action</li>
7787 * <li>stopPropagation {Boolean} True to prevent event propagation</li>
7788 * <li>normalized {Boolean} False to pass a browser event to the handler function instead of an Roo.EventObject</li>
7789 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
7790 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
7791 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
7792 * by the specified number of milliseconds. If the event fires again within that time, the original
7793 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
7796 * <b>Combining Options</b><br>
7797 * Using the options argument, it is possible to combine different types of listeners:<br>
7799 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)<div style="margin: 5px 20px 20px;">
7801 el.on('click', this.onClick, this, {
7808 * <b>Attaching multiple handlers in 1 call</b><br>
7809 * The method also allows for a single argument to be passed which is a config object containing properties
7810 * which specify multiple handlers.
7820 fn: this.onMouseOver
7829 * Or a shorthand syntax:<br>
7832 'click' : this.onClick,
7833 'mouseover' : this.onMouseOver,
7834 'mouseout' : this.onMouseOut
7838 pub.on = pub.addListener;
7839 pub.un = pub.removeListener;
7841 pub.stoppedMouseDownEvent = new Roo.util.Event();
7845 * Fires when the document is ready (before onload and before images are loaded). Shorthand of {@link Roo.EventManager#onDocumentReady}.
7846 * @param {Function} fn The method the event invokes
7847 * @param {Object} scope An object that becomes the scope of the handler
7848 * @param {boolean} override If true, the obj passed in becomes
7849 * the execution scope of the listener
7853 Roo.onReady = Roo.EventManager.onDocumentReady;
7855 Roo.onReady(function(){
7856 var bd = Roo.get(document.body);
7861 : Roo.isIE11 ? "roo-ie11"
7862 : Roo.isEdge ? "roo-edge"
7863 : Roo.isGecko ? "roo-gecko"
7864 : Roo.isOpera ? "roo-opera"
7865 : Roo.isSafari ? "roo-safari" : ""];
7868 cls.push("roo-mac");
7871 cls.push("roo-linux");
7874 cls.push("roo-ios");
7877 cls.push("roo-touch");
7879 if(Roo.isBorderBox){
7880 cls.push('roo-border-box');
7882 if(Roo.isStrict){ // add to the parent to allow for selectors like ".ext-strict .ext-ie"
7883 var p = bd.dom.parentNode;
7885 p.className += ' roo-strict';
7888 bd.addClass(cls.join(' '));
7892 * @class Roo.EventObject
7893 * EventObject exposes the Yahoo! UI Event functionality directly on the object
7894 * passed to your event handler. It exists mostly for convenience. It also fixes the annoying null checks automatically to cleanup your code
7897 function handleClick(e){ // e is not a standard event object, it is a Roo.EventObject
7899 var target = e.getTarget();
7902 var myDiv = Roo.get("myDiv");
7903 myDiv.on("click", handleClick);
7905 Roo.EventManager.on("myDiv", 'click', handleClick);
7906 Roo.EventManager.addListener("myDiv", 'click', handleClick);
7910 Roo.EventObject = function(){
7912 var E = Roo.lib.Event;
7914 // safari keypress events for special keys return bad keycodes
7917 63235 : 39, // right
7920 63276 : 33, // page up
7921 63277 : 34, // page down
7922 63272 : 46, // delete
7927 // normalize button clicks
7928 var btnMap = Roo.isIE ? {1:0,4:1,2:2} :
7929 (Roo.isSafari ? {1:0,2:1,3:2} : {0:0,1:1,2:2});
7931 Roo.EventObjectImpl = function(e){
7933 this.setEvent(e.browserEvent || e);
7936 Roo.EventObjectImpl.prototype = {
7938 * Used to fix doc tools.
7939 * @scope Roo.EventObject.prototype
7945 /** The normal browser event */
7946 browserEvent : null,
7947 /** The button pressed in a mouse event */
7949 /** True if the shift key was down during the event */
7951 /** True if the control key was down during the event */
7953 /** True if the alt key was down during the event */
8012 setEvent : function(e){
8013 if(e == this || (e && e.browserEvent)){ // already wrapped
8016 this.browserEvent = e;
8018 // normalize buttons
8019 this.button = e.button ? btnMap[e.button] : (e.which ? e.which-1 : -1);
8020 if(e.type == 'click' && this.button == -1){
8024 this.shiftKey = e.shiftKey;
8025 // mac metaKey behaves like ctrlKey
8026 this.ctrlKey = e.ctrlKey || e.metaKey;
8027 this.altKey = e.altKey;
8028 // in getKey these will be normalized for the mac
8029 this.keyCode = e.keyCode;
8030 // keyup warnings on firefox.
8031 this.charCode = (e.type == 'keyup' || e.type == 'keydown') ? 0 : e.charCode;
8032 // cache the target for the delayed and or buffered events
8033 this.target = E.getTarget(e);
8035 this.xy = E.getXY(e);
8038 this.shiftKey = false;
8039 this.ctrlKey = false;
8040 this.altKey = false;
8050 * Stop the event (preventDefault and stopPropagation)
8052 stopEvent : function(){
8053 if(this.browserEvent){
8054 if(this.browserEvent.type == 'mousedown'){
8055 Roo.EventManager.stoppedMouseDownEvent.fire(this);
8057 E.stopEvent(this.browserEvent);
8062 * Prevents the browsers default handling of the event.
8064 preventDefault : function(){
8065 if(this.browserEvent){
8066 E.preventDefault(this.browserEvent);
8071 isNavKeyPress : function(){
8072 var k = this.keyCode;
8073 k = Roo.isSafari ? (safariKeys[k] || k) : k;
8074 return (k >= 33 && k <= 40) || k == this.RETURN || k == this.TAB || k == this.ESC;
8077 isSpecialKey : function(){
8078 var k = this.keyCode;
8079 return (this.type == 'keypress' && this.ctrlKey) || k == 9 || k == 13 || k == 40 || k == 27 ||
8080 (k == 16) || (k == 17) ||
8081 (k >= 18 && k <= 20) ||
8082 (k >= 33 && k <= 35) ||
8083 (k >= 36 && k <= 39) ||
8084 (k >= 44 && k <= 45);
8087 * Cancels bubbling of the event.
8089 stopPropagation : function(){
8090 if(this.browserEvent){
8091 if(this.type == 'mousedown'){
8092 Roo.EventManager.stoppedMouseDownEvent.fire(this);
8094 E.stopPropagation(this.browserEvent);
8099 * Gets the key code for the event.
8102 getCharCode : function(){
8103 return this.charCode || this.keyCode;
8107 * Returns a normalized keyCode for the event.
8108 * @return {Number} The key code
8110 getKey : function(){
8111 var k = this.keyCode || this.charCode;
8112 return Roo.isSafari ? (safariKeys[k] || k) : k;
8116 * Gets the x coordinate of the event.
8119 getPageX : function(){
8124 * Gets the y coordinate of the event.
8127 getPageY : function(){
8132 * Gets the time of the event.
8135 getTime : function(){
8136 if(this.browserEvent){
8137 return E.getTime(this.browserEvent);
8143 * Gets the page coordinates of the event.
8144 * @return {Array} The xy values like [x, y]
8151 * Gets the target for the event.
8152 * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target
8153 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
8154 search as a number or element (defaults to 10 || document.body)
8155 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
8156 * @return {HTMLelement}
8158 getTarget : function(selector, maxDepth, returnEl){
8159 return selector ? Roo.fly(this.target).findParent(selector, maxDepth, returnEl) : this.target;
8162 * Gets the related target.
8163 * @return {HTMLElement}
8165 getRelatedTarget : function(){
8166 if(this.browserEvent){
8167 return E.getRelatedTarget(this.browserEvent);
8173 * Normalizes mouse wheel delta across browsers
8174 * @return {Number} The delta
8176 getWheelDelta : function(){
8177 var e = this.browserEvent;
8179 if(e.wheelDelta){ /* IE/Opera. */
8180 delta = e.wheelDelta/120;
8181 }else if(e.detail){ /* Mozilla case. */
8182 delta = -e.detail/3;
8188 * Returns true if the control, meta, shift or alt key was pressed during this event.
8191 hasModifier : function(){
8192 return !!((this.ctrlKey || this.altKey) || this.shiftKey);
8196 * Returns true if the target of this event equals el or is a child of el
8197 * @param {String/HTMLElement/Element} el
8198 * @param {Boolean} related (optional) true to test if the related target is within el instead of the target
8201 within : function(el, related){
8202 var t = this[related ? "getRelatedTarget" : "getTarget"]();
8203 return t && Roo.fly(el).contains(t);
8206 getPoint : function(){
8207 return new Roo.lib.Point(this.xy[0], this.xy[1]);
8211 return new Roo.EventObjectImpl();
8216 * Ext JS Library 1.1.1
8217 * Copyright(c) 2006-2007, Ext JS, LLC.
8219 * Originally Released Under LGPL - original licence link has changed is not relivant.
8222 * <script type="text/javascript">
8226 // was in Composite Element!??!?!
8229 var D = Roo.lib.Dom;
8230 var E = Roo.lib.Event;
8231 var A = Roo.lib.Anim;
8233 // local style camelizing for speed
8235 var camelRe = /(-[a-z])/gi;
8236 var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); };
8237 var view = document.defaultView;
8240 * @class Roo.Element
8241 * Represents an Element in the DOM.<br><br>
8244 var el = Roo.get("my-div");
8247 var el = getEl("my-div");
8249 // or with a DOM element
8250 var el = Roo.get(myDivElement);
8252 * Using Roo.get() or getEl() instead of calling the constructor directly ensures you get the same object
8253 * each call instead of constructing a new one.<br><br>
8254 * <b>Animations</b><br />
8255 * Many of the functions for manipulating an element have an optional "animate" parameter. The animate parameter
8256 * should either be a boolean (true) or an object literal with animation options. The animation options are:
8258 Option Default Description
8259 --------- -------- ---------------------------------------------
8260 duration .35 The duration of the animation in seconds
8261 easing easeOut The YUI easing method
8262 callback none A function to execute when the anim completes
8263 scope this The scope (this) of the callback function
8265 * Also, the Anim object being used for the animation will be set on your options object as "anim", which allows you to stop or
8266 * manipulate the animation. Here's an example:
8268 var el = Roo.get("my-div");
8273 // default animation
8274 el.setWidth(100, true);
8276 // animation with some options set
8283 // using the "anim" property to get the Anim object
8289 el.setWidth(100, opt);
8291 if(opt.anim.isAnimated()){
8295 * <b> Composite (Collections of) Elements</b><br />
8296 * For working with collections of Elements, see <a href="Roo.CompositeElement.html">Roo.CompositeElement</a>
8297 * @constructor Create a new Element directly.
8298 * @param {String/HTMLElement} element
8299 * @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).
8301 Roo.Element = function(element, forceNew)
8303 var dom = typeof element == "string" ?
8304 document.getElementById(element) : element;
8306 this.listeners = {};
8308 if(!dom){ // invalid id/element
8312 if(forceNew !== true && id && Roo.Element.cache[id]){ // element object already exists
8313 return Roo.Element.cache[id];
8323 * The DOM element ID
8326 this.id = id || Roo.id(dom);
8328 return this; // assumed for cctor?
8331 var El = Roo.Element;
8335 * The element's default display mode (defaults to "")
8338 originalDisplay : "",
8341 // note this is overridden in BS version..
8344 * The default unit to append to CSS values where a unit isn't provided (defaults to px).
8350 * Sets the element's visibility mode. When setVisible() is called it
8351 * will use this to determine whether to set the visibility or the display property.
8352 * @param visMode Element.VISIBILITY or Element.DISPLAY
8353 * @return {Roo.Element} this
8355 setVisibilityMode : function(visMode){
8356 this.visibilityMode = visMode;
8360 * Convenience method for setVisibilityMode(Element.DISPLAY)
8361 * @param {String} display (optional) What to set display to when visible
8362 * @return {Roo.Element} this
8364 enableDisplayMode : function(display){
8365 this.setVisibilityMode(El.DISPLAY);
8366 if(typeof display != "undefined") { this.originalDisplay = display; }
8371 * 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)
8372 * @param {String} selector The simple selector to test
8373 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
8374 search as a number or element (defaults to 10 || document.body)
8375 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
8376 * @return {HTMLElement} The matching DOM node (or null if no match was found)
8378 findParent : function(simpleSelector, maxDepth, returnEl){
8379 var p = this.dom, b = document.body, depth = 0, dq = Roo.DomQuery, stopEl;
8380 maxDepth = maxDepth || 50;
8381 if(typeof maxDepth != "number"){
8382 stopEl = Roo.getDom(maxDepth);
8385 while(p && p.nodeType == 1 && depth < maxDepth && p != b && p != stopEl){
8386 if(dq.is(p, simpleSelector)){
8387 return returnEl ? Roo.get(p) : p;
8397 * Looks at parent nodes for a match of the passed simple selector (e.g. div.some-class or span:first-child)
8398 * @param {String} selector The simple selector to test
8399 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
8400 search as a number or element (defaults to 10 || document.body)
8401 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
8402 * @return {HTMLElement} The matching DOM node (or null if no match was found)
8404 findParentNode : function(simpleSelector, maxDepth, returnEl){
8405 var p = Roo.fly(this.dom.parentNode, '_internal');
8406 return p ? p.findParent(simpleSelector, maxDepth, returnEl) : null;
8410 * Looks at the scrollable parent element
8412 findScrollableParent : function()
8414 var overflowRegex = /(auto|scroll)/;
8416 if(this.getStyle('position') === 'fixed'){
8417 return Roo.isAndroid ? Roo.get(document.documentElement) : Roo.get(document.body);
8420 var excludeStaticParent = this.getStyle('position') === "absolute";
8422 for (var parent = this; (parent = Roo.get(parent.dom.parentNode));){
8424 if (excludeStaticParent && parent.getStyle('position') === "static") {
8428 if (overflowRegex.test(parent.getStyle('overflow') + parent.getStyle('overflow-x') + parent.getStyle('overflow-y'))){
8432 if(parent.dom.nodeName.toLowerCase() == 'body'){
8433 return Roo.isAndroid ? Roo.get(document.documentElement) : Roo.get(document.body);
8437 return Roo.isAndroid ? Roo.get(document.documentElement) : Roo.get(document.body);
8441 * Walks up the dom looking for a parent node that matches the passed simple selector (e.g. div.some-class or span:first-child).
8442 * This is a shortcut for findParentNode() that always returns an Roo.Element.
8443 * @param {String} selector The simple selector to test
8444 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
8445 search as a number or element (defaults to 10 || document.body)
8446 * @return {Roo.Element} The matching DOM node (or null if no match was found)
8448 up : function(simpleSelector, maxDepth){
8449 return this.findParentNode(simpleSelector, maxDepth, true);
8455 * Returns true if this element matches the passed simple selector (e.g. div.some-class or span:first-child)
8456 * @param {String} selector The simple selector to test
8457 * @return {Boolean} True if this element matches the selector, else false
8459 is : function(simpleSelector){
8460 return Roo.DomQuery.is(this.dom, simpleSelector);
8464 * Perform animation on this element.
8465 * @param {Object} args The YUI animation control args
8466 * @param {Float} duration (optional) How long the animation lasts in seconds (defaults to .35)
8467 * @param {Function} onComplete (optional) Function to call when animation completes
8468 * @param {String} easing (optional) Easing method to use (defaults to 'easeOut')
8469 * @param {String} animType (optional) 'run' is the default. Can also be 'color', 'motion', or 'scroll'
8470 * @return {Roo.Element} this
8472 animate : function(args, duration, onComplete, easing, animType){
8473 this.anim(args, {duration: duration, callback: onComplete, easing: easing}, animType);
8478 * @private Internal animation call
8480 anim : function(args, opt, animType, defaultDur, defaultEase, cb){
8481 animType = animType || 'run';
8483 var anim = Roo.lib.Anim[animType](
8485 (opt.duration || defaultDur) || .35,
8486 (opt.easing || defaultEase) || 'easeOut',
8488 Roo.callback(cb, this);
8489 Roo.callback(opt.callback, opt.scope || this, [this, opt]);
8497 // private legacy anim prep
8498 preanim : function(a, i){
8499 return !a[i] ? false : (typeof a[i] == "object" ? a[i]: {duration: a[i+1], callback: a[i+2], easing: a[i+3]});
8503 * Removes worthless text nodes
8504 * @param {Boolean} forceReclean (optional) By default the element
8505 * keeps track if it has been cleaned already so
8506 * you can call this over and over. However, if you update the element and
8507 * need to force a reclean, you can pass true.
8509 clean : function(forceReclean){
8510 if(this.isCleaned && forceReclean !== true){
8514 var d = this.dom, n = d.firstChild, ni = -1;
8516 var nx = n.nextSibling;
8517 if(n.nodeType == 3 && !ns.test(n.nodeValue)){
8524 this.isCleaned = true;
8529 calcOffsetsTo : function(el){
8532 var restorePos = false;
8533 if(el.getStyle('position') == 'static'){
8534 el.position('relative');
8539 while(op && op != d && op.tagName != 'HTML'){
8542 op = op.offsetParent;
8545 el.position('static');
8551 * Scrolls this element into view within the passed container.
8552 * @param {String/HTMLElement/Element} container (optional) The container element to scroll (defaults to document.body)
8553 * @param {Boolean} hscroll (optional) False to disable horizontal scroll (defaults to true)
8554 * @return {Roo.Element} this
8556 scrollIntoView : function(container, hscroll){
8557 var c = Roo.getDom(container) || document.body;
8560 var o = this.calcOffsetsTo(c),
8563 b = t+el.offsetHeight,
8564 r = l+el.offsetWidth;
8566 var ch = c.clientHeight;
8567 var ct = parseInt(c.scrollTop, 10);
8568 var cl = parseInt(c.scrollLeft, 10);
8570 var cr = cl + c.clientWidth;
8578 if(hscroll !== false){
8582 c.scrollLeft = r-c.clientWidth;
8589 scrollChildIntoView : function(child, hscroll){
8590 Roo.fly(child, '_scrollChildIntoView').scrollIntoView(this, hscroll);
8594 * Measures the element's content height and updates height to match. Note: this function uses setTimeout so
8595 * the new height may not be available immediately.
8596 * @param {Boolean} animate (optional) Animate the transition (defaults to false)
8597 * @param {Float} duration (optional) Length of the animation in seconds (defaults to .35)
8598 * @param {Function} onComplete (optional) Function to call when animation completes
8599 * @param {String} easing (optional) Easing method to use (defaults to easeOut)
8600 * @return {Roo.Element} this
8602 autoHeight : function(animate, duration, onComplete, easing){
8603 var oldHeight = this.getHeight();
8605 this.setHeight(1); // force clipping
8606 setTimeout(function(){
8607 var height = parseInt(this.dom.scrollHeight, 10); // parseInt for Safari
8609 this.setHeight(height);
8611 if(typeof onComplete == "function"){
8615 this.setHeight(oldHeight); // restore original height
8616 this.setHeight(height, animate, duration, function(){
8618 if(typeof onComplete == "function") { onComplete(); }
8619 }.createDelegate(this), easing);
8621 }.createDelegate(this), 0);
8626 * Returns true if this element is an ancestor of the passed element
8627 * @param {HTMLElement/String} el The element to check
8628 * @return {Boolean} True if this element is an ancestor of el, else false
8630 contains : function(el){
8631 if(!el){return false;}
8632 return D.isAncestor(this.dom, el.dom ? el.dom : el);
8636 * Checks whether the element is currently visible using both visibility and display properties.
8637 * @param {Boolean} deep (optional) True to walk the dom and see if parent elements are hidden (defaults to false)
8638 * @return {Boolean} True if the element is currently visible, else false
8640 isVisible : function(deep) {
8641 var vis = !(this.getStyle("visibility") == "hidden" || this.getStyle("display") == "none");
8642 if(deep !== true || !vis){
8645 var p = this.dom.parentNode;
8646 while(p && p.tagName.toLowerCase() != "body"){
8647 if(!Roo.fly(p, '_isVisible').isVisible()){
8656 * Creates a {@link Roo.CompositeElement} for child nodes based on the passed CSS selector (the selector should not contain an id).
8657 * @param {String} selector The CSS selector
8658 * @param {Boolean} unique (optional) True to create a unique Roo.Element for each child (defaults to false, which creates a single shared flyweight object)
8659 * @return {CompositeElement/CompositeElementLite} The composite element
8661 select : function(selector, unique){
8662 return El.select(selector, unique, this.dom);
8666 * Selects child nodes based on the passed CSS selector (the selector should not contain an id).
8667 * @param {String} selector The CSS selector
8668 * @return {Array} An array of the matched nodes
8670 query : function(selector, unique){
8671 return Roo.DomQuery.select(selector, this.dom);
8675 * Selects a single child at any depth below this element based on the passed CSS selector (the selector should not contain an id).
8676 * @param {String} selector The CSS selector
8677 * @param {Boolean} returnDom (optional) True to return the DOM node instead of Roo.Element (defaults to false)
8678 * @return {HTMLElement/Roo.Element} The child Roo.Element (or DOM node if returnDom = true)
8680 child : function(selector, returnDom){
8681 var n = Roo.DomQuery.selectNode(selector, this.dom);
8682 return returnDom ? n : Roo.get(n);
8686 * Selects a single *direct* child based on the passed CSS selector (the selector should not contain an id).
8687 * @param {String} selector The CSS selector
8688 * @param {Boolean} returnDom (optional) True to return the DOM node instead of Roo.Element (defaults to false)
8689 * @return {HTMLElement/Roo.Element} The child Roo.Element (or DOM node if returnDom = true)
8691 down : function(selector, returnDom){
8692 var n = Roo.DomQuery.selectNode(" > " + selector, this.dom);
8693 return returnDom ? n : Roo.get(n);
8697 * Initializes a {@link Roo.dd.DD} drag drop object for this element.
8698 * @param {String} group The group the DD object is member of
8699 * @param {Object} config The DD config object
8700 * @param {Object} overrides An object containing methods to override/implement on the DD object
8701 * @return {Roo.dd.DD} The DD object
8703 initDD : function(group, config, overrides){
8704 var dd = new Roo.dd.DD(Roo.id(this.dom), group, config);
8705 return Roo.apply(dd, overrides);
8709 * Initializes a {@link Roo.dd.DDProxy} object for this element.
8710 * @param {String} group The group the DDProxy object is member of
8711 * @param {Object} config The DDProxy config object
8712 * @param {Object} overrides An object containing methods to override/implement on the DDProxy object
8713 * @return {Roo.dd.DDProxy} The DDProxy object
8715 initDDProxy : function(group, config, overrides){
8716 var dd = new Roo.dd.DDProxy(Roo.id(this.dom), group, config);
8717 return Roo.apply(dd, overrides);
8721 * Initializes a {@link Roo.dd.DDTarget} object for this element.
8722 * @param {String} group The group the DDTarget object is member of
8723 * @param {Object} config The DDTarget config object
8724 * @param {Object} overrides An object containing methods to override/implement on the DDTarget object
8725 * @return {Roo.dd.DDTarget} The DDTarget object
8727 initDDTarget : function(group, config, overrides){
8728 var dd = new Roo.dd.DDTarget(Roo.id(this.dom), group, config);
8729 return Roo.apply(dd, overrides);
8733 * Sets the visibility of the element (see details). If the visibilityMode is set to Element.DISPLAY, it will use
8734 * the display property to hide the element, otherwise it uses visibility. The default is to hide and show using the visibility property.
8735 * @param {Boolean} visible Whether the element is visible
8736 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8737 * @return {Roo.Element} this
8739 setVisible : function(visible, animate){
8741 if(this.visibilityMode == El.DISPLAY){
8742 this.setDisplayed(visible);
8745 this.dom.style.visibility = visible ? "visible" : "hidden";
8748 // closure for composites
8750 var visMode = this.visibilityMode;
8752 this.setOpacity(.01);
8753 this.setVisible(true);
8755 this.anim({opacity: { to: (visible?1:0) }},
8756 this.preanim(arguments, 1),
8757 null, .35, 'easeIn', function(){
8759 if(visMode == El.DISPLAY){
8760 dom.style.display = "none";
8762 dom.style.visibility = "hidden";
8764 Roo.get(dom).setOpacity(1);
8772 * Returns true if display is not "none"
8775 isDisplayed : function() {
8776 return this.getStyle("display") != "none";
8780 * Toggles the element's visibility or display, depending on visibility mode.
8781 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8782 * @return {Roo.Element} this
8784 toggle : function(animate){
8785 this.setVisible(!this.isVisible(), this.preanim(arguments, 0));
8790 * Sets the CSS display property. Uses originalDisplay if the specified value is a boolean true.
8791 * @param {Boolean} value Boolean value to display the element using its default display, or a string to set the display directly
8792 * @return {Roo.Element} this
8794 setDisplayed : function(value) {
8795 if(typeof value == "boolean"){
8796 value = value ? this.originalDisplay : "none";
8798 this.setStyle("display", value);
8803 * Tries to focus the element. Any exceptions are caught and ignored.
8804 * @return {Roo.Element} this
8806 focus : function() {
8814 * Tries to blur the element. Any exceptions are caught and ignored.
8815 * @return {Roo.Element} this
8825 * Adds one or more CSS classes to the element. Duplicate classes are automatically filtered out.
8826 * @param {String/Array} className The CSS class to add, or an array of classes
8827 * @return {Roo.Element} this
8829 addClass : function(className){
8830 if(className instanceof Array){
8831 for(var i = 0, len = className.length; i < len; i++) {
8832 this.addClass(className[i]);
8835 if(className && !this.hasClass(className)){
8836 if (this.dom instanceof SVGElement) {
8837 this.dom.className.baseVal =this.dom.className.baseVal + " " + className;
8839 this.dom.className = this.dom.className + " " + className;
8847 * Adds one or more CSS classes to this element and removes the same class(es) from all siblings.
8848 * @param {String/Array} className The CSS class to add, or an array of classes
8849 * @return {Roo.Element} this
8851 radioClass : function(className){
8852 var siblings = this.dom.parentNode.childNodes;
8853 for(var i = 0; i < siblings.length; i++) {
8854 var s = siblings[i];
8855 if(s.nodeType == 1){
8856 Roo.get(s).removeClass(className);
8859 this.addClass(className);
8864 * Removes one or more CSS classes from the element.
8865 * @param {String/Array} className The CSS class to remove, or an array of classes
8866 * @return {Roo.Element} this
8868 removeClass : function(className){
8870 var cn = this.dom instanceof SVGElement ? this.dom.className.baseVal : this.dom.className;
8871 if(!className || !cn){
8874 if(className instanceof Array){
8875 for(var i = 0, len = className.length; i < len; i++) {
8876 this.removeClass(className[i]);
8879 if(this.hasClass(className)){
8880 var re = this.classReCache[className];
8882 re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)', "g");
8883 this.classReCache[className] = re;
8885 if (this.dom instanceof SVGElement) {
8886 this.dom.className.baseVal = cn.replace(re, " ");
8888 this.dom.className = cn.replace(re, " ");
8899 * Toggles the specified CSS class on this element (removes it if it already exists, otherwise adds it).
8900 * @param {String} className The CSS class to toggle
8901 * @return {Roo.Element} this
8903 toggleClass : function(className){
8904 if(this.hasClass(className)){
8905 this.removeClass(className);
8907 this.addClass(className);
8913 * Checks if the specified CSS class exists on this element's DOM node.
8914 * @param {String} className The CSS class to check for
8915 * @return {Boolean} True if the class exists, else false
8917 hasClass : function(className){
8918 if (this.dom instanceof SVGElement) {
8919 return className && (' '+this.dom.className.baseVal +' ').indexOf(' '+className+' ') != -1;
8921 return className && (' '+this.dom.className+' ').indexOf(' '+className+' ') != -1;
8925 * Replaces a CSS class on the element with another. If the old name does not exist, the new name will simply be added.
8926 * @param {String} oldClassName The CSS class to replace
8927 * @param {String} newClassName The replacement CSS class
8928 * @return {Roo.Element} this
8930 replaceClass : function(oldClassName, newClassName){
8931 this.removeClass(oldClassName);
8932 this.addClass(newClassName);
8937 * Returns an object with properties matching the styles requested.
8938 * For example, el.getStyles('color', 'font-size', 'width') might return
8939 * {'color': '#FFFFFF', 'font-size': '13px', 'width': '100px'}.
8940 * @param {String} style1 A style name
8941 * @param {String} style2 A style name
8942 * @param {String} etc.
8943 * @return {Object} The style object
8945 getStyles : function(){
8946 var a = arguments, len = a.length, r = {};
8947 for(var i = 0; i < len; i++){
8948 r[a[i]] = this.getStyle(a[i]);
8954 * Normalizes currentStyle and computedStyle. This is not YUI getStyle, it is an optimised version.
8955 * @param {String} property The style property whose value is returned.
8956 * @return {String} The current value of the style property for this element.
8958 getStyle : function(){
8959 return view && view.getComputedStyle ?
8961 var el = this.dom, v, cs, camel;
8962 if(prop == 'float'){
8965 if(el.style && (v = el.style[prop])){
8968 if(cs = view.getComputedStyle(el, "")){
8969 if(!(camel = propCache[prop])){
8970 camel = propCache[prop] = prop.replace(camelRe, camelFn);
8977 var el = this.dom, v, cs, camel;
8978 if(prop == 'opacity'){
8979 if(typeof el.style.filter == 'string'){
8980 var m = el.style.filter.match(/alpha\(opacity=(.*)\)/i);
8982 var fv = parseFloat(m[1]);
8984 return fv ? fv / 100 : 0;
8989 }else if(prop == 'float'){
8990 prop = "styleFloat";
8992 if(!(camel = propCache[prop])){
8993 camel = propCache[prop] = prop.replace(camelRe, camelFn);
8995 if(v = el.style[camel]){
8998 if(cs = el.currentStyle){
9006 * Wrapper for setting style properties, also takes single object parameter of multiple styles.
9007 * @param {String/Object} property The style property to be set, or an object of multiple styles.
9008 * @param {String} value (optional) The value to apply to the given property, or null if an object was passed.
9009 * @return {Roo.Element} this
9011 setStyle : function(prop, value){
9012 if(typeof prop == "string"){
9014 if (prop == 'float') {
9015 this.setStyle(Roo.isIE ? 'styleFloat' : 'cssFloat', value);
9020 if(!(camel = propCache[prop])){
9021 camel = propCache[prop] = prop.replace(camelRe, camelFn);
9024 if(camel == 'opacity') {
9025 this.setOpacity(value);
9027 this.dom.style[camel] = value;
9030 for(var style in prop){
9031 if(typeof prop[style] != "function"){
9032 this.setStyle(style, prop[style]);
9040 * More flexible version of {@link #setStyle} for setting style properties.
9041 * @param {String/Object/Function} styles A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
9042 * a function which returns such a specification.
9043 * @return {Roo.Element} this
9045 applyStyles : function(style){
9046 Roo.DomHelper.applyStyles(this.dom, style);
9051 * 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).
9052 * @return {Number} The X position of the element
9055 return D.getX(this.dom);
9059 * 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).
9060 * @return {Number} The Y position of the element
9063 return D.getY(this.dom);
9067 * 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).
9068 * @return {Array} The XY position of the element
9071 return D.getXY(this.dom);
9075 * 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).
9076 * @param {Number} The X position of the element
9077 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
9078 * @return {Roo.Element} this
9080 setX : function(x, animate){
9082 D.setX(this.dom, x);
9084 this.setXY([x, this.getY()], this.preanim(arguments, 1));
9090 * 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).
9091 * @param {Number} The Y position of the element
9092 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
9093 * @return {Roo.Element} this
9095 setY : function(y, animate){
9097 D.setY(this.dom, y);
9099 this.setXY([this.getX(), y], this.preanim(arguments, 1));
9105 * Sets the element's left position directly using CSS style (instead of {@link #setX}).
9106 * @param {String} left The left CSS property value
9107 * @return {Roo.Element} this
9109 setLeft : function(left){
9110 this.setStyle("left", this.addUnits(left));
9115 * Sets the element's top position directly using CSS style (instead of {@link #setY}).
9116 * @param {String} top The top CSS property value
9117 * @return {Roo.Element} this
9119 setTop : function(top){
9120 this.setStyle("top", this.addUnits(top));
9125 * Sets the element's CSS right style.
9126 * @param {String} right The right CSS property value
9127 * @return {Roo.Element} this
9129 setRight : function(right){
9130 this.setStyle("right", this.addUnits(right));
9135 * Sets the element's CSS bottom style.
9136 * @param {String} bottom The bottom CSS property value
9137 * @return {Roo.Element} this
9139 setBottom : function(bottom){
9140 this.setStyle("bottom", this.addUnits(bottom));
9145 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
9146 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
9147 * @param {Array} pos Contains X & Y [x, y] values for new position (coordinates are page-based)
9148 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
9149 * @return {Roo.Element} this
9151 setXY : function(pos, animate){
9153 D.setXY(this.dom, pos);
9155 this.anim({points: {to: pos}}, this.preanim(arguments, 1), 'motion');
9161 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
9162 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
9163 * @param {Number} x X value for new position (coordinates are page-based)
9164 * @param {Number} y Y value for new position (coordinates are page-based)
9165 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
9166 * @return {Roo.Element} this
9168 setLocation : function(x, y, animate){
9169 this.setXY([x, y], this.preanim(arguments, 2));
9174 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
9175 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
9176 * @param {Number} x X value for new position (coordinates are page-based)
9177 * @param {Number} y Y value for new position (coordinates are page-based)
9178 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
9179 * @return {Roo.Element} this
9181 moveTo : function(x, y, animate){
9182 this.setXY([x, y], this.preanim(arguments, 2));
9187 * Returns the region of the given element.
9188 * The element must be part of the DOM tree to have a region (display:none or elements not appended return false).
9189 * @return {Region} A Roo.lib.Region containing "top, left, bottom, right" member data.
9191 getRegion : function(){
9192 return D.getRegion(this.dom);
9196 * Returns the offset height of the element
9197 * @param {Boolean} contentHeight (optional) true to get the height minus borders and padding
9198 * @return {Number} The element's height
9200 getHeight : function(contentHeight){
9201 var h = this.dom.offsetHeight || 0;
9202 return contentHeight !== true ? h : h-this.getBorderWidth("tb")-this.getPadding("tb");
9206 * Returns the offset width of the element
9207 * @param {Boolean} contentWidth (optional) true to get the width minus borders and padding
9208 * @return {Number} The element's width
9210 getWidth : function(contentWidth){
9211 var w = this.dom.offsetWidth || 0;
9212 return contentWidth !== true ? w : w-this.getBorderWidth("lr")-this.getPadding("lr");
9216 * Returns either the offsetHeight or the height of this element based on CSS height adjusted by padding or borders
9217 * when needed to simulate offsetHeight when offsets aren't available. This may not work on display:none elements
9218 * if a height has not been set using CSS.
9221 getComputedHeight : function(){
9222 var h = Math.max(this.dom.offsetHeight, this.dom.clientHeight);
9224 h = parseInt(this.getStyle('height'), 10) || 0;
9225 if(!this.isBorderBox()){
9226 h += this.getFrameWidth('tb');
9233 * Returns either the offsetWidth or the width of this element based on CSS width adjusted by padding or borders
9234 * when needed to simulate offsetWidth when offsets aren't available. This may not work on display:none elements
9235 * if a width has not been set using CSS.
9238 getComputedWidth : function(){
9239 var w = Math.max(this.dom.offsetWidth, this.dom.clientWidth);
9241 w = parseInt(this.getStyle('width'), 10) || 0;
9242 if(!this.isBorderBox()){
9243 w += this.getFrameWidth('lr');
9250 * Returns the size of the element.
9251 * @param {Boolean} contentSize (optional) true to get the width/size minus borders and padding
9252 * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
9254 getSize : function(contentSize){
9255 return {width: this.getWidth(contentSize), height: this.getHeight(contentSize)};
9259 * Returns the width and height of the viewport.
9260 * @return {Object} An object containing the viewport's size {width: (viewport width), height: (viewport height)}
9262 getViewSize : function(){
9263 var d = this.dom, doc = document, aw = 0, ah = 0;
9264 if(d == doc || d == doc.body){
9265 return {width : D.getViewWidth(), height: D.getViewHeight()};
9268 width : d.clientWidth,
9269 height: d.clientHeight
9275 * Returns the value of the "value" attribute
9276 * @param {Boolean} asNumber true to parse the value as a number
9277 * @return {String/Number}
9279 getValue : function(asNumber){
9280 return asNumber ? parseInt(this.dom.value, 10) : this.dom.value;
9284 adjustWidth : function(width){
9285 if(typeof width == "number"){
9286 if(this.autoBoxAdjust && !this.isBorderBox()){
9287 width -= (this.getBorderWidth("lr") + this.getPadding("lr"));
9297 adjustHeight : function(height){
9298 if(typeof height == "number"){
9299 if(this.autoBoxAdjust && !this.isBorderBox()){
9300 height -= (this.getBorderWidth("tb") + this.getPadding("tb"));
9310 * Set the width of the element
9311 * @param {Number} width The new width
9312 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9313 * @return {Roo.Element} this
9315 setWidth : function(width, animate){
9316 width = this.adjustWidth(width);
9318 this.dom.style.width = this.addUnits(width);
9320 this.anim({width: {to: width}}, this.preanim(arguments, 1));
9326 * Set the height of the element
9327 * @param {Number} height The new height
9328 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9329 * @return {Roo.Element} this
9331 setHeight : function(height, animate){
9332 height = this.adjustHeight(height);
9334 this.dom.style.height = this.addUnits(height);
9336 this.anim({height: {to: height}}, this.preanim(arguments, 1));
9342 * Set the size of the element. If animation is true, both width an height will be animated concurrently.
9343 * @param {Number} width The new width
9344 * @param {Number} height The new height
9345 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9346 * @return {Roo.Element} this
9348 setSize : function(width, height, animate){
9349 if(typeof width == "object"){ // in case of object from getSize()
9350 height = width.height; width = width.width;
9352 width = this.adjustWidth(width); height = this.adjustHeight(height);
9354 this.dom.style.width = this.addUnits(width);
9355 this.dom.style.height = this.addUnits(height);
9357 this.anim({width: {to: width}, height: {to: height}}, this.preanim(arguments, 2));
9363 * Sets the element's position and size in one shot. If animation is true then width, height, x and y will be animated concurrently.
9364 * @param {Number} x X value for new position (coordinates are page-based)
9365 * @param {Number} y Y value for new position (coordinates are page-based)
9366 * @param {Number} width The new width
9367 * @param {Number} height The new height
9368 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9369 * @return {Roo.Element} this
9371 setBounds : function(x, y, width, height, animate){
9373 this.setSize(width, height);
9374 this.setLocation(x, y);
9376 width = this.adjustWidth(width); height = this.adjustHeight(height);
9377 this.anim({points: {to: [x, y]}, width: {to: width}, height: {to: height}},
9378 this.preanim(arguments, 4), 'motion');
9384 * 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.
9385 * @param {Roo.lib.Region} region The region to fill
9386 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9387 * @return {Roo.Element} this
9389 setRegion : function(region, animate){
9390 this.setBounds(region.left, region.top, region.right-region.left, region.bottom-region.top, this.preanim(arguments, 1));
9395 * Appends an event handler
9397 * @param {String} eventName The type of event to append
9398 * @param {Function} fn The method the event invokes
9399 * @param {Object} scope (optional) The scope (this object) of the fn
9400 * @param {Object} options (optional)An object with standard {@link Roo.EventManager#addListener} options
9402 addListener : function(eventName, fn, scope, options)
9404 if (eventName == 'dblclick') { // doublclick (touchstart) - faked on touch.
9405 this.addListener('touchstart', this.onTapHandler, this);
9408 // we need to handle a special case where dom element is a svg element.
9409 // in this case we do not actua
9414 if (this.dom instanceof SVGElement && !(this.dom instanceof SVGSVGElement)) {
9415 if (typeof(this.listeners[eventName]) == 'undefined') {
9416 this.listeners[eventName] = new Roo.util.Event(this, eventName);
9418 this.listeners[eventName].addListener(fn, scope, options);
9423 Roo.EventManager.on(this.dom, eventName, fn, scope || this, options);
9428 onTapHandler : function(event)
9430 if(!this.tapedTwice) {
9431 this.tapedTwice = true;
9433 setTimeout( function() {
9434 s.tapedTwice = false;
9438 event.preventDefault();
9439 var revent = new MouseEvent('dblclick', {
9445 this.dom.dispatchEvent(revent);
9446 //action on double tap goes below
9451 * Removes an event handler from this element
9452 * @param {String} eventName the type of event to remove
9453 * @param {Function} fn the method the event invokes
9454 * @param {Function} scope (needed for svg fake listeners)
9455 * @return {Roo.Element} this
9457 removeListener : function(eventName, fn, scope){
9458 Roo.EventManager.removeListener(this.dom, eventName, fn);
9459 if (typeof(this.listeners) == 'undefined' || typeof(this.listeners[eventName]) == 'undefined') {
9462 this.listeners[eventName].removeListener(fn, scope);
9467 * Removes all previous added listeners from this element
9468 * @return {Roo.Element} this
9470 removeAllListeners : function(){
9471 E.purgeElement(this.dom);
9472 this.listeners = {};
9476 relayEvent : function(eventName, observable){
9477 this.on(eventName, function(e){
9478 observable.fireEvent(eventName, e);
9484 * Set the opacity of the element
9485 * @param {Float} opacity The new opacity. 0 = transparent, .5 = 50% visibile, 1 = fully visible, etc
9486 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9487 * @return {Roo.Element} this
9489 setOpacity : function(opacity, animate){
9491 var s = this.dom.style;
9494 s.filter = (s.filter || '').replace(/alpha\([^\)]*\)/gi,"") +
9495 (opacity == 1 ? "" : "alpha(opacity=" + opacity * 100 + ")");
9497 s.opacity = opacity;
9500 this.anim({opacity: {to: opacity}}, this.preanim(arguments, 1), null, .35, 'easeIn');
9506 * Gets the left X coordinate
9507 * @param {Boolean} local True to get the local css position instead of page coordinate
9510 getLeft : function(local){
9514 return parseInt(this.getStyle("left"), 10) || 0;
9519 * Gets the right X coordinate of the element (element X position + element width)
9520 * @param {Boolean} local True to get the local css position instead of page coordinate
9523 getRight : function(local){
9525 return this.getX() + this.getWidth();
9527 return (this.getLeft(true) + this.getWidth()) || 0;
9532 * Gets the top Y coordinate
9533 * @param {Boolean} local True to get the local css position instead of page coordinate
9536 getTop : function(local) {
9540 return parseInt(this.getStyle("top"), 10) || 0;
9545 * Gets the bottom Y coordinate of the element (element Y position + element height)
9546 * @param {Boolean} local True to get the local css position instead of page coordinate
9549 getBottom : function(local){
9551 return this.getY() + this.getHeight();
9553 return (this.getTop(true) + this.getHeight()) || 0;
9558 * Initializes positioning on this element. If a desired position is not passed, it will make the
9559 * the element positioned relative IF it is not already positioned.
9560 * @param {String} pos (optional) Positioning to use "relative", "absolute" or "fixed"
9561 * @param {Number} zIndex (optional) The zIndex to apply
9562 * @param {Number} x (optional) Set the page X position
9563 * @param {Number} y (optional) Set the page Y position
9565 position : function(pos, zIndex, x, y){
9567 if(this.getStyle('position') == 'static'){
9568 this.setStyle('position', 'relative');
9571 this.setStyle("position", pos);
9574 this.setStyle("z-index", zIndex);
9576 if(x !== undefined && y !== undefined){
9578 }else if(x !== undefined){
9580 }else if(y !== undefined){
9586 * Clear positioning back to the default when the document was loaded
9587 * @param {String} value (optional) The value to use for the left,right,top,bottom, defaults to '' (empty string). You could use 'auto'.
9588 * @return {Roo.Element} this
9590 clearPositioning : function(value){
9598 "position" : "static"
9604 * Gets an object with all CSS positioning properties. Useful along with setPostioning to get
9605 * snapshot before performing an update and then restoring the element.
9608 getPositioning : function(){
9609 var l = this.getStyle("left");
9610 var t = this.getStyle("top");
9612 "position" : this.getStyle("position"),
9614 "right" : l ? "" : this.getStyle("right"),
9616 "bottom" : t ? "" : this.getStyle("bottom"),
9617 "z-index" : this.getStyle("z-index")
9622 * Gets the width of the border(s) for the specified side(s)
9623 * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
9624 * passing lr would get the border (l)eft width + the border (r)ight width.
9625 * @return {Number} The width of the sides passed added together
9627 getBorderWidth : function(side){
9628 return this.addStyles(side, El.borders);
9632 * Gets the width of the padding(s) for the specified side(s)
9633 * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
9634 * passing lr would get the padding (l)eft + the padding (r)ight.
9635 * @return {Number} The padding of the sides passed added together
9637 getPadding : function(side){
9638 return this.addStyles(side, El.paddings);
9642 * Set positioning with an object returned by getPositioning().
9643 * @param {Object} posCfg
9644 * @return {Roo.Element} this
9646 setPositioning : function(pc){
9647 this.applyStyles(pc);
9648 if(pc.right == "auto"){
9649 this.dom.style.right = "";
9651 if(pc.bottom == "auto"){
9652 this.dom.style.bottom = "";
9658 fixDisplay : function(){
9659 if(this.getStyle("display") == "none"){
9660 this.setStyle("visibility", "hidden");
9661 this.setStyle("display", this.originalDisplay); // first try reverting to default
9662 if(this.getStyle("display") == "none"){ // if that fails, default to block
9663 this.setStyle("display", "block");
9669 * Quick set left and top adding default units
9670 * @param {String} left The left CSS property value
9671 * @param {String} top The top CSS property value
9672 * @return {Roo.Element} this
9674 setLeftTop : function(left, top){
9675 this.dom.style.left = this.addUnits(left);
9676 this.dom.style.top = this.addUnits(top);
9681 * Move this element relative to its current position.
9682 * @param {String} direction Possible values are: "l","left" - "r","right" - "t","top","up" - "b","bottom","down".
9683 * @param {Number} distance How far to move the element in pixels
9684 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9685 * @return {Roo.Element} this
9687 move : function(direction, distance, animate){
9688 var xy = this.getXY();
9689 direction = direction.toLowerCase();
9693 this.moveTo(xy[0]-distance, xy[1], this.preanim(arguments, 2));
9697 this.moveTo(xy[0]+distance, xy[1], this.preanim(arguments, 2));
9702 this.moveTo(xy[0], xy[1]-distance, this.preanim(arguments, 2));
9707 this.moveTo(xy[0], xy[1]+distance, this.preanim(arguments, 2));
9714 * Store the current overflow setting and clip overflow on the element - use {@link #unclip} to remove
9715 * @return {Roo.Element} this
9718 if(!this.isClipped){
9719 this.isClipped = true;
9720 this.originalClip = {
9721 "o": this.getStyle("overflow"),
9722 "x": this.getStyle("overflow-x"),
9723 "y": this.getStyle("overflow-y")
9725 this.setStyle("overflow", "hidden");
9726 this.setStyle("overflow-x", "hidden");
9727 this.setStyle("overflow-y", "hidden");
9733 * Return clipping (overflow) to original clipping before clip() was called
9734 * @return {Roo.Element} this
9736 unclip : function(){
9738 this.isClipped = false;
9739 var o = this.originalClip;
9740 if(o.o){this.setStyle("overflow", o.o);}
9741 if(o.x){this.setStyle("overflow-x", o.x);}
9742 if(o.y){this.setStyle("overflow-y", o.y);}
9749 * Gets the x,y coordinates specified by the anchor position on the element.
9750 * @param {String} anchor (optional) The specified anchor position (defaults to "c"). See {@link #alignTo} for details on supported anchor positions.
9751 * @param {Object} size (optional) An object containing the size to use for calculating anchor position
9752 * {width: (target width), height: (target height)} (defaults to the element's current size)
9753 * @param {Boolean} local (optional) True to get the local (element top/left-relative) anchor position instead of page coordinates
9754 * @return {Array} [x, y] An array containing the element's x and y coordinates
9756 getAnchorXY : function(anchor, local, s){
9757 //Passing a different size is useful for pre-calculating anchors,
9758 //especially for anchored animations that change the el size.
9760 var w, h, vp = false;
9763 if(d == document.body || d == document){
9765 w = D.getViewWidth(); h = D.getViewHeight();
9767 w = this.getWidth(); h = this.getHeight();
9770 w = s.width; h = s.height;
9772 var x = 0, y = 0, r = Math.round;
9773 switch((anchor || "tl").toLowerCase()){
9815 var sc = this.getScroll();
9816 return [x + sc.left, y + sc.top];
9818 //Add the element's offset xy
9819 var o = this.getXY();
9820 return [x+o[0], y+o[1]];
9824 * Gets the x,y coordinates to align this element with another element. See {@link #alignTo} for more info on the
9825 * supported position values.
9826 * @param {String/HTMLElement/Roo.Element} element The element to align to.
9827 * @param {String} position The position to align to.
9828 * @param {Array} offsets (optional) Offset the positioning by [x, y]
9829 * @return {Array} [x, y]
9831 getAlignToXY : function(el, p, o)
9836 throw "Element.alignTo with an element that doesn't exist";
9838 var c = false; //constrain to viewport
9839 var p1 = "", p2 = "";
9846 }else if(p.indexOf("-") == -1){
9849 p = p.toLowerCase();
9850 var m = p.match(/^([a-z]+)-([a-z]+)(\?)?$/);
9852 throw "Element.alignTo with an invalid alignment " + p;
9854 p1 = m[1]; p2 = m[2]; c = !!m[3];
9856 //Subtract the aligned el's internal xy from the target's offset xy
9857 //plus custom offset to get the aligned el's new offset xy
9858 var a1 = this.getAnchorXY(p1, true);
9859 var a2 = el.getAnchorXY(p2, false);
9860 var x = a2[0] - a1[0] + o[0];
9861 var y = a2[1] - a1[1] + o[1];
9863 //constrain the aligned el to viewport if necessary
9864 var w = this.getWidth(), h = this.getHeight(), r = el.getRegion();
9865 // 5px of margin for ie
9866 var dw = D.getViewWidth()-5, dh = D.getViewHeight()-5;
9868 //If we are at a viewport boundary and the aligned el is anchored on a target border that is
9869 //perpendicular to the vp border, allow the aligned el to slide on that border,
9870 //otherwise swap the aligned el to the opposite border of the target.
9871 var p1y = p1.charAt(0), p1x = p1.charAt(p1.length-1);
9872 var p2y = p2.charAt(0), p2x = p2.charAt(p2.length-1);
9873 var swapY = ((p1y=="t" && p2y=="b") || (p1y=="b" && p2y=="t") );
9874 var swapX = ((p1x=="r" && p2x=="l") || (p1x=="l" && p2x=="r"));
9877 var scrollX = (doc.documentElement.scrollLeft || doc.body.scrollLeft || 0)+5;
9878 var scrollY = (doc.documentElement.scrollTop || doc.body.scrollTop || 0)+5;
9880 if((x+w) > dw + scrollX){
9881 x = swapX ? r.left-w : dw+scrollX-w;
9884 x = swapX ? r.right : scrollX;
9886 if((y+h) > dh + scrollY){
9887 y = swapY ? r.top-h : dh+scrollY-h;
9890 y = swapY ? r.bottom : scrollY;
9897 getConstrainToXY : function(){
9898 var os = {top:0, left:0, bottom:0, right: 0};
9900 return function(el, local, offsets, proposedXY){
9902 offsets = offsets ? Roo.applyIf(offsets, os) : os;
9904 var vw, vh, vx = 0, vy = 0;
9905 if(el.dom == document.body || el.dom == document){
9906 vw = Roo.lib.Dom.getViewWidth();
9907 vh = Roo.lib.Dom.getViewHeight();
9909 vw = el.dom.clientWidth;
9910 vh = el.dom.clientHeight;
9912 var vxy = el.getXY();
9918 var s = el.getScroll();
9920 vx += offsets.left + s.left;
9921 vy += offsets.top + s.top;
9923 vw -= offsets.right;
9924 vh -= offsets.bottom;
9929 var xy = proposedXY || (!local ? this.getXY() : [this.getLeft(true), this.getTop(true)]);
9930 var x = xy[0], y = xy[1];
9931 var w = this.dom.offsetWidth, h = this.dom.offsetHeight;
9933 // only move it if it needs it
9936 // first validate right/bottom
9945 // then make sure top/left isn't negative
9954 return moved ? [x, y] : false;
9959 adjustForConstraints : function(xy, parent, offsets){
9960 return this.getConstrainToXY(parent || document, false, offsets, xy) || xy;
9964 * Aligns this element with another element relative to the specified anchor points. If the other element is the
9965 * document it aligns it to the viewport.
9966 * The position parameter is optional, and can be specified in any one of the following formats:
9968 * <li><b>Blank</b>: Defaults to aligning the element's top-left corner to the target's bottom-left corner ("tl-bl").</li>
9969 * <li><b>One anchor (deprecated)</b>: The passed anchor position is used as the target element's anchor point.
9970 * The element being aligned will position its top-left corner (tl) to that point. <i>This method has been
9971 * deprecated in favor of the newer two anchor syntax below</i>.</li>
9972 * <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
9973 * element's anchor point, and the second value is used as the target's anchor point.</li>
9975 * In addition to the anchor points, the position parameter also supports the "?" character. If "?" is passed at the end of
9976 * the position string, the element will attempt to align as specified, but the position will be adjusted to constrain to
9977 * the viewport if necessary. Note that the element being aligned might be swapped to align to a different position than
9978 * that specified in order to enforce the viewport constraints.
9979 * Following are all of the supported anchor positions:
9982 ----- -----------------------------
9983 tl The top left corner (default)
9984 t The center of the top edge
9985 tr The top right corner
9986 l The center of the left edge
9987 c In the center of the element
9988 r The center of the right edge
9989 bl The bottom left corner
9990 b The center of the bottom edge
9991 br The bottom right corner
9995 // align el to other-el using the default positioning ("tl-bl", non-constrained)
9996 el.alignTo("other-el");
9998 // align the top left corner of el with the top right corner of other-el (constrained to viewport)
9999 el.alignTo("other-el", "tr?");
10001 // align the bottom right corner of el with the center left edge of other-el
10002 el.alignTo("other-el", "br-l?");
10004 // align the center of el with the bottom left corner of other-el and
10005 // adjust the x position by -6 pixels (and the y position by 0)
10006 el.alignTo("other-el", "c-bl", [-6, 0]);
10008 * @param {String/HTMLElement/Roo.Element} element The element to align to.
10009 * @param {String} position The position to align to.
10010 * @param {Array} offsets (optional) Offset the positioning by [x, y]
10011 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
10012 * @return {Roo.Element} this
10014 alignTo : function(element, position, offsets, animate){
10015 var xy = this.getAlignToXY(element, position, offsets);
10016 this.setXY(xy, this.preanim(arguments, 3));
10021 * Anchors an element to another element and realigns it when the window is resized.
10022 * @param {String/HTMLElement/Roo.Element} element The element to align to.
10023 * @param {String} position The position to align to.
10024 * @param {Array} offsets (optional) Offset the positioning by [x, y]
10025 * @param {Boolean/Object} animate (optional) True for the default animation or a standard Element animation config object
10026 * @param {Boolean/Number} monitorScroll (optional) True to monitor body scroll and reposition. If this parameter
10027 * is a number, it is used as the buffer delay (defaults to 50ms).
10028 * @param {Function} callback The function to call after the animation finishes
10029 * @return {Roo.Element} this
10031 anchorTo : function(el, alignment, offsets, animate, monitorScroll, callback){
10032 var action = function(){
10033 this.alignTo(el, alignment, offsets, animate);
10034 Roo.callback(callback, this);
10036 Roo.EventManager.onWindowResize(action, this);
10037 var tm = typeof monitorScroll;
10038 if(tm != 'undefined'){
10039 Roo.EventManager.on(window, 'scroll', action, this,
10040 {buffer: tm == 'number' ? monitorScroll : 50});
10042 action.call(this); // align immediately
10046 * Clears any opacity settings from this element. Required in some cases for IE.
10047 * @return {Roo.Element} this
10049 clearOpacity : function(){
10050 if (window.ActiveXObject) {
10051 if(typeof this.dom.style.filter == 'string' && (/alpha/i).test(this.dom.style.filter)){
10052 this.dom.style.filter = "";
10055 this.dom.style.opacity = "";
10056 this.dom.style["-moz-opacity"] = "";
10057 this.dom.style["-khtml-opacity"] = "";
10063 * Hide this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
10064 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
10065 * @return {Roo.Element} this
10067 hide : function(animate){
10068 this.setVisible(false, this.preanim(arguments, 0));
10073 * Show this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
10074 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
10075 * @return {Roo.Element} this
10077 show : function(animate){
10078 this.setVisible(true, this.preanim(arguments, 0));
10083 * @private Test if size has a unit, otherwise appends the default
10085 addUnits : function(size){
10086 return Roo.Element.addUnits(size, this.defaultUnit);
10090 * Temporarily enables offsets (width,height,x,y) for an element with display:none, use endMeasure() when done.
10091 * @return {Roo.Element} this
10093 beginMeasure : function(){
10095 if(el.offsetWidth || el.offsetHeight){
10096 return this; // offsets work already
10099 var p = this.dom, b = document.body; // start with this element
10100 while((!el.offsetWidth && !el.offsetHeight) && p && p.tagName && p != b){
10101 var pe = Roo.get(p);
10102 if(pe.getStyle('display') == 'none'){
10103 changed.push({el: p, visibility: pe.getStyle("visibility")});
10104 p.style.visibility = "hidden";
10105 p.style.display = "block";
10109 this._measureChanged = changed;
10115 * Restores displays to before beginMeasure was called
10116 * @return {Roo.Element} this
10118 endMeasure : function(){
10119 var changed = this._measureChanged;
10121 for(var i = 0, len = changed.length; i < len; i++) {
10122 var r = changed[i];
10123 r.el.style.visibility = r.visibility;
10124 r.el.style.display = "none";
10126 this._measureChanged = null;
10132 * Update the innerHTML of this element, optionally searching for and processing scripts
10133 * @param {String} html The new HTML
10134 * @param {Boolean} loadScripts (optional) true to look for and process scripts
10135 * @param {Function} callback For async script loading you can be noticed when the update completes
10136 * @return {Roo.Element} this
10138 update : function(html, loadScripts, callback){
10139 if(typeof html == "undefined"){
10142 if(loadScripts !== true){
10143 this.dom.innerHTML = html;
10144 if(typeof callback == "function"){
10150 var dom = this.dom;
10152 html += '<span id="' + id + '"></span>';
10154 E.onAvailable(id, function(){
10155 var hd = document.getElementsByTagName("head")[0];
10156 var re = /(?:<script([^>]*)?>)((\n|\r|.)*?)(?:<\/script>)/ig;
10157 var srcRe = /\ssrc=([\'\"])(.*?)\1/i;
10158 var typeRe = /\stype=([\'\"])(.*?)\1/i;
10161 while(match = re.exec(html)){
10162 var attrs = match[1];
10163 var srcMatch = attrs ? attrs.match(srcRe) : false;
10164 if(srcMatch && srcMatch[2]){
10165 var s = document.createElement("script");
10166 s.src = srcMatch[2];
10167 var typeMatch = attrs.match(typeRe);
10168 if(typeMatch && typeMatch[2]){
10169 s.type = typeMatch[2];
10172 }else if(match[2] && match[2].length > 0){
10173 if(window.execScript) {
10174 window.execScript(match[2]);
10182 window.eval(match[2]);
10186 var el = document.getElementById(id);
10187 if(el){el.parentNode.removeChild(el);}
10188 if(typeof callback == "function"){
10192 dom.innerHTML = html.replace(/(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig, "");
10197 * Direct access to the UpdateManager update() method (takes the same parameters).
10198 * @param {String/Function} url The url for this request or a function to call to get the url
10199 * @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}
10200 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
10201 * @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.
10202 * @return {Roo.Element} this
10205 var um = this.getUpdateManager();
10206 um.update.apply(um, arguments);
10211 * Gets this element's UpdateManager
10212 * @return {Roo.UpdateManager} The UpdateManager
10214 getUpdateManager : function(){
10215 if(!this.updateManager){
10216 this.updateManager = new Roo.UpdateManager(this);
10218 return this.updateManager;
10222 * Disables text selection for this element (normalized across browsers)
10223 * @return {Roo.Element} this
10225 unselectable : function(){
10226 this.dom.unselectable = "on";
10227 this.swallowEvent("selectstart", true);
10228 this.applyStyles("-moz-user-select:none;-khtml-user-select:none;");
10229 this.addClass("x-unselectable");
10234 * Calculates the x, y to center this element on the screen
10235 * @return {Array} The x, y values [x, y]
10237 getCenterXY : function(){
10238 return this.getAlignToXY(document, 'c-c');
10242 * Centers the Element in either the viewport, or another Element.
10243 * @param {String/HTMLElement/Roo.Element} centerIn (optional) The element in which to center the element.
10245 center : function(centerIn){
10246 this.alignTo(centerIn || document, 'c-c');
10251 * Tests various css rules/browsers to determine if this element uses a border box
10252 * @return {Boolean}
10254 isBorderBox : function(){
10255 return noBoxAdjust[this.dom.tagName.toLowerCase()] || Roo.isBorderBox;
10259 * Return a box {x, y, width, height} that can be used to set another elements
10260 * size/location to match this element.
10261 * @param {Boolean} contentBox (optional) If true a box for the content of the element is returned.
10262 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page x/y.
10263 * @return {Object} box An object in the format {x, y, width, height}
10265 getBox : function(contentBox, local){
10270 var left = parseInt(this.getStyle("left"), 10) || 0;
10271 var top = parseInt(this.getStyle("top"), 10) || 0;
10274 var el = this.dom, w = el.offsetWidth, h = el.offsetHeight, bx;
10276 bx = {x: xy[0], y: xy[1], 0: xy[0], 1: xy[1], width: w, height: h};
10278 var l = this.getBorderWidth("l")+this.getPadding("l");
10279 var r = this.getBorderWidth("r")+this.getPadding("r");
10280 var t = this.getBorderWidth("t")+this.getPadding("t");
10281 var b = this.getBorderWidth("b")+this.getPadding("b");
10282 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)};
10284 bx.right = bx.x + bx.width;
10285 bx.bottom = bx.y + bx.height;
10290 * Returns the sum width of the padding and borders for the passed "sides". See getBorderWidth()
10291 for more information about the sides.
10292 * @param {String} sides
10295 getFrameWidth : function(sides, onlyContentBox){
10296 return onlyContentBox && Roo.isBorderBox ? 0 : (this.getPadding(sides) + this.getBorderWidth(sides));
10300 * 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.
10301 * @param {Object} box The box to fill {x, y, width, height}
10302 * @param {Boolean} adjust (optional) Whether to adjust for box-model issues automatically
10303 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
10304 * @return {Roo.Element} this
10306 setBox : function(box, adjust, animate){
10307 var w = box.width, h = box.height;
10308 if((adjust && !this.autoBoxAdjust) && !this.isBorderBox()){
10309 w -= (this.getBorderWidth("lr") + this.getPadding("lr"));
10310 h -= (this.getBorderWidth("tb") + this.getPadding("tb"));
10312 this.setBounds(box.x, box.y, w, h, this.preanim(arguments, 2));
10317 * Forces the browser to repaint this element
10318 * @return {Roo.Element} this
10320 repaint : function(){
10321 var dom = this.dom;
10322 this.addClass("x-repaint");
10323 setTimeout(function(){
10324 Roo.get(dom).removeClass("x-repaint");
10330 * Returns an object with properties top, left, right and bottom representing the margins of this element unless sides is passed,
10331 * then it returns the calculated width of the sides (see getPadding)
10332 * @param {String} sides (optional) Any combination of l, r, t, b to get the sum of those sides
10333 * @return {Object/Number}
10335 getMargins : function(side){
10338 top: parseInt(this.getStyle("margin-top"), 10) || 0,
10339 left: parseInt(this.getStyle("margin-left"), 10) || 0,
10340 bottom: parseInt(this.getStyle("margin-bottom"), 10) || 0,
10341 right: parseInt(this.getStyle("margin-right"), 10) || 0
10344 return this.addStyles(side, El.margins);
10349 addStyles : function(sides, styles){
10351 for(var i = 0, len = sides.length; i < len; i++){
10352 v = this.getStyle(styles[sides.charAt(i)]);
10354 w = parseInt(v, 10);
10362 * Creates a proxy element of this element
10363 * @param {String/Object} config The class name of the proxy element or a DomHelper config object
10364 * @param {String/HTMLElement} renderTo (optional) The element or element id to render the proxy to (defaults to document.body)
10365 * @param {Boolean} matchBox (optional) True to align and size the proxy to this element now (defaults to false)
10366 * @return {Roo.Element} The new proxy element
10368 createProxy : function(config, renderTo, matchBox){
10370 renderTo = Roo.getDom(renderTo);
10372 renderTo = document.body;
10374 config = typeof config == "object" ?
10375 config : {tag : "div", cls: config};
10376 var proxy = Roo.DomHelper.append(renderTo, config, true);
10378 proxy.setBox(this.getBox());
10384 * Puts a mask over this element to disable user interaction. Requires core.css.
10385 * This method can only be applied to elements which accept child nodes.
10386 * @param {String} msg (optional) A message to display in the mask
10387 * @param {String} msgCls (optional) A css class to apply to the msg element - use no-spinner to hide the spinner on bootstrap
10388 * @return {Element} The mask element
10390 mask : function(msg, msgCls)
10392 if(this.getStyle("position") == "static" && this.dom.tagName !== 'BODY'){
10393 this.setStyle("position", "relative");
10396 this._mask = Roo.DomHelper.append(this.dom, {cls:"roo-el-mask"}, true);
10399 this.addClass("x-masked");
10400 this._mask.setDisplayed(true);
10404 var dom = this.dom;
10405 while (dom && dom.style) {
10406 if (!isNaN(parseInt(dom.style.zIndex))) {
10407 z = Math.max(z, parseInt(dom.style.zIndex));
10409 dom = dom.parentNode;
10411 // if we are masking the body - then it hides everything..
10412 if (this.dom == document.body) {
10414 this._mask.setWidth(Roo.lib.Dom.getDocumentWidth());
10415 this._mask.setHeight(Roo.lib.Dom.getDocumentHeight());
10418 if(typeof msg == 'string'){
10419 if(!this._maskMsg){
10420 this._maskMsg = Roo.DomHelper.append(this.dom, {
10421 cls: "roo-el-mask-msg",
10425 cls: 'fa fa-spinner fa-spin'
10433 var mm = this._maskMsg;
10434 mm.dom.className = msgCls ? "roo-el-mask-msg " + msgCls : "roo-el-mask-msg";
10435 if (mm.dom.lastChild) { // weird IE issue?
10436 mm.dom.lastChild.innerHTML = msg;
10438 mm.setDisplayed(true);
10440 mm.setStyle('z-index', z + 102);
10442 if(Roo.isIE && !(Roo.isIE7 && Roo.isStrict) && this.getStyle('height') == 'auto'){ // ie will not expand full height automatically
10443 this._mask.setHeight(this.getHeight());
10445 this._mask.setStyle('z-index', z + 100);
10451 * Removes a previously applied mask. If removeEl is true the mask overlay is destroyed, otherwise
10452 * it is cached for reuse.
10454 unmask : function(removeEl){
10456 if(removeEl === true){
10457 this._mask.remove();
10460 this._maskMsg.remove();
10461 delete this._maskMsg;
10464 this._mask.setDisplayed(false);
10466 this._maskMsg.setDisplayed(false);
10470 this.removeClass("x-masked");
10474 * Returns true if this element is masked
10475 * @return {Boolean}
10477 isMasked : function(){
10478 return this._mask && this._mask.isVisible();
10482 * Creates an iframe shim for this element to keep selects and other windowed objects from
10484 * @return {Roo.Element} The new shim element
10486 createShim : function(){
10487 var el = document.createElement('iframe');
10488 el.frameBorder = 'no';
10489 el.className = 'roo-shim';
10490 if(Roo.isIE && Roo.isSecure){
10491 el.src = Roo.SSL_SECURE_URL;
10493 var shim = Roo.get(this.dom.parentNode.insertBefore(el, this.dom));
10494 shim.autoBoxAdjust = false;
10499 * Removes this element from the DOM and deletes it from the cache
10501 remove : function(){
10502 if(this.dom.parentNode){
10503 this.dom.parentNode.removeChild(this.dom);
10505 delete El.cache[this.dom.id];
10509 * Sets up event handlers to add and remove a css class when the mouse is over this element
10510 * @param {String} className
10511 * @param {Boolean} preventFlicker (optional) If set to true, it prevents flickering by filtering
10512 * mouseout events for children elements
10513 * @return {Roo.Element} this
10515 addClassOnOver : function(className, preventFlicker){
10516 this.on("mouseover", function(){
10517 Roo.fly(this, '_internal').addClass(className);
10519 var removeFn = function(e){
10520 if(preventFlicker !== true || !e.within(this, true)){
10521 Roo.fly(this, '_internal').removeClass(className);
10524 this.on("mouseout", removeFn, this.dom);
10529 * Sets up event handlers to add and remove a css class when this element has the focus
10530 * @param {String} className
10531 * @return {Roo.Element} this
10533 addClassOnFocus : function(className){
10534 this.on("focus", function(){
10535 Roo.fly(this, '_internal').addClass(className);
10537 this.on("blur", function(){
10538 Roo.fly(this, '_internal').removeClass(className);
10543 * 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)
10544 * @param {String} className
10545 * @return {Roo.Element} this
10547 addClassOnClick : function(className){
10548 var dom = this.dom;
10549 this.on("mousedown", function(){
10550 Roo.fly(dom, '_internal').addClass(className);
10551 var d = Roo.get(document);
10552 var fn = function(){
10553 Roo.fly(dom, '_internal').removeClass(className);
10554 d.removeListener("mouseup", fn);
10556 d.on("mouseup", fn);
10562 * Stops the specified event from bubbling and optionally prevents the default action
10563 * @param {String} eventName
10564 * @param {Boolean} preventDefault (optional) true to prevent the default action too
10565 * @return {Roo.Element} this
10567 swallowEvent : function(eventName, preventDefault){
10568 var fn = function(e){
10569 e.stopPropagation();
10570 if(preventDefault){
10571 e.preventDefault();
10574 if(eventName instanceof Array){
10575 for(var i = 0, len = eventName.length; i < len; i++){
10576 this.on(eventName[i], fn);
10580 this.on(eventName, fn);
10587 fitToParentDelegate : Roo.emptyFn, // keep a reference to the fitToParent delegate
10590 * Sizes this element to its parent element's dimensions performing
10591 * neccessary box adjustments.
10592 * @param {Boolean} monitorResize (optional) If true maintains the fit when the browser window is resized.
10593 * @param {String/HTMLElment/Element} targetParent (optional) The target parent, default to the parentNode.
10594 * @return {Roo.Element} this
10596 fitToParent : function(monitorResize, targetParent) {
10597 Roo.EventManager.removeResizeListener(this.fitToParentDelegate); // always remove previous fitToParent delegate from onWindowResize
10598 this.fitToParentDelegate = Roo.emptyFn; // remove reference to previous delegate
10599 if (monitorResize === true && !this.dom.parentNode) { // check if this Element still exists
10602 var p = Roo.get(targetParent || this.dom.parentNode);
10603 this.setSize(p.getComputedWidth() - p.getFrameWidth('lr'), p.getComputedHeight() - p.getFrameWidth('tb'));
10604 if (monitorResize === true) {
10605 this.fitToParentDelegate = this.fitToParent.createDelegate(this, [true, targetParent]);
10606 Roo.EventManager.onWindowResize(this.fitToParentDelegate);
10612 * Gets the next sibling, skipping text nodes
10613 * @return {HTMLElement} The next sibling or null
10615 getNextSibling : function(){
10616 var n = this.dom.nextSibling;
10617 while(n && n.nodeType != 1){
10624 * Gets the previous sibling, skipping text nodes
10625 * @return {HTMLElement} The previous sibling or null
10627 getPrevSibling : function(){
10628 var n = this.dom.previousSibling;
10629 while(n && n.nodeType != 1){
10630 n = n.previousSibling;
10637 * Appends the passed element(s) to this element
10638 * @param {String/HTMLElement/Array/Element/CompositeElement} el
10639 * @return {Roo.Element} this
10641 appendChild: function(el){
10648 * Creates the passed DomHelper config and appends it to this element or optionally inserts it before the passed child element.
10649 * @param {Object} config DomHelper element config object. If no tag is specified (e.g., {tag:'input'}) then a div will be
10650 * automatically generated with the specified attributes.
10651 * @param {HTMLElement} insertBefore (optional) a child element of this element
10652 * @param {Boolean} returnDom (optional) true to return the dom node instead of creating an Element
10653 * @return {Roo.Element} The new child element
10655 createChild: function(config, insertBefore, returnDom){
10656 config = config || {tag:'div'};
10658 return Roo.DomHelper.insertBefore(insertBefore, config, returnDom !== true);
10660 return Roo.DomHelper[!this.dom.firstChild ? 'overwrite' : 'append'](this.dom, config, returnDom !== true);
10664 * Appends this element to the passed element
10665 * @param {String/HTMLElement/Element} el The new parent element
10666 * @return {Roo.Element} this
10668 appendTo: function(el){
10669 el = Roo.getDom(el);
10670 el.appendChild(this.dom);
10675 * Inserts this element before the passed element in the DOM
10676 * @param {String/HTMLElement/Element} el The element to insert before
10677 * @return {Roo.Element} this
10679 insertBefore: function(el){
10680 el = Roo.getDom(el);
10681 el.parentNode.insertBefore(this.dom, el);
10686 * Inserts this element after the passed element in the DOM
10687 * @param {String/HTMLElement/Element} el The element to insert after
10688 * @return {Roo.Element} this
10690 insertAfter: function(el){
10691 el = Roo.getDom(el);
10692 el.parentNode.insertBefore(this.dom, el.nextSibling);
10697 * Inserts (or creates) an element (or DomHelper config) as the first child of the this element
10698 * @param {String/HTMLElement/Element/Object} el The id or element to insert or a DomHelper config to create and insert
10699 * @return {Roo.Element} The new child
10701 insertFirst: function(el, returnDom){
10703 if(typeof el == 'object' && !el.nodeType){ // dh config
10704 return this.createChild(el, this.dom.firstChild, returnDom);
10706 el = Roo.getDom(el);
10707 this.dom.insertBefore(el, this.dom.firstChild);
10708 return !returnDom ? Roo.get(el) : el;
10713 * Inserts (or creates) the passed element (or DomHelper config) as a sibling of this element
10714 * @param {String/HTMLElement/Element/Object} el The id or element to insert or a DomHelper config to create and insert
10715 * @param {String} where (optional) 'before' or 'after' defaults to before
10716 * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Roo.Element
10717 * @return {Roo.Element} the inserted Element
10719 insertSibling: function(el, where, returnDom){
10720 where = where ? where.toLowerCase() : 'before';
10722 var rt, refNode = where == 'before' ? this.dom : this.dom.nextSibling;
10724 if(typeof el == 'object' && !el.nodeType){ // dh config
10725 if(where == 'after' && !this.dom.nextSibling){
10726 rt = Roo.DomHelper.append(this.dom.parentNode, el, !returnDom);
10728 rt = Roo.DomHelper[where == 'after' ? 'insertAfter' : 'insertBefore'](this.dom, el, !returnDom);
10732 rt = this.dom.parentNode.insertBefore(Roo.getDom(el),
10733 where == 'before' ? this.dom : this.dom.nextSibling);
10742 * Creates and wraps this element with another element
10743 * @param {Object} config (optional) DomHelper element config object for the wrapper element or null for an empty div
10744 * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Roo.Element
10745 * @return {HTMLElement/Element} The newly created wrapper element
10747 wrap: function(config, returnDom){
10749 config = {tag: "div"};
10751 var newEl = Roo.DomHelper.insertBefore(this.dom, config, !returnDom);
10752 newEl.dom ? newEl.dom.appendChild(this.dom) : newEl.appendChild(this.dom);
10757 * Replaces the passed element with this element
10758 * @param {String/HTMLElement/Element} el The element to replace
10759 * @return {Roo.Element} this
10761 replace: function(el){
10763 this.insertBefore(el);
10769 * Inserts an html fragment into this element
10770 * @param {String} where Where to insert the html in relation to the this element - beforeBegin, afterBegin, beforeEnd, afterEnd.
10771 * @param {String} html The HTML fragment
10772 * @param {Boolean} returnEl True to return an Roo.Element
10773 * @return {HTMLElement/Roo.Element} The inserted node (or nearest related if more than 1 inserted)
10775 insertHtml : function(where, html, returnEl){
10776 var el = Roo.DomHelper.insertHtml(where, this.dom, html);
10777 return returnEl ? Roo.get(el) : el;
10781 * Sets the passed attributes as attributes of this element (a style attribute can be a string, object or function)
10782 * @param {Object} o The object with the attributes
10783 * @param {Boolean} useSet (optional) false to override the default setAttribute to use expandos.
10784 * @return {Roo.Element} this
10786 set : function(o, useSet){
10788 useSet = typeof useSet == 'undefined' ? (el.setAttribute ? true : false) : useSet;
10789 for(var attr in o){
10790 if(attr == "style" || typeof o[attr] == "function") { continue; }
10792 el.className = o["cls"];
10795 el.setAttribute(attr, o[attr]);
10797 el[attr] = o[attr];
10802 Roo.DomHelper.applyStyles(el, o.style);
10808 * Convenience method for constructing a KeyMap
10809 * @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:
10810 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
10811 * @param {Function} fn The function to call
10812 * @param {Object} scope (optional) The scope of the function
10813 * @return {Roo.KeyMap} The KeyMap created
10815 addKeyListener : function(key, fn, scope){
10817 if(typeof key != "object" || key instanceof Array){
10833 return new Roo.KeyMap(this, config);
10837 * Creates a KeyMap for this element
10838 * @param {Object} config The KeyMap config. See {@link Roo.KeyMap} for more details
10839 * @return {Roo.KeyMap} The KeyMap created
10841 addKeyMap : function(config){
10842 return new Roo.KeyMap(this, config);
10846 * Returns true if this element is scrollable.
10847 * @return {Boolean}
10849 isScrollable : function(){
10850 var dom = this.dom;
10851 return dom.scrollHeight > dom.clientHeight || dom.scrollWidth > dom.clientWidth;
10855 * 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().
10856 * @param {String} side Either "left" for scrollLeft values or "top" for scrollTop values.
10857 * @param {Number} value The new scroll value
10858 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
10859 * @return {Element} this
10862 scrollTo : function(side, value, animate){
10863 var prop = side.toLowerCase() == "left" ? "scrollLeft" : "scrollTop";
10864 if(!animate || !A){
10865 this.dom[prop] = value;
10867 var to = prop == "scrollLeft" ? [value, this.dom.scrollTop] : [this.dom.scrollLeft, value];
10868 this.anim({scroll: {"to": to}}, this.preanim(arguments, 2), 'scroll');
10874 * Scrolls this element the specified direction. Does bounds checking to make sure the scroll is
10875 * within this element's scrollable range.
10876 * @param {String} direction Possible values are: "l","left" - "r","right" - "t","top","up" - "b","bottom","down".
10877 * @param {Number} distance How far to scroll the element in pixels
10878 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
10879 * @return {Boolean} Returns true if a scroll was triggered or false if the element
10880 * was scrolled as far as it could go.
10882 scroll : function(direction, distance, animate){
10883 if(!this.isScrollable()){
10887 var l = el.scrollLeft, t = el.scrollTop;
10888 var w = el.scrollWidth, h = el.scrollHeight;
10889 var cw = el.clientWidth, ch = el.clientHeight;
10890 direction = direction.toLowerCase();
10891 var scrolled = false;
10892 var a = this.preanim(arguments, 2);
10897 var v = Math.min(l + distance, w-cw);
10898 this.scrollTo("left", v, a);
10905 var v = Math.max(l - distance, 0);
10906 this.scrollTo("left", v, a);
10914 var v = Math.max(t - distance, 0);
10915 this.scrollTo("top", v, a);
10923 var v = Math.min(t + distance, h-ch);
10924 this.scrollTo("top", v, a);
10933 * Translates the passed page coordinates into left/top css values for this element
10934 * @param {Number/Array} x The page x or an array containing [x, y]
10935 * @param {Number} y The page y
10936 * @return {Object} An object with left and top properties. e.g. {left: (value), top: (value)}
10938 translatePoints : function(x, y){
10939 if(typeof x == 'object' || x instanceof Array){
10940 y = x[1]; x = x[0];
10942 var p = this.getStyle('position');
10943 var o = this.getXY();
10945 var l = parseInt(this.getStyle('left'), 10);
10946 var t = parseInt(this.getStyle('top'), 10);
10949 l = (p == "relative") ? 0 : this.dom.offsetLeft;
10952 t = (p == "relative") ? 0 : this.dom.offsetTop;
10955 return {left: (x - o[0] + l), top: (y - o[1] + t)};
10959 * Returns the current scroll position of the element.
10960 * @return {Object} An object containing the scroll position in the format {left: (scrollLeft), top: (scrollTop)}
10962 getScroll : function(){
10963 var d = this.dom, doc = document;
10964 if(d == doc || d == doc.body){
10965 var l = window.pageXOffset || doc.documentElement.scrollLeft || doc.body.scrollLeft || 0;
10966 var t = window.pageYOffset || doc.documentElement.scrollTop || doc.body.scrollTop || 0;
10967 return {left: l, top: t};
10969 return {left: d.scrollLeft, top: d.scrollTop};
10974 * Return the CSS color for the specified CSS attribute. rgb, 3 digit (like #fff) and valid values
10975 * are convert to standard 6 digit hex color.
10976 * @param {String} attr The css attribute
10977 * @param {String} defaultValue The default value to use when a valid color isn't found
10978 * @param {String} prefix (optional) defaults to #. Use an empty string when working with
10981 getColor : function(attr, defaultValue, prefix){
10982 var v = this.getStyle(attr);
10983 if(!v || v == "transparent" || v == "inherit") {
10984 return defaultValue;
10986 var color = typeof prefix == "undefined" ? "#" : prefix;
10987 if(v.substr(0, 4) == "rgb("){
10988 var rvs = v.slice(4, v.length -1).split(",");
10989 for(var i = 0; i < 3; i++){
10990 var h = parseInt(rvs[i]).toString(16);
10997 if(v.substr(0, 1) == "#"){
10998 if(v.length == 4) {
10999 for(var i = 1; i < 4; i++){
11000 var c = v.charAt(i);
11003 }else if(v.length == 7){
11004 color += v.substr(1);
11008 return(color.length > 5 ? color.toLowerCase() : defaultValue);
11012 * Wraps the specified element with a special markup/CSS block that renders by default as a gray container with a
11013 * gradient background, rounded corners and a 4-way shadow.
11014 * @param {String} class (optional) A base CSS class to apply to the containing wrapper element (defaults to 'x-box').
11015 * Note that there are a number of CSS rules that are dependent on this name to make the overall effect work,
11016 * so if you supply an alternate base class, make sure you also supply all of the necessary rules.
11017 * @return {Roo.Element} this
11019 boxWrap : function(cls){
11020 cls = cls || 'x-box';
11021 var el = Roo.get(this.insertHtml('beforeBegin', String.format('<div class="{0}">'+El.boxMarkup+'</div>', cls)));
11022 el.child('.'+cls+'-mc').dom.appendChild(this.dom);
11027 * Returns the value of a namespaced attribute from the element's underlying DOM node.
11028 * @param {String} namespace The namespace in which to look for the attribute
11029 * @param {String} name The attribute name
11030 * @return {String} The attribute value
11032 getAttributeNS : Roo.isIE ? function(ns, name){
11034 var type = typeof d[ns+":"+name];
11035 if(type != 'undefined' && type != 'unknown'){
11036 return d[ns+":"+name];
11039 } : function(ns, name){
11041 return d.getAttributeNS(ns, name) || d.getAttribute(ns+":"+name) || d.getAttribute(name) || d[name];
11046 * Sets or Returns the value the dom attribute value
11047 * @param {String|Object} name The attribute name (or object to set multiple attributes)
11048 * @param {String} value (optional) The value to set the attribute to
11049 * @return {String} The attribute value
11051 attr : function(name){
11052 if (arguments.length > 1) {
11053 this.dom.setAttribute(name, arguments[1]);
11054 return arguments[1];
11056 if (typeof(name) == 'object') {
11057 for(var i in name) {
11058 this.attr(i, name[i]);
11064 if (!this.dom.hasAttribute(name)) {
11067 return this.dom.getAttribute(name);
11074 var ep = El.prototype;
11077 * Appends an event handler (Shorthand for addListener)
11078 * @param {String} eventName The type of event to append
11079 * @param {Function} fn The method the event invokes
11080 * @param {Object} scope (optional) The scope (this object) of the fn
11081 * @param {Object} options (optional)An object with standard {@link Roo.EventManager#addListener} options
11084 ep.on = ep.addListener;
11085 // backwards compat
11086 ep.mon = ep.addListener;
11089 * Removes an event handler from this element (shorthand for removeListener)
11090 * @param {String} eventName the type of event to remove
11091 * @param {Function} fn the method the event invokes
11092 * @return {Roo.Element} this
11095 ep.un = ep.removeListener;
11098 * true to automatically adjust width and height settings for box-model issues (default to true)
11100 ep.autoBoxAdjust = true;
11103 El.unitPattern = /\d+(px|em|%|en|ex|pt|in|cm|mm|pc)$/i;
11106 El.addUnits = function(v, defaultUnit){
11107 if(v === "" || v == "auto"){
11110 if(v === undefined){
11113 if(typeof v == "number" || !El.unitPattern.test(v)){
11114 return v + (defaultUnit || 'px');
11119 // special markup used throughout Roo when box wrapping elements
11120 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>';
11122 * Visibility mode constant - Use visibility to hide element
11128 * Visibility mode constant - Use display to hide element
11134 El.borders = {l: "border-left-width", r: "border-right-width", t: "border-top-width", b: "border-bottom-width"};
11135 El.paddings = {l: "padding-left", r: "padding-right", t: "padding-top", b: "padding-bottom"};
11136 El.margins = {l: "margin-left", r: "margin-right", t: "margin-top", b: "margin-bottom"};
11148 * Static method to retrieve Element objects. Uses simple caching to consistently return the same object.
11149 * Automatically fixes if an object was recreated with the same id via AJAX or DOM.
11150 * @param {String/HTMLElement/Element} el The id of the node, a DOM Node or an existing Element.
11151 * @return {Element} The Element object
11154 El.get = function(el){
11156 if(!el){ return null; }
11157 if(typeof el == "string"){ // element id
11158 if(!(elm = document.getElementById(el))){
11161 if(ex = El.cache[el]){
11164 ex = El.cache[el] = new El(elm);
11167 }else if(el.tagName){ // dom element
11171 if(ex = El.cache[id]){
11174 ex = El.cache[id] = new El(el);
11177 }else if(el instanceof El){
11179 el.dom = document.getElementById(el.id) || el.dom; // refresh dom element in case no longer valid,
11180 // catch case where it hasn't been appended
11181 El.cache[el.id] = el; // in case it was created directly with Element(), let's cache it
11184 }else if(el.isComposite){
11186 }else if(el instanceof Array){
11187 return El.select(el);
11188 }else if(el == document){
11189 // create a bogus element object representing the document object
11191 var f = function(){};
11192 f.prototype = El.prototype;
11194 docEl.dom = document;
11202 El.uncache = function(el){
11203 for(var i = 0, a = arguments, len = a.length; i < len; i++) {
11205 delete El.cache[a[i].id || a[i]];
11211 // Garbage collection - uncache elements/purge listeners on orphaned elements
11212 // so we don't hold a reference and cause the browser to retain them
11213 El.garbageCollect = function(){
11214 if(!Roo.enableGarbageCollector){
11215 clearInterval(El.collectorThread);
11218 for(var eid in El.cache){
11219 var el = El.cache[eid], d = el.dom;
11220 // -------------------------------------------------------
11221 // Determining what is garbage:
11222 // -------------------------------------------------------
11224 // dom node is null, definitely garbage
11225 // -------------------------------------------------------
11227 // no parentNode == direct orphan, definitely garbage
11228 // -------------------------------------------------------
11229 // !d.offsetParent && !document.getElementById(eid)
11230 // display none elements have no offsetParent so we will
11231 // also try to look it up by it's id. However, check
11232 // offsetParent first so we don't do unneeded lookups.
11233 // This enables collection of elements that are not orphans
11234 // directly, but somewhere up the line they have an orphan
11236 // -------------------------------------------------------
11237 if(!d || !d.parentNode || (!d.offsetParent && !document.getElementById(eid))){
11238 delete El.cache[eid];
11239 if(d && Roo.enableListenerCollection){
11245 El.collectorThreadId = setInterval(El.garbageCollect, 30000);
11249 El.Flyweight = function(dom){
11252 El.Flyweight.prototype = El.prototype;
11254 El._flyweights = {};
11256 * Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
11257 * the dom node can be overwritten by other code.
11258 * @param {String/HTMLElement} el The dom node or id
11259 * @param {String} named (optional) Allows for creation of named reusable flyweights to
11260 * prevent conflicts (e.g. internally Roo uses "_internal")
11262 * @return {Element} The shared Element object
11264 El.fly = function(el, named){
11265 named = named || '_global';
11266 el = Roo.getDom(el);
11270 if(!El._flyweights[named]){
11271 El._flyweights[named] = new El.Flyweight();
11273 El._flyweights[named].dom = el;
11274 return El._flyweights[named];
11278 * Static method to retrieve Element objects. Uses simple caching to consistently return the same object.
11279 * Automatically fixes if an object was recreated with the same id via AJAX or DOM.
11280 * Shorthand of {@link Roo.Element#get}
11281 * @param {String/HTMLElement/Element} el The id of the node, a DOM Node or an existing Element.
11282 * @return {Element} The Element object
11288 * Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
11289 * the dom node can be overwritten by other code.
11290 * Shorthand of {@link Roo.Element#fly}
11291 * @param {String/HTMLElement} el The dom node or id
11292 * @param {String} named (optional) Allows for creation of named reusable flyweights to
11293 * prevent conflicts (e.g. internally Roo uses "_internal")
11295 * @return {Element} The shared Element object
11301 // speedy lookup for elements never to box adjust
11302 var noBoxAdjust = Roo.isStrict ? {
11305 input:1, select:1, textarea:1
11307 if(Roo.isIE || Roo.isGecko){
11308 noBoxAdjust['button'] = 1;
11312 Roo.EventManager.on(window, 'unload', function(){
11314 delete El._flyweights;
11322 Roo.Element.selectorFunction = Roo.DomQuery.select;
11325 Roo.Element.select = function(selector, unique, root){
11327 if(typeof selector == "string"){
11328 els = Roo.Element.selectorFunction(selector, root);
11329 }else if(selector.length !== undefined){
11332 throw "Invalid selector";
11334 if(unique === true){
11335 return new Roo.CompositeElement(els);
11337 return new Roo.CompositeElementLite(els);
11341 * Selects elements based on the passed CSS selector to enable working on them as 1.
11342 * @param {String/Array} selector The CSS selector or an array of elements
11343 * @param {Boolean} unique (optional) true to create a unique Roo.Element for each element (defaults to a shared flyweight object)
11344 * @param {HTMLElement/String} root (optional) The root element of the query or id of the root
11345 * @return {CompositeElementLite/CompositeElement}
11349 Roo.select = Roo.Element.select;
11366 * Ext JS Library 1.1.1
11367 * Copyright(c) 2006-2007, Ext JS, LLC.
11369 * Originally Released Under LGPL - original licence link has changed is not relivant.
11372 * <script type="text/javascript">
11377 //Notifies Element that fx methods are available
11378 Roo.enableFx = true;
11382 * <p>A class to provide basic animation and visual effects support. <b>Note:</b> This class is automatically applied
11383 * to the {@link Roo.Element} interface when included, so all effects calls should be performed via Element.
11384 * Conversely, since the effects are not actually defined in Element, Roo.Fx <b>must</b> be included in order for the
11385 * Element effects to work.</p><br/>
11387 * <p>It is important to note that although the Fx methods and many non-Fx Element methods support "method chaining" in that
11388 * they return the Element object itself as the method return value, it is not always possible to mix the two in a single
11389 * method chain. The Fx methods use an internal effects queue so that each effect can be properly timed and sequenced.
11390 * Non-Fx methods, on the other hand, have no such internal queueing and will always execute immediately. For this reason,
11391 * while it may be possible to mix certain Fx and non-Fx method calls in a single chain, it may not always provide the
11392 * expected results and should be done with care.</p><br/>
11394 * <p>Motion effects support 8-way anchoring, meaning that you can choose one of 8 different anchor points on the Element
11395 * that will serve as either the start or end point of the animation. Following are all of the supported anchor positions:</p>
11398 ----- -----------------------------
11399 tl The top left corner
11400 t The center of the top edge
11401 tr The top right corner
11402 l The center of the left edge
11403 r The center of the right edge
11404 bl The bottom left corner
11405 b The center of the bottom edge
11406 br The bottom right corner
11408 * <b>Although some Fx methods accept specific custom config parameters, the ones shown in the Config Options section
11409 * below are common options that can be passed to any Fx method.</b>
11410 * @cfg {Function} callback A function called when the effect is finished
11411 * @cfg {Object} scope The scope of the effect function
11412 * @cfg {String} easing A valid Easing value for the effect
11413 * @cfg {String} afterCls A css class to apply after the effect
11414 * @cfg {Number} duration The length of time (in seconds) that the effect should last
11415 * @cfg {Boolean} remove Whether the Element should be removed from the DOM and destroyed after the effect finishes
11416 * @cfg {Boolean} useDisplay Whether to use the <i>display</i> CSS property instead of <i>visibility</i> when hiding Elements (only applies to
11417 * effects that end with the element being visually hidden, ignored otherwise)
11418 * @cfg {String/Object/Function} afterStyle A style specification string, e.g. "width:100px", or an object in the form {width:"100px"}, or
11419 * a function which returns such a specification that will be applied to the Element after the effect finishes
11420 * @cfg {Boolean} block Whether the effect should block other effects from queueing while it runs
11421 * @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
11422 * @cfg {Boolean} stopFx Whether subsequent effects should be stopped and removed after the current effect finishes
11426 * Slides the element into view. An anchor point can be optionally passed to set the point of
11427 * origin for the slide effect. This function automatically handles wrapping the element with
11428 * a fixed-size container if needed. See the Fx class overview for valid anchor point options.
11431 // default: slide the element in from the top
11434 // custom: slide the element in from the right with a 2-second duration
11435 el.slideIn('r', { duration: 2 });
11437 // common config options shown with default values
11443 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to top: 't')
11444 * @param {Object} options (optional) Object literal with any of the Fx config options
11445 * @return {Roo.Element} The Element
11447 slideIn : function(anchor, o){
11448 var el = this.getFxEl();
11451 el.queueFx(o, function(){
11453 anchor = anchor || "t";
11455 // fix display to visibility
11458 // restore values after effect
11459 var r = this.getFxRestore();
11460 var b = this.getBox();
11461 // fixed size for slide
11465 var wrap = this.fxWrap(r.pos, o, "hidden");
11467 var st = this.dom.style;
11468 st.visibility = "visible";
11469 st.position = "absolute";
11471 // clear out temp styles after slide and unwrap
11472 var after = function(){
11473 el.fxUnwrap(wrap, r.pos, o);
11474 st.width = r.width;
11475 st.height = r.height;
11478 // time to calc the positions
11479 var a, pt = {to: [b.x, b.y]}, bw = {to: b.width}, bh = {to: b.height};
11481 switch(anchor.toLowerCase()){
11483 wrap.setSize(b.width, 0);
11484 st.left = st.bottom = "0";
11488 wrap.setSize(0, b.height);
11489 st.right = st.top = "0";
11493 wrap.setSize(0, b.height);
11494 wrap.setX(b.right);
11495 st.left = st.top = "0";
11496 a = {width: bw, points: pt};
11499 wrap.setSize(b.width, 0);
11500 wrap.setY(b.bottom);
11501 st.left = st.top = "0";
11502 a = {height: bh, points: pt};
11505 wrap.setSize(0, 0);
11506 st.right = st.bottom = "0";
11507 a = {width: bw, height: bh};
11510 wrap.setSize(0, 0);
11511 wrap.setY(b.y+b.height);
11512 st.right = st.top = "0";
11513 a = {width: bw, height: bh, points: pt};
11516 wrap.setSize(0, 0);
11517 wrap.setXY([b.right, b.bottom]);
11518 st.left = st.top = "0";
11519 a = {width: bw, height: bh, points: pt};
11522 wrap.setSize(0, 0);
11523 wrap.setX(b.x+b.width);
11524 st.left = st.bottom = "0";
11525 a = {width: bw, height: bh, points: pt};
11528 this.dom.style.visibility = "visible";
11531 arguments.callee.anim = wrap.fxanim(a,
11541 * Slides the element out of view. An anchor point can be optionally passed to set the end point
11542 * for the slide effect. When the effect is completed, the element will be hidden (visibility =
11543 * 'hidden') but block elements will still take up space in the document. The element must be removed
11544 * from the DOM using the 'remove' config option if desired. This function automatically handles
11545 * wrapping the element with a fixed-size container if needed. See the Fx class overview for valid anchor point options.
11548 // default: slide the element out to the top
11551 // custom: slide the element out to the right with a 2-second duration
11552 el.slideOut('r', { duration: 2 });
11554 // common config options shown with default values
11562 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to top: 't')
11563 * @param {Object} options (optional) Object literal with any of the Fx config options
11564 * @return {Roo.Element} The Element
11566 slideOut : function(anchor, o){
11567 var el = this.getFxEl();
11570 el.queueFx(o, function(){
11572 anchor = anchor || "t";
11574 // restore values after effect
11575 var r = this.getFxRestore();
11577 var b = this.getBox();
11578 // fixed size for slide
11582 var wrap = this.fxWrap(r.pos, o, "visible");
11584 var st = this.dom.style;
11585 st.visibility = "visible";
11586 st.position = "absolute";
11590 var after = function(){
11592 el.setDisplayed(false);
11597 el.fxUnwrap(wrap, r.pos, o);
11599 st.width = r.width;
11600 st.height = r.height;
11605 var a, zero = {to: 0};
11606 switch(anchor.toLowerCase()){
11608 st.left = st.bottom = "0";
11609 a = {height: zero};
11612 st.right = st.top = "0";
11616 st.left = st.top = "0";
11617 a = {width: zero, points: {to:[b.right, b.y]}};
11620 st.left = st.top = "0";
11621 a = {height: zero, points: {to:[b.x, b.bottom]}};
11624 st.right = st.bottom = "0";
11625 a = {width: zero, height: zero};
11628 st.right = st.top = "0";
11629 a = {width: zero, height: zero, points: {to:[b.x, b.bottom]}};
11632 st.left = st.top = "0";
11633 a = {width: zero, height: zero, points: {to:[b.x+b.width, b.bottom]}};
11636 st.left = st.bottom = "0";
11637 a = {width: zero, height: zero, points: {to:[b.right, b.y]}};
11641 arguments.callee.anim = wrap.fxanim(a,
11651 * Fades the element out while slowly expanding it in all directions. When the effect is completed, the
11652 * element will be hidden (visibility = 'hidden') but block elements will still take up space in the document.
11653 * The element must be removed from the DOM using the 'remove' config option if desired.
11659 // common config options shown with default values
11667 * @param {Object} options (optional) Object literal with any of the Fx config options
11668 * @return {Roo.Element} The Element
11670 puff : function(o){
11671 var el = this.getFxEl();
11674 el.queueFx(o, function(){
11675 this.clearOpacity();
11678 // restore values after effect
11679 var r = this.getFxRestore();
11680 var st = this.dom.style;
11682 var after = function(){
11684 el.setDisplayed(false);
11691 el.setPositioning(r.pos);
11692 st.width = r.width;
11693 st.height = r.height;
11698 var width = this.getWidth();
11699 var height = this.getHeight();
11701 arguments.callee.anim = this.fxanim({
11702 width : {to: this.adjustWidth(width * 2)},
11703 height : {to: this.adjustHeight(height * 2)},
11704 points : {by: [-(width * .5), -(height * .5)]},
11706 fontSize: {to:200, unit: "%"}
11717 * Blinks the element as if it was clicked and then collapses on its center (similar to switching off a television).
11718 * When the effect is completed, the element will be hidden (visibility = 'hidden') but block elements will still
11719 * take up space in the document. The element must be removed from the DOM using the 'remove' config option if desired.
11725 // all config options shown with default values
11733 * @param {Object} options (optional) Object literal with any of the Fx config options
11734 * @return {Roo.Element} The Element
11736 switchOff : function(o){
11737 var el = this.getFxEl();
11740 el.queueFx(o, function(){
11741 this.clearOpacity();
11744 // restore values after effect
11745 var r = this.getFxRestore();
11746 var st = this.dom.style;
11748 var after = function(){
11750 el.setDisplayed(false);
11756 el.setPositioning(r.pos);
11757 st.width = r.width;
11758 st.height = r.height;
11763 this.fxanim({opacity:{to:0.3}}, null, null, .1, null, function(){
11764 this.clearOpacity();
11768 points:{by:[0, this.getHeight() * .5]}
11769 }, o, 'motion', 0.3, 'easeIn', after);
11770 }).defer(100, this);
11777 * Highlights the Element by setting a color (applies to the background-color by default, but can be
11778 * changed using the "attr" config option) and then fading back to the original color. If no original
11779 * color is available, you should provide the "endColor" config option which will be cleared after the animation.
11782 // default: highlight background to yellow
11785 // custom: highlight foreground text to blue for 2 seconds
11786 el.highlight("0000ff", { attr: 'color', duration: 2 });
11788 // common config options shown with default values
11789 el.highlight("ffff9c", {
11790 attr: "background-color", //can be any valid CSS property (attribute) that supports a color value
11791 endColor: (current color) or "ffffff",
11796 * @param {String} color (optional) The highlight color. Should be a 6 char hex color without the leading # (defaults to yellow: 'ffff9c')
11797 * @param {Object} options (optional) Object literal with any of the Fx config options
11798 * @return {Roo.Element} The Element
11800 highlight : function(color, o){
11801 var el = this.getFxEl();
11804 el.queueFx(o, function(){
11805 color = color || "ffff9c";
11806 attr = o.attr || "backgroundColor";
11808 this.clearOpacity();
11811 var origColor = this.getColor(attr);
11812 var restoreColor = this.dom.style[attr];
11813 endColor = (o.endColor || origColor) || "ffffff";
11815 var after = function(){
11816 el.dom.style[attr] = restoreColor;
11821 a[attr] = {from: color, to: endColor};
11822 arguments.callee.anim = this.fxanim(a,
11832 * Shows a ripple of exploding, attenuating borders to draw attention to an Element.
11835 // default: a single light blue ripple
11838 // custom: 3 red ripples lasting 3 seconds total
11839 el.frame("ff0000", 3, { duration: 3 });
11841 // common config options shown with default values
11842 el.frame("C3DAF9", 1, {
11843 duration: 1 //duration of entire animation (not each individual ripple)
11844 // Note: Easing is not configurable and will be ignored if included
11847 * @param {String} color (optional) The color of the border. Should be a 6 char hex color without the leading # (defaults to light blue: 'C3DAF9').
11848 * @param {Number} count (optional) The number of ripples to display (defaults to 1)
11849 * @param {Object} options (optional) Object literal with any of the Fx config options
11850 * @return {Roo.Element} The Element
11852 frame : function(color, count, o){
11853 var el = this.getFxEl();
11856 el.queueFx(o, function(){
11857 color = color || "#C3DAF9";
11858 if(color.length == 6){
11859 color = "#" + color;
11861 count = count || 1;
11862 duration = o.duration || 1;
11865 var b = this.getBox();
11866 var animFn = function(){
11867 var proxy = this.createProxy({
11870 visbility:"hidden",
11871 position:"absolute",
11872 "z-index":"35000", // yee haw
11873 border:"0px solid " + color
11876 var scale = Roo.isBorderBox ? 2 : 1;
11878 top:{from:b.y, to:b.y - 20},
11879 left:{from:b.x, to:b.x - 20},
11880 borderWidth:{from:0, to:10},
11881 opacity:{from:1, to:0},
11882 height:{from:b.height, to:(b.height + (20*scale))},
11883 width:{from:b.width, to:(b.width + (20*scale))}
11884 }, duration, function(){
11888 animFn.defer((duration/2)*1000, this);
11899 * Creates a pause before any subsequent queued effects begin. If there are
11900 * no effects queued after the pause it will have no effect.
11905 * @param {Number} seconds The length of time to pause (in seconds)
11906 * @return {Roo.Element} The Element
11908 pause : function(seconds){
11909 var el = this.getFxEl();
11912 el.queueFx(o, function(){
11913 setTimeout(function(){
11915 }, seconds * 1000);
11921 * Fade an element in (from transparent to opaque). The ending opacity can be specified
11922 * using the "endOpacity" config option.
11925 // default: fade in from opacity 0 to 100%
11928 // custom: fade in from opacity 0 to 75% over 2 seconds
11929 el.fadeIn({ endOpacity: .75, duration: 2});
11931 // common config options shown with default values
11933 endOpacity: 1, //can be any value between 0 and 1 (e.g. .5)
11938 * @param {Object} options (optional) Object literal with any of the Fx config options
11939 * @return {Roo.Element} The Element
11941 fadeIn : function(o){
11942 var el = this.getFxEl();
11944 el.queueFx(o, function(){
11945 this.setOpacity(0);
11947 this.dom.style.visibility = 'visible';
11948 var to = o.endOpacity || 1;
11949 arguments.callee.anim = this.fxanim({opacity:{to:to}},
11950 o, null, .5, "easeOut", function(){
11952 this.clearOpacity();
11961 * Fade an element out (from opaque to transparent). The ending opacity can be specified
11962 * using the "endOpacity" config option.
11965 // default: fade out from the element's current opacity to 0
11968 // custom: fade out from the element's current opacity to 25% over 2 seconds
11969 el.fadeOut({ endOpacity: .25, duration: 2});
11971 // common config options shown with default values
11973 endOpacity: 0, //can be any value between 0 and 1 (e.g. .5)
11980 * @param {Object} options (optional) Object literal with any of the Fx config options
11981 * @return {Roo.Element} The Element
11983 fadeOut : function(o){
11984 var el = this.getFxEl();
11986 el.queueFx(o, function(){
11987 arguments.callee.anim = this.fxanim({opacity:{to:o.endOpacity || 0}},
11988 o, null, .5, "easeOut", function(){
11989 if(this.visibilityMode == Roo.Element.DISPLAY || o.useDisplay){
11990 this.dom.style.display = "none";
11992 this.dom.style.visibility = "hidden";
11994 this.clearOpacity();
12002 * Animates the transition of an element's dimensions from a starting height/width
12003 * to an ending height/width.
12006 // change height and width to 100x100 pixels
12007 el.scale(100, 100);
12009 // common config options shown with default values. The height and width will default to
12010 // the element's existing values if passed as null.
12013 [element's height], {
12018 * @param {Number} width The new width (pass undefined to keep the original width)
12019 * @param {Number} height The new height (pass undefined to keep the original height)
12020 * @param {Object} options (optional) Object literal with any of the Fx config options
12021 * @return {Roo.Element} The Element
12023 scale : function(w, h, o){
12024 this.shift(Roo.apply({}, o, {
12032 * Animates the transition of any combination of an element's dimensions, xy position and/or opacity.
12033 * Any of these properties not specified in the config object will not be changed. This effect
12034 * requires that at least one new dimension, position or opacity setting must be passed in on
12035 * the config object in order for the function to have any effect.
12038 // slide the element horizontally to x position 200 while changing the height and opacity
12039 el.shift({ x: 200, height: 50, opacity: .8 });
12041 // common config options shown with default values.
12043 width: [element's width],
12044 height: [element's height],
12045 x: [element's x position],
12046 y: [element's y position],
12047 opacity: [element's opacity],
12052 * @param {Object} options Object literal with any of the Fx config options
12053 * @return {Roo.Element} The Element
12055 shift : function(o){
12056 var el = this.getFxEl();
12058 el.queueFx(o, function(){
12059 var a = {}, w = o.width, h = o.height, x = o.x, y = o.y, op = o.opacity;
12060 if(w !== undefined){
12061 a.width = {to: this.adjustWidth(w)};
12063 if(h !== undefined){
12064 a.height = {to: this.adjustHeight(h)};
12066 if(x !== undefined || y !== undefined){
12068 x !== undefined ? x : this.getX(),
12069 y !== undefined ? y : this.getY()
12072 if(op !== undefined){
12073 a.opacity = {to: op};
12075 if(o.xy !== undefined){
12076 a.points = {to: o.xy};
12078 arguments.callee.anim = this.fxanim(a,
12079 o, 'motion', .35, "easeOut", function(){
12087 * Slides the element while fading it out of view. An anchor point can be optionally passed to set the
12088 * ending point of the effect.
12091 // default: slide the element downward while fading out
12094 // custom: slide the element out to the right with a 2-second duration
12095 el.ghost('r', { duration: 2 });
12097 // common config options shown with default values
12105 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to bottom: 'b')
12106 * @param {Object} options (optional) Object literal with any of the Fx config options
12107 * @return {Roo.Element} The Element
12109 ghost : function(anchor, o){
12110 var el = this.getFxEl();
12113 el.queueFx(o, function(){
12114 anchor = anchor || "b";
12116 // restore values after effect
12117 var r = this.getFxRestore();
12118 var w = this.getWidth(),
12119 h = this.getHeight();
12121 var st = this.dom.style;
12123 var after = function(){
12125 el.setDisplayed(false);
12131 el.setPositioning(r.pos);
12132 st.width = r.width;
12133 st.height = r.height;
12138 var a = {opacity: {to: 0}, points: {}}, pt = a.points;
12139 switch(anchor.toLowerCase()){
12166 arguments.callee.anim = this.fxanim(a,
12176 * Ensures that all effects queued after syncFx is called on the element are
12177 * run concurrently. This is the opposite of {@link #sequenceFx}.
12178 * @return {Roo.Element} The Element
12180 syncFx : function(){
12181 this.fxDefaults = Roo.apply(this.fxDefaults || {}, {
12190 * Ensures that all effects queued after sequenceFx is called on the element are
12191 * run in sequence. This is the opposite of {@link #syncFx}.
12192 * @return {Roo.Element} The Element
12194 sequenceFx : function(){
12195 this.fxDefaults = Roo.apply(this.fxDefaults || {}, {
12197 concurrent : false,
12204 nextFx : function(){
12205 var ef = this.fxQueue[0];
12212 * Returns true if the element has any effects actively running or queued, else returns false.
12213 * @return {Boolean} True if element has active effects, else false
12215 hasActiveFx : function(){
12216 return this.fxQueue && this.fxQueue[0];
12220 * Stops any running effects and clears the element's internal effects queue if it contains
12221 * any additional effects that haven't started yet.
12222 * @return {Roo.Element} The Element
12224 stopFx : function(){
12225 if(this.hasActiveFx()){
12226 var cur = this.fxQueue[0];
12227 if(cur && cur.anim && cur.anim.isAnimated()){
12228 this.fxQueue = [cur]; // clear out others
12229 cur.anim.stop(true);
12236 beforeFx : function(o){
12237 if(this.hasActiveFx() && !o.concurrent){
12248 * Returns true if the element is currently blocking so that no other effect can be queued
12249 * until this effect is finished, else returns false if blocking is not set. This is commonly
12250 * used to ensure that an effect initiated by a user action runs to completion prior to the
12251 * same effect being restarted (e.g., firing only one effect even if the user clicks several times).
12252 * @return {Boolean} True if blocking, else false
12254 hasFxBlock : function(){
12255 var q = this.fxQueue;
12256 return q && q[0] && q[0].block;
12260 queueFx : function(o, fn){
12264 if(!this.hasFxBlock()){
12265 Roo.applyIf(o, this.fxDefaults);
12267 var run = this.beforeFx(o);
12268 fn.block = o.block;
12269 this.fxQueue.push(fn);
12281 fxWrap : function(pos, o, vis){
12283 if(!o.wrap || !(wrap = Roo.get(o.wrap))){
12286 wrapXY = this.getXY();
12288 var div = document.createElement("div");
12289 div.style.visibility = vis;
12290 wrap = Roo.get(this.dom.parentNode.insertBefore(div, this.dom));
12291 wrap.setPositioning(pos);
12292 if(wrap.getStyle("position") == "static"){
12293 wrap.position("relative");
12295 this.clearPositioning('auto');
12297 wrap.dom.appendChild(this.dom);
12299 wrap.setXY(wrapXY);
12306 fxUnwrap : function(wrap, pos, o){
12307 this.clearPositioning();
12308 this.setPositioning(pos);
12310 wrap.dom.parentNode.insertBefore(this.dom, wrap.dom);
12316 getFxRestore : function(){
12317 var st = this.dom.style;
12318 return {pos: this.getPositioning(), width: st.width, height : st.height};
12322 afterFx : function(o){
12324 this.applyStyles(o.afterStyle);
12327 this.addClass(o.afterCls);
12329 if(o.remove === true){
12332 Roo.callback(o.callback, o.scope, [this]);
12334 this.fxQueue.shift();
12340 getFxEl : function(){ // support for composite element fx
12341 return Roo.get(this.dom);
12345 fxanim : function(args, opt, animType, defaultDur, defaultEase, cb){
12346 animType = animType || 'run';
12348 var anim = Roo.lib.Anim[animType](
12350 (opt.duration || defaultDur) || .35,
12351 (opt.easing || defaultEase) || 'easeOut',
12353 Roo.callback(cb, this);
12362 // backwords compat
12363 Roo.Fx.resize = Roo.Fx.scale;
12365 //When included, Roo.Fx is automatically applied to Element so that all basic
12366 //effects are available directly via the Element API
12367 Roo.apply(Roo.Element.prototype, Roo.Fx);/*
12369 * Ext JS Library 1.1.1
12370 * Copyright(c) 2006-2007, Ext JS, LLC.
12372 * Originally Released Under LGPL - original licence link has changed is not relivant.
12375 * <script type="text/javascript">
12380 * @class Roo.CompositeElement
12381 * Standard composite class. Creates a Roo.Element for every element in the collection.
12383 * <b>NOTE: Although they are not listed, this class supports all of the set/update methods of Roo.Element. All Roo.Element
12384 * actions will be performed on all the elements in this collection.</b>
12386 * All methods return <i>this</i> and can be chained.
12388 var els = Roo.select("#some-el div.some-class", true);
12389 // or select directly from an existing element
12390 var el = Roo.get('some-el');
12391 el.select('div.some-class', true);
12393 els.setWidth(100); // all elements become 100 width
12394 els.hide(true); // all elements fade out and hide
12396 els.setWidth(100).hide(true);
12399 Roo.CompositeElement = function(els){
12400 this.elements = [];
12401 this.addElements(els);
12403 Roo.CompositeElement.prototype = {
12405 addElements : function(els){
12409 if(typeof els == "string"){
12410 els = Roo.Element.selectorFunction(els);
12412 var yels = this.elements;
12413 var index = yels.length-1;
12414 for(var i = 0, len = els.length; i < len; i++) {
12415 yels[++index] = Roo.get(els[i]);
12421 * Clears this composite and adds the elements returned by the passed selector.
12422 * @param {String/Array} els A string CSS selector, an array of elements or an element
12423 * @return {CompositeElement} this
12425 fill : function(els){
12426 this.elements = [];
12432 * Filters this composite to only elements that match the passed selector.
12433 * @param {String} selector A string CSS selector
12434 * @param {Boolean} inverse return inverse filter (not matches)
12435 * @return {CompositeElement} this
12437 filter : function(selector, inverse){
12439 inverse = inverse || false;
12440 this.each(function(el){
12441 var match = inverse ? !el.is(selector) : el.is(selector);
12443 els[els.length] = el.dom;
12450 invoke : function(fn, args){
12451 var els = this.elements;
12452 for(var i = 0, len = els.length; i < len; i++) {
12453 Roo.Element.prototype[fn].apply(els[i], args);
12458 * Adds elements to this composite.
12459 * @param {String/Array} els A string CSS selector, an array of elements or an element
12460 * @return {CompositeElement} this
12462 add : function(els){
12463 if(typeof els == "string"){
12464 this.addElements(Roo.Element.selectorFunction(els));
12465 }else if(els.length !== undefined){
12466 this.addElements(els);
12468 this.addElements([els]);
12473 * Calls the passed function passing (el, this, index) for each element in this composite.
12474 * @param {Function} fn The function to call
12475 * @param {Object} scope (optional) The <i>this</i> object (defaults to the element)
12476 * @return {CompositeElement} this
12478 each : function(fn, scope){
12479 var els = this.elements;
12480 for(var i = 0, len = els.length; i < len; i++){
12481 if(fn.call(scope || els[i], els[i], this, i) === false) {
12489 * Returns the Element object at the specified index
12490 * @param {Number} index
12491 * @return {Roo.Element}
12493 item : function(index){
12494 return this.elements[index] || null;
12498 * Returns the first Element
12499 * @return {Roo.Element}
12501 first : function(){
12502 return this.item(0);
12506 * Returns the last Element
12507 * @return {Roo.Element}
12510 return this.item(this.elements.length-1);
12514 * Returns the number of elements in this composite
12517 getCount : function(){
12518 return this.elements.length;
12522 * Returns true if this composite contains the passed element
12525 contains : function(el){
12526 return this.indexOf(el) !== -1;
12530 * Returns true if this composite contains the passed element
12533 indexOf : function(el){
12534 return this.elements.indexOf(Roo.get(el));
12539 * Removes the specified element(s).
12540 * @param {Mixed} el The id of an element, the Element itself, the index of the element in this composite
12541 * or an array of any of those.
12542 * @param {Boolean} removeDom (optional) True to also remove the element from the document
12543 * @return {CompositeElement} this
12545 removeElement : function(el, removeDom){
12546 if(el instanceof Array){
12547 for(var i = 0, len = el.length; i < len; i++){
12548 this.removeElement(el[i]);
12552 var index = typeof el == 'number' ? el : this.indexOf(el);
12555 var d = this.elements[index];
12559 d.parentNode.removeChild(d);
12562 this.elements.splice(index, 1);
12568 * Replaces the specified element with the passed element.
12569 * @param {String/HTMLElement/Element/Number} el The id of an element, the Element itself, the index of the element in this composite
12571 * @param {String/HTMLElement/Element} replacement The id of an element or the Element itself.
12572 * @param {Boolean} domReplace (Optional) True to remove and replace the element in the document too.
12573 * @return {CompositeElement} this
12575 replaceElement : function(el, replacement, domReplace){
12576 var index = typeof el == 'number' ? el : this.indexOf(el);
12579 this.elements[index].replaceWith(replacement);
12581 this.elements.splice(index, 1, Roo.get(replacement))
12588 * Removes all elements.
12590 clear : function(){
12591 this.elements = [];
12595 Roo.CompositeElement.createCall = function(proto, fnName){
12596 if(!proto[fnName]){
12597 proto[fnName] = function(){
12598 return this.invoke(fnName, arguments);
12602 for(var fnName in Roo.Element.prototype){
12603 if(typeof Roo.Element.prototype[fnName] == "function"){
12604 Roo.CompositeElement.createCall(Roo.CompositeElement.prototype, fnName);
12610 * Ext JS Library 1.1.1
12611 * Copyright(c) 2006-2007, Ext JS, LLC.
12613 * Originally Released Under LGPL - original licence link has changed is not relivant.
12616 * <script type="text/javascript">
12620 * @class Roo.CompositeElementLite
12621 * @extends Roo.CompositeElement
12622 * Flyweight composite class. Reuses the same Roo.Element for element operations.
12624 var els = Roo.select("#some-el div.some-class");
12625 // or select directly from an existing element
12626 var el = Roo.get('some-el');
12627 el.select('div.some-class');
12629 els.setWidth(100); // all elements become 100 width
12630 els.hide(true); // all elements fade out and hide
12632 els.setWidth(100).hide(true);
12633 </code></pre><br><br>
12634 * <b>NOTE: Although they are not listed, this class supports all of the set/update methods of Roo.Element. All Roo.Element
12635 * actions will be performed on all the elements in this collection.</b>
12637 Roo.CompositeElementLite = function(els){
12638 Roo.CompositeElementLite.superclass.constructor.call(this, els);
12639 this.el = new Roo.Element.Flyweight();
12641 Roo.extend(Roo.CompositeElementLite, Roo.CompositeElement, {
12642 addElements : function(els){
12644 if(els instanceof Array){
12645 this.elements = this.elements.concat(els);
12647 var yels = this.elements;
12648 var index = yels.length-1;
12649 for(var i = 0, len = els.length; i < len; i++) {
12650 yels[++index] = els[i];
12656 invoke : function(fn, args){
12657 var els = this.elements;
12659 for(var i = 0, len = els.length; i < len; i++) {
12661 Roo.Element.prototype[fn].apply(el, args);
12666 * Returns a flyweight Element of the dom element object at the specified index
12667 * @param {Number} index
12668 * @return {Roo.Element}
12670 item : function(index){
12671 if(!this.elements[index]){
12674 this.el.dom = this.elements[index];
12678 // fixes scope with flyweight
12679 addListener : function(eventName, handler, scope, opt){
12680 var els = this.elements;
12681 for(var i = 0, len = els.length; i < len; i++) {
12682 Roo.EventManager.on(els[i], eventName, handler, scope || els[i], opt);
12688 * Calls the passed function passing (el, this, index) for each element in this composite. <b>The element
12689 * passed is the flyweight (shared) Roo.Element instance, so if you require a
12690 * a reference to the dom node, use el.dom.</b>
12691 * @param {Function} fn The function to call
12692 * @param {Object} scope (optional) The <i>this</i> object (defaults to the element)
12693 * @return {CompositeElement} this
12695 each : function(fn, scope){
12696 var els = this.elements;
12698 for(var i = 0, len = els.length; i < len; i++){
12700 if(fn.call(scope || el, el, this, i) === false){
12707 indexOf : function(el){
12708 return this.elements.indexOf(Roo.getDom(el));
12711 replaceElement : function(el, replacement, domReplace){
12712 var index = typeof el == 'number' ? el : this.indexOf(el);
12714 replacement = Roo.getDom(replacement);
12716 var d = this.elements[index];
12717 d.parentNode.insertBefore(replacement, d);
12718 d.parentNode.removeChild(d);
12720 this.elements.splice(index, 1, replacement);
12725 Roo.CompositeElementLite.prototype.on = Roo.CompositeElementLite.prototype.addListener;
12729 * Ext JS Library 1.1.1
12730 * Copyright(c) 2006-2007, Ext JS, LLC.
12732 * Originally Released Under LGPL - original licence link has changed is not relivant.
12735 * <script type="text/javascript">
12741 * @class Roo.data.Connection
12742 * @extends Roo.util.Observable
12743 * The class encapsulates a connection to the page's originating domain, allowing requests to be made
12744 * either to a configured URL, or to a URL specified at request time.
12746 * Requests made by this class are asynchronous, and will return immediately. No data from
12747 * the server will be available to the statement immediately following the {@link #request} call.
12748 * To process returned data, use a callback in the request options object, or an event listener.
12750 * Note: If you are doing a file upload, you will not get a normal response object sent back to
12751 * your callback or event handler. Since the upload is handled via in IFRAME, there is no XMLHttpRequest.
12752 * The response object is created using the innerHTML of the IFRAME's document as the responseText
12753 * property and, if present, the IFRAME's XML document as the responseXML property.
12755 * This means that a valid XML or HTML document must be returned. If JSON data is required, it is suggested
12756 * that it be placed either inside a <textarea> in an HTML document and retrieved from the responseText
12757 * using a regex, or inside a CDATA section in an XML document and retrieved from the responseXML using
12758 * standard DOM methods.
12760 * @param {Object} config a configuration object.
12762 Roo.data.Connection = function(config){
12763 Roo.apply(this, config);
12766 * @event beforerequest
12767 * Fires before a network request is made to retrieve a data object.
12768 * @param {Connection} conn This Connection object.
12769 * @param {Object} options The options config object passed to the {@link #request} method.
12771 "beforerequest" : true,
12773 * @event requestcomplete
12774 * Fires if the request was successfully completed.
12775 * @param {Connection} conn This Connection object.
12776 * @param {Object} response The XHR object containing the response data.
12777 * See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
12778 * @param {Object} options The options config object passed to the {@link #request} method.
12780 "requestcomplete" : true,
12782 * @event requestexception
12783 * Fires if an error HTTP status was returned from the server.
12784 * See {@link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html} for details of HTTP status codes.
12785 * @param {Connection} conn This Connection object.
12786 * @param {Object} response The XHR object containing the response data.
12787 * See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
12788 * @param {Object} options The options config object passed to the {@link #request} method.
12790 "requestexception" : true
12792 Roo.data.Connection.superclass.constructor.call(this);
12795 Roo.extend(Roo.data.Connection, Roo.util.Observable, {
12797 * @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
12800 * @cfg {Object} extraParams (Optional) An object containing properties which are used as
12801 * extra parameters to each request made by this object. (defaults to undefined)
12804 * @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
12805 * to each request made by this object. (defaults to undefined)
12808 * @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)
12811 * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
12815 * @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
12821 * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
12824 disableCaching: true,
12827 * Sends an HTTP request to a remote server.
12828 * @param {Object} options An object which may contain the following properties:<ul>
12829 * <li><b>url</b> {String} (Optional) The URL to which to send the request. Defaults to configured URL</li>
12830 * <li><b>params</b> {Object/String/Function} (Optional) An object containing properties which are used as parameters to the
12831 * request, a url encoded string or a function to call to get either.</li>
12832 * <li><b>method</b> {String} (Optional) The HTTP method to use for the request. Defaults to the configured method, or
12833 * if no method was configured, "GET" if no parameters are being sent, and "POST" if parameters are being sent.</li>
12834 * <li><b>callback</b> {Function} (Optional) The function to be called upon receipt of the HTTP response.
12835 * The callback is called regardless of success or failure and is passed the following parameters:<ul>
12836 * <li>options {Object} The parameter to the request call.</li>
12837 * <li>success {Boolean} True if the request succeeded.</li>
12838 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
12840 * <li><b>success</b> {Function} (Optional) The function to be called upon success of the request.
12841 * The callback is passed the following parameters:<ul>
12842 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
12843 * <li>options {Object} The parameter to the request call.</li>
12845 * <li><b>failure</b> {Function} (Optional) The function to be called upon failure of the request.
12846 * The callback is passed the following parameters:<ul>
12847 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
12848 * <li>options {Object} The parameter to the request call.</li>
12850 * <li><b>scope</b> {Object} (Optional) The scope in which to execute the callbacks: The "this" object
12851 * for the callback function. Defaults to the browser window.</li>
12852 * <li><b>form</b> {Object/String} (Optional) A form object or id to pull parameters from.</li>
12853 * <li><b>isUpload</b> {Boolean} (Optional) True if the form object is a file upload (will usually be automatically detected).</li>
12854 * <li><b>headers</b> {Object} (Optional) Request headers to set for the request.</li>
12855 * <li><b>xmlData</b> {Object} (Optional) XML document to use for the post. Note: This will be used instead of
12856 * params for the post data. Any params will be appended to the URL.</li>
12857 * <li><b>disableCaching</b> {Boolean} (Optional) True to add a unique cache-buster param to GET requests.</li>
12859 * @return {Number} transactionId
12861 request : function(o){
12862 if(this.fireEvent("beforerequest", this, o) !== false){
12865 if(typeof p == "function"){
12866 p = p.call(o.scope||window, o);
12868 if(typeof p == "object"){
12869 p = Roo.urlEncode(o.params);
12871 if(this.extraParams){
12872 var extras = Roo.urlEncode(this.extraParams);
12873 p = p ? (p + '&' + extras) : extras;
12876 var url = o.url || this.url;
12877 if(typeof url == 'function'){
12878 url = url.call(o.scope||window, o);
12882 var form = Roo.getDom(o.form);
12883 url = url || form.action;
12885 var enctype = form.getAttribute("enctype");
12888 return this.doFormDataUpload(o, url);
12891 if(o.isUpload || (enctype && enctype.toLowerCase() == 'multipart/form-data')){
12892 return this.doFormUpload(o, p, url);
12894 var f = Roo.lib.Ajax.serializeForm(form);
12895 p = p ? (p + '&' + f) : f;
12898 if (!o.form && o.formData) {
12899 o.formData = o.formData === true ? new FormData() : o.formData;
12900 for (var k in o.params) {
12901 o.formData.append(k,o.params[k]);
12904 return this.doFormDataUpload(o, url);
12908 var hs = o.headers;
12909 if(this.defaultHeaders){
12910 hs = Roo.apply(hs || {}, this.defaultHeaders);
12917 success: this.handleResponse,
12918 failure: this.handleFailure,
12920 argument: {options: o},
12921 timeout : o.timeout || this.timeout
12924 var method = o.method||this.method||(p ? "POST" : "GET");
12926 if(method == 'GET' && (this.disableCaching && o.disableCaching !== false) || o.disableCaching === true){
12927 url += (url.indexOf('?') != -1 ? '&' : '?') + '_dc=' + (new Date().getTime());
12930 if(typeof o.autoAbort == 'boolean'){ // options gets top priority
12934 }else if(this.autoAbort !== false){
12938 if((method == 'GET' && p) || o.xmlData){
12939 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
12942 Roo.lib.Ajax.useDefaultHeader = typeof(o.headers) == 'undefined' || typeof(o.headers['Content-Type']) == 'undefined';
12943 this.transId = Roo.lib.Ajax.request(method, url, cb, p, o);
12944 Roo.lib.Ajax.useDefaultHeader == true;
12945 return this.transId;
12947 Roo.callback(o.callback, o.scope, [o, null, null]);
12953 * Determine whether this object has a request outstanding.
12954 * @param {Number} transactionId (Optional) defaults to the last transaction
12955 * @return {Boolean} True if there is an outstanding request.
12957 isLoading : function(transId){
12959 return Roo.lib.Ajax.isCallInProgress(transId);
12961 return this.transId ? true : false;
12966 * Aborts any outstanding request.
12967 * @param {Number} transactionId (Optional) defaults to the last transaction
12969 abort : function(transId){
12970 if(transId || this.isLoading()){
12971 Roo.lib.Ajax.abort(transId || this.transId);
12976 handleResponse : function(response){
12977 this.transId = false;
12978 var options = response.argument.options;
12979 response.argument = options ? options.argument : null;
12980 this.fireEvent("requestcomplete", this, response, options);
12981 Roo.callback(options.success, options.scope, [response, options]);
12982 Roo.callback(options.callback, options.scope, [options, true, response]);
12986 handleFailure : function(response, e){
12987 this.transId = false;
12988 var options = response.argument.options;
12989 response.argument = options ? options.argument : null;
12990 this.fireEvent("requestexception", this, response, options, e);
12991 Roo.callback(options.failure, options.scope, [response, options]);
12992 Roo.callback(options.callback, options.scope, [options, false, response]);
12996 doFormUpload : function(o, ps, url){
12998 var frame = document.createElement('iframe');
13001 frame.className = 'x-hidden';
13003 frame.src = Roo.SSL_SECURE_URL;
13005 document.body.appendChild(frame);
13008 document.frames[id].name = id;
13011 var form = Roo.getDom(o.form);
13013 form.method = 'POST';
13014 form.enctype = form.encoding = 'multipart/form-data';
13020 if(ps){ // add dynamic params
13022 ps = Roo.urlDecode(ps, false);
13024 if(ps.hasOwnProperty(k)){
13025 hd = document.createElement('input');
13026 hd.type = 'hidden';
13029 form.appendChild(hd);
13036 var r = { // bogus response object
13041 r.argument = o ? o.argument : null;
13046 doc = frame.contentWindow.document;
13048 doc = (frame.contentDocument || window.frames[id].document);
13050 if(doc && doc.body){
13051 r.responseText = doc.body.innerHTML;
13053 if(doc && doc.XMLDocument){
13054 r.responseXML = doc.XMLDocument;
13056 r.responseXML = doc;
13063 Roo.EventManager.removeListener(frame, 'load', cb, this);
13065 this.fireEvent("requestcomplete", this, r, o);
13066 Roo.callback(o.success, o.scope, [r, o]);
13067 Roo.callback(o.callback, o.scope, [o, true, r]);
13069 setTimeout(function(){document.body.removeChild(frame);}, 100);
13072 Roo.EventManager.on(frame, 'load', cb, this);
13075 if(hiddens){ // remove dynamic params
13076 for(var i = 0, len = hiddens.length; i < len; i++){
13077 form.removeChild(hiddens[i]);
13081 // this is a 'formdata version???'
13084 doFormDataUpload : function(o, url)
13088 var form = Roo.getDom(o.form);
13089 form.enctype = form.encoding = 'multipart/form-data';
13090 formData = o.formData === true ? new FormData(form) : o.formData;
13092 formData = o.formData === true ? new FormData() : o.formData;
13097 success: this.handleResponse,
13098 failure: this.handleFailure,
13100 argument: {options: o},
13101 timeout : o.timeout || this.timeout
13104 if(typeof o.autoAbort == 'boolean'){ // options gets top priority
13108 }else if(this.autoAbort !== false){
13112 //Roo.lib.Ajax.defaultPostHeader = null;
13113 Roo.lib.Ajax.useDefaultHeader = false;
13114 this.transId = Roo.lib.Ajax.request( "POST", url, cb, formData, o);
13115 Roo.lib.Ajax.useDefaultHeader = true;
13123 * Ext JS Library 1.1.1
13124 * Copyright(c) 2006-2007, Ext JS, LLC.
13126 * Originally Released Under LGPL - original licence link has changed is not relivant.
13129 * <script type="text/javascript">
13133 * Global Ajax request class.
13136 * @extends Roo.data.Connection
13139 * @cfg {String} url The default URL to be used for requests to the server. (defaults to undefined)
13140 * @cfg {Object} extraParams An object containing properties which are used as extra parameters to each request made by this object. (defaults to undefined)
13141 * @cfg {Object} defaultHeaders An object containing request headers which are added to each request made by this object. (defaults to undefined)
13142 * @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)
13143 * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
13144 * @cfg {Boolean} autoAbort (Optional) Whether a new request should abort any pending requests. (defaults to false)
13145 * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
13147 Roo.Ajax = new Roo.data.Connection({
13156 * Serialize the passed form into a url encoded string
13158 * @param {String/HTMLElement} form
13161 serializeForm : function(form){
13162 return Roo.lib.Ajax.serializeForm(form);
13166 * Ext JS Library 1.1.1
13167 * Copyright(c) 2006-2007, Ext JS, LLC.
13169 * Originally Released Under LGPL - original licence link has changed is not relivant.
13172 * <script type="text/javascript">
13177 * @class Roo.UpdateManager
13178 * @extends Roo.util.Observable
13179 * Provides AJAX-style update for Element object.<br><br>
13182 * // Get it from a Roo.Element object
13183 * var el = Roo.get("foo");
13184 * var mgr = el.getUpdateManager();
13185 * mgr.update("http://myserver.com/index.php", "param1=1&param2=2");
13187 * mgr.formUpdate("myFormId", "http://myserver.com/index.php");
13189 * // or directly (returns the same UpdateManager instance)
13190 * var mgr = new Roo.UpdateManager("myElementId");
13191 * mgr.startAutoRefresh(60, "http://myserver.com/index.php");
13192 * mgr.on("update", myFcnNeedsToKnow);
13194 // short handed call directly from the element object
13195 Roo.get("foo").load({
13199 text: "Loading Foo..."
13203 * Create new UpdateManager directly.
13204 * @param {String/HTMLElement/Roo.Element} el The element to update
13205 * @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).
13207 Roo.UpdateManager = function(el, forceNew){
13209 if(!forceNew && el.updateManager){
13210 return el.updateManager;
13213 * The Element object
13214 * @type Roo.Element
13218 * Cached url to use for refreshes. Overwritten every time update() is called unless "discardUrl" param is set to true.
13221 this.defaultUrl = null;
13225 * @event beforeupdate
13226 * Fired before an update is made, return false from your handler and the update is cancelled.
13227 * @param {Roo.Element} el
13228 * @param {String/Object/Function} url
13229 * @param {String/Object} params
13231 "beforeupdate": true,
13234 * Fired after successful update is made.
13235 * @param {Roo.Element} el
13236 * @param {Object} oResponseObject The response Object
13241 * Fired on update failure.
13242 * @param {Roo.Element} el
13243 * @param {Object} oResponseObject The response Object
13247 var d = Roo.UpdateManager.defaults;
13249 * Blank page URL to use with SSL file uploads (Defaults to Roo.UpdateManager.defaults.sslBlankUrl or "about:blank").
13252 this.sslBlankUrl = d.sslBlankUrl;
13254 * Whether to append unique parameter on get request to disable caching (Defaults to Roo.UpdateManager.defaults.disableCaching or false).
13257 this.disableCaching = d.disableCaching;
13259 * Text for loading indicator (Defaults to Roo.UpdateManager.defaults.indicatorText or '<div class="loading-indicator">Loading...</div>').
13262 this.indicatorText = d.indicatorText;
13264 * Whether to show indicatorText when loading (Defaults to Roo.UpdateManager.defaults.showLoadIndicator or true).
13267 this.showLoadIndicator = d.showLoadIndicator;
13269 * Timeout for requests or form posts in seconds (Defaults to Roo.UpdateManager.defaults.timeout or 30 seconds).
13272 this.timeout = d.timeout;
13275 * True to process scripts in the output (Defaults to Roo.UpdateManager.defaults.loadScripts (false)).
13278 this.loadScripts = d.loadScripts;
13281 * Transaction object of current executing transaction
13283 this.transaction = null;
13288 this.autoRefreshProcId = null;
13290 * Delegate for refresh() prebound to "this", use myUpdater.refreshDelegate.createCallback(arg1, arg2) to bind arguments
13293 this.refreshDelegate = this.refresh.createDelegate(this);
13295 * Delegate for update() prebound to "this", use myUpdater.updateDelegate.createCallback(arg1, arg2) to bind arguments
13298 this.updateDelegate = this.update.createDelegate(this);
13300 * Delegate for formUpdate() prebound to "this", use myUpdater.formUpdateDelegate.createCallback(arg1, arg2) to bind arguments
13303 this.formUpdateDelegate = this.formUpdate.createDelegate(this);
13307 this.successDelegate = this.processSuccess.createDelegate(this);
13311 this.failureDelegate = this.processFailure.createDelegate(this);
13313 if(!this.renderer){
13315 * The renderer for this UpdateManager. Defaults to {@link Roo.UpdateManager.BasicRenderer}.
13317 this.renderer = new Roo.UpdateManager.BasicRenderer();
13320 Roo.UpdateManager.superclass.constructor.call(this);
13323 Roo.extend(Roo.UpdateManager, Roo.util.Observable, {
13325 * Get the Element this UpdateManager is bound to
13326 * @return {Roo.Element} The element
13328 getEl : function(){
13332 * Performs an async request, updating this element with the response. If params are specified it uses POST, otherwise it uses GET.
13333 * @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:
13336 url: "your-url.php",<br/>
13337 params: {param1: "foo", param2: "bar"}, // or a URL encoded string<br/>
13338 callback: yourFunction,<br/>
13339 scope: yourObject, //(optional scope) <br/>
13340 discardUrl: false, <br/>
13341 nocache: false,<br/>
13342 text: "Loading...",<br/>
13344 scripts: false<br/>
13347 * The only required property is url. The optional properties nocache, text and scripts
13348 * are shorthand for disableCaching, indicatorText and loadScripts and are used to set their associated property on this UpdateManager instance.
13349 * @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}
13350 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess, oResponse)
13351 * @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.
13353 update : function(url, params, callback, discardUrl){
13354 if(this.fireEvent("beforeupdate", this.el, url, params) !== false){
13355 var method = this.method,
13357 if(typeof url == "object"){ // must be config object
13360 params = params || cfg.params;
13361 callback = callback || cfg.callback;
13362 discardUrl = discardUrl || cfg.discardUrl;
13363 if(callback && cfg.scope){
13364 callback = callback.createDelegate(cfg.scope);
13366 if(typeof cfg.method != "undefined"){method = cfg.method;};
13367 if(typeof cfg.nocache != "undefined"){this.disableCaching = cfg.nocache;};
13368 if(typeof cfg.text != "undefined"){this.indicatorText = '<div class="loading-indicator">'+cfg.text+"</div>";};
13369 if(typeof cfg.scripts != "undefined"){this.loadScripts = cfg.scripts;};
13370 if(typeof cfg.timeout != "undefined"){this.timeout = cfg.timeout;};
13372 this.showLoading();
13374 this.defaultUrl = url;
13376 if(typeof url == "function"){
13377 url = url.call(this);
13380 method = method || (params ? "POST" : "GET");
13381 if(method == "GET"){
13382 url = this.prepareUrl(url);
13385 var o = Roo.apply(cfg ||{}, {
13388 success: this.successDelegate,
13389 failure: this.failureDelegate,
13390 callback: undefined,
13391 timeout: (this.timeout*1000),
13392 argument: {"url": url, "form": null, "callback": callback, "params": params}
13394 Roo.log("updated manager called with timeout of " + o.timeout);
13395 this.transaction = Roo.Ajax.request(o);
13400 * 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.
13401 * Uses this.sslBlankUrl for SSL file uploads to prevent IE security warning.
13402 * @param {String/HTMLElement} form The form Id or form element
13403 * @param {String} url (optional) The url to pass the form to. If omitted the action attribute on the form will be used.
13404 * @param {Boolean} reset (optional) Whether to try to reset the form after the update
13405 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess, oResponse)
13407 formUpdate : function(form, url, reset, callback){
13408 if(this.fireEvent("beforeupdate", this.el, form, url) !== false){
13409 if(typeof url == "function"){
13410 url = url.call(this);
13412 form = Roo.getDom(form);
13413 this.transaction = Roo.Ajax.request({
13416 success: this.successDelegate,
13417 failure: this.failureDelegate,
13418 timeout: (this.timeout*1000),
13419 argument: {"url": url, "form": form, "callback": callback, "reset": reset}
13421 this.showLoading.defer(1, this);
13426 * Refresh the element with the last used url or defaultUrl. If there is no url, it returns immediately
13427 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
13429 refresh : function(callback){
13430 if(this.defaultUrl == null){
13433 this.update(this.defaultUrl, null, callback, true);
13437 * Set this element to auto refresh.
13438 * @param {Number} interval How often to update (in seconds).
13439 * @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)
13440 * @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}
13441 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
13442 * @param {Boolean} refreshNow (optional) Whether to execute the refresh now, or wait the interval
13444 startAutoRefresh : function(interval, url, params, callback, refreshNow){
13446 this.update(url || this.defaultUrl, params, callback, true);
13448 if(this.autoRefreshProcId){
13449 clearInterval(this.autoRefreshProcId);
13451 this.autoRefreshProcId = setInterval(this.update.createDelegate(this, [url || this.defaultUrl, params, callback, true]), interval*1000);
13455 * Stop auto refresh on this element.
13457 stopAutoRefresh : function(){
13458 if(this.autoRefreshProcId){
13459 clearInterval(this.autoRefreshProcId);
13460 delete this.autoRefreshProcId;
13464 isAutoRefreshing : function(){
13465 return this.autoRefreshProcId ? true : false;
13468 * Called to update the element to "Loading" state. Override to perform custom action.
13470 showLoading : function(){
13471 if(this.showLoadIndicator){
13472 this.el.update(this.indicatorText);
13477 * Adds unique parameter to query string if disableCaching = true
13480 prepareUrl : function(url){
13481 if(this.disableCaching){
13482 var append = "_dc=" + (new Date().getTime());
13483 if(url.indexOf("?") !== -1){
13484 url += "&" + append;
13486 url += "?" + append;
13495 processSuccess : function(response){
13496 this.transaction = null;
13497 if(response.argument.form && response.argument.reset){
13498 try{ // put in try/catch since some older FF releases had problems with this
13499 response.argument.form.reset();
13502 if(this.loadScripts){
13503 this.renderer.render(this.el, response, this,
13504 this.updateComplete.createDelegate(this, [response]));
13506 this.renderer.render(this.el, response, this);
13507 this.updateComplete(response);
13511 updateComplete : function(response){
13512 this.fireEvent("update", this.el, response);
13513 if(typeof response.argument.callback == "function"){
13514 response.argument.callback(this.el, true, response);
13521 processFailure : function(response){
13522 this.transaction = null;
13523 this.fireEvent("failure", this.el, response);
13524 if(typeof response.argument.callback == "function"){
13525 response.argument.callback(this.el, false, response);
13530 * Set the content renderer for this UpdateManager. See {@link Roo.UpdateManager.BasicRenderer#render} for more details.
13531 * @param {Object} renderer The object implementing the render() method
13533 setRenderer : function(renderer){
13534 this.renderer = renderer;
13537 getRenderer : function(){
13538 return this.renderer;
13542 * Set the defaultUrl used for updates
13543 * @param {String/Function} defaultUrl The url or a function to call to get the url
13545 setDefaultUrl : function(defaultUrl){
13546 this.defaultUrl = defaultUrl;
13550 * Aborts the executing transaction
13552 abort : function(){
13553 if(this.transaction){
13554 Roo.Ajax.abort(this.transaction);
13559 * Returns true if an update is in progress
13560 * @return {Boolean}
13562 isUpdating : function(){
13563 if(this.transaction){
13564 return Roo.Ajax.isLoading(this.transaction);
13571 * @class Roo.UpdateManager.defaults
13572 * @static (not really - but it helps the doc tool)
13573 * The defaults collection enables customizing the default properties of UpdateManager
13575 Roo.UpdateManager.defaults = {
13577 * Timeout for requests or form posts in seconds (Defaults 30 seconds).
13583 * True to process scripts by default (Defaults to false).
13586 loadScripts : false,
13589 * Blank page URL to use with SSL file uploads (Defaults to "javascript:false").
13592 sslBlankUrl : (Roo.SSL_SECURE_URL || "javascript:false"),
13594 * Whether to append unique parameter on get request to disable caching (Defaults to false).
13597 disableCaching : false,
13599 * Whether to show indicatorText when loading (Defaults to true).
13602 showLoadIndicator : true,
13604 * Text for loading indicator (Defaults to '<div class="loading-indicator">Loading...</div>').
13607 indicatorText : '<div class="loading-indicator">Loading...</div>'
13611 * Static convenience method. This method is deprecated in favor of el.load({url:'foo.php', ...}).
13613 * <pre><code>Roo.UpdateManager.updateElement("my-div", "stuff.php");</code></pre>
13614 * @param {String/HTMLElement/Roo.Element} el The element to update
13615 * @param {String} url The url
13616 * @param {String/Object} params (optional) Url encoded param string or an object of name/value pairs
13617 * @param {Object} options (optional) A config object with any of the UpdateManager properties you want to set - for example: {disableCaching:true, indicatorText: "Loading data..."}
13620 * @member Roo.UpdateManager
13622 Roo.UpdateManager.updateElement = function(el, url, params, options){
13623 var um = Roo.get(el, true).getUpdateManager();
13624 Roo.apply(um, options);
13625 um.update(url, params, options ? options.callback : null);
13627 // alias for backwards compat
13628 Roo.UpdateManager.update = Roo.UpdateManager.updateElement;
13630 * @class Roo.UpdateManager.BasicRenderer
13631 * Default Content renderer. Updates the elements innerHTML with the responseText.
13633 Roo.UpdateManager.BasicRenderer = function(){};
13635 Roo.UpdateManager.BasicRenderer.prototype = {
13637 * This is called when the transaction is completed and it's time to update the element - The BasicRenderer
13638 * updates the elements innerHTML with the responseText - To perform a custom render (i.e. XML or JSON processing),
13639 * create an object with a "render(el, response)" method and pass it to setRenderer on the UpdateManager.
13640 * @param {Roo.Element} el The element being rendered
13641 * @param {Object} response The YUI Connect response object
13642 * @param {UpdateManager} updateManager The calling update manager
13643 * @param {Function} callback A callback that will need to be called if loadScripts is true on the UpdateManager
13645 render : function(el, response, updateManager, callback){
13646 el.update(response.responseText, updateManager.loadScripts, callback);
13652 * (c)) Alan Knowles
13658 * @class Roo.DomTemplate
13659 * @extends Roo.Template
13660 * An effort at a dom based template engine..
13662 * Similar to XTemplate, except it uses dom parsing to create the template..
13664 * Supported features:
13669 {a_variable} - output encoded.
13670 {a_variable.format:("Y-m-d")} - call a method on the variable
13671 {a_variable:raw} - unencoded output
13672 {a_variable:toFixed(1,2)} - Roo.util.Format."toFixed"
13673 {a_variable:this.method_on_template(...)} - call a method on the template object.
13678 <div roo-for="a_variable or condition.."></div>
13679 <div roo-if="a_variable or condition"></div>
13680 <div roo-exec="some javascript"></div>
13681 <div roo-name="named_template"></div>
13686 Roo.DomTemplate = function()
13688 Roo.DomTemplate.superclass.constructor.apply(this, arguments);
13695 Roo.extend(Roo.DomTemplate, Roo.Template, {
13697 * id counter for sub templates.
13701 * flag to indicate if dom parser is inside a pre,
13702 * it will strip whitespace if not.
13707 * The various sub templates
13715 * basic tag replacing syntax
13718 * // you can fake an object call by doing this
13722 re : /(\{|\%7B)([\w-\.]+)(?:\:([\w\.]*)(?:\(([^)]*?)?\))?)?(\}|\%7D)/g,
13723 //re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
13725 iterChild : function (node, method) {
13727 var oldPre = this.inPre;
13728 if (node.tagName == 'PRE') {
13731 for( var i = 0; i < node.childNodes.length; i++) {
13732 method.call(this, node.childNodes[i]);
13734 this.inPre = oldPre;
13740 * compile the template
13742 * This is not recursive, so I'm not sure how nested templates are really going to be handled..
13745 compile: function()
13749 // covert the html into DOM...
13753 doc = document.implementation.createHTMLDocument("");
13754 doc.documentElement.innerHTML = this.html ;
13755 div = doc.documentElement;
13757 // old IE... - nasty -- it causes all sorts of issues.. with
13758 // images getting pulled from server..
13759 div = document.createElement('div');
13760 div.innerHTML = this.html;
13762 //doc.documentElement.innerHTML = htmlBody
13768 this.iterChild(div, function(n) {_t.compileNode(n, true); });
13770 var tpls = this.tpls;
13772 // create a top level template from the snippet..
13774 //Roo.log(div.innerHTML);
13781 body : div.innerHTML,
13794 Roo.each(tpls, function(tp){
13795 this.compileTpl(tp);
13796 this.tpls[tp.id] = tp;
13799 this.master = tpls[0];
13805 compileNode : function(node, istop) {
13810 // skip anything not a tag..
13811 if (node.nodeType != 1) {
13812 if (node.nodeType == 3 && !this.inPre) {
13813 // reduce white space..
13814 node.nodeValue = node.nodeValue.replace(/\s+/g, ' ');
13837 case (node.hasAttribute('roo-for')): tpl.attr = 'for'; break;
13838 case (node.hasAttribute('roo-if')): tpl.attr = 'if'; break;
13839 case (node.hasAttribute('roo-name')): tpl.attr = 'name'; break;
13840 case (node.hasAttribute('roo-exec')): tpl.attr = 'exec'; break;
13846 // just itterate children..
13847 this.iterChild(node,this.compileNode);
13850 tpl.uid = this.id++;
13851 tpl.value = node.getAttribute('roo-' + tpl.attr);
13852 node.removeAttribute('roo-'+ tpl.attr);
13853 if (tpl.attr != 'name') {
13854 var placeholder = document.createTextNode('{domtpl' + tpl.uid + '}');
13855 node.parentNode.replaceChild(placeholder, node);
13858 var placeholder = document.createElement('span');
13859 placeholder.className = 'roo-tpl-' + tpl.value;
13860 node.parentNode.replaceChild(placeholder, node);
13863 // parent now sees '{domtplXXXX}
13864 this.iterChild(node,this.compileNode);
13866 // we should now have node body...
13867 var div = document.createElement('div');
13868 div.appendChild(node);
13870 // this has the unfortunate side effect of converting tagged attributes
13871 // eg. href="{...}" into %7C...%7D
13872 // this has been fixed by searching for those combo's although it's a bit hacky..
13875 tpl.body = div.innerHTML;
13882 switch (tpl.value) {
13883 case '.': tpl.forCall = new Function('values', 'parent', 'with(values){ return values; }'); break;
13884 case '..': tpl.forCall= new Function('values', 'parent', 'with(values){ return parent; }'); break;
13885 default: tpl.forCall= new Function('values', 'parent', 'with(values){ return '+tpl.value+'; }');
13890 tpl.execCall = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
13894 tpl.ifCall = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
13898 tpl.id = tpl.value; // replace non characters???
13904 this.tpls.push(tpl);
13914 * Compile a segment of the template into a 'sub-template'
13920 compileTpl : function(tpl)
13922 var fm = Roo.util.Format;
13923 var useF = this.disableFormats !== true;
13925 var sep = Roo.isGecko ? "+\n" : ",\n";
13927 var undef = function(str) {
13928 Roo.debug && Roo.log("Property not found :" + str);
13932 //Roo.log(tpl.body);
13936 var fn = function(m, lbrace, name, format, args)
13939 //Roo.log(arguments);
13940 args = args ? args.replace(/\\'/g,"'") : args;
13941 //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
13942 if (typeof(format) == 'undefined') {
13943 format = 'htmlEncode';
13945 if (format == 'raw' ) {
13949 if(name.substr(0, 6) == 'domtpl'){
13950 return "'"+ sep +'this.applySubTemplate('+name.substr(6)+', values, parent)'+sep+"'";
13953 // build an array of options to determine if value is undefined..
13955 // basically get 'xxxx.yyyy' then do
13956 // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
13957 // (function () { Roo.log("Property not found"); return ''; })() :
13962 Roo.each(name.split('.'), function(st) {
13963 lookfor += (lookfor.length ? '.': '') + st;
13964 udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
13967 var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
13970 if(format && useF){
13972 args = args ? ',' + args : "";
13974 if(format.substr(0, 5) != "this."){
13975 format = "fm." + format + '(';
13977 format = 'this.call("'+ format.substr(5) + '", ';
13981 return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
13984 if (args && args.length) {
13985 // called with xxyx.yuu:(test,test)
13987 return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
13989 // raw.. - :raw modifier..
13990 return "'"+ sep + udef_st + name + ")"+sep+"'";
13994 // branched to use + in gecko and [].join() in others
13996 body = "tpl.compiled = function(values, parent){ with(values) { return '" +
13997 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
14000 body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
14001 body.push(tpl.body.replace(/(\r\n|\n)/g,
14002 '\\n').replace(/'/g, "\\'").replace(this.re, fn));
14003 body.push("'].join('');};};");
14004 body = body.join('');
14007 Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
14009 /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
14016 * same as applyTemplate, except it's done to one of the subTemplates
14017 * when using named templates, you can do:
14019 * var str = pl.applySubTemplate('your-name', values);
14022 * @param {Number} id of the template
14023 * @param {Object} values to apply to template
14024 * @param {Object} parent (normaly the instance of this object)
14026 applySubTemplate : function(id, values, parent)
14030 var t = this.tpls[id];
14034 if(t.ifCall && !t.ifCall.call(this, values, parent)){
14035 Roo.debug && Roo.log('if call on ' + t.value + ' return false');
14039 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-if="' + t.value + '" - ' + e.toString());
14046 if(t.execCall && t.execCall.call(this, values, parent)){
14050 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
14056 var vs = t.forCall ? t.forCall.call(this, values, parent) : values;
14057 parent = t.target ? values : parent;
14058 if(t.forCall && vs instanceof Array){
14060 for(var i = 0, len = vs.length; i < len; i++){
14062 buf[buf.length] = t.compiled.call(this, vs[i], parent);
14064 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
14066 //Roo.log(t.compiled);
14070 return buf.join('');
14073 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
14078 return t.compiled.call(this, vs, parent);
14080 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
14082 //Roo.log(t.compiled);
14090 applyTemplate : function(values){
14091 return this.master.compiled.call(this, values, {});
14092 //var s = this.subs;
14095 apply : function(){
14096 return this.applyTemplate.apply(this, arguments);
14101 Roo.DomTemplate.from = function(el){
14102 el = Roo.getDom(el);
14103 return new Roo.Domtemplate(el.value || el.innerHTML);
14106 * Ext JS Library 1.1.1
14107 * Copyright(c) 2006-2007, Ext JS, LLC.
14109 * Originally Released Under LGPL - original licence link has changed is not relivant.
14112 * <script type="text/javascript">
14116 * @class Roo.util.DelayedTask
14117 * Provides a convenient method of performing setTimeout where a new
14118 * timeout cancels the old timeout. An example would be performing validation on a keypress.
14119 * You can use this class to buffer
14120 * the keypress events for a certain number of milliseconds, and perform only if they stop
14121 * for that amount of time.
14122 * @constructor The parameters to this constructor serve as defaults and are not required.
14123 * @param {Function} fn (optional) The default function to timeout
14124 * @param {Object} scope (optional) The default scope of that timeout
14125 * @param {Array} args (optional) The default Array of arguments
14127 Roo.util.DelayedTask = function(fn, scope, args){
14128 var id = null, d, t;
14130 var call = function(){
14131 var now = new Date().getTime();
14135 fn.apply(scope, args || []);
14139 * Cancels any pending timeout and queues a new one
14140 * @param {Number} delay The milliseconds to delay
14141 * @param {Function} newFn (optional) Overrides function passed to constructor
14142 * @param {Object} newScope (optional) Overrides scope passed to constructor
14143 * @param {Array} newArgs (optional) Overrides args passed to constructor
14145 this.delay = function(delay, newFn, newScope, newArgs){
14146 if(id && delay != d){
14150 t = new Date().getTime();
14152 scope = newScope || scope;
14153 args = newArgs || args;
14155 id = setInterval(call, d);
14160 * Cancel the last queued timeout
14162 this.cancel = function(){
14170 * Ext JS Library 1.1.1
14171 * Copyright(c) 2006-2007, Ext JS, LLC.
14173 * Originally Released Under LGPL - original licence link has changed is not relivant.
14176 * <script type="text/javascript">
14179 * @class Roo.util.TaskRunner
14180 * Manage background tasks - not sure why this is better that setInterval?
14185 Roo.util.TaskRunner = function(interval){
14186 interval = interval || 10;
14187 var tasks = [], removeQueue = [];
14189 var running = false;
14191 var stopThread = function(){
14197 var startThread = function(){
14200 id = setInterval(runTasks, interval);
14204 var removeTask = function(task){
14205 removeQueue.push(task);
14211 var runTasks = function(){
14212 if(removeQueue.length > 0){
14213 for(var i = 0, len = removeQueue.length; i < len; i++){
14214 tasks.remove(removeQueue[i]);
14217 if(tasks.length < 1){
14222 var now = new Date().getTime();
14223 for(var i = 0, len = tasks.length; i < len; ++i){
14225 var itime = now - t.taskRunTime;
14226 if(t.interval <= itime){
14227 var rt = t.run.apply(t.scope || t, t.args || [++t.taskRunCount]);
14228 t.taskRunTime = now;
14229 if(rt === false || t.taskRunCount === t.repeat){
14234 if(t.duration && t.duration <= (now - t.taskStartTime)){
14241 * Queues a new task.
14242 * @param {Object} task
14244 * Task property : interval = how frequent to run.
14245 * Task object should implement
14247 * Task object may implement
14248 * function onStop()
14250 this.start = function(task){
14252 task.taskStartTime = new Date().getTime();
14253 task.taskRunTime = 0;
14254 task.taskRunCount = 0;
14260 * @param {Object} task
14262 this.stop = function(task){
14269 this.stopAll = function(){
14271 for(var i = 0, len = tasks.length; i < len; i++){
14272 if(tasks[i].onStop){
14281 Roo.TaskMgr = new Roo.util.TaskRunner();/*
14283 * Ext JS Library 1.1.1
14284 * Copyright(c) 2006-2007, Ext JS, LLC.
14286 * Originally Released Under LGPL - original licence link has changed is not relivant.
14289 * <script type="text/javascript">
14294 * @class Roo.util.MixedCollection
14295 * @extends Roo.util.Observable
14296 * A Collection class that maintains both numeric indexes and keys and exposes events.
14298 * @param {Boolean} allowFunctions True if the addAll function should add function references to the
14299 * collection (defaults to false)
14300 * @param {Function} keyFn A function that can accept an item of the type(s) stored in this MixedCollection
14301 * and return the key value for that item. This is used when available to look up the key on items that
14302 * were passed without an explicit key parameter to a MixedCollection method. Passing this parameter is
14303 * equivalent to providing an implementation for the {@link #getKey} method.
14305 Roo.util.MixedCollection = function(allowFunctions, keyFn){
14313 * Fires when the collection is cleared.
14318 * Fires when an item is added to the collection.
14319 * @param {Number} index The index at which the item was added.
14320 * @param {Object} o The item added.
14321 * @param {String} key The key associated with the added item.
14326 * Fires when an item is replaced in the collection.
14327 * @param {String} key he key associated with the new added.
14328 * @param {Object} old The item being replaced.
14329 * @param {Object} new The new item.
14334 * Fires when an item is removed from the collection.
14335 * @param {Object} o The item being removed.
14336 * @param {String} key (optional) The key associated with the removed item.
14341 this.allowFunctions = allowFunctions === true;
14343 this.getKey = keyFn;
14345 Roo.util.MixedCollection.superclass.constructor.call(this);
14348 Roo.extend(Roo.util.MixedCollection, Roo.util.Observable, {
14349 allowFunctions : false,
14352 * Adds an item to the collection.
14353 * @param {String} key The key to associate with the item
14354 * @param {Object} o The item to add.
14355 * @return {Object} The item added.
14357 add : function(key, o){
14358 if(arguments.length == 1){
14360 key = this.getKey(o);
14362 if(typeof key == "undefined" || key === null){
14364 this.items.push(o);
14365 this.keys.push(null);
14367 var old = this.map[key];
14369 return this.replace(key, o);
14372 this.items.push(o);
14374 this.keys.push(key);
14376 this.fireEvent("add", this.length-1, o, key);
14381 * MixedCollection has a generic way to fetch keys if you implement getKey.
14384 var mc = new Roo.util.MixedCollection();
14385 mc.add(someEl.dom.id, someEl);
14386 mc.add(otherEl.dom.id, otherEl);
14390 var mc = new Roo.util.MixedCollection();
14391 mc.getKey = function(el){
14397 // or via the constructor
14398 var mc = new Roo.util.MixedCollection(false, function(el){
14404 * @param o {Object} The item for which to find the key.
14405 * @return {Object} The key for the passed item.
14407 getKey : function(o){
14412 * Replaces an item in the collection.
14413 * @param {String} key The key associated with the item to replace, or the item to replace.
14414 * @param o {Object} o (optional) If the first parameter passed was a key, the item to associate with that key.
14415 * @return {Object} The new item.
14417 replace : function(key, o){
14418 if(arguments.length == 1){
14420 key = this.getKey(o);
14422 var old = this.item(key);
14423 if(typeof key == "undefined" || key === null || typeof old == "undefined"){
14424 return this.add(key, o);
14426 var index = this.indexOfKey(key);
14427 this.items[index] = o;
14429 this.fireEvent("replace", key, old, o);
14434 * Adds all elements of an Array or an Object to the collection.
14435 * @param {Object/Array} objs An Object containing properties which will be added to the collection, or
14436 * an Array of values, each of which are added to the collection.
14438 addAll : function(objs){
14439 if(arguments.length > 1 || objs instanceof Array){
14440 var args = arguments.length > 1 ? arguments : objs;
14441 for(var i = 0, len = args.length; i < len; i++){
14445 for(var key in objs){
14446 if(this.allowFunctions || typeof objs[key] != "function"){
14447 this.add(key, objs[key]);
14454 * Executes the specified function once for every item in the collection, passing each
14455 * item as the first and only parameter. returning false from the function will stop the iteration.
14456 * @param {Function} fn The function to execute for each item.
14457 * @param {Object} scope (optional) The scope in which to execute the function.
14459 each : function(fn, scope){
14460 var items = [].concat(this.items); // each safe for removal
14461 for(var i = 0, len = items.length; i < len; i++){
14462 if(fn.call(scope || items[i], items[i], i, len) === false){
14469 * Executes the specified function once for every key in the collection, passing each
14470 * key, and its associated item as the first two parameters.
14471 * @param {Function} fn The function to execute for each item.
14472 * @param {Object} scope (optional) The scope in which to execute the function.
14474 eachKey : function(fn, scope){
14475 for(var i = 0, len = this.keys.length; i < len; i++){
14476 fn.call(scope || window, this.keys[i], this.items[i], i, len);
14481 * Returns the first item in the collection which elicits a true return value from the
14482 * passed selection function.
14483 * @param {Function} fn The selection function to execute for each item.
14484 * @param {Object} scope (optional) The scope in which to execute the function.
14485 * @return {Object} The first item in the collection which returned true from the selection function.
14487 find : function(fn, scope){
14488 for(var i = 0, len = this.items.length; i < len; i++){
14489 if(fn.call(scope || window, this.items[i], this.keys[i])){
14490 return this.items[i];
14497 * Inserts an item at the specified index in the collection.
14498 * @param {Number} index The index to insert the item at.
14499 * @param {String} key The key to associate with the new item, or the item itself.
14500 * @param {Object} o (optional) If the second parameter was a key, the new item.
14501 * @return {Object} The item inserted.
14503 insert : function(index, key, o){
14504 if(arguments.length == 2){
14506 key = this.getKey(o);
14508 if(index >= this.length){
14509 return this.add(key, o);
14512 this.items.splice(index, 0, o);
14513 if(typeof key != "undefined" && key != null){
14516 this.keys.splice(index, 0, key);
14517 this.fireEvent("add", index, o, key);
14522 * Removed an item from the collection.
14523 * @param {Object} o The item to remove.
14524 * @return {Object} The item removed.
14526 remove : function(o){
14527 return this.removeAt(this.indexOf(o));
14531 * Remove an item from a specified index in the collection.
14532 * @param {Number} index The index within the collection of the item to remove.
14534 removeAt : function(index){
14535 if(index < this.length && index >= 0){
14537 var o = this.items[index];
14538 this.items.splice(index, 1);
14539 var key = this.keys[index];
14540 if(typeof key != "undefined"){
14541 delete this.map[key];
14543 this.keys.splice(index, 1);
14544 this.fireEvent("remove", o, key);
14549 * Removed an item associated with the passed key fom the collection.
14550 * @param {String} key The key of the item to remove.
14552 removeKey : function(key){
14553 return this.removeAt(this.indexOfKey(key));
14557 * Returns the number of items in the collection.
14558 * @return {Number} the number of items in the collection.
14560 getCount : function(){
14561 return this.length;
14565 * Returns index within the collection of the passed Object.
14566 * @param {Object} o The item to find the index of.
14567 * @return {Number} index of the item.
14569 indexOf : function(o){
14570 if(!this.items.indexOf){
14571 for(var i = 0, len = this.items.length; i < len; i++){
14572 if(this.items[i] == o) {
14578 return this.items.indexOf(o);
14583 * Returns index within the collection of the passed key.
14584 * @param {String} key The key to find the index of.
14585 * @return {Number} index of the key.
14587 indexOfKey : function(key){
14588 if(!this.keys.indexOf){
14589 for(var i = 0, len = this.keys.length; i < len; i++){
14590 if(this.keys[i] == key) {
14596 return this.keys.indexOf(key);
14601 * Returns the item associated with the passed key OR index. Key has priority over index.
14602 * @param {String/Number} key The key or index of the item.
14603 * @return {Object} The item associated with the passed key.
14605 item : function(key){
14606 if (key === 'length') {
14609 var item = typeof this.map[key] != "undefined" ? this.map[key] : this.items[key];
14610 return typeof item != 'function' || this.allowFunctions ? item : null; // for prototype!
14614 * Returns the item at the specified index.
14615 * @param {Number} index The index of the item.
14618 itemAt : function(index){
14619 return this.items[index];
14623 * Returns the item associated with the passed key.
14624 * @param {String/Number} key The key of the item.
14625 * @return {Object} The item associated with the passed key.
14627 key : function(key){
14628 return this.map[key];
14632 * Returns true if the collection contains the passed Object as an item.
14633 * @param {Object} o The Object to look for in the collection.
14634 * @return {Boolean} True if the collection contains the Object as an item.
14636 contains : function(o){
14637 return this.indexOf(o) != -1;
14641 * Returns true if the collection contains the passed Object as a key.
14642 * @param {String} key The key to look for in the collection.
14643 * @return {Boolean} True if the collection contains the Object as a key.
14645 containsKey : function(key){
14646 return typeof this.map[key] != "undefined";
14650 * Removes all items from the collection.
14652 clear : function(){
14657 this.fireEvent("clear");
14661 * Returns the first item in the collection.
14662 * @return {Object} the first item in the collection..
14664 first : function(){
14665 return this.items[0];
14669 * Returns the last item in the collection.
14670 * @return {Object} the last item in the collection..
14673 return this.items[this.length-1];
14676 _sort : function(property, dir, fn){
14677 var dsc = String(dir).toUpperCase() == "DESC" ? -1 : 1;
14678 fn = fn || function(a, b){
14681 var c = [], k = this.keys, items = this.items;
14682 for(var i = 0, len = items.length; i < len; i++){
14683 c[c.length] = {key: k[i], value: items[i], index: i};
14685 c.sort(function(a, b){
14686 var v = fn(a[property], b[property]) * dsc;
14688 v = (a.index < b.index ? -1 : 1);
14692 for(var i = 0, len = c.length; i < len; i++){
14693 items[i] = c[i].value;
14696 this.fireEvent("sort", this);
14700 * Sorts this collection with the passed comparison function
14701 * @param {String} direction (optional) "ASC" or "DESC"
14702 * @param {Function} fn (optional) comparison function
14704 sort : function(dir, fn){
14705 this._sort("value", dir, fn);
14709 * Sorts this collection by keys
14710 * @param {String} direction (optional) "ASC" or "DESC"
14711 * @param {Function} fn (optional) a comparison function (defaults to case insensitive string)
14713 keySort : function(dir, fn){
14714 this._sort("key", dir, fn || function(a, b){
14715 return String(a).toUpperCase()-String(b).toUpperCase();
14720 * Returns a range of items in this collection
14721 * @param {Number} startIndex (optional) defaults to 0
14722 * @param {Number} endIndex (optional) default to the last item
14723 * @return {Array} An array of items
14725 getRange : function(start, end){
14726 var items = this.items;
14727 if(items.length < 1){
14730 start = start || 0;
14731 end = Math.min(typeof end == "undefined" ? this.length-1 : end, this.length-1);
14734 for(var i = start; i <= end; i++) {
14735 r[r.length] = items[i];
14738 for(var i = start; i >= end; i--) {
14739 r[r.length] = items[i];
14746 * Filter the <i>objects</i> in this collection by a specific property.
14747 * Returns a new collection that has been filtered.
14748 * @param {String} property A property on your objects
14749 * @param {String/RegExp} value Either string that the property values
14750 * should start with or a RegExp to test against the property
14751 * @return {MixedCollection} The new filtered collection
14753 filter : function(property, value){
14754 if(!value.exec){ // not a regex
14755 value = String(value);
14756 if(value.length == 0){
14757 return this.clone();
14759 value = new RegExp("^" + Roo.escapeRe(value), "i");
14761 return this.filterBy(function(o){
14762 return o && value.test(o[property]);
14767 * Filter by a function. * Returns a new collection that has been filtered.
14768 * The passed function will be called with each
14769 * object in the collection. If the function returns true, the value is included
14770 * otherwise it is filtered.
14771 * @param {Function} fn The function to be called, it will receive the args o (the object), k (the key)
14772 * @param {Object} scope (optional) The scope of the function (defaults to this)
14773 * @return {MixedCollection} The new filtered collection
14775 filterBy : function(fn, scope){
14776 var r = new Roo.util.MixedCollection();
14777 r.getKey = this.getKey;
14778 var k = this.keys, it = this.items;
14779 for(var i = 0, len = it.length; i < len; i++){
14780 if(fn.call(scope||this, it[i], k[i])){
14781 r.add(k[i], it[i]);
14788 * Creates a duplicate of this collection
14789 * @return {MixedCollection}
14791 clone : function(){
14792 var r = new Roo.util.MixedCollection();
14793 var k = this.keys, it = this.items;
14794 for(var i = 0, len = it.length; i < len; i++){
14795 r.add(k[i], it[i]);
14797 r.getKey = this.getKey;
14802 * Returns the item associated with the passed key or index.
14804 * @param {String/Number} key The key or index of the item.
14805 * @return {Object} The item associated with the passed key.
14807 Roo.util.MixedCollection.prototype.get = Roo.util.MixedCollection.prototype.item;/*
14809 * Ext JS Library 1.1.1
14810 * Copyright(c) 2006-2007, Ext JS, LLC.
14812 * Originally Released Under LGPL - original licence link has changed is not relivant.
14815 * <script type="text/javascript">
14818 * @class Roo.util.JSON
14819 * Modified version of Douglas Crockford"s json.js that doesn"t
14820 * mess with the Object prototype
14821 * http://www.json.org/js.html
14824 Roo.util.JSON = new (function(){
14825 var useHasOwn = {}.hasOwnProperty ? true : false;
14827 // crashes Safari in some instances
14828 //var validRE = /^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/;
14830 var pad = function(n) {
14831 return n < 10 ? "0" + n : n;
14844 var encodeString = function(s){
14845 if (/["\\\x00-\x1f]/.test(s)) {
14846 return '"' + s.replace(/([\x00-\x1f\\"])/g, function(a, b) {
14851 c = b.charCodeAt();
14853 Math.floor(c / 16).toString(16) +
14854 (c % 16).toString(16);
14857 return '"' + s + '"';
14860 var encodeArray = function(o){
14861 var a = ["["], b, i, l = o.length, v;
14862 for (i = 0; i < l; i += 1) {
14864 switch (typeof v) {
14873 a.push(v === null ? "null" : Roo.util.JSON.encode(v));
14881 var encodeDate = function(o){
14882 return '"' + o.getFullYear() + "-" +
14883 pad(o.getMonth() + 1) + "-" +
14884 pad(o.getDate()) + "T" +
14885 pad(o.getHours()) + ":" +
14886 pad(o.getMinutes()) + ":" +
14887 pad(o.getSeconds()) + '"';
14891 * Encodes an Object, Array or other value
14892 * @param {Mixed} o The variable to encode
14893 * @return {String} The JSON string
14895 this.encode = function(o)
14897 // should this be extended to fully wrap stringify..
14899 if(typeof o == "undefined" || o === null){
14901 }else if(o instanceof Array){
14902 return encodeArray(o);
14903 }else if(o instanceof Date){
14904 return encodeDate(o);
14905 }else if(typeof o == "string"){
14906 return encodeString(o);
14907 }else if(typeof o == "number"){
14908 return isFinite(o) ? String(o) : "null";
14909 }else if(typeof o == "boolean"){
14912 var a = ["{"], b, i, v;
14914 if(!useHasOwn || o.hasOwnProperty(i)) {
14916 switch (typeof v) {
14925 a.push(this.encode(i), ":",
14926 v === null ? "null" : this.encode(v));
14937 * Decodes (parses) a JSON string to an object. If the JSON is invalid, this function throws a SyntaxError.
14938 * @param {String} json The JSON string
14939 * @return {Object} The resulting object
14941 this.decode = function(json){
14943 return /** eval:var:json */ eval("(" + json + ')');
14947 * Shorthand for {@link Roo.util.JSON#encode}
14948 * @member Roo encode
14950 Roo.encode = typeof(JSON) != 'undefined' && JSON.stringify ? JSON.stringify : Roo.util.JSON.encode;
14952 * Shorthand for {@link Roo.util.JSON#decode}
14953 * @member Roo decode
14955 Roo.decode = typeof(JSON) != 'undefined' && JSON.parse ? JSON.parse : Roo.util.JSON.decode;
14958 * Ext JS Library 1.1.1
14959 * Copyright(c) 2006-2007, Ext JS, LLC.
14961 * Originally Released Under LGPL - original licence link has changed is not relivant.
14964 * <script type="text/javascript">
14968 * @class Roo.util.Format
14969 * Reusable data formatting functions
14972 Roo.util.Format = function(){
14973 var trimRe = /^\s+|\s+$/g;
14976 * Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length
14977 * @param {String} value The string to truncate
14978 * @param {Number} length The maximum length to allow before truncating
14979 * @return {String} The converted text
14981 ellipsis : function(value, len){
14982 if(value && value.length > len){
14983 return value.substr(0, len-3)+"...";
14989 * Checks a reference and converts it to empty string if it is undefined
14990 * @param {Mixed} value Reference to check
14991 * @return {Mixed} Empty string if converted, otherwise the original value
14993 undef : function(value){
14994 return typeof value != "undefined" ? value : "";
14998 * Convert certain characters (&, <, >, and ') to their HTML character equivalents for literal display in web pages.
14999 * @param {String} value The string to encode
15000 * @return {String} The encoded text
15002 htmlEncode : function(value){
15003 return !value ? value : String(value).replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, """);
15007 * Convert certain characters (&, <, >, and ') from their HTML character equivalents.
15008 * @param {String} value The string to decode
15009 * @return {String} The decoded text
15011 htmlDecode : function(value){
15012 return !value ? value : String(value).replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, '"');
15016 * Trims any whitespace from either side of a string
15017 * @param {String} value The text to trim
15018 * @return {String} The trimmed text
15020 trim : function(value){
15021 return String(value).replace(trimRe, "");
15025 * Returns a substring from within an original string
15026 * @param {String} value The original text
15027 * @param {Number} start The start index of the substring
15028 * @param {Number} length The length of the substring
15029 * @return {String} The substring
15031 substr : function(value, start, length){
15032 return String(value).substr(start, length);
15036 * Converts a string to all lower case letters
15037 * @param {String} value The text to convert
15038 * @return {String} The converted text
15040 lowercase : function(value){
15041 return String(value).toLowerCase();
15045 * Converts a string to all upper case letters
15046 * @param {String} value The text to convert
15047 * @return {String} The converted text
15049 uppercase : function(value){
15050 return String(value).toUpperCase();
15054 * Converts the first character only of a string to upper case
15055 * @param {String} value The text to convert
15056 * @return {String} The converted text
15058 capitalize : function(value){
15059 return !value ? value : value.charAt(0).toUpperCase() + value.substr(1).toLowerCase();
15063 call : function(value, fn){
15064 if(arguments.length > 2){
15065 var args = Array.prototype.slice.call(arguments, 2);
15066 args.unshift(value);
15068 return /** eval:var:value */ eval(fn).apply(window, args);
15070 /** eval:var:value */
15071 return /** eval:var:value */ eval(fn).call(window, value);
15077 * safer version of Math.toFixed..??/
15078 * @param {Number/String} value The numeric value to format
15079 * @param {Number/String} value Decimal places
15080 * @return {String} The formatted currency string
15082 toFixed : function(v, n)
15084 // why not use to fixed - precision is buggered???
15086 return Math.round(v-0);
15088 var fact = Math.pow(10,n+1);
15089 v = (Math.round((v-0)*fact))/fact;
15090 var z = (''+fact).substring(2);
15091 if (v == Math.floor(v)) {
15092 return Math.floor(v) + '.' + z;
15095 // now just padd decimals..
15096 var ps = String(v).split('.');
15097 var fd = (ps[1] + z);
15098 var r = fd.substring(0,n);
15099 var rm = fd.substring(n);
15101 return ps[0] + '.' + r;
15103 r*=1; // turn it into a number;
15105 if (String(r).length != n) {
15108 r = String(r).substring(1); // chop the end off.
15111 return ps[0] + '.' + r;
15116 * Format a number as US currency
15117 * @param {Number/String} value The numeric value to format
15118 * @return {String} The formatted currency string
15120 usMoney : function(v){
15121 return '$' + Roo.util.Format.number(v);
15126 * eventually this should probably emulate php's number_format
15127 * @param {Number/String} value The numeric value to format
15128 * @param {Number} decimals number of decimal places
15129 * @param {String} delimiter for thousands (default comma)
15130 * @return {String} The formatted currency string
15132 number : function(v, decimals, thousandsDelimiter)
15134 // multiply and round.
15135 decimals = typeof(decimals) == 'undefined' ? 2 : decimals;
15136 thousandsDelimiter = typeof(thousandsDelimiter) == 'undefined' ? ',' : thousandsDelimiter;
15138 var mul = Math.pow(10, decimals);
15139 var zero = String(mul).substring(1);
15140 v = (Math.round((v-0)*mul))/mul;
15142 // if it's '0' number.. then
15144 //v = (v == Math.floor(v)) ? v + "." + zero : ((v*10 == Math.floor(v*10)) ? v + "0" : v);
15146 var ps = v.split('.');
15149 var r = /(\d+)(\d{3})/;
15152 if(thousandsDelimiter.length != 0) {
15153 whole = whole.replace(/\B(?=(\d{3})+(?!\d))/g, thousandsDelimiter );
15158 (decimals ? ('.'+ ps[1] + zero.substring(ps[1].length)) : '') :
15159 // does not have decimals
15160 (decimals ? ('.' + zero) : '');
15163 return whole + sub ;
15167 * Parse a value into a formatted date using the specified format pattern.
15168 * @param {Mixed} value The value to format
15169 * @param {String} format (optional) Any valid date format string (defaults to 'm/d/Y')
15170 * @return {String} The formatted date string
15172 date : function(v, format){
15176 if(!(v instanceof Date)){
15177 v = new Date(Date.parse(v));
15179 return v.dateFormat(format || Roo.util.Format.defaults.date);
15183 * Returns a date rendering function that can be reused to apply a date format multiple times efficiently
15184 * @param {String} format Any valid date format string
15185 * @return {Function} The date formatting function
15187 dateRenderer : function(format){
15188 return function(v){
15189 return Roo.util.Format.date(v, format);
15194 stripTagsRE : /<\/?[^>]+>/gi,
15197 * Strips all HTML tags
15198 * @param {Mixed} value The text from which to strip tags
15199 * @return {String} The stripped text
15201 stripTags : function(v){
15202 return !v ? v : String(v).replace(this.stripTagsRE, "");
15206 * Size in Mb,Gb etc.
15207 * @param {Number} value The number to be formated
15208 * @param {number} decimals how many decimal places
15209 * @return {String} the formated string
15211 size : function(value, decimals)
15213 var sizes = ['b', 'k', 'M', 'G', 'T'];
15217 var i = parseInt(Math.floor(Math.log(value) / Math.log(1024)));
15218 return Roo.util.Format.number(value/ Math.pow(1024, i) ,decimals) + sizes[i];
15225 Roo.util.Format.defaults = {
15229 * Ext JS Library 1.1.1
15230 * Copyright(c) 2006-2007, Ext JS, LLC.
15232 * Originally Released Under LGPL - original licence link has changed is not relivant.
15235 * <script type="text/javascript">
15242 * @class Roo.MasterTemplate
15243 * @extends Roo.Template
15244 * Provides a template that can have child templates. The syntax is:
15246 var t = new Roo.MasterTemplate(
15247 '<select name="{name}">',
15248 '<tpl name="options"><option value="{value:trim}">{text:ellipsis(10)}</option></tpl>',
15251 t.add('options', {value: 'foo', text: 'bar'});
15252 // or you can add multiple child elements in one shot
15253 t.addAll('options', [
15254 {value: 'foo', text: 'bar'},
15255 {value: 'foo2', text: 'bar2'},
15256 {value: 'foo3', text: 'bar3'}
15258 // then append, applying the master template values
15259 t.append('my-form', {name: 'my-select'});
15261 * A name attribute for the child template is not required if you have only one child
15262 * template or you want to refer to them by index.
15264 Roo.MasterTemplate = function(){
15265 Roo.MasterTemplate.superclass.constructor.apply(this, arguments);
15266 this.originalHtml = this.html;
15268 var m, re = this.subTemplateRe;
15271 while(m = re.exec(this.html)){
15272 var name = m[1], content = m[2];
15277 tpl : new Roo.Template(content)
15280 st[name] = st[subIndex];
15282 st[subIndex].tpl.compile();
15283 st[subIndex].tpl.call = this.call.createDelegate(this);
15286 this.subCount = subIndex;
15289 Roo.extend(Roo.MasterTemplate, Roo.Template, {
15291 * The regular expression used to match sub templates
15295 subTemplateRe : /<tpl(?:\sname="([\w-]+)")?>((?:.|\n)*?)<\/tpl>/gi,
15298 * Applies the passed values to a child template.
15299 * @param {String/Number} name (optional) The name or index of the child template
15300 * @param {Array/Object} values The values to be applied to the template
15301 * @return {MasterTemplate} this
15303 add : function(name, values){
15304 if(arguments.length == 1){
15305 values = arguments[0];
15308 var s = this.subs[name];
15309 s.buffer[s.buffer.length] = s.tpl.apply(values);
15314 * Applies all the passed values to a child template.
15315 * @param {String/Number} name (optional) The name or index of the child template
15316 * @param {Array} values The values to be applied to the template, this should be an array of objects.
15317 * @param {Boolean} reset (optional) True to reset the template first
15318 * @return {MasterTemplate} this
15320 fill : function(name, values, reset){
15322 if(a.length == 1 || (a.length == 2 && typeof a[1] == "boolean")){
15330 for(var i = 0, len = values.length; i < len; i++){
15331 this.add(name, values[i]);
15337 * Resets the template for reuse
15338 * @return {MasterTemplate} this
15340 reset : function(){
15342 for(var i = 0; i < this.subCount; i++){
15348 applyTemplate : function(values){
15350 var replaceIndex = -1;
15351 this.html = this.originalHtml.replace(this.subTemplateRe, function(m, name){
15352 return s[++replaceIndex].buffer.join("");
15354 return Roo.MasterTemplate.superclass.applyTemplate.call(this, values);
15357 apply : function(){
15358 return this.applyTemplate.apply(this, arguments);
15361 compile : function(){return this;}
15365 * Alias for fill().
15368 Roo.MasterTemplate.prototype.addAll = Roo.MasterTemplate.prototype.fill;
15370 * Creates a template from the passed element's value (display:none textarea, preferred) or innerHTML. e.g.
15371 * var tpl = Roo.MasterTemplate.from('element-id');
15372 * @param {String/HTMLElement} el
15373 * @param {Object} config
15376 Roo.MasterTemplate.from = function(el, config){
15377 el = Roo.getDom(el);
15378 return new Roo.MasterTemplate(el.value || el.innerHTML, config || '');
15381 * Ext JS Library 1.1.1
15382 * Copyright(c) 2006-2007, Ext JS, LLC.
15384 * Originally Released Under LGPL - original licence link has changed is not relivant.
15387 * <script type="text/javascript">
15392 * @class Roo.util.CSS
15393 * Utility class for manipulating CSS rules
15397 Roo.util.CSS = function(){
15399 var doc = document;
15401 var camelRe = /(-[a-z])/gi;
15402 var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); };
15406 * Very simple dynamic creation of stylesheets from a text blob of rules. The text will wrapped in a style
15407 * tag and appended to the HEAD of the document.
15408 * @param {String|Object} cssText The text containing the css rules
15409 * @param {String} id An id to add to the stylesheet for later removal
15410 * @return {StyleSheet}
15412 createStyleSheet : function(cssText, id){
15414 var head = doc.getElementsByTagName("head")[0];
15415 var nrules = doc.createElement("style");
15416 nrules.setAttribute("type", "text/css");
15418 nrules.setAttribute("id", id);
15420 if (typeof(cssText) != 'string') {
15421 // support object maps..
15422 // not sure if this a good idea..
15423 // perhaps it should be merged with the general css handling
15424 // and handle js style props.
15425 var cssTextNew = [];
15426 for(var n in cssText) {
15428 for(var k in cssText[n]) {
15429 citems.push( k + ' : ' +cssText[n][k] + ';' );
15431 cssTextNew.push( n + ' { ' + citems.join(' ') + '} ');
15434 cssText = cssTextNew.join("\n");
15440 head.appendChild(nrules);
15441 ss = nrules.styleSheet;
15442 ss.cssText = cssText;
15445 nrules.appendChild(doc.createTextNode(cssText));
15447 nrules.cssText = cssText;
15449 head.appendChild(nrules);
15450 ss = nrules.styleSheet ? nrules.styleSheet : (nrules.sheet || doc.styleSheets[doc.styleSheets.length-1]);
15452 this.cacheStyleSheet(ss);
15457 * Removes a style or link tag by id
15458 * @param {String} id The id of the tag
15460 removeStyleSheet : function(id){
15461 var existing = doc.getElementById(id);
15463 existing.parentNode.removeChild(existing);
15468 * Dynamically swaps an existing stylesheet reference for a new one
15469 * @param {String} id The id of an existing link tag to remove
15470 * @param {String} url The href of the new stylesheet to include
15472 swapStyleSheet : function(id, url){
15473 this.removeStyleSheet(id);
15474 var ss = doc.createElement("link");
15475 ss.setAttribute("rel", "stylesheet");
15476 ss.setAttribute("type", "text/css");
15477 ss.setAttribute("id", id);
15478 ss.setAttribute("href", url);
15479 doc.getElementsByTagName("head")[0].appendChild(ss);
15483 * Refresh the rule cache if you have dynamically added stylesheets
15484 * @return {Object} An object (hash) of rules indexed by selector
15486 refreshCache : function(){
15487 return this.getRules(true);
15491 cacheStyleSheet : function(stylesheet){
15495 try{// try catch for cross domain access issue
15496 var ssRules = stylesheet.cssRules || stylesheet.rules;
15497 for(var j = ssRules.length-1; j >= 0; --j){
15498 rules[ssRules[j].selectorText] = ssRules[j];
15504 * Gets all css rules for the document
15505 * @param {Boolean} refreshCache true to refresh the internal cache
15506 * @return {Object} An object (hash) of rules indexed by selector
15508 getRules : function(refreshCache){
15509 if(rules == null || refreshCache){
15511 var ds = doc.styleSheets;
15512 for(var i =0, len = ds.length; i < len; i++){
15514 this.cacheStyleSheet(ds[i]);
15522 * Gets an an individual CSS rule by selector(s)
15523 * @param {String/Array} selector The CSS selector or an array of selectors to try. The first selector that is found is returned.
15524 * @param {Boolean} refreshCache true to refresh the internal cache if you have recently updated any rules or added styles dynamically
15525 * @return {CSSRule} The CSS rule or null if one is not found
15527 getRule : function(selector, refreshCache){
15528 var rs = this.getRules(refreshCache);
15529 if(!(selector instanceof Array)){
15530 return rs[selector];
15532 for(var i = 0; i < selector.length; i++){
15533 if(rs[selector[i]]){
15534 return rs[selector[i]];
15542 * Updates a rule property
15543 * @param {String/Array} selector If it's an array it tries each selector until it finds one. Stops immediately once one is found.
15544 * @param {String} property The css property
15545 * @param {String} value The new value for the property
15546 * @return {Boolean} true If a rule was found and updated
15548 updateRule : function(selector, property, value){
15549 if(!(selector instanceof Array)){
15550 var rule = this.getRule(selector);
15552 rule.style[property.replace(camelRe, camelFn)] = value;
15556 for(var i = 0; i < selector.length; i++){
15557 if(this.updateRule(selector[i], property, value)){
15567 * Ext JS Library 1.1.1
15568 * Copyright(c) 2006-2007, Ext JS, LLC.
15570 * Originally Released Under LGPL - original licence link has changed is not relivant.
15573 * <script type="text/javascript">
15579 * @class Roo.util.ClickRepeater
15580 * @extends Roo.util.Observable
15582 * A wrapper class which can be applied to any element. Fires a "click" event while the
15583 * mouse is pressed. The interval between firings may be specified in the config but
15584 * defaults to 10 milliseconds.
15586 * Optionally, a CSS class may be applied to the element during the time it is pressed.
15588 * @cfg {String/HTMLElement/Element} el The element to act as a button.
15589 * @cfg {Number} delay The initial delay before the repeating event begins firing.
15590 * Similar to an autorepeat key delay.
15591 * @cfg {Number} interval The interval between firings of the "click" event. Default 10 ms.
15592 * @cfg {String} pressClass A CSS class name to be applied to the element while pressed.
15593 * @cfg {Boolean} accelerate True if autorepeating should start slowly and accelerate.
15594 * "interval" and "delay" are ignored. "immediate" is honored.
15595 * @cfg {Boolean} preventDefault True to prevent the default click event
15596 * @cfg {Boolean} stopDefault True to stop the default click event
15599 * 2007-02-02 jvs Original code contributed by Nige "Animal" White
15600 * 2007-02-02 jvs Renamed to ClickRepeater
15601 * 2007-02-03 jvs Modifications for FF Mac and Safari
15604 * @param {String/HTMLElement/Element} el The element to listen on
15605 * @param {Object} config
15607 Roo.util.ClickRepeater = function(el, config)
15609 this.el = Roo.get(el);
15610 this.el.unselectable();
15612 Roo.apply(this, config);
15617 * Fires when the mouse button is depressed.
15618 * @param {Roo.util.ClickRepeater} this
15620 "mousedown" : true,
15623 * Fires on a specified interval during the time the element is pressed.
15624 * @param {Roo.util.ClickRepeater} this
15629 * Fires when the mouse key is released.
15630 * @param {Roo.util.ClickRepeater} this
15635 this.el.on("mousedown", this.handleMouseDown, this);
15636 if(this.preventDefault || this.stopDefault){
15637 this.el.on("click", function(e){
15638 if(this.preventDefault){
15639 e.preventDefault();
15641 if(this.stopDefault){
15647 // allow inline handler
15649 this.on("click", this.handler, this.scope || this);
15652 Roo.util.ClickRepeater.superclass.constructor.call(this);
15655 Roo.extend(Roo.util.ClickRepeater, Roo.util.Observable, {
15658 preventDefault : true,
15659 stopDefault : false,
15663 handleMouseDown : function(){
15664 clearTimeout(this.timer);
15666 if(this.pressClass){
15667 this.el.addClass(this.pressClass);
15669 this.mousedownTime = new Date();
15671 Roo.get(document).on("mouseup", this.handleMouseUp, this);
15672 this.el.on("mouseout", this.handleMouseOut, this);
15674 this.fireEvent("mousedown", this);
15675 this.fireEvent("click", this);
15677 this.timer = this.click.defer(this.delay || this.interval, this);
15681 click : function(){
15682 this.fireEvent("click", this);
15683 this.timer = this.click.defer(this.getInterval(), this);
15687 getInterval: function(){
15688 if(!this.accelerate){
15689 return this.interval;
15691 var pressTime = this.mousedownTime.getElapsed();
15692 if(pressTime < 500){
15694 }else if(pressTime < 1700){
15696 }else if(pressTime < 2600){
15698 }else if(pressTime < 3500){
15700 }else if(pressTime < 4400){
15702 }else if(pressTime < 5300){
15704 }else if(pressTime < 6200){
15712 handleMouseOut : function(){
15713 clearTimeout(this.timer);
15714 if(this.pressClass){
15715 this.el.removeClass(this.pressClass);
15717 this.el.on("mouseover", this.handleMouseReturn, this);
15721 handleMouseReturn : function(){
15722 this.el.un("mouseover", this.handleMouseReturn);
15723 if(this.pressClass){
15724 this.el.addClass(this.pressClass);
15730 handleMouseUp : function(){
15731 clearTimeout(this.timer);
15732 this.el.un("mouseover", this.handleMouseReturn);
15733 this.el.un("mouseout", this.handleMouseOut);
15734 Roo.get(document).un("mouseup", this.handleMouseUp);
15735 this.el.removeClass(this.pressClass);
15736 this.fireEvent("mouseup", this);
15739 * @class Roo.util.Clipboard
15745 Roo.util.Clipboard = {
15747 * Writes a string to the clipboard - using the Clipboard API if https, otherwise using text area.
15748 * @param {String} text to copy to clipboard
15750 write : function(text) {
15751 // navigator clipboard api needs a secure context (https)
15752 if (navigator.clipboard && window.isSecureContext) {
15753 // navigator clipboard api method'
15754 navigator.clipboard.writeText(text);
15757 // text area method
15758 var ta = document.createElement("textarea");
15760 // make the textarea out of viewport
15761 ta.style.position = "fixed";
15762 ta.style.left = "-999999px";
15763 ta.style.top = "-999999px";
15764 document.body.appendChild(ta);
15767 document.execCommand('copy');
15777 * Ext JS Library 1.1.1
15778 * Copyright(c) 2006-2007, Ext JS, LLC.
15780 * Originally Released Under LGPL - original licence link has changed is not relivant.
15783 * <script type="text/javascript">
15788 * @class Roo.KeyNav
15789 * <p>Provides a convenient wrapper for normalized keyboard navigation. KeyNav allows you to bind
15790 * navigation keys to function calls that will get called when the keys are pressed, providing an easy
15791 * way to implement custom navigation schemes for any UI component.</p>
15792 * <p>The following are all of the possible keys that can be implemented: enter, left, right, up, down, tab, esc,
15793 * pageUp, pageDown, del, home, end. Usage:</p>
15795 var nav = new Roo.KeyNav("my-element", {
15796 "left" : function(e){
15797 this.moveLeft(e.ctrlKey);
15799 "right" : function(e){
15800 this.moveRight(e.ctrlKey);
15802 "enter" : function(e){
15809 * @param {String/HTMLElement/Roo.Element} el The element to bind to
15810 * @param {Object} config The config
15812 Roo.KeyNav = function(el, config){
15813 this.el = Roo.get(el);
15814 Roo.apply(this, config);
15815 if(!this.disabled){
15816 this.disabled = true;
15821 Roo.KeyNav.prototype = {
15823 * @cfg {Boolean} disabled
15824 * True to disable this KeyNav instance (defaults to false)
15828 * @cfg {String} defaultEventAction
15829 * The method to call on the {@link Roo.EventObject} after this KeyNav intercepts a key. Valid values are
15830 * {@link Roo.EventObject#stopEvent}, {@link Roo.EventObject#preventDefault} and
15831 * {@link Roo.EventObject#stopPropagation} (defaults to 'stopEvent')
15833 defaultEventAction: "stopEvent",
15835 * @cfg {Boolean} forceKeyDown
15836 * Handle the keydown event instead of keypress (defaults to false). KeyNav automatically does this for IE since
15837 * IE does not propagate special keys on keypress, but setting this to true will force other browsers to also
15838 * handle keydown instead of keypress.
15840 forceKeyDown : false,
15843 prepareEvent : function(e){
15844 var k = e.getKey();
15845 var h = this.keyToHandler[k];
15846 //if(h && this[h]){
15847 // e.stopPropagation();
15849 if(Roo.isSafari && h && k >= 37 && k <= 40){
15855 relay : function(e){
15856 var k = e.getKey();
15857 var h = this.keyToHandler[k];
15859 if(this.doRelay(e, this[h], h) !== true){
15860 e[this.defaultEventAction]();
15866 doRelay : function(e, h, hname){
15867 return h.call(this.scope || this, e);
15870 // possible handlers
15884 // quick lookup hash
15901 * Enable this KeyNav
15903 enable: function(){
15905 // ie won't do special keys on keypress, no one else will repeat keys with keydown
15906 // the EventObject will normalize Safari automatically
15907 if(this.forceKeyDown || Roo.isIE || Roo.isAir){
15908 this.el.on("keydown", this.relay, this);
15910 this.el.on("keydown", this.prepareEvent, this);
15911 this.el.on("keypress", this.relay, this);
15913 this.disabled = false;
15918 * Disable this KeyNav
15920 disable: function(){
15921 if(!this.disabled){
15922 if(this.forceKeyDown || Roo.isIE || Roo.isAir){
15923 this.el.un("keydown", this.relay);
15925 this.el.un("keydown", this.prepareEvent);
15926 this.el.un("keypress", this.relay);
15928 this.disabled = true;
15933 * Ext JS Library 1.1.1
15934 * Copyright(c) 2006-2007, Ext JS, LLC.
15936 * Originally Released Under LGPL - original licence link has changed is not relivant.
15939 * <script type="text/javascript">
15944 * @class Roo.KeyMap
15945 * Handles mapping keys to actions for an element. One key map can be used for multiple actions.
15946 * The constructor accepts the same config object as defined by {@link #addBinding}.
15947 * If you bind a callback function to a KeyMap, anytime the KeyMap handles an expected key
15948 * combination it will call the function with this signature (if the match is a multi-key
15949 * combination the callback will still be called only once): (String key, Roo.EventObject e)
15950 * A KeyMap can also handle a string representation of keys.<br />
15953 // map one key by key code
15954 var map = new Roo.KeyMap("my-element", {
15955 key: 13, // or Roo.EventObject.ENTER
15960 // map multiple keys to one action by string
15961 var map = new Roo.KeyMap("my-element", {
15967 // map multiple keys to multiple actions by strings and array of codes
15968 var map = new Roo.KeyMap("my-element", [
15971 fn: function(){ alert("Return was pressed"); }
15974 fn: function(){ alert('a, b or c was pressed'); }
15979 fn: function(){ alert('Control + shift + tab was pressed.'); }
15983 * <b>Note: A KeyMap starts enabled</b>
15985 * @param {String/HTMLElement/Roo.Element} el The element to bind to
15986 * @param {Object} config The config (see {@link #addBinding})
15987 * @param {String} eventName (optional) The event to bind to (defaults to "keydown")
15989 Roo.KeyMap = function(el, config, eventName){
15990 this.el = Roo.get(el);
15991 this.eventName = eventName || "keydown";
15992 this.bindings = [];
15994 this.addBinding(config);
15999 Roo.KeyMap.prototype = {
16001 * True to stop the event from bubbling and prevent the default browser action if the
16002 * key was handled by the KeyMap (defaults to false)
16008 * Add a new binding to this KeyMap. The following config object properties are supported:
16010 Property Type Description
16011 ---------- --------------- ----------------------------------------------------------------------
16012 key String/Array A single keycode or an array of keycodes to handle
16013 shift Boolean True to handle key only when shift is pressed (defaults to false)
16014 ctrl Boolean True to handle key only when ctrl is pressed (defaults to false)
16015 alt Boolean True to handle key only when alt is pressed (defaults to false)
16016 fn Function The function to call when KeyMap finds the expected key combination
16017 scope Object The scope of the callback function
16023 var map = new Roo.KeyMap(document, {
16024 key: Roo.EventObject.ENTER,
16029 //Add a new binding to the existing KeyMap later
16037 * @param {Object/Array} config A single KeyMap config or an array of configs
16039 addBinding : function(config){
16040 if(config instanceof Array){
16041 for(var i = 0, len = config.length; i < len; i++){
16042 this.addBinding(config[i]);
16046 var keyCode = config.key,
16047 shift = config.shift,
16048 ctrl = config.ctrl,
16051 scope = config.scope;
16052 if(typeof keyCode == "string"){
16054 var keyString = keyCode.toUpperCase();
16055 for(var j = 0, len = keyString.length; j < len; j++){
16056 ks.push(keyString.charCodeAt(j));
16060 var keyArray = keyCode instanceof Array;
16061 var handler = function(e){
16062 if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) && (!alt || e.altKey)){
16063 var k = e.getKey();
16065 for(var i = 0, len = keyCode.length; i < len; i++){
16066 if(keyCode[i] == k){
16067 if(this.stopEvent){
16070 fn.call(scope || window, k, e);
16076 if(this.stopEvent){
16079 fn.call(scope || window, k, e);
16084 this.bindings.push(handler);
16088 * Shorthand for adding a single key listener
16089 * @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the
16090 * following options:
16091 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
16092 * @param {Function} fn The function to call
16093 * @param {Object} scope (optional) The scope of the function
16095 on : function(key, fn, scope){
16096 var keyCode, shift, ctrl, alt;
16097 if(typeof key == "object" && !(key instanceof Array)){
16116 handleKeyDown : function(e){
16117 if(this.enabled){ //just in case
16118 var b = this.bindings;
16119 for(var i = 0, len = b.length; i < len; i++){
16120 b[i].call(this, e);
16126 * Returns true if this KeyMap is enabled
16127 * @return {Boolean}
16129 isEnabled : function(){
16130 return this.enabled;
16134 * Enables this KeyMap
16136 enable: function(){
16138 this.el.on(this.eventName, this.handleKeyDown, this);
16139 this.enabled = true;
16144 * Disable this KeyMap
16146 disable: function(){
16148 this.el.removeListener(this.eventName, this.handleKeyDown, this);
16149 this.enabled = false;
16154 * Ext JS Library 1.1.1
16155 * Copyright(c) 2006-2007, Ext JS, LLC.
16157 * Originally Released Under LGPL - original licence link has changed is not relivant.
16160 * <script type="text/javascript">
16165 * @class Roo.util.TextMetrics
16166 * Provides precise pixel measurements for blocks of text so that you can determine exactly how high and
16167 * wide, in pixels, a given block of text will be.
16170 Roo.util.TextMetrics = function(){
16174 * Measures the size of the specified text
16175 * @param {String/HTMLElement} el The element, dom node or id from which to copy existing CSS styles
16176 * that can affect the size of the rendered text
16177 * @param {String} text The text to measure
16178 * @param {Number} fixedWidth (optional) If the text will be multiline, you have to set a fixed width
16179 * in order to accurately measure the text height
16180 * @return {Object} An object containing the text's size {width: (width), height: (height)}
16182 measure : function(el, text, fixedWidth){
16184 shared = Roo.util.TextMetrics.Instance(el, fixedWidth);
16187 shared.setFixedWidth(fixedWidth || 'auto');
16188 return shared.getSize(text);
16192 * Return a unique TextMetrics instance that can be bound directly to an element and reused. This reduces
16193 * the overhead of multiple calls to initialize the style properties on each measurement.
16194 * @param {String/HTMLElement} el The element, dom node or id that the instance will be bound to
16195 * @param {Number} fixedWidth (optional) If the text will be multiline, you have to set a fixed width
16196 * in order to accurately measure the text height
16197 * @return {Roo.util.TextMetrics.Instance} instance The new instance
16199 createInstance : function(el, fixedWidth){
16200 return Roo.util.TextMetrics.Instance(el, fixedWidth);
16206 * @class Roo.util.TextMetrics.Instance
16207 * Instance of TextMetrics Calcuation
16209 * Create a new TextMetrics Instance
16210 * @param {Object} bindto
16211 * @param {Boolean} fixedWidth
16214 Roo.util.TextMetrics.Instance = function(bindTo, fixedWidth)
16216 var ml = new Roo.Element(document.createElement('div'));
16217 document.body.appendChild(ml.dom);
16218 ml.position('absolute');
16219 ml.setLeftTop(-1000, -1000);
16223 ml.setWidth(fixedWidth);
16228 * Returns the size of the specified text based on the internal element's style and width properties
16229 * @param {String} text The text to measure
16230 * @return {Object} An object containing the text's size {width: (width), height: (height)}
16232 getSize : function(text){
16234 var s = ml.getSize();
16240 * Binds this TextMetrics instance to an element from which to copy existing CSS styles
16241 * that can affect the size of the rendered text
16242 * @param {String/HTMLElement} el The element, dom node or id
16244 bind : function(el){
16246 Roo.fly(el).getStyles('font-size','font-style', 'font-weight', 'font-family','line-height')
16251 * Sets a fixed width on the internal measurement element. If the text will be multiline, you have
16252 * to set a fixed width in order to accurately measure the text height.
16253 * @param {Number} width The width to set on the element
16255 setFixedWidth : function(width){
16256 ml.setWidth(width);
16260 * Returns the measured width of the specified text
16261 * @param {String} text The text to measure
16262 * @return {Number} width The width in pixels
16264 getWidth : function(text){
16265 ml.dom.style.width = 'auto';
16266 return this.getSize(text).width;
16270 * Returns the measured height of the specified text. For multiline text, be sure to call
16271 * {@link #setFixedWidth} if necessary.
16272 * @param {String} text The text to measure
16273 * @return {Number} height The height in pixels
16275 getHeight : function(text){
16276 return this.getSize(text).height;
16280 instance.bind(bindTo);
16285 // backwards compat
16286 Roo.Element.measureText = Roo.util.TextMetrics.measure;/*
16288 * Ext JS Library 1.1.1
16289 * Copyright(c) 2006-2007, Ext JS, LLC.
16291 * Originally Released Under LGPL - original licence link has changed is not relivant.
16294 * <script type="text/javascript">
16298 * @class Roo.state.Provider
16299 * Abstract base class for state provider implementations. This class provides methods
16300 * for encoding and decoding <b>typed</b> variables including dates and defines the
16301 * Provider interface.
16303 Roo.state.Provider = function(){
16305 * @event statechange
16306 * Fires when a state change occurs.
16307 * @param {Provider} this This state provider
16308 * @param {String} key The state key which was changed
16309 * @param {String} value The encoded value for the state
16312 "statechange": true
16315 Roo.state.Provider.superclass.constructor.call(this);
16317 Roo.extend(Roo.state.Provider, Roo.util.Observable, {
16319 * Returns the current value for a key
16320 * @param {String} name The key name
16321 * @param {Mixed} defaultValue A default value to return if the key's value is not found
16322 * @return {Mixed} The state data
16324 get : function(name, defaultValue){
16325 return typeof this.state[name] == "undefined" ?
16326 defaultValue : this.state[name];
16330 * Clears a value from the state
16331 * @param {String} name The key name
16333 clear : function(name){
16334 delete this.state[name];
16335 this.fireEvent("statechange", this, name, null);
16339 * Sets the value for a key
16340 * @param {String} name The key name
16341 * @param {Mixed} value The value to set
16343 set : function(name, value){
16344 this.state[name] = value;
16345 this.fireEvent("statechange", this, name, value);
16349 * Decodes a string previously encoded with {@link #encodeValue}.
16350 * @param {String} value The value to decode
16351 * @return {Mixed} The decoded value
16353 decodeValue : function(cookie){
16354 var re = /^(a|n|d|b|s|o)\:(.*)$/;
16355 var matches = re.exec(unescape(cookie));
16356 if(!matches || !matches[1]) {
16357 return; // non state cookie
16359 var type = matches[1];
16360 var v = matches[2];
16363 return parseFloat(v);
16365 return new Date(Date.parse(v));
16370 var values = v.split("^");
16371 for(var i = 0, len = values.length; i < len; i++){
16372 all.push(this.decodeValue(values[i]));
16377 var values = v.split("^");
16378 for(var i = 0, len = values.length; i < len; i++){
16379 var kv = values[i].split("=");
16380 all[kv[0]] = this.decodeValue(kv[1]);
16389 * Encodes a value including type information. Decode with {@link #decodeValue}.
16390 * @param {Mixed} value The value to encode
16391 * @return {String} The encoded value
16393 encodeValue : function(v){
16395 if(typeof v == "number"){
16397 }else if(typeof v == "boolean"){
16398 enc = "b:" + (v ? "1" : "0");
16399 }else if(v instanceof Date){
16400 enc = "d:" + v.toGMTString();
16401 }else if(v instanceof Array){
16403 for(var i = 0, len = v.length; i < len; i++){
16404 flat += this.encodeValue(v[i]);
16410 }else if(typeof v == "object"){
16413 if(typeof v[key] != "function"){
16414 flat += key + "=" + this.encodeValue(v[key]) + "^";
16417 enc = "o:" + flat.substring(0, flat.length-1);
16421 return escape(enc);
16427 * Ext JS Library 1.1.1
16428 * Copyright(c) 2006-2007, Ext JS, LLC.
16430 * Originally Released Under LGPL - original licence link has changed is not relivant.
16433 * <script type="text/javascript">
16436 * @class Roo.state.Manager
16437 * This is the global state manager. By default all components that are "state aware" check this class
16438 * for state information if you don't pass them a custom state provider. In order for this class
16439 * to be useful, it must be initialized with a provider when your application initializes.
16441 // in your initialization function
16443 Roo.state.Manager.setProvider(new Roo.state.CookieProvider());
16445 // supposed you have a {@link Roo.BorderLayout}
16446 var layout = new Roo.BorderLayout(...);
16447 layout.restoreState();
16448 // or a {Roo.BasicDialog}
16449 var dialog = new Roo.BasicDialog(...);
16450 dialog.restoreState();
16454 Roo.state.Manager = function(){
16455 var provider = new Roo.state.Provider();
16459 * Configures the default state provider for your application
16460 * @param {Provider} stateProvider The state provider to set
16462 setProvider : function(stateProvider){
16463 provider = stateProvider;
16467 * Returns the current value for a key
16468 * @param {String} name The key name
16469 * @param {Mixed} defaultValue The default value to return if the key lookup does not match
16470 * @return {Mixed} The state data
16472 get : function(key, defaultValue){
16473 return provider.get(key, defaultValue);
16477 * Sets the value for a key
16478 * @param {String} name The key name
16479 * @param {Mixed} value The state data
16481 set : function(key, value){
16482 provider.set(key, value);
16486 * Clears a value from the state
16487 * @param {String} name The key name
16489 clear : function(key){
16490 provider.clear(key);
16494 * Gets the currently configured state provider
16495 * @return {Provider} The state provider
16497 getProvider : function(){
16504 * Ext JS Library 1.1.1
16505 * Copyright(c) 2006-2007, Ext JS, LLC.
16507 * Originally Released Under LGPL - original licence link has changed is not relivant.
16510 * <script type="text/javascript">
16513 * @class Roo.state.CookieProvider
16514 * @extends Roo.state.Provider
16515 * The default Provider implementation which saves state via cookies.
16518 var cp = new Roo.state.CookieProvider({
16520 expires: new Date(new Date().getTime()+(1000*60*60*24*30)); //30 days
16521 domain: "roojs.com"
16523 Roo.state.Manager.setProvider(cp);
16525 * @cfg {String} path The path for which the cookie is active (defaults to root '/' which makes it active for all pages in the site)
16526 * @cfg {Date} expires The cookie expiration date (defaults to 7 days from now)
16527 * @cfg {String} domain The domain to save the cookie for. Note that you cannot specify a different domain than
16528 * your page is on, but you can specify a sub-domain, or simply the domain itself like 'roojs.com' to include
16529 * all sub-domains if you need to access cookies across different sub-domains (defaults to null which uses the same
16530 * domain the page is running on including the 'www' like 'www.roojs.com')
16531 * @cfg {Boolean} secure True if the site is using SSL (defaults to false)
16533 * Create a new CookieProvider
16534 * @param {Object} config The configuration object
16536 Roo.state.CookieProvider = function(config){
16537 Roo.state.CookieProvider.superclass.constructor.call(this);
16539 this.expires = new Date(new Date().getTime()+(1000*60*60*24*7)); //7 days
16540 this.domain = null;
16541 this.secure = false;
16542 Roo.apply(this, config);
16543 this.state = this.readCookies();
16546 Roo.extend(Roo.state.CookieProvider, Roo.state.Provider, {
16548 set : function(name, value){
16549 if(typeof value == "undefined" || value === null){
16553 this.setCookie(name, value);
16554 Roo.state.CookieProvider.superclass.set.call(this, name, value);
16558 clear : function(name){
16559 this.clearCookie(name);
16560 Roo.state.CookieProvider.superclass.clear.call(this, name);
16564 readCookies : function(){
16566 var c = document.cookie + ";";
16567 var re = /\s?(.*?)=(.*?);/g;
16569 while((matches = re.exec(c)) != null){
16570 var name = matches[1];
16571 var value = matches[2];
16572 if(name && name.substring(0,3) == "ys-"){
16573 cookies[name.substr(3)] = this.decodeValue(value);
16580 setCookie : function(name, value){
16581 document.cookie = "ys-"+ name + "=" + this.encodeValue(value) +
16582 ((this.expires == null) ? "" : ("; expires=" + this.expires.toGMTString())) +
16583 ((this.path == null) ? "" : ("; path=" + this.path)) +
16584 ((this.domain == null) ? "" : ("; domain=" + this.domain)) +
16585 ((this.secure == true) ? "; secure" : "");
16589 clearCookie : function(name){
16590 document.cookie = "ys-" + name + "=null; expires=Thu, 01-Jan-70 00:00:01 GMT" +
16591 ((this.path == null) ? "" : ("; path=" + this.path)) +
16592 ((this.domain == null) ? "" : ("; domain=" + this.domain)) +
16593 ((this.secure == true) ? "; secure" : "");
16597 * Ext JS Library 1.1.1
16598 * Copyright(c) 2006-2007, Ext JS, LLC.
16600 * Originally Released Under LGPL - original licence link has changed is not relivant.
16603 * <script type="text/javascript">
16608 * @class Roo.ComponentMgr
16609 * Provides a common registry of all components on a page so that they can be easily accessed by component id (see {@link Roo.getCmp}).
16612 Roo.ComponentMgr = function(){
16613 var all = new Roo.util.MixedCollection();
16617 * Registers a component.
16618 * @param {Roo.Component} c The component
16620 register : function(c){
16625 * Unregisters a component.
16626 * @param {Roo.Component} c The component
16628 unregister : function(c){
16633 * Returns a component by id
16634 * @param {String} id The component id
16636 get : function(id){
16637 return all.get(id);
16641 * Registers a function that will be called when a specified component is added to ComponentMgr
16642 * @param {String} id The component id
16643 * @param {Funtction} fn The callback function
16644 * @param {Object} scope The scope of the callback
16646 onAvailable : function(id, fn, scope){
16647 all.on("add", function(index, o){
16649 fn.call(scope || o, o);
16650 all.un("add", fn, scope);
16657 * Ext JS Library 1.1.1
16658 * Copyright(c) 2006-2007, Ext JS, LLC.
16660 * Originally Released Under LGPL - original licence link has changed is not relivant.
16663 * <script type="text/javascript">
16667 * @class Roo.Component
16668 * @extends Roo.util.Observable
16669 * Base class for all major Roo components. All subclasses of Component can automatically participate in the standard
16670 * Roo component lifecycle of creation, rendering and destruction. They also have automatic support for basic hide/show
16671 * and enable/disable behavior. Component allows any subclass to be lazy-rendered into any {@link Roo.Container} and
16672 * to be automatically registered with the {@link Roo.ComponentMgr} so that it can be referenced at any time via {@link Roo.getCmp}.
16673 * All visual components (widgets) that require rendering into a layout should subclass Component.
16675 * @param {Roo.Element/String/Object} config The configuration options. If an element is passed, it is set as the internal
16676 * 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
16677 * and is used as the component id. Otherwise, it is assumed to be a standard config object and is applied to the component.
16679 Roo.Component = function(config){
16680 config = config || {};
16681 if(config.tagName || config.dom || typeof config == "string"){ // element object
16682 config = {el: config, id: config.id || config};
16684 this.initialConfig = config;
16686 Roo.apply(this, config);
16690 * Fires after the component is disabled.
16691 * @param {Roo.Component} this
16696 * Fires after the component is enabled.
16697 * @param {Roo.Component} this
16701 * @event beforeshow
16702 * Fires before the component is shown. Return false to stop the show.
16703 * @param {Roo.Component} this
16708 * Fires after the component is shown.
16709 * @param {Roo.Component} this
16713 * @event beforehide
16714 * Fires before the component is hidden. Return false to stop the hide.
16715 * @param {Roo.Component} this
16720 * Fires after the component is hidden.
16721 * @param {Roo.Component} this
16725 * @event beforerender
16726 * Fires before the component is rendered. Return false to stop the render.
16727 * @param {Roo.Component} this
16729 beforerender : true,
16732 * Fires after the component is rendered.
16733 * @param {Roo.Component} this
16737 * @event beforedestroy
16738 * Fires before the component is destroyed. Return false to stop the destroy.
16739 * @param {Roo.Component} this
16741 beforedestroy : true,
16744 * Fires after the component is destroyed.
16745 * @param {Roo.Component} this
16750 this.id = "roo-comp-" + (++Roo.Component.AUTO_ID);
16752 Roo.ComponentMgr.register(this);
16753 Roo.Component.superclass.constructor.call(this);
16754 this.initComponent();
16755 if(this.renderTo){ // not supported by all components yet. use at your own risk!
16756 this.render(this.renderTo);
16757 delete this.renderTo;
16762 Roo.Component.AUTO_ID = 1000;
16764 Roo.extend(Roo.Component, Roo.util.Observable, {
16766 * @scope Roo.Component.prototype
16768 * true if this component is hidden. Read-only.
16773 * true if this component is disabled. Read-only.
16778 * true if this component has been rendered. Read-only.
16782 /** @cfg {String} disableClass
16783 * CSS class added to the component when it is disabled (defaults to "x-item-disabled").
16785 disabledClass : "x-item-disabled",
16786 /** @cfg {Boolean} allowDomMove
16787 * Whether the component can move the Dom node when rendering (defaults to true).
16789 allowDomMove : true,
16790 /** @cfg {String} hideMode (display|visibility)
16791 * How this component should hidden. Supported values are
16792 * "visibility" (css visibility), "offsets" (negative offset position) and
16793 * "display" (css display) - defaults to "display".
16795 hideMode: 'display',
16798 ctype : "Roo.Component",
16801 * @cfg {String} actionMode
16802 * which property holds the element that used for hide() / show() / disable() / enable()
16803 * default is 'el' for forms you probably want to set this to fieldEl
16808 getActionEl : function(){
16809 return this[this.actionMode];
16812 initComponent : Roo.emptyFn,
16814 * If this is a lazy rendering component, render it to its container element.
16815 * @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.
16817 render : function(container, position){
16823 if(this.fireEvent("beforerender", this) === false){
16827 if(!container && this.el){
16828 this.el = Roo.get(this.el);
16829 container = this.el.dom.parentNode;
16830 this.allowDomMove = false;
16832 this.container = Roo.get(container);
16833 this.rendered = true;
16834 if(position !== undefined){
16835 if(typeof position == 'number'){
16836 position = this.container.dom.childNodes[position];
16838 position = Roo.getDom(position);
16841 this.onRender(this.container, position || null);
16843 this.el.addClass(this.cls);
16847 this.el.applyStyles(this.style);
16850 this.fireEvent("render", this);
16851 this.afterRender(this.container);
16864 // default function is not really useful
16865 onRender : function(ct, position){
16867 this.el = Roo.get(this.el);
16868 if(this.allowDomMove !== false){
16869 ct.dom.insertBefore(this.el.dom, position);
16875 getAutoCreate : function(){
16876 var cfg = typeof this.autoCreate == "object" ?
16877 this.autoCreate : Roo.apply({}, this.defaultAutoCreate);
16878 if(this.id && !cfg.id){
16885 afterRender : Roo.emptyFn,
16888 * Destroys this component by purging any event listeners, removing the component's element from the DOM,
16889 * removing the component from its {@link Roo.Container} (if applicable) and unregistering it from {@link Roo.ComponentMgr}.
16891 destroy : function(){
16892 if(this.fireEvent("beforedestroy", this) !== false){
16893 this.purgeListeners();
16894 this.beforeDestroy();
16896 this.el.removeAllListeners();
16898 if(this.actionMode == "container"){
16899 this.container.remove();
16903 Roo.ComponentMgr.unregister(this);
16904 this.fireEvent("destroy", this);
16909 beforeDestroy : function(){
16914 onDestroy : function(){
16919 * Returns the underlying {@link Roo.Element}.
16920 * @return {Roo.Element} The element
16922 getEl : function(){
16927 * Returns the id of this component.
16930 getId : function(){
16935 * Try to focus this component.
16936 * @param {Boolean} selectText True to also select the text in this component (if applicable)
16937 * @return {Roo.Component} this
16939 focus : function(selectText){
16942 if(selectText === true){
16943 this.el.dom.select();
16958 * Disable this component.
16959 * @return {Roo.Component} this
16961 disable : function(){
16965 this.disabled = true;
16966 this.fireEvent("disable", this);
16971 onDisable : function(){
16972 this.getActionEl().addClass(this.disabledClass);
16973 this.el.dom.disabled = true;
16977 * Enable this component.
16978 * @return {Roo.Component} this
16980 enable : function(){
16984 this.disabled = false;
16985 this.fireEvent("enable", this);
16990 onEnable : function(){
16991 this.getActionEl().removeClass(this.disabledClass);
16992 this.el.dom.disabled = false;
16996 * Convenience function for setting disabled/enabled by boolean.
16997 * @param {Boolean} disabled
16999 setDisabled : function(disabled){
17000 this[disabled ? "disable" : "enable"]();
17004 * Show this component.
17005 * @return {Roo.Component} this
17008 if(this.fireEvent("beforeshow", this) !== false){
17009 this.hidden = false;
17013 this.fireEvent("show", this);
17019 onShow : function(){
17020 var ae = this.getActionEl();
17021 if(this.hideMode == 'visibility'){
17022 ae.dom.style.visibility = "visible";
17023 }else if(this.hideMode == 'offsets'){
17024 ae.removeClass('x-hidden');
17026 ae.dom.style.display = "";
17031 * Hide this component.
17032 * @return {Roo.Component} this
17035 if(this.fireEvent("beforehide", this) !== false){
17036 this.hidden = true;
17040 this.fireEvent("hide", this);
17046 onHide : function(){
17047 var ae = this.getActionEl();
17048 if(this.hideMode == 'visibility'){
17049 ae.dom.style.visibility = "hidden";
17050 }else if(this.hideMode == 'offsets'){
17051 ae.addClass('x-hidden');
17053 ae.dom.style.display = "none";
17058 * Convenience function to hide or show this component by boolean.
17059 * @param {Boolean} visible True to show, false to hide
17060 * @return {Roo.Component} this
17062 setVisible: function(visible){
17072 * Returns true if this component is visible.
17074 isVisible : function(){
17075 return this.getActionEl().isVisible();
17078 cloneConfig : function(overrides){
17079 overrides = overrides || {};
17080 var id = overrides.id || Roo.id();
17081 var cfg = Roo.applyIf(overrides, this.initialConfig);
17082 cfg.id = id; // prevent dup id
17083 return new this.constructor(cfg);
17087 * Ext JS Library 1.1.1
17088 * Copyright(c) 2006-2007, Ext JS, LLC.
17090 * Originally Released Under LGPL - original licence link has changed is not relivant.
17093 * <script type="text/javascript">
17097 * @class Roo.BoxComponent
17098 * @extends Roo.Component
17099 * Base class for any visual {@link Roo.Component} that uses a box container. BoxComponent provides automatic box
17100 * model adjustments for sizing and positioning and will work correctly withnin the Component rendering model. All
17101 * container classes should subclass BoxComponent so that they will work consistently when nested within other Roo
17102 * layout containers.
17104 * @param {Roo.Element/String/Object} config The configuration options.
17106 Roo.BoxComponent = function(config){
17107 Roo.Component.call(this, config);
17111 * Fires after the component is resized.
17112 * @param {Roo.Component} this
17113 * @param {Number} adjWidth The box-adjusted width that was set
17114 * @param {Number} adjHeight The box-adjusted height that was set
17115 * @param {Number} rawWidth The width that was originally specified
17116 * @param {Number} rawHeight The height that was originally specified
17121 * Fires after the component is moved.
17122 * @param {Roo.Component} this
17123 * @param {Number} x The new x position
17124 * @param {Number} y The new y position
17130 Roo.extend(Roo.BoxComponent, Roo.Component, {
17131 // private, set in afterRender to signify that the component has been rendered
17133 // private, used to defer height settings to subclasses
17134 deferHeight: false,
17135 /** @cfg {Number} width
17136 * width (optional) size of component
17138 /** @cfg {Number} height
17139 * height (optional) size of component
17143 * Sets the width and height of the component. This method fires the resize event. This method can accept
17144 * either width and height as separate numeric arguments, or you can pass a size object like {width:10, height:20}.
17145 * @param {Number/Object} width The new width to set, or a size object in the format {width, height}
17146 * @param {Number} height The new height to set (not required if a size object is passed as the first arg)
17147 * @return {Roo.BoxComponent} this
17149 setSize : function(w, h){
17150 // support for standard size objects
17151 if(typeof w == 'object'){
17156 if(!this.boxReady){
17162 // prevent recalcs when not needed
17163 if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
17166 this.lastSize = {width: w, height: h};
17168 var adj = this.adjustSize(w, h);
17169 var aw = adj.width, ah = adj.height;
17170 if(aw !== undefined || ah !== undefined){ // this code is nasty but performs better with floaters
17171 var rz = this.getResizeEl();
17172 if(!this.deferHeight && aw !== undefined && ah !== undefined){
17173 rz.setSize(aw, ah);
17174 }else if(!this.deferHeight && ah !== undefined){
17176 }else if(aw !== undefined){
17179 this.onResize(aw, ah, w, h);
17180 this.fireEvent('resize', this, aw, ah, w, h);
17186 * Gets the current size of the component's underlying element.
17187 * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
17189 getSize : function(){
17190 return this.el.getSize();
17194 * Gets the current XY position of the component's underlying element.
17195 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
17196 * @return {Array} The XY position of the element (e.g., [100, 200])
17198 getPosition : function(local){
17199 if(local === true){
17200 return [this.el.getLeft(true), this.el.getTop(true)];
17202 return this.xy || this.el.getXY();
17206 * Gets the current box measurements of the component's underlying element.
17207 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
17208 * @returns {Object} box An object in the format {x, y, width, height}
17210 getBox : function(local){
17211 var s = this.el.getSize();
17213 s.x = this.el.getLeft(true);
17214 s.y = this.el.getTop(true);
17216 var xy = this.xy || this.el.getXY();
17224 * Sets the current box measurements of the component's underlying element.
17225 * @param {Object} box An object in the format {x, y, width, height}
17226 * @returns {Roo.BoxComponent} this
17228 updateBox : function(box){
17229 this.setSize(box.width, box.height);
17230 this.setPagePosition(box.x, box.y);
17235 getResizeEl : function(){
17236 return this.resizeEl || this.el;
17240 getPositionEl : function(){
17241 return this.positionEl || this.el;
17245 * Sets the left and top of the component. To set the page XY position instead, use {@link #setPagePosition}.
17246 * This method fires the move event.
17247 * @param {Number} left The new left
17248 * @param {Number} top The new top
17249 * @returns {Roo.BoxComponent} this
17251 setPosition : function(x, y){
17254 if(!this.boxReady){
17257 var adj = this.adjustPosition(x, y);
17258 var ax = adj.x, ay = adj.y;
17260 var el = this.getPositionEl();
17261 if(ax !== undefined || ay !== undefined){
17262 if(ax !== undefined && ay !== undefined){
17263 el.setLeftTop(ax, ay);
17264 }else if(ax !== undefined){
17266 }else if(ay !== undefined){
17269 this.onPosition(ax, ay);
17270 this.fireEvent('move', this, ax, ay);
17276 * Sets the page XY position of the component. To set the left and top instead, use {@link #setPosition}.
17277 * This method fires the move event.
17278 * @param {Number} x The new x position
17279 * @param {Number} y The new y position
17280 * @returns {Roo.BoxComponent} this
17282 setPagePosition : function(x, y){
17285 if(!this.boxReady){
17288 if(x === undefined || y === undefined){ // cannot translate undefined points
17291 var p = this.el.translatePoints(x, y);
17292 this.setPosition(p.left, p.top);
17297 onRender : function(ct, position){
17298 Roo.BoxComponent.superclass.onRender.call(this, ct, position);
17300 this.resizeEl = Roo.get(this.resizeEl);
17302 if(this.positionEl){
17303 this.positionEl = Roo.get(this.positionEl);
17308 afterRender : function(){
17309 Roo.BoxComponent.superclass.afterRender.call(this);
17310 this.boxReady = true;
17311 this.setSize(this.width, this.height);
17312 if(this.x || this.y){
17313 this.setPosition(this.x, this.y);
17315 if(this.pageX || this.pageY){
17316 this.setPagePosition(this.pageX, this.pageY);
17321 * Force the component's size to recalculate based on the underlying element's current height and width.
17322 * @returns {Roo.BoxComponent} this
17324 syncSize : function(){
17325 delete this.lastSize;
17326 this.setSize(this.el.getWidth(), this.el.getHeight());
17331 * Called after the component is resized, this method is empty by default but can be implemented by any
17332 * subclass that needs to perform custom logic after a resize occurs.
17333 * @param {Number} adjWidth The box-adjusted width that was set
17334 * @param {Number} adjHeight The box-adjusted height that was set
17335 * @param {Number} rawWidth The width that was originally specified
17336 * @param {Number} rawHeight The height that was originally specified
17338 onResize : function(adjWidth, adjHeight, rawWidth, rawHeight){
17343 * Called after the component is moved, this method is empty by default but can be implemented by any
17344 * subclass that needs to perform custom logic after a move occurs.
17345 * @param {Number} x The new x position
17346 * @param {Number} y The new y position
17348 onPosition : function(x, y){
17353 adjustSize : function(w, h){
17354 if(this.autoWidth){
17357 if(this.autoHeight){
17360 return {width : w, height: h};
17364 adjustPosition : function(x, y){
17365 return {x : x, y: y};
17369 * Ext JS Library 1.1.1
17370 * Copyright(c) 2006-2007, Ext JS, LLC.
17372 * Originally Released Under LGPL - original licence link has changed is not relivant.
17375 * <script type="text/javascript">
17380 * @extends Roo.Element
17381 * An extended {@link Roo.Element} object that supports a shadow and shim, constrain to viewport and
17382 * automatic maintaining of shadow/shim positions.
17383 * @cfg {Boolean} shim False to disable the iframe shim in browsers which need one (defaults to true)
17384 * @cfg {String/Boolean} shadow True to create a shadow element with default class "x-layer-shadow", or
17385 * you can pass a string with a CSS class name. False turns off the shadow.
17386 * @cfg {Object} dh DomHelper object config to create element with (defaults to {tag: "div", cls: "x-layer"}).
17387 * @cfg {Boolean} constrain False to disable constrain to viewport (defaults to true)
17388 * @cfg {String} cls CSS class to add to the element
17389 * @cfg {Number} zindex Starting z-index (defaults to 11000)
17390 * @cfg {Number} shadowOffset Number of pixels to offset the shadow (defaults to 3)
17392 * @param {Object} config An object with config options.
17393 * @param {String/HTMLElement} existingEl (optional) Uses an existing DOM element. If the element is not found it creates it.
17396 Roo.Layer = function(config, existingEl){
17397 config = config || {};
17398 var dh = Roo.DomHelper;
17399 var cp = config.parentEl, pel = cp ? Roo.getDom(cp) : document.body;
17401 this.dom = Roo.getDom(existingEl);
17404 var o = config.dh || {tag: "div", cls: "x-layer"};
17405 this.dom = dh.append(pel, o);
17408 this.addClass(config.cls);
17410 this.constrain = config.constrain !== false;
17411 this.visibilityMode = Roo.Element.VISIBILITY;
17413 this.id = this.dom.id = config.id;
17415 this.id = Roo.id(this.dom);
17417 this.zindex = config.zindex || this.getZIndex();
17418 this.position("absolute", this.zindex);
17420 this.shadowOffset = config.shadowOffset || 4;
17421 this.shadow = new Roo.Shadow({
17422 offset : this.shadowOffset,
17423 mode : config.shadow
17426 this.shadowOffset = 0;
17428 this.useShim = config.shim !== false && Roo.useShims;
17429 this.useDisplay = config.useDisplay;
17433 var supr = Roo.Element.prototype;
17435 // shims are shared among layer to keep from having 100 iframes
17438 Roo.extend(Roo.Layer, Roo.Element, {
17440 getZIndex : function(){
17441 return this.zindex || parseInt(this.getStyle("z-index"), 10) || 11000;
17444 getShim : function(){
17451 var shim = shims.shift();
17453 shim = this.createShim();
17454 shim.enableDisplayMode('block');
17455 shim.dom.style.display = 'none';
17456 shim.dom.style.visibility = 'visible';
17458 var pn = this.dom.parentNode;
17459 if(shim.dom.parentNode != pn){
17460 pn.insertBefore(shim.dom, this.dom);
17462 shim.setStyle('z-index', this.getZIndex()-2);
17467 hideShim : function(){
17469 this.shim.setDisplayed(false);
17470 shims.push(this.shim);
17475 disableShadow : function(){
17477 this.shadowDisabled = true;
17478 this.shadow.hide();
17479 this.lastShadowOffset = this.shadowOffset;
17480 this.shadowOffset = 0;
17484 enableShadow : function(show){
17486 this.shadowDisabled = false;
17487 this.shadowOffset = this.lastShadowOffset;
17488 delete this.lastShadowOffset;
17496 // this code can execute repeatedly in milliseconds (i.e. during a drag) so
17497 // code size was sacrificed for effeciency (e.g. no getBox/setBox, no XY calls)
17498 sync : function(doShow){
17499 var sw = this.shadow;
17500 if(!this.updating && this.isVisible() && (sw || this.useShim)){
17501 var sh = this.getShim();
17503 var w = this.getWidth(),
17504 h = this.getHeight();
17506 var l = this.getLeft(true),
17507 t = this.getTop(true);
17509 if(sw && !this.shadowDisabled){
17510 if(doShow && !sw.isVisible()){
17513 sw.realign(l, t, w, h);
17519 // fit the shim behind the shadow, so it is shimmed too
17520 var a = sw.adjusts, s = sh.dom.style;
17521 s.left = (Math.min(l, l+a.l))+"px";
17522 s.top = (Math.min(t, t+a.t))+"px";
17523 s.width = (w+a.w)+"px";
17524 s.height = (h+a.h)+"px";
17531 sh.setLeftTop(l, t);
17538 destroy : function(){
17541 this.shadow.hide();
17543 this.removeAllListeners();
17544 var pn = this.dom.parentNode;
17546 pn.removeChild(this.dom);
17548 Roo.Element.uncache(this.id);
17551 remove : function(){
17556 beginUpdate : function(){
17557 this.updating = true;
17561 endUpdate : function(){
17562 this.updating = false;
17567 hideUnders : function(negOffset){
17569 this.shadow.hide();
17575 constrainXY : function(){
17576 if(this.constrain){
17577 var vw = Roo.lib.Dom.getViewWidth(),
17578 vh = Roo.lib.Dom.getViewHeight();
17579 var s = Roo.get(document).getScroll();
17581 var xy = this.getXY();
17582 var x = xy[0], y = xy[1];
17583 var w = this.dom.offsetWidth+this.shadowOffset, h = this.dom.offsetHeight+this.shadowOffset;
17584 // only move it if it needs it
17586 // first validate right/bottom
17587 if((x + w) > vw+s.left){
17588 x = vw - w - this.shadowOffset;
17591 if((y + h) > vh+s.top){
17592 y = vh - h - this.shadowOffset;
17595 // then make sure top/left isn't negative
17606 var ay = this.avoidY;
17607 if(y <= ay && (y+h) >= ay){
17613 supr.setXY.call(this, xy);
17619 isVisible : function(){
17620 return this.visible;
17624 showAction : function(){
17625 this.visible = true; // track visibility to prevent getStyle calls
17626 if(this.useDisplay === true){
17627 this.setDisplayed("");
17628 }else if(this.lastXY){
17629 supr.setXY.call(this, this.lastXY);
17630 }else if(this.lastLT){
17631 supr.setLeftTop.call(this, this.lastLT[0], this.lastLT[1]);
17636 hideAction : function(){
17637 this.visible = false;
17638 if(this.useDisplay === true){
17639 this.setDisplayed(false);
17641 this.setLeftTop(-10000,-10000);
17645 // overridden Element method
17646 setVisible : function(v, a, d, c, e){
17651 var cb = function(){
17656 }.createDelegate(this);
17657 supr.setVisible.call(this, true, true, d, cb, e);
17660 this.hideUnders(true);
17669 }.createDelegate(this);
17671 supr.setVisible.call(this, v, a, d, cb, e);
17680 storeXY : function(xy){
17681 delete this.lastLT;
17685 storeLeftTop : function(left, top){
17686 delete this.lastXY;
17687 this.lastLT = [left, top];
17691 beforeFx : function(){
17692 this.beforeAction();
17693 return Roo.Layer.superclass.beforeFx.apply(this, arguments);
17697 afterFx : function(){
17698 Roo.Layer.superclass.afterFx.apply(this, arguments);
17699 this.sync(this.isVisible());
17703 beforeAction : function(){
17704 if(!this.updating && this.shadow){
17705 this.shadow.hide();
17709 // overridden Element method
17710 setLeft : function(left){
17711 this.storeLeftTop(left, this.getTop(true));
17712 supr.setLeft.apply(this, arguments);
17716 setTop : function(top){
17717 this.storeLeftTop(this.getLeft(true), top);
17718 supr.setTop.apply(this, arguments);
17722 setLeftTop : function(left, top){
17723 this.storeLeftTop(left, top);
17724 supr.setLeftTop.apply(this, arguments);
17728 setXY : function(xy, a, d, c, e){
17730 this.beforeAction();
17732 var cb = this.createCB(c);
17733 supr.setXY.call(this, xy, a, d, cb, e);
17740 createCB : function(c){
17751 // overridden Element method
17752 setX : function(x, a, d, c, e){
17753 this.setXY([x, this.getY()], a, d, c, e);
17756 // overridden Element method
17757 setY : function(y, a, d, c, e){
17758 this.setXY([this.getX(), y], a, d, c, e);
17761 // overridden Element method
17762 setSize : function(w, h, a, d, c, e){
17763 this.beforeAction();
17764 var cb = this.createCB(c);
17765 supr.setSize.call(this, w, h, a, d, cb, e);
17771 // overridden Element method
17772 setWidth : function(w, a, d, c, e){
17773 this.beforeAction();
17774 var cb = this.createCB(c);
17775 supr.setWidth.call(this, w, a, d, cb, e);
17781 // overridden Element method
17782 setHeight : function(h, a, d, c, e){
17783 this.beforeAction();
17784 var cb = this.createCB(c);
17785 supr.setHeight.call(this, h, a, d, cb, e);
17791 // overridden Element method
17792 setBounds : function(x, y, w, h, a, d, c, e){
17793 this.beforeAction();
17794 var cb = this.createCB(c);
17796 this.storeXY([x, y]);
17797 supr.setXY.call(this, [x, y]);
17798 supr.setSize.call(this, w, h, a, d, cb, e);
17801 supr.setBounds.call(this, x, y, w, h, a, d, cb, e);
17807 * Sets the z-index of this layer and adjusts any shadow and shim z-indexes. The layer z-index is automatically
17808 * incremented by two more than the value passed in so that it always shows above any shadow or shim (the shadow
17809 * element, if any, will be assigned z-index + 1, and the shim element, if any, will be assigned the unmodified z-index).
17810 * @param {Number} zindex The new z-index to set
17811 * @return {this} The Layer
17813 setZIndex : function(zindex){
17814 this.zindex = zindex;
17815 this.setStyle("z-index", zindex + 2);
17817 this.shadow.setZIndex(zindex + 1);
17820 this.shim.setStyle("z-index", zindex);
17825 * Original code for Roojs - LGPL
17826 * <script type="text/javascript">
17830 * @class Roo.XComponent
17831 * A delayed Element creator...
17832 * Or a way to group chunks of interface together.
17833 * technically this is a wrapper around a tree of Roo elements (which defines a 'module'),
17834 * used in conjunction with XComponent.build() it will create an instance of each element,
17835 * then call addxtype() to build the User interface.
17837 * Mypart.xyx = new Roo.XComponent({
17839 parent : 'Mypart.xyz', // empty == document.element.!!
17843 disabled : function() {}
17845 tree : function() { // return an tree of xtype declared components
17849 xtype : 'NestedLayoutPanel',
17856 * It can be used to build a big heiracy, with parent etc.
17857 * or you can just use this to render a single compoent to a dom element
17858 * MYPART.render(Roo.Element | String(id) | dom_element )
17865 * Roo is designed primarily as a single page application, so the UI build for a standard interface will
17866 * expect a single 'TOP' level module normally indicated by the 'parent' of the XComponent definition being defined as false.
17868 * Each sub module is expected to have a parent pointing to the class name of it's parent module.
17870 * When the top level is false, a 'Roo.BorderLayout' is created and the element is flagged as 'topModule'
17871 * - if mulitple topModules exist, the last one is defined as the top module.
17875 * When the top level or multiple modules are to embedded into a existing HTML page,
17876 * the parent element can container '#id' of the element where the module will be drawn.
17880 * Unlike classic Roo, the bootstrap tends not to be used as a single page.
17881 * it relies more on a include mechanism, where sub modules are included into an outer page.
17882 * This is normally managed by the builder tools using Roo.apply( options, Included.Sub.Module )
17884 * Bootstrap Roo Included elements
17886 * Our builder application needs the ability to preview these sub compoennts. They will normally have parent=false set,
17887 * hence confusing the component builder as it thinks there are multiple top level elements.
17889 * String Over-ride & Translations
17891 * Our builder application writes all the strings as _strings and _named_strings. This is to enable the translation of elements,
17892 * and also the 'overlaying of string values - needed when different versions of the same application with different text content
17893 * are needed. @see Roo.XComponent.overlayString
17897 * @extends Roo.util.Observable
17899 * @param cfg {Object} configuration of component
17902 Roo.XComponent = function(cfg) {
17903 Roo.apply(this, cfg);
17907 * Fires when this the componnt is built
17908 * @param {Roo.XComponent} c the component
17913 this.region = this.region || 'center'; // default..
17914 Roo.XComponent.register(this);
17915 this.modules = false;
17916 this.el = false; // where the layout goes..
17920 Roo.extend(Roo.XComponent, Roo.util.Observable, {
17923 * The created element (with Roo.factory())
17924 * @type {Roo.Layout}
17930 * for BC - use el in new code
17931 * @type {Roo.Layout}
17937 * for BC - use el in new code
17938 * @type {Roo.Layout}
17943 * @cfg {Function|boolean} disabled
17944 * If this module is disabled by some rule, return true from the funtion
17949 * @cfg {String} parent
17950 * Name of parent element which it get xtype added to..
17955 * @cfg {String} order
17956 * Used to set the order in which elements are created (usefull for multiple tabs)
17961 * @cfg {String} name
17962 * String to display while loading.
17966 * @cfg {String} region
17967 * Region to render component to (defaults to center)
17972 * @cfg {Array} items
17973 * A single item array - the first element is the root of the tree..
17974 * It's done this way to stay compatible with the Xtype system...
17980 * The method that retuns the tree of parts that make up this compoennt
17987 * render element to dom or tree
17988 * @param {Roo.Element|String|DomElement} optional render to if parent is not set.
17991 render : function(el)
17995 var hp = this.parent ? 1 : 0;
17996 Roo.debug && Roo.log(this);
17998 var tree = this._tree ? this._tree() : this.tree();
18001 if (!el && typeof(this.parent) == 'string' && this.parent.substring(0,1) == '#') {
18002 // if parent is a '#.....' string, then let's use that..
18003 var ename = this.parent.substr(1);
18004 this.parent = false;
18005 Roo.debug && Roo.log(ename);
18007 case 'bootstrap-body':
18008 if (typeof(tree.el) != 'undefined' && tree.el == document.body) {
18009 // this is the BorderLayout standard?
18010 this.parent = { el : true };
18013 if (["Nest", "Content", "Grid", "Tree"].indexOf(tree.xtype) > -1) {
18014 // need to insert stuff...
18016 el : new Roo.bootstrap.layout.Border({
18017 el : document.body,
18023 tabPosition: 'top',
18024 //resizeTabs: true,
18025 alwaysShowTabs: true,
18035 if (typeof(Roo.bootstrap.Body) != 'undefined' ) {
18036 this.parent = { el : new Roo.bootstrap.Body() };
18037 Roo.debug && Roo.log("setting el to doc body");
18040 throw "Container is bootstrap body, but Roo.bootstrap.Body is not defined";
18044 this.parent = { el : true};
18047 el = Roo.get(ename);
18048 if (typeof(Roo.bootstrap) != 'undefined' && tree['|xns'] == 'Roo.bootstrap') {
18049 this.parent = { el : true};
18056 if (!el && !this.parent) {
18057 Roo.debug && Roo.log("Warning - element can not be found :#" + ename );
18062 Roo.debug && Roo.log("EL:");
18063 Roo.debug && Roo.log(el);
18064 Roo.debug && Roo.log("this.parent.el:");
18065 Roo.debug && Roo.log(this.parent.el);
18068 // altertive root elements ??? - we need a better way to indicate these.
18069 var is_alt = Roo.XComponent.is_alt ||
18070 (typeof(tree.el) != 'undefined' && tree.el == document.body) ||
18071 (typeof(Roo.bootstrap) != 'undefined' && tree.xns == Roo.bootstrap) ||
18072 (typeof(Roo.mailer) != 'undefined' && tree.xns == Roo.mailer) ;
18076 if (!this.parent && is_alt) {
18077 //el = Roo.get(document.body);
18078 this.parent = { el : true };
18083 if (!this.parent) {
18085 Roo.debug && Roo.log("no parent - creating one");
18087 el = el ? Roo.get(el) : false;
18089 if (typeof(Roo.BorderLayout) == 'undefined' ) {
18092 el : new Roo.bootstrap.layout.Border({
18093 el: el || document.body,
18099 tabPosition: 'top',
18100 //resizeTabs: true,
18101 alwaysShowTabs: false,
18104 overflow: 'visible'
18110 // it's a top level one..
18112 el : new Roo.BorderLayout(el || document.body, {
18117 tabPosition: 'top',
18118 //resizeTabs: true,
18119 alwaysShowTabs: el && hp? false : true,
18120 hideTabs: el || !hp ? true : false,
18128 if (!this.parent.el) {
18129 // probably an old style ctor, which has been disabled.
18133 // The 'tree' method is '_tree now'
18135 tree.region = tree.region || this.region;
18136 var is_body = false;
18137 if (this.parent.el === true) {
18138 // bootstrap... - body..
18142 this.parent.el = Roo.factory(tree);
18146 this.el = this.parent.el.addxtype(tree, undefined, is_body);
18147 this.fireEvent('built', this);
18149 this.panel = this.el;
18150 this.layout = this.panel.layout;
18151 this.parentLayout = this.parent.layout || false;
18157 Roo.apply(Roo.XComponent, {
18159 * @property hideProgress
18160 * true to disable the building progress bar.. usefull on single page renders.
18163 hideProgress : false,
18165 * @property buildCompleted
18166 * True when the builder has completed building the interface.
18169 buildCompleted : false,
18172 * @property topModule
18173 * the upper most module - uses document.element as it's constructor.
18180 * @property modules
18181 * array of modules to be created by registration system.
18182 * @type {Array} of Roo.XComponent
18187 * @property elmodules
18188 * array of modules to be created by which use #ID
18189 * @type {Array} of Roo.XComponent
18196 * Is an alternative Root - normally used by bootstrap or other systems,
18197 * where the top element in the tree can wrap 'body'
18198 * @type {boolean} (default false)
18203 * @property build_from_html
18204 * Build elements from html - used by bootstrap HTML stuff
18205 * - this is cleared after build is completed
18206 * @type {boolean} (default false)
18209 build_from_html : false,
18211 * Register components to be built later.
18213 * This solves the following issues
18214 * - Building is not done on page load, but after an authentication process has occured.
18215 * - Interface elements are registered on page load
18216 * - Parent Interface elements may not be loaded before child, so this handles that..
18223 module : 'Pman.Tab.projectMgr',
18225 parent : 'Pman.layout',
18226 disabled : false, // or use a function..
18229 * * @param {Object} details about module
18231 register : function(obj) {
18233 Roo.XComponent.event.fireEvent('register', obj);
18234 switch(typeof(obj.disabled) ) {
18240 if ( obj.disabled() ) {
18246 if (obj.disabled || obj.region == '#disabled') {
18252 this.modules.push(obj);
18256 * convert a string to an object..
18257 * eg. 'AAA.BBB' -> finds AAA.BBB
18261 toObject : function(str)
18263 if (!str || typeof(str) == 'object') {
18266 if (str.substring(0,1) == '#') {
18270 var ar = str.split('.');
18275 eval('if (typeof ' + rt + ' == "undefined"){ o = false;} o = ' + rt + ';');
18277 throw "Module not found : " + str;
18281 throw "Module not found : " + str;
18283 Roo.each(ar, function(e) {
18284 if (typeof(o[e]) == 'undefined') {
18285 throw "Module not found : " + str;
18296 * move modules into their correct place in the tree..
18299 preBuild : function ()
18302 Roo.each(this.modules , function (obj)
18304 Roo.XComponent.event.fireEvent('beforebuild', obj);
18306 var opar = obj.parent;
18308 obj.parent = this.toObject(opar);
18310 Roo.debug && Roo.log("parent:toObject failed: " + e.toString());
18315 Roo.debug && Roo.log("GOT top level module");
18316 Roo.debug && Roo.log(obj);
18317 obj.modules = new Roo.util.MixedCollection(false,
18318 function(o) { return o.order + '' }
18320 this.topModule = obj;
18323 // parent is a string (usually a dom element name..)
18324 if (typeof(obj.parent) == 'string') {
18325 this.elmodules.push(obj);
18328 if (obj.parent.constructor != Roo.XComponent) {
18329 Roo.debug && Roo.log("Warning : Object Parent is not instance of XComponent:" + obj.name)
18331 if (!obj.parent.modules) {
18332 obj.parent.modules = new Roo.util.MixedCollection(false,
18333 function(o) { return o.order + '' }
18336 if (obj.parent.disabled) {
18337 obj.disabled = true;
18339 obj.parent.modules.add(obj);
18344 * make a list of modules to build.
18345 * @return {Array} list of modules.
18348 buildOrder : function()
18351 var cmp = function(a,b) {
18352 return String(a).toUpperCase() > String(b).toUpperCase() ? 1 : -1;
18354 if ((!this.topModule || !this.topModule.modules) && !this.elmodules.length) {
18355 throw "No top level modules to build";
18358 // make a flat list in order of modules to build.
18359 var mods = this.topModule ? [ this.topModule ] : [];
18362 // elmodules (is a list of DOM based modules )
18363 Roo.each(this.elmodules, function(e) {
18365 if (!this.topModule &&
18366 typeof(e.parent) == 'string' &&
18367 e.parent.substring(0,1) == '#' &&
18368 Roo.get(e.parent.substr(1))
18371 _this.topModule = e;
18377 // add modules to their parents..
18378 var addMod = function(m) {
18379 Roo.debug && Roo.log("build Order: add: " + m.name);
18382 if (m.modules && !m.disabled) {
18383 Roo.debug && Roo.log("build Order: " + m.modules.length + " child modules");
18384 m.modules.keySort('ASC', cmp );
18385 Roo.debug && Roo.log("build Order: " + m.modules.length + " child modules (after sort)");
18387 m.modules.each(addMod);
18389 Roo.debug && Roo.log("build Order: no child modules");
18391 // not sure if this is used any more..
18393 m.finalize.name = m.name + " (clean up) ";
18394 mods.push(m.finalize);
18398 if (this.topModule && this.topModule.modules) {
18399 this.topModule.modules.keySort('ASC', cmp );
18400 this.topModule.modules.each(addMod);
18406 * Build the registered modules.
18407 * @param {Object} parent element.
18408 * @param {Function} optional method to call after module has been added.
18412 build : function(opts)
18415 if (typeof(opts) != 'undefined') {
18416 Roo.apply(this,opts);
18420 var mods = this.buildOrder();
18422 //this.allmods = mods;
18423 //Roo.debug && Roo.log(mods);
18425 if (!mods.length) { // should not happen
18426 throw "NO modules!!!";
18430 var msg = "Building Interface...";
18431 // flash it up as modal - so we store the mask!?
18432 if (!this.hideProgress && Roo.MessageBox) {
18433 Roo.MessageBox.show({ title: 'loading' });
18434 Roo.MessageBox.show({
18435 title: "Please wait...",
18445 var total = mods.length;
18448 var progressRun = function() {
18449 if (!mods.length) {
18450 Roo.debug && Roo.log('hide?');
18451 if (!this.hideProgress && Roo.MessageBox) {
18452 Roo.MessageBox.hide();
18454 Roo.XComponent.build_from_html = false; // reset, so dialogs will be build from javascript
18456 Roo.XComponent.event.fireEvent('buildcomplete', _this.topModule);
18462 var m = mods.shift();
18465 Roo.debug && Roo.log(m);
18466 // not sure if this is supported any more.. - modules that are are just function
18467 if (typeof(m) == 'function') {
18469 return progressRun.defer(10, _this);
18473 msg = "Building Interface " + (total - mods.length) +
18475 (m.name ? (' - ' + m.name) : '');
18476 Roo.debug && Roo.log(msg);
18477 if (!_this.hideProgress && Roo.MessageBox) {
18478 Roo.MessageBox.updateProgress( (total - mods.length)/total, msg );
18482 // is the module disabled?
18483 var disabled = (typeof(m.disabled) == 'function') ?
18484 m.disabled.call(m.module.disabled) : m.disabled;
18488 return progressRun(); // we do not update the display!
18496 // it's 10 on top level, and 1 on others??? why...
18497 return progressRun.defer(10, _this);
18500 progressRun.defer(1, _this);
18506 * Overlay a set of modified strings onto a component
18507 * This is dependant on our builder exporting the strings and 'named strings' elements.
18509 * @param {Object} element to overlay on - eg. Pman.Dialog.Login
18510 * @param {Object} associative array of 'named' string and it's new value.
18513 overlayStrings : function( component, strings )
18515 if (typeof(component['_named_strings']) == 'undefined') {
18516 throw "ERROR: component does not have _named_strings";
18518 for ( var k in strings ) {
18519 var md = typeof(component['_named_strings'][k]) == 'undefined' ? false : component['_named_strings'][k];
18520 if (md !== false) {
18521 component['_strings'][md] = strings[k];
18523 Roo.log('could not find named string: ' + k + ' in');
18524 Roo.log(component);
18539 * wrapper for event.on - aliased later..
18540 * Typically use to register a event handler for register:
18542 * eg. Roo.XComponent.on('register', function(comp) { comp.disable = true } );
18551 Roo.XComponent.event = new Roo.util.Observable({
18555 * Fires when an Component is registered,
18556 * set the disable property on the Component to stop registration.
18557 * @param {Roo.XComponent} c the component being registerd.
18562 * @event beforebuild
18563 * Fires before each Component is built
18564 * can be used to apply permissions.
18565 * @param {Roo.XComponent} c the component being registerd.
18568 'beforebuild' : true,
18570 * @event buildcomplete
18571 * Fires on the top level element when all elements have been built
18572 * @param {Roo.XComponent} the top level component.
18574 'buildcomplete' : true
18579 Roo.XComponent.on = Roo.XComponent.event.on.createDelegate(Roo.XComponent.event);
18582 * marked - a markdown parser
18583 * Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed)
18584 * https://github.com/chjj/marked
18590 * Roo.Markdown - is a very crude wrapper around marked..
18594 * alert( Roo.Markdown.toHtml("Markdown *rocks*.") );
18596 * Note: move the sample code to the bottom of this
18597 * file before uncommenting it.
18602 Roo.Markdown.toHtml = function(text) {
18604 var c = new Roo.Markdown.marked.setOptions({
18605 renderer: new Roo.Markdown.marked.Renderer(),
18616 text = text.replace(/\\\n/g,' ');
18617 return Roo.Markdown.marked(text);
18622 // Wraps all "globals" so that the only thing
18623 // exposed is makeHtml().
18629 * eval:var:unescape
18637 var escape = function (html, encode) {
18639 .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&')
18640 .replace(/</g, '<')
18641 .replace(/>/g, '>')
18642 .replace(/"/g, '"')
18643 .replace(/'/g, ''');
18646 var unescape = function (html) {
18647 // explicitly match decimal, hex, and named HTML entities
18648 return html.replace(/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/g, function(_, n) {
18649 n = n.toLowerCase();
18650 if (n === 'colon') { return ':'; }
18651 if (n.charAt(0) === '#') {
18652 return n.charAt(1) === 'x'
18653 ? String.fromCharCode(parseInt(n.substring(2), 16))
18654 : String.fromCharCode(+n.substring(1));
18660 var replace = function (regex, opt) {
18661 regex = regex.source;
18663 return function self(name, val) {
18664 if (!name) { return new RegExp(regex, opt); }
18665 val = val.source || val;
18666 val = val.replace(/(^|[^\[])\^/g, '$1');
18667 regex = regex.replace(name, val);
18676 var noop = function () {}
18682 var merge = function (obj) {
18687 for (; i < arguments.length; i++) {
18688 target = arguments[i];
18689 for (key in target) {
18690 if (Object.prototype.hasOwnProperty.call(target, key)) {
18691 obj[key] = target[key];
18701 * Block-Level Grammar
18709 code: /^( {4}[^\n]+\n*)+/,
18711 hr: /^( *[-*_]){3,} *(?:\n+|$)/,
18712 heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,
18714 lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,
18715 blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/,
18716 list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,
18717 html: /^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/,
18718 def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,
18720 paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,
18724 block.bullet = /(?:[*+-]|\d+\.)/;
18725 block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/;
18726 block.item = replace(block.item, 'gm')
18727 (/bull/g, block.bullet)
18730 block.list = replace(block.list)
18731 (/bull/g, block.bullet)
18732 ('hr', '\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))')
18733 ('def', '\\n+(?=' + block.def.source + ')')
18736 block.blockquote = replace(block.blockquote)
18740 block._tag = '(?!(?:'
18741 + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code'
18742 + '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo'
18743 + '|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b';
18745 block.html = replace(block.html)
18746 ('comment', /<!--[\s\S]*?-->/)
18747 ('closed', /<(tag)[\s\S]+?<\/\1>/)
18748 ('closing', /<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)
18749 (/tag/g, block._tag)
18752 block.paragraph = replace(block.paragraph)
18754 ('heading', block.heading)
18755 ('lheading', block.lheading)
18756 ('blockquote', block.blockquote)
18757 ('tag', '<' + block._tag)
18762 * Normal Block Grammar
18765 block.normal = merge({}, block);
18768 * GFM Block Grammar
18771 block.gfm = merge({}, block.normal, {
18772 fences: /^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/,
18774 heading: /^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/
18777 block.gfm.paragraph = replace(block.paragraph)
18779 + block.gfm.fences.source.replace('\\1', '\\2') + '|'
18780 + block.list.source.replace('\\1', '\\3') + '|')
18784 * GFM + Tables Block Grammar
18787 block.tables = merge({}, block.gfm, {
18788 nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,
18789 table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/
18796 var Lexer = function (options) {
18798 this.tokens.links = {};
18799 this.options = options || marked.defaults;
18800 this.rules = block.normal;
18802 if (this.options.gfm) {
18803 if (this.options.tables) {
18804 this.rules = block.tables;
18806 this.rules = block.gfm;
18812 * Expose Block Rules
18815 Lexer.rules = block;
18818 * Static Lex Method
18821 Lexer.lex = function(src, options) {
18822 var lexer = new Lexer(options);
18823 return lexer.lex(src);
18830 Lexer.prototype.lex = function(src) {
18832 .replace(/\r\n|\r/g, '\n')
18833 .replace(/\t/g, ' ')
18834 .replace(/\u00a0/g, ' ')
18835 .replace(/\u2424/g, '\n');
18837 return this.token(src, true);
18844 Lexer.prototype.token = function(src, top, bq) {
18845 var src = src.replace(/^ +$/gm, '')
18858 if (cap = this.rules.newline.exec(src)) {
18859 src = src.substring(cap[0].length);
18860 if (cap[0].length > 1) {
18868 if (cap = this.rules.code.exec(src)) {
18869 src = src.substring(cap[0].length);
18870 cap = cap[0].replace(/^ {4}/gm, '');
18873 text: !this.options.pedantic
18874 ? cap.replace(/\n+$/, '')
18881 if (cap = this.rules.fences.exec(src)) {
18882 src = src.substring(cap[0].length);
18892 if (cap = this.rules.heading.exec(src)) {
18893 src = src.substring(cap[0].length);
18896 depth: cap[1].length,
18902 // table no leading pipe (gfm)
18903 if (top && (cap = this.rules.nptable.exec(src))) {
18904 src = src.substring(cap[0].length);
18908 header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
18909 align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
18910 cells: cap[3].replace(/\n$/, '').split('\n')
18913 for (i = 0; i < item.align.length; i++) {
18914 if (/^ *-+: *$/.test(item.align[i])) {
18915 item.align[i] = 'right';
18916 } else if (/^ *:-+: *$/.test(item.align[i])) {
18917 item.align[i] = 'center';
18918 } else if (/^ *:-+ *$/.test(item.align[i])) {
18919 item.align[i] = 'left';
18921 item.align[i] = null;
18925 for (i = 0; i < item.cells.length; i++) {
18926 item.cells[i] = item.cells[i].split(/ *\| */);
18929 this.tokens.push(item);
18935 if (cap = this.rules.lheading.exec(src)) {
18936 src = src.substring(cap[0].length);
18939 depth: cap[2] === '=' ? 1 : 2,
18946 if (cap = this.rules.hr.exec(src)) {
18947 src = src.substring(cap[0].length);
18955 if (cap = this.rules.blockquote.exec(src)) {
18956 src = src.substring(cap[0].length);
18959 type: 'blockquote_start'
18962 cap = cap[0].replace(/^ *> ?/gm, '');
18964 // Pass `top` to keep the current
18965 // "toplevel" state. This is exactly
18966 // how markdown.pl works.
18967 this.token(cap, top, true);
18970 type: 'blockquote_end'
18977 if (cap = this.rules.list.exec(src)) {
18978 src = src.substring(cap[0].length);
18982 type: 'list_start',
18983 ordered: bull.length > 1
18986 // Get each top-level item.
18987 cap = cap[0].match(this.rules.item);
18993 for (; i < l; i++) {
18996 // Remove the list item's bullet
18997 // so it is seen as the next token.
18998 space = item.length;
18999 item = item.replace(/^ *([*+-]|\d+\.) +/, '');
19001 // Outdent whatever the
19002 // list item contains. Hacky.
19003 if (~item.indexOf('\n ')) {
19004 space -= item.length;
19005 item = !this.options.pedantic
19006 ? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '')
19007 : item.replace(/^ {1,4}/gm, '');
19010 // Determine whether the next list item belongs here.
19011 // Backpedal if it does not belong in this list.
19012 if (this.options.smartLists && i !== l - 1) {
19013 b = block.bullet.exec(cap[i + 1])[0];
19014 if (bull !== b && !(bull.length > 1 && b.length > 1)) {
19015 src = cap.slice(i + 1).join('\n') + src;
19020 // Determine whether item is loose or not.
19021 // Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/
19022 // for discount behavior.
19023 loose = next || /\n\n(?!\s*$)/.test(item);
19025 next = item.charAt(item.length - 1) === '\n';
19026 if (!loose) { loose = next; }
19031 ? 'loose_item_start'
19032 : 'list_item_start'
19036 this.token(item, false, bq);
19039 type: 'list_item_end'
19051 if (cap = this.rules.html.exec(src)) {
19052 src = src.substring(cap[0].length);
19054 type: this.options.sanitize
19057 pre: !this.options.sanitizer
19058 && (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'),
19065 if ((!bq && top) && (cap = this.rules.def.exec(src))) {
19066 src = src.substring(cap[0].length);
19067 this.tokens.links[cap[1].toLowerCase()] = {
19075 if (top && (cap = this.rules.table.exec(src))) {
19076 src = src.substring(cap[0].length);
19080 header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
19081 align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
19082 cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n')
19085 for (i = 0; i < item.align.length; i++) {
19086 if (/^ *-+: *$/.test(item.align[i])) {
19087 item.align[i] = 'right';
19088 } else if (/^ *:-+: *$/.test(item.align[i])) {
19089 item.align[i] = 'center';
19090 } else if (/^ *:-+ *$/.test(item.align[i])) {
19091 item.align[i] = 'left';
19093 item.align[i] = null;
19097 for (i = 0; i < item.cells.length; i++) {
19098 item.cells[i] = item.cells[i]
19099 .replace(/^ *\| *| *\| *$/g, '')
19103 this.tokens.push(item);
19108 // top-level paragraph
19109 if (top && (cap = this.rules.paragraph.exec(src))) {
19110 src = src.substring(cap[0].length);
19113 text: cap[1].charAt(cap[1].length - 1) === '\n'
19114 ? cap[1].slice(0, -1)
19121 if (cap = this.rules.text.exec(src)) {
19122 // Top-level should never reach here.
19123 src = src.substring(cap[0].length);
19133 Error('Infinite loop on byte: ' + src.charCodeAt(0));
19137 return this.tokens;
19141 * Inline-Level Grammar
19145 escape: /^\\([\\`*{}\[\]()#+\-.!_>])/,
19146 autolink: /^<([^ >]+(@|:\/)[^ >]+)>/,
19148 tag: /^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,
19149 link: /^!?\[(inside)\]\(href\)/,
19150 reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/,
19151 nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,
19152 strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,
19153 em: /^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,
19154 code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,
19155 br: /^ {2,}\n(?!\s*$)/,
19157 text: /^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/
19160 inline._inside = /(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/;
19161 inline._href = /\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/;
19163 inline.link = replace(inline.link)
19164 ('inside', inline._inside)
19165 ('href', inline._href)
19168 inline.reflink = replace(inline.reflink)
19169 ('inside', inline._inside)
19173 * Normal Inline Grammar
19176 inline.normal = merge({}, inline);
19179 * Pedantic Inline Grammar
19182 inline.pedantic = merge({}, inline.normal, {
19183 strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
19184 em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/
19188 * GFM Inline Grammar
19191 inline.gfm = merge({}, inline.normal, {
19192 escape: replace(inline.escape)('])', '~|])')(),
19193 url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,
19194 del: /^~~(?=\S)([\s\S]*?\S)~~/,
19195 text: replace(inline.text)
19197 ('|', '|https?://|')
19202 * GFM + Line Breaks Inline Grammar
19205 inline.breaks = merge({}, inline.gfm, {
19206 br: replace(inline.br)('{2,}', '*')(),
19207 text: replace(inline.gfm.text)('{2,}', '*')()
19211 * Inline Lexer & Compiler
19214 var InlineLexer = function (links, options) {
19215 this.options = options || marked.defaults;
19216 this.links = links;
19217 this.rules = inline.normal;
19218 this.renderer = this.options.renderer || new Renderer;
19219 this.renderer.options = this.options;
19223 Error('Tokens array requires a `links` property.');
19226 if (this.options.gfm) {
19227 if (this.options.breaks) {
19228 this.rules = inline.breaks;
19230 this.rules = inline.gfm;
19232 } else if (this.options.pedantic) {
19233 this.rules = inline.pedantic;
19238 * Expose Inline Rules
19241 InlineLexer.rules = inline;
19244 * Static Lexing/Compiling Method
19247 InlineLexer.output = function(src, links, options) {
19248 var inline = new InlineLexer(links, options);
19249 return inline.output(src);
19256 InlineLexer.prototype.output = function(src) {
19265 if (cap = this.rules.escape.exec(src)) {
19266 src = src.substring(cap[0].length);
19272 if (cap = this.rules.autolink.exec(src)) {
19273 src = src.substring(cap[0].length);
19274 if (cap[2] === '@') {
19275 text = cap[1].charAt(6) === ':'
19276 ? this.mangle(cap[1].substring(7))
19277 : this.mangle(cap[1]);
19278 href = this.mangle('mailto:') + text;
19280 text = escape(cap[1]);
19283 out += this.renderer.link(href, null, text);
19288 if (!this.inLink && (cap = this.rules.url.exec(src))) {
19289 src = src.substring(cap[0].length);
19290 text = escape(cap[1]);
19292 out += this.renderer.link(href, null, text);
19297 if (cap = this.rules.tag.exec(src)) {
19298 if (!this.inLink && /^<a /i.test(cap[0])) {
19299 this.inLink = true;
19300 } else if (this.inLink && /^<\/a>/i.test(cap[0])) {
19301 this.inLink = false;
19303 src = src.substring(cap[0].length);
19304 out += this.options.sanitize
19305 ? this.options.sanitizer
19306 ? this.options.sanitizer(cap[0])
19313 if (cap = this.rules.link.exec(src)) {
19314 src = src.substring(cap[0].length);
19315 this.inLink = true;
19316 out += this.outputLink(cap, {
19320 this.inLink = false;
19325 if ((cap = this.rules.reflink.exec(src))
19326 || (cap = this.rules.nolink.exec(src))) {
19327 src = src.substring(cap[0].length);
19328 link = (cap[2] || cap[1]).replace(/\s+/g, ' ');
19329 link = this.links[link.toLowerCase()];
19330 if (!link || !link.href) {
19331 out += cap[0].charAt(0);
19332 src = cap[0].substring(1) + src;
19335 this.inLink = true;
19336 out += this.outputLink(cap, link);
19337 this.inLink = false;
19342 if (cap = this.rules.strong.exec(src)) {
19343 src = src.substring(cap[0].length);
19344 out += this.renderer.strong(this.output(cap[2] || cap[1]));
19349 if (cap = this.rules.em.exec(src)) {
19350 src = src.substring(cap[0].length);
19351 out += this.renderer.em(this.output(cap[2] || cap[1]));
19356 if (cap = this.rules.code.exec(src)) {
19357 src = src.substring(cap[0].length);
19358 out += this.renderer.codespan(escape(cap[2], true));
19363 if (cap = this.rules.br.exec(src)) {
19364 src = src.substring(cap[0].length);
19365 out += this.renderer.br();
19370 if (cap = this.rules.del.exec(src)) {
19371 src = src.substring(cap[0].length);
19372 out += this.renderer.del(this.output(cap[1]));
19377 if (cap = this.rules.text.exec(src)) {
19378 src = src.substring(cap[0].length);
19379 out += this.renderer.text(escape(this.smartypants(cap[0])));
19385 Error('Infinite loop on byte: ' + src.charCodeAt(0));
19396 InlineLexer.prototype.outputLink = function(cap, link) {
19397 var href = escape(link.href)
19398 , title = link.title ? escape(link.title) : null;
19400 return cap[0].charAt(0) !== '!'
19401 ? this.renderer.link(href, title, this.output(cap[1]))
19402 : this.renderer.image(href, title, escape(cap[1]));
19406 * Smartypants Transformations
19409 InlineLexer.prototype.smartypants = function(text) {
19410 if (!this.options.smartypants) { return text; }
19413 .replace(/---/g, '\u2014')
19415 .replace(/--/g, '\u2013')
19417 .replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018')
19418 // closing singles & apostrophes
19419 .replace(/'/g, '\u2019')
19421 .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c')
19423 .replace(/"/g, '\u201d')
19425 .replace(/\.{3}/g, '\u2026');
19432 InlineLexer.prototype.mangle = function(text) {
19433 if (!this.options.mangle) { return text; }
19439 for (; i < l; i++) {
19440 ch = text.charCodeAt(i);
19441 if (Math.random() > 0.5) {
19442 ch = 'x' + ch.toString(16);
19444 out += '&#' + ch + ';';
19455 * eval:var:Renderer
19458 var Renderer = function (options) {
19459 this.options = options || {};
19462 Renderer.prototype.code = function(code, lang, escaped) {
19463 if (this.options.highlight) {
19464 var out = this.options.highlight(code, lang);
19465 if (out != null && out !== code) {
19470 // hack!!! - it's already escapeD?
19475 return '<pre><code>'
19476 + (escaped ? code : escape(code, true))
19477 + '\n</code></pre>';
19480 return '<pre><code class="'
19481 + this.options.langPrefix
19482 + escape(lang, true)
19484 + (escaped ? code : escape(code, true))
19485 + '\n</code></pre>\n';
19488 Renderer.prototype.blockquote = function(quote) {
19489 return '<blockquote>\n' + quote + '</blockquote>\n';
19492 Renderer.prototype.html = function(html) {
19496 Renderer.prototype.heading = function(text, level, raw) {
19500 + this.options.headerPrefix
19501 + raw.toLowerCase().replace(/[^\w]+/g, '-')
19509 Renderer.prototype.hr = function() {
19510 return this.options.xhtml ? '<hr/>\n' : '<hr>\n';
19513 Renderer.prototype.list = function(body, ordered) {
19514 var type = ordered ? 'ol' : 'ul';
19515 return '<' + type + '>\n' + body + '</' + type + '>\n';
19518 Renderer.prototype.listitem = function(text) {
19519 return '<li>' + text + '</li>\n';
19522 Renderer.prototype.paragraph = function(text) {
19523 return '<p>' + text + '</p>\n';
19526 Renderer.prototype.table = function(header, body) {
19527 return '<table class="table table-striped">\n'
19537 Renderer.prototype.tablerow = function(content) {
19538 return '<tr>\n' + content + '</tr>\n';
19541 Renderer.prototype.tablecell = function(content, flags) {
19542 var type = flags.header ? 'th' : 'td';
19543 var tag = flags.align
19544 ? '<' + type + ' style="text-align:' + flags.align + '">'
19545 : '<' + type + '>';
19546 return tag + content + '</' + type + '>\n';
19549 // span level renderer
19550 Renderer.prototype.strong = function(text) {
19551 return '<strong>' + text + '</strong>';
19554 Renderer.prototype.em = function(text) {
19555 return '<em>' + text + '</em>';
19558 Renderer.prototype.codespan = function(text) {
19559 return '<code>' + text + '</code>';
19562 Renderer.prototype.br = function() {
19563 return this.options.xhtml ? '<br/>' : '<br>';
19566 Renderer.prototype.del = function(text) {
19567 return '<del>' + text + '</del>';
19570 Renderer.prototype.link = function(href, title, text) {
19571 if (this.options.sanitize) {
19573 var prot = decodeURIComponent(unescape(href))
19574 .replace(/[^\w:]/g, '')
19579 if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0) {
19583 var out = '<a href="' + href + '"';
19585 out += ' title="' + title + '"';
19587 out += '>' + text + '</a>';
19591 Renderer.prototype.image = function(href, title, text) {
19592 var out = '<img src="' + href + '" alt="' + text + '"';
19594 out += ' title="' + title + '"';
19596 out += this.options.xhtml ? '/>' : '>';
19600 Renderer.prototype.text = function(text) {
19605 * Parsing & Compiling
19611 var Parser= function (options) {
19614 this.options = options || marked.defaults;
19615 this.options.renderer = this.options.renderer || new Renderer;
19616 this.renderer = this.options.renderer;
19617 this.renderer.options = this.options;
19621 * Static Parse Method
19624 Parser.parse = function(src, options, renderer) {
19625 var parser = new Parser(options, renderer);
19626 return parser.parse(src);
19633 Parser.prototype.parse = function(src) {
19634 this.inline = new InlineLexer(src.links, this.options, this.renderer);
19635 this.tokens = src.reverse();
19638 while (this.next()) {
19649 Parser.prototype.next = function() {
19650 return this.token = this.tokens.pop();
19654 * Preview Next Token
19657 Parser.prototype.peek = function() {
19658 return this.tokens[this.tokens.length - 1] || 0;
19662 * Parse Text Tokens
19665 Parser.prototype.parseText = function() {
19666 var body = this.token.text;
19668 while (this.peek().type === 'text') {
19669 body += '\n' + this.next().text;
19672 return this.inline.output(body);
19676 * Parse Current Token
19679 Parser.prototype.tok = function() {
19680 switch (this.token.type) {
19685 return this.renderer.hr();
19688 return this.renderer.heading(
19689 this.inline.output(this.token.text),
19694 return this.renderer.code(this.token.text,
19696 this.token.escaped);
19709 for (i = 0; i < this.token.header.length; i++) {
19710 flags = { header: true, align: this.token.align[i] };
19711 cell += this.renderer.tablecell(
19712 this.inline.output(this.token.header[i]),
19713 { header: true, align: this.token.align[i] }
19716 header += this.renderer.tablerow(cell);
19718 for (i = 0; i < this.token.cells.length; i++) {
19719 row = this.token.cells[i];
19722 for (j = 0; j < row.length; j++) {
19723 cell += this.renderer.tablecell(
19724 this.inline.output(row[j]),
19725 { header: false, align: this.token.align[j] }
19729 body += this.renderer.tablerow(cell);
19731 return this.renderer.table(header, body);
19733 case 'blockquote_start': {
19736 while (this.next().type !== 'blockquote_end') {
19737 body += this.tok();
19740 return this.renderer.blockquote(body);
19742 case 'list_start': {
19744 , ordered = this.token.ordered;
19746 while (this.next().type !== 'list_end') {
19747 body += this.tok();
19750 return this.renderer.list(body, ordered);
19752 case 'list_item_start': {
19755 while (this.next().type !== 'list_item_end') {
19756 body += this.token.type === 'text'
19761 return this.renderer.listitem(body);
19763 case 'loose_item_start': {
19766 while (this.next().type !== 'list_item_end') {
19767 body += this.tok();
19770 return this.renderer.listitem(body);
19773 var html = !this.token.pre && !this.options.pedantic
19774 ? this.inline.output(this.token.text)
19776 return this.renderer.html(html);
19778 case 'paragraph': {
19779 return this.renderer.paragraph(this.inline.output(this.token.text));
19782 return this.renderer.paragraph(this.parseText());
19794 var marked = function (src, opt, callback) {
19795 if (callback || typeof opt === 'function') {
19801 opt = merge({}, marked.defaults, opt || {});
19803 var highlight = opt.highlight
19809 tokens = Lexer.lex(src, opt)
19811 return callback(e);
19814 pending = tokens.length;
19818 var done = function(err) {
19820 opt.highlight = highlight;
19821 return callback(err);
19827 out = Parser.parse(tokens, opt);
19832 opt.highlight = highlight;
19836 : callback(null, out);
19839 if (!highlight || highlight.length < 3) {
19843 delete opt.highlight;
19845 if (!pending) { return done(); }
19847 for (; i < tokens.length; i++) {
19849 if (token.type !== 'code') {
19850 return --pending || done();
19852 return highlight(token.text, token.lang, function(err, code) {
19853 if (err) { return done(err); }
19854 if (code == null || code === token.text) {
19855 return --pending || done();
19858 token.escaped = true;
19859 --pending || done();
19867 if (opt) { opt = merge({}, marked.defaults, opt); }
19868 return Parser.parse(Lexer.lex(src, opt), opt);
19870 e.message += '\nPlease report this to https://github.com/chjj/marked.';
19871 if ((opt || marked.defaults).silent) {
19872 return '<p>An error occured:</p><pre>'
19873 + escape(e.message + '', true)
19885 marked.setOptions = function(opt) {
19886 merge(marked.defaults, opt);
19890 marked.defaults = {
19901 langPrefix: 'lang-',
19902 smartypants: false,
19904 renderer: new Renderer,
19912 marked.Parser = Parser;
19913 marked.parser = Parser.parse;
19915 marked.Renderer = Renderer;
19917 marked.Lexer = Lexer;
19918 marked.lexer = Lexer.lex;
19920 marked.InlineLexer = InlineLexer;
19921 marked.inlineLexer = InlineLexer.output;
19923 marked.parse = marked;
19925 Roo.Markdown.marked = marked;
19929 * Ext JS Library 1.1.1
19930 * Copyright(c) 2006-2007, Ext JS, LLC.
19932 * Originally Released Under LGPL - original licence link has changed is not relivant.
19935 * <script type="text/javascript">
19941 * These classes are derivatives of the similarly named classes in the YUI Library.
19942 * The original license:
19943 * Copyright (c) 2006, Yahoo! Inc. All rights reserved.
19944 * Code licensed under the BSD License:
19945 * http://developer.yahoo.net/yui/license.txt
19950 var Event=Roo.EventManager;
19951 var Dom=Roo.lib.Dom;
19954 * @class Roo.dd.DragDrop
19955 * @extends Roo.util.Observable
19956 * Defines the interface and base operation of items that that can be
19957 * dragged or can be drop targets. It was designed to be extended, overriding
19958 * the event handlers for startDrag, onDrag, onDragOver and onDragOut.
19959 * Up to three html elements can be associated with a DragDrop instance:
19961 * <li>linked element: the element that is passed into the constructor.
19962 * This is the element which defines the boundaries for interaction with
19963 * other DragDrop objects.</li>
19964 * <li>handle element(s): The drag operation only occurs if the element that
19965 * was clicked matches a handle element. By default this is the linked
19966 * element, but there are times that you will want only a portion of the
19967 * linked element to initiate the drag operation, and the setHandleElId()
19968 * method provides a way to define this.</li>
19969 * <li>drag element: this represents the element that would be moved along
19970 * with the cursor during a drag operation. By default, this is the linked
19971 * element itself as in {@link Roo.dd.DD}. setDragElId() lets you define
19972 * a separate element that would be moved, as in {@link Roo.dd.DDProxy}.
19975 * This class should not be instantiated until the onload event to ensure that
19976 * the associated elements are available.
19977 * The following would define a DragDrop obj that would interact with any
19978 * other DragDrop obj in the "group1" group:
19980 * dd = new Roo.dd.DragDrop("div1", "group1");
19982 * Since none of the event handlers have been implemented, nothing would
19983 * actually happen if you were to run the code above. Normally you would
19984 * override this class or one of the default implementations, but you can
19985 * also override the methods you want on an instance of the class...
19987 * dd.onDragDrop = function(e, id) {
19988 * alert("dd was dropped on " + id);
19992 * @param {String} id of the element that is linked to this instance
19993 * @param {String} sGroup the group of related DragDrop objects
19994 * @param {object} config an object containing configurable attributes
19995 * Valid properties for DragDrop:
19996 * padding, isTarget, maintainOffset, primaryButtonOnly
19998 Roo.dd.DragDrop = function(id, sGroup, config) {
20000 this.init(id, sGroup, config);
20005 Roo.extend(Roo.dd.DragDrop, Roo.util.Observable , {
20008 * The id of the element associated with this object. This is what we
20009 * refer to as the "linked element" because the size and position of
20010 * this element is used to determine when the drag and drop objects have
20018 * Configuration attributes passed into the constructor
20025 * The id of the element that will be dragged. By default this is same
20026 * as the linked element , but could be changed to another element. Ex:
20028 * @property dragElId
20035 * the id of the element that initiates the drag operation. By default
20036 * this is the linked element, but could be changed to be a child of this
20037 * element. This lets us do things like only starting the drag when the
20038 * header element within the linked html element is clicked.
20039 * @property handleElId
20046 * An associative array of HTML tags that will be ignored if clicked.
20047 * @property invalidHandleTypes
20048 * @type {string: string}
20050 invalidHandleTypes: null,
20053 * An associative array of ids for elements that will be ignored if clicked
20054 * @property invalidHandleIds
20055 * @type {string: string}
20057 invalidHandleIds: null,
20060 * An indexted array of css class names for elements that will be ignored
20062 * @property invalidHandleClasses
20065 invalidHandleClasses: null,
20068 * The linked element's absolute X position at the time the drag was
20070 * @property startPageX
20077 * The linked element's absolute X position at the time the drag was
20079 * @property startPageY
20086 * The group defines a logical collection of DragDrop objects that are
20087 * related. Instances only get events when interacting with other
20088 * DragDrop object in the same group. This lets us define multiple
20089 * groups using a single DragDrop subclass if we want.
20091 * @type {string: string}
20096 * Individual drag/drop instances can be locked. This will prevent
20097 * onmousedown start drag.
20105 * Lock this instance
20108 lock: function() { this.locked = true; },
20111 * Unlock this instace
20114 unlock: function() { this.locked = false; },
20117 * By default, all insances can be a drop target. This can be disabled by
20118 * setting isTarget to false.
20125 * The padding configured for this drag and drop object for calculating
20126 * the drop zone intersection with this object.
20133 * Cached reference to the linked element
20134 * @property _domRef
20140 * Internal typeof flag
20141 * @property __ygDragDrop
20144 __ygDragDrop: true,
20147 * Set to true when horizontal contraints are applied
20148 * @property constrainX
20155 * Set to true when vertical contraints are applied
20156 * @property constrainY
20163 * The left constraint
20171 * The right constraint
20179 * The up constraint
20188 * The down constraint
20196 * Maintain offsets when we resetconstraints. Set to true when you want
20197 * the position of the element relative to its parent to stay the same
20198 * when the page changes
20200 * @property maintainOffset
20203 maintainOffset: false,
20206 * Array of pixel locations the element will snap to if we specified a
20207 * horizontal graduation/interval. This array is generated automatically
20208 * when you define a tick interval.
20215 * Array of pixel locations the element will snap to if we specified a
20216 * vertical graduation/interval. This array is generated automatically
20217 * when you define a tick interval.
20224 * By default the drag and drop instance will only respond to the primary
20225 * button click (left button for a right-handed mouse). Set to true to
20226 * allow drag and drop to start with any mouse click that is propogated
20228 * @property primaryButtonOnly
20231 primaryButtonOnly: true,
20234 * The availabe property is false until the linked dom element is accessible.
20235 * @property available
20241 * By default, drags can only be initiated if the mousedown occurs in the
20242 * region the linked element is. This is done in part to work around a
20243 * bug in some browsers that mis-report the mousedown if the previous
20244 * mouseup happened outside of the window. This property is set to true
20245 * if outer handles are defined.
20247 * @property hasOuterHandles
20251 hasOuterHandles: false,
20254 * Code that executes immediately before the startDrag event
20255 * @method b4StartDrag
20258 b4StartDrag: function(x, y) { },
20261 * Abstract method called after a drag/drop object is clicked
20262 * and the drag or mousedown time thresholds have beeen met.
20263 * @method startDrag
20264 * @param {int} X click location
20265 * @param {int} Y click location
20267 startDrag: function(x, y) { /* override this */ },
20270 * Code that executes immediately before the onDrag event
20274 b4Drag: function(e) { },
20277 * Abstract method called during the onMouseMove event while dragging an
20280 * @param {Event} e the mousemove event
20282 onDrag: function(e) { /* override this */ },
20285 * Abstract method called when this element fist begins hovering over
20286 * another DragDrop obj
20287 * @method onDragEnter
20288 * @param {Event} e the mousemove event
20289 * @param {String|DragDrop[]} id In POINT mode, the element
20290 * id this is hovering over. In INTERSECT mode, an array of one or more
20291 * dragdrop items being hovered over.
20293 onDragEnter: function(e, id) { /* override this */ },
20296 * Code that executes immediately before the onDragOver event
20297 * @method b4DragOver
20300 b4DragOver: function(e) { },
20303 * Abstract method called when this element is hovering over another
20305 * @method onDragOver
20306 * @param {Event} e the mousemove event
20307 * @param {String|DragDrop[]} id In POINT mode, the element
20308 * id this is hovering over. In INTERSECT mode, an array of dd items
20309 * being hovered over.
20311 onDragOver: function(e, id) { /* override this */ },
20314 * Code that executes immediately before the onDragOut event
20315 * @method b4DragOut
20318 b4DragOut: function(e) { },
20321 * Abstract method called when we are no longer hovering over an element
20322 * @method onDragOut
20323 * @param {Event} e the mousemove event
20324 * @param {String|DragDrop[]} id In POINT mode, the element
20325 * id this was hovering over. In INTERSECT mode, an array of dd items
20326 * that the mouse is no longer over.
20328 onDragOut: function(e, id) { /* override this */ },
20331 * Code that executes immediately before the onDragDrop event
20332 * @method b4DragDrop
20335 b4DragDrop: function(e) { },
20338 * Abstract method called when this item is dropped on another DragDrop
20340 * @method onDragDrop
20341 * @param {Event} e the mouseup event
20342 * @param {String|DragDrop[]} id In POINT mode, the element
20343 * id this was dropped on. In INTERSECT mode, an array of dd items this
20346 onDragDrop: function(e, id) { /* override this */ },
20349 * Abstract method called when this item is dropped on an area with no
20351 * @method onInvalidDrop
20352 * @param {Event} e the mouseup event
20354 onInvalidDrop: function(e) { /* override this */ },
20357 * Code that executes immediately before the endDrag event
20358 * @method b4EndDrag
20361 b4EndDrag: function(e) { },
20364 * Fired when we are done dragging the object
20366 * @param {Event} e the mouseup event
20368 endDrag: function(e) { /* override this */ },
20371 * Code executed immediately before the onMouseDown event
20372 * @method b4MouseDown
20373 * @param {Event} e the mousedown event
20376 b4MouseDown: function(e) { },
20379 * Event handler that fires when a drag/drop obj gets a mousedown
20380 * @method onMouseDown
20381 * @param {Event} e the mousedown event
20383 onMouseDown: function(e) { /* override this */ },
20386 * Event handler that fires when a drag/drop obj gets a mouseup
20387 * @method onMouseUp
20388 * @param {Event} e the mouseup event
20390 onMouseUp: function(e) { /* override this */ },
20393 * Override the onAvailable method to do what is needed after the initial
20394 * position was determined.
20395 * @method onAvailable
20397 onAvailable: function () {
20401 * Provides default constraint padding to "constrainTo" elements (defaults to {left: 0, right:0, top:0, bottom:0}).
20404 defaultPadding : {left:0, right:0, top:0, bottom:0},
20407 * Initializes the drag drop object's constraints to restrict movement to a certain element.
20411 var dd = new Roo.dd.DDProxy("dragDiv1", "proxytest",
20412 { dragElId: "existingProxyDiv" });
20413 dd.startDrag = function(){
20414 this.constrainTo("parent-id");
20417 * Or you can initalize it using the {@link Roo.Element} object:
20419 Roo.get("dragDiv1").initDDProxy("proxytest", {dragElId: "existingProxyDiv"}, {
20420 startDrag : function(){
20421 this.constrainTo("parent-id");
20425 * @param {String/HTMLElement/Element} constrainTo The element to constrain to.
20426 * @param {Object/Number} pad (optional) Pad provides a way to specify "padding" of the constraints,
20427 * and can be either a number for symmetrical padding (4 would be equal to {left:4, right:4, top:4, bottom:4}) or
20428 * an object containing the sides to pad. For example: {right:10, bottom:10}
20429 * @param {Boolean} inContent (optional) Constrain the draggable in the content box of the element (inside padding and borders)
20431 constrainTo : function(constrainTo, pad, inContent){
20432 if(typeof pad == "number"){
20433 pad = {left: pad, right:pad, top:pad, bottom:pad};
20435 pad = pad || this.defaultPadding;
20436 var b = Roo.get(this.getEl()).getBox();
20437 var ce = Roo.get(constrainTo);
20438 var s = ce.getScroll();
20439 var c, cd = ce.dom;
20440 if(cd == document.body){
20441 c = { x: s.left, y: s.top, width: Roo.lib.Dom.getViewWidth(), height: Roo.lib.Dom.getViewHeight()};
20444 c = {x : xy[0]+s.left, y: xy[1]+s.top, width: cd.clientWidth, height: cd.clientHeight};
20448 var topSpace = b.y - c.y;
20449 var leftSpace = b.x - c.x;
20451 this.resetConstraints();
20452 this.setXConstraint(leftSpace - (pad.left||0), // left
20453 c.width - leftSpace - b.width - (pad.right||0) //right
20455 this.setYConstraint(topSpace - (pad.top||0), //top
20456 c.height - topSpace - b.height - (pad.bottom||0) //bottom
20461 * Returns a reference to the linked element
20463 * @return {HTMLElement} the html element
20465 getEl: function() {
20466 if (!this._domRef) {
20467 this._domRef = Roo.getDom(this.id);
20470 return this._domRef;
20474 * Returns a reference to the actual element to drag. By default this is
20475 * the same as the html element, but it can be assigned to another
20476 * element. An example of this can be found in Roo.dd.DDProxy
20477 * @method getDragEl
20478 * @return {HTMLElement} the html element
20480 getDragEl: function() {
20481 return Roo.getDom(this.dragElId);
20485 * Sets up the DragDrop object. Must be called in the constructor of any
20486 * Roo.dd.DragDrop subclass
20488 * @param id the id of the linked element
20489 * @param {String} sGroup the group of related items
20490 * @param {object} config configuration attributes
20492 init: function(id, sGroup, config) {
20493 this.initTarget(id, sGroup, config);
20494 if (!Roo.isTouch) {
20495 Event.on(this.id, "mousedown", this.handleMouseDown, this);
20497 Event.on(this.id, "touchstart", this.handleMouseDown, this);
20498 // Event.on(this.id, "selectstart", Event.preventDefault);
20502 * Initializes Targeting functionality only... the object does not
20503 * get a mousedown handler.
20504 * @method initTarget
20505 * @param id the id of the linked element
20506 * @param {String} sGroup the group of related items
20507 * @param {object} config configuration attributes
20509 initTarget: function(id, sGroup, config) {
20511 // configuration attributes
20512 this.config = config || {};
20514 // create a local reference to the drag and drop manager
20515 this.DDM = Roo.dd.DDM;
20516 // initialize the groups array
20519 // assume that we have an element reference instead of an id if the
20520 // parameter is not a string
20521 if (typeof id !== "string") {
20528 // add to an interaction group
20529 this.addToGroup((sGroup) ? sGroup : "default");
20531 // We don't want to register this as the handle with the manager
20532 // so we just set the id rather than calling the setter.
20533 this.handleElId = id;
20535 // the linked element is the element that gets dragged by default
20536 this.setDragElId(id);
20538 // by default, clicked anchors will not start drag operations.
20539 this.invalidHandleTypes = { A: "A" };
20540 this.invalidHandleIds = {};
20541 this.invalidHandleClasses = [];
20543 this.applyConfig();
20545 this.handleOnAvailable();
20549 * Applies the configuration parameters that were passed into the constructor.
20550 * This is supposed to happen at each level through the inheritance chain. So
20551 * a DDProxy implentation will execute apply config on DDProxy, DD, and
20552 * DragDrop in order to get all of the parameters that are available in
20554 * @method applyConfig
20556 applyConfig: function() {
20558 // configurable properties:
20559 // padding, isTarget, maintainOffset, primaryButtonOnly
20560 this.padding = this.config.padding || [0, 0, 0, 0];
20561 this.isTarget = (this.config.isTarget !== false);
20562 this.maintainOffset = (this.config.maintainOffset);
20563 this.primaryButtonOnly = (this.config.primaryButtonOnly !== false);
20568 * Executed when the linked element is available
20569 * @method handleOnAvailable
20572 handleOnAvailable: function() {
20573 this.available = true;
20574 this.resetConstraints();
20575 this.onAvailable();
20579 * Configures the padding for the target zone in px. Effectively expands
20580 * (or reduces) the virtual object size for targeting calculations.
20581 * Supports css-style shorthand; if only one parameter is passed, all sides
20582 * will have that padding, and if only two are passed, the top and bottom
20583 * will have the first param, the left and right the second.
20584 * @method setPadding
20585 * @param {int} iTop Top pad
20586 * @param {int} iRight Right pad
20587 * @param {int} iBot Bot pad
20588 * @param {int} iLeft Left pad
20590 setPadding: function(iTop, iRight, iBot, iLeft) {
20591 // this.padding = [iLeft, iRight, iTop, iBot];
20592 if (!iRight && 0 !== iRight) {
20593 this.padding = [iTop, iTop, iTop, iTop];
20594 } else if (!iBot && 0 !== iBot) {
20595 this.padding = [iTop, iRight, iTop, iRight];
20597 this.padding = [iTop, iRight, iBot, iLeft];
20602 * Stores the initial placement of the linked element.
20603 * @method setInitialPosition
20604 * @param {int} diffX the X offset, default 0
20605 * @param {int} diffY the Y offset, default 0
20607 setInitPosition: function(diffX, diffY) {
20608 var el = this.getEl();
20610 if (!this.DDM.verifyEl(el)) {
20614 var dx = diffX || 0;
20615 var dy = diffY || 0;
20617 var p = Dom.getXY( el );
20619 this.initPageX = p[0] - dx;
20620 this.initPageY = p[1] - dy;
20622 this.lastPageX = p[0];
20623 this.lastPageY = p[1];
20626 this.setStartPosition(p);
20630 * Sets the start position of the element. This is set when the obj
20631 * is initialized, the reset when a drag is started.
20632 * @method setStartPosition
20633 * @param pos current position (from previous lookup)
20636 setStartPosition: function(pos) {
20637 var p = pos || Dom.getXY( this.getEl() );
20638 this.deltaSetXY = null;
20640 this.startPageX = p[0];
20641 this.startPageY = p[1];
20645 * Add this instance to a group of related drag/drop objects. All
20646 * instances belong to at least one group, and can belong to as many
20647 * groups as needed.
20648 * @method addToGroup
20649 * @param sGroup {string} the name of the group
20651 addToGroup: function(sGroup) {
20652 this.groups[sGroup] = true;
20653 this.DDM.regDragDrop(this, sGroup);
20657 * Remove's this instance from the supplied interaction group
20658 * @method removeFromGroup
20659 * @param {string} sGroup The group to drop
20661 removeFromGroup: function(sGroup) {
20662 if (this.groups[sGroup]) {
20663 delete this.groups[sGroup];
20666 this.DDM.removeDDFromGroup(this, sGroup);
20670 * Allows you to specify that an element other than the linked element
20671 * will be moved with the cursor during a drag
20672 * @method setDragElId
20673 * @param id {string} the id of the element that will be used to initiate the drag
20675 setDragElId: function(id) {
20676 this.dragElId = id;
20680 * Allows you to specify a child of the linked element that should be
20681 * used to initiate the drag operation. An example of this would be if
20682 * you have a content div with text and links. Clicking anywhere in the
20683 * content area would normally start the drag operation. Use this method
20684 * to specify that an element inside of the content div is the element
20685 * that starts the drag operation.
20686 * @method setHandleElId
20687 * @param id {string} the id of the element that will be used to
20688 * initiate the drag.
20690 setHandleElId: function(id) {
20691 if (typeof id !== "string") {
20694 this.handleElId = id;
20695 this.DDM.regHandle(this.id, id);
20699 * Allows you to set an element outside of the linked element as a drag
20701 * @method setOuterHandleElId
20702 * @param id the id of the element that will be used to initiate the drag
20704 setOuterHandleElId: function(id) {
20705 if (typeof id !== "string") {
20708 Event.on(id, "mousedown",
20709 this.handleMouseDown, this);
20710 this.setHandleElId(id);
20712 this.hasOuterHandles = true;
20716 * Remove all drag and drop hooks for this element
20719 unreg: function() {
20720 Event.un(this.id, "mousedown",
20721 this.handleMouseDown);
20722 Event.un(this.id, "touchstart",
20723 this.handleMouseDown);
20724 this._domRef = null;
20725 this.DDM._remove(this);
20728 destroy : function(){
20733 * Returns true if this instance is locked, or the drag drop mgr is locked
20734 * (meaning that all drag/drop is disabled on the page.)
20736 * @return {boolean} true if this obj or all drag/drop is locked, else
20739 isLocked: function() {
20740 return (this.DDM.isLocked() || this.locked);
20744 * Fired when this object is clicked
20745 * @method handleMouseDown
20747 * @param {Roo.dd.DragDrop} oDD the clicked dd object (this dd obj)
20750 handleMouseDown: function(e, oDD){
20752 if (!Roo.isTouch && this.primaryButtonOnly && e.button != 0) {
20753 //Roo.log('not touch/ button !=0');
20756 if (e.browserEvent.touches && e.browserEvent.touches.length != 1) {
20757 return; // double touch..
20761 if (this.isLocked()) {
20762 //Roo.log('locked');
20766 this.DDM.refreshCache(this.groups);
20767 // Roo.log([Roo.lib.Event.getPageX(e), Roo.lib.Event.getPageY(e)]);
20768 var pt = new Roo.lib.Point(Roo.lib.Event.getPageX(e), Roo.lib.Event.getPageY(e));
20769 if (!this.hasOuterHandles && !this.DDM.isOverTarget(pt, this) ) {
20770 //Roo.log('no outer handes or not over target');
20773 // Roo.log('check validator');
20774 if (this.clickValidator(e)) {
20775 // Roo.log('validate success');
20776 // set the initial element position
20777 this.setStartPosition();
20780 this.b4MouseDown(e);
20781 this.onMouseDown(e);
20783 this.DDM.handleMouseDown(e, this);
20785 this.DDM.stopEvent(e);
20793 clickValidator: function(e) {
20794 var target = e.getTarget();
20795 return ( this.isValidHandleChild(target) &&
20796 (this.id == this.handleElId ||
20797 this.DDM.handleWasClicked(target, this.id)) );
20801 * Allows you to specify a tag name that should not start a drag operation
20802 * when clicked. This is designed to facilitate embedding links within a
20803 * drag handle that do something other than start the drag.
20804 * @method addInvalidHandleType
20805 * @param {string} tagName the type of element to exclude
20807 addInvalidHandleType: function(tagName) {
20808 var type = tagName.toUpperCase();
20809 this.invalidHandleTypes[type] = type;
20813 * Lets you to specify an element id for a child of a drag handle
20814 * that should not initiate a drag
20815 * @method addInvalidHandleId
20816 * @param {string} id the element id of the element you wish to ignore
20818 addInvalidHandleId: function(id) {
20819 if (typeof id !== "string") {
20822 this.invalidHandleIds[id] = id;
20826 * Lets you specify a css class of elements that will not initiate a drag
20827 * @method addInvalidHandleClass
20828 * @param {string} cssClass the class of the elements you wish to ignore
20830 addInvalidHandleClass: function(cssClass) {
20831 this.invalidHandleClasses.push(cssClass);
20835 * Unsets an excluded tag name set by addInvalidHandleType
20836 * @method removeInvalidHandleType
20837 * @param {string} tagName the type of element to unexclude
20839 removeInvalidHandleType: function(tagName) {
20840 var type = tagName.toUpperCase();
20841 // this.invalidHandleTypes[type] = null;
20842 delete this.invalidHandleTypes[type];
20846 * Unsets an invalid handle id
20847 * @method removeInvalidHandleId
20848 * @param {string} id the id of the element to re-enable
20850 removeInvalidHandleId: function(id) {
20851 if (typeof id !== "string") {
20854 delete this.invalidHandleIds[id];
20858 * Unsets an invalid css class
20859 * @method removeInvalidHandleClass
20860 * @param {string} cssClass the class of the element(s) you wish to
20863 removeInvalidHandleClass: function(cssClass) {
20864 for (var i=0, len=this.invalidHandleClasses.length; i<len; ++i) {
20865 if (this.invalidHandleClasses[i] == cssClass) {
20866 delete this.invalidHandleClasses[i];
20872 * Checks the tag exclusion list to see if this click should be ignored
20873 * @method isValidHandleChild
20874 * @param {HTMLElement} node the HTMLElement to evaluate
20875 * @return {boolean} true if this is a valid tag type, false if not
20877 isValidHandleChild: function(node) {
20880 // var n = (node.nodeName == "#text") ? node.parentNode : node;
20883 nodeName = node.nodeName.toUpperCase();
20885 nodeName = node.nodeName;
20887 valid = valid && !this.invalidHandleTypes[nodeName];
20888 valid = valid && !this.invalidHandleIds[node.id];
20890 for (var i=0, len=this.invalidHandleClasses.length; valid && i<len; ++i) {
20891 valid = !Dom.hasClass(node, this.invalidHandleClasses[i]);
20900 * Create the array of horizontal tick marks if an interval was specified
20901 * in setXConstraint().
20902 * @method setXTicks
20905 setXTicks: function(iStartX, iTickSize) {
20907 this.xTickSize = iTickSize;
20911 for (var i = this.initPageX; i >= this.minX; i = i - iTickSize) {
20913 this.xTicks[this.xTicks.length] = i;
20918 for (i = this.initPageX; i <= this.maxX; i = i + iTickSize) {
20920 this.xTicks[this.xTicks.length] = i;
20925 this.xTicks.sort(this.DDM.numericSort) ;
20929 * Create the array of vertical tick marks if an interval was specified in
20930 * setYConstraint().
20931 * @method setYTicks
20934 setYTicks: function(iStartY, iTickSize) {
20936 this.yTickSize = iTickSize;
20940 for (var i = this.initPageY; i >= this.minY; i = i - iTickSize) {
20942 this.yTicks[this.yTicks.length] = i;
20947 for (i = this.initPageY; i <= this.maxY; i = i + iTickSize) {
20949 this.yTicks[this.yTicks.length] = i;
20954 this.yTicks.sort(this.DDM.numericSort) ;
20958 * By default, the element can be dragged any place on the screen. Use
20959 * this method to limit the horizontal travel of the element. Pass in
20960 * 0,0 for the parameters if you want to lock the drag to the y axis.
20961 * @method setXConstraint
20962 * @param {int} iLeft the number of pixels the element can move to the left
20963 * @param {int} iRight the number of pixels the element can move to the
20965 * @param {int} iTickSize optional parameter for specifying that the
20967 * should move iTickSize pixels at a time.
20969 setXConstraint: function(iLeft, iRight, iTickSize) {
20970 this.leftConstraint = iLeft;
20971 this.rightConstraint = iRight;
20973 this.minX = this.initPageX - iLeft;
20974 this.maxX = this.initPageX + iRight;
20975 if (iTickSize) { this.setXTicks(this.initPageX, iTickSize); }
20977 this.constrainX = true;
20981 * Clears any constraints applied to this instance. Also clears ticks
20982 * since they can't exist independent of a constraint at this time.
20983 * @method clearConstraints
20985 clearConstraints: function() {
20986 this.constrainX = false;
20987 this.constrainY = false;
20992 * Clears any tick interval defined for this instance
20993 * @method clearTicks
20995 clearTicks: function() {
20996 this.xTicks = null;
20997 this.yTicks = null;
20998 this.xTickSize = 0;
20999 this.yTickSize = 0;
21003 * By default, the element can be dragged any place on the screen. Set
21004 * this to limit the vertical travel of the element. Pass in 0,0 for the
21005 * parameters if you want to lock the drag to the x axis.
21006 * @method setYConstraint
21007 * @param {int} iUp the number of pixels the element can move up
21008 * @param {int} iDown the number of pixels the element can move down
21009 * @param {int} iTickSize optional parameter for specifying that the
21010 * element should move iTickSize pixels at a time.
21012 setYConstraint: function(iUp, iDown, iTickSize) {
21013 this.topConstraint = iUp;
21014 this.bottomConstraint = iDown;
21016 this.minY = this.initPageY - iUp;
21017 this.maxY = this.initPageY + iDown;
21018 if (iTickSize) { this.setYTicks(this.initPageY, iTickSize); }
21020 this.constrainY = true;
21025 * resetConstraints must be called if you manually reposition a dd element.
21026 * @method resetConstraints
21027 * @param {boolean} maintainOffset
21029 resetConstraints: function() {
21032 // Maintain offsets if necessary
21033 if (this.initPageX || this.initPageX === 0) {
21034 // figure out how much this thing has moved
21035 var dx = (this.maintainOffset) ? this.lastPageX - this.initPageX : 0;
21036 var dy = (this.maintainOffset) ? this.lastPageY - this.initPageY : 0;
21038 this.setInitPosition(dx, dy);
21040 // This is the first time we have detected the element's position
21042 this.setInitPosition();
21045 if (this.constrainX) {
21046 this.setXConstraint( this.leftConstraint,
21047 this.rightConstraint,
21051 if (this.constrainY) {
21052 this.setYConstraint( this.topConstraint,
21053 this.bottomConstraint,
21059 * Normally the drag element is moved pixel by pixel, but we can specify
21060 * that it move a number of pixels at a time. This method resolves the
21061 * location when we have it set up like this.
21063 * @param {int} val where we want to place the object
21064 * @param {int[]} tickArray sorted array of valid points
21065 * @return {int} the closest tick
21068 getTick: function(val, tickArray) {
21071 // If tick interval is not defined, it is effectively 1 pixel,
21072 // so we return the value passed to us.
21074 } else if (tickArray[0] >= val) {
21075 // The value is lower than the first tick, so we return the first
21077 return tickArray[0];
21079 for (var i=0, len=tickArray.length; i<len; ++i) {
21081 if (tickArray[next] && tickArray[next] >= val) {
21082 var diff1 = val - tickArray[i];
21083 var diff2 = tickArray[next] - val;
21084 return (diff2 > diff1) ? tickArray[i] : tickArray[next];
21088 // The value is larger than the last tick, so we return the last
21090 return tickArray[tickArray.length - 1];
21097 * @return {string} string representation of the dd obj
21099 toString: function() {
21100 return ("DragDrop " + this.id);
21108 * Ext JS Library 1.1.1
21109 * Copyright(c) 2006-2007, Ext JS, LLC.
21111 * Originally Released Under LGPL - original licence link has changed is not relivant.
21114 * <script type="text/javascript">
21119 * The drag and drop utility provides a framework for building drag and drop
21120 * applications. In addition to enabling drag and drop for specific elements,
21121 * the drag and drop elements are tracked by the manager class, and the
21122 * interactions between the various elements are tracked during the drag and
21123 * the implementing code is notified about these important moments.
21126 // Only load the library once. Rewriting the manager class would orphan
21127 // existing drag and drop instances.
21128 if (!Roo.dd.DragDropMgr) {
21131 * @class Roo.dd.DragDropMgr
21132 * DragDropMgr is a singleton that tracks the element interaction for
21133 * all DragDrop items in the window. Generally, you will not call
21134 * this class directly, but it does have helper methods that could
21135 * be useful in your DragDrop implementations.
21138 Roo.dd.DragDropMgr = function() {
21140 var Event = Roo.EventManager;
21145 * Two dimensional Array of registered DragDrop objects. The first
21146 * dimension is the DragDrop item group, the second the DragDrop
21149 * @type {string: string}
21156 * Array of element ids defined as drag handles. Used to determine
21157 * if the element that generated the mousedown event is actually the
21158 * handle and not the html element itself.
21159 * @property handleIds
21160 * @type {string: string}
21167 * the DragDrop object that is currently being dragged
21168 * @property dragCurrent
21176 * the DragDrop object(s) that are being hovered over
21177 * @property dragOvers
21185 * the X distance between the cursor and the object being dragged
21194 * the Y distance between the cursor and the object being dragged
21203 * Flag to determine if we should prevent the default behavior of the
21204 * events we define. By default this is true, but this can be set to
21205 * false if you need the default behavior (not recommended)
21206 * @property preventDefault
21210 preventDefault: true,
21213 * Flag to determine if we should stop the propagation of the events
21214 * we generate. This is true by default but you may want to set it to
21215 * false if the html element contains other features that require the
21217 * @property stopPropagation
21221 stopPropagation: true,
21224 * Internal flag that is set to true when drag and drop has been
21226 * @property initialized
21233 * All drag and drop can be disabled.
21241 * Called the first time an element is registered.
21247 this.initialized = true;
21251 * In point mode, drag and drop interaction is defined by the
21252 * location of the cursor during the drag/drop
21260 * In intersect mode, drag and drop interactio nis defined by the
21261 * overlap of two or more drag and drop objects.
21262 * @property INTERSECT
21269 * The current drag and drop mode. Default: POINT
21277 * Runs method on all drag and drop objects
21278 * @method _execOnAll
21282 _execOnAll: function(sMethod, args) {
21283 for (var i in this.ids) {
21284 for (var j in this.ids[i]) {
21285 var oDD = this.ids[i][j];
21286 if (! this.isTypeOfDD(oDD)) {
21289 oDD[sMethod].apply(oDD, args);
21295 * Drag and drop initialization. Sets up the global event handlers
21300 _onLoad: function() {
21304 if (!Roo.isTouch) {
21305 Event.on(document, "mouseup", this.handleMouseUp, this, true);
21306 Event.on(document, "mousemove", this.handleMouseMove, this, true);
21308 Event.on(document, "touchend", this.handleMouseUp, this, true);
21309 Event.on(document, "touchmove", this.handleMouseMove, this, true);
21311 Event.on(window, "unload", this._onUnload, this, true);
21312 Event.on(window, "resize", this._onResize, this, true);
21313 // Event.on(window, "mouseout", this._test);
21318 * Reset constraints on all drag and drop objs
21319 * @method _onResize
21323 _onResize: function(e) {
21324 this._execOnAll("resetConstraints", []);
21328 * Lock all drag and drop functionality
21332 lock: function() { this.locked = true; },
21335 * Unlock all drag and drop functionality
21339 unlock: function() { this.locked = false; },
21342 * Is drag and drop locked?
21344 * @return {boolean} True if drag and drop is locked, false otherwise.
21347 isLocked: function() { return this.locked; },
21350 * Location cache that is set for all drag drop objects when a drag is
21351 * initiated, cleared when the drag is finished.
21352 * @property locationCache
21359 * Set useCache to false if you want to force object the lookup of each
21360 * drag and drop linked element constantly during a drag.
21361 * @property useCache
21368 * The number of pixels that the mouse needs to move after the
21369 * mousedown before the drag is initiated. Default=3;
21370 * @property clickPixelThresh
21374 clickPixelThresh: 3,
21377 * The number of milliseconds after the mousedown event to initiate the
21378 * drag if we don't get a mouseup event. Default=1000
21379 * @property clickTimeThresh
21383 clickTimeThresh: 350,
21386 * Flag that indicates that either the drag pixel threshold or the
21387 * mousdown time threshold has been met
21388 * @property dragThreshMet
21393 dragThreshMet: false,
21396 * Timeout used for the click time threshold
21397 * @property clickTimeout
21402 clickTimeout: null,
21405 * The X position of the mousedown event stored for later use when a
21406 * drag threshold is met.
21415 * The Y position of the mousedown event stored for later use when a
21416 * drag threshold is met.
21425 * Each DragDrop instance must be registered with the DragDropMgr.
21426 * This is executed in DragDrop.init()
21427 * @method regDragDrop
21428 * @param {DragDrop} oDD the DragDrop object to register
21429 * @param {String} sGroup the name of the group this element belongs to
21432 regDragDrop: function(oDD, sGroup) {
21433 if (!this.initialized) { this.init(); }
21435 if (!this.ids[sGroup]) {
21436 this.ids[sGroup] = {};
21438 this.ids[sGroup][oDD.id] = oDD;
21442 * Removes the supplied dd instance from the supplied group. Executed
21443 * by DragDrop.removeFromGroup, so don't call this function directly.
21444 * @method removeDDFromGroup
21448 removeDDFromGroup: function(oDD, sGroup) {
21449 if (!this.ids[sGroup]) {
21450 this.ids[sGroup] = {};
21453 var obj = this.ids[sGroup];
21454 if (obj && obj[oDD.id]) {
21455 delete obj[oDD.id];
21460 * Unregisters a drag and drop item. This is executed in
21461 * DragDrop.unreg, use that method instead of calling this directly.
21466 _remove: function(oDD) {
21467 for (var g in oDD.groups) {
21468 if (g && this.ids[g][oDD.id]) {
21469 delete this.ids[g][oDD.id];
21472 delete this.handleIds[oDD.id];
21476 * Each DragDrop handle element must be registered. This is done
21477 * automatically when executing DragDrop.setHandleElId()
21478 * @method regHandle
21479 * @param {String} sDDId the DragDrop id this element is a handle for
21480 * @param {String} sHandleId the id of the element that is the drag
21484 regHandle: function(sDDId, sHandleId) {
21485 if (!this.handleIds[sDDId]) {
21486 this.handleIds[sDDId] = {};
21488 this.handleIds[sDDId][sHandleId] = sHandleId;
21492 * Utility function to determine if a given element has been
21493 * registered as a drag drop item.
21494 * @method isDragDrop
21495 * @param {String} id the element id to check
21496 * @return {boolean} true if this element is a DragDrop item,
21500 isDragDrop: function(id) {
21501 return ( this.getDDById(id) ) ? true : false;
21505 * Returns the drag and drop instances that are in all groups the
21506 * passed in instance belongs to.
21507 * @method getRelated
21508 * @param {DragDrop} p_oDD the obj to get related data for
21509 * @param {boolean} bTargetsOnly if true, only return targetable objs
21510 * @return {DragDrop[]} the related instances
21513 getRelated: function(p_oDD, bTargetsOnly) {
21515 for (var i in p_oDD.groups) {
21516 for (j in this.ids[i]) {
21517 var dd = this.ids[i][j];
21518 if (! this.isTypeOfDD(dd)) {
21521 if (!bTargetsOnly || dd.isTarget) {
21522 oDDs[oDDs.length] = dd;
21531 * Returns true if the specified dd target is a legal target for
21532 * the specifice drag obj
21533 * @method isLegalTarget
21534 * @param {DragDrop} the drag obj
21535 * @param {DragDrop} the target
21536 * @return {boolean} true if the target is a legal target for the
21540 isLegalTarget: function (oDD, oTargetDD) {
21541 var targets = this.getRelated(oDD, true);
21542 for (var i=0, len=targets.length;i<len;++i) {
21543 if (targets[i].id == oTargetDD.id) {
21552 * My goal is to be able to transparently determine if an object is
21553 * typeof DragDrop, and the exact subclass of DragDrop. typeof
21554 * returns "object", oDD.constructor.toString() always returns
21555 * "DragDrop" and not the name of the subclass. So for now it just
21556 * evaluates a well-known variable in DragDrop.
21557 * @method isTypeOfDD
21558 * @param {Object} the object to evaluate
21559 * @return {boolean} true if typeof oDD = DragDrop
21562 isTypeOfDD: function (oDD) {
21563 return (oDD && oDD.__ygDragDrop);
21567 * Utility function to determine if a given element has been
21568 * registered as a drag drop handle for the given Drag Drop object.
21570 * @param {String} id the element id to check
21571 * @return {boolean} true if this element is a DragDrop handle, false
21575 isHandle: function(sDDId, sHandleId) {
21576 return ( this.handleIds[sDDId] &&
21577 this.handleIds[sDDId][sHandleId] );
21581 * Returns the DragDrop instance for a given id
21582 * @method getDDById
21583 * @param {String} id the id of the DragDrop object
21584 * @return {DragDrop} the drag drop object, null if it is not found
21587 getDDById: function(id) {
21588 for (var i in this.ids) {
21589 if (this.ids[i][id]) {
21590 return this.ids[i][id];
21597 * Fired after a registered DragDrop object gets the mousedown event.
21598 * Sets up the events required to track the object being dragged
21599 * @method handleMouseDown
21600 * @param {Event} e the event
21601 * @param oDD the DragDrop object being dragged
21605 handleMouseDown: function(e, oDD) {
21607 Roo.QuickTips.disable();
21609 this.currentTarget = e.getTarget();
21611 this.dragCurrent = oDD;
21613 var el = oDD.getEl();
21615 // track start position
21616 this.startX = e.getPageX();
21617 this.startY = e.getPageY();
21619 this.deltaX = this.startX - el.offsetLeft;
21620 this.deltaY = this.startY - el.offsetTop;
21622 this.dragThreshMet = false;
21624 this.clickTimeout = setTimeout(
21626 var DDM = Roo.dd.DDM;
21627 DDM.startDrag(DDM.startX, DDM.startY);
21629 this.clickTimeThresh );
21633 * Fired when either the drag pixel threshol or the mousedown hold
21634 * time threshold has been met.
21635 * @method startDrag
21636 * @param x {int} the X position of the original mousedown
21637 * @param y {int} the Y position of the original mousedown
21640 startDrag: function(x, y) {
21641 clearTimeout(this.clickTimeout);
21642 if (this.dragCurrent) {
21643 this.dragCurrent.b4StartDrag(x, y);
21644 this.dragCurrent.startDrag(x, y);
21646 this.dragThreshMet = true;
21650 * Internal function to handle the mouseup event. Will be invoked
21651 * from the context of the document.
21652 * @method handleMouseUp
21653 * @param {Event} e the event
21657 handleMouseUp: function(e) {
21660 Roo.QuickTips.enable();
21662 if (! this.dragCurrent) {
21666 clearTimeout(this.clickTimeout);
21668 if (this.dragThreshMet) {
21669 this.fireEvents(e, true);
21679 * Utility to stop event propagation and event default, if these
21680 * features are turned on.
21681 * @method stopEvent
21682 * @param {Event} e the event as returned by this.getEvent()
21685 stopEvent: function(e){
21686 if(this.stopPropagation) {
21687 e.stopPropagation();
21690 if (this.preventDefault) {
21691 e.preventDefault();
21696 * Internal function to clean up event handlers after the drag
21697 * operation is complete
21699 * @param {Event} e the event
21703 stopDrag: function(e) {
21704 // Fire the drag end event for the item that was dragged
21705 if (this.dragCurrent) {
21706 if (this.dragThreshMet) {
21707 this.dragCurrent.b4EndDrag(e);
21708 this.dragCurrent.endDrag(e);
21711 this.dragCurrent.onMouseUp(e);
21714 this.dragCurrent = null;
21715 this.dragOvers = {};
21719 * Internal function to handle the mousemove event. Will be invoked
21720 * from the context of the html element.
21722 * @TODO figure out what we can do about mouse events lost when the
21723 * user drags objects beyond the window boundary. Currently we can
21724 * detect this in internet explorer by verifying that the mouse is
21725 * down during the mousemove event. Firefox doesn't give us the
21726 * button state on the mousemove event.
21727 * @method handleMouseMove
21728 * @param {Event} e the event
21732 handleMouseMove: function(e) {
21733 if (! this.dragCurrent) {
21737 // var button = e.which || e.button;
21739 // check for IE mouseup outside of page boundary
21740 if (Roo.isIE && (e.button !== 0 && e.button !== 1 && e.button !== 2)) {
21742 return this.handleMouseUp(e);
21745 if (!this.dragThreshMet) {
21746 var diffX = Math.abs(this.startX - e.getPageX());
21747 var diffY = Math.abs(this.startY - e.getPageY());
21748 if (diffX > this.clickPixelThresh ||
21749 diffY > this.clickPixelThresh) {
21750 this.startDrag(this.startX, this.startY);
21754 if (this.dragThreshMet) {
21755 this.dragCurrent.b4Drag(e);
21756 this.dragCurrent.onDrag(e);
21757 if(!this.dragCurrent.moveOnly){
21758 this.fireEvents(e, false);
21768 * Iterates over all of the DragDrop elements to find ones we are
21769 * hovering over or dropping on
21770 * @method fireEvents
21771 * @param {Event} e the event
21772 * @param {boolean} isDrop is this a drop op or a mouseover op?
21776 fireEvents: function(e, isDrop) {
21777 var dc = this.dragCurrent;
21779 // If the user did the mouse up outside of the window, we could
21780 // get here even though we have ended the drag.
21781 if (!dc || dc.isLocked()) {
21785 var pt = e.getPoint();
21787 // cache the previous dragOver array
21793 var enterEvts = [];
21795 // Check to see if the object(s) we were hovering over is no longer
21796 // being hovered over so we can fire the onDragOut event
21797 for (var i in this.dragOvers) {
21799 var ddo = this.dragOvers[i];
21801 if (! this.isTypeOfDD(ddo)) {
21805 if (! this.isOverTarget(pt, ddo, this.mode)) {
21806 outEvts.push( ddo );
21809 oldOvers[i] = true;
21810 delete this.dragOvers[i];
21813 for (var sGroup in dc.groups) {
21815 if ("string" != typeof sGroup) {
21819 for (i in this.ids[sGroup]) {
21820 var oDD = this.ids[sGroup][i];
21821 if (! this.isTypeOfDD(oDD)) {
21825 if (oDD.isTarget && !oDD.isLocked() && oDD != dc) {
21826 if (this.isOverTarget(pt, oDD, this.mode)) {
21827 // look for drop interactions
21829 dropEvts.push( oDD );
21830 // look for drag enter and drag over interactions
21833 // initial drag over: dragEnter fires
21834 if (!oldOvers[oDD.id]) {
21835 enterEvts.push( oDD );
21836 // subsequent drag overs: dragOver fires
21838 overEvts.push( oDD );
21841 this.dragOvers[oDD.id] = oDD;
21849 if (outEvts.length) {
21850 dc.b4DragOut(e, outEvts);
21851 dc.onDragOut(e, outEvts);
21854 if (enterEvts.length) {
21855 dc.onDragEnter(e, enterEvts);
21858 if (overEvts.length) {
21859 dc.b4DragOver(e, overEvts);
21860 dc.onDragOver(e, overEvts);
21863 if (dropEvts.length) {
21864 dc.b4DragDrop(e, dropEvts);
21865 dc.onDragDrop(e, dropEvts);
21869 // fire dragout events
21871 for (i=0, len=outEvts.length; i<len; ++i) {
21872 dc.b4DragOut(e, outEvts[i].id);
21873 dc.onDragOut(e, outEvts[i].id);
21876 // fire enter events
21877 for (i=0,len=enterEvts.length; i<len; ++i) {
21878 // dc.b4DragEnter(e, oDD.id);
21879 dc.onDragEnter(e, enterEvts[i].id);
21882 // fire over events
21883 for (i=0,len=overEvts.length; i<len; ++i) {
21884 dc.b4DragOver(e, overEvts[i].id);
21885 dc.onDragOver(e, overEvts[i].id);
21888 // fire drop events
21889 for (i=0, len=dropEvts.length; i<len; ++i) {
21890 dc.b4DragDrop(e, dropEvts[i].id);
21891 dc.onDragDrop(e, dropEvts[i].id);
21896 // notify about a drop that did not find a target
21897 if (isDrop && !dropEvts.length) {
21898 dc.onInvalidDrop(e);
21904 * Helper function for getting the best match from the list of drag
21905 * and drop objects returned by the drag and drop events when we are
21906 * in INTERSECT mode. It returns either the first object that the
21907 * cursor is over, or the object that has the greatest overlap with
21908 * the dragged element.
21909 * @method getBestMatch
21910 * @param {DragDrop[]} dds The array of drag and drop objects
21912 * @return {DragDrop} The best single match
21915 getBestMatch: function(dds) {
21917 // Return null if the input is not what we expect
21918 //if (!dds || !dds.length || dds.length == 0) {
21920 // If there is only one item, it wins
21921 //} else if (dds.length == 1) {
21923 var len = dds.length;
21928 // Loop through the targeted items
21929 for (var i=0; i<len; ++i) {
21931 // If the cursor is over the object, it wins. If the
21932 // cursor is over multiple matches, the first one we come
21934 if (dd.cursorIsOver) {
21937 // Otherwise the object with the most overlap wins
21940 winner.overlap.getArea() < dd.overlap.getArea()) {
21951 * Refreshes the cache of the top-left and bottom-right points of the
21952 * drag and drop objects in the specified group(s). This is in the
21953 * format that is stored in the drag and drop instance, so typical
21956 * Roo.dd.DragDropMgr.refreshCache(ddinstance.groups);
21960 * Roo.dd.DragDropMgr.refreshCache({group1:true, group2:true});
21962 * @TODO this really should be an indexed array. Alternatively this
21963 * method could accept both.
21964 * @method refreshCache
21965 * @param {Object} groups an associative array of groups to refresh
21968 refreshCache: function(groups) {
21969 for (var sGroup in groups) {
21970 if ("string" != typeof sGroup) {
21973 for (var i in this.ids[sGroup]) {
21974 var oDD = this.ids[sGroup][i];
21976 if (this.isTypeOfDD(oDD)) {
21977 // if (this.isTypeOfDD(oDD) && oDD.isTarget) {
21978 var loc = this.getLocation(oDD);
21980 this.locationCache[oDD.id] = loc;
21982 delete this.locationCache[oDD.id];
21983 // this will unregister the drag and drop object if
21984 // the element is not in a usable state
21993 * This checks to make sure an element exists and is in the DOM. The
21994 * main purpose is to handle cases where innerHTML is used to remove
21995 * drag and drop objects from the DOM. IE provides an 'unspecified
21996 * error' when trying to access the offsetParent of such an element
21998 * @param {HTMLElement} el the element to check
21999 * @return {boolean} true if the element looks usable
22002 verifyEl: function(el) {
22007 parent = el.offsetParent;
22010 parent = el.offsetParent;
22021 * Returns a Region object containing the drag and drop element's position
22022 * and size, including the padding configured for it
22023 * @method getLocation
22024 * @param {DragDrop} oDD the drag and drop object to get the
22026 * @return {Roo.lib.Region} a Region object representing the total area
22027 * the element occupies, including any padding
22028 * the instance is configured for.
22031 getLocation: function(oDD) {
22032 if (! this.isTypeOfDD(oDD)) {
22036 var el = oDD.getEl(), pos, x1, x2, y1, y2, t, r, b, l;
22039 pos= Roo.lib.Dom.getXY(el);
22047 x2 = x1 + el.offsetWidth;
22049 y2 = y1 + el.offsetHeight;
22051 t = y1 - oDD.padding[0];
22052 r = x2 + oDD.padding[1];
22053 b = y2 + oDD.padding[2];
22054 l = x1 - oDD.padding[3];
22056 return new Roo.lib.Region( t, r, b, l );
22060 * Checks the cursor location to see if it over the target
22061 * @method isOverTarget
22062 * @param {Roo.lib.Point} pt The point to evaluate
22063 * @param {DragDrop} oTarget the DragDrop object we are inspecting
22064 * @return {boolean} true if the mouse is over the target
22068 isOverTarget: function(pt, oTarget, intersect) {
22069 // use cache if available
22070 var loc = this.locationCache[oTarget.id];
22071 if (!loc || !this.useCache) {
22072 loc = this.getLocation(oTarget);
22073 this.locationCache[oTarget.id] = loc;
22081 oTarget.cursorIsOver = loc.contains( pt );
22083 // DragDrop is using this as a sanity check for the initial mousedown
22084 // in this case we are done. In POINT mode, if the drag obj has no
22085 // contraints, we are also done. Otherwise we need to evaluate the
22086 // location of the target as related to the actual location of the
22087 // dragged element.
22088 var dc = this.dragCurrent;
22089 if (!dc || !dc.getTargetCoord ||
22090 (!intersect && !dc.constrainX && !dc.constrainY)) {
22091 return oTarget.cursorIsOver;
22094 oTarget.overlap = null;
22096 // Get the current location of the drag element, this is the
22097 // location of the mouse event less the delta that represents
22098 // where the original mousedown happened on the element. We
22099 // need to consider constraints and ticks as well.
22100 var pos = dc.getTargetCoord(pt.x, pt.y);
22102 var el = dc.getDragEl();
22103 var curRegion = new Roo.lib.Region( pos.y,
22104 pos.x + el.offsetWidth,
22105 pos.y + el.offsetHeight,
22108 var overlap = curRegion.intersect(loc);
22111 oTarget.overlap = overlap;
22112 return (intersect) ? true : oTarget.cursorIsOver;
22119 * unload event handler
22120 * @method _onUnload
22124 _onUnload: function(e, me) {
22125 Roo.dd.DragDropMgr.unregAll();
22129 * Cleans up the drag and drop events and objects.
22134 unregAll: function() {
22136 if (this.dragCurrent) {
22138 this.dragCurrent = null;
22141 this._execOnAll("unreg", []);
22143 for (i in this.elementCache) {
22144 delete this.elementCache[i];
22147 this.elementCache = {};
22152 * A cache of DOM elements
22153 * @property elementCache
22160 * Get the wrapper for the DOM element specified
22161 * @method getElWrapper
22162 * @param {String} id the id of the element to get
22163 * @return {Roo.dd.DDM.ElementWrapper} the wrapped element
22165 * @deprecated This wrapper isn't that useful
22168 getElWrapper: function(id) {
22169 var oWrapper = this.elementCache[id];
22170 if (!oWrapper || !oWrapper.el) {
22171 oWrapper = this.elementCache[id] =
22172 new this.ElementWrapper(Roo.getDom(id));
22178 * Returns the actual DOM element
22179 * @method getElement
22180 * @param {String} id the id of the elment to get
22181 * @return {Object} The element
22182 * @deprecated use Roo.getDom instead
22185 getElement: function(id) {
22186 return Roo.getDom(id);
22190 * Returns the style property for the DOM element (i.e.,
22191 * document.getElById(id).style)
22193 * @param {String} id the id of the elment to get
22194 * @return {Object} The style property of the element
22195 * @deprecated use Roo.getDom instead
22198 getCss: function(id) {
22199 var el = Roo.getDom(id);
22200 return (el) ? el.style : null;
22204 * Inner class for cached elements
22205 * @class DragDropMgr.ElementWrapper
22210 ElementWrapper: function(el) {
22215 this.el = el || null;
22220 this.id = this.el && el.id;
22222 * A reference to the style property
22225 this.css = this.el && el.style;
22229 * Returns the X position of an html element
22231 * @param el the element for which to get the position
22232 * @return {int} the X coordinate
22234 * @deprecated use Roo.lib.Dom.getX instead
22237 getPosX: function(el) {
22238 return Roo.lib.Dom.getX(el);
22242 * Returns the Y position of an html element
22244 * @param el the element for which to get the position
22245 * @return {int} the Y coordinate
22246 * @deprecated use Roo.lib.Dom.getY instead
22249 getPosY: function(el) {
22250 return Roo.lib.Dom.getY(el);
22254 * Swap two nodes. In IE, we use the native method, for others we
22255 * emulate the IE behavior
22257 * @param n1 the first node to swap
22258 * @param n2 the other node to swap
22261 swapNode: function(n1, n2) {
22265 var p = n2.parentNode;
22266 var s = n2.nextSibling;
22269 p.insertBefore(n1, n2);
22270 } else if (n2 == n1.nextSibling) {
22271 p.insertBefore(n2, n1);
22273 n1.parentNode.replaceChild(n2, n1);
22274 p.insertBefore(n1, s);
22280 * Returns the current scroll position
22281 * @method getScroll
22285 getScroll: function () {
22286 var t, l, dde=document.documentElement, db=document.body;
22287 if (dde && (dde.scrollTop || dde.scrollLeft)) {
22289 l = dde.scrollLeft;
22296 return { top: t, left: l };
22300 * Returns the specified element style property
22302 * @param {HTMLElement} el the element
22303 * @param {string} styleProp the style property
22304 * @return {string} The value of the style property
22305 * @deprecated use Roo.lib.Dom.getStyle
22308 getStyle: function(el, styleProp) {
22309 return Roo.fly(el).getStyle(styleProp);
22313 * Gets the scrollTop
22314 * @method getScrollTop
22315 * @return {int} the document's scrollTop
22318 getScrollTop: function () { return this.getScroll().top; },
22321 * Gets the scrollLeft
22322 * @method getScrollLeft
22323 * @return {int} the document's scrollTop
22326 getScrollLeft: function () { return this.getScroll().left; },
22329 * Sets the x/y position of an element to the location of the
22332 * @param {HTMLElement} moveEl The element to move
22333 * @param {HTMLElement} targetEl The position reference element
22336 moveToEl: function (moveEl, targetEl) {
22337 var aCoord = Roo.lib.Dom.getXY(targetEl);
22338 Roo.lib.Dom.setXY(moveEl, aCoord);
22342 * Numeric array sort function
22343 * @method numericSort
22346 numericSort: function(a, b) { return (a - b); },
22350 * @property _timeoutCount
22357 * Trying to make the load order less important. Without this we get
22358 * an error if this file is loaded before the Event Utility.
22359 * @method _addListeners
22363 _addListeners: function() {
22364 var DDM = Roo.dd.DDM;
22365 if ( Roo.lib.Event && document ) {
22368 if (DDM._timeoutCount > 2000) {
22370 setTimeout(DDM._addListeners, 10);
22371 if (document && document.body) {
22372 DDM._timeoutCount += 1;
22379 * Recursively searches the immediate parent and all child nodes for
22380 * the handle element in order to determine wheter or not it was
22382 * @method handleWasClicked
22383 * @param node the html element to inspect
22386 handleWasClicked: function(node, id) {
22387 if (this.isHandle(id, node.id)) {
22390 // check to see if this is a text node child of the one we want
22391 var p = node.parentNode;
22394 if (this.isHandle(id, p.id)) {
22409 // shorter alias, save a few bytes
22410 Roo.dd.DDM = Roo.dd.DragDropMgr;
22411 Roo.dd.DDM._addListeners();
22415 * Ext JS Library 1.1.1
22416 * Copyright(c) 2006-2007, Ext JS, LLC.
22418 * Originally Released Under LGPL - original licence link has changed is not relivant.
22421 * <script type="text/javascript">
22426 * A DragDrop implementation where the linked element follows the
22427 * mouse cursor during a drag.
22428 * @extends Roo.dd.DragDrop
22430 * @param {String} id the id of the linked element
22431 * @param {String} sGroup the group of related DragDrop items
22432 * @param {object} config an object containing configurable attributes
22433 * Valid properties for DD:
22436 Roo.dd.DD = function(id, sGroup, config) {
22438 this.init(id, sGroup, config);
22442 Roo.extend(Roo.dd.DD, Roo.dd.DragDrop, {
22445 * When set to true, the utility automatically tries to scroll the browser
22446 * window wehn a drag and drop element is dragged near the viewport boundary.
22447 * Defaults to true.
22454 * Sets the pointer offset to the distance between the linked element's top
22455 * left corner and the location the element was clicked
22456 * @method autoOffset
22457 * @param {int} iPageX the X coordinate of the click
22458 * @param {int} iPageY the Y coordinate of the click
22460 autoOffset: function(iPageX, iPageY) {
22461 var x = iPageX - this.startPageX;
22462 var y = iPageY - this.startPageY;
22463 this.setDelta(x, y);
22467 * Sets the pointer offset. You can call this directly to force the
22468 * offset to be in a particular location (e.g., pass in 0,0 to set it
22469 * to the center of the object)
22471 * @param {int} iDeltaX the distance from the left
22472 * @param {int} iDeltaY the distance from the top
22474 setDelta: function(iDeltaX, iDeltaY) {
22475 this.deltaX = iDeltaX;
22476 this.deltaY = iDeltaY;
22480 * Sets the drag element to the location of the mousedown or click event,
22481 * maintaining the cursor location relative to the location on the element
22482 * that was clicked. Override this if you want to place the element in a
22483 * location other than where the cursor is.
22484 * @method setDragElPos
22485 * @param {int} iPageX the X coordinate of the mousedown or drag event
22486 * @param {int} iPageY the Y coordinate of the mousedown or drag event
22488 setDragElPos: function(iPageX, iPageY) {
22489 // the first time we do this, we are going to check to make sure
22490 // the element has css positioning
22492 var el = this.getDragEl();
22493 this.alignElWithMouse(el, iPageX, iPageY);
22497 * Sets the element to the location of the mousedown or click event,
22498 * maintaining the cursor location relative to the location on the element
22499 * that was clicked. Override this if you want to place the element in a
22500 * location other than where the cursor is.
22501 * @method alignElWithMouse
22502 * @param {HTMLElement} el the element to move
22503 * @param {int} iPageX the X coordinate of the mousedown or drag event
22504 * @param {int} iPageY the Y coordinate of the mousedown or drag event
22506 alignElWithMouse: function(el, iPageX, iPageY) {
22507 var oCoord = this.getTargetCoord(iPageX, iPageY);
22508 var fly = el.dom ? el : Roo.fly(el);
22509 if (!this.deltaSetXY) {
22510 var aCoord = [oCoord.x, oCoord.y];
22512 var newLeft = fly.getLeft(true);
22513 var newTop = fly.getTop(true);
22514 this.deltaSetXY = [ newLeft - oCoord.x, newTop - oCoord.y ];
22516 fly.setLeftTop(oCoord.x + this.deltaSetXY[0], oCoord.y + this.deltaSetXY[1]);
22519 this.cachePosition(oCoord.x, oCoord.y);
22520 this.autoScroll(oCoord.x, oCoord.y, el.offsetHeight, el.offsetWidth);
22525 * Saves the most recent position so that we can reset the constraints and
22526 * tick marks on-demand. We need to know this so that we can calculate the
22527 * number of pixels the element is offset from its original position.
22528 * @method cachePosition
22529 * @param iPageX the current x position (optional, this just makes it so we
22530 * don't have to look it up again)
22531 * @param iPageY the current y position (optional, this just makes it so we
22532 * don't have to look it up again)
22534 cachePosition: function(iPageX, iPageY) {
22536 this.lastPageX = iPageX;
22537 this.lastPageY = iPageY;
22539 var aCoord = Roo.lib.Dom.getXY(this.getEl());
22540 this.lastPageX = aCoord[0];
22541 this.lastPageY = aCoord[1];
22546 * Auto-scroll the window if the dragged object has been moved beyond the
22547 * visible window boundary.
22548 * @method autoScroll
22549 * @param {int} x the drag element's x position
22550 * @param {int} y the drag element's y position
22551 * @param {int} h the height of the drag element
22552 * @param {int} w the width of the drag element
22555 autoScroll: function(x, y, h, w) {
22558 // The client height
22559 var clientH = Roo.lib.Dom.getViewWidth();
22561 // The client width
22562 var clientW = Roo.lib.Dom.getViewHeight();
22564 // The amt scrolled down
22565 var st = this.DDM.getScrollTop();
22567 // The amt scrolled right
22568 var sl = this.DDM.getScrollLeft();
22570 // Location of the bottom of the element
22573 // Location of the right of the element
22576 // The distance from the cursor to the bottom of the visible area,
22577 // adjusted so that we don't scroll if the cursor is beyond the
22578 // element drag constraints
22579 var toBot = (clientH + st - y - this.deltaY);
22581 // The distance from the cursor to the right of the visible area
22582 var toRight = (clientW + sl - x - this.deltaX);
22585 // How close to the edge the cursor must be before we scroll
22586 // var thresh = (document.all) ? 100 : 40;
22589 // How many pixels to scroll per autoscroll op. This helps to reduce
22590 // clunky scrolling. IE is more sensitive about this ... it needs this
22591 // value to be higher.
22592 var scrAmt = (document.all) ? 80 : 30;
22594 // Scroll down if we are near the bottom of the visible page and the
22595 // obj extends below the crease
22596 if ( bot > clientH && toBot < thresh ) {
22597 window.scrollTo(sl, st + scrAmt);
22600 // Scroll up if the window is scrolled down and the top of the object
22601 // goes above the top border
22602 if ( y < st && st > 0 && y - st < thresh ) {
22603 window.scrollTo(sl, st - scrAmt);
22606 // Scroll right if the obj is beyond the right border and the cursor is
22607 // near the border.
22608 if ( right > clientW && toRight < thresh ) {
22609 window.scrollTo(sl + scrAmt, st);
22612 // Scroll left if the window has been scrolled to the right and the obj
22613 // extends past the left border
22614 if ( x < sl && sl > 0 && x - sl < thresh ) {
22615 window.scrollTo(sl - scrAmt, st);
22621 * Finds the location the element should be placed if we want to move
22622 * it to where the mouse location less the click offset would place us.
22623 * @method getTargetCoord
22624 * @param {int} iPageX the X coordinate of the click
22625 * @param {int} iPageY the Y coordinate of the click
22626 * @return an object that contains the coordinates (Object.x and Object.y)
22629 getTargetCoord: function(iPageX, iPageY) {
22632 var x = iPageX - this.deltaX;
22633 var y = iPageY - this.deltaY;
22635 if (this.constrainX) {
22636 if (x < this.minX) { x = this.minX; }
22637 if (x > this.maxX) { x = this.maxX; }
22640 if (this.constrainY) {
22641 if (y < this.minY) { y = this.minY; }
22642 if (y > this.maxY) { y = this.maxY; }
22645 x = this.getTick(x, this.xTicks);
22646 y = this.getTick(y, this.yTicks);
22653 * Sets up config options specific to this class. Overrides
22654 * Roo.dd.DragDrop, but all versions of this method through the
22655 * inheritance chain are called
22657 applyConfig: function() {
22658 Roo.dd.DD.superclass.applyConfig.call(this);
22659 this.scroll = (this.config.scroll !== false);
22663 * Event that fires prior to the onMouseDown event. Overrides
22666 b4MouseDown: function(e) {
22667 // this.resetConstraints();
22668 this.autoOffset(e.getPageX(),
22673 * Event that fires prior to the onDrag event. Overrides
22676 b4Drag: function(e) {
22677 this.setDragElPos(e.getPageX(),
22681 toString: function() {
22682 return ("DD " + this.id);
22685 //////////////////////////////////////////////////////////////////////////
22686 // Debugging ygDragDrop events that can be overridden
22687 //////////////////////////////////////////////////////////////////////////
22689 startDrag: function(x, y) {
22692 onDrag: function(e) {
22695 onDragEnter: function(e, id) {
22698 onDragOver: function(e, id) {
22701 onDragOut: function(e, id) {
22704 onDragDrop: function(e, id) {
22707 endDrag: function(e) {
22714 * Ext JS Library 1.1.1
22715 * Copyright(c) 2006-2007, Ext JS, LLC.
22717 * Originally Released Under LGPL - original licence link has changed is not relivant.
22720 * <script type="text/javascript">
22724 * @class Roo.dd.DDProxy
22725 * A DragDrop implementation that inserts an empty, bordered div into
22726 * the document that follows the cursor during drag operations. At the time of
22727 * the click, the frame div is resized to the dimensions of the linked html
22728 * element, and moved to the exact location of the linked element.
22730 * References to the "frame" element refer to the single proxy element that
22731 * was created to be dragged in place of all DDProxy elements on the
22734 * @extends Roo.dd.DD
22736 * @param {String} id the id of the linked html element
22737 * @param {String} sGroup the group of related DragDrop objects
22738 * @param {object} config an object containing configurable attributes
22739 * Valid properties for DDProxy in addition to those in DragDrop:
22740 * resizeFrame, centerFrame, dragElId
22742 Roo.dd.DDProxy = function(id, sGroup, config) {
22744 this.init(id, sGroup, config);
22750 * The default drag frame div id
22751 * @property Roo.dd.DDProxy.dragElId
22755 Roo.dd.DDProxy.dragElId = "ygddfdiv";
22757 Roo.extend(Roo.dd.DDProxy, Roo.dd.DD, {
22760 * By default we resize the drag frame to be the same size as the element
22761 * we want to drag (this is to get the frame effect). We can turn it off
22762 * if we want a different behavior.
22763 * @property resizeFrame
22769 * By default the frame is positioned exactly where the drag element is, so
22770 * we use the cursor offset provided by Roo.dd.DD. Another option that works only if
22771 * you do not have constraints on the obj is to have the drag frame centered
22772 * around the cursor. Set centerFrame to true for this effect.
22773 * @property centerFrame
22776 centerFrame: false,
22779 * Creates the proxy element if it does not yet exist
22780 * @method createFrame
22782 createFrame: function() {
22784 var body = document.body;
22786 if (!body || !body.firstChild) {
22787 setTimeout( function() { self.createFrame(); }, 50 );
22791 var div = this.getDragEl();
22794 div = document.createElement("div");
22795 div.id = this.dragElId;
22798 s.position = "absolute";
22799 s.visibility = "hidden";
22801 s.border = "2px solid #aaa";
22804 // appendChild can blow up IE if invoked prior to the window load event
22805 // while rendering a table. It is possible there are other scenarios
22806 // that would cause this to happen as well.
22807 body.insertBefore(div, body.firstChild);
22812 * Initialization for the drag frame element. Must be called in the
22813 * constructor of all subclasses
22814 * @method initFrame
22816 initFrame: function() {
22817 this.createFrame();
22820 applyConfig: function() {
22821 Roo.dd.DDProxy.superclass.applyConfig.call(this);
22823 this.resizeFrame = (this.config.resizeFrame !== false);
22824 this.centerFrame = (this.config.centerFrame);
22825 this.setDragElId(this.config.dragElId || Roo.dd.DDProxy.dragElId);
22829 * Resizes the drag frame to the dimensions of the clicked object, positions
22830 * it over the object, and finally displays it
22831 * @method showFrame
22832 * @param {int} iPageX X click position
22833 * @param {int} iPageY Y click position
22836 showFrame: function(iPageX, iPageY) {
22837 var el = this.getEl();
22838 var dragEl = this.getDragEl();
22839 var s = dragEl.style;
22841 this._resizeProxy();
22843 if (this.centerFrame) {
22844 this.setDelta( Math.round(parseInt(s.width, 10)/2),
22845 Math.round(parseInt(s.height, 10)/2) );
22848 this.setDragElPos(iPageX, iPageY);
22850 Roo.fly(dragEl).show();
22854 * The proxy is automatically resized to the dimensions of the linked
22855 * element when a drag is initiated, unless resizeFrame is set to false
22856 * @method _resizeProxy
22859 _resizeProxy: function() {
22860 if (this.resizeFrame) {
22861 var el = this.getEl();
22862 Roo.fly(this.getDragEl()).setSize(el.offsetWidth, el.offsetHeight);
22866 // overrides Roo.dd.DragDrop
22867 b4MouseDown: function(e) {
22868 var x = e.getPageX();
22869 var y = e.getPageY();
22870 this.autoOffset(x, y);
22871 this.setDragElPos(x, y);
22874 // overrides Roo.dd.DragDrop
22875 b4StartDrag: function(x, y) {
22876 // show the drag frame
22877 this.showFrame(x, y);
22880 // overrides Roo.dd.DragDrop
22881 b4EndDrag: function(e) {
22882 Roo.fly(this.getDragEl()).hide();
22885 // overrides Roo.dd.DragDrop
22886 // By default we try to move the element to the last location of the frame.
22887 // This is so that the default behavior mirrors that of Roo.dd.DD.
22888 endDrag: function(e) {
22890 var lel = this.getEl();
22891 var del = this.getDragEl();
22893 // Show the drag frame briefly so we can get its position
22894 del.style.visibility = "";
22897 // Hide the linked element before the move to get around a Safari
22899 lel.style.visibility = "hidden";
22900 Roo.dd.DDM.moveToEl(lel, del);
22901 del.style.visibility = "hidden";
22902 lel.style.visibility = "";
22907 beforeMove : function(){
22911 afterDrag : function(){
22915 toString: function() {
22916 return ("DDProxy " + this.id);
22922 * Ext JS Library 1.1.1
22923 * Copyright(c) 2006-2007, Ext JS, LLC.
22925 * Originally Released Under LGPL - original licence link has changed is not relivant.
22928 * <script type="text/javascript">
22932 * @class Roo.dd.DDTarget
22933 * A DragDrop implementation that does not move, but can be a drop
22934 * target. You would get the same result by simply omitting implementation
22935 * for the event callbacks, but this way we reduce the processing cost of the
22936 * event listener and the callbacks.
22937 * @extends Roo.dd.DragDrop
22939 * @param {String} id the id of the element that is a drop target
22940 * @param {String} sGroup the group of related DragDrop objects
22941 * @param {object} config an object containing configurable attributes
22942 * Valid properties for DDTarget in addition to those in
22946 Roo.dd.DDTarget = function(id, sGroup, config) {
22948 this.initTarget(id, sGroup, config);
22950 if (config && (config.listeners || config.events)) {
22951 Roo.dd.DragDrop.superclass.constructor.call(this, {
22952 listeners : config.listeners || {},
22953 events : config.events || {}
22958 // Roo.dd.DDTarget.prototype = new Roo.dd.DragDrop();
22959 Roo.extend(Roo.dd.DDTarget, Roo.dd.DragDrop, {
22960 toString: function() {
22961 return ("DDTarget " + this.id);
22966 * Ext JS Library 1.1.1
22967 * Copyright(c) 2006-2007, Ext JS, LLC.
22969 * Originally Released Under LGPL - original licence link has changed is not relivant.
22972 * <script type="text/javascript">
22977 * @class Roo.dd.ScrollManager
22978 * Provides automatic scrolling of overflow regions in the page during drag operations.<br><br>
22979 * <b>Note: This class uses "Point Mode" and is untested in "Intersect Mode".</b>
22982 Roo.dd.ScrollManager = function(){
22983 var ddm = Roo.dd.DragDropMgr;
22990 var onStop = function(e){
22995 var triggerRefresh = function(){
22996 if(ddm.dragCurrent){
22997 ddm.refreshCache(ddm.dragCurrent.groups);
23001 var doScroll = function(){
23002 if(ddm.dragCurrent){
23003 var dds = Roo.dd.ScrollManager;
23005 if(proc.el.scroll(proc.dir, dds.increment)){
23009 proc.el.scroll(proc.dir, dds.increment, true, dds.animDuration, triggerRefresh);
23014 var clearProc = function(){
23016 clearInterval(proc.id);
23023 var startProc = function(el, dir){
23024 Roo.log('scroll startproc');
23028 proc.id = setInterval(doScroll, Roo.dd.ScrollManager.frequency);
23031 var onFire = function(e, isDrop){
23033 if(isDrop || !ddm.dragCurrent){ return; }
23034 var dds = Roo.dd.ScrollManager;
23035 if(!dragEl || dragEl != ddm.dragCurrent){
23036 dragEl = ddm.dragCurrent;
23037 // refresh regions on drag start
23038 dds.refreshCache();
23041 var xy = Roo.lib.Event.getXY(e);
23042 var pt = new Roo.lib.Point(xy[0], xy[1]);
23043 for(var id in els){
23044 var el = els[id], r = el._region;
23045 if(r && r.contains(pt) && el.isScrollable()){
23046 if(r.bottom - pt.y <= dds.thresh){
23048 startProc(el, "down");
23051 }else if(r.right - pt.x <= dds.thresh){
23053 startProc(el, "left");
23056 }else if(pt.y - r.top <= dds.thresh){
23058 startProc(el, "up");
23061 }else if(pt.x - r.left <= dds.thresh){
23063 startProc(el, "right");
23072 ddm.fireEvents = ddm.fireEvents.createSequence(onFire, ddm);
23073 ddm.stopDrag = ddm.stopDrag.createSequence(onStop, ddm);
23077 * Registers new overflow element(s) to auto scroll
23078 * @param {String/HTMLElement/Element/Array} el The id of or the element to be scrolled or an array of either
23080 register : function(el){
23081 if(el instanceof Array){
23082 for(var i = 0, len = el.length; i < len; i++) {
23083 this.register(el[i]);
23089 Roo.dd.ScrollManager.els = els;
23093 * Unregisters overflow element(s) so they are no longer scrolled
23094 * @param {String/HTMLElement/Element/Array} el The id of or the element to be removed or an array of either
23096 unregister : function(el){
23097 if(el instanceof Array){
23098 for(var i = 0, len = el.length; i < len; i++) {
23099 this.unregister(el[i]);
23108 * The number of pixels from the edge of a container the pointer needs to be to
23109 * trigger scrolling (defaults to 25)
23115 * The number of pixels to scroll in each scroll increment (defaults to 50)
23121 * The frequency of scrolls in milliseconds (defaults to 500)
23127 * True to animate the scroll (defaults to true)
23133 * The animation duration in seconds -
23134 * MUST BE less than Roo.dd.ScrollManager.frequency! (defaults to .4)
23140 * Manually trigger a cache refresh.
23142 refreshCache : function(){
23143 for(var id in els){
23144 if(typeof els[id] == 'object'){ // for people extending the object prototype
23145 els[id]._region = els[id].getRegion();
23152 * Ext JS Library 1.1.1
23153 * Copyright(c) 2006-2007, Ext JS, LLC.
23155 * Originally Released Under LGPL - original licence link has changed is not relivant.
23158 * <script type="text/javascript">
23163 * @class Roo.dd.Registry
23164 * Provides easy access to all drag drop components that are registered on a page. Items can be retrieved either
23165 * directly by DOM node id, or by passing in the drag drop event that occurred and looking up the event target.
23168 Roo.dd.Registry = function(){
23171 var autoIdSeed = 0;
23173 var getId = function(el, autogen){
23174 if(typeof el == "string"){
23178 if(!id && autogen !== false){
23179 id = "roodd-" + (++autoIdSeed);
23187 * Register a drag drop element
23188 * @param {String|HTMLElement} element The id or DOM node to register
23189 * @param {Object} data (optional) A custom data object that will be passed between the elements that are involved
23190 * in drag drop operations. You can populate this object with any arbitrary properties that your own code
23191 * knows how to interpret, plus there are some specific properties known to the Registry that should be
23192 * populated in the data object (if applicable):
23194 Value Description<br />
23195 --------- ------------------------------------------<br />
23196 handles Array of DOM nodes that trigger dragging<br />
23197 for the element being registered<br />
23198 isHandle True if the element passed in triggers<br />
23199 dragging itself, else false
23202 register : function(el, data){
23204 if(typeof el == "string"){
23205 el = document.getElementById(el);
23208 elements[getId(el)] = data;
23209 if(data.isHandle !== false){
23210 handles[data.ddel.id] = data;
23213 var hs = data.handles;
23214 for(var i = 0, len = hs.length; i < len; i++){
23215 handles[getId(hs[i])] = data;
23221 * Unregister a drag drop element
23222 * @param {String|HTMLElement} element The id or DOM node to unregister
23224 unregister : function(el){
23225 var id = getId(el, false);
23226 var data = elements[id];
23228 delete elements[id];
23230 var hs = data.handles;
23231 for(var i = 0, len = hs.length; i < len; i++){
23232 delete handles[getId(hs[i], false)];
23239 * Returns the handle registered for a DOM Node by id
23240 * @param {String|HTMLElement} id The DOM node or id to look up
23241 * @return {Object} handle The custom handle data
23243 getHandle : function(id){
23244 if(typeof id != "string"){ // must be element?
23247 return handles[id];
23251 * Returns the handle that is registered for the DOM node that is the target of the event
23252 * @param {Event} e The event
23253 * @return {Object} handle The custom handle data
23255 getHandleFromEvent : function(e){
23256 var t = Roo.lib.Event.getTarget(e);
23257 return t ? handles[t.id] : null;
23261 * Returns a custom data object that is registered for a DOM node by id
23262 * @param {String|HTMLElement} id The DOM node or id to look up
23263 * @return {Object} data The custom data
23265 getTarget : function(id){
23266 if(typeof id != "string"){ // must be element?
23269 return elements[id];
23273 * Returns a custom data object that is registered for the DOM node that is the target of the event
23274 * @param {Event} e The event
23275 * @return {Object} data The custom data
23277 getTargetFromEvent : function(e){
23278 var t = Roo.lib.Event.getTarget(e);
23279 return t ? elements[t.id] || handles[t.id] : null;
23284 * Ext JS Library 1.1.1
23285 * Copyright(c) 2006-2007, Ext JS, LLC.
23287 * Originally Released Under LGPL - original licence link has changed is not relivant.
23290 * <script type="text/javascript">
23295 * @class Roo.dd.StatusProxy
23296 * A specialized drag proxy that supports a drop status icon, {@link Roo.Layer} styles and auto-repair. This is the
23297 * default drag proxy used by all Roo.dd components.
23299 * @param {Object} config
23301 Roo.dd.StatusProxy = function(config){
23302 Roo.apply(this, config);
23303 this.id = this.id || Roo.id();
23304 this.el = new Roo.Layer({
23306 id: this.id, tag: "div", cls: "x-dd-drag-proxy "+this.dropNotAllowed, children: [
23307 {tag: "div", cls: "x-dd-drop-icon"},
23308 {tag: "div", cls: "x-dd-drag-ghost"}
23311 shadow: !config || config.shadow !== false
23313 this.ghost = Roo.get(this.el.dom.childNodes[1]);
23314 this.dropStatus = this.dropNotAllowed;
23317 Roo.dd.StatusProxy.prototype = {
23319 * @cfg {String} dropAllowed
23320 * The CSS class to apply to the status element when drop is allowed (defaults to "x-dd-drop-ok").
23322 dropAllowed : "x-dd-drop-ok",
23324 * @cfg {String} dropNotAllowed
23325 * The CSS class to apply to the status element when drop is not allowed (defaults to "x-dd-drop-nodrop").
23327 dropNotAllowed : "x-dd-drop-nodrop",
23330 * Updates the proxy's visual element to indicate the status of whether or not drop is allowed
23331 * over the current target element.
23332 * @param {String} cssClass The css class for the new drop status indicator image
23334 setStatus : function(cssClass){
23335 cssClass = cssClass || this.dropNotAllowed;
23336 if(this.dropStatus != cssClass){
23337 this.el.replaceClass(this.dropStatus, cssClass);
23338 this.dropStatus = cssClass;
23343 * Resets the status indicator to the default dropNotAllowed value
23344 * @param {Boolean} clearGhost True to also remove all content from the ghost, false to preserve it
23346 reset : function(clearGhost){
23347 this.el.dom.className = "x-dd-drag-proxy " + this.dropNotAllowed;
23348 this.dropStatus = this.dropNotAllowed;
23350 this.ghost.update("");
23355 * Updates the contents of the ghost element
23356 * @param {String} html The html that will replace the current innerHTML of the ghost element
23358 update : function(html){
23359 if(typeof html == "string"){
23360 this.ghost.update(html);
23362 this.ghost.update("");
23363 html.style.margin = "0";
23364 this.ghost.dom.appendChild(html);
23366 // ensure float = none set?? cant remember why though.
23367 var el = this.ghost.dom.firstChild;
23369 Roo.fly(el).setStyle('float', 'none');
23374 * Returns the underlying proxy {@link Roo.Layer}
23375 * @return {Roo.Layer} el
23377 getEl : function(){
23382 * Returns the ghost element
23383 * @return {Roo.Element} el
23385 getGhost : function(){
23391 * @param {Boolean} clear True to reset the status and clear the ghost contents, false to preserve them
23393 hide : function(clear){
23401 * Stops the repair animation if it's currently running
23404 if(this.anim && this.anim.isAnimated && this.anim.isAnimated()){
23410 * Displays this proxy
23417 * Force the Layer to sync its shadow and shim positions to the element
23424 * Causes the proxy to return to its position of origin via an animation. Should be called after an
23425 * invalid drop operation by the item being dragged.
23426 * @param {Array} xy The XY position of the element ([x, y])
23427 * @param {Function} callback The function to call after the repair is complete
23428 * @param {Object} scope The scope in which to execute the callback
23430 repair : function(xy, callback, scope){
23431 this.callback = callback;
23432 this.scope = scope;
23433 if(xy && this.animRepair !== false){
23434 this.el.addClass("x-dd-drag-repair");
23435 this.el.hideUnders(true);
23436 this.anim = this.el.shift({
23437 duration: this.repairDuration || .5,
23441 callback: this.afterRepair,
23445 this.afterRepair();
23450 afterRepair : function(){
23452 if(typeof this.callback == "function"){
23453 this.callback.call(this.scope || this);
23455 this.callback = null;
23460 * Ext JS Library 1.1.1
23461 * Copyright(c) 2006-2007, Ext JS, LLC.
23463 * Originally Released Under LGPL - original licence link has changed is not relivant.
23466 * <script type="text/javascript">
23470 * @class Roo.dd.DragSource
23471 * @extends Roo.dd.DDProxy
23472 * A simple class that provides the basic implementation needed to make any element draggable.
23474 * @param {String/HTMLElement/Element} el The container element
23475 * @param {Object} config
23477 Roo.dd.DragSource = function(el, config){
23478 this.el = Roo.get(el);
23479 this.dragData = {};
23481 Roo.apply(this, config);
23484 this.proxy = new Roo.dd.StatusProxy();
23487 Roo.dd.DragSource.superclass.constructor.call(this, this.el.dom, this.ddGroup || this.group,
23488 {dragElId : this.proxy.id, resizeFrame: false, isTarget: false, scroll: this.scroll === true});
23490 this.dragging = false;
23493 Roo.extend(Roo.dd.DragSource, Roo.dd.DDProxy, {
23495 * @cfg {String} dropAllowed
23496 * The CSS class returned to the drag source when drop is allowed (defaults to "x-dd-drop-ok").
23498 dropAllowed : "x-dd-drop-ok",
23500 * @cfg {String} dropNotAllowed
23501 * The CSS class returned to the drag source when drop is not allowed (defaults to "x-dd-drop-nodrop").
23503 dropNotAllowed : "x-dd-drop-nodrop",
23506 * Returns the data object associated with this drag source
23507 * @return {Object} data An object containing arbitrary data
23509 getDragData : function(e){
23510 return this.dragData;
23514 onDragEnter : function(e, id){
23515 var target = Roo.dd.DragDropMgr.getDDById(id);
23516 this.cachedTarget = target;
23517 if(this.beforeDragEnter(target, e, id) !== false){
23518 if(target.isNotifyTarget){
23519 var status = target.notifyEnter(this, e, this.dragData);
23520 this.proxy.setStatus(status);
23522 this.proxy.setStatus(this.dropAllowed);
23525 if(this.afterDragEnter){
23527 * An empty function by default, but provided so that you can perform a custom action
23528 * when the dragged item enters the drop target by providing an implementation.
23529 * @param {Roo.dd.DragDrop} target The drop target
23530 * @param {Event} e The event object
23531 * @param {String} id The id of the dragged element
23532 * @method afterDragEnter
23534 this.afterDragEnter(target, e, id);
23540 * An empty function by default, but provided so that you can perform a custom action
23541 * before the dragged item enters the drop target and optionally cancel the onDragEnter.
23542 * @param {Roo.dd.DragDrop} target The drop target
23543 * @param {Event} e The event object
23544 * @param {String} id The id of the dragged element
23545 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
23547 beforeDragEnter : function(target, e, id){
23552 alignElWithMouse: function() {
23553 Roo.dd.DragSource.superclass.alignElWithMouse.apply(this, arguments);
23558 onDragOver : function(e, id){
23559 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
23560 if(this.beforeDragOver(target, e, id) !== false){
23561 if(target.isNotifyTarget){
23562 var status = target.notifyOver(this, e, this.dragData);
23563 this.proxy.setStatus(status);
23566 if(this.afterDragOver){
23568 * An empty function by default, but provided so that you can perform a custom action
23569 * while the dragged item is over the drop target by providing an implementation.
23570 * @param {Roo.dd.DragDrop} target The drop target
23571 * @param {Event} e The event object
23572 * @param {String} id The id of the dragged element
23573 * @method afterDragOver
23575 this.afterDragOver(target, e, id);
23581 * An empty function by default, but provided so that you can perform a custom action
23582 * while the dragged item is over the drop target and optionally cancel the onDragOver.
23583 * @param {Roo.dd.DragDrop} target The drop target
23584 * @param {Event} e The event object
23585 * @param {String} id The id of the dragged element
23586 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
23588 beforeDragOver : function(target, e, id){
23593 onDragOut : function(e, id){
23594 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
23595 if(this.beforeDragOut(target, e, id) !== false){
23596 if(target.isNotifyTarget){
23597 target.notifyOut(this, e, this.dragData);
23599 this.proxy.reset();
23600 if(this.afterDragOut){
23602 * An empty function by default, but provided so that you can perform a custom action
23603 * after the dragged item is dragged out of the target without dropping.
23604 * @param {Roo.dd.DragDrop} target The drop target
23605 * @param {Event} e The event object
23606 * @param {String} id The id of the dragged element
23607 * @method afterDragOut
23609 this.afterDragOut(target, e, id);
23612 this.cachedTarget = null;
23616 * An empty function by default, but provided so that you can perform a custom action before the dragged
23617 * item is dragged out of the target without dropping, and optionally cancel the onDragOut.
23618 * @param {Roo.dd.DragDrop} target The drop target
23619 * @param {Event} e The event object
23620 * @param {String} id The id of the dragged element
23621 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
23623 beforeDragOut : function(target, e, id){
23628 onDragDrop : function(e, id){
23629 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
23630 if(this.beforeDragDrop(target, e, id) !== false){
23631 if(target.isNotifyTarget){
23632 if(target.notifyDrop(this, e, this.dragData)){ // valid drop?
23633 this.onValidDrop(target, e, id);
23635 this.onInvalidDrop(target, e, id);
23638 this.onValidDrop(target, e, id);
23641 if(this.afterDragDrop){
23643 * An empty function by default, but provided so that you can perform a custom action
23644 * after a valid drag drop has occurred by providing an implementation.
23645 * @param {Roo.dd.DragDrop} target The drop target
23646 * @param {Event} e The event object
23647 * @param {String} id The id of the dropped element
23648 * @method afterDragDrop
23650 this.afterDragDrop(target, e, id);
23653 delete this.cachedTarget;
23657 * An empty function by default, but provided so that you can perform a custom action before the dragged
23658 * item is dropped onto the target and optionally cancel the onDragDrop.
23659 * @param {Roo.dd.DragDrop} target The drop target
23660 * @param {Event} e The event object
23661 * @param {String} id The id of the dragged element
23662 * @return {Boolean} isValid True if the drag drop event is valid, else false to cancel
23664 beforeDragDrop : function(target, e, id){
23669 onValidDrop : function(target, e, id){
23671 if(this.afterValidDrop){
23673 * An empty function by default, but provided so that you can perform a custom action
23674 * after a valid drop has occurred by providing an implementation.
23675 * @param {Object} target The target DD
23676 * @param {Event} e The event object
23677 * @param {String} id The id of the dropped element
23678 * @method afterInvalidDrop
23680 this.afterValidDrop(target, e, id);
23685 getRepairXY : function(e, data){
23686 return this.el.getXY();
23690 onInvalidDrop : function(target, e, id){
23691 this.beforeInvalidDrop(target, e, id);
23692 if(this.cachedTarget){
23693 if(this.cachedTarget.isNotifyTarget){
23694 this.cachedTarget.notifyOut(this, e, this.dragData);
23696 this.cacheTarget = null;
23698 this.proxy.repair(this.getRepairXY(e, this.dragData), this.afterRepair, this);
23700 if(this.afterInvalidDrop){
23702 * An empty function by default, but provided so that you can perform a custom action
23703 * after an invalid drop has occurred by providing an implementation.
23704 * @param {Event} e The event object
23705 * @param {String} id The id of the dropped element
23706 * @method afterInvalidDrop
23708 this.afterInvalidDrop(e, id);
23713 afterRepair : function(){
23715 this.el.highlight(this.hlColor || "c3daf9");
23717 this.dragging = false;
23721 * An empty function by default, but provided so that you can perform a custom action after an invalid
23722 * drop has occurred.
23723 * @param {Roo.dd.DragDrop} target The drop target
23724 * @param {Event} e The event object
23725 * @param {String} id The id of the dragged element
23726 * @return {Boolean} isValid True if the invalid drop should proceed, else false to cancel
23728 beforeInvalidDrop : function(target, e, id){
23733 handleMouseDown : function(e){
23734 if(this.dragging) {
23737 var data = this.getDragData(e);
23738 if(data && this.onBeforeDrag(data, e) !== false){
23739 this.dragData = data;
23741 Roo.dd.DragSource.superclass.handleMouseDown.apply(this, arguments);
23746 * An empty function by default, but provided so that you can perform a custom action before the initial
23747 * drag event begins and optionally cancel it.
23748 * @param {Object} data An object containing arbitrary data to be shared with drop targets
23749 * @param {Event} e The event object
23750 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
23752 onBeforeDrag : function(data, e){
23757 * An empty function by default, but provided so that you can perform a custom action once the initial
23758 * drag event has begun. The drag cannot be canceled from this function.
23759 * @param {Number} x The x position of the click on the dragged object
23760 * @param {Number} y The y position of the click on the dragged object
23762 onStartDrag : Roo.emptyFn,
23764 // private - YUI override
23765 startDrag : function(x, y){
23766 this.proxy.reset();
23767 this.dragging = true;
23768 this.proxy.update("");
23769 this.onInitDrag(x, y);
23774 onInitDrag : function(x, y){
23775 var clone = this.el.dom.cloneNode(true);
23776 clone.id = Roo.id(); // prevent duplicate ids
23777 this.proxy.update(clone);
23778 this.onStartDrag(x, y);
23783 * Returns the drag source's underlying {@link Roo.dd.StatusProxy}
23784 * @return {Roo.dd.StatusProxy} proxy The StatusProxy
23786 getProxy : function(){
23791 * Hides the drag source's {@link Roo.dd.StatusProxy}
23793 hideProxy : function(){
23795 this.proxy.reset(true);
23796 this.dragging = false;
23800 triggerCacheRefresh : function(){
23801 Roo.dd.DDM.refreshCache(this.groups);
23804 // private - override to prevent hiding
23805 b4EndDrag: function(e) {
23808 // private - override to prevent moving
23809 endDrag : function(e){
23810 this.onEndDrag(this.dragData, e);
23814 onEndDrag : function(data, e){
23817 // private - pin to cursor
23818 autoOffset : function(x, y) {
23819 this.setDelta(-12, -20);
23823 * Ext JS Library 1.1.1
23824 * Copyright(c) 2006-2007, Ext JS, LLC.
23826 * Originally Released Under LGPL - original licence link has changed is not relivant.
23829 * <script type="text/javascript">
23834 * @class Roo.dd.DropTarget
23835 * @extends Roo.dd.DDTarget
23836 * A simple class that provides the basic implementation needed to make any element a drop target that can have
23837 * draggable items dropped onto it. The drop has no effect until an implementation of notifyDrop is provided.
23839 * @param {String/HTMLElement/Element} el The container element
23840 * @param {Object} config
23842 Roo.dd.DropTarget = function(el, config){
23843 this.el = Roo.get(el);
23845 var listeners = false; ;
23846 if (config && config.listeners) {
23847 listeners= config.listeners;
23848 delete config.listeners;
23850 Roo.apply(this, config);
23852 if(this.containerScroll){
23853 Roo.dd.ScrollManager.register(this.el);
23857 * @scope Roo.dd.DropTarget
23862 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the source is now over the
23863 * target. This default implementation adds the CSS class specified by overClass (if any) to the drop element
23864 * and returns the dropAllowed config value. This method should be overridden if drop validation is required.
23866 * IMPORTANT : it should set this.valid to true|false
23868 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
23869 * @param {Event} e The event
23870 * @param {Object} data An object containing arbitrary data supplied by the drag source
23876 * The function a {@link Roo.dd.DragSource} calls continuously while it is being dragged over the target.
23877 * This method will be called on every mouse movement while the drag source is over the drop target.
23878 * This default implementation simply returns the dropAllowed config value.
23880 * IMPORTANT : it should set this.valid to true|false
23882 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
23883 * @param {Event} e The event
23884 * @param {Object} data An object containing arbitrary data supplied by the drag source
23890 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the source has been dragged
23891 * out of the target without dropping. This default implementation simply removes the CSS class specified by
23892 * overClass (if any) from the drop element.
23895 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
23896 * @param {Event} e The event
23897 * @param {Object} data An object containing arbitrary data supplied by the drag source
23903 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the dragged item has
23904 * been dropped on it. This method has no default implementation and returns false, so you must provide an
23905 * implementation that does something to process the drop event and returns true so that the drag source's
23906 * repair action does not run.
23908 * IMPORTANT : it should set this.success
23910 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
23911 * @param {Event} e The event
23912 * @param {Object} data An object containing arbitrary data supplied by the drag source
23918 Roo.dd.DropTarget.superclass.constructor.call( this,
23920 this.ddGroup || this.group,
23923 listeners : listeners || {}
23931 Roo.extend(Roo.dd.DropTarget, Roo.dd.DDTarget, {
23933 * @cfg {String} overClass
23934 * The CSS class applied to the drop target element while the drag source is over it (defaults to "").
23937 * @cfg {String} ddGroup
23938 * The drag drop group to handle drop events for
23942 * @cfg {String} dropAllowed
23943 * The CSS class returned to the drag source when drop is allowed (defaults to "x-dd-drop-ok").
23945 dropAllowed : "x-dd-drop-ok",
23947 * @cfg {String} dropNotAllowed
23948 * The CSS class returned to the drag source when drop is not allowed (defaults to "x-dd-drop-nodrop").
23950 dropNotAllowed : "x-dd-drop-nodrop",
23952 * @cfg {boolean} success
23953 * set this after drop listener..
23957 * @cfg {boolean|String} valid true/false or string (ok-add/ok-sub/ok/nodrop)
23958 * if the drop point is valid for over/enter..
23965 isNotifyTarget : true,
23970 notifyEnter : function(dd, e, data)
23973 this.fireEvent('enter', dd, e, data);
23974 if(this.overClass){
23975 this.el.addClass(this.overClass);
23977 return typeof(this.valid) == 'string' ? 'x-dd-drop-' + this.valid : (
23978 this.valid ? this.dropAllowed : this.dropNotAllowed
23985 notifyOver : function(dd, e, data)
23988 this.fireEvent('over', dd, e, data);
23989 return typeof(this.valid) == 'string' ? 'x-dd-drop-' + this.valid : (
23990 this.valid ? this.dropAllowed : this.dropNotAllowed
23997 notifyOut : function(dd, e, data)
23999 this.fireEvent('out', dd, e, data);
24000 if(this.overClass){
24001 this.el.removeClass(this.overClass);
24008 notifyDrop : function(dd, e, data)
24010 this.success = false;
24011 this.fireEvent('drop', dd, e, data);
24012 return this.success;
24016 * Ext JS Library 1.1.1
24017 * Copyright(c) 2006-2007, Ext JS, LLC.
24019 * Originally Released Under LGPL - original licence link has changed is not relivant.
24022 * <script type="text/javascript">
24027 * @class Roo.dd.DragZone
24028 * @extends Roo.dd.DragSource
24029 * This class provides a container DD instance that proxies for multiple child node sources.<br />
24030 * By default, this class requires that draggable child nodes are registered with {@link Roo.dd.Registry}.
24032 * @param {String/HTMLElement/Element} el The container element
24033 * @param {Object} config
24035 Roo.dd.DragZone = function(el, config){
24036 Roo.dd.DragZone.superclass.constructor.call(this, el, config);
24037 if(this.containerScroll){
24038 Roo.dd.ScrollManager.register(this.el);
24042 Roo.extend(Roo.dd.DragZone, Roo.dd.DragSource, {
24044 * @cfg {Boolean} containerScroll True to register this container with the Scrollmanager
24045 * for auto scrolling during drag operations.
24048 * @cfg {String} hlColor The color to use when visually highlighting the drag source in the afterRepair
24049 * method after a failed drop (defaults to "c3daf9" - light blue)
24053 * Called when a mousedown occurs in this container. Looks in {@link Roo.dd.Registry}
24054 * for a valid target to drag based on the mouse down. Override this method
24055 * to provide your own lookup logic (e.g. finding a child by class name). Make sure your returned
24056 * object has a "ddel" attribute (with an HTML Element) for other functions to work.
24057 * @param {EventObject} e The mouse down event
24058 * @return {Object} The dragData
24060 getDragData : function(e){
24061 return Roo.dd.Registry.getHandleFromEvent(e);
24065 * Called once drag threshold has been reached to initialize the proxy element. By default, it clones the
24066 * this.dragData.ddel
24067 * @param {Number} x The x position of the click on the dragged object
24068 * @param {Number} y The y position of the click on the dragged object
24069 * @return {Boolean} true to continue the drag, false to cancel
24071 onInitDrag : function(x, y){
24072 this.proxy.update(this.dragData.ddel.cloneNode(true));
24073 this.onStartDrag(x, y);
24078 * Called after a repair of an invalid drop. By default, highlights this.dragData.ddel
24080 afterRepair : function(){
24082 Roo.Element.fly(this.dragData.ddel).highlight(this.hlColor || "c3daf9");
24084 this.dragging = false;
24088 * Called before a repair of an invalid drop to get the XY to animate to. By default returns
24089 * the XY of this.dragData.ddel
24090 * @param {EventObject} e The mouse up event
24091 * @return {Array} The xy location (e.g. [100, 200])
24093 getRepairXY : function(e){
24094 return Roo.Element.fly(this.dragData.ddel).getXY();
24098 * Ext JS Library 1.1.1
24099 * Copyright(c) 2006-2007, Ext JS, LLC.
24101 * Originally Released Under LGPL - original licence link has changed is not relivant.
24104 * <script type="text/javascript">
24107 * @class Roo.dd.DropZone
24108 * @extends Roo.dd.DropTarget
24109 * This class provides a container DD instance that proxies for multiple child node targets.<br />
24110 * By default, this class requires that child nodes accepting drop are registered with {@link Roo.dd.Registry}.
24112 * @param {String/HTMLElement/Element} el The container element
24113 * @param {Object} config
24115 Roo.dd.DropZone = function(el, config){
24116 Roo.dd.DropZone.superclass.constructor.call(this, el, config);
24119 Roo.extend(Roo.dd.DropZone, Roo.dd.DropTarget, {
24121 * Returns a custom data object associated with the DOM node that is the target of the event. By default
24122 * this looks up the event target in the {@link Roo.dd.Registry}, although you can override this method to
24123 * provide your own custom lookup.
24124 * @param {Event} e The event
24125 * @return {Object} data The custom data
24127 getTargetFromEvent : function(e){
24128 return Roo.dd.Registry.getTargetFromEvent(e);
24132 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has entered a drop node
24133 * that it has registered. This method has no default implementation and should be overridden to provide
24134 * node-specific processing if necessary.
24135 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
24136 * {@link #getTargetFromEvent} for this node)
24137 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
24138 * @param {Event} e The event
24139 * @param {Object} data An object containing arbitrary data supplied by the drag source
24141 onNodeEnter : function(n, dd, e, data){
24146 * Called internally while the DropZone determines that a {@link Roo.dd.DragSource} is over a drop node
24147 * that it has registered. The default implementation returns this.dropNotAllowed, so it should be
24148 * overridden to provide the proper feedback.
24149 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
24150 * {@link #getTargetFromEvent} for this node)
24151 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
24152 * @param {Event} e The event
24153 * @param {Object} data An object containing arbitrary data supplied by the drag source
24154 * @return {String} status The CSS class that communicates the drop status back to the source so that the
24155 * underlying {@link Roo.dd.StatusProxy} can be updated
24157 onNodeOver : function(n, dd, e, data){
24158 return this.dropAllowed;
24162 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dragged out of
24163 * the drop node without dropping. This method has no default implementation and should be overridden to provide
24164 * node-specific processing if necessary.
24165 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
24166 * {@link #getTargetFromEvent} for this node)
24167 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
24168 * @param {Event} e The event
24169 * @param {Object} data An object containing arbitrary data supplied by the drag source
24171 onNodeOut : function(n, dd, e, data){
24176 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dropped onto
24177 * the drop node. The default implementation returns false, so it should be overridden to provide the
24178 * appropriate processing of the drop event and return true so that the drag source's repair action does not run.
24179 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
24180 * {@link #getTargetFromEvent} for this node)
24181 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
24182 * @param {Event} e The event
24183 * @param {Object} data An object containing arbitrary data supplied by the drag source
24184 * @return {Boolean} True if the drop was valid, else false
24186 onNodeDrop : function(n, dd, e, data){
24191 * Called internally while the DropZone determines that a {@link Roo.dd.DragSource} is being dragged over it,
24192 * but not over any of its registered drop nodes. The default implementation returns this.dropNotAllowed, so
24193 * it should be overridden to provide the proper feedback if necessary.
24194 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
24195 * @param {Event} e The event
24196 * @param {Object} data An object containing arbitrary data supplied by the drag source
24197 * @return {String} status The CSS class that communicates the drop status back to the source so that the
24198 * underlying {@link Roo.dd.StatusProxy} can be updated
24200 onContainerOver : function(dd, e, data){
24201 return this.dropNotAllowed;
24205 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dropped on it,
24206 * but not on any of its registered drop nodes. The default implementation returns false, so it should be
24207 * overridden to provide the appropriate processing of the drop event if you need the drop zone itself to
24208 * be able to accept drops. It should return true when valid so that the drag source's repair action does not run.
24209 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
24210 * @param {Event} e The event
24211 * @param {Object} data An object containing arbitrary data supplied by the drag source
24212 * @return {Boolean} True if the drop was valid, else false
24214 onContainerDrop : function(dd, e, data){
24219 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the source is now over
24220 * the zone. The default implementation returns this.dropNotAllowed and expects that only registered drop
24221 * nodes can process drag drop operations, so if you need the drop zone itself to be able to process drops
24222 * you should override this method and provide a custom implementation.
24223 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
24224 * @param {Event} e The event
24225 * @param {Object} data An object containing arbitrary data supplied by the drag source
24226 * @return {String} status The CSS class that communicates the drop status back to the source so that the
24227 * underlying {@link Roo.dd.StatusProxy} can be updated
24229 notifyEnter : function(dd, e, data){
24230 return this.dropNotAllowed;
24234 * The function a {@link Roo.dd.DragSource} calls continuously while it is being dragged over the drop zone.
24235 * This method will be called on every mouse movement while the drag source is over the drop zone.
24236 * It will call {@link #onNodeOver} while the drag source is over a registered node, and will also automatically
24237 * delegate to the appropriate node-specific methods as necessary when the drag source enters and exits
24238 * registered nodes ({@link #onNodeEnter}, {@link #onNodeOut}). If the drag source is not currently over a
24239 * registered node, it will call {@link #onContainerOver}.
24240 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
24241 * @param {Event} e The event
24242 * @param {Object} data An object containing arbitrary data supplied by the drag source
24243 * @return {String} status The CSS class that communicates the drop status back to the source so that the
24244 * underlying {@link Roo.dd.StatusProxy} can be updated
24246 notifyOver : function(dd, e, data){
24247 var n = this.getTargetFromEvent(e);
24248 if(!n){ // not over valid drop target
24249 if(this.lastOverNode){
24250 this.onNodeOut(this.lastOverNode, dd, e, data);
24251 this.lastOverNode = null;
24253 return this.onContainerOver(dd, e, data);
24255 if(this.lastOverNode != n){
24256 if(this.lastOverNode){
24257 this.onNodeOut(this.lastOverNode, dd, e, data);
24259 this.onNodeEnter(n, dd, e, data);
24260 this.lastOverNode = n;
24262 return this.onNodeOver(n, dd, e, data);
24266 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the source has been dragged
24267 * out of the zone without dropping. If the drag source is currently over a registered node, the notification
24268 * will be delegated to {@link #onNodeOut} for node-specific handling, otherwise it will be ignored.
24269 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
24270 * @param {Event} e The event
24271 * @param {Object} data An object containing arbitrary data supplied by the drag zone
24273 notifyOut : function(dd, e, data){
24274 if(this.lastOverNode){
24275 this.onNodeOut(this.lastOverNode, dd, e, data);
24276 this.lastOverNode = null;
24281 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the dragged item has
24282 * been dropped on it. The drag zone will look up the target node based on the event passed in, and if there
24283 * is a node registered for that event, it will delegate to {@link #onNodeDrop} for node-specific handling,
24284 * otherwise it will call {@link #onContainerDrop}.
24285 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
24286 * @param {Event} e The event
24287 * @param {Object} data An object containing arbitrary data supplied by the drag source
24288 * @return {Boolean} True if the drop was valid, else false
24290 notifyDrop : function(dd, e, data){
24291 if(this.lastOverNode){
24292 this.onNodeOut(this.lastOverNode, dd, e, data);
24293 this.lastOverNode = null;
24295 var n = this.getTargetFromEvent(e);
24297 this.onNodeDrop(n, dd, e, data) :
24298 this.onContainerDrop(dd, e, data);
24302 triggerCacheRefresh : function(){
24303 Roo.dd.DDM.refreshCache(this.groups);