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);
4912 * Ext JS Library 1.1.1
4913 * Copyright(c) 2006-2007, Ext JS, LLC.
4915 * Originally Released Under LGPL - original licence link has changed is not relivant.
4918 * <script type="text/javascript">
4922 // nasty IE9 hack - what a pile of crap that is..
4924 if (typeof Range != "undefined" && typeof Range.prototype.createContextualFragment == "undefined") {
4925 Range.prototype.createContextualFragment = function (html) {
4926 var doc = window.document;
4927 var container = doc.createElement("div");
4928 container.innerHTML = html;
4929 var frag = doc.createDocumentFragment(), n;
4930 while ((n = container.firstChild)) {
4931 frag.appendChild(n);
4938 * @class Roo.DomHelper
4939 * Utility class for working with DOM and/or Templates. It transparently supports using HTML fragments or DOM.
4940 * 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>.
4943 Roo.DomHelper = function(){
4944 var tempTableEl = null;
4945 var emptyTags = /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i;
4946 var tableRe = /^table|tbody|tr|td$/i;
4948 // build as innerHTML where available
4950 var createHtml = function(o){
4951 if(typeof o == 'string'){
4960 if(attr == "tag" || attr == "children" || attr == "cn" || attr == "html" || typeof o[attr] == "function") { continue; }
4961 if(attr == "style"){
4963 if(typeof s == "function"){
4966 if(typeof s == "string"){
4967 b += ' style="' + s + '"';
4968 }else if(typeof s == "object"){
4971 if(typeof s[key] != "function"){
4972 b += key + ":" + s[key] + ";";
4979 b += ' class="' + o["cls"] + '"';
4980 }else if(attr == "htmlFor"){
4981 b += ' for="' + o["htmlFor"] + '"';
4983 b += " " + attr + '="' + o[attr] + '"';
4987 if(emptyTags.test(o.tag)){
4991 var cn = o.children || o.cn;
4993 //http://bugs.kde.org/show_bug.cgi?id=71506
4994 if((cn instanceof Array) || (Roo.isSafari && typeof(cn.join) == "function")){
4995 for(var i = 0, len = cn.length; i < len; i++) {
4996 b += createHtml(cn[i], b);
4999 b += createHtml(cn, b);
5005 b += "</" + o.tag + ">";
5012 var createDom = function(o, parentNode){
5014 // defininition craeted..
5016 if (o.ns && o.ns != 'html') {
5018 if (o.xmlns && typeof(xmlns[o.ns]) == 'undefined') {
5019 xmlns[o.ns] = o.xmlns;
5022 if (typeof(xmlns[o.ns]) == 'undefined') {
5023 console.log("Trying to create namespace element " + o.ns + ", however no xmlns was sent to builder previously");
5029 if (typeof(o) == 'string') {
5030 return parentNode.appendChild(document.createTextNode(o));
5032 o.tag = o.tag || div;
5033 if (o.ns && Roo.isIE) {
5035 o.tag = o.ns + ':' + o.tag;
5038 var el = ns ? document.createElementNS( ns, o.tag||'div') : document.createElement(o.tag||'div');
5039 var useSet = el.setAttribute ? true : false; // In IE some elements don't have setAttribute
5042 if(attr == "tag" || attr == "ns" ||attr == "xmlns" ||attr == "children" || attr == "cn" || attr == "html" ||
5043 attr == "style" || typeof o[attr] == "function") { continue; }
5045 if(attr=="cls" && Roo.isIE){
5046 el.className = o["cls"];
5048 if(useSet) { el.setAttribute(attr=="cls" ? 'class' : attr, o[attr]);}
5054 Roo.DomHelper.applyStyles(el, o.style);
5055 var cn = o.children || o.cn;
5057 //http://bugs.kde.org/show_bug.cgi?id=71506
5058 if((cn instanceof Array) || (Roo.isSafari && typeof(cn.join) == "function")){
5059 for(var i = 0, len = cn.length; i < len; i++) {
5060 createDom(cn[i], el);
5067 el.innerHTML = o.html;
5070 parentNode.appendChild(el);
5075 var ieTable = function(depth, s, h, e){
5076 tempTableEl.innerHTML = [s, h, e].join('');
5077 var i = -1, el = tempTableEl;
5078 while(++i < depth && el.firstChild){
5084 // kill repeat to save bytes
5088 tbe = '</tbody>'+te,
5094 * Nasty code for IE's broken table implementation
5096 var insertIntoTable = function(tag, where, el, html){
5098 tempTableEl = document.createElement('div');
5103 if(where == 'afterbegin' || where == 'beforeend'){ // INTO a TD
5106 if(where == 'beforebegin'){
5110 before = el.nextSibling;
5113 node = ieTable(4, trs, html, tre);
5115 else if(tag == 'tr'){
5116 if(where == 'beforebegin'){
5119 node = ieTable(3, tbs, html, tbe);
5120 } else if(where == 'afterend'){
5121 before = el.nextSibling;
5123 node = ieTable(3, tbs, html, tbe);
5124 } else{ // INTO a TR
5125 if(where == 'afterbegin'){
5126 before = el.firstChild;
5128 node = ieTable(4, trs, html, tre);
5130 } else if(tag == 'tbody'){
5131 if(where == 'beforebegin'){
5134 node = ieTable(2, ts, html, te);
5135 } else if(where == 'afterend'){
5136 before = el.nextSibling;
5138 node = ieTable(2, ts, html, te);
5140 if(where == 'afterbegin'){
5141 before = el.firstChild;
5143 node = ieTable(3, tbs, html, tbe);
5146 if(where == 'beforebegin' || where == 'afterend'){ // OUTSIDE the table
5149 if(where == 'afterbegin'){
5150 before = el.firstChild;
5152 node = ieTable(2, ts, html, te);
5154 el.insertBefore(node, before);
5158 // this is a bit like the react update code...
5161 var updateNode = function(from, to)
5163 // should we handle non-standard elements?
5164 Roo.log(["UpdateNode" , from, to]);
5165 if (from.nodeType != to.nodeType) {
5166 Roo.log(["ReplaceChild - mismatch notType" , to, from ]);
5167 from.parentNode.replaceChild(to, from);
5170 if (from.nodeType == 3) {
5171 // assume it's text?!
5172 if (from.data == to.data) {
5175 from.data = to.data;
5178 if (!from.parentNode) {
5179 // not sure why this is happening?
5182 // assume 'to' doesnt have '1/3 nodetypes!
5183 // not sure why, by from, parent node might not exist?
5184 if (from.nodeType !=1 || from.tagName != to.tagName) {
5185 Roo.log(["ReplaceChild" , from, to ]);
5187 from.parentNode.replaceChild(to, from);
5190 // compare attributes
5191 var ar = Array.from(from.attributes);
5192 for(var i = 0; i< ar.length;i++) {
5193 if (to.hasAttribute(ar[i].name)) {
5196 if (ar[i].name == 'id') { // always keep ids?
5199 //if (ar[i].name == 'style') {
5200 // throw "style removed?";
5202 Roo.log("removeAttribute" + ar[i].name);
5203 from.removeAttribute(ar[i].name);
5206 for(var i = 0; i< ar.length;i++) {
5207 if (from.getAttribute(ar[i].name) == to.getAttribute(ar[i].name)) {
5208 Roo.log("skipAttribute " + ar[i].name + '=' + to.getAttribute(ar[i].name));
5211 Roo.log("updateAttribute " + ar[i].name + '=>' + to.getAttribute(ar[i].name));
5212 from.setAttribute(ar[i].name, to.getAttribute(ar[i].name));
5215 var far = Array.from(from.childNodes);
5216 var tar = Array.from(to.childNodes);
5217 // if the lengths are different.. then it's probably a editable content change, rather than
5218 // a change of the block definition..
5220 // this did notwork , as our rebuilt nodes did not include ID's so did not match at all.
5221 /*if (from.innerHTML == to.innerHTML) {
5224 if (far.length != tar.length) {
5225 from.innerHTML = to.innerHTML;
5230 for(var i = 0; i < Math.max(tar.length, far.length); i++) {
5231 if (i >= far.length) {
5232 from.appendChild(tar[i]);
5233 Roo.log(["add", tar[i]]);
5235 } else if ( i >= tar.length) {
5236 from.removeChild(far[i]);
5237 Roo.log(["remove", far[i]]);
5240 updateNode(far[i], tar[i]);
5252 /** True to force the use of DOM instead of html fragments @type Boolean */
5256 * Returns the markup for the passed Element(s) config
5257 * @param {Object} o The Dom object spec (and children)
5260 markup : function(o){
5261 return createHtml(o);
5265 * Applies a style specification to an element
5266 * @param {String/HTMLElement} el The element to apply styles to
5267 * @param {String/Object/Function} styles A style specification string eg "width:100px", or object in the form {width:"100px"}, or
5268 * a function which returns such a specification.
5270 applyStyles : function(el, styles){
5273 if(typeof styles == "string"){
5274 var re = /\s?([a-z\-]*)\:\s?([^;]*);?/gi;
5276 while ((matches = re.exec(styles)) != null){
5277 el.setStyle(matches[1], matches[2]);
5279 }else if (typeof styles == "object"){
5280 for (var style in styles){
5281 el.setStyle(style, styles[style]);
5283 }else if (typeof styles == "function"){
5284 Roo.DomHelper.applyStyles(el, styles.call());
5290 * Inserts an HTML fragment into the Dom
5291 * @param {String} where Where to insert the html in relation to el - beforeBegin, afterBegin, beforeEnd, afterEnd.
5292 * @param {HTMLElement} el The context element
5293 * @param {String} html The HTML fragmenet
5294 * @return {HTMLElement} The new node
5296 insertHtml : function(where, el, html){
5297 where = where.toLowerCase();
5298 if(el.insertAdjacentHTML){
5299 if(tableRe.test(el.tagName)){
5301 if(rs = insertIntoTable(el.tagName.toLowerCase(), where, el, html)){
5307 el.insertAdjacentHTML('BeforeBegin', html);
5308 return el.previousSibling;
5310 el.insertAdjacentHTML('AfterBegin', html);
5311 return el.firstChild;
5313 el.insertAdjacentHTML('BeforeEnd', html);
5314 return el.lastChild;
5316 el.insertAdjacentHTML('AfterEnd', html);
5317 return el.nextSibling;
5319 throw 'Illegal insertion point -> "' + where + '"';
5321 var range = el.ownerDocument.createRange();
5325 range.setStartBefore(el);
5326 frag = range.createContextualFragment(html);
5327 el.parentNode.insertBefore(frag, el);
5328 return el.previousSibling;
5331 range.setStartBefore(el.firstChild);
5332 frag = range.createContextualFragment(html);
5333 el.insertBefore(frag, el.firstChild);
5334 return el.firstChild;
5336 el.innerHTML = html;
5337 return el.firstChild;
5341 range.setStartAfter(el.lastChild);
5342 frag = range.createContextualFragment(html);
5343 el.appendChild(frag);
5344 return el.lastChild;
5346 el.innerHTML = html;
5347 return el.lastChild;
5350 range.setStartAfter(el);
5351 frag = range.createContextualFragment(html);
5352 el.parentNode.insertBefore(frag, el.nextSibling);
5353 return el.nextSibling;
5355 throw 'Illegal insertion point -> "' + where + '"';
5359 * Creates new Dom element(s) and inserts them before el
5360 * @param {String/HTMLElement/Element} el The context element
5361 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5362 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5363 * @return {HTMLElement/Roo.Element} The new node
5365 insertBefore : function(el, o, returnElement){
5366 return this.doInsert(el, o, returnElement, "beforeBegin");
5370 * Creates new Dom element(s) and inserts them after el
5371 * @param {String/HTMLElement/Element} el The context element
5372 * @param {Object} o The Dom object spec (and children)
5373 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5374 * @return {HTMLElement/Roo.Element} The new node
5376 insertAfter : function(el, o, returnElement){
5377 return this.doInsert(el, o, returnElement, "afterEnd", "nextSibling");
5381 * Creates new Dom element(s) and inserts them as the first child of el
5382 * @param {String/HTMLElement/Element} el The context element
5383 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5384 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5385 * @return {HTMLElement/Roo.Element} The new node
5387 insertFirst : function(el, o, returnElement){
5388 return this.doInsert(el, o, returnElement, "afterBegin");
5392 doInsert : function(el, o, returnElement, pos, sibling){
5393 el = Roo.getDom(el);
5395 if(this.useDom || o.ns){
5396 newNode = createDom(o, null);
5397 el.parentNode.insertBefore(newNode, sibling ? el[sibling] : el);
5399 var html = createHtml(o);
5400 newNode = this.insertHtml(pos, el, html);
5402 return returnElement ? Roo.get(newNode, true) : newNode;
5406 * Creates new Dom element(s) and appends them to el
5407 * @param {String/HTMLElement/Element} el The context element
5408 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5409 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5410 * @return {HTMLElement/Roo.Element} The new node
5412 append : function(el, o, returnElement){
5413 el = Roo.getDom(el);
5415 if(this.useDom || o.ns){
5416 newNode = createDom(o, null);
5417 el.appendChild(newNode);
5419 var html = createHtml(o);
5420 newNode = this.insertHtml("beforeEnd", el, html);
5422 return returnElement ? Roo.get(newNode, true) : newNode;
5426 * Creates new Dom element(s) and overwrites the contents of el with them
5427 * @param {String/HTMLElement/Element} el The context element
5428 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5429 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5430 * @return {HTMLElement/Roo.Element} The new node
5432 overwrite : function(el, o, returnElement)
5434 el = Roo.getDom(el);
5437 while (el.childNodes.length) {
5438 el.removeChild(el.firstChild);
5442 el.innerHTML = createHtml(o);
5445 return returnElement ? Roo.get(el.firstChild, true) : el.firstChild;
5449 * Creates a new Roo.DomHelper.Template from the Dom object spec
5450 * @param {Object} o The Dom object spec (and children)
5451 * @return {Roo.DomHelper.Template} The new template
5453 createTemplate : function(o){
5454 var html = createHtml(o);
5455 return new Roo.Template(html);
5458 * Updates the first element with the spec from the o (replacing if necessary)
5459 * This iterates through the children, and updates attributes / children etc..
5460 * @param {String/HTMLElement/Element} el The context element
5461 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5464 update : function(el, o)
5466 updateNode(Roo.getDom(el), createDom(o));
5475 * Ext JS Library 1.1.1
5476 * Copyright(c) 2006-2007, Ext JS, LLC.
5478 * Originally Released Under LGPL - original licence link has changed is not relivant.
5481 * <script type="text/javascript">
5485 * @class Roo.Template
5486 * Represents an HTML fragment template. Templates can be precompiled for greater performance.
5487 * For a list of available format functions, see {@link Roo.util.Format}.<br />
5490 var t = new Roo.Template({
5491 html : '<div name="{id}">' +
5492 '<span class="{cls}">{name:trim} {someval:this.myformat}{value:ellipsis(10)}</span>' +
5494 myformat: function (value, allValues) {
5495 return 'XX' + value;
5498 t.append('some-element', {id: 'myid', cls: 'myclass', name: 'foo', value: 'bar'});
5500 * For more information see this blog post with examples:
5501 * <a href="http://www.cnitblog.com/seeyeah/archive/2011/12/30/38728.html/">DomHelper
5502 - Create Elements using DOM, HTML fragments and Templates</a>.
5504 * @param {Object} cfg - Configuration object.
5506 Roo.Template = function(cfg){
5508 if(cfg instanceof Array){
5510 }else if(arguments.length > 1){
5511 cfg = Array.prototype.join.call(arguments, "");
5515 if (typeof(cfg) == 'object') {
5526 Roo.Template.prototype = {
5529 * @cfg {Function} onLoad Called after the template has been loaded and complied (usually from a remove source)
5535 * @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..
5536 * it should be fixed so that template is observable...
5540 * @cfg {String} html The HTML fragment or an array of fragments to join("") or multiple arguments to join("")
5548 * Returns an HTML fragment of this template with the specified values applied.
5549 * @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'})
5550 * @return {String} The HTML fragment
5555 applyTemplate : function(values){
5556 //Roo.log(["applyTemplate", values]);
5560 return this.compiled(values);
5562 var useF = this.disableFormats !== true;
5563 var fm = Roo.util.Format, tpl = this;
5564 var fn = function(m, name, format, args){
5566 if(format.substr(0, 5) == "this."){
5567 return tpl.call(format.substr(5), values[name], values);
5570 // quoted values are required for strings in compiled templates,
5571 // but for non compiled we need to strip them
5572 // quoted reversed for jsmin
5573 var re = /^\s*['"](.*)["']\s*$/;
5574 args = args.split(',');
5575 for(var i = 0, len = args.length; i < len; i++){
5576 args[i] = args[i].replace(re, "$1");
5578 args = [values[name]].concat(args);
5580 args = [values[name]];
5582 return fm[format].apply(fm, args);
5585 return values[name] !== undefined ? values[name] : "";
5588 return this.html.replace(this.re, fn);
5606 this.loading = true;
5607 this.compiled = false;
5609 var cx = new Roo.data.Connection();
5613 success : function (response) {
5617 _t.set(response.responseText,true);
5623 failure : function(response) {
5624 Roo.log("Template failed to load from " + _t.url);
5631 * Sets the HTML used as the template and optionally compiles it.
5632 * @param {String} html
5633 * @param {Boolean} compile (optional) True to compile the template (defaults to undefined)
5634 * @return {Roo.Template} this
5636 set : function(html, compile){
5638 this.compiled = false;
5646 * True to disable format functions (defaults to false)
5649 disableFormats : false,
5652 * The regular expression used to match template variables
5656 re : /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
5659 * Compiles the template into an internal function, eliminating the RegEx overhead.
5660 * @return {Roo.Template} this
5662 compile : function(){
5663 var fm = Roo.util.Format;
5664 var useF = this.disableFormats !== true;
5665 var sep = Roo.isGecko ? "+" : ",";
5666 var fn = function(m, name, format, args){
5668 args = args ? ',' + args : "";
5669 if(format.substr(0, 5) != "this."){
5670 format = "fm." + format + '(';
5672 format = 'this.call("'+ format.substr(5) + '", ';
5676 args= ''; format = "(values['" + name + "'] == undefined ? '' : ";
5678 return "'"+ sep + format + "values['" + name + "']" + args + ")"+sep+"'";
5681 // branched to use + in gecko and [].join() in others
5683 body = "this.compiled = function(values){ return '" +
5684 this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
5687 body = ["this.compiled = function(values){ return ['"];
5688 body.push(this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn));
5689 body.push("'].join('');};");
5690 body = body.join('');
5700 // private function used to call members
5701 call : function(fnName, value, allValues){
5702 return this[fnName](value, allValues);
5706 * Applies the supplied values to the template and inserts the new node(s) as the first child of el.
5707 * @param {String/HTMLElement/Roo.Element} el The context element
5708 * @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'})
5709 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
5710 * @return {HTMLElement/Roo.Element} The new node or Element
5712 insertFirst: function(el, values, returnElement){
5713 return this.doInsert('afterBegin', el, values, returnElement);
5717 * Applies the supplied values to the template and inserts the new node(s) before el.
5718 * @param {String/HTMLElement/Roo.Element} el The context element
5719 * @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'})
5720 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
5721 * @return {HTMLElement/Roo.Element} The new node or Element
5723 insertBefore: function(el, values, returnElement){
5724 return this.doInsert('beforeBegin', el, values, returnElement);
5728 * Applies the supplied values to the template and inserts the new node(s) after el.
5729 * @param {String/HTMLElement/Roo.Element} el The context element
5730 * @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'})
5731 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
5732 * @return {HTMLElement/Roo.Element} The new node or Element
5734 insertAfter : function(el, values, returnElement){
5735 return this.doInsert('afterEnd', el, values, returnElement);
5739 * Applies the supplied values to the template and appends the new node(s) to el.
5740 * @param {String/HTMLElement/Roo.Element} el The context element
5741 * @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'})
5742 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
5743 * @return {HTMLElement/Roo.Element} The new node or Element
5745 append : function(el, values, returnElement){
5746 return this.doInsert('beforeEnd', el, values, returnElement);
5749 doInsert : function(where, el, values, returnEl){
5750 el = Roo.getDom(el);
5751 var newNode = Roo.DomHelper.insertHtml(where, el, this.applyTemplate(values));
5752 return returnEl ? Roo.get(newNode, true) : newNode;
5756 * Applies the supplied values to the template and overwrites the content of el with the new node(s).
5757 * @param {String/HTMLElement/Roo.Element} el The context element
5758 * @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'})
5759 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
5760 * @return {HTMLElement/Roo.Element} The new node or Element
5762 overwrite : function(el, values, returnElement){
5763 el = Roo.getDom(el);
5764 el.innerHTML = this.applyTemplate(values);
5765 return returnElement ? Roo.get(el.firstChild, true) : el.firstChild;
5769 * Alias for {@link #applyTemplate}
5772 Roo.Template.prototype.apply = Roo.Template.prototype.applyTemplate;
5775 Roo.DomHelper.Template = Roo.Template;
5778 * Creates a template from the passed element's value (<i>display:none</i> textarea, preferred) or innerHTML.
5779 * @param {String/HTMLElement} el A DOM element or its id
5780 * @returns {Roo.Template} The created template
5783 Roo.Template.from = function(el){
5784 el = Roo.getDom(el);
5785 return new Roo.Template(el.value || el.innerHTML);
5788 * Ext JS Library 1.1.1
5789 * Copyright(c) 2006-2007, Ext JS, LLC.
5791 * Originally Released Under LGPL - original licence link has changed is not relivant.
5794 * <script type="text/javascript">
5799 * This is code is also distributed under MIT license for use
5800 * with jQuery and prototype JavaScript libraries.
5803 * @class Roo.DomQuery
5804 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).
5806 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>
5809 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.
5811 <h4>Element Selectors:</h4>
5813 <li> <b>*</b> any element</li>
5814 <li> <b>E</b> an element with the tag E</li>
5815 <li> <b>E F</b> All descendent elements of E that have the tag F</li>
5816 <li> <b>E > F</b> or <b>E/F</b> all direct children elements of E that have the tag F</li>
5817 <li> <b>E + F</b> all elements with the tag F that are immediately preceded by an element with the tag E</li>
5818 <li> <b>E ~ F</b> all elements with the tag F that are preceded by a sibling element with the tag E</li>
5820 <h4>Attribute Selectors:</h4>
5821 <p>The use of @ and quotes are optional. For example, div[@foo='bar'] is also a valid attribute selector.</p>
5823 <li> <b>E[foo]</b> has an attribute "foo"</li>
5824 <li> <b>E[foo=bar]</b> has an attribute "foo" that equals "bar"</li>
5825 <li> <b>E[foo^=bar]</b> has an attribute "foo" that starts with "bar"</li>
5826 <li> <b>E[foo$=bar]</b> has an attribute "foo" that ends with "bar"</li>
5827 <li> <b>E[foo*=bar]</b> has an attribute "foo" that contains the substring "bar"</li>
5828 <li> <b>E[foo%=2]</b> has an attribute "foo" that is evenly divisible by 2</li>
5829 <li> <b>E[foo!=bar]</b> has an attribute "foo" that does not equal "bar"</li>
5831 <h4>Pseudo Classes:</h4>
5833 <li> <b>E:first-child</b> E is the first child of its parent</li>
5834 <li> <b>E:last-child</b> E is the last child of its parent</li>
5835 <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>
5836 <li> <b>E:nth-child(odd)</b> E is an odd child of its parent</li>
5837 <li> <b>E:nth-child(even)</b> E is an even child of its parent</li>
5838 <li> <b>E:only-child</b> E is the only child of its parent</li>
5839 <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>
5840 <li> <b>E:first</b> the first E in the resultset</li>
5841 <li> <b>E:last</b> the last E in the resultset</li>
5842 <li> <b>E:nth(<i>n</i>)</b> the <i>n</i>th E in the resultset (1 based)</li>
5843 <li> <b>E:odd</b> shortcut for :nth-child(odd)</li>
5844 <li> <b>E:even</b> shortcut for :nth-child(even)</li>
5845 <li> <b>E:contains(foo)</b> E's innerHTML contains the substring "foo"</li>
5846 <li> <b>E:nodeValue(foo)</b> E contains a textNode with a nodeValue that equals "foo"</li>
5847 <li> <b>E:not(S)</b> an E element that does not match simple selector S</li>
5848 <li> <b>E:has(S)</b> an E element that has a descendent that matches simple selector S</li>
5849 <li> <b>E:next(S)</b> an E element whose next sibling matches simple selector S</li>
5850 <li> <b>E:prev(S)</b> an E element whose previous sibling matches simple selector S</li>
5852 <h4>CSS Value Selectors:</h4>
5854 <li> <b>E{display=none}</b> css value "display" that equals "none"</li>
5855 <li> <b>E{display^=none}</b> css value "display" that starts with "none"</li>
5856 <li> <b>E{display$=none}</b> css value "display" that ends with "none"</li>
5857 <li> <b>E{display*=none}</b> css value "display" that contains the substring "none"</li>
5858 <li> <b>E{display%=2}</b> css value "display" that is evenly divisible by 2</li>
5859 <li> <b>E{display!=none}</b> css value "display" that does not equal "none"</li>
5863 Roo.DomQuery = function(){
5864 var cache = {}, simpleCache = {}, valueCache = {};
5865 var nonSpace = /\S/;
5866 var trimRe = /^\s+|\s+$/g;
5867 var tplRe = /\{(\d+)\}/g;
5868 var modeRe = /^(\s?[\/>+~]\s?|\s|$)/;
5869 var tagTokenRe = /^(#)?([\w-\*]+)/;
5870 var nthRe = /(\d*)n\+?(\d*)/, nthRe2 = /\D/;
5872 function child(p, index){
5874 var n = p.firstChild;
5876 if(n.nodeType == 1){
5887 while((n = n.nextSibling) && n.nodeType != 1);
5892 while((n = n.previousSibling) && n.nodeType != 1);
5896 function children(d){
5897 var n = d.firstChild, ni = -1;
5899 var nx = n.nextSibling;
5900 if(n.nodeType == 3 && !nonSpace.test(n.nodeValue)){
5910 function byClassName(c, a, v){
5914 var r = [], ri = -1, cn;
5915 for(var i = 0, ci; ci = c[i]; i++){
5919 ( (ci instanceof SVGElement) ? ci.className.baseVal : ci.className)
5920 +' ').indexOf(v) != -1){
5927 function attrValue(n, attr){
5928 if(!n.tagName && typeof n.length != "undefined"){
5937 if(attr == "class" || attr == "className"){
5938 return (n instanceof SVGElement) ? n.className.baseVal : n.className;
5940 return n.getAttribute(attr) || n[attr];
5944 function getNodes(ns, mode, tagName){
5945 var result = [], ri = -1, cs;
5949 tagName = tagName || "*";
5950 if(typeof ns.getElementsByTagName != "undefined"){
5954 for(var i = 0, ni; ni = ns[i]; i++){
5955 cs = ni.getElementsByTagName(tagName);
5956 for(var j = 0, ci; ci = cs[j]; j++){
5960 }else if(mode == "/" || mode == ">"){
5961 var utag = tagName.toUpperCase();
5962 for(var i = 0, ni, cn; ni = ns[i]; i++){
5963 cn = ni.children || ni.childNodes;
5964 for(var j = 0, cj; cj = cn[j]; j++){
5965 if(cj.nodeName == utag || cj.nodeName == tagName || tagName == '*'){
5970 }else if(mode == "+"){
5971 var utag = tagName.toUpperCase();
5972 for(var i = 0, n; n = ns[i]; i++){
5973 while((n = n.nextSibling) && n.nodeType != 1);
5974 if(n && (n.nodeName == utag || n.nodeName == tagName || tagName == '*')){
5978 }else if(mode == "~"){
5979 for(var i = 0, n; n = ns[i]; i++){
5980 while((n = n.nextSibling) && (n.nodeType != 1 || (tagName == '*' || n.tagName.toLowerCase()!=tagName)));
5989 function concat(a, b){
5993 for(var i = 0, l = b.length; i < l; i++){
5999 function byTag(cs, tagName){
6000 if(cs.tagName || cs == document){
6006 var r = [], ri = -1;
6007 tagName = tagName.toLowerCase();
6008 for(var i = 0, ci; ci = cs[i]; i++){
6009 if(ci.nodeType == 1 && ci.tagName.toLowerCase()==tagName){
6016 function byId(cs, attr, id){
6017 if(cs.tagName || cs == document){
6023 var r = [], ri = -1;
6024 for(var i = 0,ci; ci = cs[i]; i++){
6025 if(ci && ci.id == id){
6033 function byAttribute(cs, attr, value, op, custom){
6034 var r = [], ri = -1, st = custom=="{";
6035 var f = Roo.DomQuery.operators[op];
6036 for(var i = 0, ci; ci = cs[i]; i++){
6039 a = Roo.DomQuery.getStyle(ci, attr);
6041 else if(attr == "class" || attr == "className"){
6042 a = (ci instanceof SVGElement) ? ci.className.baseVal : ci.className;
6043 }else if(attr == "for"){
6045 }else if(attr == "href"){
6046 a = ci.getAttribute("href", 2);
6048 a = ci.getAttribute(attr);
6050 if((f && f(a, value)) || (!f && a)){
6057 function byPseudo(cs, name, value){
6058 return Roo.DomQuery.pseudos[name](cs, value);
6061 // This is for IE MSXML which does not support expandos.
6062 // IE runs the same speed using setAttribute, however FF slows way down
6063 // and Safari completely fails so they need to continue to use expandos.
6064 var isIE = window.ActiveXObject ? true : false;
6066 // this eval is stop the compressor from
6067 // renaming the variable to something shorter
6069 /** eval:var:batch */
6074 function nodupIEXml(cs){
6076 cs[0].setAttribute("_nodup", d);
6078 for(var i = 1, len = cs.length; i < len; i++){
6080 if(!c.getAttribute("_nodup") != d){
6081 c.setAttribute("_nodup", d);
6085 for(var i = 0, len = cs.length; i < len; i++){
6086 cs[i].removeAttribute("_nodup");
6095 var len = cs.length, c, i, r = cs, cj, ri = -1;
6096 if(!len || typeof cs.nodeType != "undefined" || len == 1){
6099 if(isIE && typeof cs[0].selectSingleNode != "undefined"){
6100 return nodupIEXml(cs);
6104 for(i = 1; c = cs[i]; i++){
6109 for(var j = 0; j < i; j++){
6112 for(j = i+1; cj = cs[j]; j++){
6124 function quickDiffIEXml(c1, c2){
6126 for(var i = 0, len = c1.length; i < len; i++){
6127 c1[i].setAttribute("_qdiff", d);
6130 for(var i = 0, len = c2.length; i < len; i++){
6131 if(c2[i].getAttribute("_qdiff") != d){
6132 r[r.length] = c2[i];
6135 for(var i = 0, len = c1.length; i < len; i++){
6136 c1[i].removeAttribute("_qdiff");
6141 function quickDiff(c1, c2){
6142 var len1 = c1.length;
6146 if(isIE && c1[0].selectSingleNode){
6147 return quickDiffIEXml(c1, c2);
6150 for(var i = 0; i < len1; i++){
6154 for(var i = 0, len = c2.length; i < len; i++){
6155 if(c2[i]._qdiff != d){
6156 r[r.length] = c2[i];
6162 function quickId(ns, mode, root, id){
6164 var d = root.ownerDocument || root;
6165 return d.getElementById(id);
6167 ns = getNodes(ns, mode, "*");
6168 return byId(ns, null, id);
6172 getStyle : function(el, name){
6173 return Roo.fly(el).getStyle(name);
6176 * Compiles a selector/xpath query into a reusable function. The returned function
6177 * takes one parameter "root" (optional), which is the context node from where the query should start.
6178 * @param {String} selector The selector/xpath query
6179 * @param {String} type (optional) Either "select" (the default) or "simple" for a simple selector match
6180 * @return {Function}
6182 compile : function(path, type){
6183 type = type || "select";
6185 var fn = ["var f = function(root){\n var mode; ++batch; var n = root || document;\n"];
6186 var q = path, mode, lq;
6187 var tk = Roo.DomQuery.matchers;
6188 var tklen = tk.length;
6191 // accept leading mode switch
6192 var lmode = q.match(modeRe);
6193 if(lmode && lmode[1]){
6194 fn[fn.length] = 'mode="'+lmode[1].replace(trimRe, "")+'";';
6195 q = q.replace(lmode[1], "");
6197 // strip leading slashes
6198 while(path.substr(0, 1)=="/"){
6199 path = path.substr(1);
6202 while(q && lq != q){
6204 var tm = q.match(tagTokenRe);
6205 if(type == "select"){
6208 fn[fn.length] = 'n = quickId(n, mode, root, "'+tm[2]+'");';
6210 fn[fn.length] = 'n = getNodes(n, mode, "'+tm[2]+'");';
6212 q = q.replace(tm[0], "");
6213 }else if(q.substr(0, 1) != '@'){
6214 fn[fn.length] = 'n = getNodes(n, mode, "*");';
6219 fn[fn.length] = 'n = byId(n, null, "'+tm[2]+'");';
6221 fn[fn.length] = 'n = byTag(n, "'+tm[2]+'");';
6223 q = q.replace(tm[0], "");
6226 while(!(mm = q.match(modeRe))){
6227 var matched = false;
6228 for(var j = 0; j < tklen; j++){
6230 var m = q.match(t.re);
6232 fn[fn.length] = t.select.replace(tplRe, function(x, i){
6235 q = q.replace(m[0], "");
6240 // prevent infinite loop on bad selector
6242 throw 'Error parsing selector, parsing failed at "' + q + '"';
6246 fn[fn.length] = 'mode="'+mm[1].replace(trimRe, "")+'";';
6247 q = q.replace(mm[1], "");
6250 fn[fn.length] = "return nodup(n);\n}";
6253 * list of variables that need from compression as they are used by eval.
6263 * eval:var:byClassName
6265 * eval:var:byAttribute
6266 * eval:var:attrValue
6274 * Selects a group of elements.
6275 * @param {String} selector The selector/xpath query (can be a comma separated list of selectors)
6276 * @param {Node} root (optional) The start of the query (defaults to document).
6279 select : function(path, root, type){
6280 if(!root || root == document){
6283 if(typeof root == "string"){
6284 root = document.getElementById(root);
6286 var paths = path.split(",");
6288 for(var i = 0, len = paths.length; i < len; i++){
6289 var p = paths[i].replace(trimRe, "");
6291 cache[p] = Roo.DomQuery.compile(p);
6293 throw p + " is not a valid selector";
6296 var result = cache[p](root);
6297 if(result && result != document){
6298 results = results.concat(result);
6301 if(paths.length > 1){
6302 return nodup(results);
6308 * Selects a single element.
6309 * @param {String} selector The selector/xpath query
6310 * @param {Node} root (optional) The start of the query (defaults to document).
6313 selectNode : function(path, root){
6314 return Roo.DomQuery.select(path, root)[0];
6318 * Selects the value of a node, optionally replacing null with the defaultValue.
6319 * @param {String} selector The selector/xpath query
6320 * @param {Node} root (optional) The start of the query (defaults to document).
6321 * @param {String} defaultValue
6323 selectValue : function(path, root, defaultValue){
6324 path = path.replace(trimRe, "");
6325 if(!valueCache[path]){
6326 valueCache[path] = Roo.DomQuery.compile(path, "select");
6328 var n = valueCache[path](root);
6329 n = n[0] ? n[0] : n;
6330 var v = (n && n.firstChild ? n.firstChild.nodeValue : null);
6331 return ((v === null||v === undefined||v==='') ? defaultValue : v);
6335 * Selects the value of a node, parsing integers and floats.
6336 * @param {String} selector The selector/xpath query
6337 * @param {Node} root (optional) The start of the query (defaults to document).
6338 * @param {Number} defaultValue
6341 selectNumber : function(path, root, defaultValue){
6342 var v = Roo.DomQuery.selectValue(path, root, defaultValue || 0);
6343 return parseFloat(v);
6347 * Returns true if the passed element(s) match the passed simple selector (e.g. div.some-class or span:first-child)
6348 * @param {String/HTMLElement/Array} el An element id, element or array of elements
6349 * @param {String} selector The simple selector to test
6352 is : function(el, ss){
6353 if(typeof el == "string"){
6354 el = document.getElementById(el);
6356 var isArray = (el instanceof Array);
6357 var result = Roo.DomQuery.filter(isArray ? el : [el], ss);
6358 return isArray ? (result.length == el.length) : (result.length > 0);
6362 * Filters an array of elements to only include matches of a simple selector (e.g. div.some-class or span:first-child)
6363 * @param {Array} el An array of elements to filter
6364 * @param {String} selector The simple selector to test
6365 * @param {Boolean} nonMatches If true, it returns the elements that DON'T match
6366 * the selector instead of the ones that match
6369 filter : function(els, ss, nonMatches){
6370 ss = ss.replace(trimRe, "");
6371 if(!simpleCache[ss]){
6372 simpleCache[ss] = Roo.DomQuery.compile(ss, "simple");
6374 var result = simpleCache[ss](els);
6375 return nonMatches ? quickDiff(result, els) : result;
6379 * Collection of matching regular expressions and code snippets.
6383 select: 'n = byClassName(n, null, " {1} ");'
6385 re: /^\:([\w-]+)(?:\(((?:[^\s>\/]*|.*?))\))?/,
6386 select: 'n = byPseudo(n, "{1}", "{2}");'
6388 re: /^(?:([\[\{])(?:@)?([\w-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]\}])/,
6389 select: 'n = byAttribute(n, "{2}", "{4}", "{3}", "{1}");'
6392 select: 'n = byId(n, null, "{1}");'
6395 select: 'return {firstChild:{nodeValue:attrValue(n, "{1}")}};'
6400 * Collection of operator comparison functions. The default operators are =, !=, ^=, $=, *=, %=, |= and ~=.
6401 * 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, > <.
6404 "=" : function(a, v){
6407 "!=" : function(a, v){
6410 "^=" : function(a, v){
6411 return a && a.substr(0, v.length) == v;
6413 "$=" : function(a, v){
6414 return a && a.substr(a.length-v.length) == v;
6416 "*=" : function(a, v){
6417 return a && a.indexOf(v) !== -1;
6419 "%=" : function(a, v){
6420 return (a % v) == 0;
6422 "|=" : function(a, v){
6423 return a && (a == v || a.substr(0, v.length+1) == v+'-');
6425 "~=" : function(a, v){
6426 return a && (' '+a+' ').indexOf(' '+v+' ') != -1;
6431 * Collection of "pseudo class" processors. Each processor is passed the current nodeset (array)
6432 * and the argument (if any) supplied in the selector.
6435 "first-child" : function(c){
6436 var r = [], ri = -1, n;
6437 for(var i = 0, ci; ci = n = c[i]; i++){
6438 while((n = n.previousSibling) && n.nodeType != 1);
6446 "last-child" : function(c){
6447 var r = [], ri = -1, n;
6448 for(var i = 0, ci; ci = n = c[i]; i++){
6449 while((n = n.nextSibling) && n.nodeType != 1);
6457 "nth-child" : function(c, a) {
6458 var r = [], ri = -1;
6459 var m = nthRe.exec(a == "even" && "2n" || a == "odd" && "2n+1" || !nthRe2.test(a) && "n+" + a || a);
6460 var f = (m[1] || 1) - 0, l = m[2] - 0;
6461 for(var i = 0, n; n = c[i]; i++){
6462 var pn = n.parentNode;
6463 if (batch != pn._batch) {
6465 for(var cn = pn.firstChild; cn; cn = cn.nextSibling){
6466 if(cn.nodeType == 1){
6473 if (l == 0 || n.nodeIndex == l){
6476 } else if ((n.nodeIndex + l) % f == 0){
6484 "only-child" : function(c){
6485 var r = [], ri = -1;;
6486 for(var i = 0, ci; ci = c[i]; i++){
6487 if(!prev(ci) && !next(ci)){
6494 "empty" : function(c){
6495 var r = [], ri = -1;
6496 for(var i = 0, ci; ci = c[i]; i++){
6497 var cns = ci.childNodes, j = 0, cn, empty = true;
6500 if(cn.nodeType == 1 || cn.nodeType == 3){
6512 "contains" : function(c, v){
6513 var r = [], ri = -1;
6514 for(var i = 0, ci; ci = c[i]; i++){
6515 if((ci.textContent||ci.innerText||'').indexOf(v) != -1){
6522 "nodeValue" : function(c, v){
6523 var r = [], ri = -1;
6524 for(var i = 0, ci; ci = c[i]; i++){
6525 if(ci.firstChild && ci.firstChild.nodeValue == v){
6532 "checked" : function(c){
6533 var r = [], ri = -1;
6534 for(var i = 0, ci; ci = c[i]; i++){
6535 if(ci.checked == true){
6542 "not" : function(c, ss){
6543 return Roo.DomQuery.filter(c, ss, true);
6546 "odd" : function(c){
6547 return this["nth-child"](c, "odd");
6550 "even" : function(c){
6551 return this["nth-child"](c, "even");
6554 "nth" : function(c, a){
6555 return c[a-1] || [];
6558 "first" : function(c){
6562 "last" : function(c){
6563 return c[c.length-1] || [];
6566 "has" : function(c, ss){
6567 var s = Roo.DomQuery.select;
6568 var r = [], ri = -1;
6569 for(var i = 0, ci; ci = c[i]; i++){
6570 if(s(ss, ci).length > 0){
6577 "next" : function(c, ss){
6578 var is = Roo.DomQuery.is;
6579 var r = [], ri = -1;
6580 for(var i = 0, ci; ci = c[i]; i++){
6589 "prev" : function(c, ss){
6590 var is = Roo.DomQuery.is;
6591 var r = [], ri = -1;
6592 for(var i = 0, ci; ci = c[i]; i++){
6605 * Selects an array of DOM nodes by CSS/XPath selector. Shorthand of {@link Roo.DomQuery#select}
6606 * @param {String} path The selector/xpath query
6607 * @param {Node} root (optional) The start of the query (defaults to document).
6612 Roo.query = Roo.DomQuery.select;
6615 * Ext JS Library 1.1.1
6616 * Copyright(c) 2006-2007, Ext JS, LLC.
6618 * Originally Released Under LGPL - original licence link has changed is not relivant.
6621 * <script type="text/javascript">
6625 * @class Roo.util.Observable
6626 * Base class that provides a common interface for publishing events. Subclasses are expected to
6627 * to have a property "events" with all the events defined.<br>
6630 Employee = function(name){
6637 Roo.extend(Employee, Roo.util.Observable);
6639 * @param {Object} config properties to use (incuding events / listeners)
6642 Roo.util.Observable = function(cfg){
6645 this.addEvents(cfg.events || {});
6647 delete cfg.events; // make sure
6650 Roo.apply(this, cfg);
6653 this.on(this.listeners);
6654 delete this.listeners;
6657 Roo.util.Observable.prototype = {
6659 * @cfg {Object} listeners list of events and functions to call for this object,
6663 'click' : function(e) {
6673 * Fires the specified event with the passed parameters (minus the event name).
6674 * @param {String} eventName
6675 * @param {Object...} args Variable number of parameters are passed to handlers
6676 * @return {Boolean} returns false if any of the handlers return false otherwise it returns true
6678 fireEvent : function(){
6679 var ce = this.events[arguments[0].toLowerCase()];
6680 if(typeof ce == "object"){
6681 return ce.fire.apply(ce, Array.prototype.slice.call(arguments, 1));
6688 filterOptRe : /^(?:scope|delay|buffer|single)$/,
6691 * Appends an event handler to this component
6692 * @param {String} eventName The type of event to listen for
6693 * @param {Function} handler The method the event invokes
6694 * @param {Object} scope (optional) The scope in which to execute the handler
6695 * function. The handler function's "this" context.
6696 * @param {Object} options (optional) An object containing handler configuration
6697 * properties. This may contain any of the following properties:<ul>
6698 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
6699 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
6700 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
6701 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
6702 * by the specified number of milliseconds. If the event fires again within that time, the original
6703 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
6706 * <b>Combining Options</b><br>
6707 * Using the options argument, it is possible to combine different types of listeners:<br>
6709 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)
6711 el.on('click', this.onClick, this, {
6718 * <b>Attaching multiple handlers in 1 call</b><br>
6719 * The method also allows for a single argument to be passed which is a config object containing properties
6720 * which specify multiple handlers.
6729 fn: this.onMouseOver,
6733 fn: this.onMouseOut,
6739 * Or a shorthand syntax which passes the same scope object to all handlers:
6742 'click': this.onClick,
6743 'mouseover': this.onMouseOver,
6744 'mouseout': this.onMouseOut,
6749 addListener : function(eventName, fn, scope, o){
6750 if(typeof eventName == "object"){
6753 if(this.filterOptRe.test(e)){
6756 if(typeof o[e] == "function"){
6758 this.addListener(e, o[e], o.scope, o);
6760 // individual options
6761 this.addListener(e, o[e].fn, o[e].scope, o[e]);
6766 o = (!o || typeof o == "boolean") ? {} : o;
6767 eventName = eventName.toLowerCase();
6768 var ce = this.events[eventName] || true;
6769 if(typeof ce == "boolean"){
6770 ce = new Roo.util.Event(this, eventName);
6771 this.events[eventName] = ce;
6773 ce.addListener(fn, scope, o);
6777 * Removes a listener
6778 * @param {String} eventName The type of event to listen for
6779 * @param {Function} handler The handler to remove
6780 * @param {Object} scope (optional) The scope (this object) for the handler
6782 removeListener : function(eventName, fn, scope){
6783 var ce = this.events[eventName.toLowerCase()];
6784 if(typeof ce == "object"){
6785 ce.removeListener(fn, scope);
6790 * Removes all listeners for this object
6792 purgeListeners : function(){
6793 for(var evt in this.events){
6794 if(typeof this.events[evt] == "object"){
6795 this.events[evt].clearListeners();
6800 relayEvents : function(o, events){
6801 var createHandler = function(ename){
6804 return this.fireEvent.apply(this, Roo.combine(ename, Array.prototype.slice.call(arguments, 0)));
6807 for(var i = 0, len = events.length; i < len; i++){
6808 var ename = events[i];
6809 if(!this.events[ename]){
6810 this.events[ename] = true;
6812 o.on(ename, createHandler(ename), this);
6817 * Used to define events on this Observable
6818 * @param {Object} object The object with the events defined
6820 addEvents : function(o){
6824 Roo.applyIf(this.events, o);
6828 * Checks to see if this object has any listeners for a specified event
6829 * @param {String} eventName The name of the event to check for
6830 * @return {Boolean} True if the event is being listened for, else false
6832 hasListener : function(eventName){
6833 var e = this.events[eventName];
6834 return typeof e == "object" && e.listeners.length > 0;
6838 * Appends an event handler to this element (shorthand for addListener)
6839 * @param {String} eventName The type of event to listen for
6840 * @param {Function} handler The method the event invokes
6841 * @param {Object} scope (optional) The scope in which to execute the handler
6842 * function. The handler function's "this" context.
6843 * @param {Object} options (optional)
6846 Roo.util.Observable.prototype.on = Roo.util.Observable.prototype.addListener;
6848 * Removes a listener (shorthand for removeListener)
6849 * @param {String} eventName The type of event to listen for
6850 * @param {Function} handler The handler to remove
6851 * @param {Object} scope (optional) The scope (this object) for the handler
6854 Roo.util.Observable.prototype.un = Roo.util.Observable.prototype.removeListener;
6857 * Starts capture on the specified Observable. All events will be passed
6858 * to the supplied function with the event name + standard signature of the event
6859 * <b>before</b> the event is fired. If the supplied function returns false,
6860 * the event will not fire.
6861 * @param {Observable} o The Observable to capture
6862 * @param {Function} fn The function to call
6863 * @param {Object} scope (optional) The scope (this object) for the fn
6866 Roo.util.Observable.capture = function(o, fn, scope){
6867 o.fireEvent = o.fireEvent.createInterceptor(fn, scope);
6871 * Removes <b>all</b> added captures from the Observable.
6872 * @param {Observable} o The Observable to release
6875 Roo.util.Observable.releaseCapture = function(o){
6876 o.fireEvent = Roo.util.Observable.prototype.fireEvent;
6881 var createBuffered = function(h, o, scope){
6882 var task = new Roo.util.DelayedTask();
6884 task.delay(o.buffer, h, scope, Array.prototype.slice.call(arguments, 0));
6888 var createSingle = function(h, e, fn, scope){
6890 e.removeListener(fn, scope);
6891 return h.apply(scope, arguments);
6895 var createDelayed = function(h, o, scope){
6897 var args = Array.prototype.slice.call(arguments, 0);
6898 setTimeout(function(){
6899 h.apply(scope, args);
6904 Roo.util.Event = function(obj, name){
6907 this.listeners = [];
6910 Roo.util.Event.prototype = {
6911 addListener : function(fn, scope, options){
6912 var o = options || {};
6913 scope = scope || this.obj;
6914 if(!this.isListening(fn, scope)){
6915 var l = {fn: fn, scope: scope, options: o};
6918 h = createDelayed(h, o, scope);
6921 h = createSingle(h, this, fn, scope);
6924 h = createBuffered(h, o, scope);
6927 if(!this.firing){ // if we are currently firing this event, don't disturb the listener loop
6928 this.listeners.push(l);
6930 this.listeners = this.listeners.slice(0);
6931 this.listeners.push(l);
6936 findListener : function(fn, scope){
6937 scope = scope || this.obj;
6938 var ls = this.listeners;
6939 for(var i = 0, len = ls.length; i < len; i++){
6941 if(l.fn == fn && l.scope == scope){
6948 isListening : function(fn, scope){
6949 return this.findListener(fn, scope) != -1;
6952 removeListener : function(fn, scope){
6954 if((index = this.findListener(fn, scope)) != -1){
6956 this.listeners.splice(index, 1);
6958 this.listeners = this.listeners.slice(0);
6959 this.listeners.splice(index, 1);
6966 clearListeners : function(){
6967 this.listeners = [];
6971 var ls = this.listeners, scope, len = ls.length;
6974 var args = Array.prototype.slice.call(arguments, 0);
6975 for(var i = 0; i < len; i++){
6977 if(l.fireFn.apply(l.scope||this.obj||window, args) === false){
6978 this.firing = false;
6982 this.firing = false;
6989 * Copyright(c) 2007-2017, Roo J Solutions Ltd
6996 * @class Roo.Document
6997 * @extends Roo.util.Observable
6998 * This is a convience class to wrap up the main document loading code.. , rather than adding Roo.onReady(......)
7000 * @param {Object} config the methods and properties of the 'base' class for the application.
7002 * Generic Page handler - implement this to start your app..
7005 * MyProject = new Roo.Document({
7007 'load' : true // your events..
7010 'ready' : function() {
7011 // fired on Roo.onReady()
7016 Roo.Document = function(cfg) {
7021 Roo.util.Observable.call(this,cfg);
7025 Roo.onReady(function() {
7026 _this.fireEvent('ready');
7032 Roo.extend(Roo.Document, Roo.util.Observable, {});/*
7034 * Ext JS Library 1.1.1
7035 * Copyright(c) 2006-2007, Ext JS, LLC.
7037 * Originally Released Under LGPL - original licence link has changed is not relivant.
7040 * <script type="text/javascript">
7044 * @class Roo.EventManager
7045 * Registers event handlers that want to receive a normalized EventObject instead of the standard browser event and provides
7046 * several useful events directly.
7047 * See {@link Roo.EventObject} for more details on normalized event objects.
7050 Roo.EventManager = function(){
7051 var docReadyEvent, docReadyProcId, docReadyState = false;
7052 var resizeEvent, resizeTask, textEvent, textSize;
7053 var E = Roo.lib.Event;
7054 var D = Roo.lib.Dom;
7059 var fireDocReady = function(){
7061 docReadyState = true;
7064 clearInterval(docReadyProcId);
7066 if(Roo.isGecko || Roo.isOpera) {
7067 document.removeEventListener("DOMContentLoaded", fireDocReady, false);
7070 var defer = document.getElementById("ie-deferred-loader");
7072 defer.onreadystatechange = null;
7073 defer.parentNode.removeChild(defer);
7077 docReadyEvent.fire();
7078 docReadyEvent.clearListeners();
7083 var initDocReady = function(){
7084 docReadyEvent = new Roo.util.Event();
7085 if(Roo.isGecko || Roo.isOpera) {
7086 document.addEventListener("DOMContentLoaded", fireDocReady, false);
7088 document.write("<s"+'cript id="ie-deferred-loader" defer="defer" src="/'+'/:"></s'+"cript>");
7089 var defer = document.getElementById("ie-deferred-loader");
7090 defer.onreadystatechange = function(){
7091 if(this.readyState == "complete"){
7095 }else if(Roo.isSafari){
7096 docReadyProcId = setInterval(function(){
7097 var rs = document.readyState;
7098 if(rs == "complete") {
7103 // no matter what, make sure it fires on load
7104 E.on(window, "load", fireDocReady);
7107 var createBuffered = function(h, o){
7108 var task = new Roo.util.DelayedTask(h);
7110 // create new event object impl so new events don't wipe out properties
7111 e = new Roo.EventObjectImpl(e);
7112 task.delay(o.buffer, h, null, [e]);
7116 var createSingle = function(h, el, ename, fn){
7118 Roo.EventManager.removeListener(el, ename, fn);
7123 var createDelayed = function(h, o){
7125 // create new event object impl so new events don't wipe out properties
7126 e = new Roo.EventObjectImpl(e);
7127 setTimeout(function(){
7132 var transitionEndVal = false;
7134 var transitionEnd = function()
7136 if (transitionEndVal) {
7137 return transitionEndVal;
7139 var el = document.createElement('div');
7141 var transEndEventNames = {
7142 WebkitTransition : 'webkitTransitionEnd',
7143 MozTransition : 'transitionend',
7144 OTransition : 'oTransitionEnd otransitionend',
7145 transition : 'transitionend'
7148 for (var name in transEndEventNames) {
7149 if (el.style[name] !== undefined) {
7150 transitionEndVal = transEndEventNames[name];
7151 return transitionEndVal ;
7158 var listen = function(element, ename, opt, fn, scope)
7160 var o = (!opt || typeof opt == "boolean") ? {} : opt;
7161 fn = fn || o.fn; scope = scope || o.scope;
7162 var el = Roo.getDom(element);
7166 throw "Error listening for \"" + ename + '\". Element "' + element + '" doesn\'t exist.';
7169 if (ename == 'transitionend') {
7170 ename = transitionEnd();
7172 var h = function(e){
7173 e = Roo.EventObject.setEvent(e);
7176 t = e.getTarget(o.delegate, el);
7183 if(o.stopEvent === true){
7186 if(o.preventDefault === true){
7189 if(o.stopPropagation === true){
7190 e.stopPropagation();
7193 if(o.normalized === false){
7197 fn.call(scope || el, e, t, o);
7200 h = createDelayed(h, o);
7203 h = createSingle(h, el, ename, fn);
7206 h = createBuffered(h, o);
7209 fn._handlers = fn._handlers || [];
7212 fn._handlers.push([Roo.id(el), ename, h]);
7216 E.on(el, ename, h); // this adds the actuall listener to the object..
7219 if(ename == "mousewheel" && el.addEventListener){ // workaround for jQuery
7220 el.addEventListener("DOMMouseScroll", h, false);
7221 E.on(window, 'unload', function(){
7222 el.removeEventListener("DOMMouseScroll", h, false);
7225 if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
7226 Roo.EventManager.stoppedMouseDownEvent.addListener(h);
7231 var stopListening = function(el, ename, fn){
7232 var id = Roo.id(el), hds = fn._handlers, hd = fn;
7234 for(var i = 0, len = hds.length; i < len; i++){
7236 if(h[0] == id && h[1] == ename){
7243 E.un(el, ename, hd);
7244 el = Roo.getDom(el);
7245 if(ename == "mousewheel" && el.addEventListener){
7246 el.removeEventListener("DOMMouseScroll", hd, false);
7248 if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
7249 Roo.EventManager.stoppedMouseDownEvent.removeListener(hd);
7253 var propRe = /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/;
7260 * @scope Roo.EventManager
7265 * This is no longer needed and is deprecated. Places a simple wrapper around an event handler to override the browser event
7266 * object with a Roo.EventObject
7267 * @param {Function} fn The method the event invokes
7268 * @param {Object} scope An object that becomes the scope of the handler
7269 * @param {boolean} override If true, the obj passed in becomes
7270 * the execution scope of the listener
7271 * @return {Function} The wrapped function
7274 wrap : function(fn, scope, override){
7276 Roo.EventObject.setEvent(e);
7277 fn.call(override ? scope || window : window, Roo.EventObject, scope);
7282 * Appends an event handler to an element (shorthand for addListener)
7283 * @param {String/HTMLElement} element The html element or id to assign the
7284 * @param {String} eventName The type of event to listen for
7285 * @param {Function} handler The method the event invokes
7286 * @param {Object} scope (optional) The scope in which to execute the handler
7287 * function. The handler function's "this" context.
7288 * @param {Object} options (optional) An object containing handler configuration
7289 * properties. This may contain any of the following properties:<ul>
7290 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
7291 * <li>delegate {String} A simple selector to filter the target or look for a descendant of the target</li>
7292 * <li>stopEvent {Boolean} True to stop the event. That is stop propagation, and prevent the default action.</li>
7293 * <li>preventDefault {Boolean} True to prevent the default action</li>
7294 * <li>stopPropagation {Boolean} True to prevent event propagation</li>
7295 * <li>normalized {Boolean} False to pass a browser event to the handler function instead of an Roo.EventObject</li>
7296 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
7297 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
7298 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
7299 * by the specified number of milliseconds. If the event fires again within that time, the original
7300 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
7303 * <b>Combining Options</b><br>
7304 * Using the options argument, it is possible to combine different types of listeners:<br>
7306 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)<div style="margin: 5px 20px 20px;">
7308 el.on('click', this.onClick, this, {
7315 * <b>Attaching multiple handlers in 1 call</b><br>
7316 * The method also allows for a single argument to be passed which is a config object containing properties
7317 * which specify multiple handlers.
7327 fn: this.onMouseOver
7336 * Or a shorthand syntax:<br>
7339 'click' : this.onClick,
7340 'mouseover' : this.onMouseOver,
7341 'mouseout' : this.onMouseOut
7345 addListener : function(element, eventName, fn, scope, options){
7346 if(typeof eventName == "object"){
7352 if(typeof o[e] == "function"){
7354 listen(element, e, o, o[e], o.scope);
7356 // individual options
7357 listen(element, e, o[e]);
7362 return listen(element, eventName, options, fn, scope);
7366 * Removes an event handler
7368 * @param {String/HTMLElement} element The id or html element to remove the
7370 * @param {String} eventName The type of event
7371 * @param {Function} fn
7372 * @return {Boolean} True if a listener was actually removed
7374 removeListener : function(element, eventName, fn){
7375 return stopListening(element, eventName, fn);
7379 * Fires when the document is ready (before onload and before images are loaded). Can be
7380 * accessed shorthanded Roo.onReady().
7381 * @param {Function} fn The method the event invokes
7382 * @param {Object} scope An object that becomes the scope of the handler
7383 * @param {boolean} options
7385 onDocumentReady : function(fn, scope, options){
7386 if(docReadyState){ // if it already fired
7387 docReadyEvent.addListener(fn, scope, options);
7388 docReadyEvent.fire();
7389 docReadyEvent.clearListeners();
7395 docReadyEvent.addListener(fn, scope, options);
7399 * Fires when the window is resized and provides resize event buffering (50 milliseconds), passes new viewport width and height to handlers.
7400 * @param {Function} fn The method the event invokes
7401 * @param {Object} scope An object that becomes the scope of the handler
7402 * @param {boolean} options
7404 onWindowResize : function(fn, scope, options)
7407 resizeEvent = new Roo.util.Event();
7408 resizeTask = new Roo.util.DelayedTask(function(){
7409 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
7411 E.on(window, "resize", function()
7414 resizeTask.delay(50);
7416 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
7420 resizeEvent.addListener(fn, scope, options);
7424 * Fires when the user changes the active text size. Handler gets called with 2 params, the old size and the new size.
7425 * @param {Function} fn The method the event invokes
7426 * @param {Object} scope An object that becomes the scope of the handler
7427 * @param {boolean} options
7429 onTextResize : function(fn, scope, options){
7431 textEvent = new Roo.util.Event();
7432 var textEl = new Roo.Element(document.createElement('div'));
7433 textEl.dom.className = 'x-text-resize';
7434 textEl.dom.innerHTML = 'X';
7435 textEl.appendTo(document.body);
7436 textSize = textEl.dom.offsetHeight;
7437 setInterval(function(){
7438 if(textEl.dom.offsetHeight != textSize){
7439 textEvent.fire(textSize, textSize = textEl.dom.offsetHeight);
7441 }, this.textResizeInterval);
7443 textEvent.addListener(fn, scope, options);
7447 * Removes the passed window resize listener.
7448 * @param {Function} fn The method the event invokes
7449 * @param {Object} scope The scope of handler
7451 removeResizeListener : function(fn, scope){
7453 resizeEvent.removeListener(fn, scope);
7458 fireResize : function(){
7460 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
7464 * Url used for onDocumentReady with using SSL (defaults to Roo.SSL_SECURE_URL)
7468 * The frequency, in milliseconds, to check for text resize events (defaults to 50)
7470 textResizeInterval : 50
7475 * @scopeAlias pub=Roo.EventManager
7479 * Appends an event handler to an element (shorthand for addListener)
7480 * @param {String/HTMLElement} element The html element or id to assign the
7481 * @param {String} eventName The type of event to listen for
7482 * @param {Function} handler The method the event invokes
7483 * @param {Object} scope (optional) The scope in which to execute the handler
7484 * function. The handler function's "this" context.
7485 * @param {Object} options (optional) An object containing handler configuration
7486 * properties. This may contain any of the following properties:<ul>
7487 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
7488 * <li>delegate {String} A simple selector to filter the target or look for a descendant of the target</li>
7489 * <li>stopEvent {Boolean} True to stop the event. That is stop propagation, and prevent the default action.</li>
7490 * <li>preventDefault {Boolean} True to prevent the default action</li>
7491 * <li>stopPropagation {Boolean} True to prevent event propagation</li>
7492 * <li>normalized {Boolean} False to pass a browser event to the handler function instead of an Roo.EventObject</li>
7493 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
7494 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
7495 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
7496 * by the specified number of milliseconds. If the event fires again within that time, the original
7497 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
7500 * <b>Combining Options</b><br>
7501 * Using the options argument, it is possible to combine different types of listeners:<br>
7503 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)<div style="margin: 5px 20px 20px;">
7505 el.on('click', this.onClick, this, {
7512 * <b>Attaching multiple handlers in 1 call</b><br>
7513 * The method also allows for a single argument to be passed which is a config object containing properties
7514 * which specify multiple handlers.
7524 fn: this.onMouseOver
7533 * Or a shorthand syntax:<br>
7536 'click' : this.onClick,
7537 'mouseover' : this.onMouseOver,
7538 'mouseout' : this.onMouseOut
7542 pub.on = pub.addListener;
7543 pub.un = pub.removeListener;
7545 pub.stoppedMouseDownEvent = new Roo.util.Event();
7549 * Fires when the document is ready (before onload and before images are loaded). Shorthand of {@link Roo.EventManager#onDocumentReady}.
7550 * @param {Function} fn The method the event invokes
7551 * @param {Object} scope An object that becomes the scope of the handler
7552 * @param {boolean} override If true, the obj passed in becomes
7553 * the execution scope of the listener
7557 Roo.onReady = Roo.EventManager.onDocumentReady;
7559 Roo.onReady(function(){
7560 var bd = Roo.get(document.body);
7565 : Roo.isIE11 ? "roo-ie11"
7566 : Roo.isEdge ? "roo-edge"
7567 : Roo.isGecko ? "roo-gecko"
7568 : Roo.isOpera ? "roo-opera"
7569 : Roo.isSafari ? "roo-safari" : ""];
7572 cls.push("roo-mac");
7575 cls.push("roo-linux");
7578 cls.push("roo-ios");
7581 cls.push("roo-touch");
7583 if(Roo.isBorderBox){
7584 cls.push('roo-border-box');
7586 if(Roo.isStrict){ // add to the parent to allow for selectors like ".ext-strict .ext-ie"
7587 var p = bd.dom.parentNode;
7589 p.className += ' roo-strict';
7592 bd.addClass(cls.join(' '));
7596 * @class Roo.EventObject
7597 * EventObject exposes the Yahoo! UI Event functionality directly on the object
7598 * passed to your event handler. It exists mostly for convenience. It also fixes the annoying null checks automatically to cleanup your code
7601 function handleClick(e){ // e is not a standard event object, it is a Roo.EventObject
7603 var target = e.getTarget();
7606 var myDiv = Roo.get("myDiv");
7607 myDiv.on("click", handleClick);
7609 Roo.EventManager.on("myDiv", 'click', handleClick);
7610 Roo.EventManager.addListener("myDiv", 'click', handleClick);
7614 Roo.EventObject = function(){
7616 var E = Roo.lib.Event;
7618 // safari keypress events for special keys return bad keycodes
7621 63235 : 39, // right
7624 63276 : 33, // page up
7625 63277 : 34, // page down
7626 63272 : 46, // delete
7631 // normalize button clicks
7632 var btnMap = Roo.isIE ? {1:0,4:1,2:2} :
7633 (Roo.isSafari ? {1:0,2:1,3:2} : {0:0,1:1,2:2});
7635 Roo.EventObjectImpl = function(e){
7637 this.setEvent(e.browserEvent || e);
7640 Roo.EventObjectImpl.prototype = {
7642 * Used to fix doc tools.
7643 * @scope Roo.EventObject.prototype
7649 /** The normal browser event */
7650 browserEvent : null,
7651 /** The button pressed in a mouse event */
7653 /** True if the shift key was down during the event */
7655 /** True if the control key was down during the event */
7657 /** True if the alt key was down during the event */
7716 setEvent : function(e){
7717 if(e == this || (e && e.browserEvent)){ // already wrapped
7720 this.browserEvent = e;
7722 // normalize buttons
7723 this.button = e.button ? btnMap[e.button] : (e.which ? e.which-1 : -1);
7724 if(e.type == 'click' && this.button == -1){
7728 this.shiftKey = e.shiftKey;
7729 // mac metaKey behaves like ctrlKey
7730 this.ctrlKey = e.ctrlKey || e.metaKey;
7731 this.altKey = e.altKey;
7732 // in getKey these will be normalized for the mac
7733 this.keyCode = e.keyCode;
7734 // keyup warnings on firefox.
7735 this.charCode = (e.type == 'keyup' || e.type == 'keydown') ? 0 : e.charCode;
7736 // cache the target for the delayed and or buffered events
7737 this.target = E.getTarget(e);
7739 this.xy = E.getXY(e);
7742 this.shiftKey = false;
7743 this.ctrlKey = false;
7744 this.altKey = false;
7754 * Stop the event (preventDefault and stopPropagation)
7756 stopEvent : function(){
7757 if(this.browserEvent){
7758 if(this.browserEvent.type == 'mousedown'){
7759 Roo.EventManager.stoppedMouseDownEvent.fire(this);
7761 E.stopEvent(this.browserEvent);
7766 * Prevents the browsers default handling of the event.
7768 preventDefault : function(){
7769 if(this.browserEvent){
7770 E.preventDefault(this.browserEvent);
7775 isNavKeyPress : function(){
7776 var k = this.keyCode;
7777 k = Roo.isSafari ? (safariKeys[k] || k) : k;
7778 return (k >= 33 && k <= 40) || k == this.RETURN || k == this.TAB || k == this.ESC;
7781 isSpecialKey : function(){
7782 var k = this.keyCode;
7783 return (this.type == 'keypress' && this.ctrlKey) || k == 9 || k == 13 || k == 40 || k == 27 ||
7784 (k == 16) || (k == 17) ||
7785 (k >= 18 && k <= 20) ||
7786 (k >= 33 && k <= 35) ||
7787 (k >= 36 && k <= 39) ||
7788 (k >= 44 && k <= 45);
7791 * Cancels bubbling of the event.
7793 stopPropagation : function(){
7794 if(this.browserEvent){
7795 if(this.type == 'mousedown'){
7796 Roo.EventManager.stoppedMouseDownEvent.fire(this);
7798 E.stopPropagation(this.browserEvent);
7803 * Gets the key code for the event.
7806 getCharCode : function(){
7807 return this.charCode || this.keyCode;
7811 * Returns a normalized keyCode for the event.
7812 * @return {Number} The key code
7814 getKey : function(){
7815 var k = this.keyCode || this.charCode;
7816 return Roo.isSafari ? (safariKeys[k] || k) : k;
7820 * Gets the x coordinate of the event.
7823 getPageX : function(){
7828 * Gets the y coordinate of the event.
7831 getPageY : function(){
7836 * Gets the time of the event.
7839 getTime : function(){
7840 if(this.browserEvent){
7841 return E.getTime(this.browserEvent);
7847 * Gets the page coordinates of the event.
7848 * @return {Array} The xy values like [x, y]
7855 * Gets the target for the event.
7856 * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target
7857 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
7858 search as a number or element (defaults to 10 || document.body)
7859 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
7860 * @return {HTMLelement}
7862 getTarget : function(selector, maxDepth, returnEl){
7863 return selector ? Roo.fly(this.target).findParent(selector, maxDepth, returnEl) : this.target;
7866 * Gets the related target.
7867 * @return {HTMLElement}
7869 getRelatedTarget : function(){
7870 if(this.browserEvent){
7871 return E.getRelatedTarget(this.browserEvent);
7877 * Normalizes mouse wheel delta across browsers
7878 * @return {Number} The delta
7880 getWheelDelta : function(){
7881 var e = this.browserEvent;
7883 if(e.wheelDelta){ /* IE/Opera. */
7884 delta = e.wheelDelta/120;
7885 }else if(e.detail){ /* Mozilla case. */
7886 delta = -e.detail/3;
7892 * Returns true if the control, meta, shift or alt key was pressed during this event.
7895 hasModifier : function(){
7896 return !!((this.ctrlKey || this.altKey) || this.shiftKey);
7900 * Returns true if the target of this event equals el or is a child of el
7901 * @param {String/HTMLElement/Element} el
7902 * @param {Boolean} related (optional) true to test if the related target is within el instead of the target
7905 within : function(el, related){
7906 var t = this[related ? "getRelatedTarget" : "getTarget"]();
7907 return t && Roo.fly(el).contains(t);
7910 getPoint : function(){
7911 return new Roo.lib.Point(this.xy[0], this.xy[1]);
7915 return new Roo.EventObjectImpl();
7920 * Ext JS Library 1.1.1
7921 * Copyright(c) 2006-2007, Ext JS, LLC.
7923 * Originally Released Under LGPL - original licence link has changed is not relivant.
7926 * <script type="text/javascript">
7930 // was in Composite Element!??!?!
7933 var D = Roo.lib.Dom;
7934 var E = Roo.lib.Event;
7935 var A = Roo.lib.Anim;
7937 // local style camelizing for speed
7939 var camelRe = /(-[a-z])/gi;
7940 var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); };
7941 var view = document.defaultView;
7944 * @class Roo.Element
7945 * Represents an Element in the DOM.<br><br>
7948 var el = Roo.get("my-div");
7951 var el = getEl("my-div");
7953 // or with a DOM element
7954 var el = Roo.get(myDivElement);
7956 * Using Roo.get() or getEl() instead of calling the constructor directly ensures you get the same object
7957 * each call instead of constructing a new one.<br><br>
7958 * <b>Animations</b><br />
7959 * Many of the functions for manipulating an element have an optional "animate" parameter. The animate parameter
7960 * should either be a boolean (true) or an object literal with animation options. The animation options are:
7962 Option Default Description
7963 --------- -------- ---------------------------------------------
7964 duration .35 The duration of the animation in seconds
7965 easing easeOut The YUI easing method
7966 callback none A function to execute when the anim completes
7967 scope this The scope (this) of the callback function
7969 * Also, the Anim object being used for the animation will be set on your options object as "anim", which allows you to stop or
7970 * manipulate the animation. Here's an example:
7972 var el = Roo.get("my-div");
7977 // default animation
7978 el.setWidth(100, true);
7980 // animation with some options set
7987 // using the "anim" property to get the Anim object
7993 el.setWidth(100, opt);
7995 if(opt.anim.isAnimated()){
7999 * <b> Composite (Collections of) Elements</b><br />
8000 * For working with collections of Elements, see <a href="Roo.CompositeElement.html">Roo.CompositeElement</a>
8001 * @constructor Create a new Element directly.
8002 * @param {String/HTMLElement} element
8003 * @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).
8005 Roo.Element = function(element, forceNew)
8007 var dom = typeof element == "string" ?
8008 document.getElementById(element) : element;
8010 this.listeners = {};
8012 if(!dom){ // invalid id/element
8016 if(forceNew !== true && id && Roo.Element.cache[id]){ // element object already exists
8017 return Roo.Element.cache[id];
8027 * The DOM element ID
8030 this.id = id || Roo.id(dom);
8032 return this; // assumed for cctor?
8035 var El = Roo.Element;
8039 * The element's default display mode (defaults to "")
8042 originalDisplay : "",
8045 // note this is overridden in BS version..
8048 * The default unit to append to CSS values where a unit isn't provided (defaults to px).
8054 * Sets the element's visibility mode. When setVisible() is called it
8055 * will use this to determine whether to set the visibility or the display property.
8056 * @param visMode Element.VISIBILITY or Element.DISPLAY
8057 * @return {Roo.Element} this
8059 setVisibilityMode : function(visMode){
8060 this.visibilityMode = visMode;
8064 * Convenience method for setVisibilityMode(Element.DISPLAY)
8065 * @param {String} display (optional) What to set display to when visible
8066 * @return {Roo.Element} this
8068 enableDisplayMode : function(display){
8069 this.setVisibilityMode(El.DISPLAY);
8070 if(typeof display != "undefined") { this.originalDisplay = display; }
8075 * 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)
8076 * @param {String} selector The simple selector to test
8077 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
8078 search as a number or element (defaults to 10 || document.body)
8079 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
8080 * @return {HTMLElement} The matching DOM node (or null if no match was found)
8082 findParent : function(simpleSelector, maxDepth, returnEl){
8083 var p = this.dom, b = document.body, depth = 0, dq = Roo.DomQuery, stopEl;
8084 maxDepth = maxDepth || 50;
8085 if(typeof maxDepth != "number"){
8086 stopEl = Roo.getDom(maxDepth);
8089 while(p && p.nodeType == 1 && depth < maxDepth && p != b && p != stopEl){
8090 if(dq.is(p, simpleSelector)){
8091 return returnEl ? Roo.get(p) : p;
8101 * Looks at parent nodes for a match of the passed simple selector (e.g. div.some-class or span:first-child)
8102 * @param {String} selector The simple selector to test
8103 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
8104 search as a number or element (defaults to 10 || document.body)
8105 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
8106 * @return {HTMLElement} The matching DOM node (or null if no match was found)
8108 findParentNode : function(simpleSelector, maxDepth, returnEl){
8109 var p = Roo.fly(this.dom.parentNode, '_internal');
8110 return p ? p.findParent(simpleSelector, maxDepth, returnEl) : null;
8114 * Looks at the scrollable parent element
8116 findScrollableParent : function()
8118 var overflowRegex = /(auto|scroll)/;
8120 if(this.getStyle('position') === 'fixed'){
8121 return Roo.isAndroid ? Roo.get(document.documentElement) : Roo.get(document.body);
8124 var excludeStaticParent = this.getStyle('position') === "absolute";
8126 for (var parent = this; (parent = Roo.get(parent.dom.parentNode));){
8128 if (excludeStaticParent && parent.getStyle('position') === "static") {
8132 if (overflowRegex.test(parent.getStyle('overflow') + parent.getStyle('overflow-x') + parent.getStyle('overflow-y'))){
8136 if(parent.dom.nodeName.toLowerCase() == 'body'){
8137 return Roo.isAndroid ? Roo.get(document.documentElement) : Roo.get(document.body);
8141 return Roo.isAndroid ? Roo.get(document.documentElement) : Roo.get(document.body);
8145 * Walks up the dom looking for a parent node that matches the passed simple selector (e.g. div.some-class or span:first-child).
8146 * This is a shortcut for findParentNode() that always returns an Roo.Element.
8147 * @param {String} selector The simple selector to test
8148 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
8149 search as a number or element (defaults to 10 || document.body)
8150 * @return {Roo.Element} The matching DOM node (or null if no match was found)
8152 up : function(simpleSelector, maxDepth){
8153 return this.findParentNode(simpleSelector, maxDepth, true);
8159 * Returns true if this element matches the passed simple selector (e.g. div.some-class or span:first-child)
8160 * @param {String} selector The simple selector to test
8161 * @return {Boolean} True if this element matches the selector, else false
8163 is : function(simpleSelector){
8164 return Roo.DomQuery.is(this.dom, simpleSelector);
8168 * Perform animation on this element.
8169 * @param {Object} args The YUI animation control args
8170 * @param {Float} duration (optional) How long the animation lasts in seconds (defaults to .35)
8171 * @param {Function} onComplete (optional) Function to call when animation completes
8172 * @param {String} easing (optional) Easing method to use (defaults to 'easeOut')
8173 * @param {String} animType (optional) 'run' is the default. Can also be 'color', 'motion', or 'scroll'
8174 * @return {Roo.Element} this
8176 animate : function(args, duration, onComplete, easing, animType){
8177 this.anim(args, {duration: duration, callback: onComplete, easing: easing}, animType);
8182 * @private Internal animation call
8184 anim : function(args, opt, animType, defaultDur, defaultEase, cb){
8185 animType = animType || 'run';
8187 var anim = Roo.lib.Anim[animType](
8189 (opt.duration || defaultDur) || .35,
8190 (opt.easing || defaultEase) || 'easeOut',
8192 Roo.callback(cb, this);
8193 Roo.callback(opt.callback, opt.scope || this, [this, opt]);
8201 // private legacy anim prep
8202 preanim : function(a, i){
8203 return !a[i] ? false : (typeof a[i] == "object" ? a[i]: {duration: a[i+1], callback: a[i+2], easing: a[i+3]});
8207 * Removes worthless text nodes
8208 * @param {Boolean} forceReclean (optional) By default the element
8209 * keeps track if it has been cleaned already so
8210 * you can call this over and over. However, if you update the element and
8211 * need to force a reclean, you can pass true.
8213 clean : function(forceReclean){
8214 if(this.isCleaned && forceReclean !== true){
8218 var d = this.dom, n = d.firstChild, ni = -1;
8220 var nx = n.nextSibling;
8221 if(n.nodeType == 3 && !ns.test(n.nodeValue)){
8228 this.isCleaned = true;
8233 calcOffsetsTo : function(el){
8236 var restorePos = false;
8237 if(el.getStyle('position') == 'static'){
8238 el.position('relative');
8243 while(op && op != d && op.tagName != 'HTML'){
8246 op = op.offsetParent;
8249 el.position('static');
8255 * Scrolls this element into view within the passed container.
8256 * @param {String/HTMLElement/Element} container (optional) The container element to scroll (defaults to document.body)
8257 * @param {Boolean} hscroll (optional) False to disable horizontal scroll (defaults to true)
8258 * @return {Roo.Element} this
8260 scrollIntoView : function(container, hscroll){
8261 var c = Roo.getDom(container) || document.body;
8264 var o = this.calcOffsetsTo(c),
8267 b = t+el.offsetHeight,
8268 r = l+el.offsetWidth;
8270 var ch = c.clientHeight;
8271 var ct = parseInt(c.scrollTop, 10);
8272 var cl = parseInt(c.scrollLeft, 10);
8274 var cr = cl + c.clientWidth;
8282 if(hscroll !== false){
8286 c.scrollLeft = r-c.clientWidth;
8293 scrollChildIntoView : function(child, hscroll){
8294 Roo.fly(child, '_scrollChildIntoView').scrollIntoView(this, hscroll);
8298 * Measures the element's content height and updates height to match. Note: this function uses setTimeout so
8299 * the new height may not be available immediately.
8300 * @param {Boolean} animate (optional) Animate the transition (defaults to false)
8301 * @param {Float} duration (optional) Length of the animation in seconds (defaults to .35)
8302 * @param {Function} onComplete (optional) Function to call when animation completes
8303 * @param {String} easing (optional) Easing method to use (defaults to easeOut)
8304 * @return {Roo.Element} this
8306 autoHeight : function(animate, duration, onComplete, easing){
8307 var oldHeight = this.getHeight();
8309 this.setHeight(1); // force clipping
8310 setTimeout(function(){
8311 var height = parseInt(this.dom.scrollHeight, 10); // parseInt for Safari
8313 this.setHeight(height);
8315 if(typeof onComplete == "function"){
8319 this.setHeight(oldHeight); // restore original height
8320 this.setHeight(height, animate, duration, function(){
8322 if(typeof onComplete == "function") { onComplete(); }
8323 }.createDelegate(this), easing);
8325 }.createDelegate(this), 0);
8330 * Returns true if this element is an ancestor of the passed element
8331 * @param {HTMLElement/String} el The element to check
8332 * @return {Boolean} True if this element is an ancestor of el, else false
8334 contains : function(el){
8335 if(!el){return false;}
8336 return D.isAncestor(this.dom, el.dom ? el.dom : el);
8340 * Checks whether the element is currently visible using both visibility and display properties.
8341 * @param {Boolean} deep (optional) True to walk the dom and see if parent elements are hidden (defaults to false)
8342 * @return {Boolean} True if the element is currently visible, else false
8344 isVisible : function(deep) {
8345 var vis = !(this.getStyle("visibility") == "hidden" || this.getStyle("display") == "none");
8346 if(deep !== true || !vis){
8349 var p = this.dom.parentNode;
8350 while(p && p.tagName.toLowerCase() != "body"){
8351 if(!Roo.fly(p, '_isVisible').isVisible()){
8360 * Creates a {@link Roo.CompositeElement} for child nodes based on the passed CSS selector (the selector should not contain an id).
8361 * @param {String} selector The CSS selector
8362 * @param {Boolean} unique (optional) True to create a unique Roo.Element for each child (defaults to false, which creates a single shared flyweight object)
8363 * @return {CompositeElement/CompositeElementLite} The composite element
8365 select : function(selector, unique){
8366 return El.select(selector, unique, this.dom);
8370 * Selects child nodes based on the passed CSS selector (the selector should not contain an id).
8371 * @param {String} selector The CSS selector
8372 * @return {Array} An array of the matched nodes
8374 query : function(selector, unique){
8375 return Roo.DomQuery.select(selector, this.dom);
8379 * Selects a single child at any depth below this element based on the passed CSS selector (the selector should not contain an id).
8380 * @param {String} selector The CSS selector
8381 * @param {Boolean} returnDom (optional) True to return the DOM node instead of Roo.Element (defaults to false)
8382 * @return {HTMLElement/Roo.Element} The child Roo.Element (or DOM node if returnDom = true)
8384 child : function(selector, returnDom){
8385 var n = Roo.DomQuery.selectNode(selector, this.dom);
8386 return returnDom ? n : Roo.get(n);
8390 * Selects a single *direct* child based on the passed CSS selector (the selector should not contain an id).
8391 * @param {String} selector The CSS selector
8392 * @param {Boolean} returnDom (optional) True to return the DOM node instead of Roo.Element (defaults to false)
8393 * @return {HTMLElement/Roo.Element} The child Roo.Element (or DOM node if returnDom = true)
8395 down : function(selector, returnDom){
8396 var n = Roo.DomQuery.selectNode(" > " + selector, this.dom);
8397 return returnDom ? n : Roo.get(n);
8401 * Initializes a {@link Roo.dd.DD} drag drop object for this element.
8402 * @param {String} group The group the DD object is member of
8403 * @param {Object} config The DD config object
8404 * @param {Object} overrides An object containing methods to override/implement on the DD object
8405 * @return {Roo.dd.DD} The DD object
8407 initDD : function(group, config, overrides){
8408 var dd = new Roo.dd.DD(Roo.id(this.dom), group, config);
8409 return Roo.apply(dd, overrides);
8413 * Initializes a {@link Roo.dd.DDProxy} object for this element.
8414 * @param {String} group The group the DDProxy object is member of
8415 * @param {Object} config The DDProxy config object
8416 * @param {Object} overrides An object containing methods to override/implement on the DDProxy object
8417 * @return {Roo.dd.DDProxy} The DDProxy object
8419 initDDProxy : function(group, config, overrides){
8420 var dd = new Roo.dd.DDProxy(Roo.id(this.dom), group, config);
8421 return Roo.apply(dd, overrides);
8425 * Initializes a {@link Roo.dd.DDTarget} object for this element.
8426 * @param {String} group The group the DDTarget object is member of
8427 * @param {Object} config The DDTarget config object
8428 * @param {Object} overrides An object containing methods to override/implement on the DDTarget object
8429 * @return {Roo.dd.DDTarget} The DDTarget object
8431 initDDTarget : function(group, config, overrides){
8432 var dd = new Roo.dd.DDTarget(Roo.id(this.dom), group, config);
8433 return Roo.apply(dd, overrides);
8437 * Sets the visibility of the element (see details). If the visibilityMode is set to Element.DISPLAY, it will use
8438 * the display property to hide the element, otherwise it uses visibility. The default is to hide and show using the visibility property.
8439 * @param {Boolean} visible Whether the element is visible
8440 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8441 * @return {Roo.Element} this
8443 setVisible : function(visible, animate){
8445 if(this.visibilityMode == El.DISPLAY){
8446 this.setDisplayed(visible);
8449 this.dom.style.visibility = visible ? "visible" : "hidden";
8452 // closure for composites
8454 var visMode = this.visibilityMode;
8456 this.setOpacity(.01);
8457 this.setVisible(true);
8459 this.anim({opacity: { to: (visible?1:0) }},
8460 this.preanim(arguments, 1),
8461 null, .35, 'easeIn', function(){
8463 if(visMode == El.DISPLAY){
8464 dom.style.display = "none";
8466 dom.style.visibility = "hidden";
8468 Roo.get(dom).setOpacity(1);
8476 * Returns true if display is not "none"
8479 isDisplayed : function() {
8480 return this.getStyle("display") != "none";
8484 * Toggles the element's visibility or display, depending on visibility mode.
8485 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8486 * @return {Roo.Element} this
8488 toggle : function(animate){
8489 this.setVisible(!this.isVisible(), this.preanim(arguments, 0));
8494 * Sets the CSS display property. Uses originalDisplay if the specified value is a boolean true.
8495 * @param {Boolean} value Boolean value to display the element using its default display, or a string to set the display directly
8496 * @return {Roo.Element} this
8498 setDisplayed : function(value) {
8499 if(typeof value == "boolean"){
8500 value = value ? this.originalDisplay : "none";
8502 this.setStyle("display", value);
8507 * Tries to focus the element. Any exceptions are caught and ignored.
8508 * @return {Roo.Element} this
8510 focus : function() {
8518 * Tries to blur the element. Any exceptions are caught and ignored.
8519 * @return {Roo.Element} this
8529 * Adds one or more CSS classes to the element. Duplicate classes are automatically filtered out.
8530 * @param {String/Array} className The CSS class to add, or an array of classes
8531 * @return {Roo.Element} this
8533 addClass : function(className){
8534 if(className instanceof Array){
8535 for(var i = 0, len = className.length; i < len; i++) {
8536 this.addClass(className[i]);
8539 if(className && !this.hasClass(className)){
8540 if (this.dom instanceof SVGElement) {
8541 this.dom.className.baseVal =this.dom.className.baseVal + " " + className;
8543 this.dom.className = this.dom.className + " " + className;
8551 * Adds one or more CSS classes to this element and removes the same class(es) from all siblings.
8552 * @param {String/Array} className The CSS class to add, or an array of classes
8553 * @return {Roo.Element} this
8555 radioClass : function(className){
8556 var siblings = this.dom.parentNode.childNodes;
8557 for(var i = 0; i < siblings.length; i++) {
8558 var s = siblings[i];
8559 if(s.nodeType == 1){
8560 Roo.get(s).removeClass(className);
8563 this.addClass(className);
8568 * Removes one or more CSS classes from the element.
8569 * @param {String/Array} className The CSS class to remove, or an array of classes
8570 * @return {Roo.Element} this
8572 removeClass : function(className){
8574 var cn = this.dom instanceof SVGElement ? this.dom.className.baseVal : this.dom.className;
8575 if(!className || !cn){
8578 if(className instanceof Array){
8579 for(var i = 0, len = className.length; i < len; i++) {
8580 this.removeClass(className[i]);
8583 if(this.hasClass(className)){
8584 var re = this.classReCache[className];
8586 re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)', "g");
8587 this.classReCache[className] = re;
8589 if (this.dom instanceof SVGElement) {
8590 this.dom.className.baseVal = cn.replace(re, " ");
8592 this.dom.className = cn.replace(re, " ");
8603 * Toggles the specified CSS class on this element (removes it if it already exists, otherwise adds it).
8604 * @param {String} className The CSS class to toggle
8605 * @return {Roo.Element} this
8607 toggleClass : function(className){
8608 if(this.hasClass(className)){
8609 this.removeClass(className);
8611 this.addClass(className);
8617 * Checks if the specified CSS class exists on this element's DOM node.
8618 * @param {String} className The CSS class to check for
8619 * @return {Boolean} True if the class exists, else false
8621 hasClass : function(className){
8622 if (this.dom instanceof SVGElement) {
8623 return className && (' '+this.dom.className.baseVal +' ').indexOf(' '+className+' ') != -1;
8625 return className && (' '+this.dom.className+' ').indexOf(' '+className+' ') != -1;
8629 * Replaces a CSS class on the element with another. If the old name does not exist, the new name will simply be added.
8630 * @param {String} oldClassName The CSS class to replace
8631 * @param {String} newClassName The replacement CSS class
8632 * @return {Roo.Element} this
8634 replaceClass : function(oldClassName, newClassName){
8635 this.removeClass(oldClassName);
8636 this.addClass(newClassName);
8641 * Returns an object with properties matching the styles requested.
8642 * For example, el.getStyles('color', 'font-size', 'width') might return
8643 * {'color': '#FFFFFF', 'font-size': '13px', 'width': '100px'}.
8644 * @param {String} style1 A style name
8645 * @param {String} style2 A style name
8646 * @param {String} etc.
8647 * @return {Object} The style object
8649 getStyles : function(){
8650 var a = arguments, len = a.length, r = {};
8651 for(var i = 0; i < len; i++){
8652 r[a[i]] = this.getStyle(a[i]);
8658 * Normalizes currentStyle and computedStyle. This is not YUI getStyle, it is an optimised version.
8659 * @param {String} property The style property whose value is returned.
8660 * @return {String} The current value of the style property for this element.
8662 getStyle : function(){
8663 return view && view.getComputedStyle ?
8665 var el = this.dom, v, cs, camel;
8666 if(prop == 'float'){
8669 if(el.style && (v = el.style[prop])){
8672 if(cs = view.getComputedStyle(el, "")){
8673 if(!(camel = propCache[prop])){
8674 camel = propCache[prop] = prop.replace(camelRe, camelFn);
8681 var el = this.dom, v, cs, camel;
8682 if(prop == 'opacity'){
8683 if(typeof el.style.filter == 'string'){
8684 var m = el.style.filter.match(/alpha\(opacity=(.*)\)/i);
8686 var fv = parseFloat(m[1]);
8688 return fv ? fv / 100 : 0;
8693 }else if(prop == 'float'){
8694 prop = "styleFloat";
8696 if(!(camel = propCache[prop])){
8697 camel = propCache[prop] = prop.replace(camelRe, camelFn);
8699 if(v = el.style[camel]){
8702 if(cs = el.currentStyle){
8710 * Wrapper for setting style properties, also takes single object parameter of multiple styles.
8711 * @param {String/Object} property The style property to be set, or an object of multiple styles.
8712 * @param {String} value (optional) The value to apply to the given property, or null if an object was passed.
8713 * @return {Roo.Element} this
8715 setStyle : function(prop, value){
8716 if(typeof prop == "string"){
8718 if (prop == 'float') {
8719 this.setStyle(Roo.isIE ? 'styleFloat' : 'cssFloat', value);
8724 if(!(camel = propCache[prop])){
8725 camel = propCache[prop] = prop.replace(camelRe, camelFn);
8728 if(camel == 'opacity') {
8729 this.setOpacity(value);
8731 this.dom.style[camel] = value;
8734 for(var style in prop){
8735 if(typeof prop[style] != "function"){
8736 this.setStyle(style, prop[style]);
8744 * More flexible version of {@link #setStyle} for setting style properties.
8745 * @param {String/Object/Function} styles A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
8746 * a function which returns such a specification.
8747 * @return {Roo.Element} this
8749 applyStyles : function(style){
8750 Roo.DomHelper.applyStyles(this.dom, style);
8755 * 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).
8756 * @return {Number} The X position of the element
8759 return D.getX(this.dom);
8763 * 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).
8764 * @return {Number} The Y position of the element
8767 return D.getY(this.dom);
8771 * 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).
8772 * @return {Array} The XY position of the element
8775 return D.getXY(this.dom);
8779 * 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).
8780 * @param {Number} The X position of the element
8781 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8782 * @return {Roo.Element} this
8784 setX : function(x, animate){
8786 D.setX(this.dom, x);
8788 this.setXY([x, this.getY()], this.preanim(arguments, 1));
8794 * 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).
8795 * @param {Number} The Y position of the element
8796 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8797 * @return {Roo.Element} this
8799 setY : function(y, animate){
8801 D.setY(this.dom, y);
8803 this.setXY([this.getX(), y], this.preanim(arguments, 1));
8809 * Sets the element's left position directly using CSS style (instead of {@link #setX}).
8810 * @param {String} left The left CSS property value
8811 * @return {Roo.Element} this
8813 setLeft : function(left){
8814 this.setStyle("left", this.addUnits(left));
8819 * Sets the element's top position directly using CSS style (instead of {@link #setY}).
8820 * @param {String} top The top CSS property value
8821 * @return {Roo.Element} this
8823 setTop : function(top){
8824 this.setStyle("top", this.addUnits(top));
8829 * Sets the element's CSS right style.
8830 * @param {String} right The right CSS property value
8831 * @return {Roo.Element} this
8833 setRight : function(right){
8834 this.setStyle("right", this.addUnits(right));
8839 * Sets the element's CSS bottom style.
8840 * @param {String} bottom The bottom CSS property value
8841 * @return {Roo.Element} this
8843 setBottom : function(bottom){
8844 this.setStyle("bottom", this.addUnits(bottom));
8849 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
8850 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
8851 * @param {Array} pos Contains X & Y [x, y] values for new position (coordinates are page-based)
8852 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8853 * @return {Roo.Element} this
8855 setXY : function(pos, animate){
8857 D.setXY(this.dom, pos);
8859 this.anim({points: {to: pos}}, this.preanim(arguments, 1), 'motion');
8865 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
8866 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
8867 * @param {Number} x X value for new position (coordinates are page-based)
8868 * @param {Number} y Y value for new position (coordinates are page-based)
8869 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8870 * @return {Roo.Element} this
8872 setLocation : function(x, y, animate){
8873 this.setXY([x, y], this.preanim(arguments, 2));
8878 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
8879 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
8880 * @param {Number} x X value for new position (coordinates are page-based)
8881 * @param {Number} y Y value for new position (coordinates are page-based)
8882 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8883 * @return {Roo.Element} this
8885 moveTo : function(x, y, animate){
8886 this.setXY([x, y], this.preanim(arguments, 2));
8891 * Returns the region of the given element.
8892 * The element must be part of the DOM tree to have a region (display:none or elements not appended return false).
8893 * @return {Region} A Roo.lib.Region containing "top, left, bottom, right" member data.
8895 getRegion : function(){
8896 return D.getRegion(this.dom);
8900 * Returns the offset height of the element
8901 * @param {Boolean} contentHeight (optional) true to get the height minus borders and padding
8902 * @return {Number} The element's height
8904 getHeight : function(contentHeight){
8905 var h = this.dom.offsetHeight || 0;
8906 return contentHeight !== true ? h : h-this.getBorderWidth("tb")-this.getPadding("tb");
8910 * Returns the offset width of the element
8911 * @param {Boolean} contentWidth (optional) true to get the width minus borders and padding
8912 * @return {Number} The element's width
8914 getWidth : function(contentWidth){
8915 var w = this.dom.offsetWidth || 0;
8916 return contentWidth !== true ? w : w-this.getBorderWidth("lr")-this.getPadding("lr");
8920 * Returns either the offsetHeight or the height of this element based on CSS height adjusted by padding or borders
8921 * when needed to simulate offsetHeight when offsets aren't available. This may not work on display:none elements
8922 * if a height has not been set using CSS.
8925 getComputedHeight : function(){
8926 var h = Math.max(this.dom.offsetHeight, this.dom.clientHeight);
8928 h = parseInt(this.getStyle('height'), 10) || 0;
8929 if(!this.isBorderBox()){
8930 h += this.getFrameWidth('tb');
8937 * Returns either the offsetWidth or the width of this element based on CSS width adjusted by padding or borders
8938 * when needed to simulate offsetWidth when offsets aren't available. This may not work on display:none elements
8939 * if a width has not been set using CSS.
8942 getComputedWidth : function(){
8943 var w = Math.max(this.dom.offsetWidth, this.dom.clientWidth);
8945 w = parseInt(this.getStyle('width'), 10) || 0;
8946 if(!this.isBorderBox()){
8947 w += this.getFrameWidth('lr');
8954 * Returns the size of the element.
8955 * @param {Boolean} contentSize (optional) true to get the width/size minus borders and padding
8956 * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
8958 getSize : function(contentSize){
8959 return {width: this.getWidth(contentSize), height: this.getHeight(contentSize)};
8963 * Returns the width and height of the viewport.
8964 * @return {Object} An object containing the viewport's size {width: (viewport width), height: (viewport height)}
8966 getViewSize : function(){
8967 var d = this.dom, doc = document, aw = 0, ah = 0;
8968 if(d == doc || d == doc.body){
8969 return {width : D.getViewWidth(), height: D.getViewHeight()};
8972 width : d.clientWidth,
8973 height: d.clientHeight
8979 * Returns the value of the "value" attribute
8980 * @param {Boolean} asNumber true to parse the value as a number
8981 * @return {String/Number}
8983 getValue : function(asNumber){
8984 return asNumber ? parseInt(this.dom.value, 10) : this.dom.value;
8988 adjustWidth : function(width){
8989 if(typeof width == "number"){
8990 if(this.autoBoxAdjust && !this.isBorderBox()){
8991 width -= (this.getBorderWidth("lr") + this.getPadding("lr"));
9001 adjustHeight : function(height){
9002 if(typeof height == "number"){
9003 if(this.autoBoxAdjust && !this.isBorderBox()){
9004 height -= (this.getBorderWidth("tb") + this.getPadding("tb"));
9014 * Set the width of the element
9015 * @param {Number} width The new width
9016 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9017 * @return {Roo.Element} this
9019 setWidth : function(width, animate){
9020 width = this.adjustWidth(width);
9022 this.dom.style.width = this.addUnits(width);
9024 this.anim({width: {to: width}}, this.preanim(arguments, 1));
9030 * Set the height of the element
9031 * @param {Number} height The new height
9032 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9033 * @return {Roo.Element} this
9035 setHeight : function(height, animate){
9036 height = this.adjustHeight(height);
9038 this.dom.style.height = this.addUnits(height);
9040 this.anim({height: {to: height}}, this.preanim(arguments, 1));
9046 * Set the size of the element. If animation is true, both width an height will be animated concurrently.
9047 * @param {Number} width The new width
9048 * @param {Number} height The new height
9049 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9050 * @return {Roo.Element} this
9052 setSize : function(width, height, animate){
9053 if(typeof width == "object"){ // in case of object from getSize()
9054 height = width.height; width = width.width;
9056 width = this.adjustWidth(width); height = this.adjustHeight(height);
9058 this.dom.style.width = this.addUnits(width);
9059 this.dom.style.height = this.addUnits(height);
9061 this.anim({width: {to: width}, height: {to: height}}, this.preanim(arguments, 2));
9067 * Sets the element's position and size in one shot. If animation is true then width, height, x and y will be animated concurrently.
9068 * @param {Number} x X value for new position (coordinates are page-based)
9069 * @param {Number} y Y value for new position (coordinates are page-based)
9070 * @param {Number} width The new width
9071 * @param {Number} height The new height
9072 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9073 * @return {Roo.Element} this
9075 setBounds : function(x, y, width, height, animate){
9077 this.setSize(width, height);
9078 this.setLocation(x, y);
9080 width = this.adjustWidth(width); height = this.adjustHeight(height);
9081 this.anim({points: {to: [x, y]}, width: {to: width}, height: {to: height}},
9082 this.preanim(arguments, 4), 'motion');
9088 * 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.
9089 * @param {Roo.lib.Region} region The region to fill
9090 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9091 * @return {Roo.Element} this
9093 setRegion : function(region, animate){
9094 this.setBounds(region.left, region.top, region.right-region.left, region.bottom-region.top, this.preanim(arguments, 1));
9099 * Appends an event handler
9101 * @param {String} eventName The type of event to append
9102 * @param {Function} fn The method the event invokes
9103 * @param {Object} scope (optional) The scope (this object) of the fn
9104 * @param {Object} options (optional)An object with standard {@link Roo.EventManager#addListener} options
9106 addListener : function(eventName, fn, scope, options)
9108 if (eventName == 'dblclick') { // doublclick (touchstart) - faked on touch.
9109 this.addListener('touchstart', this.onTapHandler, this);
9112 // we need to handle a special case where dom element is a svg element.
9113 // in this case we do not actua
9118 if (this.dom instanceof SVGElement && !(this.dom instanceof SVGSVGElement)) {
9119 if (typeof(this.listeners[eventName]) == 'undefined') {
9120 this.listeners[eventName] = new Roo.util.Event(this, eventName);
9122 this.listeners[eventName].addListener(fn, scope, options);
9127 Roo.EventManager.on(this.dom, eventName, fn, scope || this, options);
9132 onTapHandler : function(event)
9134 if(!this.tapedTwice) {
9135 this.tapedTwice = true;
9137 setTimeout( function() {
9138 s.tapedTwice = false;
9142 event.preventDefault();
9143 var revent = new MouseEvent('dblclick', {
9149 this.dom.dispatchEvent(revent);
9150 //action on double tap goes below
9155 * Removes an event handler from this element
9156 * @param {String} eventName the type of event to remove
9157 * @param {Function} fn the method the event invokes
9158 * @param {Function} scope (needed for svg fake listeners)
9159 * @return {Roo.Element} this
9161 removeListener : function(eventName, fn, scope){
9162 Roo.EventManager.removeListener(this.dom, eventName, fn);
9163 if (typeof(this.listeners) == 'undefined' || typeof(this.listeners[eventName]) == 'undefined') {
9166 this.listeners[eventName].removeListener(fn, scope);
9171 * Removes all previous added listeners from this element
9172 * @return {Roo.Element} this
9174 removeAllListeners : function(){
9175 E.purgeElement(this.dom);
9176 this.listeners = {};
9180 relayEvent : function(eventName, observable){
9181 this.on(eventName, function(e){
9182 observable.fireEvent(eventName, e);
9188 * Set the opacity of the element
9189 * @param {Float} opacity The new opacity. 0 = transparent, .5 = 50% visibile, 1 = fully visible, etc
9190 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9191 * @return {Roo.Element} this
9193 setOpacity : function(opacity, animate){
9195 var s = this.dom.style;
9198 s.filter = (s.filter || '').replace(/alpha\([^\)]*\)/gi,"") +
9199 (opacity == 1 ? "" : "alpha(opacity=" + opacity * 100 + ")");
9201 s.opacity = opacity;
9204 this.anim({opacity: {to: opacity}}, this.preanim(arguments, 1), null, .35, 'easeIn');
9210 * Gets the left X coordinate
9211 * @param {Boolean} local True to get the local css position instead of page coordinate
9214 getLeft : function(local){
9218 return parseInt(this.getStyle("left"), 10) || 0;
9223 * Gets the right X coordinate of the element (element X position + element width)
9224 * @param {Boolean} local True to get the local css position instead of page coordinate
9227 getRight : function(local){
9229 return this.getX() + this.getWidth();
9231 return (this.getLeft(true) + this.getWidth()) || 0;
9236 * Gets the top Y coordinate
9237 * @param {Boolean} local True to get the local css position instead of page coordinate
9240 getTop : function(local) {
9244 return parseInt(this.getStyle("top"), 10) || 0;
9249 * Gets the bottom Y coordinate of the element (element Y position + element height)
9250 * @param {Boolean} local True to get the local css position instead of page coordinate
9253 getBottom : function(local){
9255 return this.getY() + this.getHeight();
9257 return (this.getTop(true) + this.getHeight()) || 0;
9262 * Initializes positioning on this element. If a desired position is not passed, it will make the
9263 * the element positioned relative IF it is not already positioned.
9264 * @param {String} pos (optional) Positioning to use "relative", "absolute" or "fixed"
9265 * @param {Number} zIndex (optional) The zIndex to apply
9266 * @param {Number} x (optional) Set the page X position
9267 * @param {Number} y (optional) Set the page Y position
9269 position : function(pos, zIndex, x, y){
9271 if(this.getStyle('position') == 'static'){
9272 this.setStyle('position', 'relative');
9275 this.setStyle("position", pos);
9278 this.setStyle("z-index", zIndex);
9280 if(x !== undefined && y !== undefined){
9282 }else if(x !== undefined){
9284 }else if(y !== undefined){
9290 * Clear positioning back to the default when the document was loaded
9291 * @param {String} value (optional) The value to use for the left,right,top,bottom, defaults to '' (empty string). You could use 'auto'.
9292 * @return {Roo.Element} this
9294 clearPositioning : function(value){
9302 "position" : "static"
9308 * Gets an object with all CSS positioning properties. Useful along with setPostioning to get
9309 * snapshot before performing an update and then restoring the element.
9312 getPositioning : function(){
9313 var l = this.getStyle("left");
9314 var t = this.getStyle("top");
9316 "position" : this.getStyle("position"),
9318 "right" : l ? "" : this.getStyle("right"),
9320 "bottom" : t ? "" : this.getStyle("bottom"),
9321 "z-index" : this.getStyle("z-index")
9326 * Gets the width of the border(s) for the specified side(s)
9327 * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
9328 * passing lr would get the border (l)eft width + the border (r)ight width.
9329 * @return {Number} The width of the sides passed added together
9331 getBorderWidth : function(side){
9332 return this.addStyles(side, El.borders);
9336 * Gets the width of the padding(s) for the specified side(s)
9337 * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
9338 * passing lr would get the padding (l)eft + the padding (r)ight.
9339 * @return {Number} The padding of the sides passed added together
9341 getPadding : function(side){
9342 return this.addStyles(side, El.paddings);
9346 * Set positioning with an object returned by getPositioning().
9347 * @param {Object} posCfg
9348 * @return {Roo.Element} this
9350 setPositioning : function(pc){
9351 this.applyStyles(pc);
9352 if(pc.right == "auto"){
9353 this.dom.style.right = "";
9355 if(pc.bottom == "auto"){
9356 this.dom.style.bottom = "";
9362 fixDisplay : function(){
9363 if(this.getStyle("display") == "none"){
9364 this.setStyle("visibility", "hidden");
9365 this.setStyle("display", this.originalDisplay); // first try reverting to default
9366 if(this.getStyle("display") == "none"){ // if that fails, default to block
9367 this.setStyle("display", "block");
9373 * Quick set left and top adding default units
9374 * @param {String} left The left CSS property value
9375 * @param {String} top The top CSS property value
9376 * @return {Roo.Element} this
9378 setLeftTop : function(left, top){
9379 this.dom.style.left = this.addUnits(left);
9380 this.dom.style.top = this.addUnits(top);
9385 * Move this element relative to its current position.
9386 * @param {String} direction Possible values are: "l","left" - "r","right" - "t","top","up" - "b","bottom","down".
9387 * @param {Number} distance How far to move the element in pixels
9388 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9389 * @return {Roo.Element} this
9391 move : function(direction, distance, animate){
9392 var xy = this.getXY();
9393 direction = direction.toLowerCase();
9397 this.moveTo(xy[0]-distance, xy[1], this.preanim(arguments, 2));
9401 this.moveTo(xy[0]+distance, xy[1], this.preanim(arguments, 2));
9406 this.moveTo(xy[0], xy[1]-distance, this.preanim(arguments, 2));
9411 this.moveTo(xy[0], xy[1]+distance, this.preanim(arguments, 2));
9418 * Store the current overflow setting and clip overflow on the element - use {@link #unclip} to remove
9419 * @return {Roo.Element} this
9422 if(!this.isClipped){
9423 this.isClipped = true;
9424 this.originalClip = {
9425 "o": this.getStyle("overflow"),
9426 "x": this.getStyle("overflow-x"),
9427 "y": this.getStyle("overflow-y")
9429 this.setStyle("overflow", "hidden");
9430 this.setStyle("overflow-x", "hidden");
9431 this.setStyle("overflow-y", "hidden");
9437 * Return clipping (overflow) to original clipping before clip() was called
9438 * @return {Roo.Element} this
9440 unclip : function(){
9442 this.isClipped = false;
9443 var o = this.originalClip;
9444 if(o.o){this.setStyle("overflow", o.o);}
9445 if(o.x){this.setStyle("overflow-x", o.x);}
9446 if(o.y){this.setStyle("overflow-y", o.y);}
9453 * Gets the x,y coordinates specified by the anchor position on the element.
9454 * @param {String} anchor (optional) The specified anchor position (defaults to "c"). See {@link #alignTo} for details on supported anchor positions.
9455 * @param {Object} size (optional) An object containing the size to use for calculating anchor position
9456 * {width: (target width), height: (target height)} (defaults to the element's current size)
9457 * @param {Boolean} local (optional) True to get the local (element top/left-relative) anchor position instead of page coordinates
9458 * @return {Array} [x, y] An array containing the element's x and y coordinates
9460 getAnchorXY : function(anchor, local, s){
9461 //Passing a different size is useful for pre-calculating anchors,
9462 //especially for anchored animations that change the el size.
9464 var w, h, vp = false;
9467 if(d == document.body || d == document){
9469 w = D.getViewWidth(); h = D.getViewHeight();
9471 w = this.getWidth(); h = this.getHeight();
9474 w = s.width; h = s.height;
9476 var x = 0, y = 0, r = Math.round;
9477 switch((anchor || "tl").toLowerCase()){
9519 var sc = this.getScroll();
9520 return [x + sc.left, y + sc.top];
9522 //Add the element's offset xy
9523 var o = this.getXY();
9524 return [x+o[0], y+o[1]];
9528 * Gets the x,y coordinates to align this element with another element. See {@link #alignTo} for more info on the
9529 * supported position values.
9530 * @param {String/HTMLElement/Roo.Element} element The element to align to.
9531 * @param {String} position The position to align to.
9532 * @param {Array} offsets (optional) Offset the positioning by [x, y]
9533 * @return {Array} [x, y]
9535 getAlignToXY : function(el, p, o)
9540 throw "Element.alignTo with an element that doesn't exist";
9542 var c = false; //constrain to viewport
9543 var p1 = "", p2 = "";
9550 }else if(p.indexOf("-") == -1){
9553 p = p.toLowerCase();
9554 var m = p.match(/^([a-z]+)-([a-z]+)(\?)?$/);
9556 throw "Element.alignTo with an invalid alignment " + p;
9558 p1 = m[1]; p2 = m[2]; c = !!m[3];
9560 //Subtract the aligned el's internal xy from the target's offset xy
9561 //plus custom offset to get the aligned el's new offset xy
9562 var a1 = this.getAnchorXY(p1, true);
9563 var a2 = el.getAnchorXY(p2, false);
9564 var x = a2[0] - a1[0] + o[0];
9565 var y = a2[1] - a1[1] + o[1];
9567 //constrain the aligned el to viewport if necessary
9568 var w = this.getWidth(), h = this.getHeight(), r = el.getRegion();
9569 // 5px of margin for ie
9570 var dw = D.getViewWidth()-5, dh = D.getViewHeight()-5;
9572 //If we are at a viewport boundary and the aligned el is anchored on a target border that is
9573 //perpendicular to the vp border, allow the aligned el to slide on that border,
9574 //otherwise swap the aligned el to the opposite border of the target.
9575 var p1y = p1.charAt(0), p1x = p1.charAt(p1.length-1);
9576 var p2y = p2.charAt(0), p2x = p2.charAt(p2.length-1);
9577 var swapY = ((p1y=="t" && p2y=="b") || (p1y=="b" && p2y=="t") );
9578 var swapX = ((p1x=="r" && p2x=="l") || (p1x=="l" && p2x=="r"));
9581 var scrollX = (doc.documentElement.scrollLeft || doc.body.scrollLeft || 0)+5;
9582 var scrollY = (doc.documentElement.scrollTop || doc.body.scrollTop || 0)+5;
9584 if((x+w) > dw + scrollX){
9585 x = swapX ? r.left-w : dw+scrollX-w;
9588 x = swapX ? r.right : scrollX;
9590 if((y+h) > dh + scrollY){
9591 y = swapY ? r.top-h : dh+scrollY-h;
9594 y = swapY ? r.bottom : scrollY;
9601 getConstrainToXY : function(){
9602 var os = {top:0, left:0, bottom:0, right: 0};
9604 return function(el, local, offsets, proposedXY){
9606 offsets = offsets ? Roo.applyIf(offsets, os) : os;
9608 var vw, vh, vx = 0, vy = 0;
9609 if(el.dom == document.body || el.dom == document){
9610 vw = Roo.lib.Dom.getViewWidth();
9611 vh = Roo.lib.Dom.getViewHeight();
9613 vw = el.dom.clientWidth;
9614 vh = el.dom.clientHeight;
9616 var vxy = el.getXY();
9622 var s = el.getScroll();
9624 vx += offsets.left + s.left;
9625 vy += offsets.top + s.top;
9627 vw -= offsets.right;
9628 vh -= offsets.bottom;
9633 var xy = proposedXY || (!local ? this.getXY() : [this.getLeft(true), this.getTop(true)]);
9634 var x = xy[0], y = xy[1];
9635 var w = this.dom.offsetWidth, h = this.dom.offsetHeight;
9637 // only move it if it needs it
9640 // first validate right/bottom
9649 // then make sure top/left isn't negative
9658 return moved ? [x, y] : false;
9663 adjustForConstraints : function(xy, parent, offsets){
9664 return this.getConstrainToXY(parent || document, false, offsets, xy) || xy;
9668 * Aligns this element with another element relative to the specified anchor points. If the other element is the
9669 * document it aligns it to the viewport.
9670 * The position parameter is optional, and can be specified in any one of the following formats:
9672 * <li><b>Blank</b>: Defaults to aligning the element's top-left corner to the target's bottom-left corner ("tl-bl").</li>
9673 * <li><b>One anchor (deprecated)</b>: The passed anchor position is used as the target element's anchor point.
9674 * The element being aligned will position its top-left corner (tl) to that point. <i>This method has been
9675 * deprecated in favor of the newer two anchor syntax below</i>.</li>
9676 * <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
9677 * element's anchor point, and the second value is used as the target's anchor point.</li>
9679 * In addition to the anchor points, the position parameter also supports the "?" character. If "?" is passed at the end of
9680 * the position string, the element will attempt to align as specified, but the position will be adjusted to constrain to
9681 * the viewport if necessary. Note that the element being aligned might be swapped to align to a different position than
9682 * that specified in order to enforce the viewport constraints.
9683 * Following are all of the supported anchor positions:
9686 ----- -----------------------------
9687 tl The top left corner (default)
9688 t The center of the top edge
9689 tr The top right corner
9690 l The center of the left edge
9691 c In the center of the element
9692 r The center of the right edge
9693 bl The bottom left corner
9694 b The center of the bottom edge
9695 br The bottom right corner
9699 // align el to other-el using the default positioning ("tl-bl", non-constrained)
9700 el.alignTo("other-el");
9702 // align the top left corner of el with the top right corner of other-el (constrained to viewport)
9703 el.alignTo("other-el", "tr?");
9705 // align the bottom right corner of el with the center left edge of other-el
9706 el.alignTo("other-el", "br-l?");
9708 // align the center of el with the bottom left corner of other-el and
9709 // adjust the x position by -6 pixels (and the y position by 0)
9710 el.alignTo("other-el", "c-bl", [-6, 0]);
9712 * @param {String/HTMLElement/Roo.Element} element The element to align to.
9713 * @param {String} position The position to align to.
9714 * @param {Array} offsets (optional) Offset the positioning by [x, y]
9715 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9716 * @return {Roo.Element} this
9718 alignTo : function(element, position, offsets, animate){
9719 var xy = this.getAlignToXY(element, position, offsets);
9720 this.setXY(xy, this.preanim(arguments, 3));
9725 * Anchors an element to another element and realigns it when the window is resized.
9726 * @param {String/HTMLElement/Roo.Element} element The element to align to.
9727 * @param {String} position The position to align to.
9728 * @param {Array} offsets (optional) Offset the positioning by [x, y]
9729 * @param {Boolean/Object} animate (optional) True for the default animation or a standard Element animation config object
9730 * @param {Boolean/Number} monitorScroll (optional) True to monitor body scroll and reposition. If this parameter
9731 * is a number, it is used as the buffer delay (defaults to 50ms).
9732 * @param {Function} callback The function to call after the animation finishes
9733 * @return {Roo.Element} this
9735 anchorTo : function(el, alignment, offsets, animate, monitorScroll, callback){
9736 var action = function(){
9737 this.alignTo(el, alignment, offsets, animate);
9738 Roo.callback(callback, this);
9740 Roo.EventManager.onWindowResize(action, this);
9741 var tm = typeof monitorScroll;
9742 if(tm != 'undefined'){
9743 Roo.EventManager.on(window, 'scroll', action, this,
9744 {buffer: tm == 'number' ? monitorScroll : 50});
9746 action.call(this); // align immediately
9750 * Clears any opacity settings from this element. Required in some cases for IE.
9751 * @return {Roo.Element} this
9753 clearOpacity : function(){
9754 if (window.ActiveXObject) {
9755 if(typeof this.dom.style.filter == 'string' && (/alpha/i).test(this.dom.style.filter)){
9756 this.dom.style.filter = "";
9759 this.dom.style.opacity = "";
9760 this.dom.style["-moz-opacity"] = "";
9761 this.dom.style["-khtml-opacity"] = "";
9767 * Hide this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
9768 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9769 * @return {Roo.Element} this
9771 hide : function(animate){
9772 this.setVisible(false, this.preanim(arguments, 0));
9777 * Show this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
9778 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9779 * @return {Roo.Element} this
9781 show : function(animate){
9782 this.setVisible(true, this.preanim(arguments, 0));
9787 * @private Test if size has a unit, otherwise appends the default
9789 addUnits : function(size){
9790 return Roo.Element.addUnits(size, this.defaultUnit);
9794 * Temporarily enables offsets (width,height,x,y) for an element with display:none, use endMeasure() when done.
9795 * @return {Roo.Element} this
9797 beginMeasure : function(){
9799 if(el.offsetWidth || el.offsetHeight){
9800 return this; // offsets work already
9803 var p = this.dom, b = document.body; // start with this element
9804 while((!el.offsetWidth && !el.offsetHeight) && p && p.tagName && p != b){
9805 var pe = Roo.get(p);
9806 if(pe.getStyle('display') == 'none'){
9807 changed.push({el: p, visibility: pe.getStyle("visibility")});
9808 p.style.visibility = "hidden";
9809 p.style.display = "block";
9813 this._measureChanged = changed;
9819 * Restores displays to before beginMeasure was called
9820 * @return {Roo.Element} this
9822 endMeasure : function(){
9823 var changed = this._measureChanged;
9825 for(var i = 0, len = changed.length; i < len; i++) {
9827 r.el.style.visibility = r.visibility;
9828 r.el.style.display = "none";
9830 this._measureChanged = null;
9836 * Update the innerHTML of this element, optionally searching for and processing scripts
9837 * @param {String} html The new HTML
9838 * @param {Boolean} loadScripts (optional) true to look for and process scripts
9839 * @param {Function} callback For async script loading you can be noticed when the update completes
9840 * @return {Roo.Element} this
9842 update : function(html, loadScripts, callback){
9843 if(typeof html == "undefined"){
9846 if(loadScripts !== true){
9847 this.dom.innerHTML = html;
9848 if(typeof callback == "function"){
9856 html += '<span id="' + id + '"></span>';
9858 E.onAvailable(id, function(){
9859 var hd = document.getElementsByTagName("head")[0];
9860 var re = /(?:<script([^>]*)?>)((\n|\r|.)*?)(?:<\/script>)/ig;
9861 var srcRe = /\ssrc=([\'\"])(.*?)\1/i;
9862 var typeRe = /\stype=([\'\"])(.*?)\1/i;
9865 while(match = re.exec(html)){
9866 var attrs = match[1];
9867 var srcMatch = attrs ? attrs.match(srcRe) : false;
9868 if(srcMatch && srcMatch[2]){
9869 var s = document.createElement("script");
9870 s.src = srcMatch[2];
9871 var typeMatch = attrs.match(typeRe);
9872 if(typeMatch && typeMatch[2]){
9873 s.type = typeMatch[2];
9876 }else if(match[2] && match[2].length > 0){
9877 if(window.execScript) {
9878 window.execScript(match[2]);
9886 window.eval(match[2]);
9890 var el = document.getElementById(id);
9891 if(el){el.parentNode.removeChild(el);}
9892 if(typeof callback == "function"){
9896 dom.innerHTML = html.replace(/(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig, "");
9901 * Direct access to the UpdateManager update() method (takes the same parameters).
9902 * @param {String/Function} url The url for this request or a function to call to get the url
9903 * @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}
9904 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
9905 * @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.
9906 * @return {Roo.Element} this
9909 var um = this.getUpdateManager();
9910 um.update.apply(um, arguments);
9915 * Gets this element's UpdateManager
9916 * @return {Roo.UpdateManager} The UpdateManager
9918 getUpdateManager : function(){
9919 if(!this.updateManager){
9920 this.updateManager = new Roo.UpdateManager(this);
9922 return this.updateManager;
9926 * Disables text selection for this element (normalized across browsers)
9927 * @return {Roo.Element} this
9929 unselectable : function(){
9930 this.dom.unselectable = "on";
9931 this.swallowEvent("selectstart", true);
9932 this.applyStyles("-moz-user-select:none;-khtml-user-select:none;");
9933 this.addClass("x-unselectable");
9938 * Calculates the x, y to center this element on the screen
9939 * @return {Array} The x, y values [x, y]
9941 getCenterXY : function(){
9942 return this.getAlignToXY(document, 'c-c');
9946 * Centers the Element in either the viewport, or another Element.
9947 * @param {String/HTMLElement/Roo.Element} centerIn (optional) The element in which to center the element.
9949 center : function(centerIn){
9950 this.alignTo(centerIn || document, 'c-c');
9955 * Tests various css rules/browsers to determine if this element uses a border box
9958 isBorderBox : function(){
9959 return noBoxAdjust[this.dom.tagName.toLowerCase()] || Roo.isBorderBox;
9963 * Return a box {x, y, width, height} that can be used to set another elements
9964 * size/location to match this element.
9965 * @param {Boolean} contentBox (optional) If true a box for the content of the element is returned.
9966 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page x/y.
9967 * @return {Object} box An object in the format {x, y, width, height}
9969 getBox : function(contentBox, local){
9974 var left = parseInt(this.getStyle("left"), 10) || 0;
9975 var top = parseInt(this.getStyle("top"), 10) || 0;
9978 var el = this.dom, w = el.offsetWidth, h = el.offsetHeight, bx;
9980 bx = {x: xy[0], y: xy[1], 0: xy[0], 1: xy[1], width: w, height: h};
9982 var l = this.getBorderWidth("l")+this.getPadding("l");
9983 var r = this.getBorderWidth("r")+this.getPadding("r");
9984 var t = this.getBorderWidth("t")+this.getPadding("t");
9985 var b = this.getBorderWidth("b")+this.getPadding("b");
9986 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)};
9988 bx.right = bx.x + bx.width;
9989 bx.bottom = bx.y + bx.height;
9994 * Returns the sum width of the padding and borders for the passed "sides". See getBorderWidth()
9995 for more information about the sides.
9996 * @param {String} sides
9999 getFrameWidth : function(sides, onlyContentBox){
10000 return onlyContentBox && Roo.isBorderBox ? 0 : (this.getPadding(sides) + this.getBorderWidth(sides));
10004 * 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.
10005 * @param {Object} box The box to fill {x, y, width, height}
10006 * @param {Boolean} adjust (optional) Whether to adjust for box-model issues automatically
10007 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
10008 * @return {Roo.Element} this
10010 setBox : function(box, adjust, animate){
10011 var w = box.width, h = box.height;
10012 if((adjust && !this.autoBoxAdjust) && !this.isBorderBox()){
10013 w -= (this.getBorderWidth("lr") + this.getPadding("lr"));
10014 h -= (this.getBorderWidth("tb") + this.getPadding("tb"));
10016 this.setBounds(box.x, box.y, w, h, this.preanim(arguments, 2));
10021 * Forces the browser to repaint this element
10022 * @return {Roo.Element} this
10024 repaint : function(){
10025 var dom = this.dom;
10026 this.addClass("x-repaint");
10027 setTimeout(function(){
10028 Roo.get(dom).removeClass("x-repaint");
10034 * Returns an object with properties top, left, right and bottom representing the margins of this element unless sides is passed,
10035 * then it returns the calculated width of the sides (see getPadding)
10036 * @param {String} sides (optional) Any combination of l, r, t, b to get the sum of those sides
10037 * @return {Object/Number}
10039 getMargins : function(side){
10042 top: parseInt(this.getStyle("margin-top"), 10) || 0,
10043 left: parseInt(this.getStyle("margin-left"), 10) || 0,
10044 bottom: parseInt(this.getStyle("margin-bottom"), 10) || 0,
10045 right: parseInt(this.getStyle("margin-right"), 10) || 0
10048 return this.addStyles(side, El.margins);
10053 addStyles : function(sides, styles){
10055 for(var i = 0, len = sides.length; i < len; i++){
10056 v = this.getStyle(styles[sides.charAt(i)]);
10058 w = parseInt(v, 10);
10066 * Creates a proxy element of this element
10067 * @param {String/Object} config The class name of the proxy element or a DomHelper config object
10068 * @param {String/HTMLElement} renderTo (optional) The element or element id to render the proxy to (defaults to document.body)
10069 * @param {Boolean} matchBox (optional) True to align and size the proxy to this element now (defaults to false)
10070 * @return {Roo.Element} The new proxy element
10072 createProxy : function(config, renderTo, matchBox){
10074 renderTo = Roo.getDom(renderTo);
10076 renderTo = document.body;
10078 config = typeof config == "object" ?
10079 config : {tag : "div", cls: config};
10080 var proxy = Roo.DomHelper.append(renderTo, config, true);
10082 proxy.setBox(this.getBox());
10088 * Puts a mask over this element to disable user interaction. Requires core.css.
10089 * This method can only be applied to elements which accept child nodes.
10090 * @param {String} msg (optional) A message to display in the mask
10091 * @param {String} msgCls (optional) A css class to apply to the msg element - use no-spinner to hide the spinner on bootstrap
10092 * @return {Element} The mask element
10094 mask : function(msg, msgCls)
10096 if(this.getStyle("position") == "static" && this.dom.tagName !== 'BODY'){
10097 this.setStyle("position", "relative");
10100 this._mask = Roo.DomHelper.append(this.dom, {cls:"roo-el-mask"}, true);
10103 this.addClass("x-masked");
10104 this._mask.setDisplayed(true);
10108 var dom = this.dom;
10109 while (dom && dom.style) {
10110 if (!isNaN(parseInt(dom.style.zIndex))) {
10111 z = Math.max(z, parseInt(dom.style.zIndex));
10113 dom = dom.parentNode;
10115 // if we are masking the body - then it hides everything..
10116 if (this.dom == document.body) {
10118 this._mask.setWidth(Roo.lib.Dom.getDocumentWidth());
10119 this._mask.setHeight(Roo.lib.Dom.getDocumentHeight());
10122 if(typeof msg == 'string'){
10123 if(!this._maskMsg){
10124 this._maskMsg = Roo.DomHelper.append(this.dom, {
10125 cls: "roo-el-mask-msg",
10129 cls: 'fa fa-spinner fa-spin'
10137 var mm = this._maskMsg;
10138 mm.dom.className = msgCls ? "roo-el-mask-msg " + msgCls : "roo-el-mask-msg";
10139 if (mm.dom.lastChild) { // weird IE issue?
10140 mm.dom.lastChild.innerHTML = msg;
10142 mm.setDisplayed(true);
10144 mm.setStyle('z-index', z + 102);
10146 if(Roo.isIE && !(Roo.isIE7 && Roo.isStrict) && this.getStyle('height') == 'auto'){ // ie will not expand full height automatically
10147 this._mask.setHeight(this.getHeight());
10149 this._mask.setStyle('z-index', z + 100);
10155 * Removes a previously applied mask. If removeEl is true the mask overlay is destroyed, otherwise
10156 * it is cached for reuse.
10158 unmask : function(removeEl){
10160 if(removeEl === true){
10161 this._mask.remove();
10164 this._maskMsg.remove();
10165 delete this._maskMsg;
10168 this._mask.setDisplayed(false);
10170 this._maskMsg.setDisplayed(false);
10174 this.removeClass("x-masked");
10178 * Returns true if this element is masked
10179 * @return {Boolean}
10181 isMasked : function(){
10182 return this._mask && this._mask.isVisible();
10186 * Creates an iframe shim for this element to keep selects and other windowed objects from
10188 * @return {Roo.Element} The new shim element
10190 createShim : function(){
10191 var el = document.createElement('iframe');
10192 el.frameBorder = 'no';
10193 el.className = 'roo-shim';
10194 if(Roo.isIE && Roo.isSecure){
10195 el.src = Roo.SSL_SECURE_URL;
10197 var shim = Roo.get(this.dom.parentNode.insertBefore(el, this.dom));
10198 shim.autoBoxAdjust = false;
10203 * Removes this element from the DOM and deletes it from the cache
10205 remove : function(){
10206 if(this.dom.parentNode){
10207 this.dom.parentNode.removeChild(this.dom);
10209 delete El.cache[this.dom.id];
10213 * Sets up event handlers to add and remove a css class when the mouse is over this element
10214 * @param {String} className
10215 * @param {Boolean} preventFlicker (optional) If set to true, it prevents flickering by filtering
10216 * mouseout events for children elements
10217 * @return {Roo.Element} this
10219 addClassOnOver : function(className, preventFlicker){
10220 this.on("mouseover", function(){
10221 Roo.fly(this, '_internal').addClass(className);
10223 var removeFn = function(e){
10224 if(preventFlicker !== true || !e.within(this, true)){
10225 Roo.fly(this, '_internal').removeClass(className);
10228 this.on("mouseout", removeFn, this.dom);
10233 * Sets up event handlers to add and remove a css class when this element has the focus
10234 * @param {String} className
10235 * @return {Roo.Element} this
10237 addClassOnFocus : function(className){
10238 this.on("focus", function(){
10239 Roo.fly(this, '_internal').addClass(className);
10241 this.on("blur", function(){
10242 Roo.fly(this, '_internal').removeClass(className);
10247 * 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)
10248 * @param {String} className
10249 * @return {Roo.Element} this
10251 addClassOnClick : function(className){
10252 var dom = this.dom;
10253 this.on("mousedown", function(){
10254 Roo.fly(dom, '_internal').addClass(className);
10255 var d = Roo.get(document);
10256 var fn = function(){
10257 Roo.fly(dom, '_internal').removeClass(className);
10258 d.removeListener("mouseup", fn);
10260 d.on("mouseup", fn);
10266 * Stops the specified event from bubbling and optionally prevents the default action
10267 * @param {String} eventName
10268 * @param {Boolean} preventDefault (optional) true to prevent the default action too
10269 * @return {Roo.Element} this
10271 swallowEvent : function(eventName, preventDefault){
10272 var fn = function(e){
10273 e.stopPropagation();
10274 if(preventDefault){
10275 e.preventDefault();
10278 if(eventName instanceof Array){
10279 for(var i = 0, len = eventName.length; i < len; i++){
10280 this.on(eventName[i], fn);
10284 this.on(eventName, fn);
10291 fitToParentDelegate : Roo.emptyFn, // keep a reference to the fitToParent delegate
10294 * Sizes this element to its parent element's dimensions performing
10295 * neccessary box adjustments.
10296 * @param {Boolean} monitorResize (optional) If true maintains the fit when the browser window is resized.
10297 * @param {String/HTMLElment/Element} targetParent (optional) The target parent, default to the parentNode.
10298 * @return {Roo.Element} this
10300 fitToParent : function(monitorResize, targetParent) {
10301 Roo.EventManager.removeResizeListener(this.fitToParentDelegate); // always remove previous fitToParent delegate from onWindowResize
10302 this.fitToParentDelegate = Roo.emptyFn; // remove reference to previous delegate
10303 if (monitorResize === true && !this.dom.parentNode) { // check if this Element still exists
10306 var p = Roo.get(targetParent || this.dom.parentNode);
10307 this.setSize(p.getComputedWidth() - p.getFrameWidth('lr'), p.getComputedHeight() - p.getFrameWidth('tb'));
10308 if (monitorResize === true) {
10309 this.fitToParentDelegate = this.fitToParent.createDelegate(this, [true, targetParent]);
10310 Roo.EventManager.onWindowResize(this.fitToParentDelegate);
10316 * Gets the next sibling, skipping text nodes
10317 * @return {HTMLElement} The next sibling or null
10319 getNextSibling : function(){
10320 var n = this.dom.nextSibling;
10321 while(n && n.nodeType != 1){
10328 * Gets the previous sibling, skipping text nodes
10329 * @return {HTMLElement} The previous sibling or null
10331 getPrevSibling : function(){
10332 var n = this.dom.previousSibling;
10333 while(n && n.nodeType != 1){
10334 n = n.previousSibling;
10341 * Appends the passed element(s) to this element
10342 * @param {String/HTMLElement/Array/Element/CompositeElement} el
10343 * @return {Roo.Element} this
10345 appendChild: function(el){
10352 * Creates the passed DomHelper config and appends it to this element or optionally inserts it before the passed child element.
10353 * @param {Object} config DomHelper element config object. If no tag is specified (e.g., {tag:'input'}) then a div will be
10354 * automatically generated with the specified attributes.
10355 * @param {HTMLElement} insertBefore (optional) a child element of this element
10356 * @param {Boolean} returnDom (optional) true to return the dom node instead of creating an Element
10357 * @return {Roo.Element} The new child element
10359 createChild: function(config, insertBefore, returnDom){
10360 config = config || {tag:'div'};
10362 return Roo.DomHelper.insertBefore(insertBefore, config, returnDom !== true);
10364 return Roo.DomHelper[!this.dom.firstChild ? 'overwrite' : 'append'](this.dom, config, returnDom !== true);
10368 * Appends this element to the passed element
10369 * @param {String/HTMLElement/Element} el The new parent element
10370 * @return {Roo.Element} this
10372 appendTo: function(el){
10373 el = Roo.getDom(el);
10374 el.appendChild(this.dom);
10379 * Inserts this element before the passed element in the DOM
10380 * @param {String/HTMLElement/Element} el The element to insert before
10381 * @return {Roo.Element} this
10383 insertBefore: function(el){
10384 el = Roo.getDom(el);
10385 el.parentNode.insertBefore(this.dom, el);
10390 * Inserts this element after the passed element in the DOM
10391 * @param {String/HTMLElement/Element} el The element to insert after
10392 * @return {Roo.Element} this
10394 insertAfter: function(el){
10395 el = Roo.getDom(el);
10396 el.parentNode.insertBefore(this.dom, el.nextSibling);
10401 * Inserts (or creates) an element (or DomHelper config) as the first child of the this element
10402 * @param {String/HTMLElement/Element/Object} el The id or element to insert or a DomHelper config to create and insert
10403 * @return {Roo.Element} The new child
10405 insertFirst: function(el, returnDom){
10407 if(typeof el == 'object' && !el.nodeType){ // dh config
10408 return this.createChild(el, this.dom.firstChild, returnDom);
10410 el = Roo.getDom(el);
10411 this.dom.insertBefore(el, this.dom.firstChild);
10412 return !returnDom ? Roo.get(el) : el;
10417 * Inserts (or creates) the passed element (or DomHelper config) as a sibling of this element
10418 * @param {String/HTMLElement/Element/Object} el The id or element to insert or a DomHelper config to create and insert
10419 * @param {String} where (optional) 'before' or 'after' defaults to before
10420 * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Roo.Element
10421 * @return {Roo.Element} the inserted Element
10423 insertSibling: function(el, where, returnDom){
10424 where = where ? where.toLowerCase() : 'before';
10426 var rt, refNode = where == 'before' ? this.dom : this.dom.nextSibling;
10428 if(typeof el == 'object' && !el.nodeType){ // dh config
10429 if(where == 'after' && !this.dom.nextSibling){
10430 rt = Roo.DomHelper.append(this.dom.parentNode, el, !returnDom);
10432 rt = Roo.DomHelper[where == 'after' ? 'insertAfter' : 'insertBefore'](this.dom, el, !returnDom);
10436 rt = this.dom.parentNode.insertBefore(Roo.getDom(el),
10437 where == 'before' ? this.dom : this.dom.nextSibling);
10446 * Creates and wraps this element with another element
10447 * @param {Object} config (optional) DomHelper element config object for the wrapper element or null for an empty div
10448 * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Roo.Element
10449 * @return {HTMLElement/Element} The newly created wrapper element
10451 wrap: function(config, returnDom){
10453 config = {tag: "div"};
10455 var newEl = Roo.DomHelper.insertBefore(this.dom, config, !returnDom);
10456 newEl.dom ? newEl.dom.appendChild(this.dom) : newEl.appendChild(this.dom);
10461 * Replaces the passed element with this element
10462 * @param {String/HTMLElement/Element} el The element to replace
10463 * @return {Roo.Element} this
10465 replace: function(el){
10467 this.insertBefore(el);
10473 * Inserts an html fragment into this element
10474 * @param {String} where Where to insert the html in relation to the this element - beforeBegin, afterBegin, beforeEnd, afterEnd.
10475 * @param {String} html The HTML fragment
10476 * @param {Boolean} returnEl True to return an Roo.Element
10477 * @return {HTMLElement/Roo.Element} The inserted node (or nearest related if more than 1 inserted)
10479 insertHtml : function(where, html, returnEl){
10480 var el = Roo.DomHelper.insertHtml(where, this.dom, html);
10481 return returnEl ? Roo.get(el) : el;
10485 * Sets the passed attributes as attributes of this element (a style attribute can be a string, object or function)
10486 * @param {Object} o The object with the attributes
10487 * @param {Boolean} useSet (optional) false to override the default setAttribute to use expandos.
10488 * @return {Roo.Element} this
10490 set : function(o, useSet){
10492 useSet = typeof useSet == 'undefined' ? (el.setAttribute ? true : false) : useSet;
10493 for(var attr in o){
10494 if(attr == "style" || typeof o[attr] == "function") { continue; }
10496 el.className = o["cls"];
10499 el.setAttribute(attr, o[attr]);
10501 el[attr] = o[attr];
10506 Roo.DomHelper.applyStyles(el, o.style);
10512 * Convenience method for constructing a KeyMap
10513 * @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:
10514 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
10515 * @param {Function} fn The function to call
10516 * @param {Object} scope (optional) The scope of the function
10517 * @return {Roo.KeyMap} The KeyMap created
10519 addKeyListener : function(key, fn, scope){
10521 if(typeof key != "object" || key instanceof Array){
10537 return new Roo.KeyMap(this, config);
10541 * Creates a KeyMap for this element
10542 * @param {Object} config The KeyMap config. See {@link Roo.KeyMap} for more details
10543 * @return {Roo.KeyMap} The KeyMap created
10545 addKeyMap : function(config){
10546 return new Roo.KeyMap(this, config);
10550 * Returns true if this element is scrollable.
10551 * @return {Boolean}
10553 isScrollable : function(){
10554 var dom = this.dom;
10555 return dom.scrollHeight > dom.clientHeight || dom.scrollWidth > dom.clientWidth;
10559 * 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().
10560 * @param {String} side Either "left" for scrollLeft values or "top" for scrollTop values.
10561 * @param {Number} value The new scroll value
10562 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
10563 * @return {Element} this
10566 scrollTo : function(side, value, animate){
10567 var prop = side.toLowerCase() == "left" ? "scrollLeft" : "scrollTop";
10568 if(!animate || !A){
10569 this.dom[prop] = value;
10571 var to = prop == "scrollLeft" ? [value, this.dom.scrollTop] : [this.dom.scrollLeft, value];
10572 this.anim({scroll: {"to": to}}, this.preanim(arguments, 2), 'scroll');
10578 * Scrolls this element the specified direction. Does bounds checking to make sure the scroll is
10579 * within this element's scrollable range.
10580 * @param {String} direction Possible values are: "l","left" - "r","right" - "t","top","up" - "b","bottom","down".
10581 * @param {Number} distance How far to scroll the element in pixels
10582 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
10583 * @return {Boolean} Returns true if a scroll was triggered or false if the element
10584 * was scrolled as far as it could go.
10586 scroll : function(direction, distance, animate){
10587 if(!this.isScrollable()){
10591 var l = el.scrollLeft, t = el.scrollTop;
10592 var w = el.scrollWidth, h = el.scrollHeight;
10593 var cw = el.clientWidth, ch = el.clientHeight;
10594 direction = direction.toLowerCase();
10595 var scrolled = false;
10596 var a = this.preanim(arguments, 2);
10601 var v = Math.min(l + distance, w-cw);
10602 this.scrollTo("left", v, a);
10609 var v = Math.max(l - distance, 0);
10610 this.scrollTo("left", v, a);
10618 var v = Math.max(t - distance, 0);
10619 this.scrollTo("top", v, a);
10627 var v = Math.min(t + distance, h-ch);
10628 this.scrollTo("top", v, a);
10637 * Translates the passed page coordinates into left/top css values for this element
10638 * @param {Number/Array} x The page x or an array containing [x, y]
10639 * @param {Number} y The page y
10640 * @return {Object} An object with left and top properties. e.g. {left: (value), top: (value)}
10642 translatePoints : function(x, y){
10643 if(typeof x == 'object' || x instanceof Array){
10644 y = x[1]; x = x[0];
10646 var p = this.getStyle('position');
10647 var o = this.getXY();
10649 var l = parseInt(this.getStyle('left'), 10);
10650 var t = parseInt(this.getStyle('top'), 10);
10653 l = (p == "relative") ? 0 : this.dom.offsetLeft;
10656 t = (p == "relative") ? 0 : this.dom.offsetTop;
10659 return {left: (x - o[0] + l), top: (y - o[1] + t)};
10663 * Returns the current scroll position of the element.
10664 * @return {Object} An object containing the scroll position in the format {left: (scrollLeft), top: (scrollTop)}
10666 getScroll : function(){
10667 var d = this.dom, doc = document;
10668 if(d == doc || d == doc.body){
10669 var l = window.pageXOffset || doc.documentElement.scrollLeft || doc.body.scrollLeft || 0;
10670 var t = window.pageYOffset || doc.documentElement.scrollTop || doc.body.scrollTop || 0;
10671 return {left: l, top: t};
10673 return {left: d.scrollLeft, top: d.scrollTop};
10678 * Return the CSS color for the specified CSS attribute. rgb, 3 digit (like #fff) and valid values
10679 * are convert to standard 6 digit hex color.
10680 * @param {String} attr The css attribute
10681 * @param {String} defaultValue The default value to use when a valid color isn't found
10682 * @param {String} prefix (optional) defaults to #. Use an empty string when working with
10685 getColor : function(attr, defaultValue, prefix){
10686 var v = this.getStyle(attr);
10687 if(!v || v == "transparent" || v == "inherit") {
10688 return defaultValue;
10690 var color = typeof prefix == "undefined" ? "#" : prefix;
10691 if(v.substr(0, 4) == "rgb("){
10692 var rvs = v.slice(4, v.length -1).split(",");
10693 for(var i = 0; i < 3; i++){
10694 var h = parseInt(rvs[i]).toString(16);
10701 if(v.substr(0, 1) == "#"){
10702 if(v.length == 4) {
10703 for(var i = 1; i < 4; i++){
10704 var c = v.charAt(i);
10707 }else if(v.length == 7){
10708 color += v.substr(1);
10712 return(color.length > 5 ? color.toLowerCase() : defaultValue);
10716 * Wraps the specified element with a special markup/CSS block that renders by default as a gray container with a
10717 * gradient background, rounded corners and a 4-way shadow.
10718 * @param {String} class (optional) A base CSS class to apply to the containing wrapper element (defaults to 'x-box').
10719 * Note that there are a number of CSS rules that are dependent on this name to make the overall effect work,
10720 * so if you supply an alternate base class, make sure you also supply all of the necessary rules.
10721 * @return {Roo.Element} this
10723 boxWrap : function(cls){
10724 cls = cls || 'x-box';
10725 var el = Roo.get(this.insertHtml('beforeBegin', String.format('<div class="{0}">'+El.boxMarkup+'</div>', cls)));
10726 el.child('.'+cls+'-mc').dom.appendChild(this.dom);
10731 * Returns the value of a namespaced attribute from the element's underlying DOM node.
10732 * @param {String} namespace The namespace in which to look for the attribute
10733 * @param {String} name The attribute name
10734 * @return {String} The attribute value
10736 getAttributeNS : Roo.isIE ? function(ns, name){
10738 var type = typeof d[ns+":"+name];
10739 if(type != 'undefined' && type != 'unknown'){
10740 return d[ns+":"+name];
10743 } : function(ns, name){
10745 return d.getAttributeNS(ns, name) || d.getAttribute(ns+":"+name) || d.getAttribute(name) || d[name];
10750 * Sets or Returns the value the dom attribute value
10751 * @param {String|Object} name The attribute name (or object to set multiple attributes)
10752 * @param {String} value (optional) The value to set the attribute to
10753 * @return {String} The attribute value
10755 attr : function(name){
10756 if (arguments.length > 1) {
10757 this.dom.setAttribute(name, arguments[1]);
10758 return arguments[1];
10760 if (typeof(name) == 'object') {
10761 for(var i in name) {
10762 this.attr(i, name[i]);
10768 if (!this.dom.hasAttribute(name)) {
10771 return this.dom.getAttribute(name);
10778 var ep = El.prototype;
10781 * Appends an event handler (Shorthand for addListener)
10782 * @param {String} eventName The type of event to append
10783 * @param {Function} fn The method the event invokes
10784 * @param {Object} scope (optional) The scope (this object) of the fn
10785 * @param {Object} options (optional)An object with standard {@link Roo.EventManager#addListener} options
10788 ep.on = ep.addListener;
10789 // backwards compat
10790 ep.mon = ep.addListener;
10793 * Removes an event handler from this element (shorthand for removeListener)
10794 * @param {String} eventName the type of event to remove
10795 * @param {Function} fn the method the event invokes
10796 * @return {Roo.Element} this
10799 ep.un = ep.removeListener;
10802 * true to automatically adjust width and height settings for box-model issues (default to true)
10804 ep.autoBoxAdjust = true;
10807 El.unitPattern = /\d+(px|em|%|en|ex|pt|in|cm|mm|pc)$/i;
10810 El.addUnits = function(v, defaultUnit){
10811 if(v === "" || v == "auto"){
10814 if(v === undefined){
10817 if(typeof v == "number" || !El.unitPattern.test(v)){
10818 return v + (defaultUnit || 'px');
10823 // special markup used throughout Roo when box wrapping elements
10824 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>';
10826 * Visibility mode constant - Use visibility to hide element
10832 * Visibility mode constant - Use display to hide element
10838 El.borders = {l: "border-left-width", r: "border-right-width", t: "border-top-width", b: "border-bottom-width"};
10839 El.paddings = {l: "padding-left", r: "padding-right", t: "padding-top", b: "padding-bottom"};
10840 El.margins = {l: "margin-left", r: "margin-right", t: "margin-top", b: "margin-bottom"};
10852 * Static method to retrieve Element objects. Uses simple caching to consistently return the same object.
10853 * Automatically fixes if an object was recreated with the same id via AJAX or DOM.
10854 * @param {String/HTMLElement/Element} el The id of the node, a DOM Node or an existing Element.
10855 * @return {Element} The Element object
10858 El.get = function(el){
10860 if(!el){ return null; }
10861 if(typeof el == "string"){ // element id
10862 if(!(elm = document.getElementById(el))){
10865 if(ex = El.cache[el]){
10868 ex = El.cache[el] = new El(elm);
10871 }else if(el.tagName){ // dom element
10875 if(ex = El.cache[id]){
10878 ex = El.cache[id] = new El(el);
10881 }else if(el instanceof El){
10883 el.dom = document.getElementById(el.id) || el.dom; // refresh dom element in case no longer valid,
10884 // catch case where it hasn't been appended
10885 El.cache[el.id] = el; // in case it was created directly with Element(), let's cache it
10888 }else if(el.isComposite){
10890 }else if(el instanceof Array){
10891 return El.select(el);
10892 }else if(el == document){
10893 // create a bogus element object representing the document object
10895 var f = function(){};
10896 f.prototype = El.prototype;
10898 docEl.dom = document;
10906 El.uncache = function(el){
10907 for(var i = 0, a = arguments, len = a.length; i < len; i++) {
10909 delete El.cache[a[i].id || a[i]];
10915 // Garbage collection - uncache elements/purge listeners on orphaned elements
10916 // so we don't hold a reference and cause the browser to retain them
10917 El.garbageCollect = function(){
10918 if(!Roo.enableGarbageCollector){
10919 clearInterval(El.collectorThread);
10922 for(var eid in El.cache){
10923 var el = El.cache[eid], d = el.dom;
10924 // -------------------------------------------------------
10925 // Determining what is garbage:
10926 // -------------------------------------------------------
10928 // dom node is null, definitely garbage
10929 // -------------------------------------------------------
10931 // no parentNode == direct orphan, definitely garbage
10932 // -------------------------------------------------------
10933 // !d.offsetParent && !document.getElementById(eid)
10934 // display none elements have no offsetParent so we will
10935 // also try to look it up by it's id. However, check
10936 // offsetParent first so we don't do unneeded lookups.
10937 // This enables collection of elements that are not orphans
10938 // directly, but somewhere up the line they have an orphan
10940 // -------------------------------------------------------
10941 if(!d || !d.parentNode || (!d.offsetParent && !document.getElementById(eid))){
10942 delete El.cache[eid];
10943 if(d && Roo.enableListenerCollection){
10949 El.collectorThreadId = setInterval(El.garbageCollect, 30000);
10953 El.Flyweight = function(dom){
10956 El.Flyweight.prototype = El.prototype;
10958 El._flyweights = {};
10960 * Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
10961 * the dom node can be overwritten by other code.
10962 * @param {String/HTMLElement} el The dom node or id
10963 * @param {String} named (optional) Allows for creation of named reusable flyweights to
10964 * prevent conflicts (e.g. internally Roo uses "_internal")
10966 * @return {Element} The shared Element object
10968 El.fly = function(el, named){
10969 named = named || '_global';
10970 el = Roo.getDom(el);
10974 if(!El._flyweights[named]){
10975 El._flyweights[named] = new El.Flyweight();
10977 El._flyweights[named].dom = el;
10978 return El._flyweights[named];
10982 * Static method to retrieve Element objects. Uses simple caching to consistently return the same object.
10983 * Automatically fixes if an object was recreated with the same id via AJAX or DOM.
10984 * Shorthand of {@link Roo.Element#get}
10985 * @param {String/HTMLElement/Element} el The id of the node, a DOM Node or an existing Element.
10986 * @return {Element} The Element object
10992 * Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
10993 * the dom node can be overwritten by other code.
10994 * Shorthand of {@link Roo.Element#fly}
10995 * @param {String/HTMLElement} el The dom node or id
10996 * @param {String} named (optional) Allows for creation of named reusable flyweights to
10997 * prevent conflicts (e.g. internally Roo uses "_internal")
10999 * @return {Element} The shared Element object
11005 // speedy lookup for elements never to box adjust
11006 var noBoxAdjust = Roo.isStrict ? {
11009 input:1, select:1, textarea:1
11011 if(Roo.isIE || Roo.isGecko){
11012 noBoxAdjust['button'] = 1;
11016 Roo.EventManager.on(window, 'unload', function(){
11018 delete El._flyweights;
11026 Roo.Element.selectorFunction = Roo.DomQuery.select;
11029 Roo.Element.select = function(selector, unique, root){
11031 if(typeof selector == "string"){
11032 els = Roo.Element.selectorFunction(selector, root);
11033 }else if(selector.length !== undefined){
11036 throw "Invalid selector";
11038 if(unique === true){
11039 return new Roo.CompositeElement(els);
11041 return new Roo.CompositeElementLite(els);
11045 * Selects elements based on the passed CSS selector to enable working on them as 1.
11046 * @param {String/Array} selector The CSS selector or an array of elements
11047 * @param {Boolean} unique (optional) true to create a unique Roo.Element for each element (defaults to a shared flyweight object)
11048 * @param {HTMLElement/String} root (optional) The root element of the query or id of the root
11049 * @return {CompositeElementLite/CompositeElement}
11053 Roo.select = Roo.Element.select;
11070 * Ext JS Library 1.1.1
11071 * Copyright(c) 2006-2007, Ext JS, LLC.
11073 * Originally Released Under LGPL - original licence link has changed is not relivant.
11076 * <script type="text/javascript">
11081 //Notifies Element that fx methods are available
11082 Roo.enableFx = true;
11086 * <p>A class to provide basic animation and visual effects support. <b>Note:</b> This class is automatically applied
11087 * to the {@link Roo.Element} interface when included, so all effects calls should be performed via Element.
11088 * Conversely, since the effects are not actually defined in Element, Roo.Fx <b>must</b> be included in order for the
11089 * Element effects to work.</p><br/>
11091 * <p>It is important to note that although the Fx methods and many non-Fx Element methods support "method chaining" in that
11092 * they return the Element object itself as the method return value, it is not always possible to mix the two in a single
11093 * method chain. The Fx methods use an internal effects queue so that each effect can be properly timed and sequenced.
11094 * Non-Fx methods, on the other hand, have no such internal queueing and will always execute immediately. For this reason,
11095 * while it may be possible to mix certain Fx and non-Fx method calls in a single chain, it may not always provide the
11096 * expected results and should be done with care.</p><br/>
11098 * <p>Motion effects support 8-way anchoring, meaning that you can choose one of 8 different anchor points on the Element
11099 * that will serve as either the start or end point of the animation. Following are all of the supported anchor positions:</p>
11102 ----- -----------------------------
11103 tl The top left corner
11104 t The center of the top edge
11105 tr The top right corner
11106 l The center of the left edge
11107 r The center of the right edge
11108 bl The bottom left corner
11109 b The center of the bottom edge
11110 br The bottom right corner
11112 * <b>Although some Fx methods accept specific custom config parameters, the ones shown in the Config Options section
11113 * below are common options that can be passed to any Fx method.</b>
11114 * @cfg {Function} callback A function called when the effect is finished
11115 * @cfg {Object} scope The scope of the effect function
11116 * @cfg {String} easing A valid Easing value for the effect
11117 * @cfg {String} afterCls A css class to apply after the effect
11118 * @cfg {Number} duration The length of time (in seconds) that the effect should last
11119 * @cfg {Boolean} remove Whether the Element should be removed from the DOM and destroyed after the effect finishes
11120 * @cfg {Boolean} useDisplay Whether to use the <i>display</i> CSS property instead of <i>visibility</i> when hiding Elements (only applies to
11121 * effects that end with the element being visually hidden, ignored otherwise)
11122 * @cfg {String/Object/Function} afterStyle A style specification string, e.g. "width:100px", or an object in the form {width:"100px"}, or
11123 * a function which returns such a specification that will be applied to the Element after the effect finishes
11124 * @cfg {Boolean} block Whether the effect should block other effects from queueing while it runs
11125 * @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
11126 * @cfg {Boolean} stopFx Whether subsequent effects should be stopped and removed after the current effect finishes
11130 * Slides the element into view. An anchor point can be optionally passed to set the point of
11131 * origin for the slide effect. This function automatically handles wrapping the element with
11132 * a fixed-size container if needed. See the Fx class overview for valid anchor point options.
11135 // default: slide the element in from the top
11138 // custom: slide the element in from the right with a 2-second duration
11139 el.slideIn('r', { duration: 2 });
11141 // common config options shown with default values
11147 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to top: 't')
11148 * @param {Object} options (optional) Object literal with any of the Fx config options
11149 * @return {Roo.Element} The Element
11151 slideIn : function(anchor, o){
11152 var el = this.getFxEl();
11155 el.queueFx(o, function(){
11157 anchor = anchor || "t";
11159 // fix display to visibility
11162 // restore values after effect
11163 var r = this.getFxRestore();
11164 var b = this.getBox();
11165 // fixed size for slide
11169 var wrap = this.fxWrap(r.pos, o, "hidden");
11171 var st = this.dom.style;
11172 st.visibility = "visible";
11173 st.position = "absolute";
11175 // clear out temp styles after slide and unwrap
11176 var after = function(){
11177 el.fxUnwrap(wrap, r.pos, o);
11178 st.width = r.width;
11179 st.height = r.height;
11182 // time to calc the positions
11183 var a, pt = {to: [b.x, b.y]}, bw = {to: b.width}, bh = {to: b.height};
11185 switch(anchor.toLowerCase()){
11187 wrap.setSize(b.width, 0);
11188 st.left = st.bottom = "0";
11192 wrap.setSize(0, b.height);
11193 st.right = st.top = "0";
11197 wrap.setSize(0, b.height);
11198 wrap.setX(b.right);
11199 st.left = st.top = "0";
11200 a = {width: bw, points: pt};
11203 wrap.setSize(b.width, 0);
11204 wrap.setY(b.bottom);
11205 st.left = st.top = "0";
11206 a = {height: bh, points: pt};
11209 wrap.setSize(0, 0);
11210 st.right = st.bottom = "0";
11211 a = {width: bw, height: bh};
11214 wrap.setSize(0, 0);
11215 wrap.setY(b.y+b.height);
11216 st.right = st.top = "0";
11217 a = {width: bw, height: bh, points: pt};
11220 wrap.setSize(0, 0);
11221 wrap.setXY([b.right, b.bottom]);
11222 st.left = st.top = "0";
11223 a = {width: bw, height: bh, points: pt};
11226 wrap.setSize(0, 0);
11227 wrap.setX(b.x+b.width);
11228 st.left = st.bottom = "0";
11229 a = {width: bw, height: bh, points: pt};
11232 this.dom.style.visibility = "visible";
11235 arguments.callee.anim = wrap.fxanim(a,
11245 * Slides the element out of view. An anchor point can be optionally passed to set the end point
11246 * for the slide effect. When the effect is completed, the element will be hidden (visibility =
11247 * 'hidden') but block elements will still take up space in the document. The element must be removed
11248 * from the DOM using the 'remove' config option if desired. This function automatically handles
11249 * wrapping the element with a fixed-size container if needed. See the Fx class overview for valid anchor point options.
11252 // default: slide the element out to the top
11255 // custom: slide the element out to the right with a 2-second duration
11256 el.slideOut('r', { duration: 2 });
11258 // common config options shown with default values
11266 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to top: 't')
11267 * @param {Object} options (optional) Object literal with any of the Fx config options
11268 * @return {Roo.Element} The Element
11270 slideOut : function(anchor, o){
11271 var el = this.getFxEl();
11274 el.queueFx(o, function(){
11276 anchor = anchor || "t";
11278 // restore values after effect
11279 var r = this.getFxRestore();
11281 var b = this.getBox();
11282 // fixed size for slide
11286 var wrap = this.fxWrap(r.pos, o, "visible");
11288 var st = this.dom.style;
11289 st.visibility = "visible";
11290 st.position = "absolute";
11294 var after = function(){
11296 el.setDisplayed(false);
11301 el.fxUnwrap(wrap, r.pos, o);
11303 st.width = r.width;
11304 st.height = r.height;
11309 var a, zero = {to: 0};
11310 switch(anchor.toLowerCase()){
11312 st.left = st.bottom = "0";
11313 a = {height: zero};
11316 st.right = st.top = "0";
11320 st.left = st.top = "0";
11321 a = {width: zero, points: {to:[b.right, b.y]}};
11324 st.left = st.top = "0";
11325 a = {height: zero, points: {to:[b.x, b.bottom]}};
11328 st.right = st.bottom = "0";
11329 a = {width: zero, height: zero};
11332 st.right = st.top = "0";
11333 a = {width: zero, height: zero, points: {to:[b.x, b.bottom]}};
11336 st.left = st.top = "0";
11337 a = {width: zero, height: zero, points: {to:[b.x+b.width, b.bottom]}};
11340 st.left = st.bottom = "0";
11341 a = {width: zero, height: zero, points: {to:[b.right, b.y]}};
11345 arguments.callee.anim = wrap.fxanim(a,
11355 * Fades the element out while slowly expanding it in all directions. When the effect is completed, the
11356 * element will be hidden (visibility = 'hidden') but block elements will still take up space in the document.
11357 * The element must be removed from the DOM using the 'remove' config option if desired.
11363 // common config options shown with default values
11371 * @param {Object} options (optional) Object literal with any of the Fx config options
11372 * @return {Roo.Element} The Element
11374 puff : function(o){
11375 var el = this.getFxEl();
11378 el.queueFx(o, function(){
11379 this.clearOpacity();
11382 // restore values after effect
11383 var r = this.getFxRestore();
11384 var st = this.dom.style;
11386 var after = function(){
11388 el.setDisplayed(false);
11395 el.setPositioning(r.pos);
11396 st.width = r.width;
11397 st.height = r.height;
11402 var width = this.getWidth();
11403 var height = this.getHeight();
11405 arguments.callee.anim = this.fxanim({
11406 width : {to: this.adjustWidth(width * 2)},
11407 height : {to: this.adjustHeight(height * 2)},
11408 points : {by: [-(width * .5), -(height * .5)]},
11410 fontSize: {to:200, unit: "%"}
11421 * Blinks the element as if it was clicked and then collapses on its center (similar to switching off a television).
11422 * When the effect is completed, the element will be hidden (visibility = 'hidden') but block elements will still
11423 * take up space in the document. The element must be removed from the DOM using the 'remove' config option if desired.
11429 // all config options shown with default values
11437 * @param {Object} options (optional) Object literal with any of the Fx config options
11438 * @return {Roo.Element} The Element
11440 switchOff : function(o){
11441 var el = this.getFxEl();
11444 el.queueFx(o, function(){
11445 this.clearOpacity();
11448 // restore values after effect
11449 var r = this.getFxRestore();
11450 var st = this.dom.style;
11452 var after = function(){
11454 el.setDisplayed(false);
11460 el.setPositioning(r.pos);
11461 st.width = r.width;
11462 st.height = r.height;
11467 this.fxanim({opacity:{to:0.3}}, null, null, .1, null, function(){
11468 this.clearOpacity();
11472 points:{by:[0, this.getHeight() * .5]}
11473 }, o, 'motion', 0.3, 'easeIn', after);
11474 }).defer(100, this);
11481 * Highlights the Element by setting a color (applies to the background-color by default, but can be
11482 * changed using the "attr" config option) and then fading back to the original color. If no original
11483 * color is available, you should provide the "endColor" config option which will be cleared after the animation.
11486 // default: highlight background to yellow
11489 // custom: highlight foreground text to blue for 2 seconds
11490 el.highlight("0000ff", { attr: 'color', duration: 2 });
11492 // common config options shown with default values
11493 el.highlight("ffff9c", {
11494 attr: "background-color", //can be any valid CSS property (attribute) that supports a color value
11495 endColor: (current color) or "ffffff",
11500 * @param {String} color (optional) The highlight color. Should be a 6 char hex color without the leading # (defaults to yellow: 'ffff9c')
11501 * @param {Object} options (optional) Object literal with any of the Fx config options
11502 * @return {Roo.Element} The Element
11504 highlight : function(color, o){
11505 var el = this.getFxEl();
11508 el.queueFx(o, function(){
11509 color = color || "ffff9c";
11510 attr = o.attr || "backgroundColor";
11512 this.clearOpacity();
11515 var origColor = this.getColor(attr);
11516 var restoreColor = this.dom.style[attr];
11517 endColor = (o.endColor || origColor) || "ffffff";
11519 var after = function(){
11520 el.dom.style[attr] = restoreColor;
11525 a[attr] = {from: color, to: endColor};
11526 arguments.callee.anim = this.fxanim(a,
11536 * Shows a ripple of exploding, attenuating borders to draw attention to an Element.
11539 // default: a single light blue ripple
11542 // custom: 3 red ripples lasting 3 seconds total
11543 el.frame("ff0000", 3, { duration: 3 });
11545 // common config options shown with default values
11546 el.frame("C3DAF9", 1, {
11547 duration: 1 //duration of entire animation (not each individual ripple)
11548 // Note: Easing is not configurable and will be ignored if included
11551 * @param {String} color (optional) The color of the border. Should be a 6 char hex color without the leading # (defaults to light blue: 'C3DAF9').
11552 * @param {Number} count (optional) The number of ripples to display (defaults to 1)
11553 * @param {Object} options (optional) Object literal with any of the Fx config options
11554 * @return {Roo.Element} The Element
11556 frame : function(color, count, o){
11557 var el = this.getFxEl();
11560 el.queueFx(o, function(){
11561 color = color || "#C3DAF9";
11562 if(color.length == 6){
11563 color = "#" + color;
11565 count = count || 1;
11566 duration = o.duration || 1;
11569 var b = this.getBox();
11570 var animFn = function(){
11571 var proxy = this.createProxy({
11574 visbility:"hidden",
11575 position:"absolute",
11576 "z-index":"35000", // yee haw
11577 border:"0px solid " + color
11580 var scale = Roo.isBorderBox ? 2 : 1;
11582 top:{from:b.y, to:b.y - 20},
11583 left:{from:b.x, to:b.x - 20},
11584 borderWidth:{from:0, to:10},
11585 opacity:{from:1, to:0},
11586 height:{from:b.height, to:(b.height + (20*scale))},
11587 width:{from:b.width, to:(b.width + (20*scale))}
11588 }, duration, function(){
11592 animFn.defer((duration/2)*1000, this);
11603 * Creates a pause before any subsequent queued effects begin. If there are
11604 * no effects queued after the pause it will have no effect.
11609 * @param {Number} seconds The length of time to pause (in seconds)
11610 * @return {Roo.Element} The Element
11612 pause : function(seconds){
11613 var el = this.getFxEl();
11616 el.queueFx(o, function(){
11617 setTimeout(function(){
11619 }, seconds * 1000);
11625 * Fade an element in (from transparent to opaque). The ending opacity can be specified
11626 * using the "endOpacity" config option.
11629 // default: fade in from opacity 0 to 100%
11632 // custom: fade in from opacity 0 to 75% over 2 seconds
11633 el.fadeIn({ endOpacity: .75, duration: 2});
11635 // common config options shown with default values
11637 endOpacity: 1, //can be any value between 0 and 1 (e.g. .5)
11642 * @param {Object} options (optional) Object literal with any of the Fx config options
11643 * @return {Roo.Element} The Element
11645 fadeIn : function(o){
11646 var el = this.getFxEl();
11648 el.queueFx(o, function(){
11649 this.setOpacity(0);
11651 this.dom.style.visibility = 'visible';
11652 var to = o.endOpacity || 1;
11653 arguments.callee.anim = this.fxanim({opacity:{to:to}},
11654 o, null, .5, "easeOut", function(){
11656 this.clearOpacity();
11665 * Fade an element out (from opaque to transparent). The ending opacity can be specified
11666 * using the "endOpacity" config option.
11669 // default: fade out from the element's current opacity to 0
11672 // custom: fade out from the element's current opacity to 25% over 2 seconds
11673 el.fadeOut({ endOpacity: .25, duration: 2});
11675 // common config options shown with default values
11677 endOpacity: 0, //can be any value between 0 and 1 (e.g. .5)
11684 * @param {Object} options (optional) Object literal with any of the Fx config options
11685 * @return {Roo.Element} The Element
11687 fadeOut : function(o){
11688 var el = this.getFxEl();
11690 el.queueFx(o, function(){
11691 arguments.callee.anim = this.fxanim({opacity:{to:o.endOpacity || 0}},
11692 o, null, .5, "easeOut", function(){
11693 if(this.visibilityMode == Roo.Element.DISPLAY || o.useDisplay){
11694 this.dom.style.display = "none";
11696 this.dom.style.visibility = "hidden";
11698 this.clearOpacity();
11706 * Animates the transition of an element's dimensions from a starting height/width
11707 * to an ending height/width.
11710 // change height and width to 100x100 pixels
11711 el.scale(100, 100);
11713 // common config options shown with default values. The height and width will default to
11714 // the element's existing values if passed as null.
11717 [element's height], {
11722 * @param {Number} width The new width (pass undefined to keep the original width)
11723 * @param {Number} height The new height (pass undefined to keep the original height)
11724 * @param {Object} options (optional) Object literal with any of the Fx config options
11725 * @return {Roo.Element} The Element
11727 scale : function(w, h, o){
11728 this.shift(Roo.apply({}, o, {
11736 * Animates the transition of any combination of an element's dimensions, xy position and/or opacity.
11737 * Any of these properties not specified in the config object will not be changed. This effect
11738 * requires that at least one new dimension, position or opacity setting must be passed in on
11739 * the config object in order for the function to have any effect.
11742 // slide the element horizontally to x position 200 while changing the height and opacity
11743 el.shift({ x: 200, height: 50, opacity: .8 });
11745 // common config options shown with default values.
11747 width: [element's width],
11748 height: [element's height],
11749 x: [element's x position],
11750 y: [element's y position],
11751 opacity: [element's opacity],
11756 * @param {Object} options Object literal with any of the Fx config options
11757 * @return {Roo.Element} The Element
11759 shift : function(o){
11760 var el = this.getFxEl();
11762 el.queueFx(o, function(){
11763 var a = {}, w = o.width, h = o.height, x = o.x, y = o.y, op = o.opacity;
11764 if(w !== undefined){
11765 a.width = {to: this.adjustWidth(w)};
11767 if(h !== undefined){
11768 a.height = {to: this.adjustHeight(h)};
11770 if(x !== undefined || y !== undefined){
11772 x !== undefined ? x : this.getX(),
11773 y !== undefined ? y : this.getY()
11776 if(op !== undefined){
11777 a.opacity = {to: op};
11779 if(o.xy !== undefined){
11780 a.points = {to: o.xy};
11782 arguments.callee.anim = this.fxanim(a,
11783 o, 'motion', .35, "easeOut", function(){
11791 * Slides the element while fading it out of view. An anchor point can be optionally passed to set the
11792 * ending point of the effect.
11795 // default: slide the element downward while fading out
11798 // custom: slide the element out to the right with a 2-second duration
11799 el.ghost('r', { duration: 2 });
11801 // common config options shown with default values
11809 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to bottom: 'b')
11810 * @param {Object} options (optional) Object literal with any of the Fx config options
11811 * @return {Roo.Element} The Element
11813 ghost : function(anchor, o){
11814 var el = this.getFxEl();
11817 el.queueFx(o, function(){
11818 anchor = anchor || "b";
11820 // restore values after effect
11821 var r = this.getFxRestore();
11822 var w = this.getWidth(),
11823 h = this.getHeight();
11825 var st = this.dom.style;
11827 var after = function(){
11829 el.setDisplayed(false);
11835 el.setPositioning(r.pos);
11836 st.width = r.width;
11837 st.height = r.height;
11842 var a = {opacity: {to: 0}, points: {}}, pt = a.points;
11843 switch(anchor.toLowerCase()){
11870 arguments.callee.anim = this.fxanim(a,
11880 * Ensures that all effects queued after syncFx is called on the element are
11881 * run concurrently. This is the opposite of {@link #sequenceFx}.
11882 * @return {Roo.Element} The Element
11884 syncFx : function(){
11885 this.fxDefaults = Roo.apply(this.fxDefaults || {}, {
11894 * Ensures that all effects queued after sequenceFx is called on the element are
11895 * run in sequence. This is the opposite of {@link #syncFx}.
11896 * @return {Roo.Element} The Element
11898 sequenceFx : function(){
11899 this.fxDefaults = Roo.apply(this.fxDefaults || {}, {
11901 concurrent : false,
11908 nextFx : function(){
11909 var ef = this.fxQueue[0];
11916 * Returns true if the element has any effects actively running or queued, else returns false.
11917 * @return {Boolean} True if element has active effects, else false
11919 hasActiveFx : function(){
11920 return this.fxQueue && this.fxQueue[0];
11924 * Stops any running effects and clears the element's internal effects queue if it contains
11925 * any additional effects that haven't started yet.
11926 * @return {Roo.Element} The Element
11928 stopFx : function(){
11929 if(this.hasActiveFx()){
11930 var cur = this.fxQueue[0];
11931 if(cur && cur.anim && cur.anim.isAnimated()){
11932 this.fxQueue = [cur]; // clear out others
11933 cur.anim.stop(true);
11940 beforeFx : function(o){
11941 if(this.hasActiveFx() && !o.concurrent){
11952 * Returns true if the element is currently blocking so that no other effect can be queued
11953 * until this effect is finished, else returns false if blocking is not set. This is commonly
11954 * used to ensure that an effect initiated by a user action runs to completion prior to the
11955 * same effect being restarted (e.g., firing only one effect even if the user clicks several times).
11956 * @return {Boolean} True if blocking, else false
11958 hasFxBlock : function(){
11959 var q = this.fxQueue;
11960 return q && q[0] && q[0].block;
11964 queueFx : function(o, fn){
11968 if(!this.hasFxBlock()){
11969 Roo.applyIf(o, this.fxDefaults);
11971 var run = this.beforeFx(o);
11972 fn.block = o.block;
11973 this.fxQueue.push(fn);
11985 fxWrap : function(pos, o, vis){
11987 if(!o.wrap || !(wrap = Roo.get(o.wrap))){
11990 wrapXY = this.getXY();
11992 var div = document.createElement("div");
11993 div.style.visibility = vis;
11994 wrap = Roo.get(this.dom.parentNode.insertBefore(div, this.dom));
11995 wrap.setPositioning(pos);
11996 if(wrap.getStyle("position") == "static"){
11997 wrap.position("relative");
11999 this.clearPositioning('auto');
12001 wrap.dom.appendChild(this.dom);
12003 wrap.setXY(wrapXY);
12010 fxUnwrap : function(wrap, pos, o){
12011 this.clearPositioning();
12012 this.setPositioning(pos);
12014 wrap.dom.parentNode.insertBefore(this.dom, wrap.dom);
12020 getFxRestore : function(){
12021 var st = this.dom.style;
12022 return {pos: this.getPositioning(), width: st.width, height : st.height};
12026 afterFx : function(o){
12028 this.applyStyles(o.afterStyle);
12031 this.addClass(o.afterCls);
12033 if(o.remove === true){
12036 Roo.callback(o.callback, o.scope, [this]);
12038 this.fxQueue.shift();
12044 getFxEl : function(){ // support for composite element fx
12045 return Roo.get(this.dom);
12049 fxanim : function(args, opt, animType, defaultDur, defaultEase, cb){
12050 animType = animType || 'run';
12052 var anim = Roo.lib.Anim[animType](
12054 (opt.duration || defaultDur) || .35,
12055 (opt.easing || defaultEase) || 'easeOut',
12057 Roo.callback(cb, this);
12066 // backwords compat
12067 Roo.Fx.resize = Roo.Fx.scale;
12069 //When included, Roo.Fx is automatically applied to Element so that all basic
12070 //effects are available directly via the Element API
12071 Roo.apply(Roo.Element.prototype, Roo.Fx);/*
12073 * Ext JS Library 1.1.1
12074 * Copyright(c) 2006-2007, Ext JS, LLC.
12076 * Originally Released Under LGPL - original licence link has changed is not relivant.
12079 * <script type="text/javascript">
12084 * @class Roo.CompositeElement
12085 * Standard composite class. Creates a Roo.Element for every element in the collection.
12087 * <b>NOTE: Although they are not listed, this class supports all of the set/update methods of Roo.Element. All Roo.Element
12088 * actions will be performed on all the elements in this collection.</b>
12090 * All methods return <i>this</i> and can be chained.
12092 var els = Roo.select("#some-el div.some-class", true);
12093 // or select directly from an existing element
12094 var el = Roo.get('some-el');
12095 el.select('div.some-class', true);
12097 els.setWidth(100); // all elements become 100 width
12098 els.hide(true); // all elements fade out and hide
12100 els.setWidth(100).hide(true);
12103 Roo.CompositeElement = function(els){
12104 this.elements = [];
12105 this.addElements(els);
12107 Roo.CompositeElement.prototype = {
12109 addElements : function(els){
12113 if(typeof els == "string"){
12114 els = Roo.Element.selectorFunction(els);
12116 var yels = this.elements;
12117 var index = yels.length-1;
12118 for(var i = 0, len = els.length; i < len; i++) {
12119 yels[++index] = Roo.get(els[i]);
12125 * Clears this composite and adds the elements returned by the passed selector.
12126 * @param {String/Array} els A string CSS selector, an array of elements or an element
12127 * @return {CompositeElement} this
12129 fill : function(els){
12130 this.elements = [];
12136 * Filters this composite to only elements that match the passed selector.
12137 * @param {String} selector A string CSS selector
12138 * @param {Boolean} inverse return inverse filter (not matches)
12139 * @return {CompositeElement} this
12141 filter : function(selector, inverse){
12143 inverse = inverse || false;
12144 this.each(function(el){
12145 var match = inverse ? !el.is(selector) : el.is(selector);
12147 els[els.length] = el.dom;
12154 invoke : function(fn, args){
12155 var els = this.elements;
12156 for(var i = 0, len = els.length; i < len; i++) {
12157 Roo.Element.prototype[fn].apply(els[i], args);
12162 * Adds elements to this composite.
12163 * @param {String/Array} els A string CSS selector, an array of elements or an element
12164 * @return {CompositeElement} this
12166 add : function(els){
12167 if(typeof els == "string"){
12168 this.addElements(Roo.Element.selectorFunction(els));
12169 }else if(els.length !== undefined){
12170 this.addElements(els);
12172 this.addElements([els]);
12177 * Calls the passed function passing (el, this, index) for each element in this composite.
12178 * @param {Function} fn The function to call
12179 * @param {Object} scope (optional) The <i>this</i> object (defaults to the element)
12180 * @return {CompositeElement} this
12182 each : function(fn, scope){
12183 var els = this.elements;
12184 for(var i = 0, len = els.length; i < len; i++){
12185 if(fn.call(scope || els[i], els[i], this, i) === false) {
12193 * Returns the Element object at the specified index
12194 * @param {Number} index
12195 * @return {Roo.Element}
12197 item : function(index){
12198 return this.elements[index] || null;
12202 * Returns the first Element
12203 * @return {Roo.Element}
12205 first : function(){
12206 return this.item(0);
12210 * Returns the last Element
12211 * @return {Roo.Element}
12214 return this.item(this.elements.length-1);
12218 * Returns the number of elements in this composite
12221 getCount : function(){
12222 return this.elements.length;
12226 * Returns true if this composite contains the passed element
12229 contains : function(el){
12230 return this.indexOf(el) !== -1;
12234 * Returns true if this composite contains the passed element
12237 indexOf : function(el){
12238 return this.elements.indexOf(Roo.get(el));
12243 * Removes the specified element(s).
12244 * @param {Mixed} el The id of an element, the Element itself, the index of the element in this composite
12245 * or an array of any of those.
12246 * @param {Boolean} removeDom (optional) True to also remove the element from the document
12247 * @return {CompositeElement} this
12249 removeElement : function(el, removeDom){
12250 if(el instanceof Array){
12251 for(var i = 0, len = el.length; i < len; i++){
12252 this.removeElement(el[i]);
12256 var index = typeof el == 'number' ? el : this.indexOf(el);
12259 var d = this.elements[index];
12263 d.parentNode.removeChild(d);
12266 this.elements.splice(index, 1);
12272 * Replaces the specified element with the passed element.
12273 * @param {String/HTMLElement/Element/Number} el The id of an element, the Element itself, the index of the element in this composite
12275 * @param {String/HTMLElement/Element} replacement The id of an element or the Element itself.
12276 * @param {Boolean} domReplace (Optional) True to remove and replace the element in the document too.
12277 * @return {CompositeElement} this
12279 replaceElement : function(el, replacement, domReplace){
12280 var index = typeof el == 'number' ? el : this.indexOf(el);
12283 this.elements[index].replaceWith(replacement);
12285 this.elements.splice(index, 1, Roo.get(replacement))
12292 * Removes all elements.
12294 clear : function(){
12295 this.elements = [];
12299 Roo.CompositeElement.createCall = function(proto, fnName){
12300 if(!proto[fnName]){
12301 proto[fnName] = function(){
12302 return this.invoke(fnName, arguments);
12306 for(var fnName in Roo.Element.prototype){
12307 if(typeof Roo.Element.prototype[fnName] == "function"){
12308 Roo.CompositeElement.createCall(Roo.CompositeElement.prototype, fnName);
12314 * Ext JS Library 1.1.1
12315 * Copyright(c) 2006-2007, Ext JS, LLC.
12317 * Originally Released Under LGPL - original licence link has changed is not relivant.
12320 * <script type="text/javascript">
12324 * @class Roo.CompositeElementLite
12325 * @extends Roo.CompositeElement
12326 * Flyweight composite class. Reuses the same Roo.Element for element operations.
12328 var els = Roo.select("#some-el div.some-class");
12329 // or select directly from an existing element
12330 var el = Roo.get('some-el');
12331 el.select('div.some-class');
12333 els.setWidth(100); // all elements become 100 width
12334 els.hide(true); // all elements fade out and hide
12336 els.setWidth(100).hide(true);
12337 </code></pre><br><br>
12338 * <b>NOTE: Although they are not listed, this class supports all of the set/update methods of Roo.Element. All Roo.Element
12339 * actions will be performed on all the elements in this collection.</b>
12341 Roo.CompositeElementLite = function(els){
12342 Roo.CompositeElementLite.superclass.constructor.call(this, els);
12343 this.el = new Roo.Element.Flyweight();
12345 Roo.extend(Roo.CompositeElementLite, Roo.CompositeElement, {
12346 addElements : function(els){
12348 if(els instanceof Array){
12349 this.elements = this.elements.concat(els);
12351 var yels = this.elements;
12352 var index = yels.length-1;
12353 for(var i = 0, len = els.length; i < len; i++) {
12354 yels[++index] = els[i];
12360 invoke : function(fn, args){
12361 var els = this.elements;
12363 for(var i = 0, len = els.length; i < len; i++) {
12365 Roo.Element.prototype[fn].apply(el, args);
12370 * Returns a flyweight Element of the dom element object at the specified index
12371 * @param {Number} index
12372 * @return {Roo.Element}
12374 item : function(index){
12375 if(!this.elements[index]){
12378 this.el.dom = this.elements[index];
12382 // fixes scope with flyweight
12383 addListener : function(eventName, handler, scope, opt){
12384 var els = this.elements;
12385 for(var i = 0, len = els.length; i < len; i++) {
12386 Roo.EventManager.on(els[i], eventName, handler, scope || els[i], opt);
12392 * Calls the passed function passing (el, this, index) for each element in this composite. <b>The element
12393 * passed is the flyweight (shared) Roo.Element instance, so if you require a
12394 * a reference to the dom node, use el.dom.</b>
12395 * @param {Function} fn The function to call
12396 * @param {Object} scope (optional) The <i>this</i> object (defaults to the element)
12397 * @return {CompositeElement} this
12399 each : function(fn, scope){
12400 var els = this.elements;
12402 for(var i = 0, len = els.length; i < len; i++){
12404 if(fn.call(scope || el, el, this, i) === false){
12411 indexOf : function(el){
12412 return this.elements.indexOf(Roo.getDom(el));
12415 replaceElement : function(el, replacement, domReplace){
12416 var index = typeof el == 'number' ? el : this.indexOf(el);
12418 replacement = Roo.getDom(replacement);
12420 var d = this.elements[index];
12421 d.parentNode.insertBefore(replacement, d);
12422 d.parentNode.removeChild(d);
12424 this.elements.splice(index, 1, replacement);
12429 Roo.CompositeElementLite.prototype.on = Roo.CompositeElementLite.prototype.addListener;
12433 * Ext JS Library 1.1.1
12434 * Copyright(c) 2006-2007, Ext JS, LLC.
12436 * Originally Released Under LGPL - original licence link has changed is not relivant.
12439 * <script type="text/javascript">
12445 * @class Roo.data.Connection
12446 * @extends Roo.util.Observable
12447 * The class encapsulates a connection to the page's originating domain, allowing requests to be made
12448 * either to a configured URL, or to a URL specified at request time.
12450 * Requests made by this class are asynchronous, and will return immediately. No data from
12451 * the server will be available to the statement immediately following the {@link #request} call.
12452 * To process returned data, use a callback in the request options object, or an event listener.
12454 * Note: If you are doing a file upload, you will not get a normal response object sent back to
12455 * your callback or event handler. Since the upload is handled via in IFRAME, there is no XMLHttpRequest.
12456 * The response object is created using the innerHTML of the IFRAME's document as the responseText
12457 * property and, if present, the IFRAME's XML document as the responseXML property.
12459 * This means that a valid XML or HTML document must be returned. If JSON data is required, it is suggested
12460 * that it be placed either inside a <textarea> in an HTML document and retrieved from the responseText
12461 * using a regex, or inside a CDATA section in an XML document and retrieved from the responseXML using
12462 * standard DOM methods.
12464 * @param {Object} config a configuration object.
12466 Roo.data.Connection = function(config){
12467 Roo.apply(this, config);
12470 * @event beforerequest
12471 * Fires before a network request is made to retrieve a data object.
12472 * @param {Connection} conn This Connection object.
12473 * @param {Object} options The options config object passed to the {@link #request} method.
12475 "beforerequest" : true,
12477 * @event requestcomplete
12478 * Fires if the request was successfully completed.
12479 * @param {Connection} conn This Connection object.
12480 * @param {Object} response The XHR object containing the response data.
12481 * See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
12482 * @param {Object} options The options config object passed to the {@link #request} method.
12484 "requestcomplete" : true,
12486 * @event requestexception
12487 * Fires if an error HTTP status was returned from the server.
12488 * See {@link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html} for details of HTTP status codes.
12489 * @param {Connection} conn This Connection object.
12490 * @param {Object} response The XHR object containing the response data.
12491 * See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
12492 * @param {Object} options The options config object passed to the {@link #request} method.
12494 "requestexception" : true
12496 Roo.data.Connection.superclass.constructor.call(this);
12499 Roo.extend(Roo.data.Connection, Roo.util.Observable, {
12501 * @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
12504 * @cfg {Object} extraParams (Optional) An object containing properties which are used as
12505 * extra parameters to each request made by this object. (defaults to undefined)
12508 * @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
12509 * to each request made by this object. (defaults to undefined)
12512 * @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)
12515 * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
12519 * @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
12525 * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
12528 disableCaching: true,
12531 * Sends an HTTP request to a remote server.
12532 * @param {Object} options An object which may contain the following properties:<ul>
12533 * <li><b>url</b> {String} (Optional) The URL to which to send the request. Defaults to configured URL</li>
12534 * <li><b>params</b> {Object/String/Function} (Optional) An object containing properties which are used as parameters to the
12535 * request, a url encoded string or a function to call to get either.</li>
12536 * <li><b>method</b> {String} (Optional) The HTTP method to use for the request. Defaults to the configured method, or
12537 * if no method was configured, "GET" if no parameters are being sent, and "POST" if parameters are being sent.</li>
12538 * <li><b>callback</b> {Function} (Optional) The function to be called upon receipt of the HTTP response.
12539 * The callback is called regardless of success or failure and is passed the following parameters:<ul>
12540 * <li>options {Object} The parameter to the request call.</li>
12541 * <li>success {Boolean} True if the request succeeded.</li>
12542 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
12544 * <li><b>success</b> {Function} (Optional) The function to be called upon success of the request.
12545 * The callback is passed the following parameters:<ul>
12546 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
12547 * <li>options {Object} The parameter to the request call.</li>
12549 * <li><b>failure</b> {Function} (Optional) The function to be called upon failure of the request.
12550 * The callback is passed the following parameters:<ul>
12551 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
12552 * <li>options {Object} The parameter to the request call.</li>
12554 * <li><b>scope</b> {Object} (Optional) The scope in which to execute the callbacks: The "this" object
12555 * for the callback function. Defaults to the browser window.</li>
12556 * <li><b>form</b> {Object/String} (Optional) A form object or id to pull parameters from.</li>
12557 * <li><b>isUpload</b> {Boolean} (Optional) True if the form object is a file upload (will usually be automatically detected).</li>
12558 * <li><b>headers</b> {Object} (Optional) Request headers to set for the request.</li>
12559 * <li><b>xmlData</b> {Object} (Optional) XML document to use for the post. Note: This will be used instead of
12560 * params for the post data. Any params will be appended to the URL.</li>
12561 * <li><b>disableCaching</b> {Boolean} (Optional) True to add a unique cache-buster param to GET requests.</li>
12563 * @return {Number} transactionId
12565 request : function(o){
12566 if(this.fireEvent("beforerequest", this, o) !== false){
12569 if(typeof p == "function"){
12570 p = p.call(o.scope||window, o);
12572 if(typeof p == "object"){
12573 p = Roo.urlEncode(o.params);
12575 if(this.extraParams){
12576 var extras = Roo.urlEncode(this.extraParams);
12577 p = p ? (p + '&' + extras) : extras;
12580 var url = o.url || this.url;
12581 if(typeof url == 'function'){
12582 url = url.call(o.scope||window, o);
12586 var form = Roo.getDom(o.form);
12587 url = url || form.action;
12589 var enctype = form.getAttribute("enctype");
12592 return this.doFormDataUpload(o, url);
12595 if(o.isUpload || (enctype && enctype.toLowerCase() == 'multipart/form-data')){
12596 return this.doFormUpload(o, p, url);
12598 var f = Roo.lib.Ajax.serializeForm(form);
12599 p = p ? (p + '&' + f) : f;
12602 if (!o.form && o.formData) {
12603 o.formData = o.formData === true ? new FormData() : o.formData;
12604 for (var k in o.params) {
12605 o.formData.append(k,o.params[k]);
12608 return this.doFormDataUpload(o, url);
12612 var hs = o.headers;
12613 if(this.defaultHeaders){
12614 hs = Roo.apply(hs || {}, this.defaultHeaders);
12621 success: this.handleResponse,
12622 failure: this.handleFailure,
12624 argument: {options: o},
12625 timeout : o.timeout || this.timeout
12628 var method = o.method||this.method||(p ? "POST" : "GET");
12630 if(method == 'GET' && (this.disableCaching && o.disableCaching !== false) || o.disableCaching === true){
12631 url += (url.indexOf('?') != -1 ? '&' : '?') + '_dc=' + (new Date().getTime());
12634 if(typeof o.autoAbort == 'boolean'){ // options gets top priority
12638 }else if(this.autoAbort !== false){
12642 if((method == 'GET' && p) || o.xmlData){
12643 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
12646 Roo.lib.Ajax.useDefaultHeader = typeof(o.headers) == 'undefined' || typeof(o.headers['Content-Type']) == 'undefined';
12647 this.transId = Roo.lib.Ajax.request(method, url, cb, p, o);
12648 Roo.lib.Ajax.useDefaultHeader == true;
12649 return this.transId;
12651 Roo.callback(o.callback, o.scope, [o, null, null]);
12657 * Determine whether this object has a request outstanding.
12658 * @param {Number} transactionId (Optional) defaults to the last transaction
12659 * @return {Boolean} True if there is an outstanding request.
12661 isLoading : function(transId){
12663 return Roo.lib.Ajax.isCallInProgress(transId);
12665 return this.transId ? true : false;
12670 * Aborts any outstanding request.
12671 * @param {Number} transactionId (Optional) defaults to the last transaction
12673 abort : function(transId){
12674 if(transId || this.isLoading()){
12675 Roo.lib.Ajax.abort(transId || this.transId);
12680 handleResponse : function(response){
12681 this.transId = false;
12682 var options = response.argument.options;
12683 response.argument = options ? options.argument : null;
12684 this.fireEvent("requestcomplete", this, response, options);
12685 Roo.callback(options.success, options.scope, [response, options]);
12686 Roo.callback(options.callback, options.scope, [options, true, response]);
12690 handleFailure : function(response, e){
12691 this.transId = false;
12692 var options = response.argument.options;
12693 response.argument = options ? options.argument : null;
12694 this.fireEvent("requestexception", this, response, options, e);
12695 Roo.callback(options.failure, options.scope, [response, options]);
12696 Roo.callback(options.callback, options.scope, [options, false, response]);
12700 doFormUpload : function(o, ps, url){
12702 var frame = document.createElement('iframe');
12705 frame.className = 'x-hidden';
12707 frame.src = Roo.SSL_SECURE_URL;
12709 document.body.appendChild(frame);
12712 document.frames[id].name = id;
12715 var form = Roo.getDom(o.form);
12717 form.method = 'POST';
12718 form.enctype = form.encoding = 'multipart/form-data';
12724 if(ps){ // add dynamic params
12726 ps = Roo.urlDecode(ps, false);
12728 if(ps.hasOwnProperty(k)){
12729 hd = document.createElement('input');
12730 hd.type = 'hidden';
12733 form.appendChild(hd);
12740 var r = { // bogus response object
12745 r.argument = o ? o.argument : null;
12750 doc = frame.contentWindow.document;
12752 doc = (frame.contentDocument || window.frames[id].document);
12754 if(doc && doc.body){
12755 r.responseText = doc.body.innerHTML;
12757 if(doc && doc.XMLDocument){
12758 r.responseXML = doc.XMLDocument;
12760 r.responseXML = doc;
12767 Roo.EventManager.removeListener(frame, 'load', cb, this);
12769 this.fireEvent("requestcomplete", this, r, o);
12770 Roo.callback(o.success, o.scope, [r, o]);
12771 Roo.callback(o.callback, o.scope, [o, true, r]);
12773 setTimeout(function(){document.body.removeChild(frame);}, 100);
12776 Roo.EventManager.on(frame, 'load', cb, this);
12779 if(hiddens){ // remove dynamic params
12780 for(var i = 0, len = hiddens.length; i < len; i++){
12781 form.removeChild(hiddens[i]);
12785 // this is a 'formdata version???'
12788 doFormDataUpload : function(o, url)
12792 var form = Roo.getDom(o.form);
12793 form.enctype = form.encoding = 'multipart/form-data';
12794 formData = o.formData === true ? new FormData(form) : o.formData;
12796 formData = o.formData === true ? new FormData() : o.formData;
12801 success: this.handleResponse,
12802 failure: this.handleFailure,
12804 argument: {options: o},
12805 timeout : o.timeout || this.timeout
12808 if(typeof o.autoAbort == 'boolean'){ // options gets top priority
12812 }else if(this.autoAbort !== false){
12816 //Roo.lib.Ajax.defaultPostHeader = null;
12817 Roo.lib.Ajax.useDefaultHeader = false;
12818 this.transId = Roo.lib.Ajax.request( "POST", url, cb, formData, o);
12819 Roo.lib.Ajax.useDefaultHeader = true;
12827 * Ext JS Library 1.1.1
12828 * Copyright(c) 2006-2007, Ext JS, LLC.
12830 * Originally Released Under LGPL - original licence link has changed is not relivant.
12833 * <script type="text/javascript">
12837 * Global Ajax request class.
12840 * @extends Roo.data.Connection
12843 * @cfg {String} url The default URL to be used for requests to the server. (defaults to undefined)
12844 * @cfg {Object} extraParams An object containing properties which are used as extra parameters to each request made by this object. (defaults to undefined)
12845 * @cfg {Object} defaultHeaders An object containing request headers which are added to each request made by this object. (defaults to undefined)
12846 * @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)
12847 * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
12848 * @cfg {Boolean} autoAbort (Optional) Whether a new request should abort any pending requests. (defaults to false)
12849 * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
12851 Roo.Ajax = new Roo.data.Connection({
12860 * Serialize the passed form into a url encoded string
12862 * @param {String/HTMLElement} form
12865 serializeForm : function(form){
12866 return Roo.lib.Ajax.serializeForm(form);
12870 * Ext JS Library 1.1.1
12871 * Copyright(c) 2006-2007, Ext JS, LLC.
12873 * Originally Released Under LGPL - original licence link has changed is not relivant.
12876 * <script type="text/javascript">
12881 * @class Roo.UpdateManager
12882 * @extends Roo.util.Observable
12883 * Provides AJAX-style update for Element object.<br><br>
12886 * // Get it from a Roo.Element object
12887 * var el = Roo.get("foo");
12888 * var mgr = el.getUpdateManager();
12889 * mgr.update("http://myserver.com/index.php", "param1=1&param2=2");
12891 * mgr.formUpdate("myFormId", "http://myserver.com/index.php");
12893 * // or directly (returns the same UpdateManager instance)
12894 * var mgr = new Roo.UpdateManager("myElementId");
12895 * mgr.startAutoRefresh(60, "http://myserver.com/index.php");
12896 * mgr.on("update", myFcnNeedsToKnow);
12898 // short handed call directly from the element object
12899 Roo.get("foo").load({
12903 text: "Loading Foo..."
12907 * Create new UpdateManager directly.
12908 * @param {String/HTMLElement/Roo.Element} el The element to update
12909 * @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).
12911 Roo.UpdateManager = function(el, forceNew){
12913 if(!forceNew && el.updateManager){
12914 return el.updateManager;
12917 * The Element object
12918 * @type Roo.Element
12922 * Cached url to use for refreshes. Overwritten every time update() is called unless "discardUrl" param is set to true.
12925 this.defaultUrl = null;
12929 * @event beforeupdate
12930 * Fired before an update is made, return false from your handler and the update is cancelled.
12931 * @param {Roo.Element} el
12932 * @param {String/Object/Function} url
12933 * @param {String/Object} params
12935 "beforeupdate": true,
12938 * Fired after successful update is made.
12939 * @param {Roo.Element} el
12940 * @param {Object} oResponseObject The response Object
12945 * Fired on update failure.
12946 * @param {Roo.Element} el
12947 * @param {Object} oResponseObject The response Object
12951 var d = Roo.UpdateManager.defaults;
12953 * Blank page URL to use with SSL file uploads (Defaults to Roo.UpdateManager.defaults.sslBlankUrl or "about:blank").
12956 this.sslBlankUrl = d.sslBlankUrl;
12958 * Whether to append unique parameter on get request to disable caching (Defaults to Roo.UpdateManager.defaults.disableCaching or false).
12961 this.disableCaching = d.disableCaching;
12963 * Text for loading indicator (Defaults to Roo.UpdateManager.defaults.indicatorText or '<div class="loading-indicator">Loading...</div>').
12966 this.indicatorText = d.indicatorText;
12968 * Whether to show indicatorText when loading (Defaults to Roo.UpdateManager.defaults.showLoadIndicator or true).
12971 this.showLoadIndicator = d.showLoadIndicator;
12973 * Timeout for requests or form posts in seconds (Defaults to Roo.UpdateManager.defaults.timeout or 30 seconds).
12976 this.timeout = d.timeout;
12979 * True to process scripts in the output (Defaults to Roo.UpdateManager.defaults.loadScripts (false)).
12982 this.loadScripts = d.loadScripts;
12985 * Transaction object of current executing transaction
12987 this.transaction = null;
12992 this.autoRefreshProcId = null;
12994 * Delegate for refresh() prebound to "this", use myUpdater.refreshDelegate.createCallback(arg1, arg2) to bind arguments
12997 this.refreshDelegate = this.refresh.createDelegate(this);
12999 * Delegate for update() prebound to "this", use myUpdater.updateDelegate.createCallback(arg1, arg2) to bind arguments
13002 this.updateDelegate = this.update.createDelegate(this);
13004 * Delegate for formUpdate() prebound to "this", use myUpdater.formUpdateDelegate.createCallback(arg1, arg2) to bind arguments
13007 this.formUpdateDelegate = this.formUpdate.createDelegate(this);
13011 this.successDelegate = this.processSuccess.createDelegate(this);
13015 this.failureDelegate = this.processFailure.createDelegate(this);
13017 if(!this.renderer){
13019 * The renderer for this UpdateManager. Defaults to {@link Roo.UpdateManager.BasicRenderer}.
13021 this.renderer = new Roo.UpdateManager.BasicRenderer();
13024 Roo.UpdateManager.superclass.constructor.call(this);
13027 Roo.extend(Roo.UpdateManager, Roo.util.Observable, {
13029 * Get the Element this UpdateManager is bound to
13030 * @return {Roo.Element} The element
13032 getEl : function(){
13036 * Performs an async request, updating this element with the response. If params are specified it uses POST, otherwise it uses GET.
13037 * @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:
13040 url: "your-url.php",<br/>
13041 params: {param1: "foo", param2: "bar"}, // or a URL encoded string<br/>
13042 callback: yourFunction,<br/>
13043 scope: yourObject, //(optional scope) <br/>
13044 discardUrl: false, <br/>
13045 nocache: false,<br/>
13046 text: "Loading...",<br/>
13048 scripts: false<br/>
13051 * The only required property is url. The optional properties nocache, text and scripts
13052 * are shorthand for disableCaching, indicatorText and loadScripts and are used to set their associated property on this UpdateManager instance.
13053 * @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}
13054 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess, oResponse)
13055 * @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.
13057 update : function(url, params, callback, discardUrl){
13058 if(this.fireEvent("beforeupdate", this.el, url, params) !== false){
13059 var method = this.method,
13061 if(typeof url == "object"){ // must be config object
13064 params = params || cfg.params;
13065 callback = callback || cfg.callback;
13066 discardUrl = discardUrl || cfg.discardUrl;
13067 if(callback && cfg.scope){
13068 callback = callback.createDelegate(cfg.scope);
13070 if(typeof cfg.method != "undefined"){method = cfg.method;};
13071 if(typeof cfg.nocache != "undefined"){this.disableCaching = cfg.nocache;};
13072 if(typeof cfg.text != "undefined"){this.indicatorText = '<div class="loading-indicator">'+cfg.text+"</div>";};
13073 if(typeof cfg.scripts != "undefined"){this.loadScripts = cfg.scripts;};
13074 if(typeof cfg.timeout != "undefined"){this.timeout = cfg.timeout;};
13076 this.showLoading();
13078 this.defaultUrl = url;
13080 if(typeof url == "function"){
13081 url = url.call(this);
13084 method = method || (params ? "POST" : "GET");
13085 if(method == "GET"){
13086 url = this.prepareUrl(url);
13089 var o = Roo.apply(cfg ||{}, {
13092 success: this.successDelegate,
13093 failure: this.failureDelegate,
13094 callback: undefined,
13095 timeout: (this.timeout*1000),
13096 argument: {"url": url, "form": null, "callback": callback, "params": params}
13098 Roo.log("updated manager called with timeout of " + o.timeout);
13099 this.transaction = Roo.Ajax.request(o);
13104 * 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.
13105 * Uses this.sslBlankUrl for SSL file uploads to prevent IE security warning.
13106 * @param {String/HTMLElement} form The form Id or form element
13107 * @param {String} url (optional) The url to pass the form to. If omitted the action attribute on the form will be used.
13108 * @param {Boolean} reset (optional) Whether to try to reset the form after the update
13109 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess, oResponse)
13111 formUpdate : function(form, url, reset, callback){
13112 if(this.fireEvent("beforeupdate", this.el, form, url) !== false){
13113 if(typeof url == "function"){
13114 url = url.call(this);
13116 form = Roo.getDom(form);
13117 this.transaction = Roo.Ajax.request({
13120 success: this.successDelegate,
13121 failure: this.failureDelegate,
13122 timeout: (this.timeout*1000),
13123 argument: {"url": url, "form": form, "callback": callback, "reset": reset}
13125 this.showLoading.defer(1, this);
13130 * Refresh the element with the last used url or defaultUrl. If there is no url, it returns immediately
13131 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
13133 refresh : function(callback){
13134 if(this.defaultUrl == null){
13137 this.update(this.defaultUrl, null, callback, true);
13141 * Set this element to auto refresh.
13142 * @param {Number} interval How often to update (in seconds).
13143 * @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)
13144 * @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}
13145 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
13146 * @param {Boolean} refreshNow (optional) Whether to execute the refresh now, or wait the interval
13148 startAutoRefresh : function(interval, url, params, callback, refreshNow){
13150 this.update(url || this.defaultUrl, params, callback, true);
13152 if(this.autoRefreshProcId){
13153 clearInterval(this.autoRefreshProcId);
13155 this.autoRefreshProcId = setInterval(this.update.createDelegate(this, [url || this.defaultUrl, params, callback, true]), interval*1000);
13159 * Stop auto refresh on this element.
13161 stopAutoRefresh : function(){
13162 if(this.autoRefreshProcId){
13163 clearInterval(this.autoRefreshProcId);
13164 delete this.autoRefreshProcId;
13168 isAutoRefreshing : function(){
13169 return this.autoRefreshProcId ? true : false;
13172 * Called to update the element to "Loading" state. Override to perform custom action.
13174 showLoading : function(){
13175 if(this.showLoadIndicator){
13176 this.el.update(this.indicatorText);
13181 * Adds unique parameter to query string if disableCaching = true
13184 prepareUrl : function(url){
13185 if(this.disableCaching){
13186 var append = "_dc=" + (new Date().getTime());
13187 if(url.indexOf("?") !== -1){
13188 url += "&" + append;
13190 url += "?" + append;
13199 processSuccess : function(response){
13200 this.transaction = null;
13201 if(response.argument.form && response.argument.reset){
13202 try{ // put in try/catch since some older FF releases had problems with this
13203 response.argument.form.reset();
13206 if(this.loadScripts){
13207 this.renderer.render(this.el, response, this,
13208 this.updateComplete.createDelegate(this, [response]));
13210 this.renderer.render(this.el, response, this);
13211 this.updateComplete(response);
13215 updateComplete : function(response){
13216 this.fireEvent("update", this.el, response);
13217 if(typeof response.argument.callback == "function"){
13218 response.argument.callback(this.el, true, response);
13225 processFailure : function(response){
13226 this.transaction = null;
13227 this.fireEvent("failure", this.el, response);
13228 if(typeof response.argument.callback == "function"){
13229 response.argument.callback(this.el, false, response);
13234 * Set the content renderer for this UpdateManager. See {@link Roo.UpdateManager.BasicRenderer#render} for more details.
13235 * @param {Object} renderer The object implementing the render() method
13237 setRenderer : function(renderer){
13238 this.renderer = renderer;
13241 getRenderer : function(){
13242 return this.renderer;
13246 * Set the defaultUrl used for updates
13247 * @param {String/Function} defaultUrl The url or a function to call to get the url
13249 setDefaultUrl : function(defaultUrl){
13250 this.defaultUrl = defaultUrl;
13254 * Aborts the executing transaction
13256 abort : function(){
13257 if(this.transaction){
13258 Roo.Ajax.abort(this.transaction);
13263 * Returns true if an update is in progress
13264 * @return {Boolean}
13266 isUpdating : function(){
13267 if(this.transaction){
13268 return Roo.Ajax.isLoading(this.transaction);
13275 * @class Roo.UpdateManager.defaults
13276 * @static (not really - but it helps the doc tool)
13277 * The defaults collection enables customizing the default properties of UpdateManager
13279 Roo.UpdateManager.defaults = {
13281 * Timeout for requests or form posts in seconds (Defaults 30 seconds).
13287 * True to process scripts by default (Defaults to false).
13290 loadScripts : false,
13293 * Blank page URL to use with SSL file uploads (Defaults to "javascript:false").
13296 sslBlankUrl : (Roo.SSL_SECURE_URL || "javascript:false"),
13298 * Whether to append unique parameter on get request to disable caching (Defaults to false).
13301 disableCaching : false,
13303 * Whether to show indicatorText when loading (Defaults to true).
13306 showLoadIndicator : true,
13308 * Text for loading indicator (Defaults to '<div class="loading-indicator">Loading...</div>').
13311 indicatorText : '<div class="loading-indicator">Loading...</div>'
13315 * Static convenience method. This method is deprecated in favor of el.load({url:'foo.php', ...}).
13317 * <pre><code>Roo.UpdateManager.updateElement("my-div", "stuff.php");</code></pre>
13318 * @param {String/HTMLElement/Roo.Element} el The element to update
13319 * @param {String} url The url
13320 * @param {String/Object} params (optional) Url encoded param string or an object of name/value pairs
13321 * @param {Object} options (optional) A config object with any of the UpdateManager properties you want to set - for example: {disableCaching:true, indicatorText: "Loading data..."}
13324 * @member Roo.UpdateManager
13326 Roo.UpdateManager.updateElement = function(el, url, params, options){
13327 var um = Roo.get(el, true).getUpdateManager();
13328 Roo.apply(um, options);
13329 um.update(url, params, options ? options.callback : null);
13331 // alias for backwards compat
13332 Roo.UpdateManager.update = Roo.UpdateManager.updateElement;
13334 * @class Roo.UpdateManager.BasicRenderer
13335 * Default Content renderer. Updates the elements innerHTML with the responseText.
13337 Roo.UpdateManager.BasicRenderer = function(){};
13339 Roo.UpdateManager.BasicRenderer.prototype = {
13341 * This is called when the transaction is completed and it's time to update the element - The BasicRenderer
13342 * updates the elements innerHTML with the responseText - To perform a custom render (i.e. XML or JSON processing),
13343 * create an object with a "render(el, response)" method and pass it to setRenderer on the UpdateManager.
13344 * @param {Roo.Element} el The element being rendered
13345 * @param {Object} response The YUI Connect response object
13346 * @param {UpdateManager} updateManager The calling update manager
13347 * @param {Function} callback A callback that will need to be called if loadScripts is true on the UpdateManager
13349 render : function(el, response, updateManager, callback){
13350 el.update(response.responseText, updateManager.loadScripts, callback);
13356 * (c)) Alan Knowles
13362 * @class Roo.DomTemplate
13363 * @extends Roo.Template
13364 * An effort at a dom based template engine..
13366 * Similar to XTemplate, except it uses dom parsing to create the template..
13368 * Supported features:
13373 {a_variable} - output encoded.
13374 {a_variable.format:("Y-m-d")} - call a method on the variable
13375 {a_variable:raw} - unencoded output
13376 {a_variable:toFixed(1,2)} - Roo.util.Format."toFixed"
13377 {a_variable:this.method_on_template(...)} - call a method on the template object.
13382 <div roo-for="a_variable or condition.."></div>
13383 <div roo-if="a_variable or condition"></div>
13384 <div roo-exec="some javascript"></div>
13385 <div roo-name="named_template"></div>
13390 Roo.DomTemplate = function()
13392 Roo.DomTemplate.superclass.constructor.apply(this, arguments);
13399 Roo.extend(Roo.DomTemplate, Roo.Template, {
13401 * id counter for sub templates.
13405 * flag to indicate if dom parser is inside a pre,
13406 * it will strip whitespace if not.
13411 * The various sub templates
13419 * basic tag replacing syntax
13422 * // you can fake an object call by doing this
13426 re : /(\{|\%7B)([\w-\.]+)(?:\:([\w\.]*)(?:\(([^)]*?)?\))?)?(\}|\%7D)/g,
13427 //re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
13429 iterChild : function (node, method) {
13431 var oldPre = this.inPre;
13432 if (node.tagName == 'PRE') {
13435 for( var i = 0; i < node.childNodes.length; i++) {
13436 method.call(this, node.childNodes[i]);
13438 this.inPre = oldPre;
13444 * compile the template
13446 * This is not recursive, so I'm not sure how nested templates are really going to be handled..
13449 compile: function()
13453 // covert the html into DOM...
13457 doc = document.implementation.createHTMLDocument("");
13458 doc.documentElement.innerHTML = this.html ;
13459 div = doc.documentElement;
13461 // old IE... - nasty -- it causes all sorts of issues.. with
13462 // images getting pulled from server..
13463 div = document.createElement('div');
13464 div.innerHTML = this.html;
13466 //doc.documentElement.innerHTML = htmlBody
13472 this.iterChild(div, function(n) {_t.compileNode(n, true); });
13474 var tpls = this.tpls;
13476 // create a top level template from the snippet..
13478 //Roo.log(div.innerHTML);
13485 body : div.innerHTML,
13498 Roo.each(tpls, function(tp){
13499 this.compileTpl(tp);
13500 this.tpls[tp.id] = tp;
13503 this.master = tpls[0];
13509 compileNode : function(node, istop) {
13514 // skip anything not a tag..
13515 if (node.nodeType != 1) {
13516 if (node.nodeType == 3 && !this.inPre) {
13517 // reduce white space..
13518 node.nodeValue = node.nodeValue.replace(/\s+/g, ' ');
13541 case (node.hasAttribute('roo-for')): tpl.attr = 'for'; break;
13542 case (node.hasAttribute('roo-if')): tpl.attr = 'if'; break;
13543 case (node.hasAttribute('roo-name')): tpl.attr = 'name'; break;
13544 case (node.hasAttribute('roo-exec')): tpl.attr = 'exec'; break;
13550 // just itterate children..
13551 this.iterChild(node,this.compileNode);
13554 tpl.uid = this.id++;
13555 tpl.value = node.getAttribute('roo-' + tpl.attr);
13556 node.removeAttribute('roo-'+ tpl.attr);
13557 if (tpl.attr != 'name') {
13558 var placeholder = document.createTextNode('{domtpl' + tpl.uid + '}');
13559 node.parentNode.replaceChild(placeholder, node);
13562 var placeholder = document.createElement('span');
13563 placeholder.className = 'roo-tpl-' + tpl.value;
13564 node.parentNode.replaceChild(placeholder, node);
13567 // parent now sees '{domtplXXXX}
13568 this.iterChild(node,this.compileNode);
13570 // we should now have node body...
13571 var div = document.createElement('div');
13572 div.appendChild(node);
13574 // this has the unfortunate side effect of converting tagged attributes
13575 // eg. href="{...}" into %7C...%7D
13576 // this has been fixed by searching for those combo's although it's a bit hacky..
13579 tpl.body = div.innerHTML;
13586 switch (tpl.value) {
13587 case '.': tpl.forCall = new Function('values', 'parent', 'with(values){ return values; }'); break;
13588 case '..': tpl.forCall= new Function('values', 'parent', 'with(values){ return parent; }'); break;
13589 default: tpl.forCall= new Function('values', 'parent', 'with(values){ return '+tpl.value+'; }');
13594 tpl.execCall = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
13598 tpl.ifCall = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
13602 tpl.id = tpl.value; // replace non characters???
13608 this.tpls.push(tpl);
13618 * Compile a segment of the template into a 'sub-template'
13624 compileTpl : function(tpl)
13626 var fm = Roo.util.Format;
13627 var useF = this.disableFormats !== true;
13629 var sep = Roo.isGecko ? "+\n" : ",\n";
13631 var undef = function(str) {
13632 Roo.debug && Roo.log("Property not found :" + str);
13636 //Roo.log(tpl.body);
13640 var fn = function(m, lbrace, name, format, args)
13643 //Roo.log(arguments);
13644 args = args ? args.replace(/\\'/g,"'") : args;
13645 //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
13646 if (typeof(format) == 'undefined') {
13647 format = 'htmlEncode';
13649 if (format == 'raw' ) {
13653 if(name.substr(0, 6) == 'domtpl'){
13654 return "'"+ sep +'this.applySubTemplate('+name.substr(6)+', values, parent)'+sep+"'";
13657 // build an array of options to determine if value is undefined..
13659 // basically get 'xxxx.yyyy' then do
13660 // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
13661 // (function () { Roo.log("Property not found"); return ''; })() :
13666 Roo.each(name.split('.'), function(st) {
13667 lookfor += (lookfor.length ? '.': '') + st;
13668 udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
13671 var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
13674 if(format && useF){
13676 args = args ? ',' + args : "";
13678 if(format.substr(0, 5) != "this."){
13679 format = "fm." + format + '(';
13681 format = 'this.call("'+ format.substr(5) + '", ';
13685 return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
13688 if (args && args.length) {
13689 // called with xxyx.yuu:(test,test)
13691 return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
13693 // raw.. - :raw modifier..
13694 return "'"+ sep + udef_st + name + ")"+sep+"'";
13698 // branched to use + in gecko and [].join() in others
13700 body = "tpl.compiled = function(values, parent){ with(values) { return '" +
13701 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
13704 body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
13705 body.push(tpl.body.replace(/(\r\n|\n)/g,
13706 '\\n').replace(/'/g, "\\'").replace(this.re, fn));
13707 body.push("'].join('');};};");
13708 body = body.join('');
13711 Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
13713 /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
13720 * same as applyTemplate, except it's done to one of the subTemplates
13721 * when using named templates, you can do:
13723 * var str = pl.applySubTemplate('your-name', values);
13726 * @param {Number} id of the template
13727 * @param {Object} values to apply to template
13728 * @param {Object} parent (normaly the instance of this object)
13730 applySubTemplate : function(id, values, parent)
13734 var t = this.tpls[id];
13738 if(t.ifCall && !t.ifCall.call(this, values, parent)){
13739 Roo.debug && Roo.log('if call on ' + t.value + ' return false');
13743 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-if="' + t.value + '" - ' + e.toString());
13750 if(t.execCall && t.execCall.call(this, values, parent)){
13754 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
13760 var vs = t.forCall ? t.forCall.call(this, values, parent) : values;
13761 parent = t.target ? values : parent;
13762 if(t.forCall && vs instanceof Array){
13764 for(var i = 0, len = vs.length; i < len; i++){
13766 buf[buf.length] = t.compiled.call(this, vs[i], parent);
13768 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
13770 //Roo.log(t.compiled);
13774 return buf.join('');
13777 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
13782 return t.compiled.call(this, vs, parent);
13784 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
13786 //Roo.log(t.compiled);
13794 applyTemplate : function(values){
13795 return this.master.compiled.call(this, values, {});
13796 //var s = this.subs;
13799 apply : function(){
13800 return this.applyTemplate.apply(this, arguments);
13805 Roo.DomTemplate.from = function(el){
13806 el = Roo.getDom(el);
13807 return new Roo.Domtemplate(el.value || el.innerHTML);
13810 * Ext JS Library 1.1.1
13811 * Copyright(c) 2006-2007, Ext JS, LLC.
13813 * Originally Released Under LGPL - original licence link has changed is not relivant.
13816 * <script type="text/javascript">
13820 * @class Roo.util.DelayedTask
13821 * Provides a convenient method of performing setTimeout where a new
13822 * timeout cancels the old timeout. An example would be performing validation on a keypress.
13823 * You can use this class to buffer
13824 * the keypress events for a certain number of milliseconds, and perform only if they stop
13825 * for that amount of time.
13826 * @constructor The parameters to this constructor serve as defaults and are not required.
13827 * @param {Function} fn (optional) The default function to timeout
13828 * @param {Object} scope (optional) The default scope of that timeout
13829 * @param {Array} args (optional) The default Array of arguments
13831 Roo.util.DelayedTask = function(fn, scope, args){
13832 var id = null, d, t;
13834 var call = function(){
13835 var now = new Date().getTime();
13839 fn.apply(scope, args || []);
13843 * Cancels any pending timeout and queues a new one
13844 * @param {Number} delay The milliseconds to delay
13845 * @param {Function} newFn (optional) Overrides function passed to constructor
13846 * @param {Object} newScope (optional) Overrides scope passed to constructor
13847 * @param {Array} newArgs (optional) Overrides args passed to constructor
13849 this.delay = function(delay, newFn, newScope, newArgs){
13850 if(id && delay != d){
13854 t = new Date().getTime();
13856 scope = newScope || scope;
13857 args = newArgs || args;
13859 id = setInterval(call, d);
13864 * Cancel the last queued timeout
13866 this.cancel = function(){
13874 * Ext JS Library 1.1.1
13875 * Copyright(c) 2006-2007, Ext JS, LLC.
13877 * Originally Released Under LGPL - original licence link has changed is not relivant.
13880 * <script type="text/javascript">
13883 * @class Roo.util.TaskRunner
13884 * Manage background tasks - not sure why this is better that setInterval?
13889 Roo.util.TaskRunner = function(interval){
13890 interval = interval || 10;
13891 var tasks = [], removeQueue = [];
13893 var running = false;
13895 var stopThread = function(){
13901 var startThread = function(){
13904 id = setInterval(runTasks, interval);
13908 var removeTask = function(task){
13909 removeQueue.push(task);
13915 var runTasks = function(){
13916 if(removeQueue.length > 0){
13917 for(var i = 0, len = removeQueue.length; i < len; i++){
13918 tasks.remove(removeQueue[i]);
13921 if(tasks.length < 1){
13926 var now = new Date().getTime();
13927 for(var i = 0, len = tasks.length; i < len; ++i){
13929 var itime = now - t.taskRunTime;
13930 if(t.interval <= itime){
13931 var rt = t.run.apply(t.scope || t, t.args || [++t.taskRunCount]);
13932 t.taskRunTime = now;
13933 if(rt === false || t.taskRunCount === t.repeat){
13938 if(t.duration && t.duration <= (now - t.taskStartTime)){
13945 * Queues a new task.
13946 * @param {Object} task
13948 * Task property : interval = how frequent to run.
13949 * Task object should implement
13951 * Task object may implement
13952 * function onStop()
13954 this.start = function(task){
13956 task.taskStartTime = new Date().getTime();
13957 task.taskRunTime = 0;
13958 task.taskRunCount = 0;
13964 * @param {Object} task
13966 this.stop = function(task){
13973 this.stopAll = function(){
13975 for(var i = 0, len = tasks.length; i < len; i++){
13976 if(tasks[i].onStop){
13985 Roo.TaskMgr = new Roo.util.TaskRunner();/*
13987 * Ext JS Library 1.1.1
13988 * Copyright(c) 2006-2007, Ext JS, LLC.
13990 * Originally Released Under LGPL - original licence link has changed is not relivant.
13993 * <script type="text/javascript">
13998 * @class Roo.util.MixedCollection
13999 * @extends Roo.util.Observable
14000 * A Collection class that maintains both numeric indexes and keys and exposes events.
14002 * @param {Boolean} allowFunctions True if the addAll function should add function references to the
14003 * collection (defaults to false)
14004 * @param {Function} keyFn A function that can accept an item of the type(s) stored in this MixedCollection
14005 * and return the key value for that item. This is used when available to look up the key on items that
14006 * were passed without an explicit key parameter to a MixedCollection method. Passing this parameter is
14007 * equivalent to providing an implementation for the {@link #getKey} method.
14009 Roo.util.MixedCollection = function(allowFunctions, keyFn){
14017 * Fires when the collection is cleared.
14022 * Fires when an item is added to the collection.
14023 * @param {Number} index The index at which the item was added.
14024 * @param {Object} o The item added.
14025 * @param {String} key The key associated with the added item.
14030 * Fires when an item is replaced in the collection.
14031 * @param {String} key he key associated with the new added.
14032 * @param {Object} old The item being replaced.
14033 * @param {Object} new The new item.
14038 * Fires when an item is removed from the collection.
14039 * @param {Object} o The item being removed.
14040 * @param {String} key (optional) The key associated with the removed item.
14045 this.allowFunctions = allowFunctions === true;
14047 this.getKey = keyFn;
14049 Roo.util.MixedCollection.superclass.constructor.call(this);
14052 Roo.extend(Roo.util.MixedCollection, Roo.util.Observable, {
14053 allowFunctions : false,
14056 * Adds an item to the collection.
14057 * @param {String} key The key to associate with the item
14058 * @param {Object} o The item to add.
14059 * @return {Object} The item added.
14061 add : function(key, o){
14062 if(arguments.length == 1){
14064 key = this.getKey(o);
14066 if(typeof key == "undefined" || key === null){
14068 this.items.push(o);
14069 this.keys.push(null);
14071 var old = this.map[key];
14073 return this.replace(key, o);
14076 this.items.push(o);
14078 this.keys.push(key);
14080 this.fireEvent("add", this.length-1, o, key);
14085 * MixedCollection has a generic way to fetch keys if you implement getKey.
14088 var mc = new Roo.util.MixedCollection();
14089 mc.add(someEl.dom.id, someEl);
14090 mc.add(otherEl.dom.id, otherEl);
14094 var mc = new Roo.util.MixedCollection();
14095 mc.getKey = function(el){
14101 // or via the constructor
14102 var mc = new Roo.util.MixedCollection(false, function(el){
14108 * @param o {Object} The item for which to find the key.
14109 * @return {Object} The key for the passed item.
14111 getKey : function(o){
14116 * Replaces an item in the collection.
14117 * @param {String} key The key associated with the item to replace, or the item to replace.
14118 * @param o {Object} o (optional) If the first parameter passed was a key, the item to associate with that key.
14119 * @return {Object} The new item.
14121 replace : function(key, o){
14122 if(arguments.length == 1){
14124 key = this.getKey(o);
14126 var old = this.item(key);
14127 if(typeof key == "undefined" || key === null || typeof old == "undefined"){
14128 return this.add(key, o);
14130 var index = this.indexOfKey(key);
14131 this.items[index] = o;
14133 this.fireEvent("replace", key, old, o);
14138 * Adds all elements of an Array or an Object to the collection.
14139 * @param {Object/Array} objs An Object containing properties which will be added to the collection, or
14140 * an Array of values, each of which are added to the collection.
14142 addAll : function(objs){
14143 if(arguments.length > 1 || objs instanceof Array){
14144 var args = arguments.length > 1 ? arguments : objs;
14145 for(var i = 0, len = args.length; i < len; i++){
14149 for(var key in objs){
14150 if(this.allowFunctions || typeof objs[key] != "function"){
14151 this.add(key, objs[key]);
14158 * Executes the specified function once for every item in the collection, passing each
14159 * item as the first and only parameter. returning false from the function will stop the iteration.
14160 * @param {Function} fn The function to execute for each item.
14161 * @param {Object} scope (optional) The scope in which to execute the function.
14163 each : function(fn, scope){
14164 var items = [].concat(this.items); // each safe for removal
14165 for(var i = 0, len = items.length; i < len; i++){
14166 if(fn.call(scope || items[i], items[i], i, len) === false){
14173 * Executes the specified function once for every key in the collection, passing each
14174 * key, and its associated item as the first two parameters.
14175 * @param {Function} fn The function to execute for each item.
14176 * @param {Object} scope (optional) The scope in which to execute the function.
14178 eachKey : function(fn, scope){
14179 for(var i = 0, len = this.keys.length; i < len; i++){
14180 fn.call(scope || window, this.keys[i], this.items[i], i, len);
14185 * Returns the first item in the collection which elicits a true return value from the
14186 * passed selection function.
14187 * @param {Function} fn The selection function to execute for each item.
14188 * @param {Object} scope (optional) The scope in which to execute the function.
14189 * @return {Object} The first item in the collection which returned true from the selection function.
14191 find : function(fn, scope){
14192 for(var i = 0, len = this.items.length; i < len; i++){
14193 if(fn.call(scope || window, this.items[i], this.keys[i])){
14194 return this.items[i];
14201 * Inserts an item at the specified index in the collection.
14202 * @param {Number} index The index to insert the item at.
14203 * @param {String} key The key to associate with the new item, or the item itself.
14204 * @param {Object} o (optional) If the second parameter was a key, the new item.
14205 * @return {Object} The item inserted.
14207 insert : function(index, key, o){
14208 if(arguments.length == 2){
14210 key = this.getKey(o);
14212 if(index >= this.length){
14213 return this.add(key, o);
14216 this.items.splice(index, 0, o);
14217 if(typeof key != "undefined" && key != null){
14220 this.keys.splice(index, 0, key);
14221 this.fireEvent("add", index, o, key);
14226 * Removed an item from the collection.
14227 * @param {Object} o The item to remove.
14228 * @return {Object} The item removed.
14230 remove : function(o){
14231 return this.removeAt(this.indexOf(o));
14235 * Remove an item from a specified index in the collection.
14236 * @param {Number} index The index within the collection of the item to remove.
14238 removeAt : function(index){
14239 if(index < this.length && index >= 0){
14241 var o = this.items[index];
14242 this.items.splice(index, 1);
14243 var key = this.keys[index];
14244 if(typeof key != "undefined"){
14245 delete this.map[key];
14247 this.keys.splice(index, 1);
14248 this.fireEvent("remove", o, key);
14253 * Removed an item associated with the passed key fom the collection.
14254 * @param {String} key The key of the item to remove.
14256 removeKey : function(key){
14257 return this.removeAt(this.indexOfKey(key));
14261 * Returns the number of items in the collection.
14262 * @return {Number} the number of items in the collection.
14264 getCount : function(){
14265 return this.length;
14269 * Returns index within the collection of the passed Object.
14270 * @param {Object} o The item to find the index of.
14271 * @return {Number} index of the item.
14273 indexOf : function(o){
14274 if(!this.items.indexOf){
14275 for(var i = 0, len = this.items.length; i < len; i++){
14276 if(this.items[i] == o) {
14282 return this.items.indexOf(o);
14287 * Returns index within the collection of the passed key.
14288 * @param {String} key The key to find the index of.
14289 * @return {Number} index of the key.
14291 indexOfKey : function(key){
14292 if(!this.keys.indexOf){
14293 for(var i = 0, len = this.keys.length; i < len; i++){
14294 if(this.keys[i] == key) {
14300 return this.keys.indexOf(key);
14305 * Returns the item associated with the passed key OR index. Key has priority over index.
14306 * @param {String/Number} key The key or index of the item.
14307 * @return {Object} The item associated with the passed key.
14309 item : function(key){
14310 if (key === 'length') {
14313 var item = typeof this.map[key] != "undefined" ? this.map[key] : this.items[key];
14314 return typeof item != 'function' || this.allowFunctions ? item : null; // for prototype!
14318 * Returns the item at the specified index.
14319 * @param {Number} index The index of the item.
14322 itemAt : function(index){
14323 return this.items[index];
14327 * Returns the item associated with the passed key.
14328 * @param {String/Number} key The key of the item.
14329 * @return {Object} The item associated with the passed key.
14331 key : function(key){
14332 return this.map[key];
14336 * Returns true if the collection contains the passed Object as an item.
14337 * @param {Object} o The Object to look for in the collection.
14338 * @return {Boolean} True if the collection contains the Object as an item.
14340 contains : function(o){
14341 return this.indexOf(o) != -1;
14345 * Returns true if the collection contains the passed Object as a key.
14346 * @param {String} key The key to look for in the collection.
14347 * @return {Boolean} True if the collection contains the Object as a key.
14349 containsKey : function(key){
14350 return typeof this.map[key] != "undefined";
14354 * Removes all items from the collection.
14356 clear : function(){
14361 this.fireEvent("clear");
14365 * Returns the first item in the collection.
14366 * @return {Object} the first item in the collection..
14368 first : function(){
14369 return this.items[0];
14373 * Returns the last item in the collection.
14374 * @return {Object} the last item in the collection..
14377 return this.items[this.length-1];
14380 _sort : function(property, dir, fn){
14381 var dsc = String(dir).toUpperCase() == "DESC" ? -1 : 1;
14382 fn = fn || function(a, b){
14385 var c = [], k = this.keys, items = this.items;
14386 for(var i = 0, len = items.length; i < len; i++){
14387 c[c.length] = {key: k[i], value: items[i], index: i};
14389 c.sort(function(a, b){
14390 var v = fn(a[property], b[property]) * dsc;
14392 v = (a.index < b.index ? -1 : 1);
14396 for(var i = 0, len = c.length; i < len; i++){
14397 items[i] = c[i].value;
14400 this.fireEvent("sort", this);
14404 * Sorts this collection with the passed comparison function
14405 * @param {String} direction (optional) "ASC" or "DESC"
14406 * @param {Function} fn (optional) comparison function
14408 sort : function(dir, fn){
14409 this._sort("value", dir, fn);
14413 * Sorts this collection by keys
14414 * @param {String} direction (optional) "ASC" or "DESC"
14415 * @param {Function} fn (optional) a comparison function (defaults to case insensitive string)
14417 keySort : function(dir, fn){
14418 this._sort("key", dir, fn || function(a, b){
14419 return String(a).toUpperCase()-String(b).toUpperCase();
14424 * Returns a range of items in this collection
14425 * @param {Number} startIndex (optional) defaults to 0
14426 * @param {Number} endIndex (optional) default to the last item
14427 * @return {Array} An array of items
14429 getRange : function(start, end){
14430 var items = this.items;
14431 if(items.length < 1){
14434 start = start || 0;
14435 end = Math.min(typeof end == "undefined" ? this.length-1 : end, this.length-1);
14438 for(var i = start; i <= end; i++) {
14439 r[r.length] = items[i];
14442 for(var i = start; i >= end; i--) {
14443 r[r.length] = items[i];
14450 * Filter the <i>objects</i> in this collection by a specific property.
14451 * Returns a new collection that has been filtered.
14452 * @param {String} property A property on your objects
14453 * @param {String/RegExp} value Either string that the property values
14454 * should start with or a RegExp to test against the property
14455 * @return {MixedCollection} The new filtered collection
14457 filter : function(property, value){
14458 if(!value.exec){ // not a regex
14459 value = String(value);
14460 if(value.length == 0){
14461 return this.clone();
14463 value = new RegExp("^" + Roo.escapeRe(value), "i");
14465 return this.filterBy(function(o){
14466 return o && value.test(o[property]);
14471 * Filter by a function. * Returns a new collection that has been filtered.
14472 * The passed function will be called with each
14473 * object in the collection. If the function returns true, the value is included
14474 * otherwise it is filtered.
14475 * @param {Function} fn The function to be called, it will receive the args o (the object), k (the key)
14476 * @param {Object} scope (optional) The scope of the function (defaults to this)
14477 * @return {MixedCollection} The new filtered collection
14479 filterBy : function(fn, scope){
14480 var r = new Roo.util.MixedCollection();
14481 r.getKey = this.getKey;
14482 var k = this.keys, it = this.items;
14483 for(var i = 0, len = it.length; i < len; i++){
14484 if(fn.call(scope||this, it[i], k[i])){
14485 r.add(k[i], it[i]);
14492 * Creates a duplicate of this collection
14493 * @return {MixedCollection}
14495 clone : function(){
14496 var r = new Roo.util.MixedCollection();
14497 var k = this.keys, it = this.items;
14498 for(var i = 0, len = it.length; i < len; i++){
14499 r.add(k[i], it[i]);
14501 r.getKey = this.getKey;
14506 * Returns the item associated with the passed key or index.
14508 * @param {String/Number} key The key or index of the item.
14509 * @return {Object} The item associated with the passed key.
14511 Roo.util.MixedCollection.prototype.get = Roo.util.MixedCollection.prototype.item;/*
14513 * Ext JS Library 1.1.1
14514 * Copyright(c) 2006-2007, Ext JS, LLC.
14516 * Originally Released Under LGPL - original licence link has changed is not relivant.
14519 * <script type="text/javascript">
14522 * @class Roo.util.JSON
14523 * Modified version of Douglas Crockford"s json.js that doesn"t
14524 * mess with the Object prototype
14525 * http://www.json.org/js.html
14528 Roo.util.JSON = new (function(){
14529 var useHasOwn = {}.hasOwnProperty ? true : false;
14531 // crashes Safari in some instances
14532 //var validRE = /^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/;
14534 var pad = function(n) {
14535 return n < 10 ? "0" + n : n;
14548 var encodeString = function(s){
14549 if (/["\\\x00-\x1f]/.test(s)) {
14550 return '"' + s.replace(/([\x00-\x1f\\"])/g, function(a, b) {
14555 c = b.charCodeAt();
14557 Math.floor(c / 16).toString(16) +
14558 (c % 16).toString(16);
14561 return '"' + s + '"';
14564 var encodeArray = function(o){
14565 var a = ["["], b, i, l = o.length, v;
14566 for (i = 0; i < l; i += 1) {
14568 switch (typeof v) {
14577 a.push(v === null ? "null" : Roo.util.JSON.encode(v));
14585 var encodeDate = function(o){
14586 return '"' + o.getFullYear() + "-" +
14587 pad(o.getMonth() + 1) + "-" +
14588 pad(o.getDate()) + "T" +
14589 pad(o.getHours()) + ":" +
14590 pad(o.getMinutes()) + ":" +
14591 pad(o.getSeconds()) + '"';
14595 * Encodes an Object, Array or other value
14596 * @param {Mixed} o The variable to encode
14597 * @return {String} The JSON string
14599 this.encode = function(o)
14601 // should this be extended to fully wrap stringify..
14603 if(typeof o == "undefined" || o === null){
14605 }else if(o instanceof Array){
14606 return encodeArray(o);
14607 }else if(o instanceof Date){
14608 return encodeDate(o);
14609 }else if(typeof o == "string"){
14610 return encodeString(o);
14611 }else if(typeof o == "number"){
14612 return isFinite(o) ? String(o) : "null";
14613 }else if(typeof o == "boolean"){
14616 var a = ["{"], b, i, v;
14618 if(!useHasOwn || o.hasOwnProperty(i)) {
14620 switch (typeof v) {
14629 a.push(this.encode(i), ":",
14630 v === null ? "null" : this.encode(v));
14641 * Decodes (parses) a JSON string to an object. If the JSON is invalid, this function throws a SyntaxError.
14642 * @param {String} json The JSON string
14643 * @return {Object} The resulting object
14645 this.decode = function(json){
14647 return /** eval:var:json */ eval("(" + json + ')');
14651 * Shorthand for {@link Roo.util.JSON#encode}
14652 * @member Roo encode
14654 Roo.encode = typeof(JSON) != 'undefined' && JSON.stringify ? JSON.stringify : Roo.util.JSON.encode;
14656 * Shorthand for {@link Roo.util.JSON#decode}
14657 * @member Roo decode
14659 Roo.decode = typeof(JSON) != 'undefined' && JSON.parse ? JSON.parse : Roo.util.JSON.decode;
14662 * Ext JS Library 1.1.1
14663 * Copyright(c) 2006-2007, Ext JS, LLC.
14665 * Originally Released Under LGPL - original licence link has changed is not relivant.
14668 * <script type="text/javascript">
14672 * @class Roo.util.Format
14673 * Reusable data formatting functions
14676 Roo.util.Format = function(){
14677 var trimRe = /^\s+|\s+$/g;
14680 * Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length
14681 * @param {String} value The string to truncate
14682 * @param {Number} length The maximum length to allow before truncating
14683 * @return {String} The converted text
14685 ellipsis : function(value, len){
14686 if(value && value.length > len){
14687 return value.substr(0, len-3)+"...";
14693 * Checks a reference and converts it to empty string if it is undefined
14694 * @param {Mixed} value Reference to check
14695 * @return {Mixed} Empty string if converted, otherwise the original value
14697 undef : function(value){
14698 return typeof value != "undefined" ? value : "";
14702 * Convert certain characters (&, <, >, and ') to their HTML character equivalents for literal display in web pages.
14703 * @param {String} value The string to encode
14704 * @return {String} The encoded text
14706 htmlEncode : function(value){
14707 return !value ? value : String(value).replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, """);
14711 * Convert certain characters (&, <, >, and ') from their HTML character equivalents.
14712 * @param {String} value The string to decode
14713 * @return {String} The decoded text
14715 htmlDecode : function(value){
14716 return !value ? value : String(value).replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, '"');
14720 * Trims any whitespace from either side of a string
14721 * @param {String} value The text to trim
14722 * @return {String} The trimmed text
14724 trim : function(value){
14725 return String(value).replace(trimRe, "");
14729 * Returns a substring from within an original string
14730 * @param {String} value The original text
14731 * @param {Number} start The start index of the substring
14732 * @param {Number} length The length of the substring
14733 * @return {String} The substring
14735 substr : function(value, start, length){
14736 return String(value).substr(start, length);
14740 * Converts a string to all lower case letters
14741 * @param {String} value The text to convert
14742 * @return {String} The converted text
14744 lowercase : function(value){
14745 return String(value).toLowerCase();
14749 * Converts a string to all upper case letters
14750 * @param {String} value The text to convert
14751 * @return {String} The converted text
14753 uppercase : function(value){
14754 return String(value).toUpperCase();
14758 * Converts the first character only of a string to upper case
14759 * @param {String} value The text to convert
14760 * @return {String} The converted text
14762 capitalize : function(value){
14763 return !value ? value : value.charAt(0).toUpperCase() + value.substr(1).toLowerCase();
14767 call : function(value, fn){
14768 if(arguments.length > 2){
14769 var args = Array.prototype.slice.call(arguments, 2);
14770 args.unshift(value);
14772 return /** eval:var:value */ eval(fn).apply(window, args);
14774 /** eval:var:value */
14775 return /** eval:var:value */ eval(fn).call(window, value);
14781 * safer version of Math.toFixed..??/
14782 * @param {Number/String} value The numeric value to format
14783 * @param {Number/String} value Decimal places
14784 * @return {String} The formatted currency string
14786 toFixed : function(v, n)
14788 // why not use to fixed - precision is buggered???
14790 return Math.round(v-0);
14792 var fact = Math.pow(10,n+1);
14793 v = (Math.round((v-0)*fact))/fact;
14794 var z = (''+fact).substring(2);
14795 if (v == Math.floor(v)) {
14796 return Math.floor(v) + '.' + z;
14799 // now just padd decimals..
14800 var ps = String(v).split('.');
14801 var fd = (ps[1] + z);
14802 var r = fd.substring(0,n);
14803 var rm = fd.substring(n);
14805 return ps[0] + '.' + r;
14807 r*=1; // turn it into a number;
14809 if (String(r).length != n) {
14812 r = String(r).substring(1); // chop the end off.
14815 return ps[0] + '.' + r;
14820 * Format a number as US currency
14821 * @param {Number/String} value The numeric value to format
14822 * @return {String} The formatted currency string
14824 usMoney : function(v){
14825 return '$' + Roo.util.Format.number(v);
14830 * eventually this should probably emulate php's number_format
14831 * @param {Number/String} value The numeric value to format
14832 * @param {Number} decimals number of decimal places
14833 * @param {String} delimiter for thousands (default comma)
14834 * @return {String} The formatted currency string
14836 number : function(v, decimals, thousandsDelimiter)
14838 // multiply and round.
14839 decimals = typeof(decimals) == 'undefined' ? 2 : decimals;
14840 thousandsDelimiter = typeof(thousandsDelimiter) == 'undefined' ? ',' : thousandsDelimiter;
14842 var mul = Math.pow(10, decimals);
14843 var zero = String(mul).substring(1);
14844 v = (Math.round((v-0)*mul))/mul;
14846 // if it's '0' number.. then
14848 //v = (v == Math.floor(v)) ? v + "." + zero : ((v*10 == Math.floor(v*10)) ? v + "0" : v);
14850 var ps = v.split('.');
14853 var r = /(\d+)(\d{3})/;
14856 if(thousandsDelimiter.length != 0) {
14857 whole = whole.replace(/\B(?=(\d{3})+(?!\d))/g, thousandsDelimiter );
14862 (decimals ? ('.'+ ps[1] + zero.substring(ps[1].length)) : '') :
14863 // does not have decimals
14864 (decimals ? ('.' + zero) : '');
14867 return whole + sub ;
14871 * Parse a value into a formatted date using the specified format pattern.
14872 * @param {Mixed} value The value to format
14873 * @param {String} format (optional) Any valid date format string (defaults to 'm/d/Y')
14874 * @return {String} The formatted date string
14876 date : function(v, format){
14880 if(!(v instanceof Date)){
14881 v = new Date(Date.parse(v));
14883 return v.dateFormat(format || Roo.util.Format.defaults.date);
14887 * Returns a date rendering function that can be reused to apply a date format multiple times efficiently
14888 * @param {String} format Any valid date format string
14889 * @return {Function} The date formatting function
14891 dateRenderer : function(format){
14892 return function(v){
14893 return Roo.util.Format.date(v, format);
14898 stripTagsRE : /<\/?[^>]+>/gi,
14901 * Strips all HTML tags
14902 * @param {Mixed} value The text from which to strip tags
14903 * @return {String} The stripped text
14905 stripTags : function(v){
14906 return !v ? v : String(v).replace(this.stripTagsRE, "");
14910 * Size in Mb,Gb etc.
14911 * @param {Number} value The number to be formated
14912 * @param {number} decimals how many decimal places
14913 * @return {String} the formated string
14915 size : function(value, decimals)
14917 var sizes = ['b', 'k', 'M', 'G', 'T'];
14921 var i = parseInt(Math.floor(Math.log(value) / Math.log(1024)));
14922 return Roo.util.Format.number(value/ Math.pow(1024, i) ,decimals) + sizes[i];
14929 Roo.util.Format.defaults = {
14933 * Ext JS Library 1.1.1
14934 * Copyright(c) 2006-2007, Ext JS, LLC.
14936 * Originally Released Under LGPL - original licence link has changed is not relivant.
14939 * <script type="text/javascript">
14946 * @class Roo.MasterTemplate
14947 * @extends Roo.Template
14948 * Provides a template that can have child templates. The syntax is:
14950 var t = new Roo.MasterTemplate(
14951 '<select name="{name}">',
14952 '<tpl name="options"><option value="{value:trim}">{text:ellipsis(10)}</option></tpl>',
14955 t.add('options', {value: 'foo', text: 'bar'});
14956 // or you can add multiple child elements in one shot
14957 t.addAll('options', [
14958 {value: 'foo', text: 'bar'},
14959 {value: 'foo2', text: 'bar2'},
14960 {value: 'foo3', text: 'bar3'}
14962 // then append, applying the master template values
14963 t.append('my-form', {name: 'my-select'});
14965 * A name attribute for the child template is not required if you have only one child
14966 * template or you want to refer to them by index.
14968 Roo.MasterTemplate = function(){
14969 Roo.MasterTemplate.superclass.constructor.apply(this, arguments);
14970 this.originalHtml = this.html;
14972 var m, re = this.subTemplateRe;
14975 while(m = re.exec(this.html)){
14976 var name = m[1], content = m[2];
14981 tpl : new Roo.Template(content)
14984 st[name] = st[subIndex];
14986 st[subIndex].tpl.compile();
14987 st[subIndex].tpl.call = this.call.createDelegate(this);
14990 this.subCount = subIndex;
14993 Roo.extend(Roo.MasterTemplate, Roo.Template, {
14995 * The regular expression used to match sub templates
14999 subTemplateRe : /<tpl(?:\sname="([\w-]+)")?>((?:.|\n)*?)<\/tpl>/gi,
15002 * Applies the passed values to a child template.
15003 * @param {String/Number} name (optional) The name or index of the child template
15004 * @param {Array/Object} values The values to be applied to the template
15005 * @return {MasterTemplate} this
15007 add : function(name, values){
15008 if(arguments.length == 1){
15009 values = arguments[0];
15012 var s = this.subs[name];
15013 s.buffer[s.buffer.length] = s.tpl.apply(values);
15018 * Applies all the passed values to a child template.
15019 * @param {String/Number} name (optional) The name or index of the child template
15020 * @param {Array} values The values to be applied to the template, this should be an array of objects.
15021 * @param {Boolean} reset (optional) True to reset the template first
15022 * @return {MasterTemplate} this
15024 fill : function(name, values, reset){
15026 if(a.length == 1 || (a.length == 2 && typeof a[1] == "boolean")){
15034 for(var i = 0, len = values.length; i < len; i++){
15035 this.add(name, values[i]);
15041 * Resets the template for reuse
15042 * @return {MasterTemplate} this
15044 reset : function(){
15046 for(var i = 0; i < this.subCount; i++){
15052 applyTemplate : function(values){
15054 var replaceIndex = -1;
15055 this.html = this.originalHtml.replace(this.subTemplateRe, function(m, name){
15056 return s[++replaceIndex].buffer.join("");
15058 return Roo.MasterTemplate.superclass.applyTemplate.call(this, values);
15061 apply : function(){
15062 return this.applyTemplate.apply(this, arguments);
15065 compile : function(){return this;}
15069 * Alias for fill().
15072 Roo.MasterTemplate.prototype.addAll = Roo.MasterTemplate.prototype.fill;
15074 * Creates a template from the passed element's value (display:none textarea, preferred) or innerHTML. e.g.
15075 * var tpl = Roo.MasterTemplate.from('element-id');
15076 * @param {String/HTMLElement} el
15077 * @param {Object} config
15080 Roo.MasterTemplate.from = function(el, config){
15081 el = Roo.getDom(el);
15082 return new Roo.MasterTemplate(el.value || el.innerHTML, config || '');
15085 * Ext JS Library 1.1.1
15086 * Copyright(c) 2006-2007, Ext JS, LLC.
15088 * Originally Released Under LGPL - original licence link has changed is not relivant.
15091 * <script type="text/javascript">
15096 * @class Roo.util.CSS
15097 * Utility class for manipulating CSS rules
15101 Roo.util.CSS = function(){
15103 var doc = document;
15105 var camelRe = /(-[a-z])/gi;
15106 var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); };
15110 * Very simple dynamic creation of stylesheets from a text blob of rules. The text will wrapped in a style
15111 * tag and appended to the HEAD of the document.
15112 * @param {String|Object} cssText The text containing the css rules
15113 * @param {String} id An id to add to the stylesheet for later removal
15114 * @return {StyleSheet}
15116 createStyleSheet : function(cssText, id){
15118 var head = doc.getElementsByTagName("head")[0];
15119 var nrules = doc.createElement("style");
15120 nrules.setAttribute("type", "text/css");
15122 nrules.setAttribute("id", id);
15124 if (typeof(cssText) != 'string') {
15125 // support object maps..
15126 // not sure if this a good idea..
15127 // perhaps it should be merged with the general css handling
15128 // and handle js style props.
15129 var cssTextNew = [];
15130 for(var n in cssText) {
15132 for(var k in cssText[n]) {
15133 citems.push( k + ' : ' +cssText[n][k] + ';' );
15135 cssTextNew.push( n + ' { ' + citems.join(' ') + '} ');
15138 cssText = cssTextNew.join("\n");
15144 head.appendChild(nrules);
15145 ss = nrules.styleSheet;
15146 ss.cssText = cssText;
15149 nrules.appendChild(doc.createTextNode(cssText));
15151 nrules.cssText = cssText;
15153 head.appendChild(nrules);
15154 ss = nrules.styleSheet ? nrules.styleSheet : (nrules.sheet || doc.styleSheets[doc.styleSheets.length-1]);
15156 this.cacheStyleSheet(ss);
15161 * Removes a style or link tag by id
15162 * @param {String} id The id of the tag
15164 removeStyleSheet : function(id){
15165 var existing = doc.getElementById(id);
15167 existing.parentNode.removeChild(existing);
15172 * Dynamically swaps an existing stylesheet reference for a new one
15173 * @param {String} id The id of an existing link tag to remove
15174 * @param {String} url The href of the new stylesheet to include
15176 swapStyleSheet : function(id, url){
15177 this.removeStyleSheet(id);
15178 var ss = doc.createElement("link");
15179 ss.setAttribute("rel", "stylesheet");
15180 ss.setAttribute("type", "text/css");
15181 ss.setAttribute("id", id);
15182 ss.setAttribute("href", url);
15183 doc.getElementsByTagName("head")[0].appendChild(ss);
15187 * Refresh the rule cache if you have dynamically added stylesheets
15188 * @return {Object} An object (hash) of rules indexed by selector
15190 refreshCache : function(){
15191 return this.getRules(true);
15195 cacheStyleSheet : function(stylesheet){
15199 try{// try catch for cross domain access issue
15200 var ssRules = stylesheet.cssRules || stylesheet.rules;
15201 for(var j = ssRules.length-1; j >= 0; --j){
15202 rules[ssRules[j].selectorText] = ssRules[j];
15208 * Gets all css rules for the document
15209 * @param {Boolean} refreshCache true to refresh the internal cache
15210 * @return {Object} An object (hash) of rules indexed by selector
15212 getRules : function(refreshCache){
15213 if(rules == null || refreshCache){
15215 var ds = doc.styleSheets;
15216 for(var i =0, len = ds.length; i < len; i++){
15218 this.cacheStyleSheet(ds[i]);
15226 * Gets an an individual CSS rule by selector(s)
15227 * @param {String/Array} selector The CSS selector or an array of selectors to try. The first selector that is found is returned.
15228 * @param {Boolean} refreshCache true to refresh the internal cache if you have recently updated any rules or added styles dynamically
15229 * @return {CSSRule} The CSS rule or null if one is not found
15231 getRule : function(selector, refreshCache){
15232 var rs = this.getRules(refreshCache);
15233 if(!(selector instanceof Array)){
15234 return rs[selector];
15236 for(var i = 0; i < selector.length; i++){
15237 if(rs[selector[i]]){
15238 return rs[selector[i]];
15246 * Updates a rule property
15247 * @param {String/Array} selector If it's an array it tries each selector until it finds one. Stops immediately once one is found.
15248 * @param {String} property The css property
15249 * @param {String} value The new value for the property
15250 * @return {Boolean} true If a rule was found and updated
15252 updateRule : function(selector, property, value){
15253 if(!(selector instanceof Array)){
15254 var rule = this.getRule(selector);
15256 rule.style[property.replace(camelRe, camelFn)] = value;
15260 for(var i = 0; i < selector.length; i++){
15261 if(this.updateRule(selector[i], property, value)){
15271 * Ext JS Library 1.1.1
15272 * Copyright(c) 2006-2007, Ext JS, LLC.
15274 * Originally Released Under LGPL - original licence link has changed is not relivant.
15277 * <script type="text/javascript">
15283 * @class Roo.util.ClickRepeater
15284 * @extends Roo.util.Observable
15286 * A wrapper class which can be applied to any element. Fires a "click" event while the
15287 * mouse is pressed. The interval between firings may be specified in the config but
15288 * defaults to 10 milliseconds.
15290 * Optionally, a CSS class may be applied to the element during the time it is pressed.
15292 * @cfg {String/HTMLElement/Element} el The element to act as a button.
15293 * @cfg {Number} delay The initial delay before the repeating event begins firing.
15294 * Similar to an autorepeat key delay.
15295 * @cfg {Number} interval The interval between firings of the "click" event. Default 10 ms.
15296 * @cfg {String} pressClass A CSS class name to be applied to the element while pressed.
15297 * @cfg {Boolean} accelerate True if autorepeating should start slowly and accelerate.
15298 * "interval" and "delay" are ignored. "immediate" is honored.
15299 * @cfg {Boolean} preventDefault True to prevent the default click event
15300 * @cfg {Boolean} stopDefault True to stop the default click event
15303 * 2007-02-02 jvs Original code contributed by Nige "Animal" White
15304 * 2007-02-02 jvs Renamed to ClickRepeater
15305 * 2007-02-03 jvs Modifications for FF Mac and Safari
15308 * @param {String/HTMLElement/Element} el The element to listen on
15309 * @param {Object} config
15311 Roo.util.ClickRepeater = function(el, config)
15313 this.el = Roo.get(el);
15314 this.el.unselectable();
15316 Roo.apply(this, config);
15321 * Fires when the mouse button is depressed.
15322 * @param {Roo.util.ClickRepeater} this
15324 "mousedown" : true,
15327 * Fires on a specified interval during the time the element is pressed.
15328 * @param {Roo.util.ClickRepeater} this
15333 * Fires when the mouse key is released.
15334 * @param {Roo.util.ClickRepeater} this
15339 this.el.on("mousedown", this.handleMouseDown, this);
15340 if(this.preventDefault || this.stopDefault){
15341 this.el.on("click", function(e){
15342 if(this.preventDefault){
15343 e.preventDefault();
15345 if(this.stopDefault){
15351 // allow inline handler
15353 this.on("click", this.handler, this.scope || this);
15356 Roo.util.ClickRepeater.superclass.constructor.call(this);
15359 Roo.extend(Roo.util.ClickRepeater, Roo.util.Observable, {
15362 preventDefault : true,
15363 stopDefault : false,
15367 handleMouseDown : function(){
15368 clearTimeout(this.timer);
15370 if(this.pressClass){
15371 this.el.addClass(this.pressClass);
15373 this.mousedownTime = new Date();
15375 Roo.get(document).on("mouseup", this.handleMouseUp, this);
15376 this.el.on("mouseout", this.handleMouseOut, this);
15378 this.fireEvent("mousedown", this);
15379 this.fireEvent("click", this);
15381 this.timer = this.click.defer(this.delay || this.interval, this);
15385 click : function(){
15386 this.fireEvent("click", this);
15387 this.timer = this.click.defer(this.getInterval(), this);
15391 getInterval: function(){
15392 if(!this.accelerate){
15393 return this.interval;
15395 var pressTime = this.mousedownTime.getElapsed();
15396 if(pressTime < 500){
15398 }else if(pressTime < 1700){
15400 }else if(pressTime < 2600){
15402 }else if(pressTime < 3500){
15404 }else if(pressTime < 4400){
15406 }else if(pressTime < 5300){
15408 }else if(pressTime < 6200){
15416 handleMouseOut : function(){
15417 clearTimeout(this.timer);
15418 if(this.pressClass){
15419 this.el.removeClass(this.pressClass);
15421 this.el.on("mouseover", this.handleMouseReturn, this);
15425 handleMouseReturn : function(){
15426 this.el.un("mouseover", this.handleMouseReturn);
15427 if(this.pressClass){
15428 this.el.addClass(this.pressClass);
15434 handleMouseUp : function(){
15435 clearTimeout(this.timer);
15436 this.el.un("mouseover", this.handleMouseReturn);
15437 this.el.un("mouseout", this.handleMouseOut);
15438 Roo.get(document).un("mouseup", this.handleMouseUp);
15439 this.el.removeClass(this.pressClass);
15440 this.fireEvent("mouseup", this);
15443 * @class Roo.util.Clipboard
15449 Roo.util.Clipboard = {
15451 * Writes a string to the clipboard - using the Clipboard API if https, otherwise using text area.
15452 * @param {String} text to copy to clipboard
15454 write : function(text) {
15455 // navigator clipboard api needs a secure context (https)
15456 if (navigator.clipboard && window.isSecureContext) {
15457 // navigator clipboard api method'
15458 navigator.clipboard.writeText(text);
15461 // text area method
15462 var ta = document.createElement("textarea");
15464 // make the textarea out of viewport
15465 ta.style.position = "fixed";
15466 ta.style.left = "-999999px";
15467 ta.style.top = "-999999px";
15468 document.body.appendChild(ta);
15471 document.execCommand('copy');
15481 * Ext JS Library 1.1.1
15482 * Copyright(c) 2006-2007, Ext JS, LLC.
15484 * Originally Released Under LGPL - original licence link has changed is not relivant.
15487 * <script type="text/javascript">
15492 * @class Roo.KeyNav
15493 * <p>Provides a convenient wrapper for normalized keyboard navigation. KeyNav allows you to bind
15494 * navigation keys to function calls that will get called when the keys are pressed, providing an easy
15495 * way to implement custom navigation schemes for any UI component.</p>
15496 * <p>The following are all of the possible keys that can be implemented: enter, left, right, up, down, tab, esc,
15497 * pageUp, pageDown, del, home, end. Usage:</p>
15499 var nav = new Roo.KeyNav("my-element", {
15500 "left" : function(e){
15501 this.moveLeft(e.ctrlKey);
15503 "right" : function(e){
15504 this.moveRight(e.ctrlKey);
15506 "enter" : function(e){
15513 * @param {String/HTMLElement/Roo.Element} el The element to bind to
15514 * @param {Object} config The config
15516 Roo.KeyNav = function(el, config){
15517 this.el = Roo.get(el);
15518 Roo.apply(this, config);
15519 if(!this.disabled){
15520 this.disabled = true;
15525 Roo.KeyNav.prototype = {
15527 * @cfg {Boolean} disabled
15528 * True to disable this KeyNav instance (defaults to false)
15532 * @cfg {String} defaultEventAction
15533 * The method to call on the {@link Roo.EventObject} after this KeyNav intercepts a key. Valid values are
15534 * {@link Roo.EventObject#stopEvent}, {@link Roo.EventObject#preventDefault} and
15535 * {@link Roo.EventObject#stopPropagation} (defaults to 'stopEvent')
15537 defaultEventAction: "stopEvent",
15539 * @cfg {Boolean} forceKeyDown
15540 * Handle the keydown event instead of keypress (defaults to false). KeyNav automatically does this for IE since
15541 * IE does not propagate special keys on keypress, but setting this to true will force other browsers to also
15542 * handle keydown instead of keypress.
15544 forceKeyDown : false,
15547 prepareEvent : function(e){
15548 var k = e.getKey();
15549 var h = this.keyToHandler[k];
15550 //if(h && this[h]){
15551 // e.stopPropagation();
15553 if(Roo.isSafari && h && k >= 37 && k <= 40){
15559 relay : function(e){
15560 var k = e.getKey();
15561 var h = this.keyToHandler[k];
15563 if(this.doRelay(e, this[h], h) !== true){
15564 e[this.defaultEventAction]();
15570 doRelay : function(e, h, hname){
15571 return h.call(this.scope || this, e);
15574 // possible handlers
15588 // quick lookup hash
15605 * Enable this KeyNav
15607 enable: function(){
15609 // ie won't do special keys on keypress, no one else will repeat keys with keydown
15610 // the EventObject will normalize Safari automatically
15611 if(this.forceKeyDown || Roo.isIE || Roo.isAir){
15612 this.el.on("keydown", this.relay, this);
15614 this.el.on("keydown", this.prepareEvent, this);
15615 this.el.on("keypress", this.relay, this);
15617 this.disabled = false;
15622 * Disable this KeyNav
15624 disable: function(){
15625 if(!this.disabled){
15626 if(this.forceKeyDown || Roo.isIE || Roo.isAir){
15627 this.el.un("keydown", this.relay);
15629 this.el.un("keydown", this.prepareEvent);
15630 this.el.un("keypress", this.relay);
15632 this.disabled = true;
15637 * Ext JS Library 1.1.1
15638 * Copyright(c) 2006-2007, Ext JS, LLC.
15640 * Originally Released Under LGPL - original licence link has changed is not relivant.
15643 * <script type="text/javascript">
15648 * @class Roo.KeyMap
15649 * Handles mapping keys to actions for an element. One key map can be used for multiple actions.
15650 * The constructor accepts the same config object as defined by {@link #addBinding}.
15651 * If you bind a callback function to a KeyMap, anytime the KeyMap handles an expected key
15652 * combination it will call the function with this signature (if the match is a multi-key
15653 * combination the callback will still be called only once): (String key, Roo.EventObject e)
15654 * A KeyMap can also handle a string representation of keys.<br />
15657 // map one key by key code
15658 var map = new Roo.KeyMap("my-element", {
15659 key: 13, // or Roo.EventObject.ENTER
15664 // map multiple keys to one action by string
15665 var map = new Roo.KeyMap("my-element", {
15671 // map multiple keys to multiple actions by strings and array of codes
15672 var map = new Roo.KeyMap("my-element", [
15675 fn: function(){ alert("Return was pressed"); }
15678 fn: function(){ alert('a, b or c was pressed'); }
15683 fn: function(){ alert('Control + shift + tab was pressed.'); }
15687 * <b>Note: A KeyMap starts enabled</b>
15689 * @param {String/HTMLElement/Roo.Element} el The element to bind to
15690 * @param {Object} config The config (see {@link #addBinding})
15691 * @param {String} eventName (optional) The event to bind to (defaults to "keydown")
15693 Roo.KeyMap = function(el, config, eventName){
15694 this.el = Roo.get(el);
15695 this.eventName = eventName || "keydown";
15696 this.bindings = [];
15698 this.addBinding(config);
15703 Roo.KeyMap.prototype = {
15705 * True to stop the event from bubbling and prevent the default browser action if the
15706 * key was handled by the KeyMap (defaults to false)
15712 * Add a new binding to this KeyMap. The following config object properties are supported:
15714 Property Type Description
15715 ---------- --------------- ----------------------------------------------------------------------
15716 key String/Array A single keycode or an array of keycodes to handle
15717 shift Boolean True to handle key only when shift is pressed (defaults to false)
15718 ctrl Boolean True to handle key only when ctrl is pressed (defaults to false)
15719 alt Boolean True to handle key only when alt is pressed (defaults to false)
15720 fn Function The function to call when KeyMap finds the expected key combination
15721 scope Object The scope of the callback function
15727 var map = new Roo.KeyMap(document, {
15728 key: Roo.EventObject.ENTER,
15733 //Add a new binding to the existing KeyMap later
15741 * @param {Object/Array} config A single KeyMap config or an array of configs
15743 addBinding : function(config){
15744 if(config instanceof Array){
15745 for(var i = 0, len = config.length; i < len; i++){
15746 this.addBinding(config[i]);
15750 var keyCode = config.key,
15751 shift = config.shift,
15752 ctrl = config.ctrl,
15755 scope = config.scope;
15756 if(typeof keyCode == "string"){
15758 var keyString = keyCode.toUpperCase();
15759 for(var j = 0, len = keyString.length; j < len; j++){
15760 ks.push(keyString.charCodeAt(j));
15764 var keyArray = keyCode instanceof Array;
15765 var handler = function(e){
15766 if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) && (!alt || e.altKey)){
15767 var k = e.getKey();
15769 for(var i = 0, len = keyCode.length; i < len; i++){
15770 if(keyCode[i] == k){
15771 if(this.stopEvent){
15774 fn.call(scope || window, k, e);
15780 if(this.stopEvent){
15783 fn.call(scope || window, k, e);
15788 this.bindings.push(handler);
15792 * Shorthand for adding a single key listener
15793 * @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the
15794 * following options:
15795 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
15796 * @param {Function} fn The function to call
15797 * @param {Object} scope (optional) The scope of the function
15799 on : function(key, fn, scope){
15800 var keyCode, shift, ctrl, alt;
15801 if(typeof key == "object" && !(key instanceof Array)){
15820 handleKeyDown : function(e){
15821 if(this.enabled){ //just in case
15822 var b = this.bindings;
15823 for(var i = 0, len = b.length; i < len; i++){
15824 b[i].call(this, e);
15830 * Returns true if this KeyMap is enabled
15831 * @return {Boolean}
15833 isEnabled : function(){
15834 return this.enabled;
15838 * Enables this KeyMap
15840 enable: function(){
15842 this.el.on(this.eventName, this.handleKeyDown, this);
15843 this.enabled = true;
15848 * Disable this KeyMap
15850 disable: function(){
15852 this.el.removeListener(this.eventName, this.handleKeyDown, this);
15853 this.enabled = false;
15858 * Ext JS Library 1.1.1
15859 * Copyright(c) 2006-2007, Ext JS, LLC.
15861 * Originally Released Under LGPL - original licence link has changed is not relivant.
15864 * <script type="text/javascript">
15869 * @class Roo.util.TextMetrics
15870 * Provides precise pixel measurements for blocks of text so that you can determine exactly how high and
15871 * wide, in pixels, a given block of text will be.
15874 Roo.util.TextMetrics = function(){
15878 * Measures the size of the specified text
15879 * @param {String/HTMLElement} el The element, dom node or id from which to copy existing CSS styles
15880 * that can affect the size of the rendered text
15881 * @param {String} text The text to measure
15882 * @param {Number} fixedWidth (optional) If the text will be multiline, you have to set a fixed width
15883 * in order to accurately measure the text height
15884 * @return {Object} An object containing the text's size {width: (width), height: (height)}
15886 measure : function(el, text, fixedWidth){
15888 shared = Roo.util.TextMetrics.Instance(el, fixedWidth);
15891 shared.setFixedWidth(fixedWidth || 'auto');
15892 return shared.getSize(text);
15896 * Return a unique TextMetrics instance that can be bound directly to an element and reused. This reduces
15897 * the overhead of multiple calls to initialize the style properties on each measurement.
15898 * @param {String/HTMLElement} el The element, dom node or id that the instance will be bound to
15899 * @param {Number} fixedWidth (optional) If the text will be multiline, you have to set a fixed width
15900 * in order to accurately measure the text height
15901 * @return {Roo.util.TextMetrics.Instance} instance The new instance
15903 createInstance : function(el, fixedWidth){
15904 return Roo.util.TextMetrics.Instance(el, fixedWidth);
15910 * @class Roo.util.TextMetrics.Instance
15911 * Instance of TextMetrics Calcuation
15913 * Create a new TextMetrics Instance
15914 * @param {Object} bindto
15915 * @param {Boolean} fixedWidth
15918 Roo.util.TextMetrics.Instance = function(bindTo, fixedWidth)
15920 var ml = new Roo.Element(document.createElement('div'));
15921 document.body.appendChild(ml.dom);
15922 ml.position('absolute');
15923 ml.setLeftTop(-1000, -1000);
15927 ml.setWidth(fixedWidth);
15932 * Returns the size of the specified text based on the internal element's style and width properties
15933 * @param {String} text The text to measure
15934 * @return {Object} An object containing the text's size {width: (width), height: (height)}
15936 getSize : function(text){
15938 var s = ml.getSize();
15944 * Binds this TextMetrics instance to an element from which to copy existing CSS styles
15945 * that can affect the size of the rendered text
15946 * @param {String/HTMLElement} el The element, dom node or id
15948 bind : function(el){
15950 Roo.fly(el).getStyles('font-size','font-style', 'font-weight', 'font-family','line-height')
15955 * Sets a fixed width on the internal measurement element. If the text will be multiline, you have
15956 * to set a fixed width in order to accurately measure the text height.
15957 * @param {Number} width The width to set on the element
15959 setFixedWidth : function(width){
15960 ml.setWidth(width);
15964 * Returns the measured width of the specified text
15965 * @param {String} text The text to measure
15966 * @return {Number} width The width in pixels
15968 getWidth : function(text){
15969 ml.dom.style.width = 'auto';
15970 return this.getSize(text).width;
15974 * Returns the measured height of the specified text. For multiline text, be sure to call
15975 * {@link #setFixedWidth} if necessary.
15976 * @param {String} text The text to measure
15977 * @return {Number} height The height in pixels
15979 getHeight : function(text){
15980 return this.getSize(text).height;
15984 instance.bind(bindTo);
15989 // backwards compat
15990 Roo.Element.measureText = Roo.util.TextMetrics.measure;/*
15992 * Ext JS Library 1.1.1
15993 * Copyright(c) 2006-2007, Ext JS, LLC.
15995 * Originally Released Under LGPL - original licence link has changed is not relivant.
15998 * <script type="text/javascript">
16002 * @class Roo.state.Provider
16003 * Abstract base class for state provider implementations. This class provides methods
16004 * for encoding and decoding <b>typed</b> variables including dates and defines the
16005 * Provider interface.
16007 Roo.state.Provider = function(){
16009 * @event statechange
16010 * Fires when a state change occurs.
16011 * @param {Provider} this This state provider
16012 * @param {String} key The state key which was changed
16013 * @param {String} value The encoded value for the state
16016 "statechange": true
16019 Roo.state.Provider.superclass.constructor.call(this);
16021 Roo.extend(Roo.state.Provider, Roo.util.Observable, {
16023 * Returns the current value for a key
16024 * @param {String} name The key name
16025 * @param {Mixed} defaultValue A default value to return if the key's value is not found
16026 * @return {Mixed} The state data
16028 get : function(name, defaultValue){
16029 return typeof this.state[name] == "undefined" ?
16030 defaultValue : this.state[name];
16034 * Clears a value from the state
16035 * @param {String} name The key name
16037 clear : function(name){
16038 delete this.state[name];
16039 this.fireEvent("statechange", this, name, null);
16043 * Sets the value for a key
16044 * @param {String} name The key name
16045 * @param {Mixed} value The value to set
16047 set : function(name, value){
16048 this.state[name] = value;
16049 this.fireEvent("statechange", this, name, value);
16053 * Decodes a string previously encoded with {@link #encodeValue}.
16054 * @param {String} value The value to decode
16055 * @return {Mixed} The decoded value
16057 decodeValue : function(cookie){
16058 var re = /^(a|n|d|b|s|o)\:(.*)$/;
16059 var matches = re.exec(unescape(cookie));
16060 if(!matches || !matches[1]) {
16061 return; // non state cookie
16063 var type = matches[1];
16064 var v = matches[2];
16067 return parseFloat(v);
16069 return new Date(Date.parse(v));
16074 var values = v.split("^");
16075 for(var i = 0, len = values.length; i < len; i++){
16076 all.push(this.decodeValue(values[i]));
16081 var values = v.split("^");
16082 for(var i = 0, len = values.length; i < len; i++){
16083 var kv = values[i].split("=");
16084 all[kv[0]] = this.decodeValue(kv[1]);
16093 * Encodes a value including type information. Decode with {@link #decodeValue}.
16094 * @param {Mixed} value The value to encode
16095 * @return {String} The encoded value
16097 encodeValue : function(v){
16099 if(typeof v == "number"){
16101 }else if(typeof v == "boolean"){
16102 enc = "b:" + (v ? "1" : "0");
16103 }else if(v instanceof Date){
16104 enc = "d:" + v.toGMTString();
16105 }else if(v instanceof Array){
16107 for(var i = 0, len = v.length; i < len; i++){
16108 flat += this.encodeValue(v[i]);
16114 }else if(typeof v == "object"){
16117 if(typeof v[key] != "function"){
16118 flat += key + "=" + this.encodeValue(v[key]) + "^";
16121 enc = "o:" + flat.substring(0, flat.length-1);
16125 return escape(enc);
16131 * Ext JS Library 1.1.1
16132 * Copyright(c) 2006-2007, Ext JS, LLC.
16134 * Originally Released Under LGPL - original licence link has changed is not relivant.
16137 * <script type="text/javascript">
16140 * @class Roo.state.Manager
16141 * This is the global state manager. By default all components that are "state aware" check this class
16142 * for state information if you don't pass them a custom state provider. In order for this class
16143 * to be useful, it must be initialized with a provider when your application initializes.
16145 // in your initialization function
16147 Roo.state.Manager.setProvider(new Roo.state.CookieProvider());
16149 // supposed you have a {@link Roo.BorderLayout}
16150 var layout = new Roo.BorderLayout(...);
16151 layout.restoreState();
16152 // or a {Roo.BasicDialog}
16153 var dialog = new Roo.BasicDialog(...);
16154 dialog.restoreState();
16158 Roo.state.Manager = function(){
16159 var provider = new Roo.state.Provider();
16163 * Configures the default state provider for your application
16164 * @param {Provider} stateProvider The state provider to set
16166 setProvider : function(stateProvider){
16167 provider = stateProvider;
16171 * Returns the current value for a key
16172 * @param {String} name The key name
16173 * @param {Mixed} defaultValue The default value to return if the key lookup does not match
16174 * @return {Mixed} The state data
16176 get : function(key, defaultValue){
16177 return provider.get(key, defaultValue);
16181 * Sets the value for a key
16182 * @param {String} name The key name
16183 * @param {Mixed} value The state data
16185 set : function(key, value){
16186 provider.set(key, value);
16190 * Clears a value from the state
16191 * @param {String} name The key name
16193 clear : function(key){
16194 provider.clear(key);
16198 * Gets the currently configured state provider
16199 * @return {Provider} The state provider
16201 getProvider : function(){
16208 * Ext JS Library 1.1.1
16209 * Copyright(c) 2006-2007, Ext JS, LLC.
16211 * Originally Released Under LGPL - original licence link has changed is not relivant.
16214 * <script type="text/javascript">
16217 * @class Roo.state.CookieProvider
16218 * @extends Roo.state.Provider
16219 * The default Provider implementation which saves state via cookies.
16222 var cp = new Roo.state.CookieProvider({
16224 expires: new Date(new Date().getTime()+(1000*60*60*24*30)); //30 days
16225 domain: "roojs.com"
16227 Roo.state.Manager.setProvider(cp);
16229 * @cfg {String} path The path for which the cookie is active (defaults to root '/' which makes it active for all pages in the site)
16230 * @cfg {Date} expires The cookie expiration date (defaults to 7 days from now)
16231 * @cfg {String} domain The domain to save the cookie for. Note that you cannot specify a different domain than
16232 * your page is on, but you can specify a sub-domain, or simply the domain itself like 'roojs.com' to include
16233 * all sub-domains if you need to access cookies across different sub-domains (defaults to null which uses the same
16234 * domain the page is running on including the 'www' like 'www.roojs.com')
16235 * @cfg {Boolean} secure True if the site is using SSL (defaults to false)
16237 * Create a new CookieProvider
16238 * @param {Object} config The configuration object
16240 Roo.state.CookieProvider = function(config){
16241 Roo.state.CookieProvider.superclass.constructor.call(this);
16243 this.expires = new Date(new Date().getTime()+(1000*60*60*24*7)); //7 days
16244 this.domain = null;
16245 this.secure = false;
16246 Roo.apply(this, config);
16247 this.state = this.readCookies();
16250 Roo.extend(Roo.state.CookieProvider, Roo.state.Provider, {
16252 set : function(name, value){
16253 if(typeof value == "undefined" || value === null){
16257 this.setCookie(name, value);
16258 Roo.state.CookieProvider.superclass.set.call(this, name, value);
16262 clear : function(name){
16263 this.clearCookie(name);
16264 Roo.state.CookieProvider.superclass.clear.call(this, name);
16268 readCookies : function(){
16270 var c = document.cookie + ";";
16271 var re = /\s?(.*?)=(.*?);/g;
16273 while((matches = re.exec(c)) != null){
16274 var name = matches[1];
16275 var value = matches[2];
16276 if(name && name.substring(0,3) == "ys-"){
16277 cookies[name.substr(3)] = this.decodeValue(value);
16284 setCookie : function(name, value){
16285 document.cookie = "ys-"+ name + "=" + this.encodeValue(value) +
16286 ((this.expires == null) ? "" : ("; expires=" + this.expires.toGMTString())) +
16287 ((this.path == null) ? "" : ("; path=" + this.path)) +
16288 ((this.domain == null) ? "" : ("; domain=" + this.domain)) +
16289 ((this.secure == true) ? "; secure" : "");
16293 clearCookie : function(name){
16294 document.cookie = "ys-" + name + "=null; expires=Thu, 01-Jan-70 00:00:01 GMT" +
16295 ((this.path == null) ? "" : ("; path=" + this.path)) +
16296 ((this.domain == null) ? "" : ("; domain=" + this.domain)) +
16297 ((this.secure == true) ? "; secure" : "");
16301 * Ext JS Library 1.1.1
16302 * Copyright(c) 2006-2007, Ext JS, LLC.
16304 * Originally Released Under LGPL - original licence link has changed is not relivant.
16307 * <script type="text/javascript">
16312 * @class Roo.ComponentMgr
16313 * Provides a common registry of all components on a page so that they can be easily accessed by component id (see {@link Roo.getCmp}).
16316 Roo.ComponentMgr = function(){
16317 var all = new Roo.util.MixedCollection();
16321 * Registers a component.
16322 * @param {Roo.Component} c The component
16324 register : function(c){
16329 * Unregisters a component.
16330 * @param {Roo.Component} c The component
16332 unregister : function(c){
16337 * Returns a component by id
16338 * @param {String} id The component id
16340 get : function(id){
16341 return all.get(id);
16345 * Registers a function that will be called when a specified component is added to ComponentMgr
16346 * @param {String} id The component id
16347 * @param {Funtction} fn The callback function
16348 * @param {Object} scope The scope of the callback
16350 onAvailable : function(id, fn, scope){
16351 all.on("add", function(index, o){
16353 fn.call(scope || o, o);
16354 all.un("add", fn, scope);
16361 * Ext JS Library 1.1.1
16362 * Copyright(c) 2006-2007, Ext JS, LLC.
16364 * Originally Released Under LGPL - original licence link has changed is not relivant.
16367 * <script type="text/javascript">
16371 * @class Roo.Component
16372 * @extends Roo.util.Observable
16373 * Base class for all major Roo components. All subclasses of Component can automatically participate in the standard
16374 * Roo component lifecycle of creation, rendering and destruction. They also have automatic support for basic hide/show
16375 * and enable/disable behavior. Component allows any subclass to be lazy-rendered into any {@link Roo.Container} and
16376 * to be automatically registered with the {@link Roo.ComponentMgr} so that it can be referenced at any time via {@link Roo.getCmp}.
16377 * All visual components (widgets) that require rendering into a layout should subclass Component.
16379 * @param {Roo.Element/String/Object} config The configuration options. If an element is passed, it is set as the internal
16380 * 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
16381 * and is used as the component id. Otherwise, it is assumed to be a standard config object and is applied to the component.
16383 Roo.Component = function(config){
16384 config = config || {};
16385 if(config.tagName || config.dom || typeof config == "string"){ // element object
16386 config = {el: config, id: config.id || config};
16388 this.initialConfig = config;
16390 Roo.apply(this, config);
16394 * Fires after the component is disabled.
16395 * @param {Roo.Component} this
16400 * Fires after the component is enabled.
16401 * @param {Roo.Component} this
16405 * @event beforeshow
16406 * Fires before the component is shown. Return false to stop the show.
16407 * @param {Roo.Component} this
16412 * Fires after the component is shown.
16413 * @param {Roo.Component} this
16417 * @event beforehide
16418 * Fires before the component is hidden. Return false to stop the hide.
16419 * @param {Roo.Component} this
16424 * Fires after the component is hidden.
16425 * @param {Roo.Component} this
16429 * @event beforerender
16430 * Fires before the component is rendered. Return false to stop the render.
16431 * @param {Roo.Component} this
16433 beforerender : true,
16436 * Fires after the component is rendered.
16437 * @param {Roo.Component} this
16441 * @event beforedestroy
16442 * Fires before the component is destroyed. Return false to stop the destroy.
16443 * @param {Roo.Component} this
16445 beforedestroy : true,
16448 * Fires after the component is destroyed.
16449 * @param {Roo.Component} this
16454 this.id = "roo-comp-" + (++Roo.Component.AUTO_ID);
16456 Roo.ComponentMgr.register(this);
16457 Roo.Component.superclass.constructor.call(this);
16458 this.initComponent();
16459 if(this.renderTo){ // not supported by all components yet. use at your own risk!
16460 this.render(this.renderTo);
16461 delete this.renderTo;
16466 Roo.Component.AUTO_ID = 1000;
16468 Roo.extend(Roo.Component, Roo.util.Observable, {
16470 * @scope Roo.Component.prototype
16472 * true if this component is hidden. Read-only.
16477 * true if this component is disabled. Read-only.
16482 * true if this component has been rendered. Read-only.
16486 /** @cfg {String} disableClass
16487 * CSS class added to the component when it is disabled (defaults to "x-item-disabled").
16489 disabledClass : "x-item-disabled",
16490 /** @cfg {Boolean} allowDomMove
16491 * Whether the component can move the Dom node when rendering (defaults to true).
16493 allowDomMove : true,
16494 /** @cfg {String} hideMode (display|visibility)
16495 * How this component should hidden. Supported values are
16496 * "visibility" (css visibility), "offsets" (negative offset position) and
16497 * "display" (css display) - defaults to "display".
16499 hideMode: 'display',
16502 ctype : "Roo.Component",
16505 * @cfg {String} actionMode
16506 * which property holds the element that used for hide() / show() / disable() / enable()
16507 * default is 'el' for forms you probably want to set this to fieldEl
16512 getActionEl : function(){
16513 return this[this.actionMode];
16516 initComponent : Roo.emptyFn,
16518 * If this is a lazy rendering component, render it to its container element.
16519 * @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.
16521 render : function(container, position){
16527 if(this.fireEvent("beforerender", this) === false){
16531 if(!container && this.el){
16532 this.el = Roo.get(this.el);
16533 container = this.el.dom.parentNode;
16534 this.allowDomMove = false;
16536 this.container = Roo.get(container);
16537 this.rendered = true;
16538 if(position !== undefined){
16539 if(typeof position == 'number'){
16540 position = this.container.dom.childNodes[position];
16542 position = Roo.getDom(position);
16545 this.onRender(this.container, position || null);
16547 this.el.addClass(this.cls);
16551 this.el.applyStyles(this.style);
16554 this.fireEvent("render", this);
16555 this.afterRender(this.container);
16568 // default function is not really useful
16569 onRender : function(ct, position){
16571 this.el = Roo.get(this.el);
16572 if(this.allowDomMove !== false){
16573 ct.dom.insertBefore(this.el.dom, position);
16579 getAutoCreate : function(){
16580 var cfg = typeof this.autoCreate == "object" ?
16581 this.autoCreate : Roo.apply({}, this.defaultAutoCreate);
16582 if(this.id && !cfg.id){
16589 afterRender : Roo.emptyFn,
16592 * Destroys this component by purging any event listeners, removing the component's element from the DOM,
16593 * removing the component from its {@link Roo.Container} (if applicable) and unregistering it from {@link Roo.ComponentMgr}.
16595 destroy : function(){
16596 if(this.fireEvent("beforedestroy", this) !== false){
16597 this.purgeListeners();
16598 this.beforeDestroy();
16600 this.el.removeAllListeners();
16602 if(this.actionMode == "container"){
16603 this.container.remove();
16607 Roo.ComponentMgr.unregister(this);
16608 this.fireEvent("destroy", this);
16613 beforeDestroy : function(){
16618 onDestroy : function(){
16623 * Returns the underlying {@link Roo.Element}.
16624 * @return {Roo.Element} The element
16626 getEl : function(){
16631 * Returns the id of this component.
16634 getId : function(){
16639 * Try to focus this component.
16640 * @param {Boolean} selectText True to also select the text in this component (if applicable)
16641 * @return {Roo.Component} this
16643 focus : function(selectText){
16646 if(selectText === true){
16647 this.el.dom.select();
16662 * Disable this component.
16663 * @return {Roo.Component} this
16665 disable : function(){
16669 this.disabled = true;
16670 this.fireEvent("disable", this);
16675 onDisable : function(){
16676 this.getActionEl().addClass(this.disabledClass);
16677 this.el.dom.disabled = true;
16681 * Enable this component.
16682 * @return {Roo.Component} this
16684 enable : function(){
16688 this.disabled = false;
16689 this.fireEvent("enable", this);
16694 onEnable : function(){
16695 this.getActionEl().removeClass(this.disabledClass);
16696 this.el.dom.disabled = false;
16700 * Convenience function for setting disabled/enabled by boolean.
16701 * @param {Boolean} disabled
16703 setDisabled : function(disabled){
16704 this[disabled ? "disable" : "enable"]();
16708 * Show this component.
16709 * @return {Roo.Component} this
16712 if(this.fireEvent("beforeshow", this) !== false){
16713 this.hidden = false;
16717 this.fireEvent("show", this);
16723 onShow : function(){
16724 var ae = this.getActionEl();
16725 if(this.hideMode == 'visibility'){
16726 ae.dom.style.visibility = "visible";
16727 }else if(this.hideMode == 'offsets'){
16728 ae.removeClass('x-hidden');
16730 ae.dom.style.display = "";
16735 * Hide this component.
16736 * @return {Roo.Component} this
16739 if(this.fireEvent("beforehide", this) !== false){
16740 this.hidden = true;
16744 this.fireEvent("hide", this);
16750 onHide : function(){
16751 var ae = this.getActionEl();
16752 if(this.hideMode == 'visibility'){
16753 ae.dom.style.visibility = "hidden";
16754 }else if(this.hideMode == 'offsets'){
16755 ae.addClass('x-hidden');
16757 ae.dom.style.display = "none";
16762 * Convenience function to hide or show this component by boolean.
16763 * @param {Boolean} visible True to show, false to hide
16764 * @return {Roo.Component} this
16766 setVisible: function(visible){
16776 * Returns true if this component is visible.
16778 isVisible : function(){
16779 return this.getActionEl().isVisible();
16782 cloneConfig : function(overrides){
16783 overrides = overrides || {};
16784 var id = overrides.id || Roo.id();
16785 var cfg = Roo.applyIf(overrides, this.initialConfig);
16786 cfg.id = id; // prevent dup id
16787 return new this.constructor(cfg);
16791 * Ext JS Library 1.1.1
16792 * Copyright(c) 2006-2007, Ext JS, LLC.
16794 * Originally Released Under LGPL - original licence link has changed is not relivant.
16797 * <script type="text/javascript">
16801 * @class Roo.BoxComponent
16802 * @extends Roo.Component
16803 * Base class for any visual {@link Roo.Component} that uses a box container. BoxComponent provides automatic box
16804 * model adjustments for sizing and positioning and will work correctly withnin the Component rendering model. All
16805 * container classes should subclass BoxComponent so that they will work consistently when nested within other Roo
16806 * layout containers.
16808 * @param {Roo.Element/String/Object} config The configuration options.
16810 Roo.BoxComponent = function(config){
16811 Roo.Component.call(this, config);
16815 * Fires after the component is resized.
16816 * @param {Roo.Component} this
16817 * @param {Number} adjWidth The box-adjusted width that was set
16818 * @param {Number} adjHeight The box-adjusted height that was set
16819 * @param {Number} rawWidth The width that was originally specified
16820 * @param {Number} rawHeight The height that was originally specified
16825 * Fires after the component is moved.
16826 * @param {Roo.Component} this
16827 * @param {Number} x The new x position
16828 * @param {Number} y The new y position
16834 Roo.extend(Roo.BoxComponent, Roo.Component, {
16835 // private, set in afterRender to signify that the component has been rendered
16837 // private, used to defer height settings to subclasses
16838 deferHeight: false,
16839 /** @cfg {Number} width
16840 * width (optional) size of component
16842 /** @cfg {Number} height
16843 * height (optional) size of component
16847 * Sets the width and height of the component. This method fires the resize event. This method can accept
16848 * either width and height as separate numeric arguments, or you can pass a size object like {width:10, height:20}.
16849 * @param {Number/Object} width The new width to set, or a size object in the format {width, height}
16850 * @param {Number} height The new height to set (not required if a size object is passed as the first arg)
16851 * @return {Roo.BoxComponent} this
16853 setSize : function(w, h){
16854 // support for standard size objects
16855 if(typeof w == 'object'){
16860 if(!this.boxReady){
16866 // prevent recalcs when not needed
16867 if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
16870 this.lastSize = {width: w, height: h};
16872 var adj = this.adjustSize(w, h);
16873 var aw = adj.width, ah = adj.height;
16874 if(aw !== undefined || ah !== undefined){ // this code is nasty but performs better with floaters
16875 var rz = this.getResizeEl();
16876 if(!this.deferHeight && aw !== undefined && ah !== undefined){
16877 rz.setSize(aw, ah);
16878 }else if(!this.deferHeight && ah !== undefined){
16880 }else if(aw !== undefined){
16883 this.onResize(aw, ah, w, h);
16884 this.fireEvent('resize', this, aw, ah, w, h);
16890 * Gets the current size of the component's underlying element.
16891 * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
16893 getSize : function(){
16894 return this.el.getSize();
16898 * Gets the current XY position of the component's underlying element.
16899 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
16900 * @return {Array} The XY position of the element (e.g., [100, 200])
16902 getPosition : function(local){
16903 if(local === true){
16904 return [this.el.getLeft(true), this.el.getTop(true)];
16906 return this.xy || this.el.getXY();
16910 * Gets the current box measurements of the component's underlying element.
16911 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
16912 * @returns {Object} box An object in the format {x, y, width, height}
16914 getBox : function(local){
16915 var s = this.el.getSize();
16917 s.x = this.el.getLeft(true);
16918 s.y = this.el.getTop(true);
16920 var xy = this.xy || this.el.getXY();
16928 * Sets the current box measurements of the component's underlying element.
16929 * @param {Object} box An object in the format {x, y, width, height}
16930 * @returns {Roo.BoxComponent} this
16932 updateBox : function(box){
16933 this.setSize(box.width, box.height);
16934 this.setPagePosition(box.x, box.y);
16939 getResizeEl : function(){
16940 return this.resizeEl || this.el;
16944 getPositionEl : function(){
16945 return this.positionEl || this.el;
16949 * Sets the left and top of the component. To set the page XY position instead, use {@link #setPagePosition}.
16950 * This method fires the move event.
16951 * @param {Number} left The new left
16952 * @param {Number} top The new top
16953 * @returns {Roo.BoxComponent} this
16955 setPosition : function(x, y){
16958 if(!this.boxReady){
16961 var adj = this.adjustPosition(x, y);
16962 var ax = adj.x, ay = adj.y;
16964 var el = this.getPositionEl();
16965 if(ax !== undefined || ay !== undefined){
16966 if(ax !== undefined && ay !== undefined){
16967 el.setLeftTop(ax, ay);
16968 }else if(ax !== undefined){
16970 }else if(ay !== undefined){
16973 this.onPosition(ax, ay);
16974 this.fireEvent('move', this, ax, ay);
16980 * Sets the page XY position of the component. To set the left and top instead, use {@link #setPosition}.
16981 * This method fires the move event.
16982 * @param {Number} x The new x position
16983 * @param {Number} y The new y position
16984 * @returns {Roo.BoxComponent} this
16986 setPagePosition : function(x, y){
16989 if(!this.boxReady){
16992 if(x === undefined || y === undefined){ // cannot translate undefined points
16995 var p = this.el.translatePoints(x, y);
16996 this.setPosition(p.left, p.top);
17001 onRender : function(ct, position){
17002 Roo.BoxComponent.superclass.onRender.call(this, ct, position);
17004 this.resizeEl = Roo.get(this.resizeEl);
17006 if(this.positionEl){
17007 this.positionEl = Roo.get(this.positionEl);
17012 afterRender : function(){
17013 Roo.BoxComponent.superclass.afterRender.call(this);
17014 this.boxReady = true;
17015 this.setSize(this.width, this.height);
17016 if(this.x || this.y){
17017 this.setPosition(this.x, this.y);
17019 if(this.pageX || this.pageY){
17020 this.setPagePosition(this.pageX, this.pageY);
17025 * Force the component's size to recalculate based on the underlying element's current height and width.
17026 * @returns {Roo.BoxComponent} this
17028 syncSize : function(){
17029 delete this.lastSize;
17030 this.setSize(this.el.getWidth(), this.el.getHeight());
17035 * Called after the component is resized, this method is empty by default but can be implemented by any
17036 * subclass that needs to perform custom logic after a resize occurs.
17037 * @param {Number} adjWidth The box-adjusted width that was set
17038 * @param {Number} adjHeight The box-adjusted height that was set
17039 * @param {Number} rawWidth The width that was originally specified
17040 * @param {Number} rawHeight The height that was originally specified
17042 onResize : function(adjWidth, adjHeight, rawWidth, rawHeight){
17047 * Called after the component is moved, this method is empty by default but can be implemented by any
17048 * subclass that needs to perform custom logic after a move occurs.
17049 * @param {Number} x The new x position
17050 * @param {Number} y The new y position
17052 onPosition : function(x, y){
17057 adjustSize : function(w, h){
17058 if(this.autoWidth){
17061 if(this.autoHeight){
17064 return {width : w, height: h};
17068 adjustPosition : function(x, y){
17069 return {x : x, y: y};
17073 * Ext JS Library 1.1.1
17074 * Copyright(c) 2006-2007, Ext JS, LLC.
17076 * Originally Released Under LGPL - original licence link has changed is not relivant.
17079 * <script type="text/javascript">
17084 * @extends Roo.Element
17085 * An extended {@link Roo.Element} object that supports a shadow and shim, constrain to viewport and
17086 * automatic maintaining of shadow/shim positions.
17087 * @cfg {Boolean} shim False to disable the iframe shim in browsers which need one (defaults to true)
17088 * @cfg {String/Boolean} shadow True to create a shadow element with default class "x-layer-shadow", or
17089 * you can pass a string with a CSS class name. False turns off the shadow.
17090 * @cfg {Object} dh DomHelper object config to create element with (defaults to {tag: "div", cls: "x-layer"}).
17091 * @cfg {Boolean} constrain False to disable constrain to viewport (defaults to true)
17092 * @cfg {String} cls CSS class to add to the element
17093 * @cfg {Number} zindex Starting z-index (defaults to 11000)
17094 * @cfg {Number} shadowOffset Number of pixels to offset the shadow (defaults to 3)
17096 * @param {Object} config An object with config options.
17097 * @param {String/HTMLElement} existingEl (optional) Uses an existing DOM element. If the element is not found it creates it.
17100 Roo.Layer = function(config, existingEl){
17101 config = config || {};
17102 var dh = Roo.DomHelper;
17103 var cp = config.parentEl, pel = cp ? Roo.getDom(cp) : document.body;
17105 this.dom = Roo.getDom(existingEl);
17108 var o = config.dh || {tag: "div", cls: "x-layer"};
17109 this.dom = dh.append(pel, o);
17112 this.addClass(config.cls);
17114 this.constrain = config.constrain !== false;
17115 this.visibilityMode = Roo.Element.VISIBILITY;
17117 this.id = this.dom.id = config.id;
17119 this.id = Roo.id(this.dom);
17121 this.zindex = config.zindex || this.getZIndex();
17122 this.position("absolute", this.zindex);
17124 this.shadowOffset = config.shadowOffset || 4;
17125 this.shadow = new Roo.Shadow({
17126 offset : this.shadowOffset,
17127 mode : config.shadow
17130 this.shadowOffset = 0;
17132 this.useShim = config.shim !== false && Roo.useShims;
17133 this.useDisplay = config.useDisplay;
17137 var supr = Roo.Element.prototype;
17139 // shims are shared among layer to keep from having 100 iframes
17142 Roo.extend(Roo.Layer, Roo.Element, {
17144 getZIndex : function(){
17145 return this.zindex || parseInt(this.getStyle("z-index"), 10) || 11000;
17148 getShim : function(){
17155 var shim = shims.shift();
17157 shim = this.createShim();
17158 shim.enableDisplayMode('block');
17159 shim.dom.style.display = 'none';
17160 shim.dom.style.visibility = 'visible';
17162 var pn = this.dom.parentNode;
17163 if(shim.dom.parentNode != pn){
17164 pn.insertBefore(shim.dom, this.dom);
17166 shim.setStyle('z-index', this.getZIndex()-2);
17171 hideShim : function(){
17173 this.shim.setDisplayed(false);
17174 shims.push(this.shim);
17179 disableShadow : function(){
17181 this.shadowDisabled = true;
17182 this.shadow.hide();
17183 this.lastShadowOffset = this.shadowOffset;
17184 this.shadowOffset = 0;
17188 enableShadow : function(show){
17190 this.shadowDisabled = false;
17191 this.shadowOffset = this.lastShadowOffset;
17192 delete this.lastShadowOffset;
17200 // this code can execute repeatedly in milliseconds (i.e. during a drag) so
17201 // code size was sacrificed for effeciency (e.g. no getBox/setBox, no XY calls)
17202 sync : function(doShow){
17203 var sw = this.shadow;
17204 if(!this.updating && this.isVisible() && (sw || this.useShim)){
17205 var sh = this.getShim();
17207 var w = this.getWidth(),
17208 h = this.getHeight();
17210 var l = this.getLeft(true),
17211 t = this.getTop(true);
17213 if(sw && !this.shadowDisabled){
17214 if(doShow && !sw.isVisible()){
17217 sw.realign(l, t, w, h);
17223 // fit the shim behind the shadow, so it is shimmed too
17224 var a = sw.adjusts, s = sh.dom.style;
17225 s.left = (Math.min(l, l+a.l))+"px";
17226 s.top = (Math.min(t, t+a.t))+"px";
17227 s.width = (w+a.w)+"px";
17228 s.height = (h+a.h)+"px";
17235 sh.setLeftTop(l, t);
17242 destroy : function(){
17245 this.shadow.hide();
17247 this.removeAllListeners();
17248 var pn = this.dom.parentNode;
17250 pn.removeChild(this.dom);
17252 Roo.Element.uncache(this.id);
17255 remove : function(){
17260 beginUpdate : function(){
17261 this.updating = true;
17265 endUpdate : function(){
17266 this.updating = false;
17271 hideUnders : function(negOffset){
17273 this.shadow.hide();
17279 constrainXY : function(){
17280 if(this.constrain){
17281 var vw = Roo.lib.Dom.getViewWidth(),
17282 vh = Roo.lib.Dom.getViewHeight();
17283 var s = Roo.get(document).getScroll();
17285 var xy = this.getXY();
17286 var x = xy[0], y = xy[1];
17287 var w = this.dom.offsetWidth+this.shadowOffset, h = this.dom.offsetHeight+this.shadowOffset;
17288 // only move it if it needs it
17290 // first validate right/bottom
17291 if((x + w) > vw+s.left){
17292 x = vw - w - this.shadowOffset;
17295 if((y + h) > vh+s.top){
17296 y = vh - h - this.shadowOffset;
17299 // then make sure top/left isn't negative
17310 var ay = this.avoidY;
17311 if(y <= ay && (y+h) >= ay){
17317 supr.setXY.call(this, xy);
17323 isVisible : function(){
17324 return this.visible;
17328 showAction : function(){
17329 this.visible = true; // track visibility to prevent getStyle calls
17330 if(this.useDisplay === true){
17331 this.setDisplayed("");
17332 }else if(this.lastXY){
17333 supr.setXY.call(this, this.lastXY);
17334 }else if(this.lastLT){
17335 supr.setLeftTop.call(this, this.lastLT[0], this.lastLT[1]);
17340 hideAction : function(){
17341 this.visible = false;
17342 if(this.useDisplay === true){
17343 this.setDisplayed(false);
17345 this.setLeftTop(-10000,-10000);
17349 // overridden Element method
17350 setVisible : function(v, a, d, c, e){
17355 var cb = function(){
17360 }.createDelegate(this);
17361 supr.setVisible.call(this, true, true, d, cb, e);
17364 this.hideUnders(true);
17373 }.createDelegate(this);
17375 supr.setVisible.call(this, v, a, d, cb, e);
17384 storeXY : function(xy){
17385 delete this.lastLT;
17389 storeLeftTop : function(left, top){
17390 delete this.lastXY;
17391 this.lastLT = [left, top];
17395 beforeFx : function(){
17396 this.beforeAction();
17397 return Roo.Layer.superclass.beforeFx.apply(this, arguments);
17401 afterFx : function(){
17402 Roo.Layer.superclass.afterFx.apply(this, arguments);
17403 this.sync(this.isVisible());
17407 beforeAction : function(){
17408 if(!this.updating && this.shadow){
17409 this.shadow.hide();
17413 // overridden Element method
17414 setLeft : function(left){
17415 this.storeLeftTop(left, this.getTop(true));
17416 supr.setLeft.apply(this, arguments);
17420 setTop : function(top){
17421 this.storeLeftTop(this.getLeft(true), top);
17422 supr.setTop.apply(this, arguments);
17426 setLeftTop : function(left, top){
17427 this.storeLeftTop(left, top);
17428 supr.setLeftTop.apply(this, arguments);
17432 setXY : function(xy, a, d, c, e){
17434 this.beforeAction();
17436 var cb = this.createCB(c);
17437 supr.setXY.call(this, xy, a, d, cb, e);
17444 createCB : function(c){
17455 // overridden Element method
17456 setX : function(x, a, d, c, e){
17457 this.setXY([x, this.getY()], a, d, c, e);
17460 // overridden Element method
17461 setY : function(y, a, d, c, e){
17462 this.setXY([this.getX(), y], a, d, c, e);
17465 // overridden Element method
17466 setSize : function(w, h, a, d, c, e){
17467 this.beforeAction();
17468 var cb = this.createCB(c);
17469 supr.setSize.call(this, w, h, a, d, cb, e);
17475 // overridden Element method
17476 setWidth : function(w, a, d, c, e){
17477 this.beforeAction();
17478 var cb = this.createCB(c);
17479 supr.setWidth.call(this, w, a, d, cb, e);
17485 // overridden Element method
17486 setHeight : function(h, a, d, c, e){
17487 this.beforeAction();
17488 var cb = this.createCB(c);
17489 supr.setHeight.call(this, h, a, d, cb, e);
17495 // overridden Element method
17496 setBounds : function(x, y, w, h, a, d, c, e){
17497 this.beforeAction();
17498 var cb = this.createCB(c);
17500 this.storeXY([x, y]);
17501 supr.setXY.call(this, [x, y]);
17502 supr.setSize.call(this, w, h, a, d, cb, e);
17505 supr.setBounds.call(this, x, y, w, h, a, d, cb, e);
17511 * Sets the z-index of this layer and adjusts any shadow and shim z-indexes. The layer z-index is automatically
17512 * incremented by two more than the value passed in so that it always shows above any shadow or shim (the shadow
17513 * element, if any, will be assigned z-index + 1, and the shim element, if any, will be assigned the unmodified z-index).
17514 * @param {Number} zindex The new z-index to set
17515 * @return {this} The Layer
17517 setZIndex : function(zindex){
17518 this.zindex = zindex;
17519 this.setStyle("z-index", zindex + 2);
17521 this.shadow.setZIndex(zindex + 1);
17524 this.shim.setStyle("z-index", zindex);
17529 * Original code for Roojs - LGPL
17530 * <script type="text/javascript">
17534 * @class Roo.XComponent
17535 * A delayed Element creator...
17536 * Or a way to group chunks of interface together.
17537 * technically this is a wrapper around a tree of Roo elements (which defines a 'module'),
17538 * used in conjunction with XComponent.build() it will create an instance of each element,
17539 * then call addxtype() to build the User interface.
17541 * Mypart.xyx = new Roo.XComponent({
17543 parent : 'Mypart.xyz', // empty == document.element.!!
17547 disabled : function() {}
17549 tree : function() { // return an tree of xtype declared components
17553 xtype : 'NestedLayoutPanel',
17560 * It can be used to build a big heiracy, with parent etc.
17561 * or you can just use this to render a single compoent to a dom element
17562 * MYPART.render(Roo.Element | String(id) | dom_element )
17569 * Roo is designed primarily as a single page application, so the UI build for a standard interface will
17570 * expect a single 'TOP' level module normally indicated by the 'parent' of the XComponent definition being defined as false.
17572 * Each sub module is expected to have a parent pointing to the class name of it's parent module.
17574 * When the top level is false, a 'Roo.BorderLayout' is created and the element is flagged as 'topModule'
17575 * - if mulitple topModules exist, the last one is defined as the top module.
17579 * When the top level or multiple modules are to embedded into a existing HTML page,
17580 * the parent element can container '#id' of the element where the module will be drawn.
17584 * Unlike classic Roo, the bootstrap tends not to be used as a single page.
17585 * it relies more on a include mechanism, where sub modules are included into an outer page.
17586 * This is normally managed by the builder tools using Roo.apply( options, Included.Sub.Module )
17588 * Bootstrap Roo Included elements
17590 * Our builder application needs the ability to preview these sub compoennts. They will normally have parent=false set,
17591 * hence confusing the component builder as it thinks there are multiple top level elements.
17593 * String Over-ride & Translations
17595 * Our builder application writes all the strings as _strings and _named_strings. This is to enable the translation of elements,
17596 * and also the 'overlaying of string values - needed when different versions of the same application with different text content
17597 * are needed. @see Roo.XComponent.overlayString
17601 * @extends Roo.util.Observable
17603 * @param cfg {Object} configuration of component
17606 Roo.XComponent = function(cfg) {
17607 Roo.apply(this, cfg);
17611 * Fires when this the componnt is built
17612 * @param {Roo.XComponent} c the component
17617 this.region = this.region || 'center'; // default..
17618 Roo.XComponent.register(this);
17619 this.modules = false;
17620 this.el = false; // where the layout goes..
17624 Roo.extend(Roo.XComponent, Roo.util.Observable, {
17627 * The created element (with Roo.factory())
17628 * @type {Roo.Layout}
17634 * for BC - use el in new code
17635 * @type {Roo.Layout}
17641 * for BC - use el in new code
17642 * @type {Roo.Layout}
17647 * @cfg {Function|boolean} disabled
17648 * If this module is disabled by some rule, return true from the funtion
17653 * @cfg {String} parent
17654 * Name of parent element which it get xtype added to..
17659 * @cfg {String} order
17660 * Used to set the order in which elements are created (usefull for multiple tabs)
17665 * @cfg {String} name
17666 * String to display while loading.
17670 * @cfg {String} region
17671 * Region to render component to (defaults to center)
17676 * @cfg {Array} items
17677 * A single item array - the first element is the root of the tree..
17678 * It's done this way to stay compatible with the Xtype system...
17684 * The method that retuns the tree of parts that make up this compoennt
17691 * render element to dom or tree
17692 * @param {Roo.Element|String|DomElement} optional render to if parent is not set.
17695 render : function(el)
17699 var hp = this.parent ? 1 : 0;
17700 Roo.debug && Roo.log(this);
17702 var tree = this._tree ? this._tree() : this.tree();
17705 if (!el && typeof(this.parent) == 'string' && this.parent.substring(0,1) == '#') {
17706 // if parent is a '#.....' string, then let's use that..
17707 var ename = this.parent.substr(1);
17708 this.parent = false;
17709 Roo.debug && Roo.log(ename);
17711 case 'bootstrap-body':
17712 if (typeof(tree.el) != 'undefined' && tree.el == document.body) {
17713 // this is the BorderLayout standard?
17714 this.parent = { el : true };
17717 if (["Nest", "Content", "Grid", "Tree"].indexOf(tree.xtype) > -1) {
17718 // need to insert stuff...
17720 el : new Roo.bootstrap.layout.Border({
17721 el : document.body,
17727 tabPosition: 'top',
17728 //resizeTabs: true,
17729 alwaysShowTabs: true,
17739 if (typeof(Roo.bootstrap.Body) != 'undefined' ) {
17740 this.parent = { el : new Roo.bootstrap.Body() };
17741 Roo.debug && Roo.log("setting el to doc body");
17744 throw "Container is bootstrap body, but Roo.bootstrap.Body is not defined";
17748 this.parent = { el : true};
17751 el = Roo.get(ename);
17752 if (typeof(Roo.bootstrap) != 'undefined' && tree['|xns'] == 'Roo.bootstrap') {
17753 this.parent = { el : true};
17760 if (!el && !this.parent) {
17761 Roo.debug && Roo.log("Warning - element can not be found :#" + ename );
17766 Roo.debug && Roo.log("EL:");
17767 Roo.debug && Roo.log(el);
17768 Roo.debug && Roo.log("this.parent.el:");
17769 Roo.debug && Roo.log(this.parent.el);
17772 // altertive root elements ??? - we need a better way to indicate these.
17773 var is_alt = Roo.XComponent.is_alt ||
17774 (typeof(tree.el) != 'undefined' && tree.el == document.body) ||
17775 (typeof(Roo.bootstrap) != 'undefined' && tree.xns == Roo.bootstrap) ||
17776 (typeof(Roo.mailer) != 'undefined' && tree.xns == Roo.mailer) ;
17780 if (!this.parent && is_alt) {
17781 //el = Roo.get(document.body);
17782 this.parent = { el : true };
17787 if (!this.parent) {
17789 Roo.debug && Roo.log("no parent - creating one");
17791 el = el ? Roo.get(el) : false;
17793 if (typeof(Roo.BorderLayout) == 'undefined' ) {
17796 el : new Roo.bootstrap.layout.Border({
17797 el: el || document.body,
17803 tabPosition: 'top',
17804 //resizeTabs: true,
17805 alwaysShowTabs: false,
17808 overflow: 'visible'
17814 // it's a top level one..
17816 el : new Roo.BorderLayout(el || document.body, {
17821 tabPosition: 'top',
17822 //resizeTabs: true,
17823 alwaysShowTabs: el && hp? false : true,
17824 hideTabs: el || !hp ? true : false,
17832 if (!this.parent.el) {
17833 // probably an old style ctor, which has been disabled.
17837 // The 'tree' method is '_tree now'
17839 tree.region = tree.region || this.region;
17840 var is_body = false;
17841 if (this.parent.el === true) {
17842 // bootstrap... - body..
17846 this.parent.el = Roo.factory(tree);
17850 this.el = this.parent.el.addxtype(tree, undefined, is_body);
17851 this.fireEvent('built', this);
17853 this.panel = this.el;
17854 this.layout = this.panel.layout;
17855 this.parentLayout = this.parent.layout || false;
17861 Roo.apply(Roo.XComponent, {
17863 * @property hideProgress
17864 * true to disable the building progress bar.. usefull on single page renders.
17867 hideProgress : false,
17869 * @property buildCompleted
17870 * True when the builder has completed building the interface.
17873 buildCompleted : false,
17876 * @property topModule
17877 * the upper most module - uses document.element as it's constructor.
17884 * @property modules
17885 * array of modules to be created by registration system.
17886 * @type {Array} of Roo.XComponent
17891 * @property elmodules
17892 * array of modules to be created by which use #ID
17893 * @type {Array} of Roo.XComponent
17900 * Is an alternative Root - normally used by bootstrap or other systems,
17901 * where the top element in the tree can wrap 'body'
17902 * @type {boolean} (default false)
17907 * @property build_from_html
17908 * Build elements from html - used by bootstrap HTML stuff
17909 * - this is cleared after build is completed
17910 * @type {boolean} (default false)
17913 build_from_html : false,
17915 * Register components to be built later.
17917 * This solves the following issues
17918 * - Building is not done on page load, but after an authentication process has occured.
17919 * - Interface elements are registered on page load
17920 * - Parent Interface elements may not be loaded before child, so this handles that..
17927 module : 'Pman.Tab.projectMgr',
17929 parent : 'Pman.layout',
17930 disabled : false, // or use a function..
17933 * * @param {Object} details about module
17935 register : function(obj) {
17937 Roo.XComponent.event.fireEvent('register', obj);
17938 switch(typeof(obj.disabled) ) {
17944 if ( obj.disabled() ) {
17950 if (obj.disabled || obj.region == '#disabled') {
17956 this.modules.push(obj);
17960 * convert a string to an object..
17961 * eg. 'AAA.BBB' -> finds AAA.BBB
17965 toObject : function(str)
17967 if (!str || typeof(str) == 'object') {
17970 if (str.substring(0,1) == '#') {
17974 var ar = str.split('.');
17979 eval('if (typeof ' + rt + ' == "undefined"){ o = false;} o = ' + rt + ';');
17981 throw "Module not found : " + str;
17985 throw "Module not found : " + str;
17987 Roo.each(ar, function(e) {
17988 if (typeof(o[e]) == 'undefined') {
17989 throw "Module not found : " + str;
18000 * move modules into their correct place in the tree..
18003 preBuild : function ()
18006 Roo.each(this.modules , function (obj)
18008 Roo.XComponent.event.fireEvent('beforebuild', obj);
18010 var opar = obj.parent;
18012 obj.parent = this.toObject(opar);
18014 Roo.debug && Roo.log("parent:toObject failed: " + e.toString());
18019 Roo.debug && Roo.log("GOT top level module");
18020 Roo.debug && Roo.log(obj);
18021 obj.modules = new Roo.util.MixedCollection(false,
18022 function(o) { return o.order + '' }
18024 this.topModule = obj;
18027 // parent is a string (usually a dom element name..)
18028 if (typeof(obj.parent) == 'string') {
18029 this.elmodules.push(obj);
18032 if (obj.parent.constructor != Roo.XComponent) {
18033 Roo.debug && Roo.log("Warning : Object Parent is not instance of XComponent:" + obj.name)
18035 if (!obj.parent.modules) {
18036 obj.parent.modules = new Roo.util.MixedCollection(false,
18037 function(o) { return o.order + '' }
18040 if (obj.parent.disabled) {
18041 obj.disabled = true;
18043 obj.parent.modules.add(obj);
18048 * make a list of modules to build.
18049 * @return {Array} list of modules.
18052 buildOrder : function()
18055 var cmp = function(a,b) {
18056 return String(a).toUpperCase() > String(b).toUpperCase() ? 1 : -1;
18058 if ((!this.topModule || !this.topModule.modules) && !this.elmodules.length) {
18059 throw "No top level modules to build";
18062 // make a flat list in order of modules to build.
18063 var mods = this.topModule ? [ this.topModule ] : [];
18066 // elmodules (is a list of DOM based modules )
18067 Roo.each(this.elmodules, function(e) {
18069 if (!this.topModule &&
18070 typeof(e.parent) == 'string' &&
18071 e.parent.substring(0,1) == '#' &&
18072 Roo.get(e.parent.substr(1))
18075 _this.topModule = e;
18081 // add modules to their parents..
18082 var addMod = function(m) {
18083 Roo.debug && Roo.log("build Order: add: " + m.name);
18086 if (m.modules && !m.disabled) {
18087 Roo.debug && Roo.log("build Order: " + m.modules.length + " child modules");
18088 m.modules.keySort('ASC', cmp );
18089 Roo.debug && Roo.log("build Order: " + m.modules.length + " child modules (after sort)");
18091 m.modules.each(addMod);
18093 Roo.debug && Roo.log("build Order: no child modules");
18095 // not sure if this is used any more..
18097 m.finalize.name = m.name + " (clean up) ";
18098 mods.push(m.finalize);
18102 if (this.topModule && this.topModule.modules) {
18103 this.topModule.modules.keySort('ASC', cmp );
18104 this.topModule.modules.each(addMod);
18110 * Build the registered modules.
18111 * @param {Object} parent element.
18112 * @param {Function} optional method to call after module has been added.
18116 build : function(opts)
18119 if (typeof(opts) != 'undefined') {
18120 Roo.apply(this,opts);
18124 var mods = this.buildOrder();
18126 //this.allmods = mods;
18127 //Roo.debug && Roo.log(mods);
18129 if (!mods.length) { // should not happen
18130 throw "NO modules!!!";
18134 var msg = "Building Interface...";
18135 // flash it up as modal - so we store the mask!?
18136 if (!this.hideProgress && Roo.MessageBox) {
18137 Roo.MessageBox.show({ title: 'loading' });
18138 Roo.MessageBox.show({
18139 title: "Please wait...",
18149 var total = mods.length;
18152 var progressRun = function() {
18153 if (!mods.length) {
18154 Roo.debug && Roo.log('hide?');
18155 if (!this.hideProgress && Roo.MessageBox) {
18156 Roo.MessageBox.hide();
18158 Roo.XComponent.build_from_html = false; // reset, so dialogs will be build from javascript
18160 Roo.XComponent.event.fireEvent('buildcomplete', _this.topModule);
18166 var m = mods.shift();
18169 Roo.debug && Roo.log(m);
18170 // not sure if this is supported any more.. - modules that are are just function
18171 if (typeof(m) == 'function') {
18173 return progressRun.defer(10, _this);
18177 msg = "Building Interface " + (total - mods.length) +
18179 (m.name ? (' - ' + m.name) : '');
18180 Roo.debug && Roo.log(msg);
18181 if (!_this.hideProgress && Roo.MessageBox) {
18182 Roo.MessageBox.updateProgress( (total - mods.length)/total, msg );
18186 // is the module disabled?
18187 var disabled = (typeof(m.disabled) == 'function') ?
18188 m.disabled.call(m.module.disabled) : m.disabled;
18192 return progressRun(); // we do not update the display!
18200 // it's 10 on top level, and 1 on others??? why...
18201 return progressRun.defer(10, _this);
18204 progressRun.defer(1, _this);
18210 * Overlay a set of modified strings onto a component
18211 * This is dependant on our builder exporting the strings and 'named strings' elements.
18213 * @param {Object} element to overlay on - eg. Pman.Dialog.Login
18214 * @param {Object} associative array of 'named' string and it's new value.
18217 overlayStrings : function( component, strings )
18219 if (typeof(component['_named_strings']) == 'undefined') {
18220 throw "ERROR: component does not have _named_strings";
18222 for ( var k in strings ) {
18223 var md = typeof(component['_named_strings'][k]) == 'undefined' ? false : component['_named_strings'][k];
18224 if (md !== false) {
18225 component['_strings'][md] = strings[k];
18227 Roo.log('could not find named string: ' + k + ' in');
18228 Roo.log(component);
18243 * wrapper for event.on - aliased later..
18244 * Typically use to register a event handler for register:
18246 * eg. Roo.XComponent.on('register', function(comp) { comp.disable = true } );
18255 Roo.XComponent.event = new Roo.util.Observable({
18259 * Fires when an Component is registered,
18260 * set the disable property on the Component to stop registration.
18261 * @param {Roo.XComponent} c the component being registerd.
18266 * @event beforebuild
18267 * Fires before each Component is built
18268 * can be used to apply permissions.
18269 * @param {Roo.XComponent} c the component being registerd.
18272 'beforebuild' : true,
18274 * @event buildcomplete
18275 * Fires on the top level element when all elements have been built
18276 * @param {Roo.XComponent} the top level component.
18278 'buildcomplete' : true
18283 Roo.XComponent.on = Roo.XComponent.event.on.createDelegate(Roo.XComponent.event);
18286 * marked - a markdown parser
18287 * Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed)
18288 * https://github.com/chjj/marked
18294 * Roo.Markdown - is a very crude wrapper around marked..
18298 * alert( Roo.Markdown.toHtml("Markdown *rocks*.") );
18300 * Note: move the sample code to the bottom of this
18301 * file before uncommenting it.
18306 Roo.Markdown.toHtml = function(text) {
18308 var c = new Roo.Markdown.marked.setOptions({
18309 renderer: new Roo.Markdown.marked.Renderer(),
18320 text = text.replace(/\\\n/g,' ');
18321 return Roo.Markdown.marked(text);
18326 // Wraps all "globals" so that the only thing
18327 // exposed is makeHtml().
18333 * eval:var:unescape
18341 var escape = function (html, encode) {
18343 .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&')
18344 .replace(/</g, '<')
18345 .replace(/>/g, '>')
18346 .replace(/"/g, '"')
18347 .replace(/'/g, ''');
18350 var unescape = function (html) {
18351 // explicitly match decimal, hex, and named HTML entities
18352 return html.replace(/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/g, function(_, n) {
18353 n = n.toLowerCase();
18354 if (n === 'colon') { return ':'; }
18355 if (n.charAt(0) === '#') {
18356 return n.charAt(1) === 'x'
18357 ? String.fromCharCode(parseInt(n.substring(2), 16))
18358 : String.fromCharCode(+n.substring(1));
18364 var replace = function (regex, opt) {
18365 regex = regex.source;
18367 return function self(name, val) {
18368 if (!name) { return new RegExp(regex, opt); }
18369 val = val.source || val;
18370 val = val.replace(/(^|[^\[])\^/g, '$1');
18371 regex = regex.replace(name, val);
18380 var noop = function () {}
18386 var merge = function (obj) {
18391 for (; i < arguments.length; i++) {
18392 target = arguments[i];
18393 for (key in target) {
18394 if (Object.prototype.hasOwnProperty.call(target, key)) {
18395 obj[key] = target[key];
18405 * Block-Level Grammar
18413 code: /^( {4}[^\n]+\n*)+/,
18415 hr: /^( *[-*_]){3,} *(?:\n+|$)/,
18416 heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,
18418 lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,
18419 blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/,
18420 list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,
18421 html: /^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/,
18422 def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,
18424 paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,
18428 block.bullet = /(?:[*+-]|\d+\.)/;
18429 block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/;
18430 block.item = replace(block.item, 'gm')
18431 (/bull/g, block.bullet)
18434 block.list = replace(block.list)
18435 (/bull/g, block.bullet)
18436 ('hr', '\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))')
18437 ('def', '\\n+(?=' + block.def.source + ')')
18440 block.blockquote = replace(block.blockquote)
18444 block._tag = '(?!(?:'
18445 + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code'
18446 + '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo'
18447 + '|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b';
18449 block.html = replace(block.html)
18450 ('comment', /<!--[\s\S]*?-->/)
18451 ('closed', /<(tag)[\s\S]+?<\/\1>/)
18452 ('closing', /<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)
18453 (/tag/g, block._tag)
18456 block.paragraph = replace(block.paragraph)
18458 ('heading', block.heading)
18459 ('lheading', block.lheading)
18460 ('blockquote', block.blockquote)
18461 ('tag', '<' + block._tag)
18466 * Normal Block Grammar
18469 block.normal = merge({}, block);
18472 * GFM Block Grammar
18475 block.gfm = merge({}, block.normal, {
18476 fences: /^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/,
18478 heading: /^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/
18481 block.gfm.paragraph = replace(block.paragraph)
18483 + block.gfm.fences.source.replace('\\1', '\\2') + '|'
18484 + block.list.source.replace('\\1', '\\3') + '|')
18488 * GFM + Tables Block Grammar
18491 block.tables = merge({}, block.gfm, {
18492 nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,
18493 table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/
18500 var Lexer = function (options) {
18502 this.tokens.links = {};
18503 this.options = options || marked.defaults;
18504 this.rules = block.normal;
18506 if (this.options.gfm) {
18507 if (this.options.tables) {
18508 this.rules = block.tables;
18510 this.rules = block.gfm;
18516 * Expose Block Rules
18519 Lexer.rules = block;
18522 * Static Lex Method
18525 Lexer.lex = function(src, options) {
18526 var lexer = new Lexer(options);
18527 return lexer.lex(src);
18534 Lexer.prototype.lex = function(src) {
18536 .replace(/\r\n|\r/g, '\n')
18537 .replace(/\t/g, ' ')
18538 .replace(/\u00a0/g, ' ')
18539 .replace(/\u2424/g, '\n');
18541 return this.token(src, true);
18548 Lexer.prototype.token = function(src, top, bq) {
18549 var src = src.replace(/^ +$/gm, '')
18562 if (cap = this.rules.newline.exec(src)) {
18563 src = src.substring(cap[0].length);
18564 if (cap[0].length > 1) {
18572 if (cap = this.rules.code.exec(src)) {
18573 src = src.substring(cap[0].length);
18574 cap = cap[0].replace(/^ {4}/gm, '');
18577 text: !this.options.pedantic
18578 ? cap.replace(/\n+$/, '')
18585 if (cap = this.rules.fences.exec(src)) {
18586 src = src.substring(cap[0].length);
18596 if (cap = this.rules.heading.exec(src)) {
18597 src = src.substring(cap[0].length);
18600 depth: cap[1].length,
18606 // table no leading pipe (gfm)
18607 if (top && (cap = this.rules.nptable.exec(src))) {
18608 src = src.substring(cap[0].length);
18612 header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
18613 align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
18614 cells: cap[3].replace(/\n$/, '').split('\n')
18617 for (i = 0; i < item.align.length; i++) {
18618 if (/^ *-+: *$/.test(item.align[i])) {
18619 item.align[i] = 'right';
18620 } else if (/^ *:-+: *$/.test(item.align[i])) {
18621 item.align[i] = 'center';
18622 } else if (/^ *:-+ *$/.test(item.align[i])) {
18623 item.align[i] = 'left';
18625 item.align[i] = null;
18629 for (i = 0; i < item.cells.length; i++) {
18630 item.cells[i] = item.cells[i].split(/ *\| */);
18633 this.tokens.push(item);
18639 if (cap = this.rules.lheading.exec(src)) {
18640 src = src.substring(cap[0].length);
18643 depth: cap[2] === '=' ? 1 : 2,
18650 if (cap = this.rules.hr.exec(src)) {
18651 src = src.substring(cap[0].length);
18659 if (cap = this.rules.blockquote.exec(src)) {
18660 src = src.substring(cap[0].length);
18663 type: 'blockquote_start'
18666 cap = cap[0].replace(/^ *> ?/gm, '');
18668 // Pass `top` to keep the current
18669 // "toplevel" state. This is exactly
18670 // how markdown.pl works.
18671 this.token(cap, top, true);
18674 type: 'blockquote_end'
18681 if (cap = this.rules.list.exec(src)) {
18682 src = src.substring(cap[0].length);
18686 type: 'list_start',
18687 ordered: bull.length > 1
18690 // Get each top-level item.
18691 cap = cap[0].match(this.rules.item);
18697 for (; i < l; i++) {
18700 // Remove the list item's bullet
18701 // so it is seen as the next token.
18702 space = item.length;
18703 item = item.replace(/^ *([*+-]|\d+\.) +/, '');
18705 // Outdent whatever the
18706 // list item contains. Hacky.
18707 if (~item.indexOf('\n ')) {
18708 space -= item.length;
18709 item = !this.options.pedantic
18710 ? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '')
18711 : item.replace(/^ {1,4}/gm, '');
18714 // Determine whether the next list item belongs here.
18715 // Backpedal if it does not belong in this list.
18716 if (this.options.smartLists && i !== l - 1) {
18717 b = block.bullet.exec(cap[i + 1])[0];
18718 if (bull !== b && !(bull.length > 1 && b.length > 1)) {
18719 src = cap.slice(i + 1).join('\n') + src;
18724 // Determine whether item is loose or not.
18725 // Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/
18726 // for discount behavior.
18727 loose = next || /\n\n(?!\s*$)/.test(item);
18729 next = item.charAt(item.length - 1) === '\n';
18730 if (!loose) { loose = next; }
18735 ? 'loose_item_start'
18736 : 'list_item_start'
18740 this.token(item, false, bq);
18743 type: 'list_item_end'
18755 if (cap = this.rules.html.exec(src)) {
18756 src = src.substring(cap[0].length);
18758 type: this.options.sanitize
18761 pre: !this.options.sanitizer
18762 && (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'),
18769 if ((!bq && top) && (cap = this.rules.def.exec(src))) {
18770 src = src.substring(cap[0].length);
18771 this.tokens.links[cap[1].toLowerCase()] = {
18779 if (top && (cap = this.rules.table.exec(src))) {
18780 src = src.substring(cap[0].length);
18784 header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
18785 align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
18786 cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n')
18789 for (i = 0; i < item.align.length; i++) {
18790 if (/^ *-+: *$/.test(item.align[i])) {
18791 item.align[i] = 'right';
18792 } else if (/^ *:-+: *$/.test(item.align[i])) {
18793 item.align[i] = 'center';
18794 } else if (/^ *:-+ *$/.test(item.align[i])) {
18795 item.align[i] = 'left';
18797 item.align[i] = null;
18801 for (i = 0; i < item.cells.length; i++) {
18802 item.cells[i] = item.cells[i]
18803 .replace(/^ *\| *| *\| *$/g, '')
18807 this.tokens.push(item);
18812 // top-level paragraph
18813 if (top && (cap = this.rules.paragraph.exec(src))) {
18814 src = src.substring(cap[0].length);
18817 text: cap[1].charAt(cap[1].length - 1) === '\n'
18818 ? cap[1].slice(0, -1)
18825 if (cap = this.rules.text.exec(src)) {
18826 // Top-level should never reach here.
18827 src = src.substring(cap[0].length);
18837 Error('Infinite loop on byte: ' + src.charCodeAt(0));
18841 return this.tokens;
18845 * Inline-Level Grammar
18849 escape: /^\\([\\`*{}\[\]()#+\-.!_>])/,
18850 autolink: /^<([^ >]+(@|:\/)[^ >]+)>/,
18852 tag: /^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,
18853 link: /^!?\[(inside)\]\(href\)/,
18854 reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/,
18855 nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,
18856 strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,
18857 em: /^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,
18858 code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,
18859 br: /^ {2,}\n(?!\s*$)/,
18861 text: /^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/
18864 inline._inside = /(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/;
18865 inline._href = /\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/;
18867 inline.link = replace(inline.link)
18868 ('inside', inline._inside)
18869 ('href', inline._href)
18872 inline.reflink = replace(inline.reflink)
18873 ('inside', inline._inside)
18877 * Normal Inline Grammar
18880 inline.normal = merge({}, inline);
18883 * Pedantic Inline Grammar
18886 inline.pedantic = merge({}, inline.normal, {
18887 strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
18888 em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/
18892 * GFM Inline Grammar
18895 inline.gfm = merge({}, inline.normal, {
18896 escape: replace(inline.escape)('])', '~|])')(),
18897 url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,
18898 del: /^~~(?=\S)([\s\S]*?\S)~~/,
18899 text: replace(inline.text)
18901 ('|', '|https?://|')
18906 * GFM + Line Breaks Inline Grammar
18909 inline.breaks = merge({}, inline.gfm, {
18910 br: replace(inline.br)('{2,}', '*')(),
18911 text: replace(inline.gfm.text)('{2,}', '*')()
18915 * Inline Lexer & Compiler
18918 var InlineLexer = function (links, options) {
18919 this.options = options || marked.defaults;
18920 this.links = links;
18921 this.rules = inline.normal;
18922 this.renderer = this.options.renderer || new Renderer;
18923 this.renderer.options = this.options;
18927 Error('Tokens array requires a `links` property.');
18930 if (this.options.gfm) {
18931 if (this.options.breaks) {
18932 this.rules = inline.breaks;
18934 this.rules = inline.gfm;
18936 } else if (this.options.pedantic) {
18937 this.rules = inline.pedantic;
18942 * Expose Inline Rules
18945 InlineLexer.rules = inline;
18948 * Static Lexing/Compiling Method
18951 InlineLexer.output = function(src, links, options) {
18952 var inline = new InlineLexer(links, options);
18953 return inline.output(src);
18960 InlineLexer.prototype.output = function(src) {
18969 if (cap = this.rules.escape.exec(src)) {
18970 src = src.substring(cap[0].length);
18976 if (cap = this.rules.autolink.exec(src)) {
18977 src = src.substring(cap[0].length);
18978 if (cap[2] === '@') {
18979 text = cap[1].charAt(6) === ':'
18980 ? this.mangle(cap[1].substring(7))
18981 : this.mangle(cap[1]);
18982 href = this.mangle('mailto:') + text;
18984 text = escape(cap[1]);
18987 out += this.renderer.link(href, null, text);
18992 if (!this.inLink && (cap = this.rules.url.exec(src))) {
18993 src = src.substring(cap[0].length);
18994 text = escape(cap[1]);
18996 out += this.renderer.link(href, null, text);
19001 if (cap = this.rules.tag.exec(src)) {
19002 if (!this.inLink && /^<a /i.test(cap[0])) {
19003 this.inLink = true;
19004 } else if (this.inLink && /^<\/a>/i.test(cap[0])) {
19005 this.inLink = false;
19007 src = src.substring(cap[0].length);
19008 out += this.options.sanitize
19009 ? this.options.sanitizer
19010 ? this.options.sanitizer(cap[0])
19017 if (cap = this.rules.link.exec(src)) {
19018 src = src.substring(cap[0].length);
19019 this.inLink = true;
19020 out += this.outputLink(cap, {
19024 this.inLink = false;
19029 if ((cap = this.rules.reflink.exec(src))
19030 || (cap = this.rules.nolink.exec(src))) {
19031 src = src.substring(cap[0].length);
19032 link = (cap[2] || cap[1]).replace(/\s+/g, ' ');
19033 link = this.links[link.toLowerCase()];
19034 if (!link || !link.href) {
19035 out += cap[0].charAt(0);
19036 src = cap[0].substring(1) + src;
19039 this.inLink = true;
19040 out += this.outputLink(cap, link);
19041 this.inLink = false;
19046 if (cap = this.rules.strong.exec(src)) {
19047 src = src.substring(cap[0].length);
19048 out += this.renderer.strong(this.output(cap[2] || cap[1]));
19053 if (cap = this.rules.em.exec(src)) {
19054 src = src.substring(cap[0].length);
19055 out += this.renderer.em(this.output(cap[2] || cap[1]));
19060 if (cap = this.rules.code.exec(src)) {
19061 src = src.substring(cap[0].length);
19062 out += this.renderer.codespan(escape(cap[2], true));
19067 if (cap = this.rules.br.exec(src)) {
19068 src = src.substring(cap[0].length);
19069 out += this.renderer.br();
19074 if (cap = this.rules.del.exec(src)) {
19075 src = src.substring(cap[0].length);
19076 out += this.renderer.del(this.output(cap[1]));
19081 if (cap = this.rules.text.exec(src)) {
19082 src = src.substring(cap[0].length);
19083 out += this.renderer.text(escape(this.smartypants(cap[0])));
19089 Error('Infinite loop on byte: ' + src.charCodeAt(0));
19100 InlineLexer.prototype.outputLink = function(cap, link) {
19101 var href = escape(link.href)
19102 , title = link.title ? escape(link.title) : null;
19104 return cap[0].charAt(0) !== '!'
19105 ? this.renderer.link(href, title, this.output(cap[1]))
19106 : this.renderer.image(href, title, escape(cap[1]));
19110 * Smartypants Transformations
19113 InlineLexer.prototype.smartypants = function(text) {
19114 if (!this.options.smartypants) { return text; }
19117 .replace(/---/g, '\u2014')
19119 .replace(/--/g, '\u2013')
19121 .replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018')
19122 // closing singles & apostrophes
19123 .replace(/'/g, '\u2019')
19125 .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c')
19127 .replace(/"/g, '\u201d')
19129 .replace(/\.{3}/g, '\u2026');
19136 InlineLexer.prototype.mangle = function(text) {
19137 if (!this.options.mangle) { return text; }
19143 for (; i < l; i++) {
19144 ch = text.charCodeAt(i);
19145 if (Math.random() > 0.5) {
19146 ch = 'x' + ch.toString(16);
19148 out += '&#' + ch + ';';
19159 * eval:var:Renderer
19162 var Renderer = function (options) {
19163 this.options = options || {};
19166 Renderer.prototype.code = function(code, lang, escaped) {
19167 if (this.options.highlight) {
19168 var out = this.options.highlight(code, lang);
19169 if (out != null && out !== code) {
19174 // hack!!! - it's already escapeD?
19179 return '<pre><code>'
19180 + (escaped ? code : escape(code, true))
19181 + '\n</code></pre>';
19184 return '<pre><code class="'
19185 + this.options.langPrefix
19186 + escape(lang, true)
19188 + (escaped ? code : escape(code, true))
19189 + '\n</code></pre>\n';
19192 Renderer.prototype.blockquote = function(quote) {
19193 return '<blockquote>\n' + quote + '</blockquote>\n';
19196 Renderer.prototype.html = function(html) {
19200 Renderer.prototype.heading = function(text, level, raw) {
19204 + this.options.headerPrefix
19205 + raw.toLowerCase().replace(/[^\w]+/g, '-')
19213 Renderer.prototype.hr = function() {
19214 return this.options.xhtml ? '<hr/>\n' : '<hr>\n';
19217 Renderer.prototype.list = function(body, ordered) {
19218 var type = ordered ? 'ol' : 'ul';
19219 return '<' + type + '>\n' + body + '</' + type + '>\n';
19222 Renderer.prototype.listitem = function(text) {
19223 return '<li>' + text + '</li>\n';
19226 Renderer.prototype.paragraph = function(text) {
19227 return '<p>' + text + '</p>\n';
19230 Renderer.prototype.table = function(header, body) {
19231 return '<table class="table table-striped">\n'
19241 Renderer.prototype.tablerow = function(content) {
19242 return '<tr>\n' + content + '</tr>\n';
19245 Renderer.prototype.tablecell = function(content, flags) {
19246 var type = flags.header ? 'th' : 'td';
19247 var tag = flags.align
19248 ? '<' + type + ' style="text-align:' + flags.align + '">'
19249 : '<' + type + '>';
19250 return tag + content + '</' + type + '>\n';
19253 // span level renderer
19254 Renderer.prototype.strong = function(text) {
19255 return '<strong>' + text + '</strong>';
19258 Renderer.prototype.em = function(text) {
19259 return '<em>' + text + '</em>';
19262 Renderer.prototype.codespan = function(text) {
19263 return '<code>' + text + '</code>';
19266 Renderer.prototype.br = function() {
19267 return this.options.xhtml ? '<br/>' : '<br>';
19270 Renderer.prototype.del = function(text) {
19271 return '<del>' + text + '</del>';
19274 Renderer.prototype.link = function(href, title, text) {
19275 if (this.options.sanitize) {
19277 var prot = decodeURIComponent(unescape(href))
19278 .replace(/[^\w:]/g, '')
19283 if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0) {
19287 var out = '<a href="' + href + '"';
19289 out += ' title="' + title + '"';
19291 out += '>' + text + '</a>';
19295 Renderer.prototype.image = function(href, title, text) {
19296 var out = '<img src="' + href + '" alt="' + text + '"';
19298 out += ' title="' + title + '"';
19300 out += this.options.xhtml ? '/>' : '>';
19304 Renderer.prototype.text = function(text) {
19309 * Parsing & Compiling
19315 var Parser= function (options) {
19318 this.options = options || marked.defaults;
19319 this.options.renderer = this.options.renderer || new Renderer;
19320 this.renderer = this.options.renderer;
19321 this.renderer.options = this.options;
19325 * Static Parse Method
19328 Parser.parse = function(src, options, renderer) {
19329 var parser = new Parser(options, renderer);
19330 return parser.parse(src);
19337 Parser.prototype.parse = function(src) {
19338 this.inline = new InlineLexer(src.links, this.options, this.renderer);
19339 this.tokens = src.reverse();
19342 while (this.next()) {
19353 Parser.prototype.next = function() {
19354 return this.token = this.tokens.pop();
19358 * Preview Next Token
19361 Parser.prototype.peek = function() {
19362 return this.tokens[this.tokens.length - 1] || 0;
19366 * Parse Text Tokens
19369 Parser.prototype.parseText = function() {
19370 var body = this.token.text;
19372 while (this.peek().type === 'text') {
19373 body += '\n' + this.next().text;
19376 return this.inline.output(body);
19380 * Parse Current Token
19383 Parser.prototype.tok = function() {
19384 switch (this.token.type) {
19389 return this.renderer.hr();
19392 return this.renderer.heading(
19393 this.inline.output(this.token.text),
19398 return this.renderer.code(this.token.text,
19400 this.token.escaped);
19413 for (i = 0; i < this.token.header.length; i++) {
19414 flags = { header: true, align: this.token.align[i] };
19415 cell += this.renderer.tablecell(
19416 this.inline.output(this.token.header[i]),
19417 { header: true, align: this.token.align[i] }
19420 header += this.renderer.tablerow(cell);
19422 for (i = 0; i < this.token.cells.length; i++) {
19423 row = this.token.cells[i];
19426 for (j = 0; j < row.length; j++) {
19427 cell += this.renderer.tablecell(
19428 this.inline.output(row[j]),
19429 { header: false, align: this.token.align[j] }
19433 body += this.renderer.tablerow(cell);
19435 return this.renderer.table(header, body);
19437 case 'blockquote_start': {
19440 while (this.next().type !== 'blockquote_end') {
19441 body += this.tok();
19444 return this.renderer.blockquote(body);
19446 case 'list_start': {
19448 , ordered = this.token.ordered;
19450 while (this.next().type !== 'list_end') {
19451 body += this.tok();
19454 return this.renderer.list(body, ordered);
19456 case 'list_item_start': {
19459 while (this.next().type !== 'list_item_end') {
19460 body += this.token.type === 'text'
19465 return this.renderer.listitem(body);
19467 case 'loose_item_start': {
19470 while (this.next().type !== 'list_item_end') {
19471 body += this.tok();
19474 return this.renderer.listitem(body);
19477 var html = !this.token.pre && !this.options.pedantic
19478 ? this.inline.output(this.token.text)
19480 return this.renderer.html(html);
19482 case 'paragraph': {
19483 return this.renderer.paragraph(this.inline.output(this.token.text));
19486 return this.renderer.paragraph(this.parseText());
19498 var marked = function (src, opt, callback) {
19499 if (callback || typeof opt === 'function') {
19505 opt = merge({}, marked.defaults, opt || {});
19507 var highlight = opt.highlight
19513 tokens = Lexer.lex(src, opt)
19515 return callback(e);
19518 pending = tokens.length;
19522 var done = function(err) {
19524 opt.highlight = highlight;
19525 return callback(err);
19531 out = Parser.parse(tokens, opt);
19536 opt.highlight = highlight;
19540 : callback(null, out);
19543 if (!highlight || highlight.length < 3) {
19547 delete opt.highlight;
19549 if (!pending) { return done(); }
19551 for (; i < tokens.length; i++) {
19553 if (token.type !== 'code') {
19554 return --pending || done();
19556 return highlight(token.text, token.lang, function(err, code) {
19557 if (err) { return done(err); }
19558 if (code == null || code === token.text) {
19559 return --pending || done();
19562 token.escaped = true;
19563 --pending || done();
19571 if (opt) { opt = merge({}, marked.defaults, opt); }
19572 return Parser.parse(Lexer.lex(src, opt), opt);
19574 e.message += '\nPlease report this to https://github.com/chjj/marked.';
19575 if ((opt || marked.defaults).silent) {
19576 return '<p>An error occured:</p><pre>'
19577 + escape(e.message + '', true)
19589 marked.setOptions = function(opt) {
19590 merge(marked.defaults, opt);
19594 marked.defaults = {
19605 langPrefix: 'lang-',
19606 smartypants: false,
19608 renderer: new Renderer,
19616 marked.Parser = Parser;
19617 marked.parser = Parser.parse;
19619 marked.Renderer = Renderer;
19621 marked.Lexer = Lexer;
19622 marked.lexer = Lexer.lex;
19624 marked.InlineLexer = InlineLexer;
19625 marked.inlineLexer = InlineLexer.output;
19627 marked.parse = marked;
19629 Roo.Markdown.marked = marked;
19633 * Ext JS Library 1.1.1
19634 * Copyright(c) 2006-2007, Ext JS, LLC.
19636 * Originally Released Under LGPL - original licence link has changed is not relivant.
19639 * <script type="text/javascript">
19645 * These classes are derivatives of the similarly named classes in the YUI Library.
19646 * The original license:
19647 * Copyright (c) 2006, Yahoo! Inc. All rights reserved.
19648 * Code licensed under the BSD License:
19649 * http://developer.yahoo.net/yui/license.txt
19654 var Event=Roo.EventManager;
19655 var Dom=Roo.lib.Dom;
19658 * @class Roo.dd.DragDrop
19659 * @extends Roo.util.Observable
19660 * Defines the interface and base operation of items that that can be
19661 * dragged or can be drop targets. It was designed to be extended, overriding
19662 * the event handlers for startDrag, onDrag, onDragOver and onDragOut.
19663 * Up to three html elements can be associated with a DragDrop instance:
19665 * <li>linked element: the element that is passed into the constructor.
19666 * This is the element which defines the boundaries for interaction with
19667 * other DragDrop objects.</li>
19668 * <li>handle element(s): The drag operation only occurs if the element that
19669 * was clicked matches a handle element. By default this is the linked
19670 * element, but there are times that you will want only a portion of the
19671 * linked element to initiate the drag operation, and the setHandleElId()
19672 * method provides a way to define this.</li>
19673 * <li>drag element: this represents the element that would be moved along
19674 * with the cursor during a drag operation. By default, this is the linked
19675 * element itself as in {@link Roo.dd.DD}. setDragElId() lets you define
19676 * a separate element that would be moved, as in {@link Roo.dd.DDProxy}.
19679 * This class should not be instantiated until the onload event to ensure that
19680 * the associated elements are available.
19681 * The following would define a DragDrop obj that would interact with any
19682 * other DragDrop obj in the "group1" group:
19684 * dd = new Roo.dd.DragDrop("div1", "group1");
19686 * Since none of the event handlers have been implemented, nothing would
19687 * actually happen if you were to run the code above. Normally you would
19688 * override this class or one of the default implementations, but you can
19689 * also override the methods you want on an instance of the class...
19691 * dd.onDragDrop = function(e, id) {
19692 * alert("dd was dropped on " + id);
19696 * @param {String} id of the element that is linked to this instance
19697 * @param {String} sGroup the group of related DragDrop objects
19698 * @param {object} config an object containing configurable attributes
19699 * Valid properties for DragDrop:
19700 * padding, isTarget, maintainOffset, primaryButtonOnly
19702 Roo.dd.DragDrop = function(id, sGroup, config) {
19704 this.init(id, sGroup, config);
19709 Roo.extend(Roo.dd.DragDrop, Roo.util.Observable , {
19712 * The id of the element associated with this object. This is what we
19713 * refer to as the "linked element" because the size and position of
19714 * this element is used to determine when the drag and drop objects have
19722 * Configuration attributes passed into the constructor
19729 * The id of the element that will be dragged. By default this is same
19730 * as the linked element , but could be changed to another element. Ex:
19732 * @property dragElId
19739 * the id of the element that initiates the drag operation. By default
19740 * this is the linked element, but could be changed to be a child of this
19741 * element. This lets us do things like only starting the drag when the
19742 * header element within the linked html element is clicked.
19743 * @property handleElId
19750 * An associative array of HTML tags that will be ignored if clicked.
19751 * @property invalidHandleTypes
19752 * @type {string: string}
19754 invalidHandleTypes: null,
19757 * An associative array of ids for elements that will be ignored if clicked
19758 * @property invalidHandleIds
19759 * @type {string: string}
19761 invalidHandleIds: null,
19764 * An indexted array of css class names for elements that will be ignored
19766 * @property invalidHandleClasses
19769 invalidHandleClasses: null,
19772 * The linked element's absolute X position at the time the drag was
19774 * @property startPageX
19781 * The linked element's absolute X position at the time the drag was
19783 * @property startPageY
19790 * The group defines a logical collection of DragDrop objects that are
19791 * related. Instances only get events when interacting with other
19792 * DragDrop object in the same group. This lets us define multiple
19793 * groups using a single DragDrop subclass if we want.
19795 * @type {string: string}
19800 * Individual drag/drop instances can be locked. This will prevent
19801 * onmousedown start drag.
19809 * Lock this instance
19812 lock: function() { this.locked = true; },
19815 * Unlock this instace
19818 unlock: function() { this.locked = false; },
19821 * By default, all insances can be a drop target. This can be disabled by
19822 * setting isTarget to false.
19829 * The padding configured for this drag and drop object for calculating
19830 * the drop zone intersection with this object.
19837 * Cached reference to the linked element
19838 * @property _domRef
19844 * Internal typeof flag
19845 * @property __ygDragDrop
19848 __ygDragDrop: true,
19851 * Set to true when horizontal contraints are applied
19852 * @property constrainX
19859 * Set to true when vertical contraints are applied
19860 * @property constrainY
19867 * The left constraint
19875 * The right constraint
19883 * The up constraint
19892 * The down constraint
19900 * Maintain offsets when we resetconstraints. Set to true when you want
19901 * the position of the element relative to its parent to stay the same
19902 * when the page changes
19904 * @property maintainOffset
19907 maintainOffset: false,
19910 * Array of pixel locations the element will snap to if we specified a
19911 * horizontal graduation/interval. This array is generated automatically
19912 * when you define a tick interval.
19919 * Array of pixel locations the element will snap to if we specified a
19920 * vertical graduation/interval. This array is generated automatically
19921 * when you define a tick interval.
19928 * By default the drag and drop instance will only respond to the primary
19929 * button click (left button for a right-handed mouse). Set to true to
19930 * allow drag and drop to start with any mouse click that is propogated
19932 * @property primaryButtonOnly
19935 primaryButtonOnly: true,
19938 * The availabe property is false until the linked dom element is accessible.
19939 * @property available
19945 * By default, drags can only be initiated if the mousedown occurs in the
19946 * region the linked element is. This is done in part to work around a
19947 * bug in some browsers that mis-report the mousedown if the previous
19948 * mouseup happened outside of the window. This property is set to true
19949 * if outer handles are defined.
19951 * @property hasOuterHandles
19955 hasOuterHandles: false,
19958 * Code that executes immediately before the startDrag event
19959 * @method b4StartDrag
19962 b4StartDrag: function(x, y) { },
19965 * Abstract method called after a drag/drop object is clicked
19966 * and the drag or mousedown time thresholds have beeen met.
19967 * @method startDrag
19968 * @param {int} X click location
19969 * @param {int} Y click location
19971 startDrag: function(x, y) { /* override this */ },
19974 * Code that executes immediately before the onDrag event
19978 b4Drag: function(e) { },
19981 * Abstract method called during the onMouseMove event while dragging an
19984 * @param {Event} e the mousemove event
19986 onDrag: function(e) { /* override this */ },
19989 * Abstract method called when this element fist begins hovering over
19990 * another DragDrop obj
19991 * @method onDragEnter
19992 * @param {Event} e the mousemove event
19993 * @param {String|DragDrop[]} id In POINT mode, the element
19994 * id this is hovering over. In INTERSECT mode, an array of one or more
19995 * dragdrop items being hovered over.
19997 onDragEnter: function(e, id) { /* override this */ },
20000 * Code that executes immediately before the onDragOver event
20001 * @method b4DragOver
20004 b4DragOver: function(e) { },
20007 * Abstract method called when this element is hovering over another
20009 * @method onDragOver
20010 * @param {Event} e the mousemove event
20011 * @param {String|DragDrop[]} id In POINT mode, the element
20012 * id this is hovering over. In INTERSECT mode, an array of dd items
20013 * being hovered over.
20015 onDragOver: function(e, id) { /* override this */ },
20018 * Code that executes immediately before the onDragOut event
20019 * @method b4DragOut
20022 b4DragOut: function(e) { },
20025 * Abstract method called when we are no longer hovering over an element
20026 * @method onDragOut
20027 * @param {Event} e the mousemove event
20028 * @param {String|DragDrop[]} id In POINT mode, the element
20029 * id this was hovering over. In INTERSECT mode, an array of dd items
20030 * that the mouse is no longer over.
20032 onDragOut: function(e, id) { /* override this */ },
20035 * Code that executes immediately before the onDragDrop event
20036 * @method b4DragDrop
20039 b4DragDrop: function(e) { },
20042 * Abstract method called when this item is dropped on another DragDrop
20044 * @method onDragDrop
20045 * @param {Event} e the mouseup event
20046 * @param {String|DragDrop[]} id In POINT mode, the element
20047 * id this was dropped on. In INTERSECT mode, an array of dd items this
20050 onDragDrop: function(e, id) { /* override this */ },
20053 * Abstract method called when this item is dropped on an area with no
20055 * @method onInvalidDrop
20056 * @param {Event} e the mouseup event
20058 onInvalidDrop: function(e) { /* override this */ },
20061 * Code that executes immediately before the endDrag event
20062 * @method b4EndDrag
20065 b4EndDrag: function(e) { },
20068 * Fired when we are done dragging the object
20070 * @param {Event} e the mouseup event
20072 endDrag: function(e) { /* override this */ },
20075 * Code executed immediately before the onMouseDown event
20076 * @method b4MouseDown
20077 * @param {Event} e the mousedown event
20080 b4MouseDown: function(e) { },
20083 * Event handler that fires when a drag/drop obj gets a mousedown
20084 * @method onMouseDown
20085 * @param {Event} e the mousedown event
20087 onMouseDown: function(e) { /* override this */ },
20090 * Event handler that fires when a drag/drop obj gets a mouseup
20091 * @method onMouseUp
20092 * @param {Event} e the mouseup event
20094 onMouseUp: function(e) { /* override this */ },
20097 * Override the onAvailable method to do what is needed after the initial
20098 * position was determined.
20099 * @method onAvailable
20101 onAvailable: function () {
20105 * Provides default constraint padding to "constrainTo" elements (defaults to {left: 0, right:0, top:0, bottom:0}).
20108 defaultPadding : {left:0, right:0, top:0, bottom:0},
20111 * Initializes the drag drop object's constraints to restrict movement to a certain element.
20115 var dd = new Roo.dd.DDProxy("dragDiv1", "proxytest",
20116 { dragElId: "existingProxyDiv" });
20117 dd.startDrag = function(){
20118 this.constrainTo("parent-id");
20121 * Or you can initalize it using the {@link Roo.Element} object:
20123 Roo.get("dragDiv1").initDDProxy("proxytest", {dragElId: "existingProxyDiv"}, {
20124 startDrag : function(){
20125 this.constrainTo("parent-id");
20129 * @param {String/HTMLElement/Element} constrainTo The element to constrain to.
20130 * @param {Object/Number} pad (optional) Pad provides a way to specify "padding" of the constraints,
20131 * and can be either a number for symmetrical padding (4 would be equal to {left:4, right:4, top:4, bottom:4}) or
20132 * an object containing the sides to pad. For example: {right:10, bottom:10}
20133 * @param {Boolean} inContent (optional) Constrain the draggable in the content box of the element (inside padding and borders)
20135 constrainTo : function(constrainTo, pad, inContent){
20136 if(typeof pad == "number"){
20137 pad = {left: pad, right:pad, top:pad, bottom:pad};
20139 pad = pad || this.defaultPadding;
20140 var b = Roo.get(this.getEl()).getBox();
20141 var ce = Roo.get(constrainTo);
20142 var s = ce.getScroll();
20143 var c, cd = ce.dom;
20144 if(cd == document.body){
20145 c = { x: s.left, y: s.top, width: Roo.lib.Dom.getViewWidth(), height: Roo.lib.Dom.getViewHeight()};
20148 c = {x : xy[0]+s.left, y: xy[1]+s.top, width: cd.clientWidth, height: cd.clientHeight};
20152 var topSpace = b.y - c.y;
20153 var leftSpace = b.x - c.x;
20155 this.resetConstraints();
20156 this.setXConstraint(leftSpace - (pad.left||0), // left
20157 c.width - leftSpace - b.width - (pad.right||0) //right
20159 this.setYConstraint(topSpace - (pad.top||0), //top
20160 c.height - topSpace - b.height - (pad.bottom||0) //bottom
20165 * Returns a reference to the linked element
20167 * @return {HTMLElement} the html element
20169 getEl: function() {
20170 if (!this._domRef) {
20171 this._domRef = Roo.getDom(this.id);
20174 return this._domRef;
20178 * Returns a reference to the actual element to drag. By default this is
20179 * the same as the html element, but it can be assigned to another
20180 * element. An example of this can be found in Roo.dd.DDProxy
20181 * @method getDragEl
20182 * @return {HTMLElement} the html element
20184 getDragEl: function() {
20185 return Roo.getDom(this.dragElId);
20189 * Sets up the DragDrop object. Must be called in the constructor of any
20190 * Roo.dd.DragDrop subclass
20192 * @param id the id of the linked element
20193 * @param {String} sGroup the group of related items
20194 * @param {object} config configuration attributes
20196 init: function(id, sGroup, config) {
20197 this.initTarget(id, sGroup, config);
20198 if (!Roo.isTouch) {
20199 Event.on(this.id, "mousedown", this.handleMouseDown, this);
20201 Event.on(this.id, "touchstart", this.handleMouseDown, this);
20202 // Event.on(this.id, "selectstart", Event.preventDefault);
20206 * Initializes Targeting functionality only... the object does not
20207 * get a mousedown handler.
20208 * @method initTarget
20209 * @param id the id of the linked element
20210 * @param {String} sGroup the group of related items
20211 * @param {object} config configuration attributes
20213 initTarget: function(id, sGroup, config) {
20215 // configuration attributes
20216 this.config = config || {};
20218 // create a local reference to the drag and drop manager
20219 this.DDM = Roo.dd.DDM;
20220 // initialize the groups array
20223 // assume that we have an element reference instead of an id if the
20224 // parameter is not a string
20225 if (typeof id !== "string") {
20232 // add to an interaction group
20233 this.addToGroup((sGroup) ? sGroup : "default");
20235 // We don't want to register this as the handle with the manager
20236 // so we just set the id rather than calling the setter.
20237 this.handleElId = id;
20239 // the linked element is the element that gets dragged by default
20240 this.setDragElId(id);
20242 // by default, clicked anchors will not start drag operations.
20243 this.invalidHandleTypes = { A: "A" };
20244 this.invalidHandleIds = {};
20245 this.invalidHandleClasses = [];
20247 this.applyConfig();
20249 this.handleOnAvailable();
20253 * Applies the configuration parameters that were passed into the constructor.
20254 * This is supposed to happen at each level through the inheritance chain. So
20255 * a DDProxy implentation will execute apply config on DDProxy, DD, and
20256 * DragDrop in order to get all of the parameters that are available in
20258 * @method applyConfig
20260 applyConfig: function() {
20262 // configurable properties:
20263 // padding, isTarget, maintainOffset, primaryButtonOnly
20264 this.padding = this.config.padding || [0, 0, 0, 0];
20265 this.isTarget = (this.config.isTarget !== false);
20266 this.maintainOffset = (this.config.maintainOffset);
20267 this.primaryButtonOnly = (this.config.primaryButtonOnly !== false);
20272 * Executed when the linked element is available
20273 * @method handleOnAvailable
20276 handleOnAvailable: function() {
20277 this.available = true;
20278 this.resetConstraints();
20279 this.onAvailable();
20283 * Configures the padding for the target zone in px. Effectively expands
20284 * (or reduces) the virtual object size for targeting calculations.
20285 * Supports css-style shorthand; if only one parameter is passed, all sides
20286 * will have that padding, and if only two are passed, the top and bottom
20287 * will have the first param, the left and right the second.
20288 * @method setPadding
20289 * @param {int} iTop Top pad
20290 * @param {int} iRight Right pad
20291 * @param {int} iBot Bot pad
20292 * @param {int} iLeft Left pad
20294 setPadding: function(iTop, iRight, iBot, iLeft) {
20295 // this.padding = [iLeft, iRight, iTop, iBot];
20296 if (!iRight && 0 !== iRight) {
20297 this.padding = [iTop, iTop, iTop, iTop];
20298 } else if (!iBot && 0 !== iBot) {
20299 this.padding = [iTop, iRight, iTop, iRight];
20301 this.padding = [iTop, iRight, iBot, iLeft];
20306 * Stores the initial placement of the linked element.
20307 * @method setInitialPosition
20308 * @param {int} diffX the X offset, default 0
20309 * @param {int} diffY the Y offset, default 0
20311 setInitPosition: function(diffX, diffY) {
20312 var el = this.getEl();
20314 if (!this.DDM.verifyEl(el)) {
20318 var dx = diffX || 0;
20319 var dy = diffY || 0;
20321 var p = Dom.getXY( el );
20323 this.initPageX = p[0] - dx;
20324 this.initPageY = p[1] - dy;
20326 this.lastPageX = p[0];
20327 this.lastPageY = p[1];
20330 this.setStartPosition(p);
20334 * Sets the start position of the element. This is set when the obj
20335 * is initialized, the reset when a drag is started.
20336 * @method setStartPosition
20337 * @param pos current position (from previous lookup)
20340 setStartPosition: function(pos) {
20341 var p = pos || Dom.getXY( this.getEl() );
20342 this.deltaSetXY = null;
20344 this.startPageX = p[0];
20345 this.startPageY = p[1];
20349 * Add this instance to a group of related drag/drop objects. All
20350 * instances belong to at least one group, and can belong to as many
20351 * groups as needed.
20352 * @method addToGroup
20353 * @param sGroup {string} the name of the group
20355 addToGroup: function(sGroup) {
20356 this.groups[sGroup] = true;
20357 this.DDM.regDragDrop(this, sGroup);
20361 * Remove's this instance from the supplied interaction group
20362 * @method removeFromGroup
20363 * @param {string} sGroup The group to drop
20365 removeFromGroup: function(sGroup) {
20366 if (this.groups[sGroup]) {
20367 delete this.groups[sGroup];
20370 this.DDM.removeDDFromGroup(this, sGroup);
20374 * Allows you to specify that an element other than the linked element
20375 * will be moved with the cursor during a drag
20376 * @method setDragElId
20377 * @param id {string} the id of the element that will be used to initiate the drag
20379 setDragElId: function(id) {
20380 this.dragElId = id;
20384 * Allows you to specify a child of the linked element that should be
20385 * used to initiate the drag operation. An example of this would be if
20386 * you have a content div with text and links. Clicking anywhere in the
20387 * content area would normally start the drag operation. Use this method
20388 * to specify that an element inside of the content div is the element
20389 * that starts the drag operation.
20390 * @method setHandleElId
20391 * @param id {string} the id of the element that will be used to
20392 * initiate the drag.
20394 setHandleElId: function(id) {
20395 if (typeof id !== "string") {
20398 this.handleElId = id;
20399 this.DDM.regHandle(this.id, id);
20403 * Allows you to set an element outside of the linked element as a drag
20405 * @method setOuterHandleElId
20406 * @param id the id of the element that will be used to initiate the drag
20408 setOuterHandleElId: function(id) {
20409 if (typeof id !== "string") {
20412 Event.on(id, "mousedown",
20413 this.handleMouseDown, this);
20414 this.setHandleElId(id);
20416 this.hasOuterHandles = true;
20420 * Remove all drag and drop hooks for this element
20423 unreg: function() {
20424 Event.un(this.id, "mousedown",
20425 this.handleMouseDown);
20426 Event.un(this.id, "touchstart",
20427 this.handleMouseDown);
20428 this._domRef = null;
20429 this.DDM._remove(this);
20432 destroy : function(){
20437 * Returns true if this instance is locked, or the drag drop mgr is locked
20438 * (meaning that all drag/drop is disabled on the page.)
20440 * @return {boolean} true if this obj or all drag/drop is locked, else
20443 isLocked: function() {
20444 return (this.DDM.isLocked() || this.locked);
20448 * Fired when this object is clicked
20449 * @method handleMouseDown
20451 * @param {Roo.dd.DragDrop} oDD the clicked dd object (this dd obj)
20454 handleMouseDown: function(e, oDD){
20456 if (!Roo.isTouch && this.primaryButtonOnly && e.button != 0) {
20457 //Roo.log('not touch/ button !=0');
20460 if (e.browserEvent.touches && e.browserEvent.touches.length != 1) {
20461 return; // double touch..
20465 if (this.isLocked()) {
20466 //Roo.log('locked');
20470 this.DDM.refreshCache(this.groups);
20471 // Roo.log([Roo.lib.Event.getPageX(e), Roo.lib.Event.getPageY(e)]);
20472 var pt = new Roo.lib.Point(Roo.lib.Event.getPageX(e), Roo.lib.Event.getPageY(e));
20473 if (!this.hasOuterHandles && !this.DDM.isOverTarget(pt, this) ) {
20474 //Roo.log('no outer handes or not over target');
20477 // Roo.log('check validator');
20478 if (this.clickValidator(e)) {
20479 // Roo.log('validate success');
20480 // set the initial element position
20481 this.setStartPosition();
20484 this.b4MouseDown(e);
20485 this.onMouseDown(e);
20487 this.DDM.handleMouseDown(e, this);
20489 this.DDM.stopEvent(e);
20497 clickValidator: function(e) {
20498 var target = e.getTarget();
20499 return ( this.isValidHandleChild(target) &&
20500 (this.id == this.handleElId ||
20501 this.DDM.handleWasClicked(target, this.id)) );
20505 * Allows you to specify a tag name that should not start a drag operation
20506 * when clicked. This is designed to facilitate embedding links within a
20507 * drag handle that do something other than start the drag.
20508 * @method addInvalidHandleType
20509 * @param {string} tagName the type of element to exclude
20511 addInvalidHandleType: function(tagName) {
20512 var type = tagName.toUpperCase();
20513 this.invalidHandleTypes[type] = type;
20517 * Lets you to specify an element id for a child of a drag handle
20518 * that should not initiate a drag
20519 * @method addInvalidHandleId
20520 * @param {string} id the element id of the element you wish to ignore
20522 addInvalidHandleId: function(id) {
20523 if (typeof id !== "string") {
20526 this.invalidHandleIds[id] = id;
20530 * Lets you specify a css class of elements that will not initiate a drag
20531 * @method addInvalidHandleClass
20532 * @param {string} cssClass the class of the elements you wish to ignore
20534 addInvalidHandleClass: function(cssClass) {
20535 this.invalidHandleClasses.push(cssClass);
20539 * Unsets an excluded tag name set by addInvalidHandleType
20540 * @method removeInvalidHandleType
20541 * @param {string} tagName the type of element to unexclude
20543 removeInvalidHandleType: function(tagName) {
20544 var type = tagName.toUpperCase();
20545 // this.invalidHandleTypes[type] = null;
20546 delete this.invalidHandleTypes[type];
20550 * Unsets an invalid handle id
20551 * @method removeInvalidHandleId
20552 * @param {string} id the id of the element to re-enable
20554 removeInvalidHandleId: function(id) {
20555 if (typeof id !== "string") {
20558 delete this.invalidHandleIds[id];
20562 * Unsets an invalid css class
20563 * @method removeInvalidHandleClass
20564 * @param {string} cssClass the class of the element(s) you wish to
20567 removeInvalidHandleClass: function(cssClass) {
20568 for (var i=0, len=this.invalidHandleClasses.length; i<len; ++i) {
20569 if (this.invalidHandleClasses[i] == cssClass) {
20570 delete this.invalidHandleClasses[i];
20576 * Checks the tag exclusion list to see if this click should be ignored
20577 * @method isValidHandleChild
20578 * @param {HTMLElement} node the HTMLElement to evaluate
20579 * @return {boolean} true if this is a valid tag type, false if not
20581 isValidHandleChild: function(node) {
20584 // var n = (node.nodeName == "#text") ? node.parentNode : node;
20587 nodeName = node.nodeName.toUpperCase();
20589 nodeName = node.nodeName;
20591 valid = valid && !this.invalidHandleTypes[nodeName];
20592 valid = valid && !this.invalidHandleIds[node.id];
20594 for (var i=0, len=this.invalidHandleClasses.length; valid && i<len; ++i) {
20595 valid = !Dom.hasClass(node, this.invalidHandleClasses[i]);
20604 * Create the array of horizontal tick marks if an interval was specified
20605 * in setXConstraint().
20606 * @method setXTicks
20609 setXTicks: function(iStartX, iTickSize) {
20611 this.xTickSize = iTickSize;
20615 for (var i = this.initPageX; i >= this.minX; i = i - iTickSize) {
20617 this.xTicks[this.xTicks.length] = i;
20622 for (i = this.initPageX; i <= this.maxX; i = i + iTickSize) {
20624 this.xTicks[this.xTicks.length] = i;
20629 this.xTicks.sort(this.DDM.numericSort) ;
20633 * Create the array of vertical tick marks if an interval was specified in
20634 * setYConstraint().
20635 * @method setYTicks
20638 setYTicks: function(iStartY, iTickSize) {
20640 this.yTickSize = iTickSize;
20644 for (var i = this.initPageY; i >= this.minY; i = i - iTickSize) {
20646 this.yTicks[this.yTicks.length] = i;
20651 for (i = this.initPageY; i <= this.maxY; i = i + iTickSize) {
20653 this.yTicks[this.yTicks.length] = i;
20658 this.yTicks.sort(this.DDM.numericSort) ;
20662 * By default, the element can be dragged any place on the screen. Use
20663 * this method to limit the horizontal travel of the element. Pass in
20664 * 0,0 for the parameters if you want to lock the drag to the y axis.
20665 * @method setXConstraint
20666 * @param {int} iLeft the number of pixels the element can move to the left
20667 * @param {int} iRight the number of pixels the element can move to the
20669 * @param {int} iTickSize optional parameter for specifying that the
20671 * should move iTickSize pixels at a time.
20673 setXConstraint: function(iLeft, iRight, iTickSize) {
20674 this.leftConstraint = iLeft;
20675 this.rightConstraint = iRight;
20677 this.minX = this.initPageX - iLeft;
20678 this.maxX = this.initPageX + iRight;
20679 if (iTickSize) { this.setXTicks(this.initPageX, iTickSize); }
20681 this.constrainX = true;
20685 * Clears any constraints applied to this instance. Also clears ticks
20686 * since they can't exist independent of a constraint at this time.
20687 * @method clearConstraints
20689 clearConstraints: function() {
20690 this.constrainX = false;
20691 this.constrainY = false;
20696 * Clears any tick interval defined for this instance
20697 * @method clearTicks
20699 clearTicks: function() {
20700 this.xTicks = null;
20701 this.yTicks = null;
20702 this.xTickSize = 0;
20703 this.yTickSize = 0;
20707 * By default, the element can be dragged any place on the screen. Set
20708 * this to limit the vertical travel of the element. Pass in 0,0 for the
20709 * parameters if you want to lock the drag to the x axis.
20710 * @method setYConstraint
20711 * @param {int} iUp the number of pixels the element can move up
20712 * @param {int} iDown the number of pixels the element can move down
20713 * @param {int} iTickSize optional parameter for specifying that the
20714 * element should move iTickSize pixels at a time.
20716 setYConstraint: function(iUp, iDown, iTickSize) {
20717 this.topConstraint = iUp;
20718 this.bottomConstraint = iDown;
20720 this.minY = this.initPageY - iUp;
20721 this.maxY = this.initPageY + iDown;
20722 if (iTickSize) { this.setYTicks(this.initPageY, iTickSize); }
20724 this.constrainY = true;
20729 * resetConstraints must be called if you manually reposition a dd element.
20730 * @method resetConstraints
20731 * @param {boolean} maintainOffset
20733 resetConstraints: function() {
20736 // Maintain offsets if necessary
20737 if (this.initPageX || this.initPageX === 0) {
20738 // figure out how much this thing has moved
20739 var dx = (this.maintainOffset) ? this.lastPageX - this.initPageX : 0;
20740 var dy = (this.maintainOffset) ? this.lastPageY - this.initPageY : 0;
20742 this.setInitPosition(dx, dy);
20744 // This is the first time we have detected the element's position
20746 this.setInitPosition();
20749 if (this.constrainX) {
20750 this.setXConstraint( this.leftConstraint,
20751 this.rightConstraint,
20755 if (this.constrainY) {
20756 this.setYConstraint( this.topConstraint,
20757 this.bottomConstraint,
20763 * Normally the drag element is moved pixel by pixel, but we can specify
20764 * that it move a number of pixels at a time. This method resolves the
20765 * location when we have it set up like this.
20767 * @param {int} val where we want to place the object
20768 * @param {int[]} tickArray sorted array of valid points
20769 * @return {int} the closest tick
20772 getTick: function(val, tickArray) {
20775 // If tick interval is not defined, it is effectively 1 pixel,
20776 // so we return the value passed to us.
20778 } else if (tickArray[0] >= val) {
20779 // The value is lower than the first tick, so we return the first
20781 return tickArray[0];
20783 for (var i=0, len=tickArray.length; i<len; ++i) {
20785 if (tickArray[next] && tickArray[next] >= val) {
20786 var diff1 = val - tickArray[i];
20787 var diff2 = tickArray[next] - val;
20788 return (diff2 > diff1) ? tickArray[i] : tickArray[next];
20792 // The value is larger than the last tick, so we return the last
20794 return tickArray[tickArray.length - 1];
20801 * @return {string} string representation of the dd obj
20803 toString: function() {
20804 return ("DragDrop " + this.id);
20812 * Ext JS Library 1.1.1
20813 * Copyright(c) 2006-2007, Ext JS, LLC.
20815 * Originally Released Under LGPL - original licence link has changed is not relivant.
20818 * <script type="text/javascript">
20823 * The drag and drop utility provides a framework for building drag and drop
20824 * applications. In addition to enabling drag and drop for specific elements,
20825 * the drag and drop elements are tracked by the manager class, and the
20826 * interactions between the various elements are tracked during the drag and
20827 * the implementing code is notified about these important moments.
20830 // Only load the library once. Rewriting the manager class would orphan
20831 // existing drag and drop instances.
20832 if (!Roo.dd.DragDropMgr) {
20835 * @class Roo.dd.DragDropMgr
20836 * DragDropMgr is a singleton that tracks the element interaction for
20837 * all DragDrop items in the window. Generally, you will not call
20838 * this class directly, but it does have helper methods that could
20839 * be useful in your DragDrop implementations.
20842 Roo.dd.DragDropMgr = function() {
20844 var Event = Roo.EventManager;
20849 * Two dimensional Array of registered DragDrop objects. The first
20850 * dimension is the DragDrop item group, the second the DragDrop
20853 * @type {string: string}
20860 * Array of element ids defined as drag handles. Used to determine
20861 * if the element that generated the mousedown event is actually the
20862 * handle and not the html element itself.
20863 * @property handleIds
20864 * @type {string: string}
20871 * the DragDrop object that is currently being dragged
20872 * @property dragCurrent
20880 * the DragDrop object(s) that are being hovered over
20881 * @property dragOvers
20889 * the X distance between the cursor and the object being dragged
20898 * the Y distance between the cursor and the object being dragged
20907 * Flag to determine if we should prevent the default behavior of the
20908 * events we define. By default this is true, but this can be set to
20909 * false if you need the default behavior (not recommended)
20910 * @property preventDefault
20914 preventDefault: true,
20917 * Flag to determine if we should stop the propagation of the events
20918 * we generate. This is true by default but you may want to set it to
20919 * false if the html element contains other features that require the
20921 * @property stopPropagation
20925 stopPropagation: true,
20928 * Internal flag that is set to true when drag and drop has been
20930 * @property initialized
20937 * All drag and drop can be disabled.
20945 * Called the first time an element is registered.
20951 this.initialized = true;
20955 * In point mode, drag and drop interaction is defined by the
20956 * location of the cursor during the drag/drop
20964 * In intersect mode, drag and drop interactio nis defined by the
20965 * overlap of two or more drag and drop objects.
20966 * @property INTERSECT
20973 * The current drag and drop mode. Default: POINT
20981 * Runs method on all drag and drop objects
20982 * @method _execOnAll
20986 _execOnAll: function(sMethod, args) {
20987 for (var i in this.ids) {
20988 for (var j in this.ids[i]) {
20989 var oDD = this.ids[i][j];
20990 if (! this.isTypeOfDD(oDD)) {
20993 oDD[sMethod].apply(oDD, args);
20999 * Drag and drop initialization. Sets up the global event handlers
21004 _onLoad: function() {
21008 if (!Roo.isTouch) {
21009 Event.on(document, "mouseup", this.handleMouseUp, this, true);
21010 Event.on(document, "mousemove", this.handleMouseMove, this, true);
21012 Event.on(document, "touchend", this.handleMouseUp, this, true);
21013 Event.on(document, "touchmove", this.handleMouseMove, this, true);
21015 Event.on(window, "unload", this._onUnload, this, true);
21016 Event.on(window, "resize", this._onResize, this, true);
21017 // Event.on(window, "mouseout", this._test);
21022 * Reset constraints on all drag and drop objs
21023 * @method _onResize
21027 _onResize: function(e) {
21028 this._execOnAll("resetConstraints", []);
21032 * Lock all drag and drop functionality
21036 lock: function() { this.locked = true; },
21039 * Unlock all drag and drop functionality
21043 unlock: function() { this.locked = false; },
21046 * Is drag and drop locked?
21048 * @return {boolean} True if drag and drop is locked, false otherwise.
21051 isLocked: function() { return this.locked; },
21054 * Location cache that is set for all drag drop objects when a drag is
21055 * initiated, cleared when the drag is finished.
21056 * @property locationCache
21063 * Set useCache to false if you want to force object the lookup of each
21064 * drag and drop linked element constantly during a drag.
21065 * @property useCache
21072 * The number of pixels that the mouse needs to move after the
21073 * mousedown before the drag is initiated. Default=3;
21074 * @property clickPixelThresh
21078 clickPixelThresh: 3,
21081 * The number of milliseconds after the mousedown event to initiate the
21082 * drag if we don't get a mouseup event. Default=1000
21083 * @property clickTimeThresh
21087 clickTimeThresh: 350,
21090 * Flag that indicates that either the drag pixel threshold or the
21091 * mousdown time threshold has been met
21092 * @property dragThreshMet
21097 dragThreshMet: false,
21100 * Timeout used for the click time threshold
21101 * @property clickTimeout
21106 clickTimeout: null,
21109 * The X position of the mousedown event stored for later use when a
21110 * drag threshold is met.
21119 * The Y position of the mousedown event stored for later use when a
21120 * drag threshold is met.
21129 * Each DragDrop instance must be registered with the DragDropMgr.
21130 * This is executed in DragDrop.init()
21131 * @method regDragDrop
21132 * @param {DragDrop} oDD the DragDrop object to register
21133 * @param {String} sGroup the name of the group this element belongs to
21136 regDragDrop: function(oDD, sGroup) {
21137 if (!this.initialized) { this.init(); }
21139 if (!this.ids[sGroup]) {
21140 this.ids[sGroup] = {};
21142 this.ids[sGroup][oDD.id] = oDD;
21146 * Removes the supplied dd instance from the supplied group. Executed
21147 * by DragDrop.removeFromGroup, so don't call this function directly.
21148 * @method removeDDFromGroup
21152 removeDDFromGroup: function(oDD, sGroup) {
21153 if (!this.ids[sGroup]) {
21154 this.ids[sGroup] = {};
21157 var obj = this.ids[sGroup];
21158 if (obj && obj[oDD.id]) {
21159 delete obj[oDD.id];
21164 * Unregisters a drag and drop item. This is executed in
21165 * DragDrop.unreg, use that method instead of calling this directly.
21170 _remove: function(oDD) {
21171 for (var g in oDD.groups) {
21172 if (g && this.ids[g][oDD.id]) {
21173 delete this.ids[g][oDD.id];
21176 delete this.handleIds[oDD.id];
21180 * Each DragDrop handle element must be registered. This is done
21181 * automatically when executing DragDrop.setHandleElId()
21182 * @method regHandle
21183 * @param {String} sDDId the DragDrop id this element is a handle for
21184 * @param {String} sHandleId the id of the element that is the drag
21188 regHandle: function(sDDId, sHandleId) {
21189 if (!this.handleIds[sDDId]) {
21190 this.handleIds[sDDId] = {};
21192 this.handleIds[sDDId][sHandleId] = sHandleId;
21196 * Utility function to determine if a given element has been
21197 * registered as a drag drop item.
21198 * @method isDragDrop
21199 * @param {String} id the element id to check
21200 * @return {boolean} true if this element is a DragDrop item,
21204 isDragDrop: function(id) {
21205 return ( this.getDDById(id) ) ? true : false;
21209 * Returns the drag and drop instances that are in all groups the
21210 * passed in instance belongs to.
21211 * @method getRelated
21212 * @param {DragDrop} p_oDD the obj to get related data for
21213 * @param {boolean} bTargetsOnly if true, only return targetable objs
21214 * @return {DragDrop[]} the related instances
21217 getRelated: function(p_oDD, bTargetsOnly) {
21219 for (var i in p_oDD.groups) {
21220 for (j in this.ids[i]) {
21221 var dd = this.ids[i][j];
21222 if (! this.isTypeOfDD(dd)) {
21225 if (!bTargetsOnly || dd.isTarget) {
21226 oDDs[oDDs.length] = dd;
21235 * Returns true if the specified dd target is a legal target for
21236 * the specifice drag obj
21237 * @method isLegalTarget
21238 * @param {DragDrop} the drag obj
21239 * @param {DragDrop} the target
21240 * @return {boolean} true if the target is a legal target for the
21244 isLegalTarget: function (oDD, oTargetDD) {
21245 var targets = this.getRelated(oDD, true);
21246 for (var i=0, len=targets.length;i<len;++i) {
21247 if (targets[i].id == oTargetDD.id) {
21256 * My goal is to be able to transparently determine if an object is
21257 * typeof DragDrop, and the exact subclass of DragDrop. typeof
21258 * returns "object", oDD.constructor.toString() always returns
21259 * "DragDrop" and not the name of the subclass. So for now it just
21260 * evaluates a well-known variable in DragDrop.
21261 * @method isTypeOfDD
21262 * @param {Object} the object to evaluate
21263 * @return {boolean} true if typeof oDD = DragDrop
21266 isTypeOfDD: function (oDD) {
21267 return (oDD && oDD.__ygDragDrop);
21271 * Utility function to determine if a given element has been
21272 * registered as a drag drop handle for the given Drag Drop object.
21274 * @param {String} id the element id to check
21275 * @return {boolean} true if this element is a DragDrop handle, false
21279 isHandle: function(sDDId, sHandleId) {
21280 return ( this.handleIds[sDDId] &&
21281 this.handleIds[sDDId][sHandleId] );
21285 * Returns the DragDrop instance for a given id
21286 * @method getDDById
21287 * @param {String} id the id of the DragDrop object
21288 * @return {DragDrop} the drag drop object, null if it is not found
21291 getDDById: function(id) {
21292 for (var i in this.ids) {
21293 if (this.ids[i][id]) {
21294 return this.ids[i][id];
21301 * Fired after a registered DragDrop object gets the mousedown event.
21302 * Sets up the events required to track the object being dragged
21303 * @method handleMouseDown
21304 * @param {Event} e the event
21305 * @param oDD the DragDrop object being dragged
21309 handleMouseDown: function(e, oDD) {
21311 Roo.QuickTips.disable();
21313 this.currentTarget = e.getTarget();
21315 this.dragCurrent = oDD;
21317 var el = oDD.getEl();
21319 // track start position
21320 this.startX = e.getPageX();
21321 this.startY = e.getPageY();
21323 this.deltaX = this.startX - el.offsetLeft;
21324 this.deltaY = this.startY - el.offsetTop;
21326 this.dragThreshMet = false;
21328 this.clickTimeout = setTimeout(
21330 var DDM = Roo.dd.DDM;
21331 DDM.startDrag(DDM.startX, DDM.startY);
21333 this.clickTimeThresh );
21337 * Fired when either the drag pixel threshol or the mousedown hold
21338 * time threshold has been met.
21339 * @method startDrag
21340 * @param x {int} the X position of the original mousedown
21341 * @param y {int} the Y position of the original mousedown
21344 startDrag: function(x, y) {
21345 clearTimeout(this.clickTimeout);
21346 if (this.dragCurrent) {
21347 this.dragCurrent.b4StartDrag(x, y);
21348 this.dragCurrent.startDrag(x, y);
21350 this.dragThreshMet = true;
21354 * Internal function to handle the mouseup event. Will be invoked
21355 * from the context of the document.
21356 * @method handleMouseUp
21357 * @param {Event} e the event
21361 handleMouseUp: function(e) {
21364 Roo.QuickTips.enable();
21366 if (! this.dragCurrent) {
21370 clearTimeout(this.clickTimeout);
21372 if (this.dragThreshMet) {
21373 this.fireEvents(e, true);
21383 * Utility to stop event propagation and event default, if these
21384 * features are turned on.
21385 * @method stopEvent
21386 * @param {Event} e the event as returned by this.getEvent()
21389 stopEvent: function(e){
21390 if(this.stopPropagation) {
21391 e.stopPropagation();
21394 if (this.preventDefault) {
21395 e.preventDefault();
21400 * Internal function to clean up event handlers after the drag
21401 * operation is complete
21403 * @param {Event} e the event
21407 stopDrag: function(e) {
21408 // Fire the drag end event for the item that was dragged
21409 if (this.dragCurrent) {
21410 if (this.dragThreshMet) {
21411 this.dragCurrent.b4EndDrag(e);
21412 this.dragCurrent.endDrag(e);
21415 this.dragCurrent.onMouseUp(e);
21418 this.dragCurrent = null;
21419 this.dragOvers = {};
21423 * Internal function to handle the mousemove event. Will be invoked
21424 * from the context of the html element.
21426 * @TODO figure out what we can do about mouse events lost when the
21427 * user drags objects beyond the window boundary. Currently we can
21428 * detect this in internet explorer by verifying that the mouse is
21429 * down during the mousemove event. Firefox doesn't give us the
21430 * button state on the mousemove event.
21431 * @method handleMouseMove
21432 * @param {Event} e the event
21436 handleMouseMove: function(e) {
21437 if (! this.dragCurrent) {
21441 // var button = e.which || e.button;
21443 // check for IE mouseup outside of page boundary
21444 if (Roo.isIE && (e.button !== 0 && e.button !== 1 && e.button !== 2)) {
21446 return this.handleMouseUp(e);
21449 if (!this.dragThreshMet) {
21450 var diffX = Math.abs(this.startX - e.getPageX());
21451 var diffY = Math.abs(this.startY - e.getPageY());
21452 if (diffX > this.clickPixelThresh ||
21453 diffY > this.clickPixelThresh) {
21454 this.startDrag(this.startX, this.startY);
21458 if (this.dragThreshMet) {
21459 this.dragCurrent.b4Drag(e);
21460 this.dragCurrent.onDrag(e);
21461 if(!this.dragCurrent.moveOnly){
21462 this.fireEvents(e, false);
21472 * Iterates over all of the DragDrop elements to find ones we are
21473 * hovering over or dropping on
21474 * @method fireEvents
21475 * @param {Event} e the event
21476 * @param {boolean} isDrop is this a drop op or a mouseover op?
21480 fireEvents: function(e, isDrop) {
21481 var dc = this.dragCurrent;
21483 // If the user did the mouse up outside of the window, we could
21484 // get here even though we have ended the drag.
21485 if (!dc || dc.isLocked()) {
21489 var pt = e.getPoint();
21491 // cache the previous dragOver array
21497 var enterEvts = [];
21499 // Check to see if the object(s) we were hovering over is no longer
21500 // being hovered over so we can fire the onDragOut event
21501 for (var i in this.dragOvers) {
21503 var ddo = this.dragOvers[i];
21505 if (! this.isTypeOfDD(ddo)) {
21509 if (! this.isOverTarget(pt, ddo, this.mode)) {
21510 outEvts.push( ddo );
21513 oldOvers[i] = true;
21514 delete this.dragOvers[i];
21517 for (var sGroup in dc.groups) {
21519 if ("string" != typeof sGroup) {
21523 for (i in this.ids[sGroup]) {
21524 var oDD = this.ids[sGroup][i];
21525 if (! this.isTypeOfDD(oDD)) {
21529 if (oDD.isTarget && !oDD.isLocked() && oDD != dc) {
21530 if (this.isOverTarget(pt, oDD, this.mode)) {
21531 // look for drop interactions
21533 dropEvts.push( oDD );
21534 // look for drag enter and drag over interactions
21537 // initial drag over: dragEnter fires
21538 if (!oldOvers[oDD.id]) {
21539 enterEvts.push( oDD );
21540 // subsequent drag overs: dragOver fires
21542 overEvts.push( oDD );
21545 this.dragOvers[oDD.id] = oDD;
21553 if (outEvts.length) {
21554 dc.b4DragOut(e, outEvts);
21555 dc.onDragOut(e, outEvts);
21558 if (enterEvts.length) {
21559 dc.onDragEnter(e, enterEvts);
21562 if (overEvts.length) {
21563 dc.b4DragOver(e, overEvts);
21564 dc.onDragOver(e, overEvts);
21567 if (dropEvts.length) {
21568 dc.b4DragDrop(e, dropEvts);
21569 dc.onDragDrop(e, dropEvts);
21573 // fire dragout events
21575 for (i=0, len=outEvts.length; i<len; ++i) {
21576 dc.b4DragOut(e, outEvts[i].id);
21577 dc.onDragOut(e, outEvts[i].id);
21580 // fire enter events
21581 for (i=0,len=enterEvts.length; i<len; ++i) {
21582 // dc.b4DragEnter(e, oDD.id);
21583 dc.onDragEnter(e, enterEvts[i].id);
21586 // fire over events
21587 for (i=0,len=overEvts.length; i<len; ++i) {
21588 dc.b4DragOver(e, overEvts[i].id);
21589 dc.onDragOver(e, overEvts[i].id);
21592 // fire drop events
21593 for (i=0, len=dropEvts.length; i<len; ++i) {
21594 dc.b4DragDrop(e, dropEvts[i].id);
21595 dc.onDragDrop(e, dropEvts[i].id);
21600 // notify about a drop that did not find a target
21601 if (isDrop && !dropEvts.length) {
21602 dc.onInvalidDrop(e);
21608 * Helper function for getting the best match from the list of drag
21609 * and drop objects returned by the drag and drop events when we are
21610 * in INTERSECT mode. It returns either the first object that the
21611 * cursor is over, or the object that has the greatest overlap with
21612 * the dragged element.
21613 * @method getBestMatch
21614 * @param {DragDrop[]} dds The array of drag and drop objects
21616 * @return {DragDrop} The best single match
21619 getBestMatch: function(dds) {
21621 // Return null if the input is not what we expect
21622 //if (!dds || !dds.length || dds.length == 0) {
21624 // If there is only one item, it wins
21625 //} else if (dds.length == 1) {
21627 var len = dds.length;
21632 // Loop through the targeted items
21633 for (var i=0; i<len; ++i) {
21635 // If the cursor is over the object, it wins. If the
21636 // cursor is over multiple matches, the first one we come
21638 if (dd.cursorIsOver) {
21641 // Otherwise the object with the most overlap wins
21644 winner.overlap.getArea() < dd.overlap.getArea()) {
21655 * Refreshes the cache of the top-left and bottom-right points of the
21656 * drag and drop objects in the specified group(s). This is in the
21657 * format that is stored in the drag and drop instance, so typical
21660 * Roo.dd.DragDropMgr.refreshCache(ddinstance.groups);
21664 * Roo.dd.DragDropMgr.refreshCache({group1:true, group2:true});
21666 * @TODO this really should be an indexed array. Alternatively this
21667 * method could accept both.
21668 * @method refreshCache
21669 * @param {Object} groups an associative array of groups to refresh
21672 refreshCache: function(groups) {
21673 for (var sGroup in groups) {
21674 if ("string" != typeof sGroup) {
21677 for (var i in this.ids[sGroup]) {
21678 var oDD = this.ids[sGroup][i];
21680 if (this.isTypeOfDD(oDD)) {
21681 // if (this.isTypeOfDD(oDD) && oDD.isTarget) {
21682 var loc = this.getLocation(oDD);
21684 this.locationCache[oDD.id] = loc;
21686 delete this.locationCache[oDD.id];
21687 // this will unregister the drag and drop object if
21688 // the element is not in a usable state
21697 * This checks to make sure an element exists and is in the DOM. The
21698 * main purpose is to handle cases where innerHTML is used to remove
21699 * drag and drop objects from the DOM. IE provides an 'unspecified
21700 * error' when trying to access the offsetParent of such an element
21702 * @param {HTMLElement} el the element to check
21703 * @return {boolean} true if the element looks usable
21706 verifyEl: function(el) {
21711 parent = el.offsetParent;
21714 parent = el.offsetParent;
21725 * Returns a Region object containing the drag and drop element's position
21726 * and size, including the padding configured for it
21727 * @method getLocation
21728 * @param {DragDrop} oDD the drag and drop object to get the
21730 * @return {Roo.lib.Region} a Region object representing the total area
21731 * the element occupies, including any padding
21732 * the instance is configured for.
21735 getLocation: function(oDD) {
21736 if (! this.isTypeOfDD(oDD)) {
21740 var el = oDD.getEl(), pos, x1, x2, y1, y2, t, r, b, l;
21743 pos= Roo.lib.Dom.getXY(el);
21751 x2 = x1 + el.offsetWidth;
21753 y2 = y1 + el.offsetHeight;
21755 t = y1 - oDD.padding[0];
21756 r = x2 + oDD.padding[1];
21757 b = y2 + oDD.padding[2];
21758 l = x1 - oDD.padding[3];
21760 return new Roo.lib.Region( t, r, b, l );
21764 * Checks the cursor location to see if it over the target
21765 * @method isOverTarget
21766 * @param {Roo.lib.Point} pt The point to evaluate
21767 * @param {DragDrop} oTarget the DragDrop object we are inspecting
21768 * @return {boolean} true if the mouse is over the target
21772 isOverTarget: function(pt, oTarget, intersect) {
21773 // use cache if available
21774 var loc = this.locationCache[oTarget.id];
21775 if (!loc || !this.useCache) {
21776 loc = this.getLocation(oTarget);
21777 this.locationCache[oTarget.id] = loc;
21785 oTarget.cursorIsOver = loc.contains( pt );
21787 // DragDrop is using this as a sanity check for the initial mousedown
21788 // in this case we are done. In POINT mode, if the drag obj has no
21789 // contraints, we are also done. Otherwise we need to evaluate the
21790 // location of the target as related to the actual location of the
21791 // dragged element.
21792 var dc = this.dragCurrent;
21793 if (!dc || !dc.getTargetCoord ||
21794 (!intersect && !dc.constrainX && !dc.constrainY)) {
21795 return oTarget.cursorIsOver;
21798 oTarget.overlap = null;
21800 // Get the current location of the drag element, this is the
21801 // location of the mouse event less the delta that represents
21802 // where the original mousedown happened on the element. We
21803 // need to consider constraints and ticks as well.
21804 var pos = dc.getTargetCoord(pt.x, pt.y);
21806 var el = dc.getDragEl();
21807 var curRegion = new Roo.lib.Region( pos.y,
21808 pos.x + el.offsetWidth,
21809 pos.y + el.offsetHeight,
21812 var overlap = curRegion.intersect(loc);
21815 oTarget.overlap = overlap;
21816 return (intersect) ? true : oTarget.cursorIsOver;
21823 * unload event handler
21824 * @method _onUnload
21828 _onUnload: function(e, me) {
21829 Roo.dd.DragDropMgr.unregAll();
21833 * Cleans up the drag and drop events and objects.
21838 unregAll: function() {
21840 if (this.dragCurrent) {
21842 this.dragCurrent = null;
21845 this._execOnAll("unreg", []);
21847 for (i in this.elementCache) {
21848 delete this.elementCache[i];
21851 this.elementCache = {};
21856 * A cache of DOM elements
21857 * @property elementCache
21864 * Get the wrapper for the DOM element specified
21865 * @method getElWrapper
21866 * @param {String} id the id of the element to get
21867 * @return {Roo.dd.DDM.ElementWrapper} the wrapped element
21869 * @deprecated This wrapper isn't that useful
21872 getElWrapper: function(id) {
21873 var oWrapper = this.elementCache[id];
21874 if (!oWrapper || !oWrapper.el) {
21875 oWrapper = this.elementCache[id] =
21876 new this.ElementWrapper(Roo.getDom(id));
21882 * Returns the actual DOM element
21883 * @method getElement
21884 * @param {String} id the id of the elment to get
21885 * @return {Object} The element
21886 * @deprecated use Roo.getDom instead
21889 getElement: function(id) {
21890 return Roo.getDom(id);
21894 * Returns the style property for the DOM element (i.e.,
21895 * document.getElById(id).style)
21897 * @param {String} id the id of the elment to get
21898 * @return {Object} The style property of the element
21899 * @deprecated use Roo.getDom instead
21902 getCss: function(id) {
21903 var el = Roo.getDom(id);
21904 return (el) ? el.style : null;
21908 * Inner class for cached elements
21909 * @class DragDropMgr.ElementWrapper
21914 ElementWrapper: function(el) {
21919 this.el = el || null;
21924 this.id = this.el && el.id;
21926 * A reference to the style property
21929 this.css = this.el && el.style;
21933 * Returns the X position of an html element
21935 * @param el the element for which to get the position
21936 * @return {int} the X coordinate
21938 * @deprecated use Roo.lib.Dom.getX instead
21941 getPosX: function(el) {
21942 return Roo.lib.Dom.getX(el);
21946 * Returns the Y position of an html element
21948 * @param el the element for which to get the position
21949 * @return {int} the Y coordinate
21950 * @deprecated use Roo.lib.Dom.getY instead
21953 getPosY: function(el) {
21954 return Roo.lib.Dom.getY(el);
21958 * Swap two nodes. In IE, we use the native method, for others we
21959 * emulate the IE behavior
21961 * @param n1 the first node to swap
21962 * @param n2 the other node to swap
21965 swapNode: function(n1, n2) {
21969 var p = n2.parentNode;
21970 var s = n2.nextSibling;
21973 p.insertBefore(n1, n2);
21974 } else if (n2 == n1.nextSibling) {
21975 p.insertBefore(n2, n1);
21977 n1.parentNode.replaceChild(n2, n1);
21978 p.insertBefore(n1, s);
21984 * Returns the current scroll position
21985 * @method getScroll
21989 getScroll: function () {
21990 var t, l, dde=document.documentElement, db=document.body;
21991 if (dde && (dde.scrollTop || dde.scrollLeft)) {
21993 l = dde.scrollLeft;
22000 return { top: t, left: l };
22004 * Returns the specified element style property
22006 * @param {HTMLElement} el the element
22007 * @param {string} styleProp the style property
22008 * @return {string} The value of the style property
22009 * @deprecated use Roo.lib.Dom.getStyle
22012 getStyle: function(el, styleProp) {
22013 return Roo.fly(el).getStyle(styleProp);
22017 * Gets the scrollTop
22018 * @method getScrollTop
22019 * @return {int} the document's scrollTop
22022 getScrollTop: function () { return this.getScroll().top; },
22025 * Gets the scrollLeft
22026 * @method getScrollLeft
22027 * @return {int} the document's scrollTop
22030 getScrollLeft: function () { return this.getScroll().left; },
22033 * Sets the x/y position of an element to the location of the
22036 * @param {HTMLElement} moveEl The element to move
22037 * @param {HTMLElement} targetEl The position reference element
22040 moveToEl: function (moveEl, targetEl) {
22041 var aCoord = Roo.lib.Dom.getXY(targetEl);
22042 Roo.lib.Dom.setXY(moveEl, aCoord);
22046 * Numeric array sort function
22047 * @method numericSort
22050 numericSort: function(a, b) { return (a - b); },
22054 * @property _timeoutCount
22061 * Trying to make the load order less important. Without this we get
22062 * an error if this file is loaded before the Event Utility.
22063 * @method _addListeners
22067 _addListeners: function() {
22068 var DDM = Roo.dd.DDM;
22069 if ( Roo.lib.Event && document ) {
22072 if (DDM._timeoutCount > 2000) {
22074 setTimeout(DDM._addListeners, 10);
22075 if (document && document.body) {
22076 DDM._timeoutCount += 1;
22083 * Recursively searches the immediate parent and all child nodes for
22084 * the handle element in order to determine wheter or not it was
22086 * @method handleWasClicked
22087 * @param node the html element to inspect
22090 handleWasClicked: function(node, id) {
22091 if (this.isHandle(id, node.id)) {
22094 // check to see if this is a text node child of the one we want
22095 var p = node.parentNode;
22098 if (this.isHandle(id, p.id)) {
22113 // shorter alias, save a few bytes
22114 Roo.dd.DDM = Roo.dd.DragDropMgr;
22115 Roo.dd.DDM._addListeners();
22119 * Ext JS Library 1.1.1
22120 * Copyright(c) 2006-2007, Ext JS, LLC.
22122 * Originally Released Under LGPL - original licence link has changed is not relivant.
22125 * <script type="text/javascript">
22130 * A DragDrop implementation where the linked element follows the
22131 * mouse cursor during a drag.
22132 * @extends Roo.dd.DragDrop
22134 * @param {String} id the id of the linked element
22135 * @param {String} sGroup the group of related DragDrop items
22136 * @param {object} config an object containing configurable attributes
22137 * Valid properties for DD:
22140 Roo.dd.DD = function(id, sGroup, config) {
22142 this.init(id, sGroup, config);
22146 Roo.extend(Roo.dd.DD, Roo.dd.DragDrop, {
22149 * When set to true, the utility automatically tries to scroll the browser
22150 * window wehn a drag and drop element is dragged near the viewport boundary.
22151 * Defaults to true.
22158 * Sets the pointer offset to the distance between the linked element's top
22159 * left corner and the location the element was clicked
22160 * @method autoOffset
22161 * @param {int} iPageX the X coordinate of the click
22162 * @param {int} iPageY the Y coordinate of the click
22164 autoOffset: function(iPageX, iPageY) {
22165 var x = iPageX - this.startPageX;
22166 var y = iPageY - this.startPageY;
22167 this.setDelta(x, y);
22171 * Sets the pointer offset. You can call this directly to force the
22172 * offset to be in a particular location (e.g., pass in 0,0 to set it
22173 * to the center of the object)
22175 * @param {int} iDeltaX the distance from the left
22176 * @param {int} iDeltaY the distance from the top
22178 setDelta: function(iDeltaX, iDeltaY) {
22179 this.deltaX = iDeltaX;
22180 this.deltaY = iDeltaY;
22184 * Sets the drag element to the location of the mousedown or click event,
22185 * maintaining the cursor location relative to the location on the element
22186 * that was clicked. Override this if you want to place the element in a
22187 * location other than where the cursor is.
22188 * @method setDragElPos
22189 * @param {int} iPageX the X coordinate of the mousedown or drag event
22190 * @param {int} iPageY the Y coordinate of the mousedown or drag event
22192 setDragElPos: function(iPageX, iPageY) {
22193 // the first time we do this, we are going to check to make sure
22194 // the element has css positioning
22196 var el = this.getDragEl();
22197 this.alignElWithMouse(el, iPageX, iPageY);
22201 * Sets the element to the location of the mousedown or click event,
22202 * maintaining the cursor location relative to the location on the element
22203 * that was clicked. Override this if you want to place the element in a
22204 * location other than where the cursor is.
22205 * @method alignElWithMouse
22206 * @param {HTMLElement} el the element to move
22207 * @param {int} iPageX the X coordinate of the mousedown or drag event
22208 * @param {int} iPageY the Y coordinate of the mousedown or drag event
22210 alignElWithMouse: function(el, iPageX, iPageY) {
22211 var oCoord = this.getTargetCoord(iPageX, iPageY);
22212 var fly = el.dom ? el : Roo.fly(el);
22213 if (!this.deltaSetXY) {
22214 var aCoord = [oCoord.x, oCoord.y];
22216 var newLeft = fly.getLeft(true);
22217 var newTop = fly.getTop(true);
22218 this.deltaSetXY = [ newLeft - oCoord.x, newTop - oCoord.y ];
22220 fly.setLeftTop(oCoord.x + this.deltaSetXY[0], oCoord.y + this.deltaSetXY[1]);
22223 this.cachePosition(oCoord.x, oCoord.y);
22224 this.autoScroll(oCoord.x, oCoord.y, el.offsetHeight, el.offsetWidth);
22229 * Saves the most recent position so that we can reset the constraints and
22230 * tick marks on-demand. We need to know this so that we can calculate the
22231 * number of pixels the element is offset from its original position.
22232 * @method cachePosition
22233 * @param iPageX the current x position (optional, this just makes it so we
22234 * don't have to look it up again)
22235 * @param iPageY the current y position (optional, this just makes it so we
22236 * don't have to look it up again)
22238 cachePosition: function(iPageX, iPageY) {
22240 this.lastPageX = iPageX;
22241 this.lastPageY = iPageY;
22243 var aCoord = Roo.lib.Dom.getXY(this.getEl());
22244 this.lastPageX = aCoord[0];
22245 this.lastPageY = aCoord[1];
22250 * Auto-scroll the window if the dragged object has been moved beyond the
22251 * visible window boundary.
22252 * @method autoScroll
22253 * @param {int} x the drag element's x position
22254 * @param {int} y the drag element's y position
22255 * @param {int} h the height of the drag element
22256 * @param {int} w the width of the drag element
22259 autoScroll: function(x, y, h, w) {
22262 // The client height
22263 var clientH = Roo.lib.Dom.getViewWidth();
22265 // The client width
22266 var clientW = Roo.lib.Dom.getViewHeight();
22268 // The amt scrolled down
22269 var st = this.DDM.getScrollTop();
22271 // The amt scrolled right
22272 var sl = this.DDM.getScrollLeft();
22274 // Location of the bottom of the element
22277 // Location of the right of the element
22280 // The distance from the cursor to the bottom of the visible area,
22281 // adjusted so that we don't scroll if the cursor is beyond the
22282 // element drag constraints
22283 var toBot = (clientH + st - y - this.deltaY);
22285 // The distance from the cursor to the right of the visible area
22286 var toRight = (clientW + sl - x - this.deltaX);
22289 // How close to the edge the cursor must be before we scroll
22290 // var thresh = (document.all) ? 100 : 40;
22293 // How many pixels to scroll per autoscroll op. This helps to reduce
22294 // clunky scrolling. IE is more sensitive about this ... it needs this
22295 // value to be higher.
22296 var scrAmt = (document.all) ? 80 : 30;
22298 // Scroll down if we are near the bottom of the visible page and the
22299 // obj extends below the crease
22300 if ( bot > clientH && toBot < thresh ) {
22301 window.scrollTo(sl, st + scrAmt);
22304 // Scroll up if the window is scrolled down and the top of the object
22305 // goes above the top border
22306 if ( y < st && st > 0 && y - st < thresh ) {
22307 window.scrollTo(sl, st - scrAmt);
22310 // Scroll right if the obj is beyond the right border and the cursor is
22311 // near the border.
22312 if ( right > clientW && toRight < thresh ) {
22313 window.scrollTo(sl + scrAmt, st);
22316 // Scroll left if the window has been scrolled to the right and the obj
22317 // extends past the left border
22318 if ( x < sl && sl > 0 && x - sl < thresh ) {
22319 window.scrollTo(sl - scrAmt, st);
22325 * Finds the location the element should be placed if we want to move
22326 * it to where the mouse location less the click offset would place us.
22327 * @method getTargetCoord
22328 * @param {int} iPageX the X coordinate of the click
22329 * @param {int} iPageY the Y coordinate of the click
22330 * @return an object that contains the coordinates (Object.x and Object.y)
22333 getTargetCoord: function(iPageX, iPageY) {
22336 var x = iPageX - this.deltaX;
22337 var y = iPageY - this.deltaY;
22339 if (this.constrainX) {
22340 if (x < this.minX) { x = this.minX; }
22341 if (x > this.maxX) { x = this.maxX; }
22344 if (this.constrainY) {
22345 if (y < this.minY) { y = this.minY; }
22346 if (y > this.maxY) { y = this.maxY; }
22349 x = this.getTick(x, this.xTicks);
22350 y = this.getTick(y, this.yTicks);
22357 * Sets up config options specific to this class. Overrides
22358 * Roo.dd.DragDrop, but all versions of this method through the
22359 * inheritance chain are called
22361 applyConfig: function() {
22362 Roo.dd.DD.superclass.applyConfig.call(this);
22363 this.scroll = (this.config.scroll !== false);
22367 * Event that fires prior to the onMouseDown event. Overrides
22370 b4MouseDown: function(e) {
22371 // this.resetConstraints();
22372 this.autoOffset(e.getPageX(),
22377 * Event that fires prior to the onDrag event. Overrides
22380 b4Drag: function(e) {
22381 this.setDragElPos(e.getPageX(),
22385 toString: function() {
22386 return ("DD " + this.id);
22389 //////////////////////////////////////////////////////////////////////////
22390 // Debugging ygDragDrop events that can be overridden
22391 //////////////////////////////////////////////////////////////////////////
22393 startDrag: function(x, y) {
22396 onDrag: function(e) {
22399 onDragEnter: function(e, id) {
22402 onDragOver: function(e, id) {
22405 onDragOut: function(e, id) {
22408 onDragDrop: function(e, id) {
22411 endDrag: function(e) {
22418 * Ext JS Library 1.1.1
22419 * Copyright(c) 2006-2007, Ext JS, LLC.
22421 * Originally Released Under LGPL - original licence link has changed is not relivant.
22424 * <script type="text/javascript">
22428 * @class Roo.dd.DDProxy
22429 * A DragDrop implementation that inserts an empty, bordered div into
22430 * the document that follows the cursor during drag operations. At the time of
22431 * the click, the frame div is resized to the dimensions of the linked html
22432 * element, and moved to the exact location of the linked element.
22434 * References to the "frame" element refer to the single proxy element that
22435 * was created to be dragged in place of all DDProxy elements on the
22438 * @extends Roo.dd.DD
22440 * @param {String} id the id of the linked html element
22441 * @param {String} sGroup the group of related DragDrop objects
22442 * @param {object} config an object containing configurable attributes
22443 * Valid properties for DDProxy in addition to those in DragDrop:
22444 * resizeFrame, centerFrame, dragElId
22446 Roo.dd.DDProxy = function(id, sGroup, config) {
22448 this.init(id, sGroup, config);
22454 * The default drag frame div id
22455 * @property Roo.dd.DDProxy.dragElId
22459 Roo.dd.DDProxy.dragElId = "ygddfdiv";
22461 Roo.extend(Roo.dd.DDProxy, Roo.dd.DD, {
22464 * By default we resize the drag frame to be the same size as the element
22465 * we want to drag (this is to get the frame effect). We can turn it off
22466 * if we want a different behavior.
22467 * @property resizeFrame
22473 * By default the frame is positioned exactly where the drag element is, so
22474 * we use the cursor offset provided by Roo.dd.DD. Another option that works only if
22475 * you do not have constraints on the obj is to have the drag frame centered
22476 * around the cursor. Set centerFrame to true for this effect.
22477 * @property centerFrame
22480 centerFrame: false,
22483 * Creates the proxy element if it does not yet exist
22484 * @method createFrame
22486 createFrame: function() {
22488 var body = document.body;
22490 if (!body || !body.firstChild) {
22491 setTimeout( function() { self.createFrame(); }, 50 );
22495 var div = this.getDragEl();
22498 div = document.createElement("div");
22499 div.id = this.dragElId;
22502 s.position = "absolute";
22503 s.visibility = "hidden";
22505 s.border = "2px solid #aaa";
22508 // appendChild can blow up IE if invoked prior to the window load event
22509 // while rendering a table. It is possible there are other scenarios
22510 // that would cause this to happen as well.
22511 body.insertBefore(div, body.firstChild);
22516 * Initialization for the drag frame element. Must be called in the
22517 * constructor of all subclasses
22518 * @method initFrame
22520 initFrame: function() {
22521 this.createFrame();
22524 applyConfig: function() {
22525 Roo.dd.DDProxy.superclass.applyConfig.call(this);
22527 this.resizeFrame = (this.config.resizeFrame !== false);
22528 this.centerFrame = (this.config.centerFrame);
22529 this.setDragElId(this.config.dragElId || Roo.dd.DDProxy.dragElId);
22533 * Resizes the drag frame to the dimensions of the clicked object, positions
22534 * it over the object, and finally displays it
22535 * @method showFrame
22536 * @param {int} iPageX X click position
22537 * @param {int} iPageY Y click position
22540 showFrame: function(iPageX, iPageY) {
22541 var el = this.getEl();
22542 var dragEl = this.getDragEl();
22543 var s = dragEl.style;
22545 this._resizeProxy();
22547 if (this.centerFrame) {
22548 this.setDelta( Math.round(parseInt(s.width, 10)/2),
22549 Math.round(parseInt(s.height, 10)/2) );
22552 this.setDragElPos(iPageX, iPageY);
22554 Roo.fly(dragEl).show();
22558 * The proxy is automatically resized to the dimensions of the linked
22559 * element when a drag is initiated, unless resizeFrame is set to false
22560 * @method _resizeProxy
22563 _resizeProxy: function() {
22564 if (this.resizeFrame) {
22565 var el = this.getEl();
22566 Roo.fly(this.getDragEl()).setSize(el.offsetWidth, el.offsetHeight);
22570 // overrides Roo.dd.DragDrop
22571 b4MouseDown: function(e) {
22572 var x = e.getPageX();
22573 var y = e.getPageY();
22574 this.autoOffset(x, y);
22575 this.setDragElPos(x, y);
22578 // overrides Roo.dd.DragDrop
22579 b4StartDrag: function(x, y) {
22580 // show the drag frame
22581 this.showFrame(x, y);
22584 // overrides Roo.dd.DragDrop
22585 b4EndDrag: function(e) {
22586 Roo.fly(this.getDragEl()).hide();
22589 // overrides Roo.dd.DragDrop
22590 // By default we try to move the element to the last location of the frame.
22591 // This is so that the default behavior mirrors that of Roo.dd.DD.
22592 endDrag: function(e) {
22594 var lel = this.getEl();
22595 var del = this.getDragEl();
22597 // Show the drag frame briefly so we can get its position
22598 del.style.visibility = "";
22601 // Hide the linked element before the move to get around a Safari
22603 lel.style.visibility = "hidden";
22604 Roo.dd.DDM.moveToEl(lel, del);
22605 del.style.visibility = "hidden";
22606 lel.style.visibility = "";
22611 beforeMove : function(){
22615 afterDrag : function(){
22619 toString: function() {
22620 return ("DDProxy " + this.id);
22626 * Ext JS Library 1.1.1
22627 * Copyright(c) 2006-2007, Ext JS, LLC.
22629 * Originally Released Under LGPL - original licence link has changed is not relivant.
22632 * <script type="text/javascript">
22636 * @class Roo.dd.DDTarget
22637 * A DragDrop implementation that does not move, but can be a drop
22638 * target. You would get the same result by simply omitting implementation
22639 * for the event callbacks, but this way we reduce the processing cost of the
22640 * event listener and the callbacks.
22641 * @extends Roo.dd.DragDrop
22643 * @param {String} id the id of the element that is a drop target
22644 * @param {String} sGroup the group of related DragDrop objects
22645 * @param {object} config an object containing configurable attributes
22646 * Valid properties for DDTarget in addition to those in
22650 Roo.dd.DDTarget = function(id, sGroup, config) {
22652 this.initTarget(id, sGroup, config);
22654 if (config && (config.listeners || config.events)) {
22655 Roo.dd.DragDrop.superclass.constructor.call(this, {
22656 listeners : config.listeners || {},
22657 events : config.events || {}
22662 // Roo.dd.DDTarget.prototype = new Roo.dd.DragDrop();
22663 Roo.extend(Roo.dd.DDTarget, Roo.dd.DragDrop, {
22664 toString: function() {
22665 return ("DDTarget " + this.id);
22670 * Ext JS Library 1.1.1
22671 * Copyright(c) 2006-2007, Ext JS, LLC.
22673 * Originally Released Under LGPL - original licence link has changed is not relivant.
22676 * <script type="text/javascript">
22681 * @class Roo.dd.ScrollManager
22682 * Provides automatic scrolling of overflow regions in the page during drag operations.<br><br>
22683 * <b>Note: This class uses "Point Mode" and is untested in "Intersect Mode".</b>
22686 Roo.dd.ScrollManager = function(){
22687 var ddm = Roo.dd.DragDropMgr;
22694 var onStop = function(e){
22699 var triggerRefresh = function(){
22700 if(ddm.dragCurrent){
22701 ddm.refreshCache(ddm.dragCurrent.groups);
22705 var doScroll = function(){
22706 if(ddm.dragCurrent){
22707 var dds = Roo.dd.ScrollManager;
22709 if(proc.el.scroll(proc.dir, dds.increment)){
22713 proc.el.scroll(proc.dir, dds.increment, true, dds.animDuration, triggerRefresh);
22718 var clearProc = function(){
22720 clearInterval(proc.id);
22727 var startProc = function(el, dir){
22728 Roo.log('scroll startproc');
22732 proc.id = setInterval(doScroll, Roo.dd.ScrollManager.frequency);
22735 var onFire = function(e, isDrop){
22737 if(isDrop || !ddm.dragCurrent){ return; }
22738 var dds = Roo.dd.ScrollManager;
22739 if(!dragEl || dragEl != ddm.dragCurrent){
22740 dragEl = ddm.dragCurrent;
22741 // refresh regions on drag start
22742 dds.refreshCache();
22745 var xy = Roo.lib.Event.getXY(e);
22746 var pt = new Roo.lib.Point(xy[0], xy[1]);
22747 for(var id in els){
22748 var el = els[id], r = el._region;
22749 if(r && r.contains(pt) && el.isScrollable()){
22750 if(r.bottom - pt.y <= dds.thresh){
22752 startProc(el, "down");
22755 }else if(r.right - pt.x <= dds.thresh){
22757 startProc(el, "left");
22760 }else if(pt.y - r.top <= dds.thresh){
22762 startProc(el, "up");
22765 }else if(pt.x - r.left <= dds.thresh){
22767 startProc(el, "right");
22776 ddm.fireEvents = ddm.fireEvents.createSequence(onFire, ddm);
22777 ddm.stopDrag = ddm.stopDrag.createSequence(onStop, ddm);
22781 * Registers new overflow element(s) to auto scroll
22782 * @param {String/HTMLElement/Element/Array} el The id of or the element to be scrolled or an array of either
22784 register : function(el){
22785 if(el instanceof Array){
22786 for(var i = 0, len = el.length; i < len; i++) {
22787 this.register(el[i]);
22793 Roo.dd.ScrollManager.els = els;
22797 * Unregisters overflow element(s) so they are no longer scrolled
22798 * @param {String/HTMLElement/Element/Array} el The id of or the element to be removed or an array of either
22800 unregister : function(el){
22801 if(el instanceof Array){
22802 for(var i = 0, len = el.length; i < len; i++) {
22803 this.unregister(el[i]);
22812 * The number of pixels from the edge of a container the pointer needs to be to
22813 * trigger scrolling (defaults to 25)
22819 * The number of pixels to scroll in each scroll increment (defaults to 50)
22825 * The frequency of scrolls in milliseconds (defaults to 500)
22831 * True to animate the scroll (defaults to true)
22837 * The animation duration in seconds -
22838 * MUST BE less than Roo.dd.ScrollManager.frequency! (defaults to .4)
22844 * Manually trigger a cache refresh.
22846 refreshCache : function(){
22847 for(var id in els){
22848 if(typeof els[id] == 'object'){ // for people extending the object prototype
22849 els[id]._region = els[id].getRegion();
22856 * Ext JS Library 1.1.1
22857 * Copyright(c) 2006-2007, Ext JS, LLC.
22859 * Originally Released Under LGPL - original licence link has changed is not relivant.
22862 * <script type="text/javascript">
22867 * @class Roo.dd.Registry
22868 * Provides easy access to all drag drop components that are registered on a page. Items can be retrieved either
22869 * directly by DOM node id, or by passing in the drag drop event that occurred and looking up the event target.
22872 Roo.dd.Registry = function(){
22875 var autoIdSeed = 0;
22877 var getId = function(el, autogen){
22878 if(typeof el == "string"){
22882 if(!id && autogen !== false){
22883 id = "roodd-" + (++autoIdSeed);
22891 * Register a drag drop element
22892 * @param {String|HTMLElement} element The id or DOM node to register
22893 * @param {Object} data (optional) A custom data object that will be passed between the elements that are involved
22894 * in drag drop operations. You can populate this object with any arbitrary properties that your own code
22895 * knows how to interpret, plus there are some specific properties known to the Registry that should be
22896 * populated in the data object (if applicable):
22898 Value Description<br />
22899 --------- ------------------------------------------<br />
22900 handles Array of DOM nodes that trigger dragging<br />
22901 for the element being registered<br />
22902 isHandle True if the element passed in triggers<br />
22903 dragging itself, else false
22906 register : function(el, data){
22908 if(typeof el == "string"){
22909 el = document.getElementById(el);
22912 elements[getId(el)] = data;
22913 if(data.isHandle !== false){
22914 handles[data.ddel.id] = data;
22917 var hs = data.handles;
22918 for(var i = 0, len = hs.length; i < len; i++){
22919 handles[getId(hs[i])] = data;
22925 * Unregister a drag drop element
22926 * @param {String|HTMLElement} element The id or DOM node to unregister
22928 unregister : function(el){
22929 var id = getId(el, false);
22930 var data = elements[id];
22932 delete elements[id];
22934 var hs = data.handles;
22935 for(var i = 0, len = hs.length; i < len; i++){
22936 delete handles[getId(hs[i], false)];
22943 * Returns the handle registered for a DOM Node by id
22944 * @param {String|HTMLElement} id The DOM node or id to look up
22945 * @return {Object} handle The custom handle data
22947 getHandle : function(id){
22948 if(typeof id != "string"){ // must be element?
22951 return handles[id];
22955 * Returns the handle that is registered for the DOM node that is the target of the event
22956 * @param {Event} e The event
22957 * @return {Object} handle The custom handle data
22959 getHandleFromEvent : function(e){
22960 var t = Roo.lib.Event.getTarget(e);
22961 return t ? handles[t.id] : null;
22965 * Returns a custom data object that is registered for a DOM node by id
22966 * @param {String|HTMLElement} id The DOM node or id to look up
22967 * @return {Object} data The custom data
22969 getTarget : function(id){
22970 if(typeof id != "string"){ // must be element?
22973 return elements[id];
22977 * Returns a custom data object that is registered for the DOM node that is the target of the event
22978 * @param {Event} e The event
22979 * @return {Object} data The custom data
22981 getTargetFromEvent : function(e){
22982 var t = Roo.lib.Event.getTarget(e);
22983 return t ? elements[t.id] || handles[t.id] : null;
22988 * Ext JS Library 1.1.1
22989 * Copyright(c) 2006-2007, Ext JS, LLC.
22991 * Originally Released Under LGPL - original licence link has changed is not relivant.
22994 * <script type="text/javascript">
22999 * @class Roo.dd.StatusProxy
23000 * A specialized drag proxy that supports a drop status icon, {@link Roo.Layer} styles and auto-repair. This is the
23001 * default drag proxy used by all Roo.dd components.
23003 * @param {Object} config
23005 Roo.dd.StatusProxy = function(config){
23006 Roo.apply(this, config);
23007 this.id = this.id || Roo.id();
23008 this.el = new Roo.Layer({
23010 id: this.id, tag: "div", cls: "x-dd-drag-proxy "+this.dropNotAllowed, children: [
23011 {tag: "div", cls: "x-dd-drop-icon"},
23012 {tag: "div", cls: "x-dd-drag-ghost"}
23015 shadow: !config || config.shadow !== false
23017 this.ghost = Roo.get(this.el.dom.childNodes[1]);
23018 this.dropStatus = this.dropNotAllowed;
23021 Roo.dd.StatusProxy.prototype = {
23023 * @cfg {String} dropAllowed
23024 * The CSS class to apply to the status element when drop is allowed (defaults to "x-dd-drop-ok").
23026 dropAllowed : "x-dd-drop-ok",
23028 * @cfg {String} dropNotAllowed
23029 * The CSS class to apply to the status element when drop is not allowed (defaults to "x-dd-drop-nodrop").
23031 dropNotAllowed : "x-dd-drop-nodrop",
23034 * Updates the proxy's visual element to indicate the status of whether or not drop is allowed
23035 * over the current target element.
23036 * @param {String} cssClass The css class for the new drop status indicator image
23038 setStatus : function(cssClass){
23039 cssClass = cssClass || this.dropNotAllowed;
23040 if(this.dropStatus != cssClass){
23041 this.el.replaceClass(this.dropStatus, cssClass);
23042 this.dropStatus = cssClass;
23047 * Resets the status indicator to the default dropNotAllowed value
23048 * @param {Boolean} clearGhost True to also remove all content from the ghost, false to preserve it
23050 reset : function(clearGhost){
23051 this.el.dom.className = "x-dd-drag-proxy " + this.dropNotAllowed;
23052 this.dropStatus = this.dropNotAllowed;
23054 this.ghost.update("");
23059 * Updates the contents of the ghost element
23060 * @param {String} html The html that will replace the current innerHTML of the ghost element
23062 update : function(html){
23063 if(typeof html == "string"){
23064 this.ghost.update(html);
23066 this.ghost.update("");
23067 html.style.margin = "0";
23068 this.ghost.dom.appendChild(html);
23070 // ensure float = none set?? cant remember why though.
23071 var el = this.ghost.dom.firstChild;
23073 Roo.fly(el).setStyle('float', 'none');
23078 * Returns the underlying proxy {@link Roo.Layer}
23079 * @return {Roo.Layer} el
23081 getEl : function(){
23086 * Returns the ghost element
23087 * @return {Roo.Element} el
23089 getGhost : function(){
23095 * @param {Boolean} clear True to reset the status and clear the ghost contents, false to preserve them
23097 hide : function(clear){
23105 * Stops the repair animation if it's currently running
23108 if(this.anim && this.anim.isAnimated && this.anim.isAnimated()){
23114 * Displays this proxy
23121 * Force the Layer to sync its shadow and shim positions to the element
23128 * Causes the proxy to return to its position of origin via an animation. Should be called after an
23129 * invalid drop operation by the item being dragged.
23130 * @param {Array} xy The XY position of the element ([x, y])
23131 * @param {Function} callback The function to call after the repair is complete
23132 * @param {Object} scope The scope in which to execute the callback
23134 repair : function(xy, callback, scope){
23135 this.callback = callback;
23136 this.scope = scope;
23137 if(xy && this.animRepair !== false){
23138 this.el.addClass("x-dd-drag-repair");
23139 this.el.hideUnders(true);
23140 this.anim = this.el.shift({
23141 duration: this.repairDuration || .5,
23145 callback: this.afterRepair,
23149 this.afterRepair();
23154 afterRepair : function(){
23156 if(typeof this.callback == "function"){
23157 this.callback.call(this.scope || this);
23159 this.callback = null;
23164 * Ext JS Library 1.1.1
23165 * Copyright(c) 2006-2007, Ext JS, LLC.
23167 * Originally Released Under LGPL - original licence link has changed is not relivant.
23170 * <script type="text/javascript">
23174 * @class Roo.dd.DragSource
23175 * @extends Roo.dd.DDProxy
23176 * A simple class that provides the basic implementation needed to make any element draggable.
23178 * @param {String/HTMLElement/Element} el The container element
23179 * @param {Object} config
23181 Roo.dd.DragSource = function(el, config){
23182 this.el = Roo.get(el);
23183 this.dragData = {};
23185 Roo.apply(this, config);
23188 this.proxy = new Roo.dd.StatusProxy();
23191 Roo.dd.DragSource.superclass.constructor.call(this, this.el.dom, this.ddGroup || this.group,
23192 {dragElId : this.proxy.id, resizeFrame: false, isTarget: false, scroll: this.scroll === true});
23194 this.dragging = false;
23197 Roo.extend(Roo.dd.DragSource, Roo.dd.DDProxy, {
23199 * @cfg {String} dropAllowed
23200 * The CSS class returned to the drag source when drop is allowed (defaults to "x-dd-drop-ok").
23202 dropAllowed : "x-dd-drop-ok",
23204 * @cfg {String} dropNotAllowed
23205 * The CSS class returned to the drag source when drop is not allowed (defaults to "x-dd-drop-nodrop").
23207 dropNotAllowed : "x-dd-drop-nodrop",
23210 * Returns the data object associated with this drag source
23211 * @return {Object} data An object containing arbitrary data
23213 getDragData : function(e){
23214 return this.dragData;
23218 onDragEnter : function(e, id){
23219 var target = Roo.dd.DragDropMgr.getDDById(id);
23220 this.cachedTarget = target;
23221 if(this.beforeDragEnter(target, e, id) !== false){
23222 if(target.isNotifyTarget){
23223 var status = target.notifyEnter(this, e, this.dragData);
23224 this.proxy.setStatus(status);
23226 this.proxy.setStatus(this.dropAllowed);
23229 if(this.afterDragEnter){
23231 * An empty function by default, but provided so that you can perform a custom action
23232 * when the dragged item enters the drop target by providing an implementation.
23233 * @param {Roo.dd.DragDrop} target The drop target
23234 * @param {Event} e The event object
23235 * @param {String} id The id of the dragged element
23236 * @method afterDragEnter
23238 this.afterDragEnter(target, e, id);
23244 * An empty function by default, but provided so that you can perform a custom action
23245 * before the dragged item enters the drop target and optionally cancel the onDragEnter.
23246 * @param {Roo.dd.DragDrop} target The drop target
23247 * @param {Event} e The event object
23248 * @param {String} id The id of the dragged element
23249 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
23251 beforeDragEnter : function(target, e, id){
23256 alignElWithMouse: function() {
23257 Roo.dd.DragSource.superclass.alignElWithMouse.apply(this, arguments);
23262 onDragOver : function(e, id){
23263 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
23264 if(this.beforeDragOver(target, e, id) !== false){
23265 if(target.isNotifyTarget){
23266 var status = target.notifyOver(this, e, this.dragData);
23267 this.proxy.setStatus(status);
23270 if(this.afterDragOver){
23272 * An empty function by default, but provided so that you can perform a custom action
23273 * while the dragged item is over the drop target by providing an implementation.
23274 * @param {Roo.dd.DragDrop} target The drop target
23275 * @param {Event} e The event object
23276 * @param {String} id The id of the dragged element
23277 * @method afterDragOver
23279 this.afterDragOver(target, e, id);
23285 * An empty function by default, but provided so that you can perform a custom action
23286 * while the dragged item is over the drop target and optionally cancel the onDragOver.
23287 * @param {Roo.dd.DragDrop} target The drop target
23288 * @param {Event} e The event object
23289 * @param {String} id The id of the dragged element
23290 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
23292 beforeDragOver : function(target, e, id){
23297 onDragOut : function(e, id){
23298 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
23299 if(this.beforeDragOut(target, e, id) !== false){
23300 if(target.isNotifyTarget){
23301 target.notifyOut(this, e, this.dragData);
23303 this.proxy.reset();
23304 if(this.afterDragOut){
23306 * An empty function by default, but provided so that you can perform a custom action
23307 * after the dragged item is dragged out of the target without dropping.
23308 * @param {Roo.dd.DragDrop} target The drop target
23309 * @param {Event} e The event object
23310 * @param {String} id The id of the dragged element
23311 * @method afterDragOut
23313 this.afterDragOut(target, e, id);
23316 this.cachedTarget = null;
23320 * An empty function by default, but provided so that you can perform a custom action before the dragged
23321 * item is dragged out of the target without dropping, and optionally cancel the onDragOut.
23322 * @param {Roo.dd.DragDrop} target The drop target
23323 * @param {Event} e The event object
23324 * @param {String} id The id of the dragged element
23325 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
23327 beforeDragOut : function(target, e, id){
23332 onDragDrop : function(e, id){
23333 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
23334 if(this.beforeDragDrop(target, e, id) !== false){
23335 if(target.isNotifyTarget){
23336 if(target.notifyDrop(this, e, this.dragData)){ // valid drop?
23337 this.onValidDrop(target, e, id);
23339 this.onInvalidDrop(target, e, id);
23342 this.onValidDrop(target, e, id);
23345 if(this.afterDragDrop){
23347 * An empty function by default, but provided so that you can perform a custom action
23348 * after a valid drag drop has occurred by providing an implementation.
23349 * @param {Roo.dd.DragDrop} target The drop target
23350 * @param {Event} e The event object
23351 * @param {String} id The id of the dropped element
23352 * @method afterDragDrop
23354 this.afterDragDrop(target, e, id);
23357 delete this.cachedTarget;
23361 * An empty function by default, but provided so that you can perform a custom action before the dragged
23362 * item is dropped onto the target and optionally cancel the onDragDrop.
23363 * @param {Roo.dd.DragDrop} target The drop target
23364 * @param {Event} e The event object
23365 * @param {String} id The id of the dragged element
23366 * @return {Boolean} isValid True if the drag drop event is valid, else false to cancel
23368 beforeDragDrop : function(target, e, id){
23373 onValidDrop : function(target, e, id){
23375 if(this.afterValidDrop){
23377 * An empty function by default, but provided so that you can perform a custom action
23378 * after a valid drop has occurred by providing an implementation.
23379 * @param {Object} target The target DD
23380 * @param {Event} e The event object
23381 * @param {String} id The id of the dropped element
23382 * @method afterInvalidDrop
23384 this.afterValidDrop(target, e, id);
23389 getRepairXY : function(e, data){
23390 return this.el.getXY();
23394 onInvalidDrop : function(target, e, id){
23395 this.beforeInvalidDrop(target, e, id);
23396 if(this.cachedTarget){
23397 if(this.cachedTarget.isNotifyTarget){
23398 this.cachedTarget.notifyOut(this, e, this.dragData);
23400 this.cacheTarget = null;
23402 this.proxy.repair(this.getRepairXY(e, this.dragData), this.afterRepair, this);
23404 if(this.afterInvalidDrop){
23406 * An empty function by default, but provided so that you can perform a custom action
23407 * after an invalid drop has occurred by providing an implementation.
23408 * @param {Event} e The event object
23409 * @param {String} id The id of the dropped element
23410 * @method afterInvalidDrop
23412 this.afterInvalidDrop(e, id);
23417 afterRepair : function(){
23419 this.el.highlight(this.hlColor || "c3daf9");
23421 this.dragging = false;
23425 * An empty function by default, but provided so that you can perform a custom action after an invalid
23426 * drop has occurred.
23427 * @param {Roo.dd.DragDrop} target The drop target
23428 * @param {Event} e The event object
23429 * @param {String} id The id of the dragged element
23430 * @return {Boolean} isValid True if the invalid drop should proceed, else false to cancel
23432 beforeInvalidDrop : function(target, e, id){
23437 handleMouseDown : function(e){
23438 if(this.dragging) {
23441 var data = this.getDragData(e);
23442 if(data && this.onBeforeDrag(data, e) !== false){
23443 this.dragData = data;
23445 Roo.dd.DragSource.superclass.handleMouseDown.apply(this, arguments);
23450 * An empty function by default, but provided so that you can perform a custom action before the initial
23451 * drag event begins and optionally cancel it.
23452 * @param {Object} data An object containing arbitrary data to be shared with drop targets
23453 * @param {Event} e The event object
23454 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
23456 onBeforeDrag : function(data, e){
23461 * An empty function by default, but provided so that you can perform a custom action once the initial
23462 * drag event has begun. The drag cannot be canceled from this function.
23463 * @param {Number} x The x position of the click on the dragged object
23464 * @param {Number} y The y position of the click on the dragged object
23466 onStartDrag : Roo.emptyFn,
23468 // private - YUI override
23469 startDrag : function(x, y){
23470 this.proxy.reset();
23471 this.dragging = true;
23472 this.proxy.update("");
23473 this.onInitDrag(x, y);
23478 onInitDrag : function(x, y){
23479 var clone = this.el.dom.cloneNode(true);
23480 clone.id = Roo.id(); // prevent duplicate ids
23481 this.proxy.update(clone);
23482 this.onStartDrag(x, y);
23487 * Returns the drag source's underlying {@link Roo.dd.StatusProxy}
23488 * @return {Roo.dd.StatusProxy} proxy The StatusProxy
23490 getProxy : function(){
23495 * Hides the drag source's {@link Roo.dd.StatusProxy}
23497 hideProxy : function(){
23499 this.proxy.reset(true);
23500 this.dragging = false;
23504 triggerCacheRefresh : function(){
23505 Roo.dd.DDM.refreshCache(this.groups);
23508 // private - override to prevent hiding
23509 b4EndDrag: function(e) {
23512 // private - override to prevent moving
23513 endDrag : function(e){
23514 this.onEndDrag(this.dragData, e);
23518 onEndDrag : function(data, e){
23521 // private - pin to cursor
23522 autoOffset : function(x, y) {
23523 this.setDelta(-12, -20);
23527 * Ext JS Library 1.1.1
23528 * Copyright(c) 2006-2007, Ext JS, LLC.
23530 * Originally Released Under LGPL - original licence link has changed is not relivant.
23533 * <script type="text/javascript">
23538 * @class Roo.dd.DropTarget
23539 * @extends Roo.dd.DDTarget
23540 * A simple class that provides the basic implementation needed to make any element a drop target that can have
23541 * draggable items dropped onto it. The drop has no effect until an implementation of notifyDrop is provided.
23543 * @param {String/HTMLElement/Element} el The container element
23544 * @param {Object} config
23546 Roo.dd.DropTarget = function(el, config){
23547 this.el = Roo.get(el);
23549 var listeners = false; ;
23550 if (config && config.listeners) {
23551 listeners= config.listeners;
23552 delete config.listeners;
23554 Roo.apply(this, config);
23556 if(this.containerScroll){
23557 Roo.dd.ScrollManager.register(this.el);
23561 * @scope Roo.dd.DropTarget
23566 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the source is now over the
23567 * target. This default implementation adds the CSS class specified by overClass (if any) to the drop element
23568 * and returns the dropAllowed config value. This method should be overridden if drop validation is required.
23570 * IMPORTANT : it should set this.valid to true|false
23572 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
23573 * @param {Event} e The event
23574 * @param {Object} data An object containing arbitrary data supplied by the drag source
23580 * The function a {@link Roo.dd.DragSource} calls continuously while it is being dragged over the target.
23581 * This method will be called on every mouse movement while the drag source is over the drop target.
23582 * This default implementation simply returns the dropAllowed config value.
23584 * IMPORTANT : it should set this.valid to true|false
23586 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
23587 * @param {Event} e The event
23588 * @param {Object} data An object containing arbitrary data supplied by the drag source
23594 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the source has been dragged
23595 * out of the target without dropping. This default implementation simply removes the CSS class specified by
23596 * overClass (if any) from the drop element.
23599 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
23600 * @param {Event} e The event
23601 * @param {Object} data An object containing arbitrary data supplied by the drag source
23607 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the dragged item has
23608 * been dropped on it. This method has no default implementation and returns false, so you must provide an
23609 * implementation that does something to process the drop event and returns true so that the drag source's
23610 * repair action does not run.
23612 * IMPORTANT : it should set this.success
23614 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
23615 * @param {Event} e The event
23616 * @param {Object} data An object containing arbitrary data supplied by the drag source
23622 Roo.dd.DropTarget.superclass.constructor.call( this,
23624 this.ddGroup || this.group,
23627 listeners : listeners || {}
23635 Roo.extend(Roo.dd.DropTarget, Roo.dd.DDTarget, {
23637 * @cfg {String} overClass
23638 * The CSS class applied to the drop target element while the drag source is over it (defaults to "").
23641 * @cfg {String} ddGroup
23642 * The drag drop group to handle drop events for
23646 * @cfg {String} dropAllowed
23647 * The CSS class returned to the drag source when drop is allowed (defaults to "x-dd-drop-ok").
23649 dropAllowed : "x-dd-drop-ok",
23651 * @cfg {String} dropNotAllowed
23652 * The CSS class returned to the drag source when drop is not allowed (defaults to "x-dd-drop-nodrop").
23654 dropNotAllowed : "x-dd-drop-nodrop",
23656 * @cfg {boolean} success
23657 * set this after drop listener..
23661 * @cfg {boolean|String} valid true/false or string (ok-add/ok-sub/ok/nodrop)
23662 * if the drop point is valid for over/enter..
23669 isNotifyTarget : true,
23674 notifyEnter : function(dd, e, data)
23677 this.fireEvent('enter', dd, e, data);
23678 if(this.overClass){
23679 this.el.addClass(this.overClass);
23681 return typeof(this.valid) == 'string' ? 'x-dd-drop-' + this.valid : (
23682 this.valid ? this.dropAllowed : this.dropNotAllowed
23689 notifyOver : function(dd, e, data)
23692 this.fireEvent('over', dd, e, data);
23693 return typeof(this.valid) == 'string' ? 'x-dd-drop-' + this.valid : (
23694 this.valid ? this.dropAllowed : this.dropNotAllowed
23701 notifyOut : function(dd, e, data)
23703 this.fireEvent('out', dd, e, data);
23704 if(this.overClass){
23705 this.el.removeClass(this.overClass);
23712 notifyDrop : function(dd, e, data)
23714 this.success = false;
23715 this.fireEvent('drop', dd, e, data);
23716 return this.success;
23720 * Ext JS Library 1.1.1
23721 * Copyright(c) 2006-2007, Ext JS, LLC.
23723 * Originally Released Under LGPL - original licence link has changed is not relivant.
23726 * <script type="text/javascript">
23731 * @class Roo.dd.DragZone
23732 * @extends Roo.dd.DragSource
23733 * This class provides a container DD instance that proxies for multiple child node sources.<br />
23734 * By default, this class requires that draggable child nodes are registered with {@link Roo.dd.Registry}.
23736 * @param {String/HTMLElement/Element} el The container element
23737 * @param {Object} config
23739 Roo.dd.DragZone = function(el, config){
23740 Roo.dd.DragZone.superclass.constructor.call(this, el, config);
23741 if(this.containerScroll){
23742 Roo.dd.ScrollManager.register(this.el);
23746 Roo.extend(Roo.dd.DragZone, Roo.dd.DragSource, {
23748 * @cfg {Boolean} containerScroll True to register this container with the Scrollmanager
23749 * for auto scrolling during drag operations.
23752 * @cfg {String} hlColor The color to use when visually highlighting the drag source in the afterRepair
23753 * method after a failed drop (defaults to "c3daf9" - light blue)
23757 * Called when a mousedown occurs in this container. Looks in {@link Roo.dd.Registry}
23758 * for a valid target to drag based on the mouse down. Override this method
23759 * to provide your own lookup logic (e.g. finding a child by class name). Make sure your returned
23760 * object has a "ddel" attribute (with an HTML Element) for other functions to work.
23761 * @param {EventObject} e The mouse down event
23762 * @return {Object} The dragData
23764 getDragData : function(e){
23765 return Roo.dd.Registry.getHandleFromEvent(e);
23769 * Called once drag threshold has been reached to initialize the proxy element. By default, it clones the
23770 * this.dragData.ddel
23771 * @param {Number} x The x position of the click on the dragged object
23772 * @param {Number} y The y position of the click on the dragged object
23773 * @return {Boolean} true to continue the drag, false to cancel
23775 onInitDrag : function(x, y){
23776 this.proxy.update(this.dragData.ddel.cloneNode(true));
23777 this.onStartDrag(x, y);
23782 * Called after a repair of an invalid drop. By default, highlights this.dragData.ddel
23784 afterRepair : function(){
23786 Roo.Element.fly(this.dragData.ddel).highlight(this.hlColor || "c3daf9");
23788 this.dragging = false;
23792 * Called before a repair of an invalid drop to get the XY to animate to. By default returns
23793 * the XY of this.dragData.ddel
23794 * @param {EventObject} e The mouse up event
23795 * @return {Array} The xy location (e.g. [100, 200])
23797 getRepairXY : function(e){
23798 return Roo.Element.fly(this.dragData.ddel).getXY();
23802 * Ext JS Library 1.1.1
23803 * Copyright(c) 2006-2007, Ext JS, LLC.
23805 * Originally Released Under LGPL - original licence link has changed is not relivant.
23808 * <script type="text/javascript">
23811 * @class Roo.dd.DropZone
23812 * @extends Roo.dd.DropTarget
23813 * This class provides a container DD instance that proxies for multiple child node targets.<br />
23814 * By default, this class requires that child nodes accepting drop are registered with {@link Roo.dd.Registry}.
23816 * @param {String/HTMLElement/Element} el The container element
23817 * @param {Object} config
23819 Roo.dd.DropZone = function(el, config){
23820 Roo.dd.DropZone.superclass.constructor.call(this, el, config);
23823 Roo.extend(Roo.dd.DropZone, Roo.dd.DropTarget, {
23825 * Returns a custom data object associated with the DOM node that is the target of the event. By default
23826 * this looks up the event target in the {@link Roo.dd.Registry}, although you can override this method to
23827 * provide your own custom lookup.
23828 * @param {Event} e The event
23829 * @return {Object} data The custom data
23831 getTargetFromEvent : function(e){
23832 return Roo.dd.Registry.getTargetFromEvent(e);
23836 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has entered a drop node
23837 * that it has registered. This method has no default implementation and should be overridden to provide
23838 * node-specific processing if necessary.
23839 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
23840 * {@link #getTargetFromEvent} for this node)
23841 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23842 * @param {Event} e The event
23843 * @param {Object} data An object containing arbitrary data supplied by the drag source
23845 onNodeEnter : function(n, dd, e, data){
23850 * Called internally while the DropZone determines that a {@link Roo.dd.DragSource} is over a drop node
23851 * that it has registered. The default implementation returns this.dropNotAllowed, so it should be
23852 * overridden to provide the proper feedback.
23853 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
23854 * {@link #getTargetFromEvent} for this node)
23855 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23856 * @param {Event} e The event
23857 * @param {Object} data An object containing arbitrary data supplied by the drag source
23858 * @return {String} status The CSS class that communicates the drop status back to the source so that the
23859 * underlying {@link Roo.dd.StatusProxy} can be updated
23861 onNodeOver : function(n, dd, e, data){
23862 return this.dropAllowed;
23866 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dragged out of
23867 * the drop node without dropping. This method has no default implementation and should be overridden to provide
23868 * node-specific processing if necessary.
23869 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
23870 * {@link #getTargetFromEvent} for this node)
23871 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23872 * @param {Event} e The event
23873 * @param {Object} data An object containing arbitrary data supplied by the drag source
23875 onNodeOut : function(n, dd, e, data){
23880 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dropped onto
23881 * the drop node. The default implementation returns false, so it should be overridden to provide the
23882 * appropriate processing of the drop event and return true so that the drag source's repair action does not run.
23883 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
23884 * {@link #getTargetFromEvent} for this node)
23885 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23886 * @param {Event} e The event
23887 * @param {Object} data An object containing arbitrary data supplied by the drag source
23888 * @return {Boolean} True if the drop was valid, else false
23890 onNodeDrop : function(n, dd, e, data){
23895 * Called internally while the DropZone determines that a {@link Roo.dd.DragSource} is being dragged over it,
23896 * but not over any of its registered drop nodes. The default implementation returns this.dropNotAllowed, so
23897 * it should be overridden to provide the proper feedback if necessary.
23898 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23899 * @param {Event} e The event
23900 * @param {Object} data An object containing arbitrary data supplied by the drag source
23901 * @return {String} status The CSS class that communicates the drop status back to the source so that the
23902 * underlying {@link Roo.dd.StatusProxy} can be updated
23904 onContainerOver : function(dd, e, data){
23905 return this.dropNotAllowed;
23909 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dropped on it,
23910 * but not on any of its registered drop nodes. The default implementation returns false, so it should be
23911 * overridden to provide the appropriate processing of the drop event if you need the drop zone itself to
23912 * be able to accept drops. It should return true when valid so that the drag source's repair action does not run.
23913 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23914 * @param {Event} e The event
23915 * @param {Object} data An object containing arbitrary data supplied by the drag source
23916 * @return {Boolean} True if the drop was valid, else false
23918 onContainerDrop : function(dd, e, data){
23923 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the source is now over
23924 * the zone. The default implementation returns this.dropNotAllowed and expects that only registered drop
23925 * nodes can process drag drop operations, so if you need the drop zone itself to be able to process drops
23926 * you should override this method and provide a custom implementation.
23927 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23928 * @param {Event} e The event
23929 * @param {Object} data An object containing arbitrary data supplied by the drag source
23930 * @return {String} status The CSS class that communicates the drop status back to the source so that the
23931 * underlying {@link Roo.dd.StatusProxy} can be updated
23933 notifyEnter : function(dd, e, data){
23934 return this.dropNotAllowed;
23938 * The function a {@link Roo.dd.DragSource} calls continuously while it is being dragged over the drop zone.
23939 * This method will be called on every mouse movement while the drag source is over the drop zone.
23940 * It will call {@link #onNodeOver} while the drag source is over a registered node, and will also automatically
23941 * delegate to the appropriate node-specific methods as necessary when the drag source enters and exits
23942 * registered nodes ({@link #onNodeEnter}, {@link #onNodeOut}). If the drag source is not currently over a
23943 * registered node, it will call {@link #onContainerOver}.
23944 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23945 * @param {Event} e The event
23946 * @param {Object} data An object containing arbitrary data supplied by the drag source
23947 * @return {String} status The CSS class that communicates the drop status back to the source so that the
23948 * underlying {@link Roo.dd.StatusProxy} can be updated
23950 notifyOver : function(dd, e, data){
23951 var n = this.getTargetFromEvent(e);
23952 if(!n){ // not over valid drop target
23953 if(this.lastOverNode){
23954 this.onNodeOut(this.lastOverNode, dd, e, data);
23955 this.lastOverNode = null;
23957 return this.onContainerOver(dd, e, data);
23959 if(this.lastOverNode != n){
23960 if(this.lastOverNode){
23961 this.onNodeOut(this.lastOverNode, dd, e, data);
23963 this.onNodeEnter(n, dd, e, data);
23964 this.lastOverNode = n;
23966 return this.onNodeOver(n, dd, e, data);
23970 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the source has been dragged
23971 * out of the zone without dropping. If the drag source is currently over a registered node, the notification
23972 * will be delegated to {@link #onNodeOut} for node-specific handling, otherwise it will be ignored.
23973 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
23974 * @param {Event} e The event
23975 * @param {Object} data An object containing arbitrary data supplied by the drag zone
23977 notifyOut : function(dd, e, data){
23978 if(this.lastOverNode){
23979 this.onNodeOut(this.lastOverNode, dd, e, data);
23980 this.lastOverNode = null;
23985 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the dragged item has
23986 * been dropped on it. The drag zone will look up the target node based on the event passed in, and if there
23987 * is a node registered for that event, it will delegate to {@link #onNodeDrop} for node-specific handling,
23988 * otherwise it will call {@link #onContainerDrop}.
23989 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
23990 * @param {Event} e The event
23991 * @param {Object} data An object containing arbitrary data supplied by the drag source
23992 * @return {Boolean} True if the drop was valid, else false
23994 notifyDrop : function(dd, e, data){
23995 if(this.lastOverNode){
23996 this.onNodeOut(this.lastOverNode, dd, e, data);
23997 this.lastOverNode = null;
23999 var n = this.getTargetFromEvent(e);
24001 this.onNodeDrop(n, dd, e, data) :
24002 this.onContainerDrop(dd, e, data);
24006 triggerCacheRefresh : function(){
24007 Roo.dd.DDM.refreshCache(this.groups);