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 * Ext JS Library 1.1.1
960 * Copyright(c) 2006-2007, Ext JS, LLC.
962 * Originally Released Under LGPL - original licence link has changed is not relivant.
965 * <script type="text/javascript">
971 Roo.applyIf(Number.prototype, {
973 * Checks whether or not the current number is within a desired range. If the number is already within the
974 * range it is returned, otherwise the min or max value is returned depending on which side of the range is
975 * exceeded. Note that this method returns the constrained value but does not change the current number.
976 * @param {Number} min The minimum number in the range
977 * @param {Number} max The maximum number in the range
978 * @return {Number} The constrained value if outside the range, otherwise the current value
980 constrain : function(min, max){
981 return Math.min(Math.max(this, min), max);
985 * Ext JS Library 1.1.1
986 * Copyright(c) 2006-2007, Ext JS, LLC.
988 * Originally Released Under LGPL - original licence link has changed is not relivant.
991 * <script type="text/javascript">
996 Roo.applyIf(Array.prototype, {
999 * Checks whether or not the specified object exists in the array.
1000 * @param {Object} o The object to check for
1001 * @return {Number} The index of o in the array (or -1 if it is not found)
1003 indexOf : function(o){
1004 for (var i = 0, len = this.length; i < len; i++){
1005 if(this[i] == o) { return i; }
1011 * Removes the specified object from the array. If the object is not found nothing happens.
1012 * @param {Object} o The object to remove
1014 remove : function(o){
1015 var index = this.indexOf(o);
1017 this.splice(index, 1);
1021 * Map (JS 1.6 compatibility)
1022 * @param {Function} function to call
1024 map : function(fun )
1026 var len = this.length >>> 0;
1027 if (typeof fun != "function") {
1028 throw new TypeError();
1030 var res = new Array(len);
1031 var thisp = arguments[1];
1032 for (var i = 0; i < len; i++)
1035 res[i] = fun.call(thisp, this[i], i, this);
1043 * @param {Array} o The array to compare to
1044 * @returns {Boolean} true if the same
1046 equals : function(b)
1048 // https://stackoverflow.com/questions/3115982/how-to-check-if-two-arrays-are-equal-with-javascript
1055 if (this.length !== b.length) {
1059 // sort?? a.sort().equals(b.sort());
1061 for (var i = 0; i < this.length; ++i) {
1062 if (this[i] !== b[i]) {
1074 Roo.applyIf(Array, {
1078 * @param {Array} o Or Array like object (eg. nodelist)
1085 for (var i =0; i < o.length; i++) {
1094 * Ext JS Library 1.1.1
1095 * Copyright(c) 2006-2007, Ext JS, LLC.
1097 * Originally Released Under LGPL - original licence link has changed is not relivant.
1100 * <script type="text/javascript">
1106 * The date parsing and format syntax is a subset of
1107 * <a href="http://www.php.net/date">PHP's date() function</a>, and the formats that are
1108 * supported will provide results equivalent to their PHP versions.
1110 * Following is the list of all currently supported formats:
1113 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'
1115 Format Output Description
1116 ------ ---------- --------------------------------------------------------------
1117 d 10 Day of the month, 2 digits with leading zeros
1118 D Wed A textual representation of a day, three letters
1119 j 10 Day of the month without leading zeros
1120 l Wednesday A full textual representation of the day of the week
1121 S th English ordinal day of month suffix, 2 chars (use with j)
1122 w 3 Numeric representation of the day of the week
1123 z 9 The julian date, or day of the year (0-365)
1124 W 01 ISO-8601 2-digit week number of year, weeks starting on Monday (00-52)
1125 F January A full textual representation of the month
1126 m 01 Numeric representation of a month, with leading zeros
1127 M Jan Month name abbreviation, three letters
1128 n 1 Numeric representation of a month, without leading zeros
1129 t 31 Number of days in the given month
1130 L 0 Whether it's a leap year (1 if it is a leap year, else 0)
1131 Y 2007 A full numeric representation of a year, 4 digits
1132 y 07 A two digit representation of a year
1133 a pm Lowercase Ante meridiem and Post meridiem
1134 A PM Uppercase Ante meridiem and Post meridiem
1135 g 3 12-hour format of an hour without leading zeros
1136 G 15 24-hour format of an hour without leading zeros
1137 h 03 12-hour format of an hour with leading zeros
1138 H 15 24-hour format of an hour with leading zeros
1139 i 05 Minutes with leading zeros
1140 s 01 Seconds, with leading zeros
1141 O -0600 Difference to Greenwich time (GMT) in hours (Allows +08, without minutes)
1142 P -06:00 Difference to Greenwich time (GMT) with colon between hours and minutes
1143 T CST Timezone setting of the machine running the code
1144 Z -21600 Timezone offset in seconds (negative if west of UTC, positive if east)
1147 * Example usage (note that you must escape format specifiers with '\\' to render them as character literals):
1149 var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
1150 document.write(dt.format('Y-m-d')); //2007-01-10
1151 document.write(dt.format('F j, Y, g:i a')); //January 10, 2007, 3:05 pm
1152 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
1155 * Here are some standard date/time patterns that you might find helpful. They
1156 * are not part of the source of Date.js, but to use them you can simply copy this
1157 * block of code into any script that is included after Date.js and they will also become
1158 * globally available on the Date object. Feel free to add or remove patterns as needed in your code.
1161 ISO8601Long:"Y-m-d H:i:s",
1162 ISO8601Short:"Y-m-d",
1164 LongDate: "l, F d, Y",
1165 FullDateTime: "l, F d, Y g:i:s A",
1168 LongTime: "g:i:s A",
1169 SortableDateTime: "Y-m-d\\TH:i:s",
1170 UniversalSortableDateTime: "Y-m-d H:i:sO",
1177 var dt = new Date();
1178 document.write(dt.format(Date.patterns.ShortDate));
1183 * Most of the date-formatting functions below are the excellent work of Baron Schwartz.
1184 * They generate precompiled functions from date formats instead of parsing and
1185 * processing the pattern every time you format a date. These functions are available
1186 * on every Date object (any javascript function).
1188 * The original article and download are here:
1189 * http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/
1196 Returns the number of milliseconds between this date and date
1197 @param {Date} date (optional) Defaults to now
1198 @return {Number} The diff in milliseconds
1199 @member Date getElapsed
1201 Date.prototype.getElapsed = function(date) {
1202 return Math.abs((date || new Date()).getTime()-this.getTime());
1204 // was in date file..
1208 Date.parseFunctions = {count:0};
1210 Date.parseRegexes = [];
1212 Date.formatFunctions = {count:0};
1215 Date.prototype.dateFormat = function(format) {
1216 if (Date.formatFunctions[format] == null) {
1217 Date.createNewFormat(format);
1219 var func = Date.formatFunctions[format];
1220 return this[func]();
1225 * Formats a date given the supplied format string
1226 * @param {String} format The format string
1227 * @return {String} The formatted date
1230 Date.prototype.format = Date.prototype.dateFormat;
1233 Date.createNewFormat = function(format) {
1234 var funcName = "format" + Date.formatFunctions.count++;
1235 Date.formatFunctions[format] = funcName;
1236 var code = "Date.prototype." + funcName + " = function(){return ";
1237 var special = false;
1239 for (var i = 0; i < format.length; ++i) {
1240 ch = format.charAt(i);
1241 if (!special && ch == "\\") {
1246 code += "'" + String.escape(ch) + "' + ";
1249 code += Date.getFormatCode(ch);
1252 /** eval:var:zzzzzzzzzzzzz */
1253 eval(code.substring(0, code.length - 3) + ";}");
1257 Date.getFormatCode = function(character) {
1258 switch (character) {
1260 return "String.leftPad(this.getDate(), 2, '0') + ";
1262 return "Date.dayNames[this.getDay()].substring(0, 3) + ";
1264 return "this.getDate() + ";
1266 return "Date.dayNames[this.getDay()] + ";
1268 return "this.getSuffix() + ";
1270 return "this.getDay() + ";
1272 return "this.getDayOfYear() + ";
1274 return "this.getWeekOfYear() + ";
1276 return "Date.monthNames[this.getMonth()] + ";
1278 return "String.leftPad(this.getMonth() + 1, 2, '0') + ";
1280 return "Date.monthNames[this.getMonth()].substring(0, 3) + ";
1282 return "(this.getMonth() + 1) + ";
1284 return "this.getDaysInMonth() + ";
1286 return "(this.isLeapYear() ? 1 : 0) + ";
1288 return "this.getFullYear() + ";
1290 return "('' + this.getFullYear()).substring(2, 4) + ";
1292 return "(this.getHours() < 12 ? 'am' : 'pm') + ";
1294 return "(this.getHours() < 12 ? 'AM' : 'PM') + ";
1296 return "((this.getHours() % 12) ? this.getHours() % 12 : 12) + ";
1298 return "this.getHours() + ";
1300 return "String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0') + ";
1302 return "String.leftPad(this.getHours(), 2, '0') + ";
1304 return "String.leftPad(this.getMinutes(), 2, '0') + ";
1306 return "String.leftPad(this.getSeconds(), 2, '0') + ";
1308 return "this.getGMTOffset() + ";
1310 return "this.getGMTColonOffset() + ";
1312 return "this.getTimezone() + ";
1314 return "(this.getTimezoneOffset() * -60) + ";
1316 return "'" + String.escape(character) + "' + ";
1321 * Parses the passed string using the specified format. Note that this function expects dates in normal calendar
1322 * format, meaning that months are 1-based (1 = January) and not zero-based like in JavaScript dates. Any part of
1323 * the date format that is not specified will default to the current date value for that part. Time parts can also
1324 * be specified, but default to 0. Keep in mind that the input date string must precisely match the specified format
1325 * string or the parse operation will fail.
1328 //dt = Fri May 25 2007 (current date)
1329 var dt = new Date();
1331 //dt = Thu May 25 2006 (today's month/day in 2006)
1332 dt = Date.parseDate("2006", "Y");
1334 //dt = Sun Jan 15 2006 (all date parts specified)
1335 dt = Date.parseDate("2006-1-15", "Y-m-d");
1337 //dt = Sun Jan 15 2006 15:20:01 GMT-0600 (CST)
1338 dt = Date.parseDate("2006-1-15 3:20:01 PM", "Y-m-d h:i:s A" );
1340 * @param {String} input The unparsed date as a string
1341 * @param {String} format The format the date is in
1342 * @return {Date} The parsed date
1345 Date.parseDate = function(input, format) {
1346 if (Date.parseFunctions[format] == null) {
1347 Date.createParser(format);
1349 var func = Date.parseFunctions[format];
1350 return Date[func](input);
1356 Date.createParser = function(format) {
1357 var funcName = "parse" + Date.parseFunctions.count++;
1358 var regexNum = Date.parseRegexes.length;
1359 var currentGroup = 1;
1360 Date.parseFunctions[format] = funcName;
1362 var code = "Date." + funcName + " = function(input){\n"
1363 + "var y = -1, m = -1, d = -1, h = -1, i = -1, s = -1, o, z, v;\n"
1364 + "var d = new Date();\n"
1365 + "y = d.getFullYear();\n"
1366 + "m = d.getMonth();\n"
1367 + "d = d.getDate();\n"
1368 + "if (typeof(input) !== 'string') { input = input.toString(); }\n"
1369 + "var results = input.match(Date.parseRegexes[" + regexNum + "]);\n"
1370 + "if (results && results.length > 0) {";
1373 var special = false;
1375 for (var i = 0; i < format.length; ++i) {
1376 ch = format.charAt(i);
1377 if (!special && ch == "\\") {
1382 regex += String.escape(ch);
1385 var obj = Date.formatCodeToRegex(ch, currentGroup);
1386 currentGroup += obj.g;
1388 if (obj.g && obj.c) {
1394 code += "if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0)\n"
1395 + "{v = new Date(y, m, d, h, i, s); v.setFullYear(y);}\n"
1396 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0)\n"
1397 + "{v = new Date(y, m, d, h, i); v.setFullYear(y);}\n"
1398 + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0)\n"
1399 + "{v = new Date(y, m, d, h); v.setFullYear(y);}\n"
1400 + "else if (y >= 0 && m >= 0 && d > 0)\n"
1401 + "{v = new Date(y, m, d); v.setFullYear(y);}\n"
1402 + "else if (y >= 0 && m >= 0)\n"
1403 + "{v = new Date(y, m); v.setFullYear(y);}\n"
1404 + "else if (y >= 0)\n"
1405 + "{v = new Date(y); v.setFullYear(y);}\n"
1406 + "}return (v && (z || o))?\n" // favour UTC offset over GMT offset
1407 + " ((z)? v.add(Date.SECOND, (v.getTimezoneOffset() * 60) + (z*1)) :\n" // reset to UTC, then add offset
1408 + " v.add(Date.HOUR, (v.getGMTOffset() / 100) + (o / -100))) : v\n" // reset to GMT, then add offset
1411 Date.parseRegexes[regexNum] = new RegExp("^" + regex + "$");
1412 /** eval:var:zzzzzzzzzzzzz */
1417 Date.formatCodeToRegex = function(character, currentGroup) {
1418 switch (character) {
1422 s:"(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)"};
1425 c:"d = parseInt(results[" + currentGroup + "], 10);\n",
1426 s:"(\\d{1,2})"}; // day of month without leading zeroes
1429 c:"d = parseInt(results[" + currentGroup + "], 10);\n",
1430 s:"(\\d{2})"}; // day of month with leading zeroes
1434 s:"(?:" + Date.dayNames.join("|") + ")"};
1438 s:"(?:st|nd|rd|th)"};
1453 c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "].substring(0, 3)], 10);\n",
1454 s:"(" + Date.monthNames.join("|") + ")"};
1457 c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "]], 10);\n",
1458 s:"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)"};
1461 c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
1462 s:"(\\d{1,2})"}; // Numeric representation of a month, without leading zeros
1465 c:"m = Math.max(0,parseInt(results[" + currentGroup + "], 10) - 1);\n",
1466 s:"(\\d{2})"}; // Numeric representation of a month, with leading zeros
1477 c:"y = parseInt(results[" + currentGroup + "], 10);\n",
1481 c:"var ty = parseInt(results[" + currentGroup + "], 10);\n"
1482 + "y = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n",
1486 c:"if (results[" + currentGroup + "] == 'am') {\n"
1487 + "if (h == 12) { h = 0; }\n"
1488 + "} else { if (h < 12) { h += 12; }}",
1492 c:"if (results[" + currentGroup + "] == 'AM') {\n"
1493 + "if (h == 12) { h = 0; }\n"
1494 + "} else { if (h < 12) { h += 12; }}",
1499 c:"h = parseInt(results[" + currentGroup + "], 10);\n",
1500 s:"(\\d{1,2})"}; // 12/24-hr format format of an hour without leading zeroes
1504 c:"h = parseInt(results[" + currentGroup + "], 10);\n",
1505 s:"(\\d{2})"}; // 12/24-hr format format of an hour with leading zeroes
1508 c:"i = parseInt(results[" + currentGroup + "], 10);\n",
1512 c:"s = parseInt(results[" + currentGroup + "], 10);\n",
1517 "o = results[", currentGroup, "];\n",
1518 "var sn = o.substring(0,1);\n", // get + / - sign
1519 "var hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60);\n", // get hours (performs minutes-to-hour conversion also)
1520 "var mn = o.substring(3,5) % 60;\n", // get minutes
1521 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n", // -12hrs <= GMT offset <= 14hrs
1522 " (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"
1524 s:"([+\-]\\d{2,4})"};
1530 "o = results[", currentGroup, "];\n",
1531 "var sn = o.substring(0,1);\n",
1532 "var hr = o.substring(1,3)*1 + Math.floor(o.substring(4,6) / 60);\n",
1533 "var mn = o.substring(4,6) % 60;\n",
1534 "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n",
1535 " (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"
1541 s:"[A-Z]{1,4}"}; // timezone abbrev. may be between 1 - 4 chars
1544 c:"z = results[" + currentGroup + "];\n" // -43200 <= UTC offset <= 50400
1545 + "z = (-43200 <= z*1 && z*1 <= 50400)? z : null;\n",
1546 s:"([+\-]?\\d{1,5})"}; // leading '+' sign is optional for UTC offset
1550 s:String.escape(character)};
1555 * Get the timezone abbreviation of the current date (equivalent to the format specifier 'T').
1556 * @return {String} The abbreviated timezone name (e.g. 'CST')
1558 Date.prototype.getTimezone = function() {
1559 return this.toString().replace(/^.*? ([A-Z]{1,4})[\-+][0-9]{4} .*$/, "$1");
1563 * Get the offset from GMT of the current date (equivalent to the format specifier 'O').
1564 * @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600')
1566 Date.prototype.getGMTOffset = function() {
1567 return (this.getTimezoneOffset() > 0 ? "-" : "+")
1568 + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
1569 + String.leftPad(this.getTimezoneOffset() % 60, 2, "0");
1573 * Get the offset from GMT of the current date (equivalent to the format specifier 'P').
1574 * @return {String} 2-characters representing hours and 2-characters representing minutes
1575 * seperated by a colon and prefixed with + or - (e.g. '-06:00')
1577 Date.prototype.getGMTColonOffset = function() {
1578 return (this.getTimezoneOffset() > 0 ? "-" : "+")
1579 + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
1581 + String.leftPad(this.getTimezoneOffset() %60, 2, "0");
1585 * Get the numeric day number of the year, adjusted for leap year.
1586 * @return {Number} 0 through 364 (365 in leap years)
1588 Date.prototype.getDayOfYear = function() {
1590 Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
1591 for (var i = 0; i < this.getMonth(); ++i) {
1592 num += Date.daysInMonth[i];
1594 return num + this.getDate() - 1;
1598 * Get the string representation of the numeric week number of the year
1599 * (equivalent to the format specifier 'W').
1600 * @return {String} '00' through '52'
1602 Date.prototype.getWeekOfYear = function() {
1603 // Skip to Thursday of this week
1604 var now = this.getDayOfYear() + (4 - this.getDay());
1605 // Find the first Thursday of the year
1606 var jan1 = new Date(this.getFullYear(), 0, 1);
1607 var then = (7 - jan1.getDay() + 4);
1608 return String.leftPad(((now - then) / 7) + 1, 2, "0");
1612 * Whether or not the current date is in a leap year.
1613 * @return {Boolean} True if the current date is in a leap year, else false
1615 Date.prototype.isLeapYear = function() {
1616 var year = this.getFullYear();
1617 return ((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
1621 * Get the first day of the current month, adjusted for leap year. The returned value
1622 * is the numeric day index within the week (0-6) which can be used in conjunction with
1623 * the {@link #monthNames} array to retrieve the textual day name.
1626 var dt = new Date('1/10/2007');
1627 document.write(Date.dayNames[dt.getFirstDayOfMonth()]); //output: 'Monday'
1629 * @return {Number} The day number (0-6)
1631 Date.prototype.getFirstDayOfMonth = function() {
1632 var day = (this.getDay() - (this.getDate() - 1)) % 7;
1633 return (day < 0) ? (day + 7) : day;
1637 * Get the last day of the current month, adjusted for leap year. The returned value
1638 * is the numeric day index within the week (0-6) which can be used in conjunction with
1639 * the {@link #monthNames} array to retrieve the textual day name.
1642 var dt = new Date('1/10/2007');
1643 document.write(Date.dayNames[dt.getLastDayOfMonth()]); //output: 'Wednesday'
1645 * @return {Number} The day number (0-6)
1647 Date.prototype.getLastDayOfMonth = function() {
1648 var day = (this.getDay() + (Date.daysInMonth[this.getMonth()] - this.getDate())) % 7;
1649 return (day < 0) ? (day + 7) : day;
1654 * Get the first date of this date's month
1657 Date.prototype.getFirstDateOfMonth = function() {
1658 return new Date(this.getFullYear(), this.getMonth(), 1);
1662 * Get the last date of this date's month
1665 Date.prototype.getLastDateOfMonth = function() {
1666 return new Date(this.getFullYear(), this.getMonth(), this.getDaysInMonth());
1669 * Get the number of days in the current month, adjusted for leap year.
1670 * @return {Number} The number of days in the month
1672 Date.prototype.getDaysInMonth = function() {
1673 Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
1674 return Date.daysInMonth[this.getMonth()];
1678 * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S').
1679 * @return {String} 'st, 'nd', 'rd' or 'th'
1681 Date.prototype.getSuffix = function() {
1682 switch (this.getDate()) {
1699 Date.daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
1702 * An array of textual month names.
1703 * Override these values for international dates, for example...
1704 * Date.monthNames = ['JanInYourLang', 'FebInYourLang', ...];
1723 * An array of textual day names.
1724 * Override these values for international dates, for example...
1725 * Date.dayNames = ['SundayInYourLang', 'MondayInYourLang', ...];
1741 Date.monthNumbers = {
1756 * Creates and returns a new Date instance with the exact same date value as the called instance.
1757 * Dates are copied and passed by reference, so if a copied date variable is modified later, the original
1758 * variable will also be changed. When the intention is to create a new variable that will not
1759 * modify the original instance, you should create a clone.
1761 * Example of correctly cloning a date:
1764 var orig = new Date('10/1/2006');
1767 document.write(orig); //returns 'Thu Oct 05 2006'!
1770 var orig = new Date('10/1/2006');
1771 var copy = orig.clone();
1773 document.write(orig); //returns 'Thu Oct 01 2006'
1775 * @return {Date} The new Date instance
1777 Date.prototype.clone = function() {
1778 return new Date(this.getTime());
1782 * Clears any time information from this date
1783 @param {Boolean} clone true to create a clone of this date, clear the time and return it
1784 @return {Date} this or the clone
1786 Date.prototype.clearTime = function(clone){
1788 return this.clone().clearTime();
1793 this.setMilliseconds(0);
1798 // safari setMonth is broken -- check that this is only donw once...
1799 if(Roo.isSafari && typeof(Date.brokenSetMonth) == 'undefined'){
1800 Date.brokenSetMonth = Date.prototype.setMonth;
1801 Date.prototype.setMonth = function(num){
1803 var n = Math.ceil(-num);
1804 var back_year = Math.ceil(n/12);
1805 var month = (n % 12) ? 12 - n % 12 : 0 ;
1806 this.setFullYear(this.getFullYear() - back_year);
1807 return Date.brokenSetMonth.call(this, month);
1809 return Date.brokenSetMonth.apply(this, arguments);
1814 /** Date interval constant
1818 /** Date interval constant
1822 /** Date interval constant
1826 /** Date interval constant
1830 /** Date interval constant
1834 /** Date interval constant
1838 /** Date interval constant
1844 * Provides a convenient method of performing basic date arithmetic. This method
1845 * does not modify the Date instance being called - it creates and returns
1846 * a new Date instance containing the resulting date value.
1851 var dt = new Date('10/29/2006').add(Date.DAY, 5);
1852 document.write(dt); //returns 'Fri Oct 06 2006 00:00:00'
1854 //Negative values will subtract correctly:
1855 var dt2 = new Date('10/1/2006').add(Date.DAY, -5);
1856 document.write(dt2); //returns 'Tue Sep 26 2006 00:00:00'
1858 //You can even chain several calls together in one line!
1859 var dt3 = new Date('10/1/2006').add(Date.DAY, 5).add(Date.HOUR, 8).add(Date.MINUTE, -30);
1860 document.write(dt3); //returns 'Fri Oct 06 2006 07:30:00'
1863 * @param {String} interval A valid date interval enum value
1864 * @param {Number} value The amount to add to the current date
1865 * @return {Date} The new Date instance
1867 Date.prototype.add = function(interval, value){
1868 var d = this.clone();
1869 if (!interval || value === 0) { return d; }
1870 switch(interval.toLowerCase()){
1872 d.setMilliseconds(this.getMilliseconds() + value);
1875 d.setSeconds(this.getSeconds() + value);
1878 d.setMinutes(this.getMinutes() + value);
1881 d.setHours(this.getHours() + value);
1884 d.setDate(this.getDate() + value);
1887 var day = this.getDate();
1889 day = Math.min(day, this.getFirstDateOfMonth().add('mo', value).getLastDateOfMonth().getDate());
1892 d.setMonth(this.getMonth() + value);
1895 d.setFullYear(this.getFullYear() + value);
1901 * @class Roo.lib.Dom
1905 * Dom utils (from YIU afaik)
1911 * Get the view width
1912 * @param {Boolean} full True will get the full document, otherwise it's the view width
1913 * @return {Number} The width
1916 getViewWidth : function(full) {
1917 return full ? this.getDocumentWidth() : this.getViewportWidth();
1920 * Get the view height
1921 * @param {Boolean} full True will get the full document, otherwise it's the view height
1922 * @return {Number} The height
1924 getViewHeight : function(full) {
1925 return full ? this.getDocumentHeight() : this.getViewportHeight();
1928 * Get the Full Document height
1929 * @return {Number} The height
1931 getDocumentHeight: function() {
1932 var scrollHeight = (document.compatMode != "CSS1Compat") ? document.body.scrollHeight : document.documentElement.scrollHeight;
1933 return Math.max(scrollHeight, this.getViewportHeight());
1936 * Get the Full Document width
1937 * @return {Number} The width
1939 getDocumentWidth: function() {
1940 var scrollWidth = (document.compatMode != "CSS1Compat") ? document.body.scrollWidth : document.documentElement.scrollWidth;
1941 return Math.max(scrollWidth, this.getViewportWidth());
1944 * Get the Window Viewport height
1945 * @return {Number} The height
1947 getViewportHeight: function() {
1948 var height = self.innerHeight;
1949 var mode = document.compatMode;
1951 if ((mode || Roo.isIE) && !Roo.isOpera) {
1952 height = (mode == "CSS1Compat") ?
1953 document.documentElement.clientHeight :
1954 document.body.clientHeight;
1960 * Get the Window Viewport width
1961 * @return {Number} The width
1963 getViewportWidth: function() {
1964 var width = self.innerWidth;
1965 var mode = document.compatMode;
1967 if (mode || Roo.isIE) {
1968 width = (mode == "CSS1Compat") ?
1969 document.documentElement.clientWidth :
1970 document.body.clientWidth;
1975 isAncestor : function(p, c) {
1982 if (p.contains && !Roo.isSafari) {
1983 return p.contains(c);
1984 } else if (p.compareDocumentPosition) {
1985 return !!(p.compareDocumentPosition(c) & 16);
1987 var parent = c.parentNode;
1992 else if (!parent.tagName || parent.tagName.toUpperCase() == "HTML") {
1995 parent = parent.parentNode;
2001 getRegion : function(el) {
2002 return Roo.lib.Region.getRegion(el);
2005 getY : function(el) {
2006 return this.getXY(el)[1];
2009 getX : function(el) {
2010 return this.getXY(el)[0];
2013 getXY : function(el) {
2014 var p, pe, b, scroll, bd = document.body;
2015 el = Roo.getDom(el);
2016 var fly = Roo.lib.AnimBase.fly;
2017 if (el.getBoundingClientRect) {
2018 b = el.getBoundingClientRect();
2019 scroll = fly(document).getScroll();
2020 return [b.left + scroll.left, b.top + scroll.top];
2026 var hasAbsolute = fly(el).getStyle("position") == "absolute";
2033 if (!hasAbsolute && fly(p).getStyle("position") == "absolute") {
2040 var bt = parseInt(pe.getStyle("borderTopWidth"), 10) || 0;
2041 var bl = parseInt(pe.getStyle("borderLeftWidth"), 10) || 0;
2048 if (p != el && pe.getStyle('overflow') != 'visible') {
2056 if (Roo.isSafari && hasAbsolute) {
2061 if (Roo.isGecko && !hasAbsolute) {
2063 x += parseInt(dbd.getStyle("borderLeftWidth"), 10) || 0;
2064 y += parseInt(dbd.getStyle("borderTopWidth"), 10) || 0;
2068 while (p && p != bd) {
2069 if (!Roo.isOpera || (p.tagName != 'TR' && fly(p).getStyle("display") != "inline")) {
2081 setXY : function(el, xy) {
2082 el = Roo.fly(el, '_setXY');
2084 var pts = el.translatePoints(xy);
2085 if (xy[0] !== false) {
2086 el.dom.style.left = pts.left + "px";
2088 if (xy[1] !== false) {
2089 el.dom.style.top = pts.top + "px";
2093 setX : function(el, x) {
2094 this.setXY(el, [x, false]);
2097 setY : function(el, y) {
2098 this.setXY(el, [false, y]);
2102 * Portions of this file are based on pieces of Yahoo User Interface Library
2103 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
2104 * YUI licensed under the BSD License:
2105 * http://developer.yahoo.net/yui/license.txt
2106 * <script type="text/javascript">
2110 Roo.lib.Event = function() {
2111 var loadComplete = false;
2113 var unloadListeners = [];
2115 var onAvailStack = [];
2117 var lastError = null;
2130 startInterval: function() {
2131 if (!this._interval) {
2133 var callback = function() {
2134 self._tryPreloadAttach();
2136 this._interval = setInterval(callback, this.POLL_INTERVAL);
2141 onAvailable: function(p_id, p_fn, p_obj, p_override) {
2142 onAvailStack.push({ id: p_id,
2145 override: p_override,
2146 checkReady: false });
2148 retryCount = this.POLL_RETRYS;
2149 this.startInterval();
2153 addListener: function(el, eventName, fn) {
2154 el = Roo.getDom(el);
2159 if ("unload" == eventName) {
2160 unloadListeners[unloadListeners.length] =
2161 [el, eventName, fn];
2165 var wrappedFn = function(e) {
2166 return fn(Roo.lib.Event.getEvent(e));
2169 var li = [el, eventName, fn, wrappedFn];
2171 var index = listeners.length;
2172 listeners[index] = li;
2174 this.doAdd(el, eventName, wrappedFn, false);
2180 removeListener: function(el, eventName, fn) {
2183 el = Roo.getDom(el);
2186 return this.purgeElement(el, false, eventName);
2190 if ("unload" == eventName) {
2192 for (i = 0,len = unloadListeners.length; i < len; i++) {
2193 var li = unloadListeners[i];
2196 li[1] == eventName &&
2198 unloadListeners.splice(i, 1);
2206 var cacheItem = null;
2209 var index = arguments[3];
2211 if ("undefined" == typeof index) {
2212 index = this._getCacheIndex(el, eventName, fn);
2216 cacheItem = listeners[index];
2219 if (!el || !cacheItem) {
2223 this.doRemove(el, eventName, cacheItem[this.WFN], false);
2225 delete listeners[index][this.WFN];
2226 delete listeners[index][this.FN];
2227 listeners.splice(index, 1);
2234 getTarget: function(ev, resolveTextNode) {
2235 ev = ev.browserEvent || ev;
2236 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2237 var t = ev.target || ev.srcElement;
2238 return this.resolveTextNode(t);
2242 resolveTextNode: function(node) {
2243 if (Roo.isSafari && node && 3 == node.nodeType) {
2244 return node.parentNode;
2251 getPageX: function(ev) {
2252 ev = ev.browserEvent || ev;
2253 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2255 if (!x && 0 !== x) {
2256 x = ev.clientX || 0;
2259 x += this.getScroll()[1];
2267 getPageY: function(ev) {
2268 ev = ev.browserEvent || ev;
2269 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2271 if (!y && 0 !== y) {
2272 y = ev.clientY || 0;
2275 y += this.getScroll()[0];
2284 getXY: function(ev) {
2285 ev = ev.browserEvent || ev;
2286 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2287 return [this.getPageX(ev), this.getPageY(ev)];
2291 getRelatedTarget: function(ev) {
2292 ev = ev.browserEvent || ev;
2293 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2294 var t = ev.relatedTarget;
2296 if (ev.type == "mouseout") {
2298 } else if (ev.type == "mouseover") {
2303 return this.resolveTextNode(t);
2307 getTime: function(ev) {
2308 ev = ev.browserEvent || ev;
2309 ev = ev.touches ? (ev.touches[0] || ev.changedTouches[0] || ev ) : ev;
2311 var t = new Date().getTime();
2315 this.lastError = ex;
2324 stopEvent: function(ev) {
2325 this.stopPropagation(ev);
2326 this.preventDefault(ev);
2330 stopPropagation: function(ev) {
2331 ev = ev.browserEvent || ev;
2332 if (ev.stopPropagation) {
2333 ev.stopPropagation();
2335 ev.cancelBubble = true;
2340 preventDefault: function(ev) {
2341 ev = ev.browserEvent || ev;
2342 if(ev.preventDefault) {
2343 ev.preventDefault();
2345 ev.returnValue = false;
2350 getEvent: function(e) {
2351 var ev = e || window.event;
2353 var c = this.getEvent.caller;
2355 ev = c.arguments[0];
2356 if (ev && Event == ev.constructor) {
2366 getCharCode: function(ev) {
2367 ev = ev.browserEvent || ev;
2368 return ev.charCode || ev.keyCode || 0;
2372 _getCacheIndex: function(el, eventName, fn) {
2373 for (var i = 0,len = listeners.length; i < len; ++i) {
2374 var li = listeners[i];
2376 li[this.FN] == fn &&
2377 li[this.EL] == el &&
2378 li[this.TYPE] == eventName) {
2390 getEl: function(id) {
2391 return document.getElementById(id);
2395 clearCache: function() {
2399 _load: function(e) {
2400 loadComplete = true;
2401 var EU = Roo.lib.Event;
2405 EU.doRemove(window, "load", EU._load);
2410 _tryPreloadAttach: function() {
2419 var tryAgain = !loadComplete;
2421 tryAgain = (retryCount > 0);
2426 for (var i = 0,len = onAvailStack.length; i < len; ++i) {
2427 var item = onAvailStack[i];
2429 var el = this.getEl(item.id);
2432 if (!item.checkReady ||
2435 (document && document.body)) {
2438 if (item.override) {
2439 if (item.override === true) {
2442 scope = item.override;
2445 item.fn.call(scope, item.obj);
2446 onAvailStack[i] = null;
2449 notAvail.push(item);
2454 retryCount = (notAvail.length === 0) ? 0 : retryCount - 1;
2458 this.startInterval();
2460 clearInterval(this._interval);
2461 this._interval = null;
2464 this.locked = false;
2471 purgeElement: function(el, recurse, eventName) {
2472 var elListeners = this.getListeners(el, eventName);
2474 for (var i = 0,len = elListeners.length; i < len; ++i) {
2475 var l = elListeners[i];
2476 this.removeListener(el, l.type, l.fn);
2480 if (recurse && el && el.childNodes) {
2481 for (i = 0,len = el.childNodes.length; i < len; ++i) {
2482 this.purgeElement(el.childNodes[i], recurse, eventName);
2488 getListeners: function(el, eventName) {
2489 var results = [], searchLists;
2491 searchLists = [listeners, unloadListeners];
2492 } else if (eventName == "unload") {
2493 searchLists = [unloadListeners];
2495 searchLists = [listeners];
2498 for (var j = 0; j < searchLists.length; ++j) {
2499 var searchList = searchLists[j];
2500 if (searchList && searchList.length > 0) {
2501 for (var i = 0,len = searchList.length; i < len; ++i) {
2502 var l = searchList[i];
2503 if (l && l[this.EL] === el &&
2504 (!eventName || eventName === l[this.TYPE])) {
2509 adjust: l[this.ADJ_SCOPE],
2517 return (results.length) ? results : null;
2521 _unload: function(e) {
2523 var EU = Roo.lib.Event, i, j, l, len, index;
2525 for (i = 0,len = unloadListeners.length; i < len; ++i) {
2526 l = unloadListeners[i];
2529 if (l[EU.ADJ_SCOPE]) {
2530 if (l[EU.ADJ_SCOPE] === true) {
2533 scope = l[EU.ADJ_SCOPE];
2536 l[EU.FN].call(scope, EU.getEvent(e), l[EU.OBJ]);
2537 unloadListeners[i] = null;
2543 unloadListeners = null;
2545 if (listeners && listeners.length > 0) {
2546 j = listeners.length;
2549 l = listeners[index];
2551 EU.removeListener(l[EU.EL], l[EU.TYPE],
2561 EU.doRemove(window, "unload", EU._unload);
2566 getScroll: function() {
2567 var dd = document.documentElement, db = document.body;
2568 if (dd && (dd.scrollTop || dd.scrollLeft)) {
2569 return [dd.scrollTop, dd.scrollLeft];
2571 return [db.scrollTop, db.scrollLeft];
2578 doAdd: function () {
2579 if (window.addEventListener) {
2580 return function(el, eventName, fn, capture) {
2581 el.addEventListener(eventName, fn, (capture));
2583 } else if (window.attachEvent) {
2584 return function(el, eventName, fn, capture) {
2585 el.attachEvent("on" + eventName, fn);
2594 doRemove: function() {
2595 if (window.removeEventListener) {
2596 return function (el, eventName, fn, capture) {
2597 el.removeEventListener(eventName, fn, (capture));
2599 } else if (window.detachEvent) {
2600 return function (el, eventName, fn) {
2601 el.detachEvent("on" + eventName, fn);
2613 var E = Roo.lib.Event;
2614 E.on = E.addListener;
2615 E.un = E.removeListener;
2617 if (document && document.body) {
2620 E.doAdd(window, "load", E._load);
2622 E.doAdd(window, "unload", E._unload);
2623 E._tryPreloadAttach();
2630 * @class Roo.lib.Ajax
2632 * provide a simple Ajax request utility functions
2634 * Portions of this file are based on pieces of Yahoo User Interface Library
2635 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
2636 * YUI licensed under the BSD License:
2637 * http://developer.yahoo.net/yui/license.txt
2638 * <script type="text/javascript">
2646 request : function(method, uri, cb, data, options) {
2648 var hs = options.headers;
2651 if(hs.hasOwnProperty(h)){
2652 this.initHeader(h, hs[h], false);
2656 if(options.xmlData){
2657 this.initHeader('Content-Type', 'text/xml', false);
2659 data = options.xmlData;
2663 return this.asyncRequest(method, uri, cb, data);
2669 * @param {DomForm} form element
2670 * @return {String} urlencode form output.
2672 serializeForm : function(form) {
2673 if(typeof form == 'string') {
2674 form = (document.getElementById(form) || document.forms[form]);
2677 var el, name, val, disabled, data = '', hasSubmit = false;
2678 for (var i = 0; i < form.elements.length; i++) {
2679 el = form.elements[i];
2680 disabled = form.elements[i].disabled;
2681 name = form.elements[i].name;
2682 val = form.elements[i].value;
2684 if (!disabled && name){
2688 case 'select-multiple':
2689 for (var j = 0; j < el.options.length; j++) {
2690 if (el.options[j].selected) {
2692 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(el.options[j].attributes['value'].specified ? el.options[j].value : el.options[j].text) + '&';
2695 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(el.options[j].hasAttribute('value') ? el.options[j].value : el.options[j].text) + '&';
2703 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2716 if(hasSubmit == false) {
2717 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2722 data += Roo.encodeURIComponent(name) + '=' + Roo.encodeURIComponent(val) + '&';
2727 data = data.substr(0, data.length - 1);
2735 useDefaultHeader:true,
2737 defaultPostHeader:'application/x-www-form-urlencoded',
2739 useDefaultXhrHeader:true,
2741 defaultXhrHeader:'XMLHttpRequest',
2743 hasDefaultHeaders:true,
2755 setProgId:function(id)
2757 this.activeX.unshift(id);
2760 setDefaultPostHeader:function(b)
2762 this.useDefaultHeader = b;
2765 setDefaultXhrHeader:function(b)
2767 this.useDefaultXhrHeader = b;
2770 setPollingInterval:function(i)
2772 if (typeof i == 'number' && isFinite(i)) {
2773 this.pollInterval = i;
2777 createXhrObject:function(transactionId)
2783 http = new XMLHttpRequest();
2785 obj = { conn:http, tId:transactionId };
2789 for (var i = 0; i < this.activeX.length; ++i) {
2793 http = new ActiveXObject(this.activeX[i]);
2795 obj = { conn:http, tId:transactionId };
2808 getConnectionObject:function()
2811 var tId = this.transactionId;
2815 o = this.createXhrObject(tId);
2817 this.transactionId++;
2828 asyncRequest:function(method, uri, callback, postData)
2830 var o = this.getConnectionObject();
2836 o.conn.open(method, uri, true);
2838 if (this.useDefaultXhrHeader) {
2839 if (!this.defaultHeaders['X-Requested-With']) {
2840 this.initHeader('X-Requested-With', this.defaultXhrHeader, true);
2844 if(postData && this.useDefaultHeader){
2845 this.initHeader('Content-Type', this.defaultPostHeader);
2848 if (this.hasDefaultHeaders || this.hasHeaders) {
2852 this.handleReadyState(o, callback);
2853 o.conn.send(postData || null);
2859 handleReadyState:function(o, callback)
2863 if (callback && callback.timeout) {
2865 this.timeout[o.tId] = window.setTimeout(function() {
2866 oConn.abort(o, callback, true);
2867 }, callback.timeout);
2870 this.poll[o.tId] = window.setInterval(
2872 if (o.conn && o.conn.readyState == 4) {
2873 window.clearInterval(oConn.poll[o.tId]);
2874 delete oConn.poll[o.tId];
2876 if(callback && callback.timeout) {
2877 window.clearTimeout(oConn.timeout[o.tId]);
2878 delete oConn.timeout[o.tId];
2881 oConn.handleTransactionResponse(o, callback);
2884 , this.pollInterval);
2887 handleTransactionResponse:function(o, callback, isAbort)
2891 this.releaseObject(o);
2895 var httpStatus, responseObject;
2899 if (o.conn.status !== undefined && o.conn.status != 0) {
2900 httpStatus = o.conn.status;
2912 if (httpStatus >= 200 && httpStatus < 300) {
2913 responseObject = this.createResponseObject(o, callback.argument);
2914 if (callback.success) {
2915 if (!callback.scope) {
2916 callback.success(responseObject);
2921 callback.success.apply(callback.scope, [responseObject]);
2926 switch (httpStatus) {
2934 responseObject = this.createExceptionObject(o.tId, callback.argument, (isAbort ? isAbort : false));
2935 if (callback.failure) {
2936 if (!callback.scope) {
2937 callback.failure(responseObject);
2940 callback.failure.apply(callback.scope, [responseObject]);
2945 responseObject = this.createResponseObject(o, callback.argument);
2946 if (callback.failure) {
2947 if (!callback.scope) {
2948 callback.failure(responseObject);
2951 callback.failure.apply(callback.scope, [responseObject]);
2957 this.releaseObject(o);
2958 responseObject = null;
2961 createResponseObject:function(o, callbackArg)
2968 var headerStr = o.conn.getAllResponseHeaders();
2969 var header = headerStr.split('\n');
2970 for (var i = 0; i < header.length; i++) {
2971 var delimitPos = header[i].indexOf(':');
2972 if (delimitPos != -1) {
2973 headerObj[header[i].substring(0, delimitPos)] = header[i].substring(delimitPos + 2);
2981 obj.status = o.conn.status;
2982 obj.statusText = o.conn.statusText;
2983 obj.getResponseHeader = headerObj;
2984 obj.getAllResponseHeaders = headerStr;
2985 obj.responseText = o.conn.responseText;
2986 obj.responseXML = o.conn.responseXML;
2988 if (typeof callbackArg !== undefined) {
2989 obj.argument = callbackArg;
2995 createExceptionObject:function(tId, callbackArg, isAbort)
2998 var COMM_ERROR = 'communication failure';
2999 var ABORT_CODE = -1;
3000 var ABORT_ERROR = 'transaction aborted';
3006 obj.status = ABORT_CODE;
3007 obj.statusText = ABORT_ERROR;
3010 obj.status = COMM_CODE;
3011 obj.statusText = COMM_ERROR;
3015 obj.argument = callbackArg;
3021 initHeader:function(label, value, isDefault)
3023 var headerObj = (isDefault) ? this.defaultHeaders : this.headers;
3025 if (headerObj[label] === undefined) {
3026 headerObj[label] = value;
3031 headerObj[label] = value + "," + headerObj[label];
3035 this.hasDefaultHeaders = true;
3038 this.hasHeaders = true;
3043 setHeader:function(o)
3045 if (this.hasDefaultHeaders) {
3046 for (var prop in this.defaultHeaders) {
3047 if (this.defaultHeaders.hasOwnProperty(prop)) {
3048 o.conn.setRequestHeader(prop, this.defaultHeaders[prop]);
3053 if (this.hasHeaders) {
3054 for (var prop in this.headers) {
3055 if (this.headers.hasOwnProperty(prop)) {
3056 o.conn.setRequestHeader(prop, this.headers[prop]);
3060 this.hasHeaders = false;
3064 resetDefaultHeaders:function() {
3065 delete this.defaultHeaders;
3066 this.defaultHeaders = {};
3067 this.hasDefaultHeaders = false;
3070 abort:function(o, callback, isTimeout)
3072 if(this.isCallInProgress(o)) {
3074 window.clearInterval(this.poll[o.tId]);
3075 delete this.poll[o.tId];
3077 delete this.timeout[o.tId];
3080 this.handleTransactionResponse(o, callback, true);
3090 isCallInProgress:function(o)
3093 return o.conn.readyState != 4 && o.conn.readyState != 0;
3102 releaseObject:function(o)
3111 'MSXML2.XMLHTTP.3.0',
3119 * Portions of this file are based on pieces of Yahoo User Interface Library
3120 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3121 * YUI licensed under the BSD License:
3122 * http://developer.yahoo.net/yui/license.txt
3123 * <script type="text/javascript">
3127 Roo.lib.Region = function(t, r, b, l) {
3137 Roo.lib.Region.prototype = {
3138 contains : function(region) {
3139 return ( region.left >= this.left &&
3140 region.right <= this.right &&
3141 region.top >= this.top &&
3142 region.bottom <= this.bottom );
3146 getArea : function() {
3147 return ( (this.bottom - this.top) * (this.right - this.left) );
3150 intersect : function(region) {
3151 var t = Math.max(this.top, region.top);
3152 var r = Math.min(this.right, region.right);
3153 var b = Math.min(this.bottom, region.bottom);
3154 var l = Math.max(this.left, region.left);
3156 if (b >= t && r >= l) {
3157 return new Roo.lib.Region(t, r, b, l);
3162 union : function(region) {
3163 var t = Math.min(this.top, region.top);
3164 var r = Math.max(this.right, region.right);
3165 var b = Math.max(this.bottom, region.bottom);
3166 var l = Math.min(this.left, region.left);
3168 return new Roo.lib.Region(t, r, b, l);
3171 adjust : function(t, l, b, r) {
3180 Roo.lib.Region.getRegion = function(el) {
3181 var p = Roo.lib.Dom.getXY(el);
3184 var r = p[0] + el.offsetWidth;
3185 var b = p[1] + el.offsetHeight;
3188 return new Roo.lib.Region(t, r, b, l);
3191 * Portions of this file are based on pieces of Yahoo User Interface Library
3192 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3193 * YUI licensed under the BSD License:
3194 * http://developer.yahoo.net/yui/license.txt
3195 * <script type="text/javascript">
3198 //@@dep Roo.lib.Region
3201 Roo.lib.Point = function(x, y) {
3202 if (x instanceof Array) {
3206 this.x = this.right = this.left = this[0] = x;
3207 this.y = this.top = this.bottom = this[1] = y;
3210 Roo.lib.Point.prototype = new Roo.lib.Region();
3212 * Portions of this file are based on pieces of Yahoo User Interface Library
3213 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3214 * YUI licensed under the BSD License:
3215 * http://developer.yahoo.net/yui/license.txt
3216 * <script type="text/javascript">
3223 scroll : function(el, args, duration, easing, cb, scope) {
3224 this.run(el, args, duration, easing, cb, scope, Roo.lib.Scroll);
3227 motion : function(el, args, duration, easing, cb, scope) {
3228 this.run(el, args, duration, easing, cb, scope, Roo.lib.Motion);
3231 color : function(el, args, duration, easing, cb, scope) {
3232 this.run(el, args, duration, easing, cb, scope, Roo.lib.ColorAnim);
3235 run : function(el, args, duration, easing, cb, scope, type) {
3236 type = type || Roo.lib.AnimBase;
3237 if (typeof easing == "string") {
3238 easing = Roo.lib.Easing[easing];
3240 var anim = new type(el, args, duration, easing);
3241 anim.animateX(function() {
3242 Roo.callback(cb, scope);
3248 * Portions of this file are based on pieces of Yahoo User Interface Library
3249 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3250 * YUI licensed under the BSD License:
3251 * http://developer.yahoo.net/yui/license.txt
3252 * <script type="text/javascript">
3260 if (!libFlyweight) {
3261 libFlyweight = new Roo.Element.Flyweight();
3263 libFlyweight.dom = el;
3264 return libFlyweight;
3267 // since this uses fly! - it cant be in DOM (which does not have fly yet..)
3271 Roo.lib.AnimBase = function(el, attributes, duration, method) {
3273 this.init(el, attributes, duration, method);
3277 Roo.lib.AnimBase.fly = fly;
3281 Roo.lib.AnimBase.prototype = {
3283 toString: function() {
3284 var el = this.getEl();
3285 var id = el.id || el.tagName;
3286 return ("Anim " + id);
3290 noNegatives: /width|height|opacity|padding/i,
3291 offsetAttribute: /^((width|height)|(top|left))$/,
3292 defaultUnit: /width|height|top$|bottom$|left$|right$/i,
3293 offsetUnit: /\d+(em|%|en|ex|pt|in|cm|mm|pc)$/i
3297 doMethod: function(attr, start, end) {
3298 return this.method(this.currentFrame, start, end - start, this.totalFrames);
3302 setAttribute: function(attr, val, unit) {
3303 if (this.patterns.noNegatives.test(attr)) {
3304 val = (val > 0) ? val : 0;
3307 Roo.fly(this.getEl(), '_anim').setStyle(attr, val + unit);
3311 getAttribute: function(attr) {
3312 var el = this.getEl();
3313 var val = fly(el).getStyle(attr);
3315 if (val !== 'auto' && !this.patterns.offsetUnit.test(val)) {
3316 return parseFloat(val);
3319 var a = this.patterns.offsetAttribute.exec(attr) || [];
3320 var pos = !!( a[3] );
3321 var box = !!( a[2] );
3324 if (box || (fly(el).getStyle('position') == 'absolute' && pos)) {
3325 val = el['offset' + a[0].charAt(0).toUpperCase() + a[0].substr(1)];
3334 getDefaultUnit: function(attr) {
3335 if (this.patterns.defaultUnit.test(attr)) {
3342 animateX : function(callback, scope) {
3343 var f = function() {
3344 this.onComplete.removeListener(f);
3345 if (typeof callback == "function") {
3346 callback.call(scope || this, this);
3349 this.onComplete.addListener(f, this);
3354 setRuntimeAttribute: function(attr) {
3357 var attributes = this.attributes;
3359 this.runtimeAttributes[attr] = {};
3361 var isset = function(prop) {
3362 return (typeof prop !== 'undefined');
3365 if (!isset(attributes[attr]['to']) && !isset(attributes[attr]['by'])) {
3369 start = ( isset(attributes[attr]['from']) ) ? attributes[attr]['from'] : this.getAttribute(attr);
3372 if (isset(attributes[attr]['to'])) {
3373 end = attributes[attr]['to'];
3374 } else if (isset(attributes[attr]['by'])) {
3375 if (start.constructor == Array) {
3377 for (var i = 0, len = start.length; i < len; ++i) {
3378 end[i] = start[i] + attributes[attr]['by'][i];
3381 end = start + attributes[attr]['by'];
3385 this.runtimeAttributes[attr].start = start;
3386 this.runtimeAttributes[attr].end = end;
3389 this.runtimeAttributes[attr].unit = ( isset(attributes[attr].unit) ) ? attributes[attr]['unit'] : this.getDefaultUnit(attr);
3393 init: function(el, attributes, duration, method) {
3395 var isAnimated = false;
3398 var startTime = null;
3401 var actualFrames = 0;
3404 el = Roo.getDom(el);
3407 this.attributes = attributes || {};
3410 this.duration = duration || 1;
3413 this.method = method || Roo.lib.Easing.easeNone;
3416 this.useSeconds = true;
3419 this.currentFrame = 0;
3422 this.totalFrames = Roo.lib.AnimMgr.fps;
3425 this.getEl = function() {
3430 this.isAnimated = function() {
3435 this.getStartTime = function() {
3439 this.runtimeAttributes = {};
3442 this.animate = function() {
3443 if (this.isAnimated()) {
3447 this.currentFrame = 0;
3449 this.totalFrames = ( this.useSeconds ) ? Math.ceil(Roo.lib.AnimMgr.fps * this.duration) : this.duration;
3451 Roo.lib.AnimMgr.registerElement(this);
3455 this.stop = function(finish) {
3457 this.currentFrame = this.totalFrames;
3458 this._onTween.fire();
3460 Roo.lib.AnimMgr.stop(this);
3463 var onStart = function() {
3464 this.onStart.fire();
3466 this.runtimeAttributes = {};
3467 for (var attr in this.attributes) {
3468 this.setRuntimeAttribute(attr);
3473 startTime = new Date();
3477 var onTween = function() {
3479 duration: new Date() - this.getStartTime(),
3480 currentFrame: this.currentFrame
3483 data.toString = function() {
3485 'duration: ' + data.duration +
3486 ', currentFrame: ' + data.currentFrame
3490 this.onTween.fire(data);
3492 var runtimeAttributes = this.runtimeAttributes;
3494 for (var attr in runtimeAttributes) {
3495 this.setAttribute(attr, this.doMethod(attr, runtimeAttributes[attr].start, runtimeAttributes[attr].end), runtimeAttributes[attr].unit);
3501 var onComplete = function() {
3502 var actual_duration = (new Date() - startTime) / 1000 ;
3505 duration: actual_duration,
3506 frames: actualFrames,
3507 fps: actualFrames / actual_duration
3510 data.toString = function() {
3512 'duration: ' + data.duration +
3513 ', frames: ' + data.frames +
3514 ', fps: ' + data.fps
3520 this.onComplete.fire(data);
3524 this._onStart = new Roo.util.Event(this);
3525 this.onStart = new Roo.util.Event(this);
3526 this.onTween = new Roo.util.Event(this);
3527 this._onTween = new Roo.util.Event(this);
3528 this.onComplete = new Roo.util.Event(this);
3529 this._onComplete = new Roo.util.Event(this);
3530 this._onStart.addListener(onStart);
3531 this._onTween.addListener(onTween);
3532 this._onComplete.addListener(onComplete);
3537 * Portions of this file are based on pieces of Yahoo User Interface Library
3538 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3539 * YUI licensed under the BSD License:
3540 * http://developer.yahoo.net/yui/license.txt
3541 * <script type="text/javascript">
3545 Roo.lib.AnimMgr = new function() {
3562 this.registerElement = function(tween) {
3563 queue[queue.length] = tween;
3565 tween._onStart.fire();
3570 this.unRegister = function(tween, index) {
3571 tween._onComplete.fire();
3572 index = index || getIndex(tween);
3574 queue.splice(index, 1);
3578 if (tweenCount <= 0) {
3584 this.start = function() {
3585 if (thread === null) {
3586 thread = setInterval(this.run, this.delay);
3591 this.stop = function(tween) {
3593 clearInterval(thread);
3595 for (var i = 0, len = queue.length; i < len; ++i) {
3596 if (queue[0].isAnimated()) {
3597 this.unRegister(queue[0], 0);
3606 this.unRegister(tween);
3611 this.run = function() {
3612 for (var i = 0, len = queue.length; i < len; ++i) {
3613 var tween = queue[i];
3614 if (!tween || !tween.isAnimated()) {
3618 if (tween.currentFrame < tween.totalFrames || tween.totalFrames === null)
3620 tween.currentFrame += 1;
3622 if (tween.useSeconds) {
3623 correctFrame(tween);
3625 tween._onTween.fire();
3628 Roo.lib.AnimMgr.stop(tween, i);
3633 var getIndex = function(anim) {
3634 for (var i = 0, len = queue.length; i < len; ++i) {
3635 if (queue[i] == anim) {
3643 var correctFrame = function(tween) {
3644 var frames = tween.totalFrames;
3645 var frame = tween.currentFrame;
3646 var expected = (tween.currentFrame * tween.duration * 1000 / tween.totalFrames);
3647 var elapsed = (new Date() - tween.getStartTime());
3650 if (elapsed < tween.duration * 1000) {
3651 tweak = Math.round((elapsed / expected - 1) * tween.currentFrame);
3653 tweak = frames - (frame + 1);
3655 if (tweak > 0 && isFinite(tweak)) {
3656 if (tween.currentFrame + tweak >= frames) {
3657 tweak = frames - (frame + 1);
3660 tween.currentFrame += tweak;
3666 * Portions of this file are based on pieces of Yahoo User Interface Library
3667 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
3668 * YUI licensed under the BSD License:
3669 * http://developer.yahoo.net/yui/license.txt
3670 * <script type="text/javascript">
3673 Roo.lib.Bezier = new function() {
3675 this.getPosition = function(points, t) {
3676 var n = points.length;
3679 for (var i = 0; i < n; ++i) {
3680 tmp[i] = [points[i][0], points[i][1]];
3683 for (var j = 1; j < n; ++j) {
3684 for (i = 0; i < n - j; ++i) {
3685 tmp[i][0] = (1 - t) * tmp[i][0] + t * tmp[parseInt(i + 1, 10)][0];
3686 tmp[i][1] = (1 - t) * tmp[i][1] + t * tmp[parseInt(i + 1, 10)][1];
3690 return [ tmp[0][0], tmp[0][1] ];
3696 * @class Roo.lib.Color
3698 * An abstract Color implementation. Concrete Color implementations should use
3699 * an instance of this function as their prototype, and implement the getRGB and
3700 * getHSL functions. getRGB should return an object representing the RGB
3701 * components of this Color, with the red, green, and blue components in the
3702 * range [0,255] and the alpha component in the range [0,100]. getHSL should
3703 * return an object representing the HSL components of this Color, with the hue
3704 * component in the range [0,360), the saturation and lightness components in
3705 * the range [0,100], and the alpha component in the range [0,1].
3710 * Functions for Color handling and processing.
3712 * http://www.safalra.com/web-design/javascript/Color-handling-and-processing/
3714 * The author of this program, Safalra (Stephen Morley), irrevocably releases all
3715 * rights to this program, with the intention of it becoming part of the public
3716 * domain. Because this program is released into the public domain, it comes with
3717 * no warranty either expressed or implied, to the extent permitted by law.
3719 * For more free and public domain JavaScript code by the same author, visit:
3720 * http://www.safalra.com/web-design/javascript/
3723 Roo.lib.Color = function() { }
3726 Roo.apply(Roo.lib.Color.prototype, {
3734 * @return {Object} an object representing the RGBA components of this Color. The red,
3735 * green, and blue components are converted to integers in the range [0,255].
3736 * The alpha is a value in the range [0,1].
3738 getIntegerRGB : function(){
3740 // get the RGB components of this Color
3741 var rgb = this.getRGB();
3743 // return the integer components
3745 'r' : Math.round(rgb.r),
3746 'g' : Math.round(rgb.g),
3747 'b' : Math.round(rgb.b),
3755 * @return {Object} an object representing the RGBA components of this Color. The red,
3756 * green, and blue components are converted to numbers in the range [0,100].
3757 * The alpha is a value in the range [0,1].
3759 getPercentageRGB : function(){
3761 // get the RGB components of this Color
3762 var rgb = this.getRGB();
3764 // return the percentage components
3766 'r' : 100 * rgb.r / 255,
3767 'g' : 100 * rgb.g / 255,
3768 'b' : 100 * rgb.b / 255,
3775 * getCSSHexadecimalRGB
3776 * @return {String} a string representing this Color as a CSS hexadecimal RGB Color
3777 * value - that is, a string of the form #RRGGBB where each of RR, GG, and BB
3778 * are two-digit hexadecimal numbers.
3780 getCSSHexadecimalRGB : function()
3783 // get the integer RGB components
3784 var rgb = this.getIntegerRGB();
3786 // determine the hexadecimal equivalents
3787 var r16 = rgb.r.toString(16);
3788 var g16 = rgb.g.toString(16);
3789 var b16 = rgb.b.toString(16);
3791 // return the CSS RGB Color value
3793 + (r16.length == 2 ? r16 : '0' + r16)
3794 + (g16.length == 2 ? g16 : '0' + g16)
3795 + (b16.length == 2 ? b16 : '0' + b16);
3801 * @return {String} a string representing this Color as a CSS integer RGB Color
3802 * value - that is, a string of the form rgb(r,g,b) where each of r, g, and b
3803 * are integers in the range [0,255].
3805 getCSSIntegerRGB : function(){
3807 // get the integer RGB components
3808 var rgb = this.getIntegerRGB();
3810 // return the CSS RGB Color value
3811 return 'rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ')';
3817 * @return {String} Returns a string representing this Color as a CSS integer RGBA Color
3818 * value - that is, a string of the form rgba(r,g,b,a) where each of r, g, and
3819 * b are integers in the range [0,255] and a is in the range [0,1].
3821 getCSSIntegerRGBA : function(){
3823 // get the integer RGB components
3824 var rgb = this.getIntegerRGB();
3826 // return the CSS integer RGBA Color value
3827 return 'rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + rgb.a + ')';
3832 * getCSSPercentageRGB
3833 * @return {String} a string representing this Color as a CSS percentage RGB Color
3834 * value - that is, a string of the form rgb(r%,g%,b%) where each of r, g, and
3835 * b are in the range [0,100].
3837 getCSSPercentageRGB : function(){
3839 // get the percentage RGB components
3840 var rgb = this.getPercentageRGB();
3842 // return the CSS RGB Color value
3843 return 'rgb(' + rgb.r + '%,' + rgb.g + '%,' + rgb.b + '%)';
3848 * getCSSPercentageRGBA
3849 * @return {String} a string representing this Color as a CSS percentage RGBA Color
3850 * value - that is, a string of the form rgba(r%,g%,b%,a) where each of r, g,
3851 * and b are in the range [0,100] and a is in the range [0,1].
3853 getCSSPercentageRGBA : function(){
3855 // get the percentage RGB components
3856 var rgb = this.getPercentageRGB();
3858 // return the CSS percentage RGBA Color value
3859 return 'rgb(' + rgb.r + '%,' + rgb.g + '%,' + rgb.b + '%,' + rgb.a + ')';
3865 * @return {String} a string representing this Color as a CSS HSL Color value - that
3866 * is, a string of the form hsl(h,s%,l%) where h is in the range [0,100] and
3867 * s and l are in the range [0,100].
3869 getCSSHSL : function(){
3871 // get the HSL components
3872 var hsl = this.getHSL();
3874 // return the CSS HSL Color value
3875 return 'hsl(' + hsl.h + ',' + hsl.s + '%,' + hsl.l + '%)';
3881 * @return {String} a string representing this Color as a CSS HSLA Color value - that
3882 * is, a string of the form hsla(h,s%,l%,a) where h is in the range [0,100],
3883 * s and l are in the range [0,100], and a is in the range [0,1].
3885 getCSSHSLA : function(){
3887 // get the HSL components
3888 var hsl = this.getHSL();
3890 // return the CSS HSL Color value
3891 return 'hsl(' + hsl.h + ',' + hsl.s + '%,' + hsl.l + '%,' + hsl.a + ')';
3896 * Sets the Color of the specified node to this Color. This functions sets
3897 * the CSS 'color' property for the node. The parameter is:
3899 * @param {DomElement} node - the node whose Color should be set
3901 setNodeColor : function(node){
3903 // set the Color of the node
3904 node.style.color = this.getCSSHexadecimalRGB();
3909 * Sets the background Color of the specified node to this Color. This
3910 * functions sets the CSS 'background-color' property for the node. The
3913 * @param {DomElement} node - the node whose background Color should be set
3915 setNodeBackgroundColor : function(node){
3917 // set the background Color of the node
3918 node.style.backgroundColor = this.getCSSHexadecimalRGB();
3921 // convert between formats..
3924 var r = this.getIntegerRGB();
3925 return new Roo.lib.RGBColor(r.r,r.g,r.b,r.a);
3930 var hsl = this.getHSL();
3931 // return the CSS HSL Color value
3932 return new Roo.lib.HSLColor(hsl.h, hsl.s, hsl.l , hsl.a );
3938 var rgb = this.toRGB();
3939 var hsv = rgb.getHSV();
3940 // return the CSS HSL Color value
3941 return new Roo.lib.HSVColor(hsv.h, hsv.s, hsv.v , hsv.a );
3945 // modify v = 0 ... 1 (eg. 0.5)
3946 saturate : function(v)
3948 var rgb = this.toRGB();
3949 var hsv = rgb.getHSV();
3950 return new Roo.lib.HSVColor(hsv.h, hsv.s * v, hsv.v , hsv.a );
3958 * @return {Object} the RGB and alpha components of this Color as an object with r,
3959 * g, b, and a properties. r, g, and b are in the range [0,255] and a is in
3964 // return the RGB components
3976 * @return {Object} the HSV and alpha components of this Color as an object with h,
3977 * s, v, and a properties. h is in the range [0,360), s and v are in the range
3978 * [0,100], and a is in the range [0,1].
3983 // calculate the HSV components if necessary
3984 if (this.hsv == null) {
3985 this.calculateHSV();
3988 // return the HSV components
4000 * @return {Object} the HSL and alpha components of this Color as an object with h,
4001 * s, l, and a properties. h is in the range [0,360), s and l are in the range
4002 * [0,100], and a is in the range [0,1].
4004 getHSL : function(){
4007 // calculate the HSV components if necessary
4008 if (this.hsl == null) { this.calculateHSL(); }
4010 // return the HSL components
4025 * @class Roo.lib.RGBColor
4026 * @extends Roo.lib.Color
4027 * Creates a Color specified in the RGB Color space, with an optional alpha
4028 * component. The parameters are:
4032 * @param {Number} r - the red component, clipped to the range [0,255]
4033 * @param {Number} g - the green component, clipped to the range [0,255]
4034 * @param {Number} b - the blue component, clipped to the range [0,255]
4035 * @param {Number} a - the alpha component, clipped to the range [0,1] - this parameter is
4036 * optional and defaults to 1
4038 Roo.lib.RGBColor = function (r, g, b, a){
4040 // store the alpha component after clipping it if necessary
4041 this.alpha = (a === undefined ? 1 : Math.max(0, Math.min(1, a)));
4043 // store the RGB components after clipping them if necessary
4046 'r' : Math.max(0, Math.min(255, r)),
4047 'g' : Math.max(0, Math.min(255, g)),
4048 'b' : Math.max(0, Math.min(255, b))
4051 // initialise the HSV and HSL components to null
4055 * //private returns the HSV or HSL hue component of this RGBColor. The hue is in the
4056 * range [0,360). The parameters are:
4058 * maximum - the maximum of the RGB component values
4059 * range - the range of the RGB component values
4064 // this does an 'exteds'
4065 Roo.extend(Roo.lib.RGBColor, Roo.lib.Color, {
4068 getHue : function(maximum, range)
4072 // check whether the range is zero
4075 // set the hue to zero (any hue is acceptable as the Color is grey)
4080 // determine which of the components has the highest value and set the hue
4083 // red has the highest value
4085 var hue = (rgb.g - rgb.b) / range * 60;
4086 if (hue < 0) { hue += 360; }
4089 // green has the highest value
4091 var hue = (rgb.b - rgb.r) / range * 60 + 120;
4094 // blue has the highest value
4096 var hue = (rgb.r - rgb.g) / range * 60 + 240;
4108 /* //private Calculates and stores the HSV components of this RGBColor so that they can
4109 * be returned be the getHSV function.
4111 calculateHSV : function(){
4113 // get the maximum and range of the RGB component values
4114 var maximum = Math.max(rgb.r, rgb.g, rgb.b);
4115 var range = maximum - Math.min(rgb.r, rgb.g, rgb.b);
4117 // store the HSV components
4120 'h' : this.getHue(maximum, range),
4121 's' : (maximum == 0 ? 0 : 100 * range / maximum),
4122 'v' : maximum / 2.55
4127 /* //private Calculates and stores the HSL components of this RGBColor so that they can
4128 * be returned be the getHSL function.
4130 calculateHSL : function(){
4132 // get the maximum and range of the RGB component values
4133 var maximum = Math.max(rgb.r, rgb.g, rgb.b);
4134 var range = maximum - Math.min(rgb.r, rgb.g, rgb.b);
4136 // determine the lightness in the range [0,1]
4137 var l = maximum / 255 - range / 510;
4139 // store the HSL components
4142 'h' : this.getHue(maximum, range),
4143 's' : (range == 0 ? 0 : range / 2.55 / (l < 0.5 ? l * 2 : 2 - l * 2)),
4152 * @class Roo.lib.HSVColor
4153 * @extends Roo.lib.Color
4154 * Creates a Color specified in the HSV Color space, with an optional alpha
4155 * component. The parameters are:
4158 * @param {Number} h - the hue component, wrapped to the range [0,360)
4159 * @param {Number} s - the saturation component, clipped to the range [0,100]
4160 * @param {Number} v - the value component, clipped to the range [0,100]
4161 * @param {Number} a - the alpha component, clipped to the range [0,1] - this parameter is
4162 * optional and defaults to 1
4164 Roo.lib.HSVColor = function (h, s, v, a){
4166 // store the alpha component after clipping it if necessary
4167 this.alpha = (a === undefined ? 1 : Math.max(0, Math.min(1, a)));
4169 // store the HSV components after clipping or wrapping them if necessary
4172 'h' : (h % 360 + 360) % 360,
4173 's' : Math.max(0, Math.min(100, s)),
4174 'v' : Math.max(0, Math.min(100, v))
4177 // initialise the RGB and HSL components to null
4182 Roo.extend(Roo.lib.HSVColor, Roo.lib.Color, {
4183 /* Calculates and stores the RGB components of this HSVColor so that they can
4184 * be returned be the getRGB function.
4186 calculateRGB: function ()
4189 // check whether the saturation is zero
4192 // set the Color to the appropriate shade of grey
4199 // set some temporary values
4200 var f = hsv.h / 60 - Math.floor(hsv.h / 60);
4201 var p = hsv.v * (1 - hsv.s / 100);
4202 var q = hsv.v * (1 - hsv.s / 100 * f);
4203 var t = hsv.v * (1 - hsv.s / 100 * (1 - f));
4205 // set the RGB Color components to their temporary values
4206 switch (Math.floor(hsv.h / 60)){
4207 case 0: var r = hsv.v; var g = t; var b = p; break;
4208 case 1: var r = q; var g = hsv.v; var b = p; break;
4209 case 2: var r = p; var g = hsv.v; var b = t; break;
4210 case 3: var r = p; var g = q; var b = hsv.v; break;
4211 case 4: var r = t; var g = p; var b = hsv.v; break;
4212 case 5: var r = hsv.v; var g = p; var b = q; break;
4217 // store the RGB components
4227 /* Calculates and stores the HSL components of this HSVColor so that they can
4228 * be returned be the getHSL function.
4230 calculateHSL : function (){
4233 // determine the lightness in the range [0,100]
4234 var l = (2 - hsv.s / 100) * hsv.v / 2;
4236 // store the HSL components
4240 's' : hsv.s * hsv.v / (l < 50 ? l * 2 : 200 - l * 2),
4244 // correct a division-by-zero error
4245 if (isNaN(hsl.s)) { hsl.s = 0; }
4254 * @class Roo.lib.HSLColor
4255 * @extends Roo.lib.Color
4258 * Creates a Color specified in the HSL Color space, with an optional alpha
4259 * component. The parameters are:
4261 * @param {Number} h - the hue component, wrapped to the range [0,360)
4262 * @param {Number} s - the saturation component, clipped to the range [0,100]
4263 * @param {Number} l - the lightness component, clipped to the range [0,100]
4264 * @param {Number} a - the alpha component, clipped to the range [0,1] - this parameter is
4265 * optional and defaults to 1
4268 Roo.lib.HSLColor = function(h, s, l, a){
4270 // store the alpha component after clipping it if necessary
4271 this.alpha = (a === undefined ? 1 : Math.max(0, Math.min(1, a)));
4273 // store the HSL components after clipping or wrapping them if necessary
4276 'h' : (h % 360 + 360) % 360,
4277 's' : Math.max(0, Math.min(100, s)),
4278 'l' : Math.max(0, Math.min(100, l))
4281 // initialise the RGB and HSV components to null
4284 Roo.extend(Roo.lib.HSLColor, Roo.lib.Color, {
4286 /* Calculates and stores the RGB components of this HSLColor so that they can
4287 * be returned be the getRGB function.
4289 calculateRGB: function (){
4291 // check whether the saturation is zero
4292 if (this.hsl.s == 0){
4294 // store the RGB components representing the appropriate shade of grey
4297 'r' : this.hsl.l * 2.55,
4298 'g' : this.hsl.l * 2.55,
4299 'b' : this.hsl.l * 2.55
4304 // set some temporary values
4305 var p = this.hsl.l < 50
4306 ? this.hsl.l * (1 + hsl.s / 100)
4307 : this.hsl.l + hsl.s - hsl.l * hsl.s / 100;
4308 var q = 2 * hsl.l - p;
4310 // initialise the RGB components
4313 'r' : (h + 120) / 60 % 6,
4315 'b' : (h + 240) / 60 % 6
4318 // loop over the RGB components
4319 for (var key in this.rgb){
4321 // ensure that the property is not inherited from the root object
4322 if (this.rgb.hasOwnProperty(key)){
4324 // set the component to its value in the range [0,100]
4325 if (this.rgb[key] < 1){
4326 this.rgb[key] = q + (p - q) * this.rgb[key];
4327 }else if (this.rgb[key] < 3){
4329 }else if (this.rgb[key] < 4){
4330 this.rgb[key] = q + (p - q) * (4 - this.rgb[key]);
4335 // set the component to its value in the range [0,255]
4336 this.rgb[key] *= 2.55;
4346 /* Calculates and stores the HSV components of this HSLColor so that they can
4347 * be returned be the getHSL function.
4349 calculateHSV : function(){
4351 // set a temporary value
4352 var t = this.hsl.s * (this.hsl.l < 50 ? this.hsl.l : 100 - this.hsl.l) / 100;
4354 // store the HSV components
4358 's' : 200 * t / (this.hsl.l + t),
4359 'v' : t + this.hsl.l
4362 // correct a division-by-zero error
4363 if (isNaN(this.hsv.s)) { this.hsv.s = 0; }
4370 * Portions of this file are based on pieces of Yahoo User Interface Library
4371 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
4372 * YUI licensed under the BSD License:
4373 * http://developer.yahoo.net/yui/license.txt
4374 * <script type="text/javascript">
4379 Roo.lib.ColorAnim = function(el, attributes, duration, method) {
4380 Roo.lib.ColorAnim.superclass.constructor.call(this, el, attributes, duration, method);
4383 Roo.extend(Roo.lib.ColorAnim, Roo.lib.AnimBase);
4385 var fly = Roo.lib.AnimBase.fly;
4387 var superclass = Y.ColorAnim.superclass;
4388 var proto = Y.ColorAnim.prototype;
4390 proto.toString = function() {
4391 var el = this.getEl();
4392 var id = el.id || el.tagName;
4393 return ("ColorAnim " + id);
4396 proto.patterns.color = /color$/i;
4397 proto.patterns.rgb = /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i;
4398 proto.patterns.hex = /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i;
4399 proto.patterns.hex3 = /^#?([0-9A-F]{1})([0-9A-F]{1})([0-9A-F]{1})$/i;
4400 proto.patterns.transparent = /^transparent|rgba\(0, 0, 0, 0\)$/;
4403 proto.parseColor = function(s) {
4404 if (s.length == 3) {
4408 var c = this.patterns.hex.exec(s);
4409 if (c && c.length == 4) {
4410 return [ parseInt(c[1], 16), parseInt(c[2], 16), parseInt(c[3], 16) ];
4413 c = this.patterns.rgb.exec(s);
4414 if (c && c.length == 4) {
4415 return [ parseInt(c[1], 10), parseInt(c[2], 10), parseInt(c[3], 10) ];
4418 c = this.patterns.hex3.exec(s);
4419 if (c && c.length == 4) {
4420 return [ parseInt(c[1] + c[1], 16), parseInt(c[2] + c[2], 16), parseInt(c[3] + c[3], 16) ];
4425 // since this uses fly! - it cant be in ColorAnim (which does not have fly yet..)
4426 proto.getAttribute = function(attr) {
4427 var el = this.getEl();
4428 if (this.patterns.color.test(attr)) {
4429 var val = fly(el).getStyle(attr);
4431 if (this.patterns.transparent.test(val)) {
4432 var parent = el.parentNode;
4433 val = fly(parent).getStyle(attr);
4435 while (parent && this.patterns.transparent.test(val)) {
4436 parent = parent.parentNode;
4437 val = fly(parent).getStyle(attr);
4438 if (parent.tagName.toUpperCase() == 'HTML') {
4444 val = superclass.getAttribute.call(this, attr);
4449 proto.getAttribute = function(attr) {
4450 var el = this.getEl();
4451 if (this.patterns.color.test(attr)) {
4452 var val = fly(el).getStyle(attr);
4454 if (this.patterns.transparent.test(val)) {
4455 var parent = el.parentNode;
4456 val = fly(parent).getStyle(attr);
4458 while (parent && this.patterns.transparent.test(val)) {
4459 parent = parent.parentNode;
4460 val = fly(parent).getStyle(attr);
4461 if (parent.tagName.toUpperCase() == 'HTML') {
4467 val = superclass.getAttribute.call(this, attr);
4473 proto.doMethod = function(attr, start, end) {
4476 if (this.patterns.color.test(attr)) {
4478 for (var i = 0, len = start.length; i < len; ++i) {
4479 val[i] = superclass.doMethod.call(this, attr, start[i], end[i]);
4482 val = 'rgb(' + Math.floor(val[0]) + ',' + Math.floor(val[1]) + ',' + Math.floor(val[2]) + ')';
4485 val = superclass.doMethod.call(this, attr, start, end);
4491 proto.setRuntimeAttribute = function(attr) {
4492 superclass.setRuntimeAttribute.call(this, attr);
4494 if (this.patterns.color.test(attr)) {
4495 var attributes = this.attributes;
4496 var start = this.parseColor(this.runtimeAttributes[attr].start);
4497 var end = this.parseColor(this.runtimeAttributes[attr].end);
4499 if (typeof attributes[attr]['to'] === 'undefined' && typeof attributes[attr]['by'] !== 'undefined') {
4500 end = this.parseColor(attributes[attr].by);
4502 for (var i = 0, len = start.length; i < len; ++i) {
4503 end[i] = start[i] + end[i];
4507 this.runtimeAttributes[attr].start = start;
4508 this.runtimeAttributes[attr].end = end;
4514 * Portions of this file are based on pieces of Yahoo User Interface Library
4515 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
4516 * YUI licensed under the BSD License:
4517 * http://developer.yahoo.net/yui/license.txt
4518 * <script type="text/javascript">
4524 easeNone: function (t, b, c, d) {
4525 return c * t / d + b;
4529 easeIn: function (t, b, c, d) {
4530 return c * (t /= d) * t + b;
4534 easeOut: function (t, b, c, d) {
4535 return -c * (t /= d) * (t - 2) + b;
4539 easeBoth: function (t, b, c, d) {
4540 if ((t /= d / 2) < 1) {
4541 return c / 2 * t * t + b;
4544 return -c / 2 * ((--t) * (t - 2) - 1) + b;
4548 easeInStrong: function (t, b, c, d) {
4549 return c * (t /= d) * t * t * t + b;
4553 easeOutStrong: function (t, b, c, d) {
4554 return -c * ((t = t / d - 1) * t * t * t - 1) + b;
4558 easeBothStrong: function (t, b, c, d) {
4559 if ((t /= d / 2) < 1) {
4560 return c / 2 * t * t * t * t + b;
4563 return -c / 2 * ((t -= 2) * t * t * t - 2) + b;
4568 elasticIn: function (t, b, c, d, a, p) {
4572 if ((t /= d) == 1) {
4579 if (!a || a < Math.abs(c)) {
4584 var s = p / (2 * Math.PI) * Math.asin(c / a);
4587 return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
4591 elasticOut: function (t, b, c, d, a, p) {
4595 if ((t /= d) == 1) {
4602 if (!a || a < Math.abs(c)) {
4607 var s = p / (2 * Math.PI) * Math.asin(c / a);
4610 return a * Math.pow(2, -10 * t) * Math.sin((t * d - s) * (2 * Math.PI) / p) + c + b;
4614 elasticBoth: function (t, b, c, d, a, p) {
4619 if ((t /= d / 2) == 2) {
4627 if (!a || a < Math.abs(c)) {
4632 var s = p / (2 * Math.PI) * Math.asin(c / a);
4636 return -.5 * (a * Math.pow(2, 10 * (t -= 1)) *
4637 Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
4639 return a * Math.pow(2, -10 * (t -= 1)) *
4640 Math.sin((t * d - s) * (2 * Math.PI) / p) * .5 + c + b;
4645 backIn: function (t, b, c, d, s) {
4646 if (typeof s == 'undefined') {
4649 return c * (t /= d) * t * ((s + 1) * t - s) + b;
4653 backOut: function (t, b, c, d, s) {
4654 if (typeof s == 'undefined') {
4657 return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
4661 backBoth: function (t, b, c, d, s) {
4662 if (typeof s == 'undefined') {
4666 if ((t /= d / 2 ) < 1) {
4667 return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b;
4669 return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;
4673 bounceIn: function (t, b, c, d) {
4674 return c - Roo.lib.Easing.bounceOut(d - t, 0, c, d) + b;
4678 bounceOut: function (t, b, c, d) {
4679 if ((t /= d) < (1 / 2.75)) {
4680 return c * (7.5625 * t * t) + b;
4681 } else if (t < (2 / 2.75)) {
4682 return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b;
4683 } else if (t < (2.5 / 2.75)) {
4684 return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b;
4686 return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b;
4690 bounceBoth: function (t, b, c, d) {
4692 return Roo.lib.Easing.bounceIn(t * 2, 0, c, d) * .5 + b;
4694 return Roo.lib.Easing.bounceOut(t * 2 - d, 0, c, d) * .5 + c * .5 + b;
4697 * Portions of this file are based on pieces of Yahoo User Interface Library
4698 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
4699 * YUI licensed under the BSD License:
4700 * http://developer.yahoo.net/yui/license.txt
4701 * <script type="text/javascript">
4705 Roo.lib.Motion = function(el, attributes, duration, method) {
4707 Roo.lib.Motion.superclass.constructor.call(this, el, attributes, duration, method);
4711 Roo.extend(Roo.lib.Motion, Roo.lib.ColorAnim);
4715 var superclass = Y.Motion.superclass;
4716 var proto = Y.Motion.prototype;
4718 proto.toString = function() {
4719 var el = this.getEl();
4720 var id = el.id || el.tagName;
4721 return ("Motion " + id);
4724 proto.patterns.points = /^points$/i;
4726 proto.setAttribute = function(attr, val, unit) {
4727 if (this.patterns.points.test(attr)) {
4728 unit = unit || 'px';
4729 superclass.setAttribute.call(this, 'left', val[0], unit);
4730 superclass.setAttribute.call(this, 'top', val[1], unit);
4732 superclass.setAttribute.call(this, attr, val, unit);
4736 proto.getAttribute = function(attr) {
4737 if (this.patterns.points.test(attr)) {
4739 superclass.getAttribute.call(this, 'left'),
4740 superclass.getAttribute.call(this, 'top')
4743 val = superclass.getAttribute.call(this, attr);
4749 proto.doMethod = function(attr, start, end) {
4752 if (this.patterns.points.test(attr)) {
4753 var t = this.method(this.currentFrame, 0, 100, this.totalFrames) / 100;
4754 val = Y.Bezier.getPosition(this.runtimeAttributes[attr], t);
4756 val = superclass.doMethod.call(this, attr, start, end);
4761 proto.setRuntimeAttribute = function(attr) {
4762 if (this.patterns.points.test(attr)) {
4763 var el = this.getEl();
4764 var attributes = this.attributes;
4766 var control = attributes['points']['control'] || [];
4770 if (control.length > 0 && !(control[0] instanceof Array)) {
4771 control = [control];
4774 for (i = 0,len = control.length; i < len; ++i) {
4775 tmp[i] = control[i];
4780 Roo.fly(el).position();
4782 if (isset(attributes['points']['from'])) {
4783 Roo.lib.Dom.setXY(el, attributes['points']['from']);
4786 Roo.lib.Dom.setXY(el, Roo.lib.Dom.getXY(el));
4789 start = this.getAttribute('points');
4792 if (isset(attributes['points']['to'])) {
4793 end = translateValues.call(this, attributes['points']['to'], start);
4795 var pageXY = Roo.lib.Dom.getXY(this.getEl());
4796 for (i = 0,len = control.length; i < len; ++i) {
4797 control[i] = translateValues.call(this, control[i], start);
4801 } else if (isset(attributes['points']['by'])) {
4802 end = [ start[0] + attributes['points']['by'][0], start[1] + attributes['points']['by'][1] ];
4804 for (i = 0,len = control.length; i < len; ++i) {
4805 control[i] = [ start[0] + control[i][0], start[1] + control[i][1] ];
4809 this.runtimeAttributes[attr] = [start];
4811 if (control.length > 0) {
4812 this.runtimeAttributes[attr] = this.runtimeAttributes[attr].concat(control);
4815 this.runtimeAttributes[attr][this.runtimeAttributes[attr].length] = end;
4818 superclass.setRuntimeAttribute.call(this, attr);
4822 var translateValues = function(val, start) {
4823 var pageXY = Roo.lib.Dom.getXY(this.getEl());
4824 val = [ val[0] - pageXY[0] + start[0], val[1] - pageXY[1] + start[1] ];
4829 var isset = function(prop) {
4830 return (typeof prop !== 'undefined');
4834 * Portions of this file are based on pieces of Yahoo User Interface Library
4835 * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
4836 * YUI licensed under the BSD License:
4837 * http://developer.yahoo.net/yui/license.txt
4838 * <script type="text/javascript">
4842 Roo.lib.Scroll = function(el, attributes, duration, method) {
4844 Roo.lib.Scroll.superclass.constructor.call(this, el, attributes, duration, method);
4848 Roo.extend(Roo.lib.Scroll, Roo.lib.ColorAnim);
4852 var superclass = Y.Scroll.superclass;
4853 var proto = Y.Scroll.prototype;
4855 proto.toString = function() {
4856 var el = this.getEl();
4857 var id = el.id || el.tagName;
4858 return ("Scroll " + id);
4861 proto.doMethod = function(attr, start, end) {
4864 if (attr == 'scroll') {
4866 this.method(this.currentFrame, start[0], end[0] - start[0], this.totalFrames),
4867 this.method(this.currentFrame, start[1], end[1] - start[1], this.totalFrames)
4871 val = superclass.doMethod.call(this, attr, start, end);
4876 proto.getAttribute = function(attr) {
4878 var el = this.getEl();
4880 if (attr == 'scroll') {
4881 val = [ el.scrollLeft, el.scrollTop ];
4883 val = superclass.getAttribute.call(this, attr);
4889 proto.setAttribute = function(attr, val, unit) {
4890 var el = this.getEl();
4892 if (attr == 'scroll') {
4893 el.scrollLeft = val[0];
4894 el.scrollTop = val[1];
4896 superclass.setAttribute.call(this, attr, val, unit);
4901 * Originally based of this code... - refactored for Roo...
4902 * https://github.com/aaalsaleh/undo-manager
4905 * @author Abdulrahman Alsaleh
4906 * @copyright 2015 Abdulrahman Alsaleh
4907 * @license MIT License (c)
4909 * Hackily modifyed by alan@roojs.com
4914 * TOTALLY UNTESTED...
4916 * Documentation to be done....
4921 * @class Roo.lib.UndoManager
4922 * An undo manager implementation in JavaScript. It follows the W3C UndoManager and DOM Transaction
4923 * Draft and the undocumented and disabled Mozilla Firefox's UndoManager implementation.
4929 editor.undoManager = new Roo.lib.UndoManager(1000, editor);
4933 * For more information see this blog post with examples:
4934 * <a href="http://www.cnitblog.com/seeyeah/archive/2011/12/30/38728.html/">DomHelper
4935 - Create Elements using DOM, HTML fragments and Templates</a>.
4937 * @param {Number} limit how far back to go ... use 1000?
4938 * @param {Object} scope usually use document..
4941 Roo.lib.UndoManager = function (limit, undoScopeHost)
4945 this.scope = undoScopeHost;
4946 this.fireEvent = typeof CustomEvent != 'undefined' && undoScopeHost && undoScopeHost.dispatchEvent;
4947 if (this.fireEvent) {
4954 Roo.lib.UndoManager.prototype = {
4965 * To push and execute a transaction, the method undoManager.transact
4966 * must be called by passing a transaction object as the first argument, and a merge
4967 * flag as the second argument. A transaction object has the following properties:
4971 undoManager.transact({
4973 execute: function() { ... },
4974 undo: function() { ... },
4975 // redo same as execute
4976 redo: function() { this.execute(); }
4979 // merge transaction
4980 undoManager.transact({
4982 execute: function() { ... }, // this will be run...
4983 undo: function() { ... }, // what to do when undo is run.
4984 // redo same as execute
4985 redo: function() { this.execute(); }
4990 * @param {Object} transaction The transaction to add to the stack.
4991 * @return {String} The HTML fragment
4995 transact : function (transaction, merge)
4997 if (arguments.length < 2) {
4998 throw new TypeError('Not enough arguments to UndoManager.transact.');
5001 transaction.execute();
5003 this.stack.splice(0, this.position);
5004 if (merge && this.length) {
5005 this.stack[0].push(transaction);
5007 this.stack.unshift([transaction]);
5012 if (this.limit && this.stack.length > this.limit) {
5013 this.length = this.stack.length = this.limit;
5015 this.length = this.stack.length;
5018 if (this.fireEvent) {
5019 this.scope.dispatchEvent(
5020 new CustomEvent('DOMTransaction', {
5022 transactions: this.stack[0].slice()
5030 Roo.log("transaction: pos:" + this.position + " len: " + this.length + " slen:" + this.stack.length);
5037 Roo.log("undo: pos:" + this.position + " len: " + this.length + " slen:" + this.stack.length);
5039 if (this.position < this.length) {
5040 for (var i = this.stack[this.position].length - 1; i >= 0; i--) {
5041 this.stack[this.position][i].undo();
5045 if (this.fireEvent) {
5046 this.scope.dispatchEvent(
5047 new CustomEvent('undo', {
5049 transactions: this.stack[this.position - 1].slice()
5061 if (this.position > 0) {
5062 for (var i = 0, n = this.stack[this.position - 1].length; i < n; i++) {
5063 this.stack[this.position - 1][i].redo();
5067 if (this.fireEvent) {
5068 this.scope.dispatchEvent(
5069 new CustomEvent('redo', {
5071 transactions: this.stack[this.position].slice()
5081 item : function (index)
5083 if (index >= 0 && index < this.length) {
5084 return this.stack[index].slice();
5089 clearUndo : function () {
5090 this.stack.length = this.length = this.position;
5093 clearRedo : function () {
5094 this.stack.splice(0, this.position);
5096 this.length = this.stack.length;
5099 * Reset the undo - probaly done on load to clear all history.
5106 this.current_html = this.scope.innerHTML;
5107 if (this.timer !== false) {
5108 clearTimeout(this.timer);
5120 // this will handle the undo/redo on the element.?
5121 bindEvents : function()
5123 var el = this.scope;
5124 el.undoManager = this;
5127 this.scope.addEventListener('keydown', function(e) {
5128 if ((e.ctrlKey || e.metaKey) && e.keyCode === 90) {
5130 el.undoManager.redo(); // Ctrl/Command + Shift + Z
5132 el.undoManager.undo(); // Ctrl/Command + Z
5139 this.scope.addEventListener('keyup', function(e) {
5140 if ((e.ctrlKey || e.metaKey) && e.keyCode === 90) {
5149 el.addEventListener('input', function(e) {
5150 if(el.innerHTML == t.current_html) {
5153 // only record events every second.
5154 if (t.timer !== false) {
5155 clearTimeout(t.timer);
5158 t.timer = setTimeout(function() { t.merge = false; }, 1000);
5160 t.addEvent(t.merge);
5161 t.merge = true; // ignore changes happening every second..
5165 * Manually add an event.
5166 * Normall called without arguements - and it will just get added to the stack.
5170 addEvent : function(merge)
5172 Roo.log("undomanager +" + (merge ? 'Y':'n'));
5173 // not sure if this should clear the timer
5174 merge = typeof(merge) == 'undefined' ? false : merge;
5176 this.scope.undoManager.transact({
5178 oldHTML: this.current_html,
5179 newHTML: this.scope.innerHTML,
5180 // nothing to execute (content already changed when input is fired)
5181 execute: function() { },
5183 this.scope.innerHTML = this.current_html = this.oldHTML;
5186 this.scope.innerHTML = this.current_html = this.newHTML;
5188 }, false); //merge);
5192 this.current_html = this.scope.innerHTML;
5203 * Ext JS Library 1.1.1
5204 * Copyright(c) 2006-2007, Ext JS, LLC.
5206 * Originally Released Under LGPL - original licence link has changed is not relivant.
5209 * <script type="text/javascript">
5213 // nasty IE9 hack - what a pile of crap that is..
5215 if (typeof Range != "undefined" && typeof Range.prototype.createContextualFragment == "undefined") {
5216 Range.prototype.createContextualFragment = function (html) {
5217 var doc = window.document;
5218 var container = doc.createElement("div");
5219 container.innerHTML = html;
5220 var frag = doc.createDocumentFragment(), n;
5221 while ((n = container.firstChild)) {
5222 frag.appendChild(n);
5229 * @class Roo.DomHelper
5230 * Utility class for working with DOM and/or Templates. It transparently supports using HTML fragments or DOM.
5231 * 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>.
5234 Roo.DomHelper = function(){
5235 var tempTableEl = null;
5236 var emptyTags = /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i;
5237 var tableRe = /^table|tbody|tr|td$/i;
5239 // build as innerHTML where available
5241 var createHtml = function(o){
5242 if(typeof o == 'string'){
5251 if(attr == "tag" || attr == "children" || attr == "cn" || attr == "html" || typeof o[attr] == "function") { continue; }
5252 if(attr == "style"){
5254 if(typeof s == "function"){
5257 if(typeof s == "string"){
5258 b += ' style="' + s + '"';
5259 }else if(typeof s == "object"){
5262 if(typeof s[key] != "function"){
5263 b += key + ":" + s[key] + ";";
5270 b += ' class="' + o["cls"] + '"';
5271 }else if(attr == "htmlFor"){
5272 b += ' for="' + o["htmlFor"] + '"';
5274 b += " " + attr + '="' + o[attr] + '"';
5278 if(emptyTags.test(o.tag)){
5282 var cn = o.children || o.cn;
5284 //http://bugs.kde.org/show_bug.cgi?id=71506
5285 if((cn instanceof Array) || (Roo.isSafari && typeof(cn.join) == "function")){
5286 for(var i = 0, len = cn.length; i < len; i++) {
5287 b += createHtml(cn[i], b);
5290 b += createHtml(cn, b);
5296 b += "</" + o.tag + ">";
5303 var createDom = function(o, parentNode){
5305 // defininition craeted..
5307 if (o.ns && o.ns != 'html') {
5309 if (o.xmlns && typeof(xmlns[o.ns]) == 'undefined') {
5310 xmlns[o.ns] = o.xmlns;
5313 if (typeof(xmlns[o.ns]) == 'undefined') {
5314 console.log("Trying to create namespace element " + o.ns + ", however no xmlns was sent to builder previously");
5320 if (typeof(o) == 'string') {
5321 return parentNode.appendChild(document.createTextNode(o));
5323 o.tag = o.tag || div;
5324 if (o.ns && Roo.isIE) {
5326 o.tag = o.ns + ':' + o.tag;
5329 var el = ns ? document.createElementNS( ns, o.tag||'div') : document.createElement(o.tag||'div');
5330 var useSet = el.setAttribute ? true : false; // In IE some elements don't have setAttribute
5333 if(attr == "tag" || attr == "ns" ||attr == "xmlns" ||attr == "children" || attr == "cn" || attr == "html" ||
5334 attr == "style" || typeof o[attr] == "function") { continue; }
5336 if(attr=="cls" && Roo.isIE){
5337 el.className = o["cls"];
5339 if(useSet) { el.setAttribute(attr=="cls" ? 'class' : attr, o[attr]);}
5345 Roo.DomHelper.applyStyles(el, o.style);
5346 var cn = o.children || o.cn;
5348 //http://bugs.kde.org/show_bug.cgi?id=71506
5349 if((cn instanceof Array) || (Roo.isSafari && typeof(cn.join) == "function")){
5350 for(var i = 0, len = cn.length; i < len; i++) {
5351 createDom(cn[i], el);
5358 el.innerHTML = o.html;
5361 parentNode.appendChild(el);
5366 var ieTable = function(depth, s, h, e){
5367 tempTableEl.innerHTML = [s, h, e].join('');
5368 var i = -1, el = tempTableEl;
5369 while(++i < depth && el.firstChild){
5375 // kill repeat to save bytes
5379 tbe = '</tbody>'+te,
5385 * Nasty code for IE's broken table implementation
5387 var insertIntoTable = function(tag, where, el, html){
5389 tempTableEl = document.createElement('div');
5394 if(where == 'afterbegin' || where == 'beforeend'){ // INTO a TD
5397 if(where == 'beforebegin'){
5401 before = el.nextSibling;
5404 node = ieTable(4, trs, html, tre);
5406 else if(tag == 'tr'){
5407 if(where == 'beforebegin'){
5410 node = ieTable(3, tbs, html, tbe);
5411 } else if(where == 'afterend'){
5412 before = el.nextSibling;
5414 node = ieTable(3, tbs, html, tbe);
5415 } else{ // INTO a TR
5416 if(where == 'afterbegin'){
5417 before = el.firstChild;
5419 node = ieTable(4, trs, html, tre);
5421 } else if(tag == 'tbody'){
5422 if(where == 'beforebegin'){
5425 node = ieTable(2, ts, html, te);
5426 } else if(where == 'afterend'){
5427 before = el.nextSibling;
5429 node = ieTable(2, ts, html, te);
5431 if(where == 'afterbegin'){
5432 before = el.firstChild;
5434 node = ieTable(3, tbs, html, tbe);
5437 if(where == 'beforebegin' || where == 'afterend'){ // OUTSIDE the table
5440 if(where == 'afterbegin'){
5441 before = el.firstChild;
5443 node = ieTable(2, ts, html, te);
5445 el.insertBefore(node, before);
5449 // this is a bit like the react update code...
5452 var updateNode = function(from, to)
5454 // should we handle non-standard elements?
5455 Roo.log(["UpdateNode" , from, to]);
5456 if (from.nodeType != to.nodeType) {
5457 Roo.log(["ReplaceChild - mismatch notType" , to, from ]);
5458 from.parentNode.replaceChild(to, from);
5461 if (from.nodeType == 3) {
5462 // assume it's text?!
5463 if (from.data == to.data) {
5466 from.data = to.data;
5470 // assume 'to' doesnt have '1/3 nodetypes!
5471 if (from.nodeType !=1 || from.tagName != to.tagName) {
5472 Roo.log(["ReplaceChild" , from, to ]);
5473 from.parentNode.replaceChild(to, from);
5476 // compare attributes
5477 var ar = Array.from(from.attributes);
5478 for(var i = 0; i< ar.length;i++) {
5479 if (to.hasAttribute(ar[i].name)) {
5482 if (ar[i].name == 'id') { // always keep ids?
5485 from.removeAttribute(ar[i].name);
5488 for(var i = 0; i< ar.length;i++) {
5489 if (from.getAttribute(ar[i].name) == to.getAttribute(ar[i].name)) {
5492 from.setAttribute(ar[i].name, to.getAttribute(ar[i].name));
5495 var far = Array.from(from.childNodes);
5496 var tar = Array.from(to.childNodes);
5497 // if the lengths are different.. then it's probably a editable content change, rather than
5498 // a change of the block definition..
5500 // this did notwork , as our rebuilt nodes did not include ID's so did not match at all.
5501 /*if (from.innerHTML == to.innerHTML) {
5504 if (far.length != tar.length) {
5505 from.innerHTML = to.innerHTML;
5510 for(var i = 0; i < Math.max(tar.length, far.length); i++) {
5511 if (i >= far.length) {
5512 from.appendChild(tar[i]);
5513 Roo.log(["add", tar[i]]);
5515 } else if ( i >= tar.length) {
5516 from.removeChild(far[i]);
5517 Roo.log(["remove", far[i]]);
5520 updateNode(far[i], tar[i]);
5532 /** True to force the use of DOM instead of html fragments @type Boolean */
5536 * Returns the markup for the passed Element(s) config
5537 * @param {Object} o The Dom object spec (and children)
5540 markup : function(o){
5541 return createHtml(o);
5545 * Applies a style specification to an element
5546 * @param {String/HTMLElement} el The element to apply styles to
5547 * @param {String/Object/Function} styles A style specification string eg "width:100px", or object in the form {width:"100px"}, or
5548 * a function which returns such a specification.
5550 applyStyles : function(el, styles){
5553 if(typeof styles == "string"){
5554 var re = /\s?([a-z\-]*)\:\s?([^;]*);?/gi;
5556 while ((matches = re.exec(styles)) != null){
5557 el.setStyle(matches[1], matches[2]);
5559 }else if (typeof styles == "object"){
5560 for (var style in styles){
5561 el.setStyle(style, styles[style]);
5563 }else if (typeof styles == "function"){
5564 Roo.DomHelper.applyStyles(el, styles.call());
5570 * Inserts an HTML fragment into the Dom
5571 * @param {String} where Where to insert the html in relation to el - beforeBegin, afterBegin, beforeEnd, afterEnd.
5572 * @param {HTMLElement} el The context element
5573 * @param {String} html The HTML fragmenet
5574 * @return {HTMLElement} The new node
5576 insertHtml : function(where, el, html){
5577 where = where.toLowerCase();
5578 if(el.insertAdjacentHTML){
5579 if(tableRe.test(el.tagName)){
5581 if(rs = insertIntoTable(el.tagName.toLowerCase(), where, el, html)){
5587 el.insertAdjacentHTML('BeforeBegin', html);
5588 return el.previousSibling;
5590 el.insertAdjacentHTML('AfterBegin', html);
5591 return el.firstChild;
5593 el.insertAdjacentHTML('BeforeEnd', html);
5594 return el.lastChild;
5596 el.insertAdjacentHTML('AfterEnd', html);
5597 return el.nextSibling;
5599 throw 'Illegal insertion point -> "' + where + '"';
5601 var range = el.ownerDocument.createRange();
5605 range.setStartBefore(el);
5606 frag = range.createContextualFragment(html);
5607 el.parentNode.insertBefore(frag, el);
5608 return el.previousSibling;
5611 range.setStartBefore(el.firstChild);
5612 frag = range.createContextualFragment(html);
5613 el.insertBefore(frag, el.firstChild);
5614 return el.firstChild;
5616 el.innerHTML = html;
5617 return el.firstChild;
5621 range.setStartAfter(el.lastChild);
5622 frag = range.createContextualFragment(html);
5623 el.appendChild(frag);
5624 return el.lastChild;
5626 el.innerHTML = html;
5627 return el.lastChild;
5630 range.setStartAfter(el);
5631 frag = range.createContextualFragment(html);
5632 el.parentNode.insertBefore(frag, el.nextSibling);
5633 return el.nextSibling;
5635 throw 'Illegal insertion point -> "' + where + '"';
5639 * Creates new Dom element(s) and inserts them before el
5640 * @param {String/HTMLElement/Element} el The context element
5641 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5642 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5643 * @return {HTMLElement/Roo.Element} The new node
5645 insertBefore : function(el, o, returnElement){
5646 return this.doInsert(el, o, returnElement, "beforeBegin");
5650 * Creates new Dom element(s) and inserts them after el
5651 * @param {String/HTMLElement/Element} el The context element
5652 * @param {Object} o The Dom object spec (and children)
5653 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5654 * @return {HTMLElement/Roo.Element} The new node
5656 insertAfter : function(el, o, returnElement){
5657 return this.doInsert(el, o, returnElement, "afterEnd", "nextSibling");
5661 * Creates new Dom element(s) and inserts them as the first child of el
5662 * @param {String/HTMLElement/Element} el The context element
5663 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5664 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5665 * @return {HTMLElement/Roo.Element} The new node
5667 insertFirst : function(el, o, returnElement){
5668 return this.doInsert(el, o, returnElement, "afterBegin");
5672 doInsert : function(el, o, returnElement, pos, sibling){
5673 el = Roo.getDom(el);
5675 if(this.useDom || o.ns){
5676 newNode = createDom(o, null);
5677 el.parentNode.insertBefore(newNode, sibling ? el[sibling] : el);
5679 var html = createHtml(o);
5680 newNode = this.insertHtml(pos, el, html);
5682 return returnElement ? Roo.get(newNode, true) : newNode;
5686 * Creates new Dom element(s) and appends them to el
5687 * @param {String/HTMLElement/Element} el The context element
5688 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5689 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5690 * @return {HTMLElement/Roo.Element} The new node
5692 append : function(el, o, returnElement){
5693 el = Roo.getDom(el);
5695 if(this.useDom || o.ns){
5696 newNode = createDom(o, null);
5697 el.appendChild(newNode);
5699 var html = createHtml(o);
5700 newNode = this.insertHtml("beforeEnd", el, html);
5702 return returnElement ? Roo.get(newNode, true) : newNode;
5706 * Creates new Dom element(s) and overwrites the contents of el with them
5707 * @param {String/HTMLElement/Element} el The context element
5708 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5709 * @param {Boolean} returnElement (optional) true to return a Roo.Element
5710 * @return {HTMLElement/Roo.Element} The new node
5712 overwrite : function(el, o, returnElement)
5714 el = Roo.getDom(el);
5717 while (el.childNodes.length) {
5718 el.removeChild(el.firstChild);
5722 el.innerHTML = createHtml(o);
5725 return returnElement ? Roo.get(el.firstChild, true) : el.firstChild;
5729 * Creates a new Roo.DomHelper.Template from the Dom object spec
5730 * @param {Object} o The Dom object spec (and children)
5731 * @return {Roo.DomHelper.Template} The new template
5733 createTemplate : function(o){
5734 var html = createHtml(o);
5735 return new Roo.Template(html);
5738 * Updates the first element with the spec from the o (replacing if necessary)
5739 * This iterates through the children, and updates attributes / children etc..
5740 * @param {String/HTMLElement/Element} el The context element
5741 * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
5744 update : function(el, o)
5746 updateNode(Roo.getDom(el), createDom(o));
5755 * Ext JS Library 1.1.1
5756 * Copyright(c) 2006-2007, Ext JS, LLC.
5758 * Originally Released Under LGPL - original licence link has changed is not relivant.
5761 * <script type="text/javascript">
5765 * @class Roo.Template
5766 * Represents an HTML fragment template. Templates can be precompiled for greater performance.
5767 * For a list of available format functions, see {@link Roo.util.Format}.<br />
5770 var t = new Roo.Template({
5771 html : '<div name="{id}">' +
5772 '<span class="{cls}">{name:trim} {someval:this.myformat}{value:ellipsis(10)}</span>' +
5774 myformat: function (value, allValues) {
5775 return 'XX' + value;
5778 t.append('some-element', {id: 'myid', cls: 'myclass', name: 'foo', value: 'bar'});
5780 * For more information see this blog post with examples:
5781 * <a href="http://www.cnitblog.com/seeyeah/archive/2011/12/30/38728.html/">DomHelper
5782 - Create Elements using DOM, HTML fragments and Templates</a>.
5784 * @param {Object} cfg - Configuration object.
5786 Roo.Template = function(cfg){
5788 if(cfg instanceof Array){
5790 }else if(arguments.length > 1){
5791 cfg = Array.prototype.join.call(arguments, "");
5795 if (typeof(cfg) == 'object') {
5806 Roo.Template.prototype = {
5809 * @cfg {Function} onLoad Called after the template has been loaded and complied (usually from a remove source)
5815 * @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..
5816 * it should be fixed so that template is observable...
5820 * @cfg {String} html The HTML fragment or an array of fragments to join("") or multiple arguments to join("")
5828 * Returns an HTML fragment of this template with the specified values applied.
5829 * @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'})
5830 * @return {String} The HTML fragment
5835 applyTemplate : function(values){
5836 //Roo.log(["applyTemplate", values]);
5840 return this.compiled(values);
5842 var useF = this.disableFormats !== true;
5843 var fm = Roo.util.Format, tpl = this;
5844 var fn = function(m, name, format, args){
5846 if(format.substr(0, 5) == "this."){
5847 return tpl.call(format.substr(5), values[name], values);
5850 // quoted values are required for strings in compiled templates,
5851 // but for non compiled we need to strip them
5852 // quoted reversed for jsmin
5853 var re = /^\s*['"](.*)["']\s*$/;
5854 args = args.split(',');
5855 for(var i = 0, len = args.length; i < len; i++){
5856 args[i] = args[i].replace(re, "$1");
5858 args = [values[name]].concat(args);
5860 args = [values[name]];
5862 return fm[format].apply(fm, args);
5865 return values[name] !== undefined ? values[name] : "";
5868 return this.html.replace(this.re, fn);
5886 this.loading = true;
5887 this.compiled = false;
5889 var cx = new Roo.data.Connection();
5893 success : function (response) {
5897 _t.set(response.responseText,true);
5903 failure : function(response) {
5904 Roo.log("Template failed to load from " + _t.url);
5911 * Sets the HTML used as the template and optionally compiles it.
5912 * @param {String} html
5913 * @param {Boolean} compile (optional) True to compile the template (defaults to undefined)
5914 * @return {Roo.Template} this
5916 set : function(html, compile){
5918 this.compiled = false;
5926 * True to disable format functions (defaults to false)
5929 disableFormats : false,
5932 * The regular expression used to match template variables
5936 re : /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
5939 * Compiles the template into an internal function, eliminating the RegEx overhead.
5940 * @return {Roo.Template} this
5942 compile : function(){
5943 var fm = Roo.util.Format;
5944 var useF = this.disableFormats !== true;
5945 var sep = Roo.isGecko ? "+" : ",";
5946 var fn = function(m, name, format, args){
5948 args = args ? ',' + args : "";
5949 if(format.substr(0, 5) != "this."){
5950 format = "fm." + format + '(';
5952 format = 'this.call("'+ format.substr(5) + '", ';
5956 args= ''; format = "(values['" + name + "'] == undefined ? '' : ";
5958 return "'"+ sep + format + "values['" + name + "']" + args + ")"+sep+"'";
5961 // branched to use + in gecko and [].join() in others
5963 body = "this.compiled = function(values){ return '" +
5964 this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
5967 body = ["this.compiled = function(values){ return ['"];
5968 body.push(this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn));
5969 body.push("'].join('');};");
5970 body = body.join('');
5980 // private function used to call members
5981 call : function(fnName, value, allValues){
5982 return this[fnName](value, allValues);
5986 * Applies the supplied values to the template and inserts the new node(s) as the first child of el.
5987 * @param {String/HTMLElement/Roo.Element} el The context element
5988 * @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'})
5989 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
5990 * @return {HTMLElement/Roo.Element} The new node or Element
5992 insertFirst: function(el, values, returnElement){
5993 return this.doInsert('afterBegin', el, values, returnElement);
5997 * Applies the supplied values to the template and inserts the new node(s) before el.
5998 * @param {String/HTMLElement/Roo.Element} el The context element
5999 * @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'})
6000 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
6001 * @return {HTMLElement/Roo.Element} The new node or Element
6003 insertBefore: function(el, values, returnElement){
6004 return this.doInsert('beforeBegin', el, values, returnElement);
6008 * Applies the supplied values to the template and inserts the new node(s) after el.
6009 * @param {String/HTMLElement/Roo.Element} el The context element
6010 * @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'})
6011 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
6012 * @return {HTMLElement/Roo.Element} The new node or Element
6014 insertAfter : function(el, values, returnElement){
6015 return this.doInsert('afterEnd', el, values, returnElement);
6019 * Applies the supplied values to the template and appends the new node(s) to el.
6020 * @param {String/HTMLElement/Roo.Element} el The context element
6021 * @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'})
6022 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
6023 * @return {HTMLElement/Roo.Element} The new node or Element
6025 append : function(el, values, returnElement){
6026 return this.doInsert('beforeEnd', el, values, returnElement);
6029 doInsert : function(where, el, values, returnEl){
6030 el = Roo.getDom(el);
6031 var newNode = Roo.DomHelper.insertHtml(where, el, this.applyTemplate(values));
6032 return returnEl ? Roo.get(newNode, true) : newNode;
6036 * Applies the supplied values to the template and overwrites the content of el with the new node(s).
6037 * @param {String/HTMLElement/Roo.Element} el The context element
6038 * @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'})
6039 * @param {Boolean} returnElement (optional) true to return a Roo.Element (defaults to undefined)
6040 * @return {HTMLElement/Roo.Element} The new node or Element
6042 overwrite : function(el, values, returnElement){
6043 el = Roo.getDom(el);
6044 el.innerHTML = this.applyTemplate(values);
6045 return returnElement ? Roo.get(el.firstChild, true) : el.firstChild;
6049 * Alias for {@link #applyTemplate}
6052 Roo.Template.prototype.apply = Roo.Template.prototype.applyTemplate;
6055 Roo.DomHelper.Template = Roo.Template;
6058 * Creates a template from the passed element's value (<i>display:none</i> textarea, preferred) or innerHTML.
6059 * @param {String/HTMLElement} el A DOM element or its id
6060 * @returns {Roo.Template} The created template
6063 Roo.Template.from = function(el){
6064 el = Roo.getDom(el);
6065 return new Roo.Template(el.value || el.innerHTML);
6068 * Ext JS Library 1.1.1
6069 * Copyright(c) 2006-2007, Ext JS, LLC.
6071 * Originally Released Under LGPL - original licence link has changed is not relivant.
6074 * <script type="text/javascript">
6079 * This is code is also distributed under MIT license for use
6080 * with jQuery and prototype JavaScript libraries.
6083 * @class Roo.DomQuery
6084 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).
6086 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>
6089 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.
6091 <h4>Element Selectors:</h4>
6093 <li> <b>*</b> any element</li>
6094 <li> <b>E</b> an element with the tag E</li>
6095 <li> <b>E F</b> All descendent elements of E that have the tag F</li>
6096 <li> <b>E > F</b> or <b>E/F</b> all direct children elements of E that have the tag F</li>
6097 <li> <b>E + F</b> all elements with the tag F that are immediately preceded by an element with the tag E</li>
6098 <li> <b>E ~ F</b> all elements with the tag F that are preceded by a sibling element with the tag E</li>
6100 <h4>Attribute Selectors:</h4>
6101 <p>The use of @ and quotes are optional. For example, div[@foo='bar'] is also a valid attribute selector.</p>
6103 <li> <b>E[foo]</b> has an attribute "foo"</li>
6104 <li> <b>E[foo=bar]</b> has an attribute "foo" that equals "bar"</li>
6105 <li> <b>E[foo^=bar]</b> has an attribute "foo" that starts with "bar"</li>
6106 <li> <b>E[foo$=bar]</b> has an attribute "foo" that ends with "bar"</li>
6107 <li> <b>E[foo*=bar]</b> has an attribute "foo" that contains the substring "bar"</li>
6108 <li> <b>E[foo%=2]</b> has an attribute "foo" that is evenly divisible by 2</li>
6109 <li> <b>E[foo!=bar]</b> has an attribute "foo" that does not equal "bar"</li>
6111 <h4>Pseudo Classes:</h4>
6113 <li> <b>E:first-child</b> E is the first child of its parent</li>
6114 <li> <b>E:last-child</b> E is the last child of its parent</li>
6115 <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>
6116 <li> <b>E:nth-child(odd)</b> E is an odd child of its parent</li>
6117 <li> <b>E:nth-child(even)</b> E is an even child of its parent</li>
6118 <li> <b>E:only-child</b> E is the only child of its parent</li>
6119 <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>
6120 <li> <b>E:first</b> the first E in the resultset</li>
6121 <li> <b>E:last</b> the last E in the resultset</li>
6122 <li> <b>E:nth(<i>n</i>)</b> the <i>n</i>th E in the resultset (1 based)</li>
6123 <li> <b>E:odd</b> shortcut for :nth-child(odd)</li>
6124 <li> <b>E:even</b> shortcut for :nth-child(even)</li>
6125 <li> <b>E:contains(foo)</b> E's innerHTML contains the substring "foo"</li>
6126 <li> <b>E:nodeValue(foo)</b> E contains a textNode with a nodeValue that equals "foo"</li>
6127 <li> <b>E:not(S)</b> an E element that does not match simple selector S</li>
6128 <li> <b>E:has(S)</b> an E element that has a descendent that matches simple selector S</li>
6129 <li> <b>E:next(S)</b> an E element whose next sibling matches simple selector S</li>
6130 <li> <b>E:prev(S)</b> an E element whose previous sibling matches simple selector S</li>
6132 <h4>CSS Value Selectors:</h4>
6134 <li> <b>E{display=none}</b> css value "display" that equals "none"</li>
6135 <li> <b>E{display^=none}</b> css value "display" that starts with "none"</li>
6136 <li> <b>E{display$=none}</b> css value "display" that ends with "none"</li>
6137 <li> <b>E{display*=none}</b> css value "display" that contains the substring "none"</li>
6138 <li> <b>E{display%=2}</b> css value "display" that is evenly divisible by 2</li>
6139 <li> <b>E{display!=none}</b> css value "display" that does not equal "none"</li>
6143 Roo.DomQuery = function(){
6144 var cache = {}, simpleCache = {}, valueCache = {};
6145 var nonSpace = /\S/;
6146 var trimRe = /^\s+|\s+$/g;
6147 var tplRe = /\{(\d+)\}/g;
6148 var modeRe = /^(\s?[\/>+~]\s?|\s|$)/;
6149 var tagTokenRe = /^(#)?([\w-\*]+)/;
6150 var nthRe = /(\d*)n\+?(\d*)/, nthRe2 = /\D/;
6152 function child(p, index){
6154 var n = p.firstChild;
6156 if(n.nodeType == 1){
6167 while((n = n.nextSibling) && n.nodeType != 1);
6172 while((n = n.previousSibling) && n.nodeType != 1);
6176 function children(d){
6177 var n = d.firstChild, ni = -1;
6179 var nx = n.nextSibling;
6180 if(n.nodeType == 3 && !nonSpace.test(n.nodeValue)){
6190 function byClassName(c, a, v){
6194 var r = [], ri = -1, cn;
6195 for(var i = 0, ci; ci = c[i]; i++){
6199 ( (ci instanceof SVGElement) ? ci.className.baseVal : ci.className)
6200 +' ').indexOf(v) != -1){
6207 function attrValue(n, attr){
6208 if(!n.tagName && typeof n.length != "undefined"){
6217 if(attr == "class" || attr == "className"){
6218 return (n instanceof SVGElement) ? n.className.baseVal : n.className;
6220 return n.getAttribute(attr) || n[attr];
6224 function getNodes(ns, mode, tagName){
6225 var result = [], ri = -1, cs;
6229 tagName = tagName || "*";
6230 if(typeof ns.getElementsByTagName != "undefined"){
6234 for(var i = 0, ni; ni = ns[i]; i++){
6235 cs = ni.getElementsByTagName(tagName);
6236 for(var j = 0, ci; ci = cs[j]; j++){
6240 }else if(mode == "/" || mode == ">"){
6241 var utag = tagName.toUpperCase();
6242 for(var i = 0, ni, cn; ni = ns[i]; i++){
6243 cn = ni.children || ni.childNodes;
6244 for(var j = 0, cj; cj = cn[j]; j++){
6245 if(cj.nodeName == utag || cj.nodeName == tagName || tagName == '*'){
6250 }else if(mode == "+"){
6251 var utag = tagName.toUpperCase();
6252 for(var i = 0, n; n = ns[i]; i++){
6253 while((n = n.nextSibling) && n.nodeType != 1);
6254 if(n && (n.nodeName == utag || n.nodeName == tagName || tagName == '*')){
6258 }else if(mode == "~"){
6259 for(var i = 0, n; n = ns[i]; i++){
6260 while((n = n.nextSibling) && (n.nodeType != 1 || (tagName == '*' || n.tagName.toLowerCase()!=tagName)));
6269 function concat(a, b){
6273 for(var i = 0, l = b.length; i < l; i++){
6279 function byTag(cs, tagName){
6280 if(cs.tagName || cs == document){
6286 var r = [], ri = -1;
6287 tagName = tagName.toLowerCase();
6288 for(var i = 0, ci; ci = cs[i]; i++){
6289 if(ci.nodeType == 1 && ci.tagName.toLowerCase()==tagName){
6296 function byId(cs, attr, id){
6297 if(cs.tagName || cs == document){
6303 var r = [], ri = -1;
6304 for(var i = 0,ci; ci = cs[i]; i++){
6305 if(ci && ci.id == id){
6313 function byAttribute(cs, attr, value, op, custom){
6314 var r = [], ri = -1, st = custom=="{";
6315 var f = Roo.DomQuery.operators[op];
6316 for(var i = 0, ci; ci = cs[i]; i++){
6319 a = Roo.DomQuery.getStyle(ci, attr);
6321 else if(attr == "class" || attr == "className"){
6322 a = (ci instanceof SVGElement) ? ci.className.baseVal : ci.className;
6323 }else if(attr == "for"){
6325 }else if(attr == "href"){
6326 a = ci.getAttribute("href", 2);
6328 a = ci.getAttribute(attr);
6330 if((f && f(a, value)) || (!f && a)){
6337 function byPseudo(cs, name, value){
6338 return Roo.DomQuery.pseudos[name](cs, value);
6341 // This is for IE MSXML which does not support expandos.
6342 // IE runs the same speed using setAttribute, however FF slows way down
6343 // and Safari completely fails so they need to continue to use expandos.
6344 var isIE = window.ActiveXObject ? true : false;
6346 // this eval is stop the compressor from
6347 // renaming the variable to something shorter
6349 /** eval:var:batch */
6354 function nodupIEXml(cs){
6356 cs[0].setAttribute("_nodup", d);
6358 for(var i = 1, len = cs.length; i < len; i++){
6360 if(!c.getAttribute("_nodup") != d){
6361 c.setAttribute("_nodup", d);
6365 for(var i = 0, len = cs.length; i < len; i++){
6366 cs[i].removeAttribute("_nodup");
6375 var len = cs.length, c, i, r = cs, cj, ri = -1;
6376 if(!len || typeof cs.nodeType != "undefined" || len == 1){
6379 if(isIE && typeof cs[0].selectSingleNode != "undefined"){
6380 return nodupIEXml(cs);
6384 for(i = 1; c = cs[i]; i++){
6389 for(var j = 0; j < i; j++){
6392 for(j = i+1; cj = cs[j]; j++){
6404 function quickDiffIEXml(c1, c2){
6406 for(var i = 0, len = c1.length; i < len; i++){
6407 c1[i].setAttribute("_qdiff", d);
6410 for(var i = 0, len = c2.length; i < len; i++){
6411 if(c2[i].getAttribute("_qdiff") != d){
6412 r[r.length] = c2[i];
6415 for(var i = 0, len = c1.length; i < len; i++){
6416 c1[i].removeAttribute("_qdiff");
6421 function quickDiff(c1, c2){
6422 var len1 = c1.length;
6426 if(isIE && c1[0].selectSingleNode){
6427 return quickDiffIEXml(c1, c2);
6430 for(var i = 0; i < len1; i++){
6434 for(var i = 0, len = c2.length; i < len; i++){
6435 if(c2[i]._qdiff != d){
6436 r[r.length] = c2[i];
6442 function quickId(ns, mode, root, id){
6444 var d = root.ownerDocument || root;
6445 return d.getElementById(id);
6447 ns = getNodes(ns, mode, "*");
6448 return byId(ns, null, id);
6452 getStyle : function(el, name){
6453 return Roo.fly(el).getStyle(name);
6456 * Compiles a selector/xpath query into a reusable function. The returned function
6457 * takes one parameter "root" (optional), which is the context node from where the query should start.
6458 * @param {String} selector The selector/xpath query
6459 * @param {String} type (optional) Either "select" (the default) or "simple" for a simple selector match
6460 * @return {Function}
6462 compile : function(path, type){
6463 type = type || "select";
6465 var fn = ["var f = function(root){\n var mode; ++batch; var n = root || document;\n"];
6466 var q = path, mode, lq;
6467 var tk = Roo.DomQuery.matchers;
6468 var tklen = tk.length;
6471 // accept leading mode switch
6472 var lmode = q.match(modeRe);
6473 if(lmode && lmode[1]){
6474 fn[fn.length] = 'mode="'+lmode[1].replace(trimRe, "")+'";';
6475 q = q.replace(lmode[1], "");
6477 // strip leading slashes
6478 while(path.substr(0, 1)=="/"){
6479 path = path.substr(1);
6482 while(q && lq != q){
6484 var tm = q.match(tagTokenRe);
6485 if(type == "select"){
6488 fn[fn.length] = 'n = quickId(n, mode, root, "'+tm[2]+'");';
6490 fn[fn.length] = 'n = getNodes(n, mode, "'+tm[2]+'");';
6492 q = q.replace(tm[0], "");
6493 }else if(q.substr(0, 1) != '@'){
6494 fn[fn.length] = 'n = getNodes(n, mode, "*");';
6499 fn[fn.length] = 'n = byId(n, null, "'+tm[2]+'");';
6501 fn[fn.length] = 'n = byTag(n, "'+tm[2]+'");';
6503 q = q.replace(tm[0], "");
6506 while(!(mm = q.match(modeRe))){
6507 var matched = false;
6508 for(var j = 0; j < tklen; j++){
6510 var m = q.match(t.re);
6512 fn[fn.length] = t.select.replace(tplRe, function(x, i){
6515 q = q.replace(m[0], "");
6520 // prevent infinite loop on bad selector
6522 throw 'Error parsing selector, parsing failed at "' + q + '"';
6526 fn[fn.length] = 'mode="'+mm[1].replace(trimRe, "")+'";';
6527 q = q.replace(mm[1], "");
6530 fn[fn.length] = "return nodup(n);\n}";
6533 * list of variables that need from compression as they are used by eval.
6543 * eval:var:byClassName
6545 * eval:var:byAttribute
6546 * eval:var:attrValue
6554 * Selects a group of elements.
6555 * @param {String} selector The selector/xpath query (can be a comma separated list of selectors)
6556 * @param {Node} root (optional) The start of the query (defaults to document).
6559 select : function(path, root, type){
6560 if(!root || root == document){
6563 if(typeof root == "string"){
6564 root = document.getElementById(root);
6566 var paths = path.split(",");
6568 for(var i = 0, len = paths.length; i < len; i++){
6569 var p = paths[i].replace(trimRe, "");
6571 cache[p] = Roo.DomQuery.compile(p);
6573 throw p + " is not a valid selector";
6576 var result = cache[p](root);
6577 if(result && result != document){
6578 results = results.concat(result);
6581 if(paths.length > 1){
6582 return nodup(results);
6588 * Selects a single element.
6589 * @param {String} selector The selector/xpath query
6590 * @param {Node} root (optional) The start of the query (defaults to document).
6593 selectNode : function(path, root){
6594 return Roo.DomQuery.select(path, root)[0];
6598 * Selects the value of a node, optionally replacing null with the defaultValue.
6599 * @param {String} selector The selector/xpath query
6600 * @param {Node} root (optional) The start of the query (defaults to document).
6601 * @param {String} defaultValue
6603 selectValue : function(path, root, defaultValue){
6604 path = path.replace(trimRe, "");
6605 if(!valueCache[path]){
6606 valueCache[path] = Roo.DomQuery.compile(path, "select");
6608 var n = valueCache[path](root);
6609 n = n[0] ? n[0] : n;
6610 var v = (n && n.firstChild ? n.firstChild.nodeValue : null);
6611 return ((v === null||v === undefined||v==='') ? defaultValue : v);
6615 * Selects the value of a node, parsing integers and floats.
6616 * @param {String} selector The selector/xpath query
6617 * @param {Node} root (optional) The start of the query (defaults to document).
6618 * @param {Number} defaultValue
6621 selectNumber : function(path, root, defaultValue){
6622 var v = Roo.DomQuery.selectValue(path, root, defaultValue || 0);
6623 return parseFloat(v);
6627 * Returns true if the passed element(s) match the passed simple selector (e.g. div.some-class or span:first-child)
6628 * @param {String/HTMLElement/Array} el An element id, element or array of elements
6629 * @param {String} selector The simple selector to test
6632 is : function(el, ss){
6633 if(typeof el == "string"){
6634 el = document.getElementById(el);
6636 var isArray = (el instanceof Array);
6637 var result = Roo.DomQuery.filter(isArray ? el : [el], ss);
6638 return isArray ? (result.length == el.length) : (result.length > 0);
6642 * Filters an array of elements to only include matches of a simple selector (e.g. div.some-class or span:first-child)
6643 * @param {Array} el An array of elements to filter
6644 * @param {String} selector The simple selector to test
6645 * @param {Boolean} nonMatches If true, it returns the elements that DON'T match
6646 * the selector instead of the ones that match
6649 filter : function(els, ss, nonMatches){
6650 ss = ss.replace(trimRe, "");
6651 if(!simpleCache[ss]){
6652 simpleCache[ss] = Roo.DomQuery.compile(ss, "simple");
6654 var result = simpleCache[ss](els);
6655 return nonMatches ? quickDiff(result, els) : result;
6659 * Collection of matching regular expressions and code snippets.
6663 select: 'n = byClassName(n, null, " {1} ");'
6665 re: /^\:([\w-]+)(?:\(((?:[^\s>\/]*|.*?))\))?/,
6666 select: 'n = byPseudo(n, "{1}", "{2}");'
6668 re: /^(?:([\[\{])(?:@)?([\w-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]\}])/,
6669 select: 'n = byAttribute(n, "{2}", "{4}", "{3}", "{1}");'
6672 select: 'n = byId(n, null, "{1}");'
6675 select: 'return {firstChild:{nodeValue:attrValue(n, "{1}")}};'
6680 * Collection of operator comparison functions. The default operators are =, !=, ^=, $=, *=, %=, |= and ~=.
6681 * 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, > <.
6684 "=" : function(a, v){
6687 "!=" : function(a, v){
6690 "^=" : function(a, v){
6691 return a && a.substr(0, v.length) == v;
6693 "$=" : function(a, v){
6694 return a && a.substr(a.length-v.length) == v;
6696 "*=" : function(a, v){
6697 return a && a.indexOf(v) !== -1;
6699 "%=" : function(a, v){
6700 return (a % v) == 0;
6702 "|=" : function(a, v){
6703 return a && (a == v || a.substr(0, v.length+1) == v+'-');
6705 "~=" : function(a, v){
6706 return a && (' '+a+' ').indexOf(' '+v+' ') != -1;
6711 * Collection of "pseudo class" processors. Each processor is passed the current nodeset (array)
6712 * and the argument (if any) supplied in the selector.
6715 "first-child" : function(c){
6716 var r = [], ri = -1, n;
6717 for(var i = 0, ci; ci = n = c[i]; i++){
6718 while((n = n.previousSibling) && n.nodeType != 1);
6726 "last-child" : function(c){
6727 var r = [], ri = -1, n;
6728 for(var i = 0, ci; ci = n = c[i]; i++){
6729 while((n = n.nextSibling) && n.nodeType != 1);
6737 "nth-child" : function(c, a) {
6738 var r = [], ri = -1;
6739 var m = nthRe.exec(a == "even" && "2n" || a == "odd" && "2n+1" || !nthRe2.test(a) && "n+" + a || a);
6740 var f = (m[1] || 1) - 0, l = m[2] - 0;
6741 for(var i = 0, n; n = c[i]; i++){
6742 var pn = n.parentNode;
6743 if (batch != pn._batch) {
6745 for(var cn = pn.firstChild; cn; cn = cn.nextSibling){
6746 if(cn.nodeType == 1){
6753 if (l == 0 || n.nodeIndex == l){
6756 } else if ((n.nodeIndex + l) % f == 0){
6764 "only-child" : function(c){
6765 var r = [], ri = -1;;
6766 for(var i = 0, ci; ci = c[i]; i++){
6767 if(!prev(ci) && !next(ci)){
6774 "empty" : function(c){
6775 var r = [], ri = -1;
6776 for(var i = 0, ci; ci = c[i]; i++){
6777 var cns = ci.childNodes, j = 0, cn, empty = true;
6780 if(cn.nodeType == 1 || cn.nodeType == 3){
6792 "contains" : function(c, v){
6793 var r = [], ri = -1;
6794 for(var i = 0, ci; ci = c[i]; i++){
6795 if((ci.textContent||ci.innerText||'').indexOf(v) != -1){
6802 "nodeValue" : function(c, v){
6803 var r = [], ri = -1;
6804 for(var i = 0, ci; ci = c[i]; i++){
6805 if(ci.firstChild && ci.firstChild.nodeValue == v){
6812 "checked" : function(c){
6813 var r = [], ri = -1;
6814 for(var i = 0, ci; ci = c[i]; i++){
6815 if(ci.checked == true){
6822 "not" : function(c, ss){
6823 return Roo.DomQuery.filter(c, ss, true);
6826 "odd" : function(c){
6827 return this["nth-child"](c, "odd");
6830 "even" : function(c){
6831 return this["nth-child"](c, "even");
6834 "nth" : function(c, a){
6835 return c[a-1] || [];
6838 "first" : function(c){
6842 "last" : function(c){
6843 return c[c.length-1] || [];
6846 "has" : function(c, ss){
6847 var s = Roo.DomQuery.select;
6848 var r = [], ri = -1;
6849 for(var i = 0, ci; ci = c[i]; i++){
6850 if(s(ss, ci).length > 0){
6857 "next" : function(c, ss){
6858 var is = Roo.DomQuery.is;
6859 var r = [], ri = -1;
6860 for(var i = 0, ci; ci = c[i]; i++){
6869 "prev" : function(c, ss){
6870 var is = Roo.DomQuery.is;
6871 var r = [], ri = -1;
6872 for(var i = 0, ci; ci = c[i]; i++){
6885 * Selects an array of DOM nodes by CSS/XPath selector. Shorthand of {@link Roo.DomQuery#select}
6886 * @param {String} path The selector/xpath query
6887 * @param {Node} root (optional) The start of the query (defaults to document).
6892 Roo.query = Roo.DomQuery.select;
6895 * Ext JS Library 1.1.1
6896 * Copyright(c) 2006-2007, Ext JS, LLC.
6898 * Originally Released Under LGPL - original licence link has changed is not relivant.
6901 * <script type="text/javascript">
6905 * @class Roo.util.Observable
6906 * Base class that provides a common interface for publishing events. Subclasses are expected to
6907 * to have a property "events" with all the events defined.<br>
6910 Employee = function(name){
6917 Roo.extend(Employee, Roo.util.Observable);
6919 * @param {Object} config properties to use (incuding events / listeners)
6922 Roo.util.Observable = function(cfg){
6925 this.addEvents(cfg.events || {});
6927 delete cfg.events; // make sure
6930 Roo.apply(this, cfg);
6933 this.on(this.listeners);
6934 delete this.listeners;
6937 Roo.util.Observable.prototype = {
6939 * @cfg {Object} listeners list of events and functions to call for this object,
6943 'click' : function(e) {
6953 * Fires the specified event with the passed parameters (minus the event name).
6954 * @param {String} eventName
6955 * @param {Object...} args Variable number of parameters are passed to handlers
6956 * @return {Boolean} returns false if any of the handlers return false otherwise it returns true
6958 fireEvent : function(){
6959 var ce = this.events[arguments[0].toLowerCase()];
6960 if(typeof ce == "object"){
6961 return ce.fire.apply(ce, Array.prototype.slice.call(arguments, 1));
6968 filterOptRe : /^(?:scope|delay|buffer|single)$/,
6971 * Appends an event handler to this component
6972 * @param {String} eventName The type of event to listen for
6973 * @param {Function} handler The method the event invokes
6974 * @param {Object} scope (optional) The scope in which to execute the handler
6975 * function. The handler function's "this" context.
6976 * @param {Object} options (optional) An object containing handler configuration
6977 * properties. This may contain any of the following properties:<ul>
6978 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
6979 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
6980 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
6981 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
6982 * by the specified number of milliseconds. If the event fires again within that time, the original
6983 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
6986 * <b>Combining Options</b><br>
6987 * Using the options argument, it is possible to combine different types of listeners:<br>
6989 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)
6991 el.on('click', this.onClick, this, {
6998 * <b>Attaching multiple handlers in 1 call</b><br>
6999 * The method also allows for a single argument to be passed which is a config object containing properties
7000 * which specify multiple handlers.
7009 fn: this.onMouseOver,
7013 fn: this.onMouseOut,
7019 * Or a shorthand syntax which passes the same scope object to all handlers:
7022 'click': this.onClick,
7023 'mouseover': this.onMouseOver,
7024 'mouseout': this.onMouseOut,
7029 addListener : function(eventName, fn, scope, o){
7030 if(typeof eventName == "object"){
7033 if(this.filterOptRe.test(e)){
7036 if(typeof o[e] == "function"){
7038 this.addListener(e, o[e], o.scope, o);
7040 // individual options
7041 this.addListener(e, o[e].fn, o[e].scope, o[e]);
7046 o = (!o || typeof o == "boolean") ? {} : o;
7047 eventName = eventName.toLowerCase();
7048 var ce = this.events[eventName] || true;
7049 if(typeof ce == "boolean"){
7050 ce = new Roo.util.Event(this, eventName);
7051 this.events[eventName] = ce;
7053 ce.addListener(fn, scope, o);
7057 * Removes a listener
7058 * @param {String} eventName The type of event to listen for
7059 * @param {Function} handler The handler to remove
7060 * @param {Object} scope (optional) The scope (this object) for the handler
7062 removeListener : function(eventName, fn, scope){
7063 var ce = this.events[eventName.toLowerCase()];
7064 if(typeof ce == "object"){
7065 ce.removeListener(fn, scope);
7070 * Removes all listeners for this object
7072 purgeListeners : function(){
7073 for(var evt in this.events){
7074 if(typeof this.events[evt] == "object"){
7075 this.events[evt].clearListeners();
7080 relayEvents : function(o, events){
7081 var createHandler = function(ename){
7084 return this.fireEvent.apply(this, Roo.combine(ename, Array.prototype.slice.call(arguments, 0)));
7087 for(var i = 0, len = events.length; i < len; i++){
7088 var ename = events[i];
7089 if(!this.events[ename]){
7090 this.events[ename] = true;
7092 o.on(ename, createHandler(ename), this);
7097 * Used to define events on this Observable
7098 * @param {Object} object The object with the events defined
7100 addEvents : function(o){
7104 Roo.applyIf(this.events, o);
7108 * Checks to see if this object has any listeners for a specified event
7109 * @param {String} eventName The name of the event to check for
7110 * @return {Boolean} True if the event is being listened for, else false
7112 hasListener : function(eventName){
7113 var e = this.events[eventName];
7114 return typeof e == "object" && e.listeners.length > 0;
7118 * Appends an event handler to this element (shorthand for addListener)
7119 * @param {String} eventName The type of event to listen for
7120 * @param {Function} handler The method the event invokes
7121 * @param {Object} scope (optional) The scope in which to execute the handler
7122 * function. The handler function's "this" context.
7123 * @param {Object} options (optional)
7126 Roo.util.Observable.prototype.on = Roo.util.Observable.prototype.addListener;
7128 * Removes a listener (shorthand for removeListener)
7129 * @param {String} eventName The type of event to listen for
7130 * @param {Function} handler The handler to remove
7131 * @param {Object} scope (optional) The scope (this object) for the handler
7134 Roo.util.Observable.prototype.un = Roo.util.Observable.prototype.removeListener;
7137 * Starts capture on the specified Observable. All events will be passed
7138 * to the supplied function with the event name + standard signature of the event
7139 * <b>before</b> the event is fired. If the supplied function returns false,
7140 * the event will not fire.
7141 * @param {Observable} o The Observable to capture
7142 * @param {Function} fn The function to call
7143 * @param {Object} scope (optional) The scope (this object) for the fn
7146 Roo.util.Observable.capture = function(o, fn, scope){
7147 o.fireEvent = o.fireEvent.createInterceptor(fn, scope);
7151 * Removes <b>all</b> added captures from the Observable.
7152 * @param {Observable} o The Observable to release
7155 Roo.util.Observable.releaseCapture = function(o){
7156 o.fireEvent = Roo.util.Observable.prototype.fireEvent;
7161 var createBuffered = function(h, o, scope){
7162 var task = new Roo.util.DelayedTask();
7164 task.delay(o.buffer, h, scope, Array.prototype.slice.call(arguments, 0));
7168 var createSingle = function(h, e, fn, scope){
7170 e.removeListener(fn, scope);
7171 return h.apply(scope, arguments);
7175 var createDelayed = function(h, o, scope){
7177 var args = Array.prototype.slice.call(arguments, 0);
7178 setTimeout(function(){
7179 h.apply(scope, args);
7184 Roo.util.Event = function(obj, name){
7187 this.listeners = [];
7190 Roo.util.Event.prototype = {
7191 addListener : function(fn, scope, options){
7192 var o = options || {};
7193 scope = scope || this.obj;
7194 if(!this.isListening(fn, scope)){
7195 var l = {fn: fn, scope: scope, options: o};
7198 h = createDelayed(h, o, scope);
7201 h = createSingle(h, this, fn, scope);
7204 h = createBuffered(h, o, scope);
7207 if(!this.firing){ // if we are currently firing this event, don't disturb the listener loop
7208 this.listeners.push(l);
7210 this.listeners = this.listeners.slice(0);
7211 this.listeners.push(l);
7216 findListener : function(fn, scope){
7217 scope = scope || this.obj;
7218 var ls = this.listeners;
7219 for(var i = 0, len = ls.length; i < len; i++){
7221 if(l.fn == fn && l.scope == scope){
7228 isListening : function(fn, scope){
7229 return this.findListener(fn, scope) != -1;
7232 removeListener : function(fn, scope){
7234 if((index = this.findListener(fn, scope)) != -1){
7236 this.listeners.splice(index, 1);
7238 this.listeners = this.listeners.slice(0);
7239 this.listeners.splice(index, 1);
7246 clearListeners : function(){
7247 this.listeners = [];
7251 var ls = this.listeners, scope, len = ls.length;
7254 var args = Array.prototype.slice.call(arguments, 0);
7255 for(var i = 0; i < len; i++){
7257 if(l.fireFn.apply(l.scope||this.obj||window, args) === false){
7258 this.firing = false;
7262 this.firing = false;
7269 * Copyright(c) 2007-2017, Roo J Solutions Ltd
7276 * @class Roo.Document
7277 * @extends Roo.util.Observable
7278 * This is a convience class to wrap up the main document loading code.. , rather than adding Roo.onReady(......)
7280 * @param {Object} config the methods and properties of the 'base' class for the application.
7282 * Generic Page handler - implement this to start your app..
7285 * MyProject = new Roo.Document({
7287 'load' : true // your events..
7290 'ready' : function() {
7291 // fired on Roo.onReady()
7296 Roo.Document = function(cfg) {
7301 Roo.util.Observable.call(this,cfg);
7305 Roo.onReady(function() {
7306 _this.fireEvent('ready');
7312 Roo.extend(Roo.Document, Roo.util.Observable, {});/*
7314 * Ext JS Library 1.1.1
7315 * Copyright(c) 2006-2007, Ext JS, LLC.
7317 * Originally Released Under LGPL - original licence link has changed is not relivant.
7320 * <script type="text/javascript">
7324 * @class Roo.EventManager
7325 * Registers event handlers that want to receive a normalized EventObject instead of the standard browser event and provides
7326 * several useful events directly.
7327 * See {@link Roo.EventObject} for more details on normalized event objects.
7330 Roo.EventManager = function(){
7331 var docReadyEvent, docReadyProcId, docReadyState = false;
7332 var resizeEvent, resizeTask, textEvent, textSize;
7333 var E = Roo.lib.Event;
7334 var D = Roo.lib.Dom;
7339 var fireDocReady = function(){
7341 docReadyState = true;
7344 clearInterval(docReadyProcId);
7346 if(Roo.isGecko || Roo.isOpera) {
7347 document.removeEventListener("DOMContentLoaded", fireDocReady, false);
7350 var defer = document.getElementById("ie-deferred-loader");
7352 defer.onreadystatechange = null;
7353 defer.parentNode.removeChild(defer);
7357 docReadyEvent.fire();
7358 docReadyEvent.clearListeners();
7363 var initDocReady = function(){
7364 docReadyEvent = new Roo.util.Event();
7365 if(Roo.isGecko || Roo.isOpera) {
7366 document.addEventListener("DOMContentLoaded", fireDocReady, false);
7368 document.write("<s"+'cript id="ie-deferred-loader" defer="defer" src="/'+'/:"></s'+"cript>");
7369 var defer = document.getElementById("ie-deferred-loader");
7370 defer.onreadystatechange = function(){
7371 if(this.readyState == "complete"){
7375 }else if(Roo.isSafari){
7376 docReadyProcId = setInterval(function(){
7377 var rs = document.readyState;
7378 if(rs == "complete") {
7383 // no matter what, make sure it fires on load
7384 E.on(window, "load", fireDocReady);
7387 var createBuffered = function(h, o){
7388 var task = new Roo.util.DelayedTask(h);
7390 // create new event object impl so new events don't wipe out properties
7391 e = new Roo.EventObjectImpl(e);
7392 task.delay(o.buffer, h, null, [e]);
7396 var createSingle = function(h, el, ename, fn){
7398 Roo.EventManager.removeListener(el, ename, fn);
7403 var createDelayed = function(h, o){
7405 // create new event object impl so new events don't wipe out properties
7406 e = new Roo.EventObjectImpl(e);
7407 setTimeout(function(){
7412 var transitionEndVal = false;
7414 var transitionEnd = function()
7416 if (transitionEndVal) {
7417 return transitionEndVal;
7419 var el = document.createElement('div');
7421 var transEndEventNames = {
7422 WebkitTransition : 'webkitTransitionEnd',
7423 MozTransition : 'transitionend',
7424 OTransition : 'oTransitionEnd otransitionend',
7425 transition : 'transitionend'
7428 for (var name in transEndEventNames) {
7429 if (el.style[name] !== undefined) {
7430 transitionEndVal = transEndEventNames[name];
7431 return transitionEndVal ;
7438 var listen = function(element, ename, opt, fn, scope)
7440 var o = (!opt || typeof opt == "boolean") ? {} : opt;
7441 fn = fn || o.fn; scope = scope || o.scope;
7442 var el = Roo.getDom(element);
7446 throw "Error listening for \"" + ename + '\". Element "' + element + '" doesn\'t exist.';
7449 if (ename == 'transitionend') {
7450 ename = transitionEnd();
7452 var h = function(e){
7453 e = Roo.EventObject.setEvent(e);
7456 t = e.getTarget(o.delegate, el);
7463 if(o.stopEvent === true){
7466 if(o.preventDefault === true){
7469 if(o.stopPropagation === true){
7470 e.stopPropagation();
7473 if(o.normalized === false){
7477 fn.call(scope || el, e, t, o);
7480 h = createDelayed(h, o);
7483 h = createSingle(h, el, ename, fn);
7486 h = createBuffered(h, o);
7489 fn._handlers = fn._handlers || [];
7492 fn._handlers.push([Roo.id(el), ename, h]);
7496 E.on(el, ename, h); // this adds the actuall listener to the object..
7499 if(ename == "mousewheel" && el.addEventListener){ // workaround for jQuery
7500 el.addEventListener("DOMMouseScroll", h, false);
7501 E.on(window, 'unload', function(){
7502 el.removeEventListener("DOMMouseScroll", h, false);
7505 if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
7506 Roo.EventManager.stoppedMouseDownEvent.addListener(h);
7511 var stopListening = function(el, ename, fn){
7512 var id = Roo.id(el), hds = fn._handlers, hd = fn;
7514 for(var i = 0, len = hds.length; i < len; i++){
7516 if(h[0] == id && h[1] == ename){
7523 E.un(el, ename, hd);
7524 el = Roo.getDom(el);
7525 if(ename == "mousewheel" && el.addEventListener){
7526 el.removeEventListener("DOMMouseScroll", hd, false);
7528 if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
7529 Roo.EventManager.stoppedMouseDownEvent.removeListener(hd);
7533 var propRe = /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/;
7540 * @scope Roo.EventManager
7545 * This is no longer needed and is deprecated. Places a simple wrapper around an event handler to override the browser event
7546 * object with a Roo.EventObject
7547 * @param {Function} fn The method the event invokes
7548 * @param {Object} scope An object that becomes the scope of the handler
7549 * @param {boolean} override If true, the obj passed in becomes
7550 * the execution scope of the listener
7551 * @return {Function} The wrapped function
7554 wrap : function(fn, scope, override){
7556 Roo.EventObject.setEvent(e);
7557 fn.call(override ? scope || window : window, Roo.EventObject, scope);
7562 * Appends an event handler to an element (shorthand for addListener)
7563 * @param {String/HTMLElement} element The html element or id to assign the
7564 * @param {String} eventName The type of event to listen for
7565 * @param {Function} handler The method the event invokes
7566 * @param {Object} scope (optional) The scope in which to execute the handler
7567 * function. The handler function's "this" context.
7568 * @param {Object} options (optional) An object containing handler configuration
7569 * properties. This may contain any of the following properties:<ul>
7570 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
7571 * <li>delegate {String} A simple selector to filter the target or look for a descendant of the target</li>
7572 * <li>stopEvent {Boolean} True to stop the event. That is stop propagation, and prevent the default action.</li>
7573 * <li>preventDefault {Boolean} True to prevent the default action</li>
7574 * <li>stopPropagation {Boolean} True to prevent event propagation</li>
7575 * <li>normalized {Boolean} False to pass a browser event to the handler function instead of an Roo.EventObject</li>
7576 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
7577 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
7578 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
7579 * by the specified number of milliseconds. If the event fires again within that time, the original
7580 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
7583 * <b>Combining Options</b><br>
7584 * Using the options argument, it is possible to combine different types of listeners:<br>
7586 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)<div style="margin: 5px 20px 20px;">
7588 el.on('click', this.onClick, this, {
7595 * <b>Attaching multiple handlers in 1 call</b><br>
7596 * The method also allows for a single argument to be passed which is a config object containing properties
7597 * which specify multiple handlers.
7607 fn: this.onMouseOver
7616 * Or a shorthand syntax:<br>
7619 'click' : this.onClick,
7620 'mouseover' : this.onMouseOver,
7621 'mouseout' : this.onMouseOut
7625 addListener : function(element, eventName, fn, scope, options){
7626 if(typeof eventName == "object"){
7632 if(typeof o[e] == "function"){
7634 listen(element, e, o, o[e], o.scope);
7636 // individual options
7637 listen(element, e, o[e]);
7642 return listen(element, eventName, options, fn, scope);
7646 * Removes an event handler
7648 * @param {String/HTMLElement} element The id or html element to remove the
7650 * @param {String} eventName The type of event
7651 * @param {Function} fn
7652 * @return {Boolean} True if a listener was actually removed
7654 removeListener : function(element, eventName, fn){
7655 return stopListening(element, eventName, fn);
7659 * Fires when the document is ready (before onload and before images are loaded). Can be
7660 * accessed shorthanded Roo.onReady().
7661 * @param {Function} fn The method the event invokes
7662 * @param {Object} scope An object that becomes the scope of the handler
7663 * @param {boolean} options
7665 onDocumentReady : function(fn, scope, options){
7666 if(docReadyState){ // if it already fired
7667 docReadyEvent.addListener(fn, scope, options);
7668 docReadyEvent.fire();
7669 docReadyEvent.clearListeners();
7675 docReadyEvent.addListener(fn, scope, options);
7679 * Fires when the window is resized and provides resize event buffering (50 milliseconds), passes new viewport width and height to handlers.
7680 * @param {Function} fn The method the event invokes
7681 * @param {Object} scope An object that becomes the scope of the handler
7682 * @param {boolean} options
7684 onWindowResize : function(fn, scope, options)
7687 resizeEvent = new Roo.util.Event();
7688 resizeTask = new Roo.util.DelayedTask(function(){
7689 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
7691 E.on(window, "resize", function()
7694 resizeTask.delay(50);
7696 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
7700 resizeEvent.addListener(fn, scope, options);
7704 * Fires when the user changes the active text size. Handler gets called with 2 params, the old size and the new size.
7705 * @param {Function} fn The method the event invokes
7706 * @param {Object} scope An object that becomes the scope of the handler
7707 * @param {boolean} options
7709 onTextResize : function(fn, scope, options){
7711 textEvent = new Roo.util.Event();
7712 var textEl = new Roo.Element(document.createElement('div'));
7713 textEl.dom.className = 'x-text-resize';
7714 textEl.dom.innerHTML = 'X';
7715 textEl.appendTo(document.body);
7716 textSize = textEl.dom.offsetHeight;
7717 setInterval(function(){
7718 if(textEl.dom.offsetHeight != textSize){
7719 textEvent.fire(textSize, textSize = textEl.dom.offsetHeight);
7721 }, this.textResizeInterval);
7723 textEvent.addListener(fn, scope, options);
7727 * Removes the passed window resize listener.
7728 * @param {Function} fn The method the event invokes
7729 * @param {Object} scope The scope of handler
7731 removeResizeListener : function(fn, scope){
7733 resizeEvent.removeListener(fn, scope);
7738 fireResize : function(){
7740 resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
7744 * Url used for onDocumentReady with using SSL (defaults to Roo.SSL_SECURE_URL)
7748 * The frequency, in milliseconds, to check for text resize events (defaults to 50)
7750 textResizeInterval : 50
7755 * @scopeAlias pub=Roo.EventManager
7759 * Appends an event handler to an element (shorthand for addListener)
7760 * @param {String/HTMLElement} element The html element or id to assign the
7761 * @param {String} eventName The type of event to listen for
7762 * @param {Function} handler The method the event invokes
7763 * @param {Object} scope (optional) The scope in which to execute the handler
7764 * function. The handler function's "this" context.
7765 * @param {Object} options (optional) An object containing handler configuration
7766 * properties. This may contain any of the following properties:<ul>
7767 * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
7768 * <li>delegate {String} A simple selector to filter the target or look for a descendant of the target</li>
7769 * <li>stopEvent {Boolean} True to stop the event. That is stop propagation, and prevent the default action.</li>
7770 * <li>preventDefault {Boolean} True to prevent the default action</li>
7771 * <li>stopPropagation {Boolean} True to prevent event propagation</li>
7772 * <li>normalized {Boolean} False to pass a browser event to the handler function instead of an Roo.EventObject</li>
7773 * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
7774 * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
7775 * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.util.DelayedTask} delayed
7776 * by the specified number of milliseconds. If the event fires again within that time, the original
7777 * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
7780 * <b>Combining Options</b><br>
7781 * Using the options argument, it is possible to combine different types of listeners:<br>
7783 * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)<div style="margin: 5px 20px 20px;">
7785 el.on('click', this.onClick, this, {
7792 * <b>Attaching multiple handlers in 1 call</b><br>
7793 * The method also allows for a single argument to be passed which is a config object containing properties
7794 * which specify multiple handlers.
7804 fn: this.onMouseOver
7813 * Or a shorthand syntax:<br>
7816 'click' : this.onClick,
7817 'mouseover' : this.onMouseOver,
7818 'mouseout' : this.onMouseOut
7822 pub.on = pub.addListener;
7823 pub.un = pub.removeListener;
7825 pub.stoppedMouseDownEvent = new Roo.util.Event();
7829 * Fires when the document is ready (before onload and before images are loaded). Shorthand of {@link Roo.EventManager#onDocumentReady}.
7830 * @param {Function} fn The method the event invokes
7831 * @param {Object} scope An object that becomes the scope of the handler
7832 * @param {boolean} override If true, the obj passed in becomes
7833 * the execution scope of the listener
7837 Roo.onReady = Roo.EventManager.onDocumentReady;
7839 Roo.onReady(function(){
7840 var bd = Roo.get(document.body);
7845 : Roo.isIE11 ? "roo-ie11"
7846 : Roo.isEdge ? "roo-edge"
7847 : Roo.isGecko ? "roo-gecko"
7848 : Roo.isOpera ? "roo-opera"
7849 : Roo.isSafari ? "roo-safari" : ""];
7852 cls.push("roo-mac");
7855 cls.push("roo-linux");
7858 cls.push("roo-ios");
7861 cls.push("roo-touch");
7863 if(Roo.isBorderBox){
7864 cls.push('roo-border-box');
7866 if(Roo.isStrict){ // add to the parent to allow for selectors like ".ext-strict .ext-ie"
7867 var p = bd.dom.parentNode;
7869 p.className += ' roo-strict';
7872 bd.addClass(cls.join(' '));
7876 * @class Roo.EventObject
7877 * EventObject exposes the Yahoo! UI Event functionality directly on the object
7878 * passed to your event handler. It exists mostly for convenience. It also fixes the annoying null checks automatically to cleanup your code
7881 function handleClick(e){ // e is not a standard event object, it is a Roo.EventObject
7883 var target = e.getTarget();
7886 var myDiv = Roo.get("myDiv");
7887 myDiv.on("click", handleClick);
7889 Roo.EventManager.on("myDiv", 'click', handleClick);
7890 Roo.EventManager.addListener("myDiv", 'click', handleClick);
7894 Roo.EventObject = function(){
7896 var E = Roo.lib.Event;
7898 // safari keypress events for special keys return bad keycodes
7901 63235 : 39, // right
7904 63276 : 33, // page up
7905 63277 : 34, // page down
7906 63272 : 46, // delete
7911 // normalize button clicks
7912 var btnMap = Roo.isIE ? {1:0,4:1,2:2} :
7913 (Roo.isSafari ? {1:0,2:1,3:2} : {0:0,1:1,2:2});
7915 Roo.EventObjectImpl = function(e){
7917 this.setEvent(e.browserEvent || e);
7920 Roo.EventObjectImpl.prototype = {
7922 * Used to fix doc tools.
7923 * @scope Roo.EventObject.prototype
7929 /** The normal browser event */
7930 browserEvent : null,
7931 /** The button pressed in a mouse event */
7933 /** True if the shift key was down during the event */
7935 /** True if the control key was down during the event */
7937 /** True if the alt key was down during the event */
7996 setEvent : function(e){
7997 if(e == this || (e && e.browserEvent)){ // already wrapped
8000 this.browserEvent = e;
8002 // normalize buttons
8003 this.button = e.button ? btnMap[e.button] : (e.which ? e.which-1 : -1);
8004 if(e.type == 'click' && this.button == -1){
8008 this.shiftKey = e.shiftKey;
8009 // mac metaKey behaves like ctrlKey
8010 this.ctrlKey = e.ctrlKey || e.metaKey;
8011 this.altKey = e.altKey;
8012 // in getKey these will be normalized for the mac
8013 this.keyCode = e.keyCode;
8014 // keyup warnings on firefox.
8015 this.charCode = (e.type == 'keyup' || e.type == 'keydown') ? 0 : e.charCode;
8016 // cache the target for the delayed and or buffered events
8017 this.target = E.getTarget(e);
8019 this.xy = E.getXY(e);
8022 this.shiftKey = false;
8023 this.ctrlKey = false;
8024 this.altKey = false;
8034 * Stop the event (preventDefault and stopPropagation)
8036 stopEvent : function(){
8037 if(this.browserEvent){
8038 if(this.browserEvent.type == 'mousedown'){
8039 Roo.EventManager.stoppedMouseDownEvent.fire(this);
8041 E.stopEvent(this.browserEvent);
8046 * Prevents the browsers default handling of the event.
8048 preventDefault : function(){
8049 if(this.browserEvent){
8050 E.preventDefault(this.browserEvent);
8055 isNavKeyPress : function(){
8056 var k = this.keyCode;
8057 k = Roo.isSafari ? (safariKeys[k] || k) : k;
8058 return (k >= 33 && k <= 40) || k == this.RETURN || k == this.TAB || k == this.ESC;
8061 isSpecialKey : function(){
8062 var k = this.keyCode;
8063 return (this.type == 'keypress' && this.ctrlKey) || k == 9 || k == 13 || k == 40 || k == 27 ||
8064 (k == 16) || (k == 17) ||
8065 (k >= 18 && k <= 20) ||
8066 (k >= 33 && k <= 35) ||
8067 (k >= 36 && k <= 39) ||
8068 (k >= 44 && k <= 45);
8071 * Cancels bubbling of the event.
8073 stopPropagation : function(){
8074 if(this.browserEvent){
8075 if(this.type == 'mousedown'){
8076 Roo.EventManager.stoppedMouseDownEvent.fire(this);
8078 E.stopPropagation(this.browserEvent);
8083 * Gets the key code for the event.
8086 getCharCode : function(){
8087 return this.charCode || this.keyCode;
8091 * Returns a normalized keyCode for the event.
8092 * @return {Number} The key code
8094 getKey : function(){
8095 var k = this.keyCode || this.charCode;
8096 return Roo.isSafari ? (safariKeys[k] || k) : k;
8100 * Gets the x coordinate of the event.
8103 getPageX : function(){
8108 * Gets the y coordinate of the event.
8111 getPageY : function(){
8116 * Gets the time of the event.
8119 getTime : function(){
8120 if(this.browserEvent){
8121 return E.getTime(this.browserEvent);
8127 * Gets the page coordinates of the event.
8128 * @return {Array} The xy values like [x, y]
8135 * Gets the target for the event.
8136 * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target
8137 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
8138 search as a number or element (defaults to 10 || document.body)
8139 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
8140 * @return {HTMLelement}
8142 getTarget : function(selector, maxDepth, returnEl){
8143 return selector ? Roo.fly(this.target).findParent(selector, maxDepth, returnEl) : this.target;
8146 * Gets the related target.
8147 * @return {HTMLElement}
8149 getRelatedTarget : function(){
8150 if(this.browserEvent){
8151 return E.getRelatedTarget(this.browserEvent);
8157 * Normalizes mouse wheel delta across browsers
8158 * @return {Number} The delta
8160 getWheelDelta : function(){
8161 var e = this.browserEvent;
8163 if(e.wheelDelta){ /* IE/Opera. */
8164 delta = e.wheelDelta/120;
8165 }else if(e.detail){ /* Mozilla case. */
8166 delta = -e.detail/3;
8172 * Returns true if the control, meta, shift or alt key was pressed during this event.
8175 hasModifier : function(){
8176 return !!((this.ctrlKey || this.altKey) || this.shiftKey);
8180 * Returns true if the target of this event equals el or is a child of el
8181 * @param {String/HTMLElement/Element} el
8182 * @param {Boolean} related (optional) true to test if the related target is within el instead of the target
8185 within : function(el, related){
8186 var t = this[related ? "getRelatedTarget" : "getTarget"]();
8187 return t && Roo.fly(el).contains(t);
8190 getPoint : function(){
8191 return new Roo.lib.Point(this.xy[0], this.xy[1]);
8195 return new Roo.EventObjectImpl();
8200 * Ext JS Library 1.1.1
8201 * Copyright(c) 2006-2007, Ext JS, LLC.
8203 * Originally Released Under LGPL - original licence link has changed is not relivant.
8206 * <script type="text/javascript">
8210 // was in Composite Element!??!?!
8213 var D = Roo.lib.Dom;
8214 var E = Roo.lib.Event;
8215 var A = Roo.lib.Anim;
8217 // local style camelizing for speed
8219 var camelRe = /(-[a-z])/gi;
8220 var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); };
8221 var view = document.defaultView;
8224 * @class Roo.Element
8225 * Represents an Element in the DOM.<br><br>
8228 var el = Roo.get("my-div");
8231 var el = getEl("my-div");
8233 // or with a DOM element
8234 var el = Roo.get(myDivElement);
8236 * Using Roo.get() or getEl() instead of calling the constructor directly ensures you get the same object
8237 * each call instead of constructing a new one.<br><br>
8238 * <b>Animations</b><br />
8239 * Many of the functions for manipulating an element have an optional "animate" parameter. The animate parameter
8240 * should either be a boolean (true) or an object literal with animation options. The animation options are:
8242 Option Default Description
8243 --------- -------- ---------------------------------------------
8244 duration .35 The duration of the animation in seconds
8245 easing easeOut The YUI easing method
8246 callback none A function to execute when the anim completes
8247 scope this The scope (this) of the callback function
8249 * Also, the Anim object being used for the animation will be set on your options object as "anim", which allows you to stop or
8250 * manipulate the animation. Here's an example:
8252 var el = Roo.get("my-div");
8257 // default animation
8258 el.setWidth(100, true);
8260 // animation with some options set
8267 // using the "anim" property to get the Anim object
8273 el.setWidth(100, opt);
8275 if(opt.anim.isAnimated()){
8279 * <b> Composite (Collections of) Elements</b><br />
8280 * For working with collections of Elements, see <a href="Roo.CompositeElement.html">Roo.CompositeElement</a>
8281 * @constructor Create a new Element directly.
8282 * @param {String/HTMLElement} element
8283 * @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).
8285 Roo.Element = function(element, forceNew)
8287 var dom = typeof element == "string" ?
8288 document.getElementById(element) : element;
8290 this.listeners = {};
8292 if(!dom){ // invalid id/element
8296 if(forceNew !== true && id && Roo.Element.cache[id]){ // element object already exists
8297 return Roo.Element.cache[id];
8307 * The DOM element ID
8310 this.id = id || Roo.id(dom);
8312 return this; // assumed for cctor?
8315 var El = Roo.Element;
8319 * The element's default display mode (defaults to "")
8322 originalDisplay : "",
8325 // note this is overridden in BS version..
8328 * The default unit to append to CSS values where a unit isn't provided (defaults to px).
8334 * Sets the element's visibility mode. When setVisible() is called it
8335 * will use this to determine whether to set the visibility or the display property.
8336 * @param visMode Element.VISIBILITY or Element.DISPLAY
8337 * @return {Roo.Element} this
8339 setVisibilityMode : function(visMode){
8340 this.visibilityMode = visMode;
8344 * Convenience method for setVisibilityMode(Element.DISPLAY)
8345 * @param {String} display (optional) What to set display to when visible
8346 * @return {Roo.Element} this
8348 enableDisplayMode : function(display){
8349 this.setVisibilityMode(El.DISPLAY);
8350 if(typeof display != "undefined") { this.originalDisplay = display; }
8355 * 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)
8356 * @param {String} selector The simple selector to test
8357 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
8358 search as a number or element (defaults to 10 || document.body)
8359 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
8360 * @return {HTMLElement} The matching DOM node (or null if no match was found)
8362 findParent : function(simpleSelector, maxDepth, returnEl){
8363 var p = this.dom, b = document.body, depth = 0, dq = Roo.DomQuery, stopEl;
8364 maxDepth = maxDepth || 50;
8365 if(typeof maxDepth != "number"){
8366 stopEl = Roo.getDom(maxDepth);
8369 while(p && p.nodeType == 1 && depth < maxDepth && p != b && p != stopEl){
8370 if(dq.is(p, simpleSelector)){
8371 return returnEl ? Roo.get(p) : p;
8381 * Looks at parent nodes for a match of the passed simple selector (e.g. div.some-class or span:first-child)
8382 * @param {String} selector The simple selector to test
8383 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
8384 search as a number or element (defaults to 10 || document.body)
8385 * @param {Boolean} returnEl (optional) True to return a Roo.Element object instead of DOM node
8386 * @return {HTMLElement} The matching DOM node (or null if no match was found)
8388 findParentNode : function(simpleSelector, maxDepth, returnEl){
8389 var p = Roo.fly(this.dom.parentNode, '_internal');
8390 return p ? p.findParent(simpleSelector, maxDepth, returnEl) : null;
8394 * Looks at the scrollable parent element
8396 findScrollableParent : function()
8398 var overflowRegex = /(auto|scroll)/;
8400 if(this.getStyle('position') === 'fixed'){
8401 return Roo.isAndroid ? Roo.get(document.documentElement) : Roo.get(document.body);
8404 var excludeStaticParent = this.getStyle('position') === "absolute";
8406 for (var parent = this; (parent = Roo.get(parent.dom.parentNode));){
8408 if (excludeStaticParent && parent.getStyle('position') === "static") {
8412 if (overflowRegex.test(parent.getStyle('overflow') + parent.getStyle('overflow-x') + parent.getStyle('overflow-y'))){
8416 if(parent.dom.nodeName.toLowerCase() == 'body'){
8417 return Roo.isAndroid ? Roo.get(document.documentElement) : Roo.get(document.body);
8421 return Roo.isAndroid ? Roo.get(document.documentElement) : Roo.get(document.body);
8425 * Walks up the dom looking for a parent node that matches the passed simple selector (e.g. div.some-class or span:first-child).
8426 * This is a shortcut for findParentNode() that always returns an Roo.Element.
8427 * @param {String} selector The simple selector to test
8428 * @param {Number/String/HTMLElement/Element} maxDepth (optional) The max depth to
8429 search as a number or element (defaults to 10 || document.body)
8430 * @return {Roo.Element} The matching DOM node (or null if no match was found)
8432 up : function(simpleSelector, maxDepth){
8433 return this.findParentNode(simpleSelector, maxDepth, true);
8439 * Returns true if this element matches the passed simple selector (e.g. div.some-class or span:first-child)
8440 * @param {String} selector The simple selector to test
8441 * @return {Boolean} True if this element matches the selector, else false
8443 is : function(simpleSelector){
8444 return Roo.DomQuery.is(this.dom, simpleSelector);
8448 * Perform animation on this element.
8449 * @param {Object} args The YUI animation control args
8450 * @param {Float} duration (optional) How long the animation lasts in seconds (defaults to .35)
8451 * @param {Function} onComplete (optional) Function to call when animation completes
8452 * @param {String} easing (optional) Easing method to use (defaults to 'easeOut')
8453 * @param {String} animType (optional) 'run' is the default. Can also be 'color', 'motion', or 'scroll'
8454 * @return {Roo.Element} this
8456 animate : function(args, duration, onComplete, easing, animType){
8457 this.anim(args, {duration: duration, callback: onComplete, easing: easing}, animType);
8462 * @private Internal animation call
8464 anim : function(args, opt, animType, defaultDur, defaultEase, cb){
8465 animType = animType || 'run';
8467 var anim = Roo.lib.Anim[animType](
8469 (opt.duration || defaultDur) || .35,
8470 (opt.easing || defaultEase) || 'easeOut',
8472 Roo.callback(cb, this);
8473 Roo.callback(opt.callback, opt.scope || this, [this, opt]);
8481 // private legacy anim prep
8482 preanim : function(a, i){
8483 return !a[i] ? false : (typeof a[i] == "object" ? a[i]: {duration: a[i+1], callback: a[i+2], easing: a[i+3]});
8487 * Removes worthless text nodes
8488 * @param {Boolean} forceReclean (optional) By default the element
8489 * keeps track if it has been cleaned already so
8490 * you can call this over and over. However, if you update the element and
8491 * need to force a reclean, you can pass true.
8493 clean : function(forceReclean){
8494 if(this.isCleaned && forceReclean !== true){
8498 var d = this.dom, n = d.firstChild, ni = -1;
8500 var nx = n.nextSibling;
8501 if(n.nodeType == 3 && !ns.test(n.nodeValue)){
8508 this.isCleaned = true;
8513 calcOffsetsTo : function(el){
8516 var restorePos = false;
8517 if(el.getStyle('position') == 'static'){
8518 el.position('relative');
8523 while(op && op != d && op.tagName != 'HTML'){
8526 op = op.offsetParent;
8529 el.position('static');
8535 * Scrolls this element into view within the passed container.
8536 * @param {String/HTMLElement/Element} container (optional) The container element to scroll (defaults to document.body)
8537 * @param {Boolean} hscroll (optional) False to disable horizontal scroll (defaults to true)
8538 * @return {Roo.Element} this
8540 scrollIntoView : function(container, hscroll){
8541 var c = Roo.getDom(container) || document.body;
8544 var o = this.calcOffsetsTo(c),
8547 b = t+el.offsetHeight,
8548 r = l+el.offsetWidth;
8550 var ch = c.clientHeight;
8551 var ct = parseInt(c.scrollTop, 10);
8552 var cl = parseInt(c.scrollLeft, 10);
8554 var cr = cl + c.clientWidth;
8562 if(hscroll !== false){
8566 c.scrollLeft = r-c.clientWidth;
8573 scrollChildIntoView : function(child, hscroll){
8574 Roo.fly(child, '_scrollChildIntoView').scrollIntoView(this, hscroll);
8578 * Measures the element's content height and updates height to match. Note: this function uses setTimeout so
8579 * the new height may not be available immediately.
8580 * @param {Boolean} animate (optional) Animate the transition (defaults to false)
8581 * @param {Float} duration (optional) Length of the animation in seconds (defaults to .35)
8582 * @param {Function} onComplete (optional) Function to call when animation completes
8583 * @param {String} easing (optional) Easing method to use (defaults to easeOut)
8584 * @return {Roo.Element} this
8586 autoHeight : function(animate, duration, onComplete, easing){
8587 var oldHeight = this.getHeight();
8589 this.setHeight(1); // force clipping
8590 setTimeout(function(){
8591 var height = parseInt(this.dom.scrollHeight, 10); // parseInt for Safari
8593 this.setHeight(height);
8595 if(typeof onComplete == "function"){
8599 this.setHeight(oldHeight); // restore original height
8600 this.setHeight(height, animate, duration, function(){
8602 if(typeof onComplete == "function") { onComplete(); }
8603 }.createDelegate(this), easing);
8605 }.createDelegate(this), 0);
8610 * Returns true if this element is an ancestor of the passed element
8611 * @param {HTMLElement/String} el The element to check
8612 * @return {Boolean} True if this element is an ancestor of el, else false
8614 contains : function(el){
8615 if(!el){return false;}
8616 return D.isAncestor(this.dom, el.dom ? el.dom : el);
8620 * Checks whether the element is currently visible using both visibility and display properties.
8621 * @param {Boolean} deep (optional) True to walk the dom and see if parent elements are hidden (defaults to false)
8622 * @return {Boolean} True if the element is currently visible, else false
8624 isVisible : function(deep) {
8625 var vis = !(this.getStyle("visibility") == "hidden" || this.getStyle("display") == "none");
8626 if(deep !== true || !vis){
8629 var p = this.dom.parentNode;
8630 while(p && p.tagName.toLowerCase() != "body"){
8631 if(!Roo.fly(p, '_isVisible').isVisible()){
8640 * Creates a {@link Roo.CompositeElement} for child nodes based on the passed CSS selector (the selector should not contain an id).
8641 * @param {String} selector The CSS selector
8642 * @param {Boolean} unique (optional) True to create a unique Roo.Element for each child (defaults to false, which creates a single shared flyweight object)
8643 * @return {CompositeElement/CompositeElementLite} The composite element
8645 select : function(selector, unique){
8646 return El.select(selector, unique, this.dom);
8650 * Selects child nodes based on the passed CSS selector (the selector should not contain an id).
8651 * @param {String} selector The CSS selector
8652 * @return {Array} An array of the matched nodes
8654 query : function(selector, unique){
8655 return Roo.DomQuery.select(selector, this.dom);
8659 * Selects a single child at any depth below this element based on the passed CSS selector (the selector should not contain an id).
8660 * @param {String} selector The CSS selector
8661 * @param {Boolean} returnDom (optional) True to return the DOM node instead of Roo.Element (defaults to false)
8662 * @return {HTMLElement/Roo.Element} The child Roo.Element (or DOM node if returnDom = true)
8664 child : function(selector, returnDom){
8665 var n = Roo.DomQuery.selectNode(selector, this.dom);
8666 return returnDom ? n : Roo.get(n);
8670 * Selects a single *direct* child based on the passed CSS selector (the selector should not contain an id).
8671 * @param {String} selector The CSS selector
8672 * @param {Boolean} returnDom (optional) True to return the DOM node instead of Roo.Element (defaults to false)
8673 * @return {HTMLElement/Roo.Element} The child Roo.Element (or DOM node if returnDom = true)
8675 down : function(selector, returnDom){
8676 var n = Roo.DomQuery.selectNode(" > " + selector, this.dom);
8677 return returnDom ? n : Roo.get(n);
8681 * Initializes a {@link Roo.dd.DD} drag drop object for this element.
8682 * @param {String} group The group the DD object is member of
8683 * @param {Object} config The DD config object
8684 * @param {Object} overrides An object containing methods to override/implement on the DD object
8685 * @return {Roo.dd.DD} The DD object
8687 initDD : function(group, config, overrides){
8688 var dd = new Roo.dd.DD(Roo.id(this.dom), group, config);
8689 return Roo.apply(dd, overrides);
8693 * Initializes a {@link Roo.dd.DDProxy} object for this element.
8694 * @param {String} group The group the DDProxy object is member of
8695 * @param {Object} config The DDProxy config object
8696 * @param {Object} overrides An object containing methods to override/implement on the DDProxy object
8697 * @return {Roo.dd.DDProxy} The DDProxy object
8699 initDDProxy : function(group, config, overrides){
8700 var dd = new Roo.dd.DDProxy(Roo.id(this.dom), group, config);
8701 return Roo.apply(dd, overrides);
8705 * Initializes a {@link Roo.dd.DDTarget} object for this element.
8706 * @param {String} group The group the DDTarget object is member of
8707 * @param {Object} config The DDTarget config object
8708 * @param {Object} overrides An object containing methods to override/implement on the DDTarget object
8709 * @return {Roo.dd.DDTarget} The DDTarget object
8711 initDDTarget : function(group, config, overrides){
8712 var dd = new Roo.dd.DDTarget(Roo.id(this.dom), group, config);
8713 return Roo.apply(dd, overrides);
8717 * Sets the visibility of the element (see details). If the visibilityMode is set to Element.DISPLAY, it will use
8718 * the display property to hide the element, otherwise it uses visibility. The default is to hide and show using the visibility property.
8719 * @param {Boolean} visible Whether the element is visible
8720 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8721 * @return {Roo.Element} this
8723 setVisible : function(visible, animate){
8725 if(this.visibilityMode == El.DISPLAY){
8726 this.setDisplayed(visible);
8729 this.dom.style.visibility = visible ? "visible" : "hidden";
8732 // closure for composites
8734 var visMode = this.visibilityMode;
8736 this.setOpacity(.01);
8737 this.setVisible(true);
8739 this.anim({opacity: { to: (visible?1:0) }},
8740 this.preanim(arguments, 1),
8741 null, .35, 'easeIn', function(){
8743 if(visMode == El.DISPLAY){
8744 dom.style.display = "none";
8746 dom.style.visibility = "hidden";
8748 Roo.get(dom).setOpacity(1);
8756 * Returns true if display is not "none"
8759 isDisplayed : function() {
8760 return this.getStyle("display") != "none";
8764 * Toggles the element's visibility or display, depending on visibility mode.
8765 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
8766 * @return {Roo.Element} this
8768 toggle : function(animate){
8769 this.setVisible(!this.isVisible(), this.preanim(arguments, 0));
8774 * Sets the CSS display property. Uses originalDisplay if the specified value is a boolean true.
8775 * @param {Boolean} value Boolean value to display the element using its default display, or a string to set the display directly
8776 * @return {Roo.Element} this
8778 setDisplayed : function(value) {
8779 if(typeof value == "boolean"){
8780 value = value ? this.originalDisplay : "none";
8782 this.setStyle("display", value);
8787 * Tries to focus the element. Any exceptions are caught and ignored.
8788 * @return {Roo.Element} this
8790 focus : function() {
8798 * Tries to blur the element. Any exceptions are caught and ignored.
8799 * @return {Roo.Element} this
8809 * Adds one or more CSS classes to the element. Duplicate classes are automatically filtered out.
8810 * @param {String/Array} className The CSS class to add, or an array of classes
8811 * @return {Roo.Element} this
8813 addClass : function(className){
8814 if(className instanceof Array){
8815 for(var i = 0, len = className.length; i < len; i++) {
8816 this.addClass(className[i]);
8819 if(className && !this.hasClass(className)){
8820 if (this.dom instanceof SVGElement) {
8821 this.dom.className.baseVal =this.dom.className.baseVal + " " + className;
8823 this.dom.className = this.dom.className + " " + className;
8831 * Adds one or more CSS classes to this element and removes the same class(es) from all siblings.
8832 * @param {String/Array} className The CSS class to add, or an array of classes
8833 * @return {Roo.Element} this
8835 radioClass : function(className){
8836 var siblings = this.dom.parentNode.childNodes;
8837 for(var i = 0; i < siblings.length; i++) {
8838 var s = siblings[i];
8839 if(s.nodeType == 1){
8840 Roo.get(s).removeClass(className);
8843 this.addClass(className);
8848 * Removes one or more CSS classes from the element.
8849 * @param {String/Array} className The CSS class to remove, or an array of classes
8850 * @return {Roo.Element} this
8852 removeClass : function(className){
8854 var cn = this.dom instanceof SVGElement ? this.dom.className.baseVal : this.dom.className;
8855 if(!className || !cn){
8858 if(className instanceof Array){
8859 for(var i = 0, len = className.length; i < len; i++) {
8860 this.removeClass(className[i]);
8863 if(this.hasClass(className)){
8864 var re = this.classReCache[className];
8866 re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)', "g");
8867 this.classReCache[className] = re;
8869 if (this.dom instanceof SVGElement) {
8870 this.dom.className.baseVal = cn.replace(re, " ");
8872 this.dom.className = cn.replace(re, " ");
8883 * Toggles the specified CSS class on this element (removes it if it already exists, otherwise adds it).
8884 * @param {String} className The CSS class to toggle
8885 * @return {Roo.Element} this
8887 toggleClass : function(className){
8888 if(this.hasClass(className)){
8889 this.removeClass(className);
8891 this.addClass(className);
8897 * Checks if the specified CSS class exists on this element's DOM node.
8898 * @param {String} className The CSS class to check for
8899 * @return {Boolean} True if the class exists, else false
8901 hasClass : function(className){
8902 if (this.dom instanceof SVGElement) {
8903 return className && (' '+this.dom.className.baseVal +' ').indexOf(' '+className+' ') != -1;
8905 return className && (' '+this.dom.className+' ').indexOf(' '+className+' ') != -1;
8909 * Replaces a CSS class on the element with another. If the old name does not exist, the new name will simply be added.
8910 * @param {String} oldClassName The CSS class to replace
8911 * @param {String} newClassName The replacement CSS class
8912 * @return {Roo.Element} this
8914 replaceClass : function(oldClassName, newClassName){
8915 this.removeClass(oldClassName);
8916 this.addClass(newClassName);
8921 * Returns an object with properties matching the styles requested.
8922 * For example, el.getStyles('color', 'font-size', 'width') might return
8923 * {'color': '#FFFFFF', 'font-size': '13px', 'width': '100px'}.
8924 * @param {String} style1 A style name
8925 * @param {String} style2 A style name
8926 * @param {String} etc.
8927 * @return {Object} The style object
8929 getStyles : function(){
8930 var a = arguments, len = a.length, r = {};
8931 for(var i = 0; i < len; i++){
8932 r[a[i]] = this.getStyle(a[i]);
8938 * Normalizes currentStyle and computedStyle. This is not YUI getStyle, it is an optimised version.
8939 * @param {String} property The style property whose value is returned.
8940 * @return {String} The current value of the style property for this element.
8942 getStyle : function(){
8943 return view && view.getComputedStyle ?
8945 var el = this.dom, v, cs, camel;
8946 if(prop == 'float'){
8949 if(el.style && (v = el.style[prop])){
8952 if(cs = view.getComputedStyle(el, "")){
8953 if(!(camel = propCache[prop])){
8954 camel = propCache[prop] = prop.replace(camelRe, camelFn);
8961 var el = this.dom, v, cs, camel;
8962 if(prop == 'opacity'){
8963 if(typeof el.style.filter == 'string'){
8964 var m = el.style.filter.match(/alpha\(opacity=(.*)\)/i);
8966 var fv = parseFloat(m[1]);
8968 return fv ? fv / 100 : 0;
8973 }else if(prop == 'float'){
8974 prop = "styleFloat";
8976 if(!(camel = propCache[prop])){
8977 camel = propCache[prop] = prop.replace(camelRe, camelFn);
8979 if(v = el.style[camel]){
8982 if(cs = el.currentStyle){
8990 * Wrapper for setting style properties, also takes single object parameter of multiple styles.
8991 * @param {String/Object} property The style property to be set, or an object of multiple styles.
8992 * @param {String} value (optional) The value to apply to the given property, or null if an object was passed.
8993 * @return {Roo.Element} this
8995 setStyle : function(prop, value){
8996 if(typeof prop == "string"){
8998 if (prop == 'float') {
8999 this.setStyle(Roo.isIE ? 'styleFloat' : 'cssFloat', value);
9004 if(!(camel = propCache[prop])){
9005 camel = propCache[prop] = prop.replace(camelRe, camelFn);
9008 if(camel == 'opacity') {
9009 this.setOpacity(value);
9011 this.dom.style[camel] = value;
9014 for(var style in prop){
9015 if(typeof prop[style] != "function"){
9016 this.setStyle(style, prop[style]);
9024 * More flexible version of {@link #setStyle} for setting style properties.
9025 * @param {String/Object/Function} styles A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
9026 * a function which returns such a specification.
9027 * @return {Roo.Element} this
9029 applyStyles : function(style){
9030 Roo.DomHelper.applyStyles(this.dom, style);
9035 * 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).
9036 * @return {Number} The X position of the element
9039 return D.getX(this.dom);
9043 * 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).
9044 * @return {Number} The Y position of the element
9047 return D.getY(this.dom);
9051 * 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).
9052 * @return {Array} The XY position of the element
9055 return D.getXY(this.dom);
9059 * 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).
9060 * @param {Number} The X position of the element
9061 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
9062 * @return {Roo.Element} this
9064 setX : function(x, animate){
9066 D.setX(this.dom, x);
9068 this.setXY([x, this.getY()], this.preanim(arguments, 1));
9074 * 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).
9075 * @param {Number} The Y position of the element
9076 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
9077 * @return {Roo.Element} this
9079 setY : function(y, animate){
9081 D.setY(this.dom, y);
9083 this.setXY([this.getX(), y], this.preanim(arguments, 1));
9089 * Sets the element's left position directly using CSS style (instead of {@link #setX}).
9090 * @param {String} left The left CSS property value
9091 * @return {Roo.Element} this
9093 setLeft : function(left){
9094 this.setStyle("left", this.addUnits(left));
9099 * Sets the element's top position directly using CSS style (instead of {@link #setY}).
9100 * @param {String} top The top CSS property value
9101 * @return {Roo.Element} this
9103 setTop : function(top){
9104 this.setStyle("top", this.addUnits(top));
9109 * Sets the element's CSS right style.
9110 * @param {String} right The right CSS property value
9111 * @return {Roo.Element} this
9113 setRight : function(right){
9114 this.setStyle("right", this.addUnits(right));
9119 * Sets the element's CSS bottom style.
9120 * @param {String} bottom The bottom CSS property value
9121 * @return {Roo.Element} this
9123 setBottom : function(bottom){
9124 this.setStyle("bottom", this.addUnits(bottom));
9129 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
9130 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
9131 * @param {Array} pos Contains X & Y [x, y] values for new position (coordinates are page-based)
9132 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
9133 * @return {Roo.Element} this
9135 setXY : function(pos, animate){
9137 D.setXY(this.dom, pos);
9139 this.anim({points: {to: pos}}, this.preanim(arguments, 1), 'motion');
9145 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
9146 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
9147 * @param {Number} x X value for new position (coordinates are page-based)
9148 * @param {Number} y Y value for new position (coordinates are page-based)
9149 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
9150 * @return {Roo.Element} this
9152 setLocation : function(x, y, animate){
9153 this.setXY([x, y], this.preanim(arguments, 2));
9158 * Sets the position of the element in page coordinates, regardless of how the element is positioned.
9159 * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
9160 * @param {Number} x X value for new position (coordinates are page-based)
9161 * @param {Number} y Y value for new position (coordinates are page-based)
9162 * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
9163 * @return {Roo.Element} this
9165 moveTo : function(x, y, animate){
9166 this.setXY([x, y], this.preanim(arguments, 2));
9171 * Returns the region of the given element.
9172 * The element must be part of the DOM tree to have a region (display:none or elements not appended return false).
9173 * @return {Region} A Roo.lib.Region containing "top, left, bottom, right" member data.
9175 getRegion : function(){
9176 return D.getRegion(this.dom);
9180 * Returns the offset height of the element
9181 * @param {Boolean} contentHeight (optional) true to get the height minus borders and padding
9182 * @return {Number} The element's height
9184 getHeight : function(contentHeight){
9185 var h = this.dom.offsetHeight || 0;
9186 return contentHeight !== true ? h : h-this.getBorderWidth("tb")-this.getPadding("tb");
9190 * Returns the offset width of the element
9191 * @param {Boolean} contentWidth (optional) true to get the width minus borders and padding
9192 * @return {Number} The element's width
9194 getWidth : function(contentWidth){
9195 var w = this.dom.offsetWidth || 0;
9196 return contentWidth !== true ? w : w-this.getBorderWidth("lr")-this.getPadding("lr");
9200 * Returns either the offsetHeight or the height of this element based on CSS height adjusted by padding or borders
9201 * when needed to simulate offsetHeight when offsets aren't available. This may not work on display:none elements
9202 * if a height has not been set using CSS.
9205 getComputedHeight : function(){
9206 var h = Math.max(this.dom.offsetHeight, this.dom.clientHeight);
9208 h = parseInt(this.getStyle('height'), 10) || 0;
9209 if(!this.isBorderBox()){
9210 h += this.getFrameWidth('tb');
9217 * Returns either the offsetWidth or the width of this element based on CSS width adjusted by padding or borders
9218 * when needed to simulate offsetWidth when offsets aren't available. This may not work on display:none elements
9219 * if a width has not been set using CSS.
9222 getComputedWidth : function(){
9223 var w = Math.max(this.dom.offsetWidth, this.dom.clientWidth);
9225 w = parseInt(this.getStyle('width'), 10) || 0;
9226 if(!this.isBorderBox()){
9227 w += this.getFrameWidth('lr');
9234 * Returns the size of the element.
9235 * @param {Boolean} contentSize (optional) true to get the width/size minus borders and padding
9236 * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
9238 getSize : function(contentSize){
9239 return {width: this.getWidth(contentSize), height: this.getHeight(contentSize)};
9243 * Returns the width and height of the viewport.
9244 * @return {Object} An object containing the viewport's size {width: (viewport width), height: (viewport height)}
9246 getViewSize : function(){
9247 var d = this.dom, doc = document, aw = 0, ah = 0;
9248 if(d == doc || d == doc.body){
9249 return {width : D.getViewWidth(), height: D.getViewHeight()};
9252 width : d.clientWidth,
9253 height: d.clientHeight
9259 * Returns the value of the "value" attribute
9260 * @param {Boolean} asNumber true to parse the value as a number
9261 * @return {String/Number}
9263 getValue : function(asNumber){
9264 return asNumber ? parseInt(this.dom.value, 10) : this.dom.value;
9268 adjustWidth : function(width){
9269 if(typeof width == "number"){
9270 if(this.autoBoxAdjust && !this.isBorderBox()){
9271 width -= (this.getBorderWidth("lr") + this.getPadding("lr"));
9281 adjustHeight : function(height){
9282 if(typeof height == "number"){
9283 if(this.autoBoxAdjust && !this.isBorderBox()){
9284 height -= (this.getBorderWidth("tb") + this.getPadding("tb"));
9294 * Set the width of the element
9295 * @param {Number} width The new width
9296 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9297 * @return {Roo.Element} this
9299 setWidth : function(width, animate){
9300 width = this.adjustWidth(width);
9302 this.dom.style.width = this.addUnits(width);
9304 this.anim({width: {to: width}}, this.preanim(arguments, 1));
9310 * Set the height of the element
9311 * @param {Number} height The new height
9312 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9313 * @return {Roo.Element} this
9315 setHeight : function(height, animate){
9316 height = this.adjustHeight(height);
9318 this.dom.style.height = this.addUnits(height);
9320 this.anim({height: {to: height}}, this.preanim(arguments, 1));
9326 * Set the size of the element. If animation is true, both width an height will be animated concurrently.
9327 * @param {Number} width The new width
9328 * @param {Number} height The new height
9329 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9330 * @return {Roo.Element} this
9332 setSize : function(width, height, animate){
9333 if(typeof width == "object"){ // in case of object from getSize()
9334 height = width.height; width = width.width;
9336 width = this.adjustWidth(width); height = this.adjustHeight(height);
9338 this.dom.style.width = this.addUnits(width);
9339 this.dom.style.height = this.addUnits(height);
9341 this.anim({width: {to: width}, height: {to: height}}, this.preanim(arguments, 2));
9347 * Sets the element's position and size in one shot. If animation is true then width, height, x and y will be animated concurrently.
9348 * @param {Number} x X value for new position (coordinates are page-based)
9349 * @param {Number} y Y value for new position (coordinates are page-based)
9350 * @param {Number} width The new width
9351 * @param {Number} height The new height
9352 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9353 * @return {Roo.Element} this
9355 setBounds : function(x, y, width, height, animate){
9357 this.setSize(width, height);
9358 this.setLocation(x, y);
9360 width = this.adjustWidth(width); height = this.adjustHeight(height);
9361 this.anim({points: {to: [x, y]}, width: {to: width}, height: {to: height}},
9362 this.preanim(arguments, 4), 'motion');
9368 * 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.
9369 * @param {Roo.lib.Region} region The region to fill
9370 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9371 * @return {Roo.Element} this
9373 setRegion : function(region, animate){
9374 this.setBounds(region.left, region.top, region.right-region.left, region.bottom-region.top, this.preanim(arguments, 1));
9379 * Appends an event handler
9381 * @param {String} eventName The type of event to append
9382 * @param {Function} fn The method the event invokes
9383 * @param {Object} scope (optional) The scope (this object) of the fn
9384 * @param {Object} options (optional)An object with standard {@link Roo.EventManager#addListener} options
9386 addListener : function(eventName, fn, scope, options)
9388 if (eventName == 'dblclick') { // doublclick (touchstart) - faked on touch.
9389 this.addListener('touchstart', this.onTapHandler, this);
9392 // we need to handle a special case where dom element is a svg element.
9393 // in this case we do not actua
9398 if (this.dom instanceof SVGElement && !(this.dom instanceof SVGSVGElement)) {
9399 if (typeof(this.listeners[eventName]) == 'undefined') {
9400 this.listeners[eventName] = new Roo.util.Event(this, eventName);
9402 this.listeners[eventName].addListener(fn, scope, options);
9407 Roo.EventManager.on(this.dom, eventName, fn, scope || this, options);
9412 onTapHandler : function(event)
9414 if(!this.tapedTwice) {
9415 this.tapedTwice = true;
9417 setTimeout( function() {
9418 s.tapedTwice = false;
9422 event.preventDefault();
9423 var revent = new MouseEvent('dblclick', {
9429 this.dom.dispatchEvent(revent);
9430 //action on double tap goes below
9435 * Removes an event handler from this element
9436 * @param {String} eventName the type of event to remove
9437 * @param {Function} fn the method the event invokes
9438 * @param {Function} scope (needed for svg fake listeners)
9439 * @return {Roo.Element} this
9441 removeListener : function(eventName, fn, scope){
9442 Roo.EventManager.removeListener(this.dom, eventName, fn);
9443 if (typeof(this.listeners) == 'undefined' || typeof(this.listeners[eventName]) == 'undefined') {
9446 this.listeners[eventName].removeListener(fn, scope);
9451 * Removes all previous added listeners from this element
9452 * @return {Roo.Element} this
9454 removeAllListeners : function(){
9455 E.purgeElement(this.dom);
9456 this.listeners = {};
9460 relayEvent : function(eventName, observable){
9461 this.on(eventName, function(e){
9462 observable.fireEvent(eventName, e);
9468 * Set the opacity of the element
9469 * @param {Float} opacity The new opacity. 0 = transparent, .5 = 50% visibile, 1 = fully visible, etc
9470 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9471 * @return {Roo.Element} this
9473 setOpacity : function(opacity, animate){
9475 var s = this.dom.style;
9478 s.filter = (s.filter || '').replace(/alpha\([^\)]*\)/gi,"") +
9479 (opacity == 1 ? "" : "alpha(opacity=" + opacity * 100 + ")");
9481 s.opacity = opacity;
9484 this.anim({opacity: {to: opacity}}, this.preanim(arguments, 1), null, .35, 'easeIn');
9490 * Gets the left X coordinate
9491 * @param {Boolean} local True to get the local css position instead of page coordinate
9494 getLeft : function(local){
9498 return parseInt(this.getStyle("left"), 10) || 0;
9503 * Gets the right X coordinate of the element (element X position + element width)
9504 * @param {Boolean} local True to get the local css position instead of page coordinate
9507 getRight : function(local){
9509 return this.getX() + this.getWidth();
9511 return (this.getLeft(true) + this.getWidth()) || 0;
9516 * Gets the top Y coordinate
9517 * @param {Boolean} local True to get the local css position instead of page coordinate
9520 getTop : function(local) {
9524 return parseInt(this.getStyle("top"), 10) || 0;
9529 * Gets the bottom Y coordinate of the element (element Y position + element height)
9530 * @param {Boolean} local True to get the local css position instead of page coordinate
9533 getBottom : function(local){
9535 return this.getY() + this.getHeight();
9537 return (this.getTop(true) + this.getHeight()) || 0;
9542 * Initializes positioning on this element. If a desired position is not passed, it will make the
9543 * the element positioned relative IF it is not already positioned.
9544 * @param {String} pos (optional) Positioning to use "relative", "absolute" or "fixed"
9545 * @param {Number} zIndex (optional) The zIndex to apply
9546 * @param {Number} x (optional) Set the page X position
9547 * @param {Number} y (optional) Set the page Y position
9549 position : function(pos, zIndex, x, y){
9551 if(this.getStyle('position') == 'static'){
9552 this.setStyle('position', 'relative');
9555 this.setStyle("position", pos);
9558 this.setStyle("z-index", zIndex);
9560 if(x !== undefined && y !== undefined){
9562 }else if(x !== undefined){
9564 }else if(y !== undefined){
9570 * Clear positioning back to the default when the document was loaded
9571 * @param {String} value (optional) The value to use for the left,right,top,bottom, defaults to '' (empty string). You could use 'auto'.
9572 * @return {Roo.Element} this
9574 clearPositioning : function(value){
9582 "position" : "static"
9588 * Gets an object with all CSS positioning properties. Useful along with setPostioning to get
9589 * snapshot before performing an update and then restoring the element.
9592 getPositioning : function(){
9593 var l = this.getStyle("left");
9594 var t = this.getStyle("top");
9596 "position" : this.getStyle("position"),
9598 "right" : l ? "" : this.getStyle("right"),
9600 "bottom" : t ? "" : this.getStyle("bottom"),
9601 "z-index" : this.getStyle("z-index")
9606 * Gets the width of the border(s) for the specified side(s)
9607 * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
9608 * passing lr would get the border (l)eft width + the border (r)ight width.
9609 * @return {Number} The width of the sides passed added together
9611 getBorderWidth : function(side){
9612 return this.addStyles(side, El.borders);
9616 * Gets the width of the padding(s) for the specified side(s)
9617 * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example,
9618 * passing lr would get the padding (l)eft + the padding (r)ight.
9619 * @return {Number} The padding of the sides passed added together
9621 getPadding : function(side){
9622 return this.addStyles(side, El.paddings);
9626 * Set positioning with an object returned by getPositioning().
9627 * @param {Object} posCfg
9628 * @return {Roo.Element} this
9630 setPositioning : function(pc){
9631 this.applyStyles(pc);
9632 if(pc.right == "auto"){
9633 this.dom.style.right = "";
9635 if(pc.bottom == "auto"){
9636 this.dom.style.bottom = "";
9642 fixDisplay : function(){
9643 if(this.getStyle("display") == "none"){
9644 this.setStyle("visibility", "hidden");
9645 this.setStyle("display", this.originalDisplay); // first try reverting to default
9646 if(this.getStyle("display") == "none"){ // if that fails, default to block
9647 this.setStyle("display", "block");
9653 * Quick set left and top adding default units
9654 * @param {String} left The left CSS property value
9655 * @param {String} top The top CSS property value
9656 * @return {Roo.Element} this
9658 setLeftTop : function(left, top){
9659 this.dom.style.left = this.addUnits(left);
9660 this.dom.style.top = this.addUnits(top);
9665 * Move this element relative to its current position.
9666 * @param {String} direction Possible values are: "l","left" - "r","right" - "t","top","up" - "b","bottom","down".
9667 * @param {Number} distance How far to move the element in pixels
9668 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9669 * @return {Roo.Element} this
9671 move : function(direction, distance, animate){
9672 var xy = this.getXY();
9673 direction = direction.toLowerCase();
9677 this.moveTo(xy[0]-distance, xy[1], this.preanim(arguments, 2));
9681 this.moveTo(xy[0]+distance, xy[1], this.preanim(arguments, 2));
9686 this.moveTo(xy[0], xy[1]-distance, this.preanim(arguments, 2));
9691 this.moveTo(xy[0], xy[1]+distance, this.preanim(arguments, 2));
9698 * Store the current overflow setting and clip overflow on the element - use {@link #unclip} to remove
9699 * @return {Roo.Element} this
9702 if(!this.isClipped){
9703 this.isClipped = true;
9704 this.originalClip = {
9705 "o": this.getStyle("overflow"),
9706 "x": this.getStyle("overflow-x"),
9707 "y": this.getStyle("overflow-y")
9709 this.setStyle("overflow", "hidden");
9710 this.setStyle("overflow-x", "hidden");
9711 this.setStyle("overflow-y", "hidden");
9717 * Return clipping (overflow) to original clipping before clip() was called
9718 * @return {Roo.Element} this
9720 unclip : function(){
9722 this.isClipped = false;
9723 var o = this.originalClip;
9724 if(o.o){this.setStyle("overflow", o.o);}
9725 if(o.x){this.setStyle("overflow-x", o.x);}
9726 if(o.y){this.setStyle("overflow-y", o.y);}
9733 * Gets the x,y coordinates specified by the anchor position on the element.
9734 * @param {String} anchor (optional) The specified anchor position (defaults to "c"). See {@link #alignTo} for details on supported anchor positions.
9735 * @param {Object} size (optional) An object containing the size to use for calculating anchor position
9736 * {width: (target width), height: (target height)} (defaults to the element's current size)
9737 * @param {Boolean} local (optional) True to get the local (element top/left-relative) anchor position instead of page coordinates
9738 * @return {Array} [x, y] An array containing the element's x and y coordinates
9740 getAnchorXY : function(anchor, local, s){
9741 //Passing a different size is useful for pre-calculating anchors,
9742 //especially for anchored animations that change the el size.
9744 var w, h, vp = false;
9747 if(d == document.body || d == document){
9749 w = D.getViewWidth(); h = D.getViewHeight();
9751 w = this.getWidth(); h = this.getHeight();
9754 w = s.width; h = s.height;
9756 var x = 0, y = 0, r = Math.round;
9757 switch((anchor || "tl").toLowerCase()){
9799 var sc = this.getScroll();
9800 return [x + sc.left, y + sc.top];
9802 //Add the element's offset xy
9803 var o = this.getXY();
9804 return [x+o[0], y+o[1]];
9808 * Gets the x,y coordinates to align this element with another element. See {@link #alignTo} for more info on the
9809 * supported position values.
9810 * @param {String/HTMLElement/Roo.Element} element The element to align to.
9811 * @param {String} position The position to align to.
9812 * @param {Array} offsets (optional) Offset the positioning by [x, y]
9813 * @return {Array} [x, y]
9815 getAlignToXY : function(el, p, o)
9820 throw "Element.alignTo with an element that doesn't exist";
9822 var c = false; //constrain to viewport
9823 var p1 = "", p2 = "";
9830 }else if(p.indexOf("-") == -1){
9833 p = p.toLowerCase();
9834 var m = p.match(/^([a-z]+)-([a-z]+)(\?)?$/);
9836 throw "Element.alignTo with an invalid alignment " + p;
9838 p1 = m[1]; p2 = m[2]; c = !!m[3];
9840 //Subtract the aligned el's internal xy from the target's offset xy
9841 //plus custom offset to get the aligned el's new offset xy
9842 var a1 = this.getAnchorXY(p1, true);
9843 var a2 = el.getAnchorXY(p2, false);
9844 var x = a2[0] - a1[0] + o[0];
9845 var y = a2[1] - a1[1] + o[1];
9847 //constrain the aligned el to viewport if necessary
9848 var w = this.getWidth(), h = this.getHeight(), r = el.getRegion();
9849 // 5px of margin for ie
9850 var dw = D.getViewWidth()-5, dh = D.getViewHeight()-5;
9852 //If we are at a viewport boundary and the aligned el is anchored on a target border that is
9853 //perpendicular to the vp border, allow the aligned el to slide on that border,
9854 //otherwise swap the aligned el to the opposite border of the target.
9855 var p1y = p1.charAt(0), p1x = p1.charAt(p1.length-1);
9856 var p2y = p2.charAt(0), p2x = p2.charAt(p2.length-1);
9857 var swapY = ((p1y=="t" && p2y=="b") || (p1y=="b" && p2y=="t") );
9858 var swapX = ((p1x=="r" && p2x=="l") || (p1x=="l" && p2x=="r"));
9861 var scrollX = (doc.documentElement.scrollLeft || doc.body.scrollLeft || 0)+5;
9862 var scrollY = (doc.documentElement.scrollTop || doc.body.scrollTop || 0)+5;
9864 if((x+w) > dw + scrollX){
9865 x = swapX ? r.left-w : dw+scrollX-w;
9868 x = swapX ? r.right : scrollX;
9870 if((y+h) > dh + scrollY){
9871 y = swapY ? r.top-h : dh+scrollY-h;
9874 y = swapY ? r.bottom : scrollY;
9881 getConstrainToXY : function(){
9882 var os = {top:0, left:0, bottom:0, right: 0};
9884 return function(el, local, offsets, proposedXY){
9886 offsets = offsets ? Roo.applyIf(offsets, os) : os;
9888 var vw, vh, vx = 0, vy = 0;
9889 if(el.dom == document.body || el.dom == document){
9890 vw = Roo.lib.Dom.getViewWidth();
9891 vh = Roo.lib.Dom.getViewHeight();
9893 vw = el.dom.clientWidth;
9894 vh = el.dom.clientHeight;
9896 var vxy = el.getXY();
9902 var s = el.getScroll();
9904 vx += offsets.left + s.left;
9905 vy += offsets.top + s.top;
9907 vw -= offsets.right;
9908 vh -= offsets.bottom;
9913 var xy = proposedXY || (!local ? this.getXY() : [this.getLeft(true), this.getTop(true)]);
9914 var x = xy[0], y = xy[1];
9915 var w = this.dom.offsetWidth, h = this.dom.offsetHeight;
9917 // only move it if it needs it
9920 // first validate right/bottom
9929 // then make sure top/left isn't negative
9938 return moved ? [x, y] : false;
9943 adjustForConstraints : function(xy, parent, offsets){
9944 return this.getConstrainToXY(parent || document, false, offsets, xy) || xy;
9948 * Aligns this element with another element relative to the specified anchor points. If the other element is the
9949 * document it aligns it to the viewport.
9950 * The position parameter is optional, and can be specified in any one of the following formats:
9952 * <li><b>Blank</b>: Defaults to aligning the element's top-left corner to the target's bottom-left corner ("tl-bl").</li>
9953 * <li><b>One anchor (deprecated)</b>: The passed anchor position is used as the target element's anchor point.
9954 * The element being aligned will position its top-left corner (tl) to that point. <i>This method has been
9955 * deprecated in favor of the newer two anchor syntax below</i>.</li>
9956 * <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
9957 * element's anchor point, and the second value is used as the target's anchor point.</li>
9959 * In addition to the anchor points, the position parameter also supports the "?" character. If "?" is passed at the end of
9960 * the position string, the element will attempt to align as specified, but the position will be adjusted to constrain to
9961 * the viewport if necessary. Note that the element being aligned might be swapped to align to a different position than
9962 * that specified in order to enforce the viewport constraints.
9963 * Following are all of the supported anchor positions:
9966 ----- -----------------------------
9967 tl The top left corner (default)
9968 t The center of the top edge
9969 tr The top right corner
9970 l The center of the left edge
9971 c In the center of the element
9972 r The center of the right edge
9973 bl The bottom left corner
9974 b The center of the bottom edge
9975 br The bottom right corner
9979 // align el to other-el using the default positioning ("tl-bl", non-constrained)
9980 el.alignTo("other-el");
9982 // align the top left corner of el with the top right corner of other-el (constrained to viewport)
9983 el.alignTo("other-el", "tr?");
9985 // align the bottom right corner of el with the center left edge of other-el
9986 el.alignTo("other-el", "br-l?");
9988 // align the center of el with the bottom left corner of other-el and
9989 // adjust the x position by -6 pixels (and the y position by 0)
9990 el.alignTo("other-el", "c-bl", [-6, 0]);
9992 * @param {String/HTMLElement/Roo.Element} element The element to align to.
9993 * @param {String} position The position to align to.
9994 * @param {Array} offsets (optional) Offset the positioning by [x, y]
9995 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
9996 * @return {Roo.Element} this
9998 alignTo : function(element, position, offsets, animate){
9999 var xy = this.getAlignToXY(element, position, offsets);
10000 this.setXY(xy, this.preanim(arguments, 3));
10005 * Anchors an element to another element and realigns it when the window is resized.
10006 * @param {String/HTMLElement/Roo.Element} element The element to align to.
10007 * @param {String} position The position to align to.
10008 * @param {Array} offsets (optional) Offset the positioning by [x, y]
10009 * @param {Boolean/Object} animate (optional) True for the default animation or a standard Element animation config object
10010 * @param {Boolean/Number} monitorScroll (optional) True to monitor body scroll and reposition. If this parameter
10011 * is a number, it is used as the buffer delay (defaults to 50ms).
10012 * @param {Function} callback The function to call after the animation finishes
10013 * @return {Roo.Element} this
10015 anchorTo : function(el, alignment, offsets, animate, monitorScroll, callback){
10016 var action = function(){
10017 this.alignTo(el, alignment, offsets, animate);
10018 Roo.callback(callback, this);
10020 Roo.EventManager.onWindowResize(action, this);
10021 var tm = typeof monitorScroll;
10022 if(tm != 'undefined'){
10023 Roo.EventManager.on(window, 'scroll', action, this,
10024 {buffer: tm == 'number' ? monitorScroll : 50});
10026 action.call(this); // align immediately
10030 * Clears any opacity settings from this element. Required in some cases for IE.
10031 * @return {Roo.Element} this
10033 clearOpacity : function(){
10034 if (window.ActiveXObject) {
10035 if(typeof this.dom.style.filter == 'string' && (/alpha/i).test(this.dom.style.filter)){
10036 this.dom.style.filter = "";
10039 this.dom.style.opacity = "";
10040 this.dom.style["-moz-opacity"] = "";
10041 this.dom.style["-khtml-opacity"] = "";
10047 * Hide this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
10048 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
10049 * @return {Roo.Element} this
10051 hide : function(animate){
10052 this.setVisible(false, this.preanim(arguments, 0));
10057 * Show this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
10058 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
10059 * @return {Roo.Element} this
10061 show : function(animate){
10062 this.setVisible(true, this.preanim(arguments, 0));
10067 * @private Test if size has a unit, otherwise appends the default
10069 addUnits : function(size){
10070 return Roo.Element.addUnits(size, this.defaultUnit);
10074 * Temporarily enables offsets (width,height,x,y) for an element with display:none, use endMeasure() when done.
10075 * @return {Roo.Element} this
10077 beginMeasure : function(){
10079 if(el.offsetWidth || el.offsetHeight){
10080 return this; // offsets work already
10083 var p = this.dom, b = document.body; // start with this element
10084 while((!el.offsetWidth && !el.offsetHeight) && p && p.tagName && p != b){
10085 var pe = Roo.get(p);
10086 if(pe.getStyle('display') == 'none'){
10087 changed.push({el: p, visibility: pe.getStyle("visibility")});
10088 p.style.visibility = "hidden";
10089 p.style.display = "block";
10093 this._measureChanged = changed;
10099 * Restores displays to before beginMeasure was called
10100 * @return {Roo.Element} this
10102 endMeasure : function(){
10103 var changed = this._measureChanged;
10105 for(var i = 0, len = changed.length; i < len; i++) {
10106 var r = changed[i];
10107 r.el.style.visibility = r.visibility;
10108 r.el.style.display = "none";
10110 this._measureChanged = null;
10116 * Update the innerHTML of this element, optionally searching for and processing scripts
10117 * @param {String} html The new HTML
10118 * @param {Boolean} loadScripts (optional) true to look for and process scripts
10119 * @param {Function} callback For async script loading you can be noticed when the update completes
10120 * @return {Roo.Element} this
10122 update : function(html, loadScripts, callback){
10123 if(typeof html == "undefined"){
10126 if(loadScripts !== true){
10127 this.dom.innerHTML = html;
10128 if(typeof callback == "function"){
10134 var dom = this.dom;
10136 html += '<span id="' + id + '"></span>';
10138 E.onAvailable(id, function(){
10139 var hd = document.getElementsByTagName("head")[0];
10140 var re = /(?:<script([^>]*)?>)((\n|\r|.)*?)(?:<\/script>)/ig;
10141 var srcRe = /\ssrc=([\'\"])(.*?)\1/i;
10142 var typeRe = /\stype=([\'\"])(.*?)\1/i;
10145 while(match = re.exec(html)){
10146 var attrs = match[1];
10147 var srcMatch = attrs ? attrs.match(srcRe) : false;
10148 if(srcMatch && srcMatch[2]){
10149 var s = document.createElement("script");
10150 s.src = srcMatch[2];
10151 var typeMatch = attrs.match(typeRe);
10152 if(typeMatch && typeMatch[2]){
10153 s.type = typeMatch[2];
10156 }else if(match[2] && match[2].length > 0){
10157 if(window.execScript) {
10158 window.execScript(match[2]);
10166 window.eval(match[2]);
10170 var el = document.getElementById(id);
10171 if(el){el.parentNode.removeChild(el);}
10172 if(typeof callback == "function"){
10176 dom.innerHTML = html.replace(/(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig, "");
10181 * Direct access to the UpdateManager update() method (takes the same parameters).
10182 * @param {String/Function} url The url for this request or a function to call to get the url
10183 * @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}
10184 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
10185 * @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.
10186 * @return {Roo.Element} this
10189 var um = this.getUpdateManager();
10190 um.update.apply(um, arguments);
10195 * Gets this element's UpdateManager
10196 * @return {Roo.UpdateManager} The UpdateManager
10198 getUpdateManager : function(){
10199 if(!this.updateManager){
10200 this.updateManager = new Roo.UpdateManager(this);
10202 return this.updateManager;
10206 * Disables text selection for this element (normalized across browsers)
10207 * @return {Roo.Element} this
10209 unselectable : function(){
10210 this.dom.unselectable = "on";
10211 this.swallowEvent("selectstart", true);
10212 this.applyStyles("-moz-user-select:none;-khtml-user-select:none;");
10213 this.addClass("x-unselectable");
10218 * Calculates the x, y to center this element on the screen
10219 * @return {Array} The x, y values [x, y]
10221 getCenterXY : function(){
10222 return this.getAlignToXY(document, 'c-c');
10226 * Centers the Element in either the viewport, or another Element.
10227 * @param {String/HTMLElement/Roo.Element} centerIn (optional) The element in which to center the element.
10229 center : function(centerIn){
10230 this.alignTo(centerIn || document, 'c-c');
10235 * Tests various css rules/browsers to determine if this element uses a border box
10236 * @return {Boolean}
10238 isBorderBox : function(){
10239 return noBoxAdjust[this.dom.tagName.toLowerCase()] || Roo.isBorderBox;
10243 * Return a box {x, y, width, height} that can be used to set another elements
10244 * size/location to match this element.
10245 * @param {Boolean} contentBox (optional) If true a box for the content of the element is returned.
10246 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page x/y.
10247 * @return {Object} box An object in the format {x, y, width, height}
10249 getBox : function(contentBox, local){
10254 var left = parseInt(this.getStyle("left"), 10) || 0;
10255 var top = parseInt(this.getStyle("top"), 10) || 0;
10258 var el = this.dom, w = el.offsetWidth, h = el.offsetHeight, bx;
10260 bx = {x: xy[0], y: xy[1], 0: xy[0], 1: xy[1], width: w, height: h};
10262 var l = this.getBorderWidth("l")+this.getPadding("l");
10263 var r = this.getBorderWidth("r")+this.getPadding("r");
10264 var t = this.getBorderWidth("t")+this.getPadding("t");
10265 var b = this.getBorderWidth("b")+this.getPadding("b");
10266 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)};
10268 bx.right = bx.x + bx.width;
10269 bx.bottom = bx.y + bx.height;
10274 * Returns the sum width of the padding and borders for the passed "sides". See getBorderWidth()
10275 for more information about the sides.
10276 * @param {String} sides
10279 getFrameWidth : function(sides, onlyContentBox){
10280 return onlyContentBox && Roo.isBorderBox ? 0 : (this.getPadding(sides) + this.getBorderWidth(sides));
10284 * 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.
10285 * @param {Object} box The box to fill {x, y, width, height}
10286 * @param {Boolean} adjust (optional) Whether to adjust for box-model issues automatically
10287 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
10288 * @return {Roo.Element} this
10290 setBox : function(box, adjust, animate){
10291 var w = box.width, h = box.height;
10292 if((adjust && !this.autoBoxAdjust) && !this.isBorderBox()){
10293 w -= (this.getBorderWidth("lr") + this.getPadding("lr"));
10294 h -= (this.getBorderWidth("tb") + this.getPadding("tb"));
10296 this.setBounds(box.x, box.y, w, h, this.preanim(arguments, 2));
10301 * Forces the browser to repaint this element
10302 * @return {Roo.Element} this
10304 repaint : function(){
10305 var dom = this.dom;
10306 this.addClass("x-repaint");
10307 setTimeout(function(){
10308 Roo.get(dom).removeClass("x-repaint");
10314 * Returns an object with properties top, left, right and bottom representing the margins of this element unless sides is passed,
10315 * then it returns the calculated width of the sides (see getPadding)
10316 * @param {String} sides (optional) Any combination of l, r, t, b to get the sum of those sides
10317 * @return {Object/Number}
10319 getMargins : function(side){
10322 top: parseInt(this.getStyle("margin-top"), 10) || 0,
10323 left: parseInt(this.getStyle("margin-left"), 10) || 0,
10324 bottom: parseInt(this.getStyle("margin-bottom"), 10) || 0,
10325 right: parseInt(this.getStyle("margin-right"), 10) || 0
10328 return this.addStyles(side, El.margins);
10333 addStyles : function(sides, styles){
10335 for(var i = 0, len = sides.length; i < len; i++){
10336 v = this.getStyle(styles[sides.charAt(i)]);
10338 w = parseInt(v, 10);
10346 * Creates a proxy element of this element
10347 * @param {String/Object} config The class name of the proxy element or a DomHelper config object
10348 * @param {String/HTMLElement} renderTo (optional) The element or element id to render the proxy to (defaults to document.body)
10349 * @param {Boolean} matchBox (optional) True to align and size the proxy to this element now (defaults to false)
10350 * @return {Roo.Element} The new proxy element
10352 createProxy : function(config, renderTo, matchBox){
10354 renderTo = Roo.getDom(renderTo);
10356 renderTo = document.body;
10358 config = typeof config == "object" ?
10359 config : {tag : "div", cls: config};
10360 var proxy = Roo.DomHelper.append(renderTo, config, true);
10362 proxy.setBox(this.getBox());
10368 * Puts a mask over this element to disable user interaction. Requires core.css.
10369 * This method can only be applied to elements which accept child nodes.
10370 * @param {String} msg (optional) A message to display in the mask
10371 * @param {String} msgCls (optional) A css class to apply to the msg element - use no-spinner to hide the spinner on bootstrap
10372 * @return {Element} The mask element
10374 mask : function(msg, msgCls)
10376 if(this.getStyle("position") == "static" && this.dom.tagName !== 'BODY'){
10377 this.setStyle("position", "relative");
10380 this._mask = Roo.DomHelper.append(this.dom, {cls:"roo-el-mask"}, true);
10383 this.addClass("x-masked");
10384 this._mask.setDisplayed(true);
10388 var dom = this.dom;
10389 while (dom && dom.style) {
10390 if (!isNaN(parseInt(dom.style.zIndex))) {
10391 z = Math.max(z, parseInt(dom.style.zIndex));
10393 dom = dom.parentNode;
10395 // if we are masking the body - then it hides everything..
10396 if (this.dom == document.body) {
10398 this._mask.setWidth(Roo.lib.Dom.getDocumentWidth());
10399 this._mask.setHeight(Roo.lib.Dom.getDocumentHeight());
10402 if(typeof msg == 'string'){
10403 if(!this._maskMsg){
10404 this._maskMsg = Roo.DomHelper.append(this.dom, {
10405 cls: "roo-el-mask-msg",
10409 cls: 'fa fa-spinner fa-spin'
10417 var mm = this._maskMsg;
10418 mm.dom.className = msgCls ? "roo-el-mask-msg " + msgCls : "roo-el-mask-msg";
10419 if (mm.dom.lastChild) { // weird IE issue?
10420 mm.dom.lastChild.innerHTML = msg;
10422 mm.setDisplayed(true);
10424 mm.setStyle('z-index', z + 102);
10426 if(Roo.isIE && !(Roo.isIE7 && Roo.isStrict) && this.getStyle('height') == 'auto'){ // ie will not expand full height automatically
10427 this._mask.setHeight(this.getHeight());
10429 this._mask.setStyle('z-index', z + 100);
10435 * Removes a previously applied mask. If removeEl is true the mask overlay is destroyed, otherwise
10436 * it is cached for reuse.
10438 unmask : function(removeEl){
10440 if(removeEl === true){
10441 this._mask.remove();
10444 this._maskMsg.remove();
10445 delete this._maskMsg;
10448 this._mask.setDisplayed(false);
10450 this._maskMsg.setDisplayed(false);
10454 this.removeClass("x-masked");
10458 * Returns true if this element is masked
10459 * @return {Boolean}
10461 isMasked : function(){
10462 return this._mask && this._mask.isVisible();
10466 * Creates an iframe shim for this element to keep selects and other windowed objects from
10468 * @return {Roo.Element} The new shim element
10470 createShim : function(){
10471 var el = document.createElement('iframe');
10472 el.frameBorder = 'no';
10473 el.className = 'roo-shim';
10474 if(Roo.isIE && Roo.isSecure){
10475 el.src = Roo.SSL_SECURE_URL;
10477 var shim = Roo.get(this.dom.parentNode.insertBefore(el, this.dom));
10478 shim.autoBoxAdjust = false;
10483 * Removes this element from the DOM and deletes it from the cache
10485 remove : function(){
10486 if(this.dom.parentNode){
10487 this.dom.parentNode.removeChild(this.dom);
10489 delete El.cache[this.dom.id];
10493 * Sets up event handlers to add and remove a css class when the mouse is over this element
10494 * @param {String} className
10495 * @param {Boolean} preventFlicker (optional) If set to true, it prevents flickering by filtering
10496 * mouseout events for children elements
10497 * @return {Roo.Element} this
10499 addClassOnOver : function(className, preventFlicker){
10500 this.on("mouseover", function(){
10501 Roo.fly(this, '_internal').addClass(className);
10503 var removeFn = function(e){
10504 if(preventFlicker !== true || !e.within(this, true)){
10505 Roo.fly(this, '_internal').removeClass(className);
10508 this.on("mouseout", removeFn, this.dom);
10513 * Sets up event handlers to add and remove a css class when this element has the focus
10514 * @param {String} className
10515 * @return {Roo.Element} this
10517 addClassOnFocus : function(className){
10518 this.on("focus", function(){
10519 Roo.fly(this, '_internal').addClass(className);
10521 this.on("blur", function(){
10522 Roo.fly(this, '_internal').removeClass(className);
10527 * 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)
10528 * @param {String} className
10529 * @return {Roo.Element} this
10531 addClassOnClick : function(className){
10532 var dom = this.dom;
10533 this.on("mousedown", function(){
10534 Roo.fly(dom, '_internal').addClass(className);
10535 var d = Roo.get(document);
10536 var fn = function(){
10537 Roo.fly(dom, '_internal').removeClass(className);
10538 d.removeListener("mouseup", fn);
10540 d.on("mouseup", fn);
10546 * Stops the specified event from bubbling and optionally prevents the default action
10547 * @param {String} eventName
10548 * @param {Boolean} preventDefault (optional) true to prevent the default action too
10549 * @return {Roo.Element} this
10551 swallowEvent : function(eventName, preventDefault){
10552 var fn = function(e){
10553 e.stopPropagation();
10554 if(preventDefault){
10555 e.preventDefault();
10558 if(eventName instanceof Array){
10559 for(var i = 0, len = eventName.length; i < len; i++){
10560 this.on(eventName[i], fn);
10564 this.on(eventName, fn);
10571 fitToParentDelegate : Roo.emptyFn, // keep a reference to the fitToParent delegate
10574 * Sizes this element to its parent element's dimensions performing
10575 * neccessary box adjustments.
10576 * @param {Boolean} monitorResize (optional) If true maintains the fit when the browser window is resized.
10577 * @param {String/HTMLElment/Element} targetParent (optional) The target parent, default to the parentNode.
10578 * @return {Roo.Element} this
10580 fitToParent : function(monitorResize, targetParent) {
10581 Roo.EventManager.removeResizeListener(this.fitToParentDelegate); // always remove previous fitToParent delegate from onWindowResize
10582 this.fitToParentDelegate = Roo.emptyFn; // remove reference to previous delegate
10583 if (monitorResize === true && !this.dom.parentNode) { // check if this Element still exists
10586 var p = Roo.get(targetParent || this.dom.parentNode);
10587 this.setSize(p.getComputedWidth() - p.getFrameWidth('lr'), p.getComputedHeight() - p.getFrameWidth('tb'));
10588 if (monitorResize === true) {
10589 this.fitToParentDelegate = this.fitToParent.createDelegate(this, [true, targetParent]);
10590 Roo.EventManager.onWindowResize(this.fitToParentDelegate);
10596 * Gets the next sibling, skipping text nodes
10597 * @return {HTMLElement} The next sibling or null
10599 getNextSibling : function(){
10600 var n = this.dom.nextSibling;
10601 while(n && n.nodeType != 1){
10608 * Gets the previous sibling, skipping text nodes
10609 * @return {HTMLElement} The previous sibling or null
10611 getPrevSibling : function(){
10612 var n = this.dom.previousSibling;
10613 while(n && n.nodeType != 1){
10614 n = n.previousSibling;
10621 * Appends the passed element(s) to this element
10622 * @param {String/HTMLElement/Array/Element/CompositeElement} el
10623 * @return {Roo.Element} this
10625 appendChild: function(el){
10632 * Creates the passed DomHelper config and appends it to this element or optionally inserts it before the passed child element.
10633 * @param {Object} config DomHelper element config object. If no tag is specified (e.g., {tag:'input'}) then a div will be
10634 * automatically generated with the specified attributes.
10635 * @param {HTMLElement} insertBefore (optional) a child element of this element
10636 * @param {Boolean} returnDom (optional) true to return the dom node instead of creating an Element
10637 * @return {Roo.Element} The new child element
10639 createChild: function(config, insertBefore, returnDom){
10640 config = config || {tag:'div'};
10642 return Roo.DomHelper.insertBefore(insertBefore, config, returnDom !== true);
10644 return Roo.DomHelper[!this.dom.firstChild ? 'overwrite' : 'append'](this.dom, config, returnDom !== true);
10648 * Appends this element to the passed element
10649 * @param {String/HTMLElement/Element} el The new parent element
10650 * @return {Roo.Element} this
10652 appendTo: function(el){
10653 el = Roo.getDom(el);
10654 el.appendChild(this.dom);
10659 * Inserts this element before the passed element in the DOM
10660 * @param {String/HTMLElement/Element} el The element to insert before
10661 * @return {Roo.Element} this
10663 insertBefore: function(el){
10664 el = Roo.getDom(el);
10665 el.parentNode.insertBefore(this.dom, el);
10670 * Inserts this element after the passed element in the DOM
10671 * @param {String/HTMLElement/Element} el The element to insert after
10672 * @return {Roo.Element} this
10674 insertAfter: function(el){
10675 el = Roo.getDom(el);
10676 el.parentNode.insertBefore(this.dom, el.nextSibling);
10681 * Inserts (or creates) an element (or DomHelper config) as the first child of the this element
10682 * @param {String/HTMLElement/Element/Object} el The id or element to insert or a DomHelper config to create and insert
10683 * @return {Roo.Element} The new child
10685 insertFirst: function(el, returnDom){
10687 if(typeof el == 'object' && !el.nodeType){ // dh config
10688 return this.createChild(el, this.dom.firstChild, returnDom);
10690 el = Roo.getDom(el);
10691 this.dom.insertBefore(el, this.dom.firstChild);
10692 return !returnDom ? Roo.get(el) : el;
10697 * Inserts (or creates) the passed element (or DomHelper config) as a sibling of this element
10698 * @param {String/HTMLElement/Element/Object} el The id or element to insert or a DomHelper config to create and insert
10699 * @param {String} where (optional) 'before' or 'after' defaults to before
10700 * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Roo.Element
10701 * @return {Roo.Element} the inserted Element
10703 insertSibling: function(el, where, returnDom){
10704 where = where ? where.toLowerCase() : 'before';
10706 var rt, refNode = where == 'before' ? this.dom : this.dom.nextSibling;
10708 if(typeof el == 'object' && !el.nodeType){ // dh config
10709 if(where == 'after' && !this.dom.nextSibling){
10710 rt = Roo.DomHelper.append(this.dom.parentNode, el, !returnDom);
10712 rt = Roo.DomHelper[where == 'after' ? 'insertAfter' : 'insertBefore'](this.dom, el, !returnDom);
10716 rt = this.dom.parentNode.insertBefore(Roo.getDom(el),
10717 where == 'before' ? this.dom : this.dom.nextSibling);
10726 * Creates and wraps this element with another element
10727 * @param {Object} config (optional) DomHelper element config object for the wrapper element or null for an empty div
10728 * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Roo.Element
10729 * @return {HTMLElement/Element} The newly created wrapper element
10731 wrap: function(config, returnDom){
10733 config = {tag: "div"};
10735 var newEl = Roo.DomHelper.insertBefore(this.dom, config, !returnDom);
10736 newEl.dom ? newEl.dom.appendChild(this.dom) : newEl.appendChild(this.dom);
10741 * Replaces the passed element with this element
10742 * @param {String/HTMLElement/Element} el The element to replace
10743 * @return {Roo.Element} this
10745 replace: function(el){
10747 this.insertBefore(el);
10753 * Inserts an html fragment into this element
10754 * @param {String} where Where to insert the html in relation to the this element - beforeBegin, afterBegin, beforeEnd, afterEnd.
10755 * @param {String} html The HTML fragment
10756 * @param {Boolean} returnEl True to return an Roo.Element
10757 * @return {HTMLElement/Roo.Element} The inserted node (or nearest related if more than 1 inserted)
10759 insertHtml : function(where, html, returnEl){
10760 var el = Roo.DomHelper.insertHtml(where, this.dom, html);
10761 return returnEl ? Roo.get(el) : el;
10765 * Sets the passed attributes as attributes of this element (a style attribute can be a string, object or function)
10766 * @param {Object} o The object with the attributes
10767 * @param {Boolean} useSet (optional) false to override the default setAttribute to use expandos.
10768 * @return {Roo.Element} this
10770 set : function(o, useSet){
10772 useSet = typeof useSet == 'undefined' ? (el.setAttribute ? true : false) : useSet;
10773 for(var attr in o){
10774 if(attr == "style" || typeof o[attr] == "function") { continue; }
10776 el.className = o["cls"];
10779 el.setAttribute(attr, o[attr]);
10781 el[attr] = o[attr];
10786 Roo.DomHelper.applyStyles(el, o.style);
10792 * Convenience method for constructing a KeyMap
10793 * @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:
10794 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
10795 * @param {Function} fn The function to call
10796 * @param {Object} scope (optional) The scope of the function
10797 * @return {Roo.KeyMap} The KeyMap created
10799 addKeyListener : function(key, fn, scope){
10801 if(typeof key != "object" || key instanceof Array){
10817 return new Roo.KeyMap(this, config);
10821 * Creates a KeyMap for this element
10822 * @param {Object} config The KeyMap config. See {@link Roo.KeyMap} for more details
10823 * @return {Roo.KeyMap} The KeyMap created
10825 addKeyMap : function(config){
10826 return new Roo.KeyMap(this, config);
10830 * Returns true if this element is scrollable.
10831 * @return {Boolean}
10833 isScrollable : function(){
10834 var dom = this.dom;
10835 return dom.scrollHeight > dom.clientHeight || dom.scrollWidth > dom.clientWidth;
10839 * 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().
10840 * @param {String} side Either "left" for scrollLeft values or "top" for scrollTop values.
10841 * @param {Number} value The new scroll value
10842 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
10843 * @return {Element} this
10846 scrollTo : function(side, value, animate){
10847 var prop = side.toLowerCase() == "left" ? "scrollLeft" : "scrollTop";
10848 if(!animate || !A){
10849 this.dom[prop] = value;
10851 var to = prop == "scrollLeft" ? [value, this.dom.scrollTop] : [this.dom.scrollLeft, value];
10852 this.anim({scroll: {"to": to}}, this.preanim(arguments, 2), 'scroll');
10858 * Scrolls this element the specified direction. Does bounds checking to make sure the scroll is
10859 * within this element's scrollable range.
10860 * @param {String} direction Possible values are: "l","left" - "r","right" - "t","top","up" - "b","bottom","down".
10861 * @param {Number} distance How far to scroll the element in pixels
10862 * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
10863 * @return {Boolean} Returns true if a scroll was triggered or false if the element
10864 * was scrolled as far as it could go.
10866 scroll : function(direction, distance, animate){
10867 if(!this.isScrollable()){
10871 var l = el.scrollLeft, t = el.scrollTop;
10872 var w = el.scrollWidth, h = el.scrollHeight;
10873 var cw = el.clientWidth, ch = el.clientHeight;
10874 direction = direction.toLowerCase();
10875 var scrolled = false;
10876 var a = this.preanim(arguments, 2);
10881 var v = Math.min(l + distance, w-cw);
10882 this.scrollTo("left", v, a);
10889 var v = Math.max(l - distance, 0);
10890 this.scrollTo("left", v, a);
10898 var v = Math.max(t - distance, 0);
10899 this.scrollTo("top", v, a);
10907 var v = Math.min(t + distance, h-ch);
10908 this.scrollTo("top", v, a);
10917 * Translates the passed page coordinates into left/top css values for this element
10918 * @param {Number/Array} x The page x or an array containing [x, y]
10919 * @param {Number} y The page y
10920 * @return {Object} An object with left and top properties. e.g. {left: (value), top: (value)}
10922 translatePoints : function(x, y){
10923 if(typeof x == 'object' || x instanceof Array){
10924 y = x[1]; x = x[0];
10926 var p = this.getStyle('position');
10927 var o = this.getXY();
10929 var l = parseInt(this.getStyle('left'), 10);
10930 var t = parseInt(this.getStyle('top'), 10);
10933 l = (p == "relative") ? 0 : this.dom.offsetLeft;
10936 t = (p == "relative") ? 0 : this.dom.offsetTop;
10939 return {left: (x - o[0] + l), top: (y - o[1] + t)};
10943 * Returns the current scroll position of the element.
10944 * @return {Object} An object containing the scroll position in the format {left: (scrollLeft), top: (scrollTop)}
10946 getScroll : function(){
10947 var d = this.dom, doc = document;
10948 if(d == doc || d == doc.body){
10949 var l = window.pageXOffset || doc.documentElement.scrollLeft || doc.body.scrollLeft || 0;
10950 var t = window.pageYOffset || doc.documentElement.scrollTop || doc.body.scrollTop || 0;
10951 return {left: l, top: t};
10953 return {left: d.scrollLeft, top: d.scrollTop};
10958 * Return the CSS color for the specified CSS attribute. rgb, 3 digit (like #fff) and valid values
10959 * are convert to standard 6 digit hex color.
10960 * @param {String} attr The css attribute
10961 * @param {String} defaultValue The default value to use when a valid color isn't found
10962 * @param {String} prefix (optional) defaults to #. Use an empty string when working with
10965 getColor : function(attr, defaultValue, prefix){
10966 var v = this.getStyle(attr);
10967 if(!v || v == "transparent" || v == "inherit") {
10968 return defaultValue;
10970 var color = typeof prefix == "undefined" ? "#" : prefix;
10971 if(v.substr(0, 4) == "rgb("){
10972 var rvs = v.slice(4, v.length -1).split(",");
10973 for(var i = 0; i < 3; i++){
10974 var h = parseInt(rvs[i]).toString(16);
10981 if(v.substr(0, 1) == "#"){
10982 if(v.length == 4) {
10983 for(var i = 1; i < 4; i++){
10984 var c = v.charAt(i);
10987 }else if(v.length == 7){
10988 color += v.substr(1);
10992 return(color.length > 5 ? color.toLowerCase() : defaultValue);
10996 * Wraps the specified element with a special markup/CSS block that renders by default as a gray container with a
10997 * gradient background, rounded corners and a 4-way shadow.
10998 * @param {String} class (optional) A base CSS class to apply to the containing wrapper element (defaults to 'x-box').
10999 * Note that there are a number of CSS rules that are dependent on this name to make the overall effect work,
11000 * so if you supply an alternate base class, make sure you also supply all of the necessary rules.
11001 * @return {Roo.Element} this
11003 boxWrap : function(cls){
11004 cls = cls || 'x-box';
11005 var el = Roo.get(this.insertHtml('beforeBegin', String.format('<div class="{0}">'+El.boxMarkup+'</div>', cls)));
11006 el.child('.'+cls+'-mc').dom.appendChild(this.dom);
11011 * Returns the value of a namespaced attribute from the element's underlying DOM node.
11012 * @param {String} namespace The namespace in which to look for the attribute
11013 * @param {String} name The attribute name
11014 * @return {String} The attribute value
11016 getAttributeNS : Roo.isIE ? function(ns, name){
11018 var type = typeof d[ns+":"+name];
11019 if(type != 'undefined' && type != 'unknown'){
11020 return d[ns+":"+name];
11023 } : function(ns, name){
11025 return d.getAttributeNS(ns, name) || d.getAttribute(ns+":"+name) || d.getAttribute(name) || d[name];
11030 * Sets or Returns the value the dom attribute value
11031 * @param {String|Object} name The attribute name (or object to set multiple attributes)
11032 * @param {String} value (optional) The value to set the attribute to
11033 * @return {String} The attribute value
11035 attr : function(name){
11036 if (arguments.length > 1) {
11037 this.dom.setAttribute(name, arguments[1]);
11038 return arguments[1];
11040 if (typeof(name) == 'object') {
11041 for(var i in name) {
11042 this.attr(i, name[i]);
11048 if (!this.dom.hasAttribute(name)) {
11051 return this.dom.getAttribute(name);
11058 var ep = El.prototype;
11061 * Appends an event handler (Shorthand for addListener)
11062 * @param {String} eventName The type of event to append
11063 * @param {Function} fn The method the event invokes
11064 * @param {Object} scope (optional) The scope (this object) of the fn
11065 * @param {Object} options (optional)An object with standard {@link Roo.EventManager#addListener} options
11068 ep.on = ep.addListener;
11069 // backwards compat
11070 ep.mon = ep.addListener;
11073 * Removes an event handler from this element (shorthand for removeListener)
11074 * @param {String} eventName the type of event to remove
11075 * @param {Function} fn the method the event invokes
11076 * @return {Roo.Element} this
11079 ep.un = ep.removeListener;
11082 * true to automatically adjust width and height settings for box-model issues (default to true)
11084 ep.autoBoxAdjust = true;
11087 El.unitPattern = /\d+(px|em|%|en|ex|pt|in|cm|mm|pc)$/i;
11090 El.addUnits = function(v, defaultUnit){
11091 if(v === "" || v == "auto"){
11094 if(v === undefined){
11097 if(typeof v == "number" || !El.unitPattern.test(v)){
11098 return v + (defaultUnit || 'px');
11103 // special markup used throughout Roo when box wrapping elements
11104 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>';
11106 * Visibility mode constant - Use visibility to hide element
11112 * Visibility mode constant - Use display to hide element
11118 El.borders = {l: "border-left-width", r: "border-right-width", t: "border-top-width", b: "border-bottom-width"};
11119 El.paddings = {l: "padding-left", r: "padding-right", t: "padding-top", b: "padding-bottom"};
11120 El.margins = {l: "margin-left", r: "margin-right", t: "margin-top", b: "margin-bottom"};
11132 * Static method to retrieve Element objects. Uses simple caching to consistently return the same object.
11133 * Automatically fixes if an object was recreated with the same id via AJAX or DOM.
11134 * @param {String/HTMLElement/Element} el The id of the node, a DOM Node or an existing Element.
11135 * @return {Element} The Element object
11138 El.get = function(el){
11140 if(!el){ return null; }
11141 if(typeof el == "string"){ // element id
11142 if(!(elm = document.getElementById(el))){
11145 if(ex = El.cache[el]){
11148 ex = El.cache[el] = new El(elm);
11151 }else if(el.tagName){ // dom element
11155 if(ex = El.cache[id]){
11158 ex = El.cache[id] = new El(el);
11161 }else if(el instanceof El){
11163 el.dom = document.getElementById(el.id) || el.dom; // refresh dom element in case no longer valid,
11164 // catch case where it hasn't been appended
11165 El.cache[el.id] = el; // in case it was created directly with Element(), let's cache it
11168 }else if(el.isComposite){
11170 }else if(el instanceof Array){
11171 return El.select(el);
11172 }else if(el == document){
11173 // create a bogus element object representing the document object
11175 var f = function(){};
11176 f.prototype = El.prototype;
11178 docEl.dom = document;
11186 El.uncache = function(el){
11187 for(var i = 0, a = arguments, len = a.length; i < len; i++) {
11189 delete El.cache[a[i].id || a[i]];
11195 // Garbage collection - uncache elements/purge listeners on orphaned elements
11196 // so we don't hold a reference and cause the browser to retain them
11197 El.garbageCollect = function(){
11198 if(!Roo.enableGarbageCollector){
11199 clearInterval(El.collectorThread);
11202 for(var eid in El.cache){
11203 var el = El.cache[eid], d = el.dom;
11204 // -------------------------------------------------------
11205 // Determining what is garbage:
11206 // -------------------------------------------------------
11208 // dom node is null, definitely garbage
11209 // -------------------------------------------------------
11211 // no parentNode == direct orphan, definitely garbage
11212 // -------------------------------------------------------
11213 // !d.offsetParent && !document.getElementById(eid)
11214 // display none elements have no offsetParent so we will
11215 // also try to look it up by it's id. However, check
11216 // offsetParent first so we don't do unneeded lookups.
11217 // This enables collection of elements that are not orphans
11218 // directly, but somewhere up the line they have an orphan
11220 // -------------------------------------------------------
11221 if(!d || !d.parentNode || (!d.offsetParent && !document.getElementById(eid))){
11222 delete El.cache[eid];
11223 if(d && Roo.enableListenerCollection){
11229 El.collectorThreadId = setInterval(El.garbageCollect, 30000);
11233 El.Flyweight = function(dom){
11236 El.Flyweight.prototype = El.prototype;
11238 El._flyweights = {};
11240 * Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
11241 * the dom node can be overwritten by other code.
11242 * @param {String/HTMLElement} el The dom node or id
11243 * @param {String} named (optional) Allows for creation of named reusable flyweights to
11244 * prevent conflicts (e.g. internally Roo uses "_internal")
11246 * @return {Element} The shared Element object
11248 El.fly = function(el, named){
11249 named = named || '_global';
11250 el = Roo.getDom(el);
11254 if(!El._flyweights[named]){
11255 El._flyweights[named] = new El.Flyweight();
11257 El._flyweights[named].dom = el;
11258 return El._flyweights[named];
11262 * Static method to retrieve Element objects. Uses simple caching to consistently return the same object.
11263 * Automatically fixes if an object was recreated with the same id via AJAX or DOM.
11264 * Shorthand of {@link Roo.Element#get}
11265 * @param {String/HTMLElement/Element} el The id of the node, a DOM Node or an existing Element.
11266 * @return {Element} The Element object
11272 * Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
11273 * the dom node can be overwritten by other code.
11274 * Shorthand of {@link Roo.Element#fly}
11275 * @param {String/HTMLElement} el The dom node or id
11276 * @param {String} named (optional) Allows for creation of named reusable flyweights to
11277 * prevent conflicts (e.g. internally Roo uses "_internal")
11279 * @return {Element} The shared Element object
11285 // speedy lookup for elements never to box adjust
11286 var noBoxAdjust = Roo.isStrict ? {
11289 input:1, select:1, textarea:1
11291 if(Roo.isIE || Roo.isGecko){
11292 noBoxAdjust['button'] = 1;
11296 Roo.EventManager.on(window, 'unload', function(){
11298 delete El._flyweights;
11306 Roo.Element.selectorFunction = Roo.DomQuery.select;
11309 Roo.Element.select = function(selector, unique, root){
11311 if(typeof selector == "string"){
11312 els = Roo.Element.selectorFunction(selector, root);
11313 }else if(selector.length !== undefined){
11316 throw "Invalid selector";
11318 if(unique === true){
11319 return new Roo.CompositeElement(els);
11321 return new Roo.CompositeElementLite(els);
11325 * Selects elements based on the passed CSS selector to enable working on them as 1.
11326 * @param {String/Array} selector The CSS selector or an array of elements
11327 * @param {Boolean} unique (optional) true to create a unique Roo.Element for each element (defaults to a shared flyweight object)
11328 * @param {HTMLElement/String} root (optional) The root element of the query or id of the root
11329 * @return {CompositeElementLite/CompositeElement}
11333 Roo.select = Roo.Element.select;
11350 * Ext JS Library 1.1.1
11351 * Copyright(c) 2006-2007, Ext JS, LLC.
11353 * Originally Released Under LGPL - original licence link has changed is not relivant.
11356 * <script type="text/javascript">
11361 //Notifies Element that fx methods are available
11362 Roo.enableFx = true;
11366 * <p>A class to provide basic animation and visual effects support. <b>Note:</b> This class is automatically applied
11367 * to the {@link Roo.Element} interface when included, so all effects calls should be performed via Element.
11368 * Conversely, since the effects are not actually defined in Element, Roo.Fx <b>must</b> be included in order for the
11369 * Element effects to work.</p><br/>
11371 * <p>It is important to note that although the Fx methods and many non-Fx Element methods support "method chaining" in that
11372 * they return the Element object itself as the method return value, it is not always possible to mix the two in a single
11373 * method chain. The Fx methods use an internal effects queue so that each effect can be properly timed and sequenced.
11374 * Non-Fx methods, on the other hand, have no such internal queueing and will always execute immediately. For this reason,
11375 * while it may be possible to mix certain Fx and non-Fx method calls in a single chain, it may not always provide the
11376 * expected results and should be done with care.</p><br/>
11378 * <p>Motion effects support 8-way anchoring, meaning that you can choose one of 8 different anchor points on the Element
11379 * that will serve as either the start or end point of the animation. Following are all of the supported anchor positions:</p>
11382 ----- -----------------------------
11383 tl The top left corner
11384 t The center of the top edge
11385 tr The top right corner
11386 l The center of the left edge
11387 r The center of the right edge
11388 bl The bottom left corner
11389 b The center of the bottom edge
11390 br The bottom right corner
11392 * <b>Although some Fx methods accept specific custom config parameters, the ones shown in the Config Options section
11393 * below are common options that can be passed to any Fx method.</b>
11394 * @cfg {Function} callback A function called when the effect is finished
11395 * @cfg {Object} scope The scope of the effect function
11396 * @cfg {String} easing A valid Easing value for the effect
11397 * @cfg {String} afterCls A css class to apply after the effect
11398 * @cfg {Number} duration The length of time (in seconds) that the effect should last
11399 * @cfg {Boolean} remove Whether the Element should be removed from the DOM and destroyed after the effect finishes
11400 * @cfg {Boolean} useDisplay Whether to use the <i>display</i> CSS property instead of <i>visibility</i> when hiding Elements (only applies to
11401 * effects that end with the element being visually hidden, ignored otherwise)
11402 * @cfg {String/Object/Function} afterStyle A style specification string, e.g. "width:100px", or an object in the form {width:"100px"}, or
11403 * a function which returns such a specification that will be applied to the Element after the effect finishes
11404 * @cfg {Boolean} block Whether the effect should block other effects from queueing while it runs
11405 * @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
11406 * @cfg {Boolean} stopFx Whether subsequent effects should be stopped and removed after the current effect finishes
11410 * Slides the element into view. An anchor point can be optionally passed to set the point of
11411 * origin for the slide effect. This function automatically handles wrapping the element with
11412 * a fixed-size container if needed. See the Fx class overview for valid anchor point options.
11415 // default: slide the element in from the top
11418 // custom: slide the element in from the right with a 2-second duration
11419 el.slideIn('r', { duration: 2 });
11421 // common config options shown with default values
11427 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to top: 't')
11428 * @param {Object} options (optional) Object literal with any of the Fx config options
11429 * @return {Roo.Element} The Element
11431 slideIn : function(anchor, o){
11432 var el = this.getFxEl();
11435 el.queueFx(o, function(){
11437 anchor = anchor || "t";
11439 // fix display to visibility
11442 // restore values after effect
11443 var r = this.getFxRestore();
11444 var b = this.getBox();
11445 // fixed size for slide
11449 var wrap = this.fxWrap(r.pos, o, "hidden");
11451 var st = this.dom.style;
11452 st.visibility = "visible";
11453 st.position = "absolute";
11455 // clear out temp styles after slide and unwrap
11456 var after = function(){
11457 el.fxUnwrap(wrap, r.pos, o);
11458 st.width = r.width;
11459 st.height = r.height;
11462 // time to calc the positions
11463 var a, pt = {to: [b.x, b.y]}, bw = {to: b.width}, bh = {to: b.height};
11465 switch(anchor.toLowerCase()){
11467 wrap.setSize(b.width, 0);
11468 st.left = st.bottom = "0";
11472 wrap.setSize(0, b.height);
11473 st.right = st.top = "0";
11477 wrap.setSize(0, b.height);
11478 wrap.setX(b.right);
11479 st.left = st.top = "0";
11480 a = {width: bw, points: pt};
11483 wrap.setSize(b.width, 0);
11484 wrap.setY(b.bottom);
11485 st.left = st.top = "0";
11486 a = {height: bh, points: pt};
11489 wrap.setSize(0, 0);
11490 st.right = st.bottom = "0";
11491 a = {width: bw, height: bh};
11494 wrap.setSize(0, 0);
11495 wrap.setY(b.y+b.height);
11496 st.right = st.top = "0";
11497 a = {width: bw, height: bh, points: pt};
11500 wrap.setSize(0, 0);
11501 wrap.setXY([b.right, b.bottom]);
11502 st.left = st.top = "0";
11503 a = {width: bw, height: bh, points: pt};
11506 wrap.setSize(0, 0);
11507 wrap.setX(b.x+b.width);
11508 st.left = st.bottom = "0";
11509 a = {width: bw, height: bh, points: pt};
11512 this.dom.style.visibility = "visible";
11515 arguments.callee.anim = wrap.fxanim(a,
11525 * Slides the element out of view. An anchor point can be optionally passed to set the end point
11526 * for the slide effect. When the effect is completed, the element will be hidden (visibility =
11527 * 'hidden') but block elements will still take up space in the document. The element must be removed
11528 * from the DOM using the 'remove' config option if desired. This function automatically handles
11529 * wrapping the element with a fixed-size container if needed. See the Fx class overview for valid anchor point options.
11532 // default: slide the element out to the top
11535 // custom: slide the element out to the right with a 2-second duration
11536 el.slideOut('r', { duration: 2 });
11538 // common config options shown with default values
11546 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to top: 't')
11547 * @param {Object} options (optional) Object literal with any of the Fx config options
11548 * @return {Roo.Element} The Element
11550 slideOut : function(anchor, o){
11551 var el = this.getFxEl();
11554 el.queueFx(o, function(){
11556 anchor = anchor || "t";
11558 // restore values after effect
11559 var r = this.getFxRestore();
11561 var b = this.getBox();
11562 // fixed size for slide
11566 var wrap = this.fxWrap(r.pos, o, "visible");
11568 var st = this.dom.style;
11569 st.visibility = "visible";
11570 st.position = "absolute";
11574 var after = function(){
11576 el.setDisplayed(false);
11581 el.fxUnwrap(wrap, r.pos, o);
11583 st.width = r.width;
11584 st.height = r.height;
11589 var a, zero = {to: 0};
11590 switch(anchor.toLowerCase()){
11592 st.left = st.bottom = "0";
11593 a = {height: zero};
11596 st.right = st.top = "0";
11600 st.left = st.top = "0";
11601 a = {width: zero, points: {to:[b.right, b.y]}};
11604 st.left = st.top = "0";
11605 a = {height: zero, points: {to:[b.x, b.bottom]}};
11608 st.right = st.bottom = "0";
11609 a = {width: zero, height: zero};
11612 st.right = st.top = "0";
11613 a = {width: zero, height: zero, points: {to:[b.x, b.bottom]}};
11616 st.left = st.top = "0";
11617 a = {width: zero, height: zero, points: {to:[b.x+b.width, b.bottom]}};
11620 st.left = st.bottom = "0";
11621 a = {width: zero, height: zero, points: {to:[b.right, b.y]}};
11625 arguments.callee.anim = wrap.fxanim(a,
11635 * Fades the element out while slowly expanding it in all directions. When the effect is completed, the
11636 * element will be hidden (visibility = 'hidden') but block elements will still take up space in the document.
11637 * The element must be removed from the DOM using the 'remove' config option if desired.
11643 // common config options shown with default values
11651 * @param {Object} options (optional) Object literal with any of the Fx config options
11652 * @return {Roo.Element} The Element
11654 puff : function(o){
11655 var el = this.getFxEl();
11658 el.queueFx(o, function(){
11659 this.clearOpacity();
11662 // restore values after effect
11663 var r = this.getFxRestore();
11664 var st = this.dom.style;
11666 var after = function(){
11668 el.setDisplayed(false);
11675 el.setPositioning(r.pos);
11676 st.width = r.width;
11677 st.height = r.height;
11682 var width = this.getWidth();
11683 var height = this.getHeight();
11685 arguments.callee.anim = this.fxanim({
11686 width : {to: this.adjustWidth(width * 2)},
11687 height : {to: this.adjustHeight(height * 2)},
11688 points : {by: [-(width * .5), -(height * .5)]},
11690 fontSize: {to:200, unit: "%"}
11701 * Blinks the element as if it was clicked and then collapses on its center (similar to switching off a television).
11702 * When the effect is completed, the element will be hidden (visibility = 'hidden') but block elements will still
11703 * take up space in the document. The element must be removed from the DOM using the 'remove' config option if desired.
11709 // all config options shown with default values
11717 * @param {Object} options (optional) Object literal with any of the Fx config options
11718 * @return {Roo.Element} The Element
11720 switchOff : function(o){
11721 var el = this.getFxEl();
11724 el.queueFx(o, function(){
11725 this.clearOpacity();
11728 // restore values after effect
11729 var r = this.getFxRestore();
11730 var st = this.dom.style;
11732 var after = function(){
11734 el.setDisplayed(false);
11740 el.setPositioning(r.pos);
11741 st.width = r.width;
11742 st.height = r.height;
11747 this.fxanim({opacity:{to:0.3}}, null, null, .1, null, function(){
11748 this.clearOpacity();
11752 points:{by:[0, this.getHeight() * .5]}
11753 }, o, 'motion', 0.3, 'easeIn', after);
11754 }).defer(100, this);
11761 * Highlights the Element by setting a color (applies to the background-color by default, but can be
11762 * changed using the "attr" config option) and then fading back to the original color. If no original
11763 * color is available, you should provide the "endColor" config option which will be cleared after the animation.
11766 // default: highlight background to yellow
11769 // custom: highlight foreground text to blue for 2 seconds
11770 el.highlight("0000ff", { attr: 'color', duration: 2 });
11772 // common config options shown with default values
11773 el.highlight("ffff9c", {
11774 attr: "background-color", //can be any valid CSS property (attribute) that supports a color value
11775 endColor: (current color) or "ffffff",
11780 * @param {String} color (optional) The highlight color. Should be a 6 char hex color without the leading # (defaults to yellow: 'ffff9c')
11781 * @param {Object} options (optional) Object literal with any of the Fx config options
11782 * @return {Roo.Element} The Element
11784 highlight : function(color, o){
11785 var el = this.getFxEl();
11788 el.queueFx(o, function(){
11789 color = color || "ffff9c";
11790 attr = o.attr || "backgroundColor";
11792 this.clearOpacity();
11795 var origColor = this.getColor(attr);
11796 var restoreColor = this.dom.style[attr];
11797 endColor = (o.endColor || origColor) || "ffffff";
11799 var after = function(){
11800 el.dom.style[attr] = restoreColor;
11805 a[attr] = {from: color, to: endColor};
11806 arguments.callee.anim = this.fxanim(a,
11816 * Shows a ripple of exploding, attenuating borders to draw attention to an Element.
11819 // default: a single light blue ripple
11822 // custom: 3 red ripples lasting 3 seconds total
11823 el.frame("ff0000", 3, { duration: 3 });
11825 // common config options shown with default values
11826 el.frame("C3DAF9", 1, {
11827 duration: 1 //duration of entire animation (not each individual ripple)
11828 // Note: Easing is not configurable and will be ignored if included
11831 * @param {String} color (optional) The color of the border. Should be a 6 char hex color without the leading # (defaults to light blue: 'C3DAF9').
11832 * @param {Number} count (optional) The number of ripples to display (defaults to 1)
11833 * @param {Object} options (optional) Object literal with any of the Fx config options
11834 * @return {Roo.Element} The Element
11836 frame : function(color, count, o){
11837 var el = this.getFxEl();
11840 el.queueFx(o, function(){
11841 color = color || "#C3DAF9";
11842 if(color.length == 6){
11843 color = "#" + color;
11845 count = count || 1;
11846 duration = o.duration || 1;
11849 var b = this.getBox();
11850 var animFn = function(){
11851 var proxy = this.createProxy({
11854 visbility:"hidden",
11855 position:"absolute",
11856 "z-index":"35000", // yee haw
11857 border:"0px solid " + color
11860 var scale = Roo.isBorderBox ? 2 : 1;
11862 top:{from:b.y, to:b.y - 20},
11863 left:{from:b.x, to:b.x - 20},
11864 borderWidth:{from:0, to:10},
11865 opacity:{from:1, to:0},
11866 height:{from:b.height, to:(b.height + (20*scale))},
11867 width:{from:b.width, to:(b.width + (20*scale))}
11868 }, duration, function(){
11872 animFn.defer((duration/2)*1000, this);
11883 * Creates a pause before any subsequent queued effects begin. If there are
11884 * no effects queued after the pause it will have no effect.
11889 * @param {Number} seconds The length of time to pause (in seconds)
11890 * @return {Roo.Element} The Element
11892 pause : function(seconds){
11893 var el = this.getFxEl();
11896 el.queueFx(o, function(){
11897 setTimeout(function(){
11899 }, seconds * 1000);
11905 * Fade an element in (from transparent to opaque). The ending opacity can be specified
11906 * using the "endOpacity" config option.
11909 // default: fade in from opacity 0 to 100%
11912 // custom: fade in from opacity 0 to 75% over 2 seconds
11913 el.fadeIn({ endOpacity: .75, duration: 2});
11915 // common config options shown with default values
11917 endOpacity: 1, //can be any value between 0 and 1 (e.g. .5)
11922 * @param {Object} options (optional) Object literal with any of the Fx config options
11923 * @return {Roo.Element} The Element
11925 fadeIn : function(o){
11926 var el = this.getFxEl();
11928 el.queueFx(o, function(){
11929 this.setOpacity(0);
11931 this.dom.style.visibility = 'visible';
11932 var to = o.endOpacity || 1;
11933 arguments.callee.anim = this.fxanim({opacity:{to:to}},
11934 o, null, .5, "easeOut", function(){
11936 this.clearOpacity();
11945 * Fade an element out (from opaque to transparent). The ending opacity can be specified
11946 * using the "endOpacity" config option.
11949 // default: fade out from the element's current opacity to 0
11952 // custom: fade out from the element's current opacity to 25% over 2 seconds
11953 el.fadeOut({ endOpacity: .25, duration: 2});
11955 // common config options shown with default values
11957 endOpacity: 0, //can be any value between 0 and 1 (e.g. .5)
11964 * @param {Object} options (optional) Object literal with any of the Fx config options
11965 * @return {Roo.Element} The Element
11967 fadeOut : function(o){
11968 var el = this.getFxEl();
11970 el.queueFx(o, function(){
11971 arguments.callee.anim = this.fxanim({opacity:{to:o.endOpacity || 0}},
11972 o, null, .5, "easeOut", function(){
11973 if(this.visibilityMode == Roo.Element.DISPLAY || o.useDisplay){
11974 this.dom.style.display = "none";
11976 this.dom.style.visibility = "hidden";
11978 this.clearOpacity();
11986 * Animates the transition of an element's dimensions from a starting height/width
11987 * to an ending height/width.
11990 // change height and width to 100x100 pixels
11991 el.scale(100, 100);
11993 // common config options shown with default values. The height and width will default to
11994 // the element's existing values if passed as null.
11997 [element's height], {
12002 * @param {Number} width The new width (pass undefined to keep the original width)
12003 * @param {Number} height The new height (pass undefined to keep the original height)
12004 * @param {Object} options (optional) Object literal with any of the Fx config options
12005 * @return {Roo.Element} The Element
12007 scale : function(w, h, o){
12008 this.shift(Roo.apply({}, o, {
12016 * Animates the transition of any combination of an element's dimensions, xy position and/or opacity.
12017 * Any of these properties not specified in the config object will not be changed. This effect
12018 * requires that at least one new dimension, position or opacity setting must be passed in on
12019 * the config object in order for the function to have any effect.
12022 // slide the element horizontally to x position 200 while changing the height and opacity
12023 el.shift({ x: 200, height: 50, opacity: .8 });
12025 // common config options shown with default values.
12027 width: [element's width],
12028 height: [element's height],
12029 x: [element's x position],
12030 y: [element's y position],
12031 opacity: [element's opacity],
12036 * @param {Object} options Object literal with any of the Fx config options
12037 * @return {Roo.Element} The Element
12039 shift : function(o){
12040 var el = this.getFxEl();
12042 el.queueFx(o, function(){
12043 var a = {}, w = o.width, h = o.height, x = o.x, y = o.y, op = o.opacity;
12044 if(w !== undefined){
12045 a.width = {to: this.adjustWidth(w)};
12047 if(h !== undefined){
12048 a.height = {to: this.adjustHeight(h)};
12050 if(x !== undefined || y !== undefined){
12052 x !== undefined ? x : this.getX(),
12053 y !== undefined ? y : this.getY()
12056 if(op !== undefined){
12057 a.opacity = {to: op};
12059 if(o.xy !== undefined){
12060 a.points = {to: o.xy};
12062 arguments.callee.anim = this.fxanim(a,
12063 o, 'motion', .35, "easeOut", function(){
12071 * Slides the element while fading it out of view. An anchor point can be optionally passed to set the
12072 * ending point of the effect.
12075 // default: slide the element downward while fading out
12078 // custom: slide the element out to the right with a 2-second duration
12079 el.ghost('r', { duration: 2 });
12081 // common config options shown with default values
12089 * @param {String} anchor (optional) One of the valid Fx anchor positions (defaults to bottom: 'b')
12090 * @param {Object} options (optional) Object literal with any of the Fx config options
12091 * @return {Roo.Element} The Element
12093 ghost : function(anchor, o){
12094 var el = this.getFxEl();
12097 el.queueFx(o, function(){
12098 anchor = anchor || "b";
12100 // restore values after effect
12101 var r = this.getFxRestore();
12102 var w = this.getWidth(),
12103 h = this.getHeight();
12105 var st = this.dom.style;
12107 var after = function(){
12109 el.setDisplayed(false);
12115 el.setPositioning(r.pos);
12116 st.width = r.width;
12117 st.height = r.height;
12122 var a = {opacity: {to: 0}, points: {}}, pt = a.points;
12123 switch(anchor.toLowerCase()){
12150 arguments.callee.anim = this.fxanim(a,
12160 * Ensures that all effects queued after syncFx is called on the element are
12161 * run concurrently. This is the opposite of {@link #sequenceFx}.
12162 * @return {Roo.Element} The Element
12164 syncFx : function(){
12165 this.fxDefaults = Roo.apply(this.fxDefaults || {}, {
12174 * Ensures that all effects queued after sequenceFx is called on the element are
12175 * run in sequence. This is the opposite of {@link #syncFx}.
12176 * @return {Roo.Element} The Element
12178 sequenceFx : function(){
12179 this.fxDefaults = Roo.apply(this.fxDefaults || {}, {
12181 concurrent : false,
12188 nextFx : function(){
12189 var ef = this.fxQueue[0];
12196 * Returns true if the element has any effects actively running or queued, else returns false.
12197 * @return {Boolean} True if element has active effects, else false
12199 hasActiveFx : function(){
12200 return this.fxQueue && this.fxQueue[0];
12204 * Stops any running effects and clears the element's internal effects queue if it contains
12205 * any additional effects that haven't started yet.
12206 * @return {Roo.Element} The Element
12208 stopFx : function(){
12209 if(this.hasActiveFx()){
12210 var cur = this.fxQueue[0];
12211 if(cur && cur.anim && cur.anim.isAnimated()){
12212 this.fxQueue = [cur]; // clear out others
12213 cur.anim.stop(true);
12220 beforeFx : function(o){
12221 if(this.hasActiveFx() && !o.concurrent){
12232 * Returns true if the element is currently blocking so that no other effect can be queued
12233 * until this effect is finished, else returns false if blocking is not set. This is commonly
12234 * used to ensure that an effect initiated by a user action runs to completion prior to the
12235 * same effect being restarted (e.g., firing only one effect even if the user clicks several times).
12236 * @return {Boolean} True if blocking, else false
12238 hasFxBlock : function(){
12239 var q = this.fxQueue;
12240 return q && q[0] && q[0].block;
12244 queueFx : function(o, fn){
12248 if(!this.hasFxBlock()){
12249 Roo.applyIf(o, this.fxDefaults);
12251 var run = this.beforeFx(o);
12252 fn.block = o.block;
12253 this.fxQueue.push(fn);
12265 fxWrap : function(pos, o, vis){
12267 if(!o.wrap || !(wrap = Roo.get(o.wrap))){
12270 wrapXY = this.getXY();
12272 var div = document.createElement("div");
12273 div.style.visibility = vis;
12274 wrap = Roo.get(this.dom.parentNode.insertBefore(div, this.dom));
12275 wrap.setPositioning(pos);
12276 if(wrap.getStyle("position") == "static"){
12277 wrap.position("relative");
12279 this.clearPositioning('auto');
12281 wrap.dom.appendChild(this.dom);
12283 wrap.setXY(wrapXY);
12290 fxUnwrap : function(wrap, pos, o){
12291 this.clearPositioning();
12292 this.setPositioning(pos);
12294 wrap.dom.parentNode.insertBefore(this.dom, wrap.dom);
12300 getFxRestore : function(){
12301 var st = this.dom.style;
12302 return {pos: this.getPositioning(), width: st.width, height : st.height};
12306 afterFx : function(o){
12308 this.applyStyles(o.afterStyle);
12311 this.addClass(o.afterCls);
12313 if(o.remove === true){
12316 Roo.callback(o.callback, o.scope, [this]);
12318 this.fxQueue.shift();
12324 getFxEl : function(){ // support for composite element fx
12325 return Roo.get(this.dom);
12329 fxanim : function(args, opt, animType, defaultDur, defaultEase, cb){
12330 animType = animType || 'run';
12332 var anim = Roo.lib.Anim[animType](
12334 (opt.duration || defaultDur) || .35,
12335 (opt.easing || defaultEase) || 'easeOut',
12337 Roo.callback(cb, this);
12346 // backwords compat
12347 Roo.Fx.resize = Roo.Fx.scale;
12349 //When included, Roo.Fx is automatically applied to Element so that all basic
12350 //effects are available directly via the Element API
12351 Roo.apply(Roo.Element.prototype, Roo.Fx);/*
12353 * Ext JS Library 1.1.1
12354 * Copyright(c) 2006-2007, Ext JS, LLC.
12356 * Originally Released Under LGPL - original licence link has changed is not relivant.
12359 * <script type="text/javascript">
12364 * @class Roo.CompositeElement
12365 * Standard composite class. Creates a Roo.Element for every element in the collection.
12367 * <b>NOTE: Although they are not listed, this class supports all of the set/update methods of Roo.Element. All Roo.Element
12368 * actions will be performed on all the elements in this collection.</b>
12370 * All methods return <i>this</i> and can be chained.
12372 var els = Roo.select("#some-el div.some-class", true);
12373 // or select directly from an existing element
12374 var el = Roo.get('some-el');
12375 el.select('div.some-class', true);
12377 els.setWidth(100); // all elements become 100 width
12378 els.hide(true); // all elements fade out and hide
12380 els.setWidth(100).hide(true);
12383 Roo.CompositeElement = function(els){
12384 this.elements = [];
12385 this.addElements(els);
12387 Roo.CompositeElement.prototype = {
12389 addElements : function(els){
12393 if(typeof els == "string"){
12394 els = Roo.Element.selectorFunction(els);
12396 var yels = this.elements;
12397 var index = yels.length-1;
12398 for(var i = 0, len = els.length; i < len; i++) {
12399 yels[++index] = Roo.get(els[i]);
12405 * Clears this composite and adds the elements returned by the passed selector.
12406 * @param {String/Array} els A string CSS selector, an array of elements or an element
12407 * @return {CompositeElement} this
12409 fill : function(els){
12410 this.elements = [];
12416 * Filters this composite to only elements that match the passed selector.
12417 * @param {String} selector A string CSS selector
12418 * @param {Boolean} inverse return inverse filter (not matches)
12419 * @return {CompositeElement} this
12421 filter : function(selector, inverse){
12423 inverse = inverse || false;
12424 this.each(function(el){
12425 var match = inverse ? !el.is(selector) : el.is(selector);
12427 els[els.length] = el.dom;
12434 invoke : function(fn, args){
12435 var els = this.elements;
12436 for(var i = 0, len = els.length; i < len; i++) {
12437 Roo.Element.prototype[fn].apply(els[i], args);
12442 * Adds elements to this composite.
12443 * @param {String/Array} els A string CSS selector, an array of elements or an element
12444 * @return {CompositeElement} this
12446 add : function(els){
12447 if(typeof els == "string"){
12448 this.addElements(Roo.Element.selectorFunction(els));
12449 }else if(els.length !== undefined){
12450 this.addElements(els);
12452 this.addElements([els]);
12457 * Calls the passed function passing (el, this, index) for each element in this composite.
12458 * @param {Function} fn The function to call
12459 * @param {Object} scope (optional) The <i>this</i> object (defaults to the element)
12460 * @return {CompositeElement} this
12462 each : function(fn, scope){
12463 var els = this.elements;
12464 for(var i = 0, len = els.length; i < len; i++){
12465 if(fn.call(scope || els[i], els[i], this, i) === false) {
12473 * Returns the Element object at the specified index
12474 * @param {Number} index
12475 * @return {Roo.Element}
12477 item : function(index){
12478 return this.elements[index] || null;
12482 * Returns the first Element
12483 * @return {Roo.Element}
12485 first : function(){
12486 return this.item(0);
12490 * Returns the last Element
12491 * @return {Roo.Element}
12494 return this.item(this.elements.length-1);
12498 * Returns the number of elements in this composite
12501 getCount : function(){
12502 return this.elements.length;
12506 * Returns true if this composite contains the passed element
12509 contains : function(el){
12510 return this.indexOf(el) !== -1;
12514 * Returns true if this composite contains the passed element
12517 indexOf : function(el){
12518 return this.elements.indexOf(Roo.get(el));
12523 * Removes the specified element(s).
12524 * @param {Mixed} el The id of an element, the Element itself, the index of the element in this composite
12525 * or an array of any of those.
12526 * @param {Boolean} removeDom (optional) True to also remove the element from the document
12527 * @return {CompositeElement} this
12529 removeElement : function(el, removeDom){
12530 if(el instanceof Array){
12531 for(var i = 0, len = el.length; i < len; i++){
12532 this.removeElement(el[i]);
12536 var index = typeof el == 'number' ? el : this.indexOf(el);
12539 var d = this.elements[index];
12543 d.parentNode.removeChild(d);
12546 this.elements.splice(index, 1);
12552 * Replaces the specified element with the passed element.
12553 * @param {String/HTMLElement/Element/Number} el The id of an element, the Element itself, the index of the element in this composite
12555 * @param {String/HTMLElement/Element} replacement The id of an element or the Element itself.
12556 * @param {Boolean} domReplace (Optional) True to remove and replace the element in the document too.
12557 * @return {CompositeElement} this
12559 replaceElement : function(el, replacement, domReplace){
12560 var index = typeof el == 'number' ? el : this.indexOf(el);
12563 this.elements[index].replaceWith(replacement);
12565 this.elements.splice(index, 1, Roo.get(replacement))
12572 * Removes all elements.
12574 clear : function(){
12575 this.elements = [];
12579 Roo.CompositeElement.createCall = function(proto, fnName){
12580 if(!proto[fnName]){
12581 proto[fnName] = function(){
12582 return this.invoke(fnName, arguments);
12586 for(var fnName in Roo.Element.prototype){
12587 if(typeof Roo.Element.prototype[fnName] == "function"){
12588 Roo.CompositeElement.createCall(Roo.CompositeElement.prototype, fnName);
12594 * Ext JS Library 1.1.1
12595 * Copyright(c) 2006-2007, Ext JS, LLC.
12597 * Originally Released Under LGPL - original licence link has changed is not relivant.
12600 * <script type="text/javascript">
12604 * @class Roo.CompositeElementLite
12605 * @extends Roo.CompositeElement
12606 * Flyweight composite class. Reuses the same Roo.Element for element operations.
12608 var els = Roo.select("#some-el div.some-class");
12609 // or select directly from an existing element
12610 var el = Roo.get('some-el');
12611 el.select('div.some-class');
12613 els.setWidth(100); // all elements become 100 width
12614 els.hide(true); // all elements fade out and hide
12616 els.setWidth(100).hide(true);
12617 </code></pre><br><br>
12618 * <b>NOTE: Although they are not listed, this class supports all of the set/update methods of Roo.Element. All Roo.Element
12619 * actions will be performed on all the elements in this collection.</b>
12621 Roo.CompositeElementLite = function(els){
12622 Roo.CompositeElementLite.superclass.constructor.call(this, els);
12623 this.el = new Roo.Element.Flyweight();
12625 Roo.extend(Roo.CompositeElementLite, Roo.CompositeElement, {
12626 addElements : function(els){
12628 if(els instanceof Array){
12629 this.elements = this.elements.concat(els);
12631 var yels = this.elements;
12632 var index = yels.length-1;
12633 for(var i = 0, len = els.length; i < len; i++) {
12634 yels[++index] = els[i];
12640 invoke : function(fn, args){
12641 var els = this.elements;
12643 for(var i = 0, len = els.length; i < len; i++) {
12645 Roo.Element.prototype[fn].apply(el, args);
12650 * Returns a flyweight Element of the dom element object at the specified index
12651 * @param {Number} index
12652 * @return {Roo.Element}
12654 item : function(index){
12655 if(!this.elements[index]){
12658 this.el.dom = this.elements[index];
12662 // fixes scope with flyweight
12663 addListener : function(eventName, handler, scope, opt){
12664 var els = this.elements;
12665 for(var i = 0, len = els.length; i < len; i++) {
12666 Roo.EventManager.on(els[i], eventName, handler, scope || els[i], opt);
12672 * Calls the passed function passing (el, this, index) for each element in this composite. <b>The element
12673 * passed is the flyweight (shared) Roo.Element instance, so if you require a
12674 * a reference to the dom node, use el.dom.</b>
12675 * @param {Function} fn The function to call
12676 * @param {Object} scope (optional) The <i>this</i> object (defaults to the element)
12677 * @return {CompositeElement} this
12679 each : function(fn, scope){
12680 var els = this.elements;
12682 for(var i = 0, len = els.length; i < len; i++){
12684 if(fn.call(scope || el, el, this, i) === false){
12691 indexOf : function(el){
12692 return this.elements.indexOf(Roo.getDom(el));
12695 replaceElement : function(el, replacement, domReplace){
12696 var index = typeof el == 'number' ? el : this.indexOf(el);
12698 replacement = Roo.getDom(replacement);
12700 var d = this.elements[index];
12701 d.parentNode.insertBefore(replacement, d);
12702 d.parentNode.removeChild(d);
12704 this.elements.splice(index, 1, replacement);
12709 Roo.CompositeElementLite.prototype.on = Roo.CompositeElementLite.prototype.addListener;
12713 * Ext JS Library 1.1.1
12714 * Copyright(c) 2006-2007, Ext JS, LLC.
12716 * Originally Released Under LGPL - original licence link has changed is not relivant.
12719 * <script type="text/javascript">
12725 * @class Roo.data.Connection
12726 * @extends Roo.util.Observable
12727 * The class encapsulates a connection to the page's originating domain, allowing requests to be made
12728 * either to a configured URL, or to a URL specified at request time.
12730 * Requests made by this class are asynchronous, and will return immediately. No data from
12731 * the server will be available to the statement immediately following the {@link #request} call.
12732 * To process returned data, use a callback in the request options object, or an event listener.
12734 * Note: If you are doing a file upload, you will not get a normal response object sent back to
12735 * your callback or event handler. Since the upload is handled via in IFRAME, there is no XMLHttpRequest.
12736 * The response object is created using the innerHTML of the IFRAME's document as the responseText
12737 * property and, if present, the IFRAME's XML document as the responseXML property.
12739 * This means that a valid XML or HTML document must be returned. If JSON data is required, it is suggested
12740 * that it be placed either inside a <textarea> in an HTML document and retrieved from the responseText
12741 * using a regex, or inside a CDATA section in an XML document and retrieved from the responseXML using
12742 * standard DOM methods.
12744 * @param {Object} config a configuration object.
12746 Roo.data.Connection = function(config){
12747 Roo.apply(this, config);
12750 * @event beforerequest
12751 * Fires before a network request is made to retrieve a data object.
12752 * @param {Connection} conn This Connection object.
12753 * @param {Object} options The options config object passed to the {@link #request} method.
12755 "beforerequest" : true,
12757 * @event requestcomplete
12758 * Fires if the request was successfully completed.
12759 * @param {Connection} conn This Connection object.
12760 * @param {Object} response The XHR object containing the response data.
12761 * See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
12762 * @param {Object} options The options config object passed to the {@link #request} method.
12764 "requestcomplete" : true,
12766 * @event requestexception
12767 * Fires if an error HTTP status was returned from the server.
12768 * See {@link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html} for details of HTTP status codes.
12769 * @param {Connection} conn This Connection object.
12770 * @param {Object} response The XHR object containing the response data.
12771 * See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
12772 * @param {Object} options The options config object passed to the {@link #request} method.
12774 "requestexception" : true
12776 Roo.data.Connection.superclass.constructor.call(this);
12779 Roo.extend(Roo.data.Connection, Roo.util.Observable, {
12781 * @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
12784 * @cfg {Object} extraParams (Optional) An object containing properties which are used as
12785 * extra parameters to each request made by this object. (defaults to undefined)
12788 * @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
12789 * to each request made by this object. (defaults to undefined)
12792 * @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)
12795 * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
12799 * @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
12805 * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
12808 disableCaching: true,
12811 * Sends an HTTP request to a remote server.
12812 * @param {Object} options An object which may contain the following properties:<ul>
12813 * <li><b>url</b> {String} (Optional) The URL to which to send the request. Defaults to configured URL</li>
12814 * <li><b>params</b> {Object/String/Function} (Optional) An object containing properties which are used as parameters to the
12815 * request, a url encoded string or a function to call to get either.</li>
12816 * <li><b>method</b> {String} (Optional) The HTTP method to use for the request. Defaults to the configured method, or
12817 * if no method was configured, "GET" if no parameters are being sent, and "POST" if parameters are being sent.</li>
12818 * <li><b>callback</b> {Function} (Optional) The function to be called upon receipt of the HTTP response.
12819 * The callback is called regardless of success or failure and is passed the following parameters:<ul>
12820 * <li>options {Object} The parameter to the request call.</li>
12821 * <li>success {Boolean} True if the request succeeded.</li>
12822 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
12824 * <li><b>success</b> {Function} (Optional) The function to be called upon success of the request.
12825 * The callback is passed the following parameters:<ul>
12826 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
12827 * <li>options {Object} The parameter to the request call.</li>
12829 * <li><b>failure</b> {Function} (Optional) The function to be called upon failure of the request.
12830 * The callback is passed the following parameters:<ul>
12831 * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
12832 * <li>options {Object} The parameter to the request call.</li>
12834 * <li><b>scope</b> {Object} (Optional) The scope in which to execute the callbacks: The "this" object
12835 * for the callback function. Defaults to the browser window.</li>
12836 * <li><b>form</b> {Object/String} (Optional) A form object or id to pull parameters from.</li>
12837 * <li><b>isUpload</b> {Boolean} (Optional) True if the form object is a file upload (will usually be automatically detected).</li>
12838 * <li><b>headers</b> {Object} (Optional) Request headers to set for the request.</li>
12839 * <li><b>xmlData</b> {Object} (Optional) XML document to use for the post. Note: This will be used instead of
12840 * params for the post data. Any params will be appended to the URL.</li>
12841 * <li><b>disableCaching</b> {Boolean} (Optional) True to add a unique cache-buster param to GET requests.</li>
12843 * @return {Number} transactionId
12845 request : function(o){
12846 if(this.fireEvent("beforerequest", this, o) !== false){
12849 if(typeof p == "function"){
12850 p = p.call(o.scope||window, o);
12852 if(typeof p == "object"){
12853 p = Roo.urlEncode(o.params);
12855 if(this.extraParams){
12856 var extras = Roo.urlEncode(this.extraParams);
12857 p = p ? (p + '&' + extras) : extras;
12860 var url = o.url || this.url;
12861 if(typeof url == 'function'){
12862 url = url.call(o.scope||window, o);
12866 var form = Roo.getDom(o.form);
12867 url = url || form.action;
12869 var enctype = form.getAttribute("enctype");
12872 return this.doFormDataUpload(o, url);
12875 if(o.isUpload || (enctype && enctype.toLowerCase() == 'multipart/form-data')){
12876 return this.doFormUpload(o, p, url);
12878 var f = Roo.lib.Ajax.serializeForm(form);
12879 p = p ? (p + '&' + f) : f;
12882 if (!o.form && o.formData) {
12883 o.formData = o.formData === true ? new FormData() : o.formData;
12884 for (var k in o.params) {
12885 o.formData.append(k,o.params[k]);
12888 return this.doFormDataUpload(o, url);
12892 var hs = o.headers;
12893 if(this.defaultHeaders){
12894 hs = Roo.apply(hs || {}, this.defaultHeaders);
12901 success: this.handleResponse,
12902 failure: this.handleFailure,
12904 argument: {options: o},
12905 timeout : o.timeout || this.timeout
12908 var method = o.method||this.method||(p ? "POST" : "GET");
12910 if(method == 'GET' && (this.disableCaching && o.disableCaching !== false) || o.disableCaching === true){
12911 url += (url.indexOf('?') != -1 ? '&' : '?') + '_dc=' + (new Date().getTime());
12914 if(typeof o.autoAbort == 'boolean'){ // options gets top priority
12918 }else if(this.autoAbort !== false){
12922 if((method == 'GET' && p) || o.xmlData){
12923 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
12926 Roo.lib.Ajax.useDefaultHeader = typeof(o.headers) == 'undefined' || typeof(o.headers['Content-Type']) == 'undefined';
12927 this.transId = Roo.lib.Ajax.request(method, url, cb, p, o);
12928 Roo.lib.Ajax.useDefaultHeader == true;
12929 return this.transId;
12931 Roo.callback(o.callback, o.scope, [o, null, null]);
12937 * Determine whether this object has a request outstanding.
12938 * @param {Number} transactionId (Optional) defaults to the last transaction
12939 * @return {Boolean} True if there is an outstanding request.
12941 isLoading : function(transId){
12943 return Roo.lib.Ajax.isCallInProgress(transId);
12945 return this.transId ? true : false;
12950 * Aborts any outstanding request.
12951 * @param {Number} transactionId (Optional) defaults to the last transaction
12953 abort : function(transId){
12954 if(transId || this.isLoading()){
12955 Roo.lib.Ajax.abort(transId || this.transId);
12960 handleResponse : function(response){
12961 this.transId = false;
12962 var options = response.argument.options;
12963 response.argument = options ? options.argument : null;
12964 this.fireEvent("requestcomplete", this, response, options);
12965 Roo.callback(options.success, options.scope, [response, options]);
12966 Roo.callback(options.callback, options.scope, [options, true, response]);
12970 handleFailure : function(response, e){
12971 this.transId = false;
12972 var options = response.argument.options;
12973 response.argument = options ? options.argument : null;
12974 this.fireEvent("requestexception", this, response, options, e);
12975 Roo.callback(options.failure, options.scope, [response, options]);
12976 Roo.callback(options.callback, options.scope, [options, false, response]);
12980 doFormUpload : function(o, ps, url){
12982 var frame = document.createElement('iframe');
12985 frame.className = 'x-hidden';
12987 frame.src = Roo.SSL_SECURE_URL;
12989 document.body.appendChild(frame);
12992 document.frames[id].name = id;
12995 var form = Roo.getDom(o.form);
12997 form.method = 'POST';
12998 form.enctype = form.encoding = 'multipart/form-data';
13004 if(ps){ // add dynamic params
13006 ps = Roo.urlDecode(ps, false);
13008 if(ps.hasOwnProperty(k)){
13009 hd = document.createElement('input');
13010 hd.type = 'hidden';
13013 form.appendChild(hd);
13020 var r = { // bogus response object
13025 r.argument = o ? o.argument : null;
13030 doc = frame.contentWindow.document;
13032 doc = (frame.contentDocument || window.frames[id].document);
13034 if(doc && doc.body){
13035 r.responseText = doc.body.innerHTML;
13037 if(doc && doc.XMLDocument){
13038 r.responseXML = doc.XMLDocument;
13040 r.responseXML = doc;
13047 Roo.EventManager.removeListener(frame, 'load', cb, this);
13049 this.fireEvent("requestcomplete", this, r, o);
13050 Roo.callback(o.success, o.scope, [r, o]);
13051 Roo.callback(o.callback, o.scope, [o, true, r]);
13053 setTimeout(function(){document.body.removeChild(frame);}, 100);
13056 Roo.EventManager.on(frame, 'load', cb, this);
13059 if(hiddens){ // remove dynamic params
13060 for(var i = 0, len = hiddens.length; i < len; i++){
13061 form.removeChild(hiddens[i]);
13065 // this is a 'formdata version???'
13068 doFormDataUpload : function(o, url)
13072 var form = Roo.getDom(o.form);
13073 form.enctype = form.encoding = 'multipart/form-data';
13074 formData = o.formData === true ? new FormData(form) : o.formData;
13076 formData = o.formData === true ? new FormData() : o.formData;
13081 success: this.handleResponse,
13082 failure: this.handleFailure,
13084 argument: {options: o},
13085 timeout : o.timeout || this.timeout
13088 if(typeof o.autoAbort == 'boolean'){ // options gets top priority
13092 }else if(this.autoAbort !== false){
13096 //Roo.lib.Ajax.defaultPostHeader = null;
13097 Roo.lib.Ajax.useDefaultHeader = false;
13098 this.transId = Roo.lib.Ajax.request( "POST", url, cb, formData, o);
13099 Roo.lib.Ajax.useDefaultHeader = true;
13107 * Ext JS Library 1.1.1
13108 * Copyright(c) 2006-2007, Ext JS, LLC.
13110 * Originally Released Under LGPL - original licence link has changed is not relivant.
13113 * <script type="text/javascript">
13117 * Global Ajax request class.
13120 * @extends Roo.data.Connection
13123 * @cfg {String} url The default URL to be used for requests to the server. (defaults to undefined)
13124 * @cfg {Object} extraParams An object containing properties which are used as extra parameters to each request made by this object. (defaults to undefined)
13125 * @cfg {Object} defaultHeaders An object containing request headers which are added to each request made by this object. (defaults to undefined)
13126 * @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)
13127 * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
13128 * @cfg {Boolean} autoAbort (Optional) Whether a new request should abort any pending requests. (defaults to false)
13129 * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
13131 Roo.Ajax = new Roo.data.Connection({
13140 * Serialize the passed form into a url encoded string
13142 * @param {String/HTMLElement} form
13145 serializeForm : function(form){
13146 return Roo.lib.Ajax.serializeForm(form);
13150 * Ext JS Library 1.1.1
13151 * Copyright(c) 2006-2007, Ext JS, LLC.
13153 * Originally Released Under LGPL - original licence link has changed is not relivant.
13156 * <script type="text/javascript">
13161 * @class Roo.UpdateManager
13162 * @extends Roo.util.Observable
13163 * Provides AJAX-style update for Element object.<br><br>
13166 * // Get it from a Roo.Element object
13167 * var el = Roo.get("foo");
13168 * var mgr = el.getUpdateManager();
13169 * mgr.update("http://myserver.com/index.php", "param1=1&param2=2");
13171 * mgr.formUpdate("myFormId", "http://myserver.com/index.php");
13173 * // or directly (returns the same UpdateManager instance)
13174 * var mgr = new Roo.UpdateManager("myElementId");
13175 * mgr.startAutoRefresh(60, "http://myserver.com/index.php");
13176 * mgr.on("update", myFcnNeedsToKnow);
13178 // short handed call directly from the element object
13179 Roo.get("foo").load({
13183 text: "Loading Foo..."
13187 * Create new UpdateManager directly.
13188 * @param {String/HTMLElement/Roo.Element} el The element to update
13189 * @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).
13191 Roo.UpdateManager = function(el, forceNew){
13193 if(!forceNew && el.updateManager){
13194 return el.updateManager;
13197 * The Element object
13198 * @type Roo.Element
13202 * Cached url to use for refreshes. Overwritten every time update() is called unless "discardUrl" param is set to true.
13205 this.defaultUrl = null;
13209 * @event beforeupdate
13210 * Fired before an update is made, return false from your handler and the update is cancelled.
13211 * @param {Roo.Element} el
13212 * @param {String/Object/Function} url
13213 * @param {String/Object} params
13215 "beforeupdate": true,
13218 * Fired after successful update is made.
13219 * @param {Roo.Element} el
13220 * @param {Object} oResponseObject The response Object
13225 * Fired on update failure.
13226 * @param {Roo.Element} el
13227 * @param {Object} oResponseObject The response Object
13231 var d = Roo.UpdateManager.defaults;
13233 * Blank page URL to use with SSL file uploads (Defaults to Roo.UpdateManager.defaults.sslBlankUrl or "about:blank").
13236 this.sslBlankUrl = d.sslBlankUrl;
13238 * Whether to append unique parameter on get request to disable caching (Defaults to Roo.UpdateManager.defaults.disableCaching or false).
13241 this.disableCaching = d.disableCaching;
13243 * Text for loading indicator (Defaults to Roo.UpdateManager.defaults.indicatorText or '<div class="loading-indicator">Loading...</div>').
13246 this.indicatorText = d.indicatorText;
13248 * Whether to show indicatorText when loading (Defaults to Roo.UpdateManager.defaults.showLoadIndicator or true).
13251 this.showLoadIndicator = d.showLoadIndicator;
13253 * Timeout for requests or form posts in seconds (Defaults to Roo.UpdateManager.defaults.timeout or 30 seconds).
13256 this.timeout = d.timeout;
13259 * True to process scripts in the output (Defaults to Roo.UpdateManager.defaults.loadScripts (false)).
13262 this.loadScripts = d.loadScripts;
13265 * Transaction object of current executing transaction
13267 this.transaction = null;
13272 this.autoRefreshProcId = null;
13274 * Delegate for refresh() prebound to "this", use myUpdater.refreshDelegate.createCallback(arg1, arg2) to bind arguments
13277 this.refreshDelegate = this.refresh.createDelegate(this);
13279 * Delegate for update() prebound to "this", use myUpdater.updateDelegate.createCallback(arg1, arg2) to bind arguments
13282 this.updateDelegate = this.update.createDelegate(this);
13284 * Delegate for formUpdate() prebound to "this", use myUpdater.formUpdateDelegate.createCallback(arg1, arg2) to bind arguments
13287 this.formUpdateDelegate = this.formUpdate.createDelegate(this);
13291 this.successDelegate = this.processSuccess.createDelegate(this);
13295 this.failureDelegate = this.processFailure.createDelegate(this);
13297 if(!this.renderer){
13299 * The renderer for this UpdateManager. Defaults to {@link Roo.UpdateManager.BasicRenderer}.
13301 this.renderer = new Roo.UpdateManager.BasicRenderer();
13304 Roo.UpdateManager.superclass.constructor.call(this);
13307 Roo.extend(Roo.UpdateManager, Roo.util.Observable, {
13309 * Get the Element this UpdateManager is bound to
13310 * @return {Roo.Element} The element
13312 getEl : function(){
13316 * Performs an async request, updating this element with the response. If params are specified it uses POST, otherwise it uses GET.
13317 * @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:
13320 url: "your-url.php",<br/>
13321 params: {param1: "foo", param2: "bar"}, // or a URL encoded string<br/>
13322 callback: yourFunction,<br/>
13323 scope: yourObject, //(optional scope) <br/>
13324 discardUrl: false, <br/>
13325 nocache: false,<br/>
13326 text: "Loading...",<br/>
13328 scripts: false<br/>
13331 * The only required property is url. The optional properties nocache, text and scripts
13332 * are shorthand for disableCaching, indicatorText and loadScripts and are used to set their associated property on this UpdateManager instance.
13333 * @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}
13334 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess, oResponse)
13335 * @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.
13337 update : function(url, params, callback, discardUrl){
13338 if(this.fireEvent("beforeupdate", this.el, url, params) !== false){
13339 var method = this.method,
13341 if(typeof url == "object"){ // must be config object
13344 params = params || cfg.params;
13345 callback = callback || cfg.callback;
13346 discardUrl = discardUrl || cfg.discardUrl;
13347 if(callback && cfg.scope){
13348 callback = callback.createDelegate(cfg.scope);
13350 if(typeof cfg.method != "undefined"){method = cfg.method;};
13351 if(typeof cfg.nocache != "undefined"){this.disableCaching = cfg.nocache;};
13352 if(typeof cfg.text != "undefined"){this.indicatorText = '<div class="loading-indicator">'+cfg.text+"</div>";};
13353 if(typeof cfg.scripts != "undefined"){this.loadScripts = cfg.scripts;};
13354 if(typeof cfg.timeout != "undefined"){this.timeout = cfg.timeout;};
13356 this.showLoading();
13358 this.defaultUrl = url;
13360 if(typeof url == "function"){
13361 url = url.call(this);
13364 method = method || (params ? "POST" : "GET");
13365 if(method == "GET"){
13366 url = this.prepareUrl(url);
13369 var o = Roo.apply(cfg ||{}, {
13372 success: this.successDelegate,
13373 failure: this.failureDelegate,
13374 callback: undefined,
13375 timeout: (this.timeout*1000),
13376 argument: {"url": url, "form": null, "callback": callback, "params": params}
13378 Roo.log("updated manager called with timeout of " + o.timeout);
13379 this.transaction = Roo.Ajax.request(o);
13384 * 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.
13385 * Uses this.sslBlankUrl for SSL file uploads to prevent IE security warning.
13386 * @param {String/HTMLElement} form The form Id or form element
13387 * @param {String} url (optional) The url to pass the form to. If omitted the action attribute on the form will be used.
13388 * @param {Boolean} reset (optional) Whether to try to reset the form after the update
13389 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess, oResponse)
13391 formUpdate : function(form, url, reset, callback){
13392 if(this.fireEvent("beforeupdate", this.el, form, url) !== false){
13393 if(typeof url == "function"){
13394 url = url.call(this);
13396 form = Roo.getDom(form);
13397 this.transaction = Roo.Ajax.request({
13400 success: this.successDelegate,
13401 failure: this.failureDelegate,
13402 timeout: (this.timeout*1000),
13403 argument: {"url": url, "form": form, "callback": callback, "reset": reset}
13405 this.showLoading.defer(1, this);
13410 * Refresh the element with the last used url or defaultUrl. If there is no url, it returns immediately
13411 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
13413 refresh : function(callback){
13414 if(this.defaultUrl == null){
13417 this.update(this.defaultUrl, null, callback, true);
13421 * Set this element to auto refresh.
13422 * @param {Number} interval How often to update (in seconds).
13423 * @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)
13424 * @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}
13425 * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess)
13426 * @param {Boolean} refreshNow (optional) Whether to execute the refresh now, or wait the interval
13428 startAutoRefresh : function(interval, url, params, callback, refreshNow){
13430 this.update(url || this.defaultUrl, params, callback, true);
13432 if(this.autoRefreshProcId){
13433 clearInterval(this.autoRefreshProcId);
13435 this.autoRefreshProcId = setInterval(this.update.createDelegate(this, [url || this.defaultUrl, params, callback, true]), interval*1000);
13439 * Stop auto refresh on this element.
13441 stopAutoRefresh : function(){
13442 if(this.autoRefreshProcId){
13443 clearInterval(this.autoRefreshProcId);
13444 delete this.autoRefreshProcId;
13448 isAutoRefreshing : function(){
13449 return this.autoRefreshProcId ? true : false;
13452 * Called to update the element to "Loading" state. Override to perform custom action.
13454 showLoading : function(){
13455 if(this.showLoadIndicator){
13456 this.el.update(this.indicatorText);
13461 * Adds unique parameter to query string if disableCaching = true
13464 prepareUrl : function(url){
13465 if(this.disableCaching){
13466 var append = "_dc=" + (new Date().getTime());
13467 if(url.indexOf("?") !== -1){
13468 url += "&" + append;
13470 url += "?" + append;
13479 processSuccess : function(response){
13480 this.transaction = null;
13481 if(response.argument.form && response.argument.reset){
13482 try{ // put in try/catch since some older FF releases had problems with this
13483 response.argument.form.reset();
13486 if(this.loadScripts){
13487 this.renderer.render(this.el, response, this,
13488 this.updateComplete.createDelegate(this, [response]));
13490 this.renderer.render(this.el, response, this);
13491 this.updateComplete(response);
13495 updateComplete : function(response){
13496 this.fireEvent("update", this.el, response);
13497 if(typeof response.argument.callback == "function"){
13498 response.argument.callback(this.el, true, response);
13505 processFailure : function(response){
13506 this.transaction = null;
13507 this.fireEvent("failure", this.el, response);
13508 if(typeof response.argument.callback == "function"){
13509 response.argument.callback(this.el, false, response);
13514 * Set the content renderer for this UpdateManager. See {@link Roo.UpdateManager.BasicRenderer#render} for more details.
13515 * @param {Object} renderer The object implementing the render() method
13517 setRenderer : function(renderer){
13518 this.renderer = renderer;
13521 getRenderer : function(){
13522 return this.renderer;
13526 * Set the defaultUrl used for updates
13527 * @param {String/Function} defaultUrl The url or a function to call to get the url
13529 setDefaultUrl : function(defaultUrl){
13530 this.defaultUrl = defaultUrl;
13534 * Aborts the executing transaction
13536 abort : function(){
13537 if(this.transaction){
13538 Roo.Ajax.abort(this.transaction);
13543 * Returns true if an update is in progress
13544 * @return {Boolean}
13546 isUpdating : function(){
13547 if(this.transaction){
13548 return Roo.Ajax.isLoading(this.transaction);
13555 * @class Roo.UpdateManager.defaults
13556 * @static (not really - but it helps the doc tool)
13557 * The defaults collection enables customizing the default properties of UpdateManager
13559 Roo.UpdateManager.defaults = {
13561 * Timeout for requests or form posts in seconds (Defaults 30 seconds).
13567 * True to process scripts by default (Defaults to false).
13570 loadScripts : false,
13573 * Blank page URL to use with SSL file uploads (Defaults to "javascript:false").
13576 sslBlankUrl : (Roo.SSL_SECURE_URL || "javascript:false"),
13578 * Whether to append unique parameter on get request to disable caching (Defaults to false).
13581 disableCaching : false,
13583 * Whether to show indicatorText when loading (Defaults to true).
13586 showLoadIndicator : true,
13588 * Text for loading indicator (Defaults to '<div class="loading-indicator">Loading...</div>').
13591 indicatorText : '<div class="loading-indicator">Loading...</div>'
13595 * Static convenience method. This method is deprecated in favor of el.load({url:'foo.php', ...}).
13597 * <pre><code>Roo.UpdateManager.updateElement("my-div", "stuff.php");</code></pre>
13598 * @param {String/HTMLElement/Roo.Element} el The element to update
13599 * @param {String} url The url
13600 * @param {String/Object} params (optional) Url encoded param string or an object of name/value pairs
13601 * @param {Object} options (optional) A config object with any of the UpdateManager properties you want to set - for example: {disableCaching:true, indicatorText: "Loading data..."}
13604 * @member Roo.UpdateManager
13606 Roo.UpdateManager.updateElement = function(el, url, params, options){
13607 var um = Roo.get(el, true).getUpdateManager();
13608 Roo.apply(um, options);
13609 um.update(url, params, options ? options.callback : null);
13611 // alias for backwards compat
13612 Roo.UpdateManager.update = Roo.UpdateManager.updateElement;
13614 * @class Roo.UpdateManager.BasicRenderer
13615 * Default Content renderer. Updates the elements innerHTML with the responseText.
13617 Roo.UpdateManager.BasicRenderer = function(){};
13619 Roo.UpdateManager.BasicRenderer.prototype = {
13621 * This is called when the transaction is completed and it's time to update the element - The BasicRenderer
13622 * updates the elements innerHTML with the responseText - To perform a custom render (i.e. XML or JSON processing),
13623 * create an object with a "render(el, response)" method and pass it to setRenderer on the UpdateManager.
13624 * @param {Roo.Element} el The element being rendered
13625 * @param {Object} response The YUI Connect response object
13626 * @param {UpdateManager} updateManager The calling update manager
13627 * @param {Function} callback A callback that will need to be called if loadScripts is true on the UpdateManager
13629 render : function(el, response, updateManager, callback){
13630 el.update(response.responseText, updateManager.loadScripts, callback);
13636 * (c)) Alan Knowles
13642 * @class Roo.DomTemplate
13643 * @extends Roo.Template
13644 * An effort at a dom based template engine..
13646 * Similar to XTemplate, except it uses dom parsing to create the template..
13648 * Supported features:
13653 {a_variable} - output encoded.
13654 {a_variable.format:("Y-m-d")} - call a method on the variable
13655 {a_variable:raw} - unencoded output
13656 {a_variable:toFixed(1,2)} - Roo.util.Format."toFixed"
13657 {a_variable:this.method_on_template(...)} - call a method on the template object.
13662 <div roo-for="a_variable or condition.."></div>
13663 <div roo-if="a_variable or condition"></div>
13664 <div roo-exec="some javascript"></div>
13665 <div roo-name="named_template"></div>
13670 Roo.DomTemplate = function()
13672 Roo.DomTemplate.superclass.constructor.apply(this, arguments);
13679 Roo.extend(Roo.DomTemplate, Roo.Template, {
13681 * id counter for sub templates.
13685 * flag to indicate if dom parser is inside a pre,
13686 * it will strip whitespace if not.
13691 * The various sub templates
13699 * basic tag replacing syntax
13702 * // you can fake an object call by doing this
13706 re : /(\{|\%7B)([\w-\.]+)(?:\:([\w\.]*)(?:\(([^)]*?)?\))?)?(\}|\%7D)/g,
13707 //re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
13709 iterChild : function (node, method) {
13711 var oldPre = this.inPre;
13712 if (node.tagName == 'PRE') {
13715 for( var i = 0; i < node.childNodes.length; i++) {
13716 method.call(this, node.childNodes[i]);
13718 this.inPre = oldPre;
13724 * compile the template
13726 * This is not recursive, so I'm not sure how nested templates are really going to be handled..
13729 compile: function()
13733 // covert the html into DOM...
13737 doc = document.implementation.createHTMLDocument("");
13738 doc.documentElement.innerHTML = this.html ;
13739 div = doc.documentElement;
13741 // old IE... - nasty -- it causes all sorts of issues.. with
13742 // images getting pulled from server..
13743 div = document.createElement('div');
13744 div.innerHTML = this.html;
13746 //doc.documentElement.innerHTML = htmlBody
13752 this.iterChild(div, function(n) {_t.compileNode(n, true); });
13754 var tpls = this.tpls;
13756 // create a top level template from the snippet..
13758 //Roo.log(div.innerHTML);
13765 body : div.innerHTML,
13778 Roo.each(tpls, function(tp){
13779 this.compileTpl(tp);
13780 this.tpls[tp.id] = tp;
13783 this.master = tpls[0];
13789 compileNode : function(node, istop) {
13794 // skip anything not a tag..
13795 if (node.nodeType != 1) {
13796 if (node.nodeType == 3 && !this.inPre) {
13797 // reduce white space..
13798 node.nodeValue = node.nodeValue.replace(/\s+/g, ' ');
13821 case (node.hasAttribute('roo-for')): tpl.attr = 'for'; break;
13822 case (node.hasAttribute('roo-if')): tpl.attr = 'if'; break;
13823 case (node.hasAttribute('roo-name')): tpl.attr = 'name'; break;
13824 case (node.hasAttribute('roo-exec')): tpl.attr = 'exec'; break;
13830 // just itterate children..
13831 this.iterChild(node,this.compileNode);
13834 tpl.uid = this.id++;
13835 tpl.value = node.getAttribute('roo-' + tpl.attr);
13836 node.removeAttribute('roo-'+ tpl.attr);
13837 if (tpl.attr != 'name') {
13838 var placeholder = document.createTextNode('{domtpl' + tpl.uid + '}');
13839 node.parentNode.replaceChild(placeholder, node);
13842 var placeholder = document.createElement('span');
13843 placeholder.className = 'roo-tpl-' + tpl.value;
13844 node.parentNode.replaceChild(placeholder, node);
13847 // parent now sees '{domtplXXXX}
13848 this.iterChild(node,this.compileNode);
13850 // we should now have node body...
13851 var div = document.createElement('div');
13852 div.appendChild(node);
13854 // this has the unfortunate side effect of converting tagged attributes
13855 // eg. href="{...}" into %7C...%7D
13856 // this has been fixed by searching for those combo's although it's a bit hacky..
13859 tpl.body = div.innerHTML;
13866 switch (tpl.value) {
13867 case '.': tpl.forCall = new Function('values', 'parent', 'with(values){ return values; }'); break;
13868 case '..': tpl.forCall= new Function('values', 'parent', 'with(values){ return parent; }'); break;
13869 default: tpl.forCall= new Function('values', 'parent', 'with(values){ return '+tpl.value+'; }');
13874 tpl.execCall = new Function('values', 'parent', 'with(values){ '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
13878 tpl.ifCall = new Function('values', 'parent', 'with(values){ return '+(Roo.util.Format.htmlDecode(tpl.value))+'; }');
13882 tpl.id = tpl.value; // replace non characters???
13888 this.tpls.push(tpl);
13898 * Compile a segment of the template into a 'sub-template'
13904 compileTpl : function(tpl)
13906 var fm = Roo.util.Format;
13907 var useF = this.disableFormats !== true;
13909 var sep = Roo.isGecko ? "+\n" : ",\n";
13911 var undef = function(str) {
13912 Roo.debug && Roo.log("Property not found :" + str);
13916 //Roo.log(tpl.body);
13920 var fn = function(m, lbrace, name, format, args)
13923 //Roo.log(arguments);
13924 args = args ? args.replace(/\\'/g,"'") : args;
13925 //["{TEST:(a,b,c)}", "TEST", "", "a,b,c", 0, "{TEST:(a,b,c)}"]
13926 if (typeof(format) == 'undefined') {
13927 format = 'htmlEncode';
13929 if (format == 'raw' ) {
13933 if(name.substr(0, 6) == 'domtpl'){
13934 return "'"+ sep +'this.applySubTemplate('+name.substr(6)+', values, parent)'+sep+"'";
13937 // build an array of options to determine if value is undefined..
13939 // basically get 'xxxx.yyyy' then do
13940 // (typeof(xxxx) == 'undefined' || typeof(xxx.yyyy) == 'undefined') ?
13941 // (function () { Roo.log("Property not found"); return ''; })() :
13946 Roo.each(name.split('.'), function(st) {
13947 lookfor += (lookfor.length ? '.': '') + st;
13948 udef_ar.push( "(typeof(" + lookfor + ") == 'undefined')" );
13951 var udef_st = '((' + udef_ar.join(" || ") +") ? undef('" + name + "') : "; // .. needs )
13954 if(format && useF){
13956 args = args ? ',' + args : "";
13958 if(format.substr(0, 5) != "this."){
13959 format = "fm." + format + '(';
13961 format = 'this.call("'+ format.substr(5) + '", ';
13965 return "'"+ sep + udef_st + format + name + args + "))"+sep+"'";
13968 if (args && args.length) {
13969 // called with xxyx.yuu:(test,test)
13971 return "'"+ sep + udef_st + name + '(' + args + "))"+sep+"'";
13973 // raw.. - :raw modifier..
13974 return "'"+ sep + udef_st + name + ")"+sep+"'";
13978 // branched to use + in gecko and [].join() in others
13980 body = "tpl.compiled = function(values, parent){ with(values) { return '" +
13981 tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
13984 body = ["tpl.compiled = function(values, parent){ with (values) { return ['"];
13985 body.push(tpl.body.replace(/(\r\n|\n)/g,
13986 '\\n').replace(/'/g, "\\'").replace(this.re, fn));
13987 body.push("'].join('');};};");
13988 body = body.join('');
13991 Roo.debug && Roo.log(body.replace(/\\n/,'\n'));
13993 /** eval:var:tpl eval:var:fm eval:var:useF eval:var:undef */
14000 * same as applyTemplate, except it's done to one of the subTemplates
14001 * when using named templates, you can do:
14003 * var str = pl.applySubTemplate('your-name', values);
14006 * @param {Number} id of the template
14007 * @param {Object} values to apply to template
14008 * @param {Object} parent (normaly the instance of this object)
14010 applySubTemplate : function(id, values, parent)
14014 var t = this.tpls[id];
14018 if(t.ifCall && !t.ifCall.call(this, values, parent)){
14019 Roo.debug && Roo.log('if call on ' + t.value + ' return false');
14023 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-if="' + t.value + '" - ' + e.toString());
14030 if(t.execCall && t.execCall.call(this, values, parent)){
14034 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
14040 var vs = t.forCall ? t.forCall.call(this, values, parent) : values;
14041 parent = t.target ? values : parent;
14042 if(t.forCall && vs instanceof Array){
14044 for(var i = 0, len = vs.length; i < len; i++){
14046 buf[buf.length] = t.compiled.call(this, vs[i], parent);
14048 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
14050 //Roo.log(t.compiled);
14054 return buf.join('');
14057 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on roo-for="' + t.value + '" - ' + e.toString());
14062 return t.compiled.call(this, vs, parent);
14064 Roo.log('Xtemplate.applySubTemplate('+ id+ '): Exception thrown on body="' + t.value + '" - ' + e.toString());
14066 //Roo.log(t.compiled);
14074 applyTemplate : function(values){
14075 return this.master.compiled.call(this, values, {});
14076 //var s = this.subs;
14079 apply : function(){
14080 return this.applyTemplate.apply(this, arguments);
14085 Roo.DomTemplate.from = function(el){
14086 el = Roo.getDom(el);
14087 return new Roo.Domtemplate(el.value || el.innerHTML);
14090 * Ext JS Library 1.1.1
14091 * Copyright(c) 2006-2007, Ext JS, LLC.
14093 * Originally Released Under LGPL - original licence link has changed is not relivant.
14096 * <script type="text/javascript">
14100 * @class Roo.util.DelayedTask
14101 * Provides a convenient method of performing setTimeout where a new
14102 * timeout cancels the old timeout. An example would be performing validation on a keypress.
14103 * You can use this class to buffer
14104 * the keypress events for a certain number of milliseconds, and perform only if they stop
14105 * for that amount of time.
14106 * @constructor The parameters to this constructor serve as defaults and are not required.
14107 * @param {Function} fn (optional) The default function to timeout
14108 * @param {Object} scope (optional) The default scope of that timeout
14109 * @param {Array} args (optional) The default Array of arguments
14111 Roo.util.DelayedTask = function(fn, scope, args){
14112 var id = null, d, t;
14114 var call = function(){
14115 var now = new Date().getTime();
14119 fn.apply(scope, args || []);
14123 * Cancels any pending timeout and queues a new one
14124 * @param {Number} delay The milliseconds to delay
14125 * @param {Function} newFn (optional) Overrides function passed to constructor
14126 * @param {Object} newScope (optional) Overrides scope passed to constructor
14127 * @param {Array} newArgs (optional) Overrides args passed to constructor
14129 this.delay = function(delay, newFn, newScope, newArgs){
14130 if(id && delay != d){
14134 t = new Date().getTime();
14136 scope = newScope || scope;
14137 args = newArgs || args;
14139 id = setInterval(call, d);
14144 * Cancel the last queued timeout
14146 this.cancel = function(){
14154 * Ext JS Library 1.1.1
14155 * Copyright(c) 2006-2007, Ext JS, LLC.
14157 * Originally Released Under LGPL - original licence link has changed is not relivant.
14160 * <script type="text/javascript">
14163 * @class Roo.util.TaskRunner
14164 * Manage background tasks - not sure why this is better that setInterval?
14169 Roo.util.TaskRunner = function(interval){
14170 interval = interval || 10;
14171 var tasks = [], removeQueue = [];
14173 var running = false;
14175 var stopThread = function(){
14181 var startThread = function(){
14184 id = setInterval(runTasks, interval);
14188 var removeTask = function(task){
14189 removeQueue.push(task);
14195 var runTasks = function(){
14196 if(removeQueue.length > 0){
14197 for(var i = 0, len = removeQueue.length; i < len; i++){
14198 tasks.remove(removeQueue[i]);
14201 if(tasks.length < 1){
14206 var now = new Date().getTime();
14207 for(var i = 0, len = tasks.length; i < len; ++i){
14209 var itime = now - t.taskRunTime;
14210 if(t.interval <= itime){
14211 var rt = t.run.apply(t.scope || t, t.args || [++t.taskRunCount]);
14212 t.taskRunTime = now;
14213 if(rt === false || t.taskRunCount === t.repeat){
14218 if(t.duration && t.duration <= (now - t.taskStartTime)){
14225 * Queues a new task.
14226 * @param {Object} task
14228 * Task property : interval = how frequent to run.
14229 * Task object should implement
14231 * Task object may implement
14232 * function onStop()
14234 this.start = function(task){
14236 task.taskStartTime = new Date().getTime();
14237 task.taskRunTime = 0;
14238 task.taskRunCount = 0;
14244 * @param {Object} task
14246 this.stop = function(task){
14253 this.stopAll = function(){
14255 for(var i = 0, len = tasks.length; i < len; i++){
14256 if(tasks[i].onStop){
14265 Roo.TaskMgr = new Roo.util.TaskRunner();/*
14267 * Ext JS Library 1.1.1
14268 * Copyright(c) 2006-2007, Ext JS, LLC.
14270 * Originally Released Under LGPL - original licence link has changed is not relivant.
14273 * <script type="text/javascript">
14278 * @class Roo.util.MixedCollection
14279 * @extends Roo.util.Observable
14280 * A Collection class that maintains both numeric indexes and keys and exposes events.
14282 * @param {Boolean} allowFunctions True if the addAll function should add function references to the
14283 * collection (defaults to false)
14284 * @param {Function} keyFn A function that can accept an item of the type(s) stored in this MixedCollection
14285 * and return the key value for that item. This is used when available to look up the key on items that
14286 * were passed without an explicit key parameter to a MixedCollection method. Passing this parameter is
14287 * equivalent to providing an implementation for the {@link #getKey} method.
14289 Roo.util.MixedCollection = function(allowFunctions, keyFn){
14297 * Fires when the collection is cleared.
14302 * Fires when an item is added to the collection.
14303 * @param {Number} index The index at which the item was added.
14304 * @param {Object} o The item added.
14305 * @param {String} key The key associated with the added item.
14310 * Fires when an item is replaced in the collection.
14311 * @param {String} key he key associated with the new added.
14312 * @param {Object} old The item being replaced.
14313 * @param {Object} new The new item.
14318 * Fires when an item is removed from the collection.
14319 * @param {Object} o The item being removed.
14320 * @param {String} key (optional) The key associated with the removed item.
14325 this.allowFunctions = allowFunctions === true;
14327 this.getKey = keyFn;
14329 Roo.util.MixedCollection.superclass.constructor.call(this);
14332 Roo.extend(Roo.util.MixedCollection, Roo.util.Observable, {
14333 allowFunctions : false,
14336 * Adds an item to the collection.
14337 * @param {String} key The key to associate with the item
14338 * @param {Object} o The item to add.
14339 * @return {Object} The item added.
14341 add : function(key, o){
14342 if(arguments.length == 1){
14344 key = this.getKey(o);
14346 if(typeof key == "undefined" || key === null){
14348 this.items.push(o);
14349 this.keys.push(null);
14351 var old = this.map[key];
14353 return this.replace(key, o);
14356 this.items.push(o);
14358 this.keys.push(key);
14360 this.fireEvent("add", this.length-1, o, key);
14365 * MixedCollection has a generic way to fetch keys if you implement getKey.
14368 var mc = new Roo.util.MixedCollection();
14369 mc.add(someEl.dom.id, someEl);
14370 mc.add(otherEl.dom.id, otherEl);
14374 var mc = new Roo.util.MixedCollection();
14375 mc.getKey = function(el){
14381 // or via the constructor
14382 var mc = new Roo.util.MixedCollection(false, function(el){
14388 * @param o {Object} The item for which to find the key.
14389 * @return {Object} The key for the passed item.
14391 getKey : function(o){
14396 * Replaces an item in the collection.
14397 * @param {String} key The key associated with the item to replace, or the item to replace.
14398 * @param o {Object} o (optional) If the first parameter passed was a key, the item to associate with that key.
14399 * @return {Object} The new item.
14401 replace : function(key, o){
14402 if(arguments.length == 1){
14404 key = this.getKey(o);
14406 var old = this.item(key);
14407 if(typeof key == "undefined" || key === null || typeof old == "undefined"){
14408 return this.add(key, o);
14410 var index = this.indexOfKey(key);
14411 this.items[index] = o;
14413 this.fireEvent("replace", key, old, o);
14418 * Adds all elements of an Array or an Object to the collection.
14419 * @param {Object/Array} objs An Object containing properties which will be added to the collection, or
14420 * an Array of values, each of which are added to the collection.
14422 addAll : function(objs){
14423 if(arguments.length > 1 || objs instanceof Array){
14424 var args = arguments.length > 1 ? arguments : objs;
14425 for(var i = 0, len = args.length; i < len; i++){
14429 for(var key in objs){
14430 if(this.allowFunctions || typeof objs[key] != "function"){
14431 this.add(key, objs[key]);
14438 * Executes the specified function once for every item in the collection, passing each
14439 * item as the first and only parameter. returning false from the function will stop the iteration.
14440 * @param {Function} fn The function to execute for each item.
14441 * @param {Object} scope (optional) The scope in which to execute the function.
14443 each : function(fn, scope){
14444 var items = [].concat(this.items); // each safe for removal
14445 for(var i = 0, len = items.length; i < len; i++){
14446 if(fn.call(scope || items[i], items[i], i, len) === false){
14453 * Executes the specified function once for every key in the collection, passing each
14454 * key, and its associated item as the first two parameters.
14455 * @param {Function} fn The function to execute for each item.
14456 * @param {Object} scope (optional) The scope in which to execute the function.
14458 eachKey : function(fn, scope){
14459 for(var i = 0, len = this.keys.length; i < len; i++){
14460 fn.call(scope || window, this.keys[i], this.items[i], i, len);
14465 * Returns the first item in the collection which elicits a true return value from the
14466 * passed selection function.
14467 * @param {Function} fn The selection function to execute for each item.
14468 * @param {Object} scope (optional) The scope in which to execute the function.
14469 * @return {Object} The first item in the collection which returned true from the selection function.
14471 find : function(fn, scope){
14472 for(var i = 0, len = this.items.length; i < len; i++){
14473 if(fn.call(scope || window, this.items[i], this.keys[i])){
14474 return this.items[i];
14481 * Inserts an item at the specified index in the collection.
14482 * @param {Number} index The index to insert the item at.
14483 * @param {String} key The key to associate with the new item, or the item itself.
14484 * @param {Object} o (optional) If the second parameter was a key, the new item.
14485 * @return {Object} The item inserted.
14487 insert : function(index, key, o){
14488 if(arguments.length == 2){
14490 key = this.getKey(o);
14492 if(index >= this.length){
14493 return this.add(key, o);
14496 this.items.splice(index, 0, o);
14497 if(typeof key != "undefined" && key != null){
14500 this.keys.splice(index, 0, key);
14501 this.fireEvent("add", index, o, key);
14506 * Removed an item from the collection.
14507 * @param {Object} o The item to remove.
14508 * @return {Object} The item removed.
14510 remove : function(o){
14511 return this.removeAt(this.indexOf(o));
14515 * Remove an item from a specified index in the collection.
14516 * @param {Number} index The index within the collection of the item to remove.
14518 removeAt : function(index){
14519 if(index < this.length && index >= 0){
14521 var o = this.items[index];
14522 this.items.splice(index, 1);
14523 var key = this.keys[index];
14524 if(typeof key != "undefined"){
14525 delete this.map[key];
14527 this.keys.splice(index, 1);
14528 this.fireEvent("remove", o, key);
14533 * Removed an item associated with the passed key fom the collection.
14534 * @param {String} key The key of the item to remove.
14536 removeKey : function(key){
14537 return this.removeAt(this.indexOfKey(key));
14541 * Returns the number of items in the collection.
14542 * @return {Number} the number of items in the collection.
14544 getCount : function(){
14545 return this.length;
14549 * Returns index within the collection of the passed Object.
14550 * @param {Object} o The item to find the index of.
14551 * @return {Number} index of the item.
14553 indexOf : function(o){
14554 if(!this.items.indexOf){
14555 for(var i = 0, len = this.items.length; i < len; i++){
14556 if(this.items[i] == o) {
14562 return this.items.indexOf(o);
14567 * Returns index within the collection of the passed key.
14568 * @param {String} key The key to find the index of.
14569 * @return {Number} index of the key.
14571 indexOfKey : function(key){
14572 if(!this.keys.indexOf){
14573 for(var i = 0, len = this.keys.length; i < len; i++){
14574 if(this.keys[i] == key) {
14580 return this.keys.indexOf(key);
14585 * Returns the item associated with the passed key OR index. Key has priority over index.
14586 * @param {String/Number} key The key or index of the item.
14587 * @return {Object} The item associated with the passed key.
14589 item : function(key){
14590 if (key === 'length') {
14593 var item = typeof this.map[key] != "undefined" ? this.map[key] : this.items[key];
14594 return typeof item != 'function' || this.allowFunctions ? item : null; // for prototype!
14598 * Returns the item at the specified index.
14599 * @param {Number} index The index of the item.
14602 itemAt : function(index){
14603 return this.items[index];
14607 * Returns the item associated with the passed key.
14608 * @param {String/Number} key The key of the item.
14609 * @return {Object} The item associated with the passed key.
14611 key : function(key){
14612 return this.map[key];
14616 * Returns true if the collection contains the passed Object as an item.
14617 * @param {Object} o The Object to look for in the collection.
14618 * @return {Boolean} True if the collection contains the Object as an item.
14620 contains : function(o){
14621 return this.indexOf(o) != -1;
14625 * Returns true if the collection contains the passed Object as a key.
14626 * @param {String} key The key to look for in the collection.
14627 * @return {Boolean} True if the collection contains the Object as a key.
14629 containsKey : function(key){
14630 return typeof this.map[key] != "undefined";
14634 * Removes all items from the collection.
14636 clear : function(){
14641 this.fireEvent("clear");
14645 * Returns the first item in the collection.
14646 * @return {Object} the first item in the collection..
14648 first : function(){
14649 return this.items[0];
14653 * Returns the last item in the collection.
14654 * @return {Object} the last item in the collection..
14657 return this.items[this.length-1];
14660 _sort : function(property, dir, fn){
14661 var dsc = String(dir).toUpperCase() == "DESC" ? -1 : 1;
14662 fn = fn || function(a, b){
14665 var c = [], k = this.keys, items = this.items;
14666 for(var i = 0, len = items.length; i < len; i++){
14667 c[c.length] = {key: k[i], value: items[i], index: i};
14669 c.sort(function(a, b){
14670 var v = fn(a[property], b[property]) * dsc;
14672 v = (a.index < b.index ? -1 : 1);
14676 for(var i = 0, len = c.length; i < len; i++){
14677 items[i] = c[i].value;
14680 this.fireEvent("sort", this);
14684 * Sorts this collection with the passed comparison function
14685 * @param {String} direction (optional) "ASC" or "DESC"
14686 * @param {Function} fn (optional) comparison function
14688 sort : function(dir, fn){
14689 this._sort("value", dir, fn);
14693 * Sorts this collection by keys
14694 * @param {String} direction (optional) "ASC" or "DESC"
14695 * @param {Function} fn (optional) a comparison function (defaults to case insensitive string)
14697 keySort : function(dir, fn){
14698 this._sort("key", dir, fn || function(a, b){
14699 return String(a).toUpperCase()-String(b).toUpperCase();
14704 * Returns a range of items in this collection
14705 * @param {Number} startIndex (optional) defaults to 0
14706 * @param {Number} endIndex (optional) default to the last item
14707 * @return {Array} An array of items
14709 getRange : function(start, end){
14710 var items = this.items;
14711 if(items.length < 1){
14714 start = start || 0;
14715 end = Math.min(typeof end == "undefined" ? this.length-1 : end, this.length-1);
14718 for(var i = start; i <= end; i++) {
14719 r[r.length] = items[i];
14722 for(var i = start; i >= end; i--) {
14723 r[r.length] = items[i];
14730 * Filter the <i>objects</i> in this collection by a specific property.
14731 * Returns a new collection that has been filtered.
14732 * @param {String} property A property on your objects
14733 * @param {String/RegExp} value Either string that the property values
14734 * should start with or a RegExp to test against the property
14735 * @return {MixedCollection} The new filtered collection
14737 filter : function(property, value){
14738 if(!value.exec){ // not a regex
14739 value = String(value);
14740 if(value.length == 0){
14741 return this.clone();
14743 value = new RegExp("^" + Roo.escapeRe(value), "i");
14745 return this.filterBy(function(o){
14746 return o && value.test(o[property]);
14751 * Filter by a function. * Returns a new collection that has been filtered.
14752 * The passed function will be called with each
14753 * object in the collection. If the function returns true, the value is included
14754 * otherwise it is filtered.
14755 * @param {Function} fn The function to be called, it will receive the args o (the object), k (the key)
14756 * @param {Object} scope (optional) The scope of the function (defaults to this)
14757 * @return {MixedCollection} The new filtered collection
14759 filterBy : function(fn, scope){
14760 var r = new Roo.util.MixedCollection();
14761 r.getKey = this.getKey;
14762 var k = this.keys, it = this.items;
14763 for(var i = 0, len = it.length; i < len; i++){
14764 if(fn.call(scope||this, it[i], k[i])){
14765 r.add(k[i], it[i]);
14772 * Creates a duplicate of this collection
14773 * @return {MixedCollection}
14775 clone : function(){
14776 var r = new Roo.util.MixedCollection();
14777 var k = this.keys, it = this.items;
14778 for(var i = 0, len = it.length; i < len; i++){
14779 r.add(k[i], it[i]);
14781 r.getKey = this.getKey;
14786 * Returns the item associated with the passed key or index.
14788 * @param {String/Number} key The key or index of the item.
14789 * @return {Object} The item associated with the passed key.
14791 Roo.util.MixedCollection.prototype.get = Roo.util.MixedCollection.prototype.item;/*
14793 * Ext JS Library 1.1.1
14794 * Copyright(c) 2006-2007, Ext JS, LLC.
14796 * Originally Released Under LGPL - original licence link has changed is not relivant.
14799 * <script type="text/javascript">
14802 * @class Roo.util.JSON
14803 * Modified version of Douglas Crockford"s json.js that doesn"t
14804 * mess with the Object prototype
14805 * http://www.json.org/js.html
14808 Roo.util.JSON = new (function(){
14809 var useHasOwn = {}.hasOwnProperty ? true : false;
14811 // crashes Safari in some instances
14812 //var validRE = /^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/;
14814 var pad = function(n) {
14815 return n < 10 ? "0" + n : n;
14828 var encodeString = function(s){
14829 if (/["\\\x00-\x1f]/.test(s)) {
14830 return '"' + s.replace(/([\x00-\x1f\\"])/g, function(a, b) {
14835 c = b.charCodeAt();
14837 Math.floor(c / 16).toString(16) +
14838 (c % 16).toString(16);
14841 return '"' + s + '"';
14844 var encodeArray = function(o){
14845 var a = ["["], b, i, l = o.length, v;
14846 for (i = 0; i < l; i += 1) {
14848 switch (typeof v) {
14857 a.push(v === null ? "null" : Roo.util.JSON.encode(v));
14865 var encodeDate = function(o){
14866 return '"' + o.getFullYear() + "-" +
14867 pad(o.getMonth() + 1) + "-" +
14868 pad(o.getDate()) + "T" +
14869 pad(o.getHours()) + ":" +
14870 pad(o.getMinutes()) + ":" +
14871 pad(o.getSeconds()) + '"';
14875 * Encodes an Object, Array or other value
14876 * @param {Mixed} o The variable to encode
14877 * @return {String} The JSON string
14879 this.encode = function(o)
14881 // should this be extended to fully wrap stringify..
14883 if(typeof o == "undefined" || o === null){
14885 }else if(o instanceof Array){
14886 return encodeArray(o);
14887 }else if(o instanceof Date){
14888 return encodeDate(o);
14889 }else if(typeof o == "string"){
14890 return encodeString(o);
14891 }else if(typeof o == "number"){
14892 return isFinite(o) ? String(o) : "null";
14893 }else if(typeof o == "boolean"){
14896 var a = ["{"], b, i, v;
14898 if(!useHasOwn || o.hasOwnProperty(i)) {
14900 switch (typeof v) {
14909 a.push(this.encode(i), ":",
14910 v === null ? "null" : this.encode(v));
14921 * Decodes (parses) a JSON string to an object. If the JSON is invalid, this function throws a SyntaxError.
14922 * @param {String} json The JSON string
14923 * @return {Object} The resulting object
14925 this.decode = function(json){
14927 return /** eval:var:json */ eval("(" + json + ')');
14931 * Shorthand for {@link Roo.util.JSON#encode}
14932 * @member Roo encode
14934 Roo.encode = typeof(JSON) != 'undefined' && JSON.stringify ? JSON.stringify : Roo.util.JSON.encode;
14936 * Shorthand for {@link Roo.util.JSON#decode}
14937 * @member Roo decode
14939 Roo.decode = typeof(JSON) != 'undefined' && JSON.parse ? JSON.parse : Roo.util.JSON.decode;
14942 * Ext JS Library 1.1.1
14943 * Copyright(c) 2006-2007, Ext JS, LLC.
14945 * Originally Released Under LGPL - original licence link has changed is not relivant.
14948 * <script type="text/javascript">
14952 * @class Roo.util.Format
14953 * Reusable data formatting functions
14956 Roo.util.Format = function(){
14957 var trimRe = /^\s+|\s+$/g;
14960 * Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length
14961 * @param {String} value The string to truncate
14962 * @param {Number} length The maximum length to allow before truncating
14963 * @return {String} The converted text
14965 ellipsis : function(value, len){
14966 if(value && value.length > len){
14967 return value.substr(0, len-3)+"...";
14973 * Checks a reference and converts it to empty string if it is undefined
14974 * @param {Mixed} value Reference to check
14975 * @return {Mixed} Empty string if converted, otherwise the original value
14977 undef : function(value){
14978 return typeof value != "undefined" ? value : "";
14982 * Convert certain characters (&, <, >, and ') to their HTML character equivalents for literal display in web pages.
14983 * @param {String} value The string to encode
14984 * @return {String} The encoded text
14986 htmlEncode : function(value){
14987 return !value ? value : String(value).replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, """);
14991 * Convert certain characters (&, <, >, and ') from their HTML character equivalents.
14992 * @param {String} value The string to decode
14993 * @return {String} The decoded text
14995 htmlDecode : function(value){
14996 return !value ? value : String(value).replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, '"');
15000 * Trims any whitespace from either side of a string
15001 * @param {String} value The text to trim
15002 * @return {String} The trimmed text
15004 trim : function(value){
15005 return String(value).replace(trimRe, "");
15009 * Returns a substring from within an original string
15010 * @param {String} value The original text
15011 * @param {Number} start The start index of the substring
15012 * @param {Number} length The length of the substring
15013 * @return {String} The substring
15015 substr : function(value, start, length){
15016 return String(value).substr(start, length);
15020 * Converts a string to all lower case letters
15021 * @param {String} value The text to convert
15022 * @return {String} The converted text
15024 lowercase : function(value){
15025 return String(value).toLowerCase();
15029 * Converts a string to all upper case letters
15030 * @param {String} value The text to convert
15031 * @return {String} The converted text
15033 uppercase : function(value){
15034 return String(value).toUpperCase();
15038 * Converts the first character only of a string to upper case
15039 * @param {String} value The text to convert
15040 * @return {String} The converted text
15042 capitalize : function(value){
15043 return !value ? value : value.charAt(0).toUpperCase() + value.substr(1).toLowerCase();
15047 call : function(value, fn){
15048 if(arguments.length > 2){
15049 var args = Array.prototype.slice.call(arguments, 2);
15050 args.unshift(value);
15052 return /** eval:var:value */ eval(fn).apply(window, args);
15054 /** eval:var:value */
15055 return /** eval:var:value */ eval(fn).call(window, value);
15061 * safer version of Math.toFixed..??/
15062 * @param {Number/String} value The numeric value to format
15063 * @param {Number/String} value Decimal places
15064 * @return {String} The formatted currency string
15066 toFixed : function(v, n)
15068 // why not use to fixed - precision is buggered???
15070 return Math.round(v-0);
15072 var fact = Math.pow(10,n+1);
15073 v = (Math.round((v-0)*fact))/fact;
15074 var z = (''+fact).substring(2);
15075 if (v == Math.floor(v)) {
15076 return Math.floor(v) + '.' + z;
15079 // now just padd decimals..
15080 var ps = String(v).split('.');
15081 var fd = (ps[1] + z);
15082 var r = fd.substring(0,n);
15083 var rm = fd.substring(n);
15085 return ps[0] + '.' + r;
15087 r*=1; // turn it into a number;
15089 if (String(r).length != n) {
15092 r = String(r).substring(1); // chop the end off.
15095 return ps[0] + '.' + r;
15100 * Format a number as US currency
15101 * @param {Number/String} value The numeric value to format
15102 * @return {String} The formatted currency string
15104 usMoney : function(v){
15105 return '$' + Roo.util.Format.number(v);
15110 * eventually this should probably emulate php's number_format
15111 * @param {Number/String} value The numeric value to format
15112 * @param {Number} decimals number of decimal places
15113 * @param {String} delimiter for thousands (default comma)
15114 * @return {String} The formatted currency string
15116 number : function(v, decimals, thousandsDelimiter)
15118 // multiply and round.
15119 decimals = typeof(decimals) == 'undefined' ? 2 : decimals;
15120 thousandsDelimiter = typeof(thousandsDelimiter) == 'undefined' ? ',' : thousandsDelimiter;
15122 var mul = Math.pow(10, decimals);
15123 var zero = String(mul).substring(1);
15124 v = (Math.round((v-0)*mul))/mul;
15126 // if it's '0' number.. then
15128 //v = (v == Math.floor(v)) ? v + "." + zero : ((v*10 == Math.floor(v*10)) ? v + "0" : v);
15130 var ps = v.split('.');
15133 var r = /(\d+)(\d{3})/;
15136 if(thousandsDelimiter.length != 0) {
15137 whole = whole.replace(/\B(?=(\d{3})+(?!\d))/g, thousandsDelimiter );
15142 (decimals ? ('.'+ ps[1] + zero.substring(ps[1].length)) : '') :
15143 // does not have decimals
15144 (decimals ? ('.' + zero) : '');
15147 return whole + sub ;
15151 * Parse a value into a formatted date using the specified format pattern.
15152 * @param {Mixed} value The value to format
15153 * @param {String} format (optional) Any valid date format string (defaults to 'm/d/Y')
15154 * @return {String} The formatted date string
15156 date : function(v, format){
15160 if(!(v instanceof Date)){
15161 v = new Date(Date.parse(v));
15163 return v.dateFormat(format || Roo.util.Format.defaults.date);
15167 * Returns a date rendering function that can be reused to apply a date format multiple times efficiently
15168 * @param {String} format Any valid date format string
15169 * @return {Function} The date formatting function
15171 dateRenderer : function(format){
15172 return function(v){
15173 return Roo.util.Format.date(v, format);
15178 stripTagsRE : /<\/?[^>]+>/gi,
15181 * Strips all HTML tags
15182 * @param {Mixed} value The text from which to strip tags
15183 * @return {String} The stripped text
15185 stripTags : function(v){
15186 return !v ? v : String(v).replace(this.stripTagsRE, "");
15190 * Size in Mb,Gb etc.
15191 * @param {Number} value The number to be formated
15192 * @param {number} decimals how many decimal places
15193 * @return {String} the formated string
15195 size : function(value, decimals)
15197 var sizes = ['b', 'k', 'M', 'G', 'T'];
15201 var i = parseInt(Math.floor(Math.log(value) / Math.log(1024)));
15202 return Roo.util.Format.number(value/ Math.pow(1024, i) ,decimals) + sizes[i];
15209 Roo.util.Format.defaults = {
15213 * Ext JS Library 1.1.1
15214 * Copyright(c) 2006-2007, Ext JS, LLC.
15216 * Originally Released Under LGPL - original licence link has changed is not relivant.
15219 * <script type="text/javascript">
15226 * @class Roo.MasterTemplate
15227 * @extends Roo.Template
15228 * Provides a template that can have child templates. The syntax is:
15230 var t = new Roo.MasterTemplate(
15231 '<select name="{name}">',
15232 '<tpl name="options"><option value="{value:trim}">{text:ellipsis(10)}</option></tpl>',
15235 t.add('options', {value: 'foo', text: 'bar'});
15236 // or you can add multiple child elements in one shot
15237 t.addAll('options', [
15238 {value: 'foo', text: 'bar'},
15239 {value: 'foo2', text: 'bar2'},
15240 {value: 'foo3', text: 'bar3'}
15242 // then append, applying the master template values
15243 t.append('my-form', {name: 'my-select'});
15245 * A name attribute for the child template is not required if you have only one child
15246 * template or you want to refer to them by index.
15248 Roo.MasterTemplate = function(){
15249 Roo.MasterTemplate.superclass.constructor.apply(this, arguments);
15250 this.originalHtml = this.html;
15252 var m, re = this.subTemplateRe;
15255 while(m = re.exec(this.html)){
15256 var name = m[1], content = m[2];
15261 tpl : new Roo.Template(content)
15264 st[name] = st[subIndex];
15266 st[subIndex].tpl.compile();
15267 st[subIndex].tpl.call = this.call.createDelegate(this);
15270 this.subCount = subIndex;
15273 Roo.extend(Roo.MasterTemplate, Roo.Template, {
15275 * The regular expression used to match sub templates
15279 subTemplateRe : /<tpl(?:\sname="([\w-]+)")?>((?:.|\n)*?)<\/tpl>/gi,
15282 * Applies the passed values to a child template.
15283 * @param {String/Number} name (optional) The name or index of the child template
15284 * @param {Array/Object} values The values to be applied to the template
15285 * @return {MasterTemplate} this
15287 add : function(name, values){
15288 if(arguments.length == 1){
15289 values = arguments[0];
15292 var s = this.subs[name];
15293 s.buffer[s.buffer.length] = s.tpl.apply(values);
15298 * Applies all the passed values to a child template.
15299 * @param {String/Number} name (optional) The name or index of the child template
15300 * @param {Array} values The values to be applied to the template, this should be an array of objects.
15301 * @param {Boolean} reset (optional) True to reset the template first
15302 * @return {MasterTemplate} this
15304 fill : function(name, values, reset){
15306 if(a.length == 1 || (a.length == 2 && typeof a[1] == "boolean")){
15314 for(var i = 0, len = values.length; i < len; i++){
15315 this.add(name, values[i]);
15321 * Resets the template for reuse
15322 * @return {MasterTemplate} this
15324 reset : function(){
15326 for(var i = 0; i < this.subCount; i++){
15332 applyTemplate : function(values){
15334 var replaceIndex = -1;
15335 this.html = this.originalHtml.replace(this.subTemplateRe, function(m, name){
15336 return s[++replaceIndex].buffer.join("");
15338 return Roo.MasterTemplate.superclass.applyTemplate.call(this, values);
15341 apply : function(){
15342 return this.applyTemplate.apply(this, arguments);
15345 compile : function(){return this;}
15349 * Alias for fill().
15352 Roo.MasterTemplate.prototype.addAll = Roo.MasterTemplate.prototype.fill;
15354 * Creates a template from the passed element's value (display:none textarea, preferred) or innerHTML. e.g.
15355 * var tpl = Roo.MasterTemplate.from('element-id');
15356 * @param {String/HTMLElement} el
15357 * @param {Object} config
15360 Roo.MasterTemplate.from = function(el, config){
15361 el = Roo.getDom(el);
15362 return new Roo.MasterTemplate(el.value || el.innerHTML, config || '');
15365 * Ext JS Library 1.1.1
15366 * Copyright(c) 2006-2007, Ext JS, LLC.
15368 * Originally Released Under LGPL - original licence link has changed is not relivant.
15371 * <script type="text/javascript">
15376 * @class Roo.util.CSS
15377 * Utility class for manipulating CSS rules
15381 Roo.util.CSS = function(){
15383 var doc = document;
15385 var camelRe = /(-[a-z])/gi;
15386 var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); };
15390 * Very simple dynamic creation of stylesheets from a text blob of rules. The text will wrapped in a style
15391 * tag and appended to the HEAD of the document.
15392 * @param {String|Object} cssText The text containing the css rules
15393 * @param {String} id An id to add to the stylesheet for later removal
15394 * @return {StyleSheet}
15396 createStyleSheet : function(cssText, id){
15398 var head = doc.getElementsByTagName("head")[0];
15399 var nrules = doc.createElement("style");
15400 nrules.setAttribute("type", "text/css");
15402 nrules.setAttribute("id", id);
15404 if (typeof(cssText) != 'string') {
15405 // support object maps..
15406 // not sure if this a good idea..
15407 // perhaps it should be merged with the general css handling
15408 // and handle js style props.
15409 var cssTextNew = [];
15410 for(var n in cssText) {
15412 for(var k in cssText[n]) {
15413 citems.push( k + ' : ' +cssText[n][k] + ';' );
15415 cssTextNew.push( n + ' { ' + citems.join(' ') + '} ');
15418 cssText = cssTextNew.join("\n");
15424 head.appendChild(nrules);
15425 ss = nrules.styleSheet;
15426 ss.cssText = cssText;
15429 nrules.appendChild(doc.createTextNode(cssText));
15431 nrules.cssText = cssText;
15433 head.appendChild(nrules);
15434 ss = nrules.styleSheet ? nrules.styleSheet : (nrules.sheet || doc.styleSheets[doc.styleSheets.length-1]);
15436 this.cacheStyleSheet(ss);
15441 * Removes a style or link tag by id
15442 * @param {String} id The id of the tag
15444 removeStyleSheet : function(id){
15445 var existing = doc.getElementById(id);
15447 existing.parentNode.removeChild(existing);
15452 * Dynamically swaps an existing stylesheet reference for a new one
15453 * @param {String} id The id of an existing link tag to remove
15454 * @param {String} url The href of the new stylesheet to include
15456 swapStyleSheet : function(id, url){
15457 this.removeStyleSheet(id);
15458 var ss = doc.createElement("link");
15459 ss.setAttribute("rel", "stylesheet");
15460 ss.setAttribute("type", "text/css");
15461 ss.setAttribute("id", id);
15462 ss.setAttribute("href", url);
15463 doc.getElementsByTagName("head")[0].appendChild(ss);
15467 * Refresh the rule cache if you have dynamically added stylesheets
15468 * @return {Object} An object (hash) of rules indexed by selector
15470 refreshCache : function(){
15471 return this.getRules(true);
15475 cacheStyleSheet : function(stylesheet){
15479 try{// try catch for cross domain access issue
15480 var ssRules = stylesheet.cssRules || stylesheet.rules;
15481 for(var j = ssRules.length-1; j >= 0; --j){
15482 rules[ssRules[j].selectorText] = ssRules[j];
15488 * Gets all css rules for the document
15489 * @param {Boolean} refreshCache true to refresh the internal cache
15490 * @return {Object} An object (hash) of rules indexed by selector
15492 getRules : function(refreshCache){
15493 if(rules == null || refreshCache){
15495 var ds = doc.styleSheets;
15496 for(var i =0, len = ds.length; i < len; i++){
15498 this.cacheStyleSheet(ds[i]);
15506 * Gets an an individual CSS rule by selector(s)
15507 * @param {String/Array} selector The CSS selector or an array of selectors to try. The first selector that is found is returned.
15508 * @param {Boolean} refreshCache true to refresh the internal cache if you have recently updated any rules or added styles dynamically
15509 * @return {CSSRule} The CSS rule or null if one is not found
15511 getRule : function(selector, refreshCache){
15512 var rs = this.getRules(refreshCache);
15513 if(!(selector instanceof Array)){
15514 return rs[selector];
15516 for(var i = 0; i < selector.length; i++){
15517 if(rs[selector[i]]){
15518 return rs[selector[i]];
15526 * Updates a rule property
15527 * @param {String/Array} selector If it's an array it tries each selector until it finds one. Stops immediately once one is found.
15528 * @param {String} property The css property
15529 * @param {String} value The new value for the property
15530 * @return {Boolean} true If a rule was found and updated
15532 updateRule : function(selector, property, value){
15533 if(!(selector instanceof Array)){
15534 var rule = this.getRule(selector);
15536 rule.style[property.replace(camelRe, camelFn)] = value;
15540 for(var i = 0; i < selector.length; i++){
15541 if(this.updateRule(selector[i], property, value)){
15551 * Ext JS Library 1.1.1
15552 * Copyright(c) 2006-2007, Ext JS, LLC.
15554 * Originally Released Under LGPL - original licence link has changed is not relivant.
15557 * <script type="text/javascript">
15563 * @class Roo.util.ClickRepeater
15564 * @extends Roo.util.Observable
15566 * A wrapper class which can be applied to any element. Fires a "click" event while the
15567 * mouse is pressed. The interval between firings may be specified in the config but
15568 * defaults to 10 milliseconds.
15570 * Optionally, a CSS class may be applied to the element during the time it is pressed.
15572 * @cfg {String/HTMLElement/Element} el The element to act as a button.
15573 * @cfg {Number} delay The initial delay before the repeating event begins firing.
15574 * Similar to an autorepeat key delay.
15575 * @cfg {Number} interval The interval between firings of the "click" event. Default 10 ms.
15576 * @cfg {String} pressClass A CSS class name to be applied to the element while pressed.
15577 * @cfg {Boolean} accelerate True if autorepeating should start slowly and accelerate.
15578 * "interval" and "delay" are ignored. "immediate" is honored.
15579 * @cfg {Boolean} preventDefault True to prevent the default click event
15580 * @cfg {Boolean} stopDefault True to stop the default click event
15583 * 2007-02-02 jvs Original code contributed by Nige "Animal" White
15584 * 2007-02-02 jvs Renamed to ClickRepeater
15585 * 2007-02-03 jvs Modifications for FF Mac and Safari
15588 * @param {String/HTMLElement/Element} el The element to listen on
15589 * @param {Object} config
15591 Roo.util.ClickRepeater = function(el, config)
15593 this.el = Roo.get(el);
15594 this.el.unselectable();
15596 Roo.apply(this, config);
15601 * Fires when the mouse button is depressed.
15602 * @param {Roo.util.ClickRepeater} this
15604 "mousedown" : true,
15607 * Fires on a specified interval during the time the element is pressed.
15608 * @param {Roo.util.ClickRepeater} this
15613 * Fires when the mouse key is released.
15614 * @param {Roo.util.ClickRepeater} this
15619 this.el.on("mousedown", this.handleMouseDown, this);
15620 if(this.preventDefault || this.stopDefault){
15621 this.el.on("click", function(e){
15622 if(this.preventDefault){
15623 e.preventDefault();
15625 if(this.stopDefault){
15631 // allow inline handler
15633 this.on("click", this.handler, this.scope || this);
15636 Roo.util.ClickRepeater.superclass.constructor.call(this);
15639 Roo.extend(Roo.util.ClickRepeater, Roo.util.Observable, {
15642 preventDefault : true,
15643 stopDefault : false,
15647 handleMouseDown : function(){
15648 clearTimeout(this.timer);
15650 if(this.pressClass){
15651 this.el.addClass(this.pressClass);
15653 this.mousedownTime = new Date();
15655 Roo.get(document).on("mouseup", this.handleMouseUp, this);
15656 this.el.on("mouseout", this.handleMouseOut, this);
15658 this.fireEvent("mousedown", this);
15659 this.fireEvent("click", this);
15661 this.timer = this.click.defer(this.delay || this.interval, this);
15665 click : function(){
15666 this.fireEvent("click", this);
15667 this.timer = this.click.defer(this.getInterval(), this);
15671 getInterval: function(){
15672 if(!this.accelerate){
15673 return this.interval;
15675 var pressTime = this.mousedownTime.getElapsed();
15676 if(pressTime < 500){
15678 }else if(pressTime < 1700){
15680 }else if(pressTime < 2600){
15682 }else if(pressTime < 3500){
15684 }else if(pressTime < 4400){
15686 }else if(pressTime < 5300){
15688 }else if(pressTime < 6200){
15696 handleMouseOut : function(){
15697 clearTimeout(this.timer);
15698 if(this.pressClass){
15699 this.el.removeClass(this.pressClass);
15701 this.el.on("mouseover", this.handleMouseReturn, this);
15705 handleMouseReturn : function(){
15706 this.el.un("mouseover", this.handleMouseReturn);
15707 if(this.pressClass){
15708 this.el.addClass(this.pressClass);
15714 handleMouseUp : function(){
15715 clearTimeout(this.timer);
15716 this.el.un("mouseover", this.handleMouseReturn);
15717 this.el.un("mouseout", this.handleMouseOut);
15718 Roo.get(document).un("mouseup", this.handleMouseUp);
15719 this.el.removeClass(this.pressClass);
15720 this.fireEvent("mouseup", this);
15723 * @class Roo.util.Clipboard
15729 Roo.util.Clipboard = {
15731 * Writes a string to the clipboard - using the Clipboard API if https, otherwise using text area.
15732 * @param {String} text to copy to clipboard
15734 write : function(text) {
15735 // navigator clipboard api needs a secure context (https)
15736 if (navigator.clipboard && window.isSecureContext) {
15737 // navigator clipboard api method'
15738 navigator.clipboard.writeText(text);
15741 // text area method
15742 var ta = document.createElement("textarea");
15744 // make the textarea out of viewport
15745 ta.style.position = "fixed";
15746 ta.style.left = "-999999px";
15747 ta.style.top = "-999999px";
15748 document.body.appendChild(ta);
15751 document.execCommand('copy');
15761 * Ext JS Library 1.1.1
15762 * Copyright(c) 2006-2007, Ext JS, LLC.
15764 * Originally Released Under LGPL - original licence link has changed is not relivant.
15767 * <script type="text/javascript">
15772 * @class Roo.KeyNav
15773 * <p>Provides a convenient wrapper for normalized keyboard navigation. KeyNav allows you to bind
15774 * navigation keys to function calls that will get called when the keys are pressed, providing an easy
15775 * way to implement custom navigation schemes for any UI component.</p>
15776 * <p>The following are all of the possible keys that can be implemented: enter, left, right, up, down, tab, esc,
15777 * pageUp, pageDown, del, home, end. Usage:</p>
15779 var nav = new Roo.KeyNav("my-element", {
15780 "left" : function(e){
15781 this.moveLeft(e.ctrlKey);
15783 "right" : function(e){
15784 this.moveRight(e.ctrlKey);
15786 "enter" : function(e){
15793 * @param {String/HTMLElement/Roo.Element} el The element to bind to
15794 * @param {Object} config The config
15796 Roo.KeyNav = function(el, config){
15797 this.el = Roo.get(el);
15798 Roo.apply(this, config);
15799 if(!this.disabled){
15800 this.disabled = true;
15805 Roo.KeyNav.prototype = {
15807 * @cfg {Boolean} disabled
15808 * True to disable this KeyNav instance (defaults to false)
15812 * @cfg {String} defaultEventAction
15813 * The method to call on the {@link Roo.EventObject} after this KeyNav intercepts a key. Valid values are
15814 * {@link Roo.EventObject#stopEvent}, {@link Roo.EventObject#preventDefault} and
15815 * {@link Roo.EventObject#stopPropagation} (defaults to 'stopEvent')
15817 defaultEventAction: "stopEvent",
15819 * @cfg {Boolean} forceKeyDown
15820 * Handle the keydown event instead of keypress (defaults to false). KeyNav automatically does this for IE since
15821 * IE does not propagate special keys on keypress, but setting this to true will force other browsers to also
15822 * handle keydown instead of keypress.
15824 forceKeyDown : false,
15827 prepareEvent : function(e){
15828 var k = e.getKey();
15829 var h = this.keyToHandler[k];
15830 //if(h && this[h]){
15831 // e.stopPropagation();
15833 if(Roo.isSafari && h && k >= 37 && k <= 40){
15839 relay : function(e){
15840 var k = e.getKey();
15841 var h = this.keyToHandler[k];
15843 if(this.doRelay(e, this[h], h) !== true){
15844 e[this.defaultEventAction]();
15850 doRelay : function(e, h, hname){
15851 return h.call(this.scope || this, e);
15854 // possible handlers
15868 // quick lookup hash
15885 * Enable this KeyNav
15887 enable: function(){
15889 // ie won't do special keys on keypress, no one else will repeat keys with keydown
15890 // the EventObject will normalize Safari automatically
15891 if(this.forceKeyDown || Roo.isIE || Roo.isAir){
15892 this.el.on("keydown", this.relay, this);
15894 this.el.on("keydown", this.prepareEvent, this);
15895 this.el.on("keypress", this.relay, this);
15897 this.disabled = false;
15902 * Disable this KeyNav
15904 disable: function(){
15905 if(!this.disabled){
15906 if(this.forceKeyDown || Roo.isIE || Roo.isAir){
15907 this.el.un("keydown", this.relay);
15909 this.el.un("keydown", this.prepareEvent);
15910 this.el.un("keypress", this.relay);
15912 this.disabled = true;
15917 * Ext JS Library 1.1.1
15918 * Copyright(c) 2006-2007, Ext JS, LLC.
15920 * Originally Released Under LGPL - original licence link has changed is not relivant.
15923 * <script type="text/javascript">
15928 * @class Roo.KeyMap
15929 * Handles mapping keys to actions for an element. One key map can be used for multiple actions.
15930 * The constructor accepts the same config object as defined by {@link #addBinding}.
15931 * If you bind a callback function to a KeyMap, anytime the KeyMap handles an expected key
15932 * combination it will call the function with this signature (if the match is a multi-key
15933 * combination the callback will still be called only once): (String key, Roo.EventObject e)
15934 * A KeyMap can also handle a string representation of keys.<br />
15937 // map one key by key code
15938 var map = new Roo.KeyMap("my-element", {
15939 key: 13, // or Roo.EventObject.ENTER
15944 // map multiple keys to one action by string
15945 var map = new Roo.KeyMap("my-element", {
15951 // map multiple keys to multiple actions by strings and array of codes
15952 var map = new Roo.KeyMap("my-element", [
15955 fn: function(){ alert("Return was pressed"); }
15958 fn: function(){ alert('a, b or c was pressed'); }
15963 fn: function(){ alert('Control + shift + tab was pressed.'); }
15967 * <b>Note: A KeyMap starts enabled</b>
15969 * @param {String/HTMLElement/Roo.Element} el The element to bind to
15970 * @param {Object} config The config (see {@link #addBinding})
15971 * @param {String} eventName (optional) The event to bind to (defaults to "keydown")
15973 Roo.KeyMap = function(el, config, eventName){
15974 this.el = Roo.get(el);
15975 this.eventName = eventName || "keydown";
15976 this.bindings = [];
15978 this.addBinding(config);
15983 Roo.KeyMap.prototype = {
15985 * True to stop the event from bubbling and prevent the default browser action if the
15986 * key was handled by the KeyMap (defaults to false)
15992 * Add a new binding to this KeyMap. The following config object properties are supported:
15994 Property Type Description
15995 ---------- --------------- ----------------------------------------------------------------------
15996 key String/Array A single keycode or an array of keycodes to handle
15997 shift Boolean True to handle key only when shift is pressed (defaults to false)
15998 ctrl Boolean True to handle key only when ctrl is pressed (defaults to false)
15999 alt Boolean True to handle key only when alt is pressed (defaults to false)
16000 fn Function The function to call when KeyMap finds the expected key combination
16001 scope Object The scope of the callback function
16007 var map = new Roo.KeyMap(document, {
16008 key: Roo.EventObject.ENTER,
16013 //Add a new binding to the existing KeyMap later
16021 * @param {Object/Array} config A single KeyMap config or an array of configs
16023 addBinding : function(config){
16024 if(config instanceof Array){
16025 for(var i = 0, len = config.length; i < len; i++){
16026 this.addBinding(config[i]);
16030 var keyCode = config.key,
16031 shift = config.shift,
16032 ctrl = config.ctrl,
16035 scope = config.scope;
16036 if(typeof keyCode == "string"){
16038 var keyString = keyCode.toUpperCase();
16039 for(var j = 0, len = keyString.length; j < len; j++){
16040 ks.push(keyString.charCodeAt(j));
16044 var keyArray = keyCode instanceof Array;
16045 var handler = function(e){
16046 if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) && (!alt || e.altKey)){
16047 var k = e.getKey();
16049 for(var i = 0, len = keyCode.length; i < len; i++){
16050 if(keyCode[i] == k){
16051 if(this.stopEvent){
16054 fn.call(scope || window, k, e);
16060 if(this.stopEvent){
16063 fn.call(scope || window, k, e);
16068 this.bindings.push(handler);
16072 * Shorthand for adding a single key listener
16073 * @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the
16074 * following options:
16075 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
16076 * @param {Function} fn The function to call
16077 * @param {Object} scope (optional) The scope of the function
16079 on : function(key, fn, scope){
16080 var keyCode, shift, ctrl, alt;
16081 if(typeof key == "object" && !(key instanceof Array)){
16100 handleKeyDown : function(e){
16101 if(this.enabled){ //just in case
16102 var b = this.bindings;
16103 for(var i = 0, len = b.length; i < len; i++){
16104 b[i].call(this, e);
16110 * Returns true if this KeyMap is enabled
16111 * @return {Boolean}
16113 isEnabled : function(){
16114 return this.enabled;
16118 * Enables this KeyMap
16120 enable: function(){
16122 this.el.on(this.eventName, this.handleKeyDown, this);
16123 this.enabled = true;
16128 * Disable this KeyMap
16130 disable: function(){
16132 this.el.removeListener(this.eventName, this.handleKeyDown, this);
16133 this.enabled = false;
16138 * Ext JS Library 1.1.1
16139 * Copyright(c) 2006-2007, Ext JS, LLC.
16141 * Originally Released Under LGPL - original licence link has changed is not relivant.
16144 * <script type="text/javascript">
16149 * @class Roo.util.TextMetrics
16150 * Provides precise pixel measurements for blocks of text so that you can determine exactly how high and
16151 * wide, in pixels, a given block of text will be.
16154 Roo.util.TextMetrics = function(){
16158 * Measures the size of the specified text
16159 * @param {String/HTMLElement} el The element, dom node or id from which to copy existing CSS styles
16160 * that can affect the size of the rendered text
16161 * @param {String} text The text to measure
16162 * @param {Number} fixedWidth (optional) If the text will be multiline, you have to set a fixed width
16163 * in order to accurately measure the text height
16164 * @return {Object} An object containing the text's size {width: (width), height: (height)}
16166 measure : function(el, text, fixedWidth){
16168 shared = Roo.util.TextMetrics.Instance(el, fixedWidth);
16171 shared.setFixedWidth(fixedWidth || 'auto');
16172 return shared.getSize(text);
16176 * Return a unique TextMetrics instance that can be bound directly to an element and reused. This reduces
16177 * the overhead of multiple calls to initialize the style properties on each measurement.
16178 * @param {String/HTMLElement} el The element, dom node or id that the instance will be bound to
16179 * @param {Number} fixedWidth (optional) If the text will be multiline, you have to set a fixed width
16180 * in order to accurately measure the text height
16181 * @return {Roo.util.TextMetrics.Instance} instance The new instance
16183 createInstance : function(el, fixedWidth){
16184 return Roo.util.TextMetrics.Instance(el, fixedWidth);
16190 * @class Roo.util.TextMetrics.Instance
16191 * Instance of TextMetrics Calcuation
16193 * Create a new TextMetrics Instance
16194 * @param {Object} bindto
16195 * @param {Boolean} fixedWidth
16198 Roo.util.TextMetrics.Instance = function(bindTo, fixedWidth)
16200 var ml = new Roo.Element(document.createElement('div'));
16201 document.body.appendChild(ml.dom);
16202 ml.position('absolute');
16203 ml.setLeftTop(-1000, -1000);
16207 ml.setWidth(fixedWidth);
16212 * Returns the size of the specified text based on the internal element's style and width properties
16213 * @param {String} text The text to measure
16214 * @return {Object} An object containing the text's size {width: (width), height: (height)}
16216 getSize : function(text){
16218 var s = ml.getSize();
16224 * Binds this TextMetrics instance to an element from which to copy existing CSS styles
16225 * that can affect the size of the rendered text
16226 * @param {String/HTMLElement} el The element, dom node or id
16228 bind : function(el){
16230 Roo.fly(el).getStyles('font-size','font-style', 'font-weight', 'font-family','line-height')
16235 * Sets a fixed width on the internal measurement element. If the text will be multiline, you have
16236 * to set a fixed width in order to accurately measure the text height.
16237 * @param {Number} width The width to set on the element
16239 setFixedWidth : function(width){
16240 ml.setWidth(width);
16244 * Returns the measured width of the specified text
16245 * @param {String} text The text to measure
16246 * @return {Number} width The width in pixels
16248 getWidth : function(text){
16249 ml.dom.style.width = 'auto';
16250 return this.getSize(text).width;
16254 * Returns the measured height of the specified text. For multiline text, be sure to call
16255 * {@link #setFixedWidth} if necessary.
16256 * @param {String} text The text to measure
16257 * @return {Number} height The height in pixels
16259 getHeight : function(text){
16260 return this.getSize(text).height;
16264 instance.bind(bindTo);
16269 // backwards compat
16270 Roo.Element.measureText = Roo.util.TextMetrics.measure;/*
16272 * Ext JS Library 1.1.1
16273 * Copyright(c) 2006-2007, Ext JS, LLC.
16275 * Originally Released Under LGPL - original licence link has changed is not relivant.
16278 * <script type="text/javascript">
16282 * @class Roo.state.Provider
16283 * Abstract base class for state provider implementations. This class provides methods
16284 * for encoding and decoding <b>typed</b> variables including dates and defines the
16285 * Provider interface.
16287 Roo.state.Provider = function(){
16289 * @event statechange
16290 * Fires when a state change occurs.
16291 * @param {Provider} this This state provider
16292 * @param {String} key The state key which was changed
16293 * @param {String} value The encoded value for the state
16296 "statechange": true
16299 Roo.state.Provider.superclass.constructor.call(this);
16301 Roo.extend(Roo.state.Provider, Roo.util.Observable, {
16303 * Returns the current value for a key
16304 * @param {String} name The key name
16305 * @param {Mixed} defaultValue A default value to return if the key's value is not found
16306 * @return {Mixed} The state data
16308 get : function(name, defaultValue){
16309 return typeof this.state[name] == "undefined" ?
16310 defaultValue : this.state[name];
16314 * Clears a value from the state
16315 * @param {String} name The key name
16317 clear : function(name){
16318 delete this.state[name];
16319 this.fireEvent("statechange", this, name, null);
16323 * Sets the value for a key
16324 * @param {String} name The key name
16325 * @param {Mixed} value The value to set
16327 set : function(name, value){
16328 this.state[name] = value;
16329 this.fireEvent("statechange", this, name, value);
16333 * Decodes a string previously encoded with {@link #encodeValue}.
16334 * @param {String} value The value to decode
16335 * @return {Mixed} The decoded value
16337 decodeValue : function(cookie){
16338 var re = /^(a|n|d|b|s|o)\:(.*)$/;
16339 var matches = re.exec(unescape(cookie));
16340 if(!matches || !matches[1]) {
16341 return; // non state cookie
16343 var type = matches[1];
16344 var v = matches[2];
16347 return parseFloat(v);
16349 return new Date(Date.parse(v));
16354 var values = v.split("^");
16355 for(var i = 0, len = values.length; i < len; i++){
16356 all.push(this.decodeValue(values[i]));
16361 var values = v.split("^");
16362 for(var i = 0, len = values.length; i < len; i++){
16363 var kv = values[i].split("=");
16364 all[kv[0]] = this.decodeValue(kv[1]);
16373 * Encodes a value including type information. Decode with {@link #decodeValue}.
16374 * @param {Mixed} value The value to encode
16375 * @return {String} The encoded value
16377 encodeValue : function(v){
16379 if(typeof v == "number"){
16381 }else if(typeof v == "boolean"){
16382 enc = "b:" + (v ? "1" : "0");
16383 }else if(v instanceof Date){
16384 enc = "d:" + v.toGMTString();
16385 }else if(v instanceof Array){
16387 for(var i = 0, len = v.length; i < len; i++){
16388 flat += this.encodeValue(v[i]);
16394 }else if(typeof v == "object"){
16397 if(typeof v[key] != "function"){
16398 flat += key + "=" + this.encodeValue(v[key]) + "^";
16401 enc = "o:" + flat.substring(0, flat.length-1);
16405 return escape(enc);
16411 * Ext JS Library 1.1.1
16412 * Copyright(c) 2006-2007, Ext JS, LLC.
16414 * Originally Released Under LGPL - original licence link has changed is not relivant.
16417 * <script type="text/javascript">
16420 * @class Roo.state.Manager
16421 * This is the global state manager. By default all components that are "state aware" check this class
16422 * for state information if you don't pass them a custom state provider. In order for this class
16423 * to be useful, it must be initialized with a provider when your application initializes.
16425 // in your initialization function
16427 Roo.state.Manager.setProvider(new Roo.state.CookieProvider());
16429 // supposed you have a {@link Roo.BorderLayout}
16430 var layout = new Roo.BorderLayout(...);
16431 layout.restoreState();
16432 // or a {Roo.BasicDialog}
16433 var dialog = new Roo.BasicDialog(...);
16434 dialog.restoreState();
16438 Roo.state.Manager = function(){
16439 var provider = new Roo.state.Provider();
16443 * Configures the default state provider for your application
16444 * @param {Provider} stateProvider The state provider to set
16446 setProvider : function(stateProvider){
16447 provider = stateProvider;
16451 * Returns the current value for a key
16452 * @param {String} name The key name
16453 * @param {Mixed} defaultValue The default value to return if the key lookup does not match
16454 * @return {Mixed} The state data
16456 get : function(key, defaultValue){
16457 return provider.get(key, defaultValue);
16461 * Sets the value for a key
16462 * @param {String} name The key name
16463 * @param {Mixed} value The state data
16465 set : function(key, value){
16466 provider.set(key, value);
16470 * Clears a value from the state
16471 * @param {String} name The key name
16473 clear : function(key){
16474 provider.clear(key);
16478 * Gets the currently configured state provider
16479 * @return {Provider} The state provider
16481 getProvider : function(){
16488 * Ext JS Library 1.1.1
16489 * Copyright(c) 2006-2007, Ext JS, LLC.
16491 * Originally Released Under LGPL - original licence link has changed is not relivant.
16494 * <script type="text/javascript">
16497 * @class Roo.state.CookieProvider
16498 * @extends Roo.state.Provider
16499 * The default Provider implementation which saves state via cookies.
16502 var cp = new Roo.state.CookieProvider({
16504 expires: new Date(new Date().getTime()+(1000*60*60*24*30)); //30 days
16505 domain: "roojs.com"
16507 Roo.state.Manager.setProvider(cp);
16509 * @cfg {String} path The path for which the cookie is active (defaults to root '/' which makes it active for all pages in the site)
16510 * @cfg {Date} expires The cookie expiration date (defaults to 7 days from now)
16511 * @cfg {String} domain The domain to save the cookie for. Note that you cannot specify a different domain than
16512 * your page is on, but you can specify a sub-domain, or simply the domain itself like 'roojs.com' to include
16513 * all sub-domains if you need to access cookies across different sub-domains (defaults to null which uses the same
16514 * domain the page is running on including the 'www' like 'www.roojs.com')
16515 * @cfg {Boolean} secure True if the site is using SSL (defaults to false)
16517 * Create a new CookieProvider
16518 * @param {Object} config The configuration object
16520 Roo.state.CookieProvider = function(config){
16521 Roo.state.CookieProvider.superclass.constructor.call(this);
16523 this.expires = new Date(new Date().getTime()+(1000*60*60*24*7)); //7 days
16524 this.domain = null;
16525 this.secure = false;
16526 Roo.apply(this, config);
16527 this.state = this.readCookies();
16530 Roo.extend(Roo.state.CookieProvider, Roo.state.Provider, {
16532 set : function(name, value){
16533 if(typeof value == "undefined" || value === null){
16537 this.setCookie(name, value);
16538 Roo.state.CookieProvider.superclass.set.call(this, name, value);
16542 clear : function(name){
16543 this.clearCookie(name);
16544 Roo.state.CookieProvider.superclass.clear.call(this, name);
16548 readCookies : function(){
16550 var c = document.cookie + ";";
16551 var re = /\s?(.*?)=(.*?);/g;
16553 while((matches = re.exec(c)) != null){
16554 var name = matches[1];
16555 var value = matches[2];
16556 if(name && name.substring(0,3) == "ys-"){
16557 cookies[name.substr(3)] = this.decodeValue(value);
16564 setCookie : function(name, value){
16565 document.cookie = "ys-"+ name + "=" + this.encodeValue(value) +
16566 ((this.expires == null) ? "" : ("; expires=" + this.expires.toGMTString())) +
16567 ((this.path == null) ? "" : ("; path=" + this.path)) +
16568 ((this.domain == null) ? "" : ("; domain=" + this.domain)) +
16569 ((this.secure == true) ? "; secure" : "");
16573 clearCookie : function(name){
16574 document.cookie = "ys-" + name + "=null; expires=Thu, 01-Jan-70 00:00:01 GMT" +
16575 ((this.path == null) ? "" : ("; path=" + this.path)) +
16576 ((this.domain == null) ? "" : ("; domain=" + this.domain)) +
16577 ((this.secure == true) ? "; secure" : "");
16581 * Ext JS Library 1.1.1
16582 * Copyright(c) 2006-2007, Ext JS, LLC.
16584 * Originally Released Under LGPL - original licence link has changed is not relivant.
16587 * <script type="text/javascript">
16592 * @class Roo.ComponentMgr
16593 * Provides a common registry of all components on a page so that they can be easily accessed by component id (see {@link Roo.getCmp}).
16596 Roo.ComponentMgr = function(){
16597 var all = new Roo.util.MixedCollection();
16601 * Registers a component.
16602 * @param {Roo.Component} c The component
16604 register : function(c){
16609 * Unregisters a component.
16610 * @param {Roo.Component} c The component
16612 unregister : function(c){
16617 * Returns a component by id
16618 * @param {String} id The component id
16620 get : function(id){
16621 return all.get(id);
16625 * Registers a function that will be called when a specified component is added to ComponentMgr
16626 * @param {String} id The component id
16627 * @param {Funtction} fn The callback function
16628 * @param {Object} scope The scope of the callback
16630 onAvailable : function(id, fn, scope){
16631 all.on("add", function(index, o){
16633 fn.call(scope || o, o);
16634 all.un("add", fn, scope);
16641 * Ext JS Library 1.1.1
16642 * Copyright(c) 2006-2007, Ext JS, LLC.
16644 * Originally Released Under LGPL - original licence link has changed is not relivant.
16647 * <script type="text/javascript">
16651 * @class Roo.Component
16652 * @extends Roo.util.Observable
16653 * Base class for all major Roo components. All subclasses of Component can automatically participate in the standard
16654 * Roo component lifecycle of creation, rendering and destruction. They also have automatic support for basic hide/show
16655 * and enable/disable behavior. Component allows any subclass to be lazy-rendered into any {@link Roo.Container} and
16656 * to be automatically registered with the {@link Roo.ComponentMgr} so that it can be referenced at any time via {@link Roo.getCmp}.
16657 * All visual components (widgets) that require rendering into a layout should subclass Component.
16659 * @param {Roo.Element/String/Object} config The configuration options. If an element is passed, it is set as the internal
16660 * 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
16661 * and is used as the component id. Otherwise, it is assumed to be a standard config object and is applied to the component.
16663 Roo.Component = function(config){
16664 config = config || {};
16665 if(config.tagName || config.dom || typeof config == "string"){ // element object
16666 config = {el: config, id: config.id || config};
16668 this.initialConfig = config;
16670 Roo.apply(this, config);
16674 * Fires after the component is disabled.
16675 * @param {Roo.Component} this
16680 * Fires after the component is enabled.
16681 * @param {Roo.Component} this
16685 * @event beforeshow
16686 * Fires before the component is shown. Return false to stop the show.
16687 * @param {Roo.Component} this
16692 * Fires after the component is shown.
16693 * @param {Roo.Component} this
16697 * @event beforehide
16698 * Fires before the component is hidden. Return false to stop the hide.
16699 * @param {Roo.Component} this
16704 * Fires after the component is hidden.
16705 * @param {Roo.Component} this
16709 * @event beforerender
16710 * Fires before the component is rendered. Return false to stop the render.
16711 * @param {Roo.Component} this
16713 beforerender : true,
16716 * Fires after the component is rendered.
16717 * @param {Roo.Component} this
16721 * @event beforedestroy
16722 * Fires before the component is destroyed. Return false to stop the destroy.
16723 * @param {Roo.Component} this
16725 beforedestroy : true,
16728 * Fires after the component is destroyed.
16729 * @param {Roo.Component} this
16734 this.id = "roo-comp-" + (++Roo.Component.AUTO_ID);
16736 Roo.ComponentMgr.register(this);
16737 Roo.Component.superclass.constructor.call(this);
16738 this.initComponent();
16739 if(this.renderTo){ // not supported by all components yet. use at your own risk!
16740 this.render(this.renderTo);
16741 delete this.renderTo;
16746 Roo.Component.AUTO_ID = 1000;
16748 Roo.extend(Roo.Component, Roo.util.Observable, {
16750 * @scope Roo.Component.prototype
16752 * true if this component is hidden. Read-only.
16757 * true if this component is disabled. Read-only.
16762 * true if this component has been rendered. Read-only.
16766 /** @cfg {String} disableClass
16767 * CSS class added to the component when it is disabled (defaults to "x-item-disabled").
16769 disabledClass : "x-item-disabled",
16770 /** @cfg {Boolean} allowDomMove
16771 * Whether the component can move the Dom node when rendering (defaults to true).
16773 allowDomMove : true,
16774 /** @cfg {String} hideMode (display|visibility)
16775 * How this component should hidden. Supported values are
16776 * "visibility" (css visibility), "offsets" (negative offset position) and
16777 * "display" (css display) - defaults to "display".
16779 hideMode: 'display',
16782 ctype : "Roo.Component",
16785 * @cfg {String} actionMode
16786 * which property holds the element that used for hide() / show() / disable() / enable()
16787 * default is 'el' for forms you probably want to set this to fieldEl
16792 getActionEl : function(){
16793 return this[this.actionMode];
16796 initComponent : Roo.emptyFn,
16798 * If this is a lazy rendering component, render it to its container element.
16799 * @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.
16801 render : function(container, position){
16807 if(this.fireEvent("beforerender", this) === false){
16811 if(!container && this.el){
16812 this.el = Roo.get(this.el);
16813 container = this.el.dom.parentNode;
16814 this.allowDomMove = false;
16816 this.container = Roo.get(container);
16817 this.rendered = true;
16818 if(position !== undefined){
16819 if(typeof position == 'number'){
16820 position = this.container.dom.childNodes[position];
16822 position = Roo.getDom(position);
16825 this.onRender(this.container, position || null);
16827 this.el.addClass(this.cls);
16831 this.el.applyStyles(this.style);
16834 this.fireEvent("render", this);
16835 this.afterRender(this.container);
16848 // default function is not really useful
16849 onRender : function(ct, position){
16851 this.el = Roo.get(this.el);
16852 if(this.allowDomMove !== false){
16853 ct.dom.insertBefore(this.el.dom, position);
16859 getAutoCreate : function(){
16860 var cfg = typeof this.autoCreate == "object" ?
16861 this.autoCreate : Roo.apply({}, this.defaultAutoCreate);
16862 if(this.id && !cfg.id){
16869 afterRender : Roo.emptyFn,
16872 * Destroys this component by purging any event listeners, removing the component's element from the DOM,
16873 * removing the component from its {@link Roo.Container} (if applicable) and unregistering it from {@link Roo.ComponentMgr}.
16875 destroy : function(){
16876 if(this.fireEvent("beforedestroy", this) !== false){
16877 this.purgeListeners();
16878 this.beforeDestroy();
16880 this.el.removeAllListeners();
16882 if(this.actionMode == "container"){
16883 this.container.remove();
16887 Roo.ComponentMgr.unregister(this);
16888 this.fireEvent("destroy", this);
16893 beforeDestroy : function(){
16898 onDestroy : function(){
16903 * Returns the underlying {@link Roo.Element}.
16904 * @return {Roo.Element} The element
16906 getEl : function(){
16911 * Returns the id of this component.
16914 getId : function(){
16919 * Try to focus this component.
16920 * @param {Boolean} selectText True to also select the text in this component (if applicable)
16921 * @return {Roo.Component} this
16923 focus : function(selectText){
16926 if(selectText === true){
16927 this.el.dom.select();
16942 * Disable this component.
16943 * @return {Roo.Component} this
16945 disable : function(){
16949 this.disabled = true;
16950 this.fireEvent("disable", this);
16955 onDisable : function(){
16956 this.getActionEl().addClass(this.disabledClass);
16957 this.el.dom.disabled = true;
16961 * Enable this component.
16962 * @return {Roo.Component} this
16964 enable : function(){
16968 this.disabled = false;
16969 this.fireEvent("enable", this);
16974 onEnable : function(){
16975 this.getActionEl().removeClass(this.disabledClass);
16976 this.el.dom.disabled = false;
16980 * Convenience function for setting disabled/enabled by boolean.
16981 * @param {Boolean} disabled
16983 setDisabled : function(disabled){
16984 this[disabled ? "disable" : "enable"]();
16988 * Show this component.
16989 * @return {Roo.Component} this
16992 if(this.fireEvent("beforeshow", this) !== false){
16993 this.hidden = false;
16997 this.fireEvent("show", this);
17003 onShow : function(){
17004 var ae = this.getActionEl();
17005 if(this.hideMode == 'visibility'){
17006 ae.dom.style.visibility = "visible";
17007 }else if(this.hideMode == 'offsets'){
17008 ae.removeClass('x-hidden');
17010 ae.dom.style.display = "";
17015 * Hide this component.
17016 * @return {Roo.Component} this
17019 if(this.fireEvent("beforehide", this) !== false){
17020 this.hidden = true;
17024 this.fireEvent("hide", this);
17030 onHide : function(){
17031 var ae = this.getActionEl();
17032 if(this.hideMode == 'visibility'){
17033 ae.dom.style.visibility = "hidden";
17034 }else if(this.hideMode == 'offsets'){
17035 ae.addClass('x-hidden');
17037 ae.dom.style.display = "none";
17042 * Convenience function to hide or show this component by boolean.
17043 * @param {Boolean} visible True to show, false to hide
17044 * @return {Roo.Component} this
17046 setVisible: function(visible){
17056 * Returns true if this component is visible.
17058 isVisible : function(){
17059 return this.getActionEl().isVisible();
17062 cloneConfig : function(overrides){
17063 overrides = overrides || {};
17064 var id = overrides.id || Roo.id();
17065 var cfg = Roo.applyIf(overrides, this.initialConfig);
17066 cfg.id = id; // prevent dup id
17067 return new this.constructor(cfg);
17071 * Ext JS Library 1.1.1
17072 * Copyright(c) 2006-2007, Ext JS, LLC.
17074 * Originally Released Under LGPL - original licence link has changed is not relivant.
17077 * <script type="text/javascript">
17081 * @class Roo.BoxComponent
17082 * @extends Roo.Component
17083 * Base class for any visual {@link Roo.Component} that uses a box container. BoxComponent provides automatic box
17084 * model adjustments for sizing and positioning and will work correctly withnin the Component rendering model. All
17085 * container classes should subclass BoxComponent so that they will work consistently when nested within other Roo
17086 * layout containers.
17088 * @param {Roo.Element/String/Object} config The configuration options.
17090 Roo.BoxComponent = function(config){
17091 Roo.Component.call(this, config);
17095 * Fires after the component is resized.
17096 * @param {Roo.Component} this
17097 * @param {Number} adjWidth The box-adjusted width that was set
17098 * @param {Number} adjHeight The box-adjusted height that was set
17099 * @param {Number} rawWidth The width that was originally specified
17100 * @param {Number} rawHeight The height that was originally specified
17105 * Fires after the component is moved.
17106 * @param {Roo.Component} this
17107 * @param {Number} x The new x position
17108 * @param {Number} y The new y position
17114 Roo.extend(Roo.BoxComponent, Roo.Component, {
17115 // private, set in afterRender to signify that the component has been rendered
17117 // private, used to defer height settings to subclasses
17118 deferHeight: false,
17119 /** @cfg {Number} width
17120 * width (optional) size of component
17122 /** @cfg {Number} height
17123 * height (optional) size of component
17127 * Sets the width and height of the component. This method fires the resize event. This method can accept
17128 * either width and height as separate numeric arguments, or you can pass a size object like {width:10, height:20}.
17129 * @param {Number/Object} width The new width to set, or a size object in the format {width, height}
17130 * @param {Number} height The new height to set (not required if a size object is passed as the first arg)
17131 * @return {Roo.BoxComponent} this
17133 setSize : function(w, h){
17134 // support for standard size objects
17135 if(typeof w == 'object'){
17140 if(!this.boxReady){
17146 // prevent recalcs when not needed
17147 if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
17150 this.lastSize = {width: w, height: h};
17152 var adj = this.adjustSize(w, h);
17153 var aw = adj.width, ah = adj.height;
17154 if(aw !== undefined || ah !== undefined){ // this code is nasty but performs better with floaters
17155 var rz = this.getResizeEl();
17156 if(!this.deferHeight && aw !== undefined && ah !== undefined){
17157 rz.setSize(aw, ah);
17158 }else if(!this.deferHeight && ah !== undefined){
17160 }else if(aw !== undefined){
17163 this.onResize(aw, ah, w, h);
17164 this.fireEvent('resize', this, aw, ah, w, h);
17170 * Gets the current size of the component's underlying element.
17171 * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
17173 getSize : function(){
17174 return this.el.getSize();
17178 * Gets the current XY position of the component's underlying element.
17179 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
17180 * @return {Array} The XY position of the element (e.g., [100, 200])
17182 getPosition : function(local){
17183 if(local === true){
17184 return [this.el.getLeft(true), this.el.getTop(true)];
17186 return this.xy || this.el.getXY();
17190 * Gets the current box measurements of the component's underlying element.
17191 * @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
17192 * @returns {Object} box An object in the format {x, y, width, height}
17194 getBox : function(local){
17195 var s = this.el.getSize();
17197 s.x = this.el.getLeft(true);
17198 s.y = this.el.getTop(true);
17200 var xy = this.xy || this.el.getXY();
17208 * Sets the current box measurements of the component's underlying element.
17209 * @param {Object} box An object in the format {x, y, width, height}
17210 * @returns {Roo.BoxComponent} this
17212 updateBox : function(box){
17213 this.setSize(box.width, box.height);
17214 this.setPagePosition(box.x, box.y);
17219 getResizeEl : function(){
17220 return this.resizeEl || this.el;
17224 getPositionEl : function(){
17225 return this.positionEl || this.el;
17229 * Sets the left and top of the component. To set the page XY position instead, use {@link #setPagePosition}.
17230 * This method fires the move event.
17231 * @param {Number} left The new left
17232 * @param {Number} top The new top
17233 * @returns {Roo.BoxComponent} this
17235 setPosition : function(x, y){
17238 if(!this.boxReady){
17241 var adj = this.adjustPosition(x, y);
17242 var ax = adj.x, ay = adj.y;
17244 var el = this.getPositionEl();
17245 if(ax !== undefined || ay !== undefined){
17246 if(ax !== undefined && ay !== undefined){
17247 el.setLeftTop(ax, ay);
17248 }else if(ax !== undefined){
17250 }else if(ay !== undefined){
17253 this.onPosition(ax, ay);
17254 this.fireEvent('move', this, ax, ay);
17260 * Sets the page XY position of the component. To set the left and top instead, use {@link #setPosition}.
17261 * This method fires the move event.
17262 * @param {Number} x The new x position
17263 * @param {Number} y The new y position
17264 * @returns {Roo.BoxComponent} this
17266 setPagePosition : function(x, y){
17269 if(!this.boxReady){
17272 if(x === undefined || y === undefined){ // cannot translate undefined points
17275 var p = this.el.translatePoints(x, y);
17276 this.setPosition(p.left, p.top);
17281 onRender : function(ct, position){
17282 Roo.BoxComponent.superclass.onRender.call(this, ct, position);
17284 this.resizeEl = Roo.get(this.resizeEl);
17286 if(this.positionEl){
17287 this.positionEl = Roo.get(this.positionEl);
17292 afterRender : function(){
17293 Roo.BoxComponent.superclass.afterRender.call(this);
17294 this.boxReady = true;
17295 this.setSize(this.width, this.height);
17296 if(this.x || this.y){
17297 this.setPosition(this.x, this.y);
17299 if(this.pageX || this.pageY){
17300 this.setPagePosition(this.pageX, this.pageY);
17305 * Force the component's size to recalculate based on the underlying element's current height and width.
17306 * @returns {Roo.BoxComponent} this
17308 syncSize : function(){
17309 delete this.lastSize;
17310 this.setSize(this.el.getWidth(), this.el.getHeight());
17315 * Called after the component is resized, this method is empty by default but can be implemented by any
17316 * subclass that needs to perform custom logic after a resize occurs.
17317 * @param {Number} adjWidth The box-adjusted width that was set
17318 * @param {Number} adjHeight The box-adjusted height that was set
17319 * @param {Number} rawWidth The width that was originally specified
17320 * @param {Number} rawHeight The height that was originally specified
17322 onResize : function(adjWidth, adjHeight, rawWidth, rawHeight){
17327 * Called after the component is moved, this method is empty by default but can be implemented by any
17328 * subclass that needs to perform custom logic after a move occurs.
17329 * @param {Number} x The new x position
17330 * @param {Number} y The new y position
17332 onPosition : function(x, y){
17337 adjustSize : function(w, h){
17338 if(this.autoWidth){
17341 if(this.autoHeight){
17344 return {width : w, height: h};
17348 adjustPosition : function(x, y){
17349 return {x : x, y: y};
17353 * Ext JS Library 1.1.1
17354 * Copyright(c) 2006-2007, Ext JS, LLC.
17356 * Originally Released Under LGPL - original licence link has changed is not relivant.
17359 * <script type="text/javascript">
17364 * @extends Roo.Element
17365 * An extended {@link Roo.Element} object that supports a shadow and shim, constrain to viewport and
17366 * automatic maintaining of shadow/shim positions.
17367 * @cfg {Boolean} shim False to disable the iframe shim in browsers which need one (defaults to true)
17368 * @cfg {String/Boolean} shadow True to create a shadow element with default class "x-layer-shadow", or
17369 * you can pass a string with a CSS class name. False turns off the shadow.
17370 * @cfg {Object} dh DomHelper object config to create element with (defaults to {tag: "div", cls: "x-layer"}).
17371 * @cfg {Boolean} constrain False to disable constrain to viewport (defaults to true)
17372 * @cfg {String} cls CSS class to add to the element
17373 * @cfg {Number} zindex Starting z-index (defaults to 11000)
17374 * @cfg {Number} shadowOffset Number of pixels to offset the shadow (defaults to 3)
17376 * @param {Object} config An object with config options.
17377 * @param {String/HTMLElement} existingEl (optional) Uses an existing DOM element. If the element is not found it creates it.
17380 Roo.Layer = function(config, existingEl){
17381 config = config || {};
17382 var dh = Roo.DomHelper;
17383 var cp = config.parentEl, pel = cp ? Roo.getDom(cp) : document.body;
17385 this.dom = Roo.getDom(existingEl);
17388 var o = config.dh || {tag: "div", cls: "x-layer"};
17389 this.dom = dh.append(pel, o);
17392 this.addClass(config.cls);
17394 this.constrain = config.constrain !== false;
17395 this.visibilityMode = Roo.Element.VISIBILITY;
17397 this.id = this.dom.id = config.id;
17399 this.id = Roo.id(this.dom);
17401 this.zindex = config.zindex || this.getZIndex();
17402 this.position("absolute", this.zindex);
17404 this.shadowOffset = config.shadowOffset || 4;
17405 this.shadow = new Roo.Shadow({
17406 offset : this.shadowOffset,
17407 mode : config.shadow
17410 this.shadowOffset = 0;
17412 this.useShim = config.shim !== false && Roo.useShims;
17413 this.useDisplay = config.useDisplay;
17417 var supr = Roo.Element.prototype;
17419 // shims are shared among layer to keep from having 100 iframes
17422 Roo.extend(Roo.Layer, Roo.Element, {
17424 getZIndex : function(){
17425 return this.zindex || parseInt(this.getStyle("z-index"), 10) || 11000;
17428 getShim : function(){
17435 var shim = shims.shift();
17437 shim = this.createShim();
17438 shim.enableDisplayMode('block');
17439 shim.dom.style.display = 'none';
17440 shim.dom.style.visibility = 'visible';
17442 var pn = this.dom.parentNode;
17443 if(shim.dom.parentNode != pn){
17444 pn.insertBefore(shim.dom, this.dom);
17446 shim.setStyle('z-index', this.getZIndex()-2);
17451 hideShim : function(){
17453 this.shim.setDisplayed(false);
17454 shims.push(this.shim);
17459 disableShadow : function(){
17461 this.shadowDisabled = true;
17462 this.shadow.hide();
17463 this.lastShadowOffset = this.shadowOffset;
17464 this.shadowOffset = 0;
17468 enableShadow : function(show){
17470 this.shadowDisabled = false;
17471 this.shadowOffset = this.lastShadowOffset;
17472 delete this.lastShadowOffset;
17480 // this code can execute repeatedly in milliseconds (i.e. during a drag) so
17481 // code size was sacrificed for effeciency (e.g. no getBox/setBox, no XY calls)
17482 sync : function(doShow){
17483 var sw = this.shadow;
17484 if(!this.updating && this.isVisible() && (sw || this.useShim)){
17485 var sh = this.getShim();
17487 var w = this.getWidth(),
17488 h = this.getHeight();
17490 var l = this.getLeft(true),
17491 t = this.getTop(true);
17493 if(sw && !this.shadowDisabled){
17494 if(doShow && !sw.isVisible()){
17497 sw.realign(l, t, w, h);
17503 // fit the shim behind the shadow, so it is shimmed too
17504 var a = sw.adjusts, s = sh.dom.style;
17505 s.left = (Math.min(l, l+a.l))+"px";
17506 s.top = (Math.min(t, t+a.t))+"px";
17507 s.width = (w+a.w)+"px";
17508 s.height = (h+a.h)+"px";
17515 sh.setLeftTop(l, t);
17522 destroy : function(){
17525 this.shadow.hide();
17527 this.removeAllListeners();
17528 var pn = this.dom.parentNode;
17530 pn.removeChild(this.dom);
17532 Roo.Element.uncache(this.id);
17535 remove : function(){
17540 beginUpdate : function(){
17541 this.updating = true;
17545 endUpdate : function(){
17546 this.updating = false;
17551 hideUnders : function(negOffset){
17553 this.shadow.hide();
17559 constrainXY : function(){
17560 if(this.constrain){
17561 var vw = Roo.lib.Dom.getViewWidth(),
17562 vh = Roo.lib.Dom.getViewHeight();
17563 var s = Roo.get(document).getScroll();
17565 var xy = this.getXY();
17566 var x = xy[0], y = xy[1];
17567 var w = this.dom.offsetWidth+this.shadowOffset, h = this.dom.offsetHeight+this.shadowOffset;
17568 // only move it if it needs it
17570 // first validate right/bottom
17571 if((x + w) > vw+s.left){
17572 x = vw - w - this.shadowOffset;
17575 if((y + h) > vh+s.top){
17576 y = vh - h - this.shadowOffset;
17579 // then make sure top/left isn't negative
17590 var ay = this.avoidY;
17591 if(y <= ay && (y+h) >= ay){
17597 supr.setXY.call(this, xy);
17603 isVisible : function(){
17604 return this.visible;
17608 showAction : function(){
17609 this.visible = true; // track visibility to prevent getStyle calls
17610 if(this.useDisplay === true){
17611 this.setDisplayed("");
17612 }else if(this.lastXY){
17613 supr.setXY.call(this, this.lastXY);
17614 }else if(this.lastLT){
17615 supr.setLeftTop.call(this, this.lastLT[0], this.lastLT[1]);
17620 hideAction : function(){
17621 this.visible = false;
17622 if(this.useDisplay === true){
17623 this.setDisplayed(false);
17625 this.setLeftTop(-10000,-10000);
17629 // overridden Element method
17630 setVisible : function(v, a, d, c, e){
17635 var cb = function(){
17640 }.createDelegate(this);
17641 supr.setVisible.call(this, true, true, d, cb, e);
17644 this.hideUnders(true);
17653 }.createDelegate(this);
17655 supr.setVisible.call(this, v, a, d, cb, e);
17664 storeXY : function(xy){
17665 delete this.lastLT;
17669 storeLeftTop : function(left, top){
17670 delete this.lastXY;
17671 this.lastLT = [left, top];
17675 beforeFx : function(){
17676 this.beforeAction();
17677 return Roo.Layer.superclass.beforeFx.apply(this, arguments);
17681 afterFx : function(){
17682 Roo.Layer.superclass.afterFx.apply(this, arguments);
17683 this.sync(this.isVisible());
17687 beforeAction : function(){
17688 if(!this.updating && this.shadow){
17689 this.shadow.hide();
17693 // overridden Element method
17694 setLeft : function(left){
17695 this.storeLeftTop(left, this.getTop(true));
17696 supr.setLeft.apply(this, arguments);
17700 setTop : function(top){
17701 this.storeLeftTop(this.getLeft(true), top);
17702 supr.setTop.apply(this, arguments);
17706 setLeftTop : function(left, top){
17707 this.storeLeftTop(left, top);
17708 supr.setLeftTop.apply(this, arguments);
17712 setXY : function(xy, a, d, c, e){
17714 this.beforeAction();
17716 var cb = this.createCB(c);
17717 supr.setXY.call(this, xy, a, d, cb, e);
17724 createCB : function(c){
17735 // overridden Element method
17736 setX : function(x, a, d, c, e){
17737 this.setXY([x, this.getY()], a, d, c, e);
17740 // overridden Element method
17741 setY : function(y, a, d, c, e){
17742 this.setXY([this.getX(), y], a, d, c, e);
17745 // overridden Element method
17746 setSize : function(w, h, a, d, c, e){
17747 this.beforeAction();
17748 var cb = this.createCB(c);
17749 supr.setSize.call(this, w, h, a, d, cb, e);
17755 // overridden Element method
17756 setWidth : function(w, a, d, c, e){
17757 this.beforeAction();
17758 var cb = this.createCB(c);
17759 supr.setWidth.call(this, w, a, d, cb, e);
17765 // overridden Element method
17766 setHeight : function(h, a, d, c, e){
17767 this.beforeAction();
17768 var cb = this.createCB(c);
17769 supr.setHeight.call(this, h, a, d, cb, e);
17775 // overridden Element method
17776 setBounds : function(x, y, w, h, a, d, c, e){
17777 this.beforeAction();
17778 var cb = this.createCB(c);
17780 this.storeXY([x, y]);
17781 supr.setXY.call(this, [x, y]);
17782 supr.setSize.call(this, w, h, a, d, cb, e);
17785 supr.setBounds.call(this, x, y, w, h, a, d, cb, e);
17791 * Sets the z-index of this layer and adjusts any shadow and shim z-indexes. The layer z-index is automatically
17792 * incremented by two more than the value passed in so that it always shows above any shadow or shim (the shadow
17793 * element, if any, will be assigned z-index + 1, and the shim element, if any, will be assigned the unmodified z-index).
17794 * @param {Number} zindex The new z-index to set
17795 * @return {this} The Layer
17797 setZIndex : function(zindex){
17798 this.zindex = zindex;
17799 this.setStyle("z-index", zindex + 2);
17801 this.shadow.setZIndex(zindex + 1);
17804 this.shim.setStyle("z-index", zindex);
17809 * Original code for Roojs - LGPL
17810 * <script type="text/javascript">
17814 * @class Roo.XComponent
17815 * A delayed Element creator...
17816 * Or a way to group chunks of interface together.
17817 * technically this is a wrapper around a tree of Roo elements (which defines a 'module'),
17818 * used in conjunction with XComponent.build() it will create an instance of each element,
17819 * then call addxtype() to build the User interface.
17821 * Mypart.xyx = new Roo.XComponent({
17823 parent : 'Mypart.xyz', // empty == document.element.!!
17827 disabled : function() {}
17829 tree : function() { // return an tree of xtype declared components
17833 xtype : 'NestedLayoutPanel',
17840 * It can be used to build a big heiracy, with parent etc.
17841 * or you can just use this to render a single compoent to a dom element
17842 * MYPART.render(Roo.Element | String(id) | dom_element )
17849 * Roo is designed primarily as a single page application, so the UI build for a standard interface will
17850 * expect a single 'TOP' level module normally indicated by the 'parent' of the XComponent definition being defined as false.
17852 * Each sub module is expected to have a parent pointing to the class name of it's parent module.
17854 * When the top level is false, a 'Roo.BorderLayout' is created and the element is flagged as 'topModule'
17855 * - if mulitple topModules exist, the last one is defined as the top module.
17859 * When the top level or multiple modules are to embedded into a existing HTML page,
17860 * the parent element can container '#id' of the element where the module will be drawn.
17864 * Unlike classic Roo, the bootstrap tends not to be used as a single page.
17865 * it relies more on a include mechanism, where sub modules are included into an outer page.
17866 * This is normally managed by the builder tools using Roo.apply( options, Included.Sub.Module )
17868 * Bootstrap Roo Included elements
17870 * Our builder application needs the ability to preview these sub compoennts. They will normally have parent=false set,
17871 * hence confusing the component builder as it thinks there are multiple top level elements.
17873 * String Over-ride & Translations
17875 * Our builder application writes all the strings as _strings and _named_strings. This is to enable the translation of elements,
17876 * and also the 'overlaying of string values - needed when different versions of the same application with different text content
17877 * are needed. @see Roo.XComponent.overlayString
17881 * @extends Roo.util.Observable
17883 * @param cfg {Object} configuration of component
17886 Roo.XComponent = function(cfg) {
17887 Roo.apply(this, cfg);
17891 * Fires when this the componnt is built
17892 * @param {Roo.XComponent} c the component
17897 this.region = this.region || 'center'; // default..
17898 Roo.XComponent.register(this);
17899 this.modules = false;
17900 this.el = false; // where the layout goes..
17904 Roo.extend(Roo.XComponent, Roo.util.Observable, {
17907 * The created element (with Roo.factory())
17908 * @type {Roo.Layout}
17914 * for BC - use el in new code
17915 * @type {Roo.Layout}
17921 * for BC - use el in new code
17922 * @type {Roo.Layout}
17927 * @cfg {Function|boolean} disabled
17928 * If this module is disabled by some rule, return true from the funtion
17933 * @cfg {String} parent
17934 * Name of parent element which it get xtype added to..
17939 * @cfg {String} order
17940 * Used to set the order in which elements are created (usefull for multiple tabs)
17945 * @cfg {String} name
17946 * String to display while loading.
17950 * @cfg {String} region
17951 * Region to render component to (defaults to center)
17956 * @cfg {Array} items
17957 * A single item array - the first element is the root of the tree..
17958 * It's done this way to stay compatible with the Xtype system...
17964 * The method that retuns the tree of parts that make up this compoennt
17971 * render element to dom or tree
17972 * @param {Roo.Element|String|DomElement} optional render to if parent is not set.
17975 render : function(el)
17979 var hp = this.parent ? 1 : 0;
17980 Roo.debug && Roo.log(this);
17982 var tree = this._tree ? this._tree() : this.tree();
17985 if (!el && typeof(this.parent) == 'string' && this.parent.substring(0,1) == '#') {
17986 // if parent is a '#.....' string, then let's use that..
17987 var ename = this.parent.substr(1);
17988 this.parent = false;
17989 Roo.debug && Roo.log(ename);
17991 case 'bootstrap-body':
17992 if (typeof(tree.el) != 'undefined' && tree.el == document.body) {
17993 // this is the BorderLayout standard?
17994 this.parent = { el : true };
17997 if (["Nest", "Content", "Grid", "Tree"].indexOf(tree.xtype) > -1) {
17998 // need to insert stuff...
18000 el : new Roo.bootstrap.layout.Border({
18001 el : document.body,
18007 tabPosition: 'top',
18008 //resizeTabs: true,
18009 alwaysShowTabs: true,
18019 if (typeof(Roo.bootstrap.Body) != 'undefined' ) {
18020 this.parent = { el : new Roo.bootstrap.Body() };
18021 Roo.debug && Roo.log("setting el to doc body");
18024 throw "Container is bootstrap body, but Roo.bootstrap.Body is not defined";
18028 this.parent = { el : true};
18031 el = Roo.get(ename);
18032 if (typeof(Roo.bootstrap) != 'undefined' && tree['|xns'] == 'Roo.bootstrap') {
18033 this.parent = { el : true};
18040 if (!el && !this.parent) {
18041 Roo.debug && Roo.log("Warning - element can not be found :#" + ename );
18046 Roo.debug && Roo.log("EL:");
18047 Roo.debug && Roo.log(el);
18048 Roo.debug && Roo.log("this.parent.el:");
18049 Roo.debug && Roo.log(this.parent.el);
18052 // altertive root elements ??? - we need a better way to indicate these.
18053 var is_alt = Roo.XComponent.is_alt ||
18054 (typeof(tree.el) != 'undefined' && tree.el == document.body) ||
18055 (typeof(Roo.bootstrap) != 'undefined' && tree.xns == Roo.bootstrap) ||
18056 (typeof(Roo.mailer) != 'undefined' && tree.xns == Roo.mailer) ;
18060 if (!this.parent && is_alt) {
18061 //el = Roo.get(document.body);
18062 this.parent = { el : true };
18067 if (!this.parent) {
18069 Roo.debug && Roo.log("no parent - creating one");
18071 el = el ? Roo.get(el) : false;
18073 if (typeof(Roo.BorderLayout) == 'undefined' ) {
18076 el : new Roo.bootstrap.layout.Border({
18077 el: el || document.body,
18083 tabPosition: 'top',
18084 //resizeTabs: true,
18085 alwaysShowTabs: false,
18088 overflow: 'visible'
18094 // it's a top level one..
18096 el : new Roo.BorderLayout(el || document.body, {
18101 tabPosition: 'top',
18102 //resizeTabs: true,
18103 alwaysShowTabs: el && hp? false : true,
18104 hideTabs: el || !hp ? true : false,
18112 if (!this.parent.el) {
18113 // probably an old style ctor, which has been disabled.
18117 // The 'tree' method is '_tree now'
18119 tree.region = tree.region || this.region;
18120 var is_body = false;
18121 if (this.parent.el === true) {
18122 // bootstrap... - body..
18126 this.parent.el = Roo.factory(tree);
18130 this.el = this.parent.el.addxtype(tree, undefined, is_body);
18131 this.fireEvent('built', this);
18133 this.panel = this.el;
18134 this.layout = this.panel.layout;
18135 this.parentLayout = this.parent.layout || false;
18141 Roo.apply(Roo.XComponent, {
18143 * @property hideProgress
18144 * true to disable the building progress bar.. usefull on single page renders.
18147 hideProgress : false,
18149 * @property buildCompleted
18150 * True when the builder has completed building the interface.
18153 buildCompleted : false,
18156 * @property topModule
18157 * the upper most module - uses document.element as it's constructor.
18164 * @property modules
18165 * array of modules to be created by registration system.
18166 * @type {Array} of Roo.XComponent
18171 * @property elmodules
18172 * array of modules to be created by which use #ID
18173 * @type {Array} of Roo.XComponent
18180 * Is an alternative Root - normally used by bootstrap or other systems,
18181 * where the top element in the tree can wrap 'body'
18182 * @type {boolean} (default false)
18187 * @property build_from_html
18188 * Build elements from html - used by bootstrap HTML stuff
18189 * - this is cleared after build is completed
18190 * @type {boolean} (default false)
18193 build_from_html : false,
18195 * Register components to be built later.
18197 * This solves the following issues
18198 * - Building is not done on page load, but after an authentication process has occured.
18199 * - Interface elements are registered on page load
18200 * - Parent Interface elements may not be loaded before child, so this handles that..
18207 module : 'Pman.Tab.projectMgr',
18209 parent : 'Pman.layout',
18210 disabled : false, // or use a function..
18213 * * @param {Object} details about module
18215 register : function(obj) {
18217 Roo.XComponent.event.fireEvent('register', obj);
18218 switch(typeof(obj.disabled) ) {
18224 if ( obj.disabled() ) {
18230 if (obj.disabled || obj.region == '#disabled') {
18236 this.modules.push(obj);
18240 * convert a string to an object..
18241 * eg. 'AAA.BBB' -> finds AAA.BBB
18245 toObject : function(str)
18247 if (!str || typeof(str) == 'object') {
18250 if (str.substring(0,1) == '#') {
18254 var ar = str.split('.');
18259 eval('if (typeof ' + rt + ' == "undefined"){ o = false;} o = ' + rt + ';');
18261 throw "Module not found : " + str;
18265 throw "Module not found : " + str;
18267 Roo.each(ar, function(e) {
18268 if (typeof(o[e]) == 'undefined') {
18269 throw "Module not found : " + str;
18280 * move modules into their correct place in the tree..
18283 preBuild : function ()
18286 Roo.each(this.modules , function (obj)
18288 Roo.XComponent.event.fireEvent('beforebuild', obj);
18290 var opar = obj.parent;
18292 obj.parent = this.toObject(opar);
18294 Roo.debug && Roo.log("parent:toObject failed: " + e.toString());
18299 Roo.debug && Roo.log("GOT top level module");
18300 Roo.debug && Roo.log(obj);
18301 obj.modules = new Roo.util.MixedCollection(false,
18302 function(o) { return o.order + '' }
18304 this.topModule = obj;
18307 // parent is a string (usually a dom element name..)
18308 if (typeof(obj.parent) == 'string') {
18309 this.elmodules.push(obj);
18312 if (obj.parent.constructor != Roo.XComponent) {
18313 Roo.debug && Roo.log("Warning : Object Parent is not instance of XComponent:" + obj.name)
18315 if (!obj.parent.modules) {
18316 obj.parent.modules = new Roo.util.MixedCollection(false,
18317 function(o) { return o.order + '' }
18320 if (obj.parent.disabled) {
18321 obj.disabled = true;
18323 obj.parent.modules.add(obj);
18328 * make a list of modules to build.
18329 * @return {Array} list of modules.
18332 buildOrder : function()
18335 var cmp = function(a,b) {
18336 return String(a).toUpperCase() > String(b).toUpperCase() ? 1 : -1;
18338 if ((!this.topModule || !this.topModule.modules) && !this.elmodules.length) {
18339 throw "No top level modules to build";
18342 // make a flat list in order of modules to build.
18343 var mods = this.topModule ? [ this.topModule ] : [];
18346 // elmodules (is a list of DOM based modules )
18347 Roo.each(this.elmodules, function(e) {
18349 if (!this.topModule &&
18350 typeof(e.parent) == 'string' &&
18351 e.parent.substring(0,1) == '#' &&
18352 Roo.get(e.parent.substr(1))
18355 _this.topModule = e;
18361 // add modules to their parents..
18362 var addMod = function(m) {
18363 Roo.debug && Roo.log("build Order: add: " + m.name);
18366 if (m.modules && !m.disabled) {
18367 Roo.debug && Roo.log("build Order: " + m.modules.length + " child modules");
18368 m.modules.keySort('ASC', cmp );
18369 Roo.debug && Roo.log("build Order: " + m.modules.length + " child modules (after sort)");
18371 m.modules.each(addMod);
18373 Roo.debug && Roo.log("build Order: no child modules");
18375 // not sure if this is used any more..
18377 m.finalize.name = m.name + " (clean up) ";
18378 mods.push(m.finalize);
18382 if (this.topModule && this.topModule.modules) {
18383 this.topModule.modules.keySort('ASC', cmp );
18384 this.topModule.modules.each(addMod);
18390 * Build the registered modules.
18391 * @param {Object} parent element.
18392 * @param {Function} optional method to call after module has been added.
18396 build : function(opts)
18399 if (typeof(opts) != 'undefined') {
18400 Roo.apply(this,opts);
18404 var mods = this.buildOrder();
18406 //this.allmods = mods;
18407 //Roo.debug && Roo.log(mods);
18409 if (!mods.length) { // should not happen
18410 throw "NO modules!!!";
18414 var msg = "Building Interface...";
18415 // flash it up as modal - so we store the mask!?
18416 if (!this.hideProgress && Roo.MessageBox) {
18417 Roo.MessageBox.show({ title: 'loading' });
18418 Roo.MessageBox.show({
18419 title: "Please wait...",
18429 var total = mods.length;
18432 var progressRun = function() {
18433 if (!mods.length) {
18434 Roo.debug && Roo.log('hide?');
18435 if (!this.hideProgress && Roo.MessageBox) {
18436 Roo.MessageBox.hide();
18438 Roo.XComponent.build_from_html = false; // reset, so dialogs will be build from javascript
18440 Roo.XComponent.event.fireEvent('buildcomplete', _this.topModule);
18446 var m = mods.shift();
18449 Roo.debug && Roo.log(m);
18450 // not sure if this is supported any more.. - modules that are are just function
18451 if (typeof(m) == 'function') {
18453 return progressRun.defer(10, _this);
18457 msg = "Building Interface " + (total - mods.length) +
18459 (m.name ? (' - ' + m.name) : '');
18460 Roo.debug && Roo.log(msg);
18461 if (!_this.hideProgress && Roo.MessageBox) {
18462 Roo.MessageBox.updateProgress( (total - mods.length)/total, msg );
18466 // is the module disabled?
18467 var disabled = (typeof(m.disabled) == 'function') ?
18468 m.disabled.call(m.module.disabled) : m.disabled;
18472 return progressRun(); // we do not update the display!
18480 // it's 10 on top level, and 1 on others??? why...
18481 return progressRun.defer(10, _this);
18484 progressRun.defer(1, _this);
18490 * Overlay a set of modified strings onto a component
18491 * This is dependant on our builder exporting the strings and 'named strings' elements.
18493 * @param {Object} element to overlay on - eg. Pman.Dialog.Login
18494 * @param {Object} associative array of 'named' string and it's new value.
18497 overlayStrings : function( component, strings )
18499 if (typeof(component['_named_strings']) == 'undefined') {
18500 throw "ERROR: component does not have _named_strings";
18502 for ( var k in strings ) {
18503 var md = typeof(component['_named_strings'][k]) == 'undefined' ? false : component['_named_strings'][k];
18504 if (md !== false) {
18505 component['_strings'][md] = strings[k];
18507 Roo.log('could not find named string: ' + k + ' in');
18508 Roo.log(component);
18523 * wrapper for event.on - aliased later..
18524 * Typically use to register a event handler for register:
18526 * eg. Roo.XComponent.on('register', function(comp) { comp.disable = true } );
18535 Roo.XComponent.event = new Roo.util.Observable({
18539 * Fires when an Component is registered,
18540 * set the disable property on the Component to stop registration.
18541 * @param {Roo.XComponent} c the component being registerd.
18546 * @event beforebuild
18547 * Fires before each Component is built
18548 * can be used to apply permissions.
18549 * @param {Roo.XComponent} c the component being registerd.
18552 'beforebuild' : true,
18554 * @event buildcomplete
18555 * Fires on the top level element when all elements have been built
18556 * @param {Roo.XComponent} the top level component.
18558 'buildcomplete' : true
18563 Roo.XComponent.on = Roo.XComponent.event.on.createDelegate(Roo.XComponent.event);
18566 * marked - a markdown parser
18567 * Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed)
18568 * https://github.com/chjj/marked
18574 * Roo.Markdown - is a very crude wrapper around marked..
18578 * alert( Roo.Markdown.toHtml("Markdown *rocks*.") );
18580 * Note: move the sample code to the bottom of this
18581 * file before uncommenting it.
18586 Roo.Markdown.toHtml = function(text) {
18588 var c = new Roo.Markdown.marked.setOptions({
18589 renderer: new Roo.Markdown.marked.Renderer(),
18600 text = text.replace(/\\\n/g,' ');
18601 return Roo.Markdown.marked(text);
18606 // Wraps all "globals" so that the only thing
18607 // exposed is makeHtml().
18613 * eval:var:unescape
18621 var escape = function (html, encode) {
18623 .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&')
18624 .replace(/</g, '<')
18625 .replace(/>/g, '>')
18626 .replace(/"/g, '"')
18627 .replace(/'/g, ''');
18630 var unescape = function (html) {
18631 // explicitly match decimal, hex, and named HTML entities
18632 return html.replace(/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/g, function(_, n) {
18633 n = n.toLowerCase();
18634 if (n === 'colon') { return ':'; }
18635 if (n.charAt(0) === '#') {
18636 return n.charAt(1) === 'x'
18637 ? String.fromCharCode(parseInt(n.substring(2), 16))
18638 : String.fromCharCode(+n.substring(1));
18644 var replace = function (regex, opt) {
18645 regex = regex.source;
18647 return function self(name, val) {
18648 if (!name) { return new RegExp(regex, opt); }
18649 val = val.source || val;
18650 val = val.replace(/(^|[^\[])\^/g, '$1');
18651 regex = regex.replace(name, val);
18660 var noop = function () {}
18666 var merge = function (obj) {
18671 for (; i < arguments.length; i++) {
18672 target = arguments[i];
18673 for (key in target) {
18674 if (Object.prototype.hasOwnProperty.call(target, key)) {
18675 obj[key] = target[key];
18685 * Block-Level Grammar
18693 code: /^( {4}[^\n]+\n*)+/,
18695 hr: /^( *[-*_]){3,} *(?:\n+|$)/,
18696 heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,
18698 lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,
18699 blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/,
18700 list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,
18701 html: /^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/,
18702 def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,
18704 paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,
18708 block.bullet = /(?:[*+-]|\d+\.)/;
18709 block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/;
18710 block.item = replace(block.item, 'gm')
18711 (/bull/g, block.bullet)
18714 block.list = replace(block.list)
18715 (/bull/g, block.bullet)
18716 ('hr', '\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))')
18717 ('def', '\\n+(?=' + block.def.source + ')')
18720 block.blockquote = replace(block.blockquote)
18724 block._tag = '(?!(?:'
18725 + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code'
18726 + '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo'
18727 + '|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b';
18729 block.html = replace(block.html)
18730 ('comment', /<!--[\s\S]*?-->/)
18731 ('closed', /<(tag)[\s\S]+?<\/\1>/)
18732 ('closing', /<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)
18733 (/tag/g, block._tag)
18736 block.paragraph = replace(block.paragraph)
18738 ('heading', block.heading)
18739 ('lheading', block.lheading)
18740 ('blockquote', block.blockquote)
18741 ('tag', '<' + block._tag)
18746 * Normal Block Grammar
18749 block.normal = merge({}, block);
18752 * GFM Block Grammar
18755 block.gfm = merge({}, block.normal, {
18756 fences: /^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/,
18758 heading: /^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/
18761 block.gfm.paragraph = replace(block.paragraph)
18763 + block.gfm.fences.source.replace('\\1', '\\2') + '|'
18764 + block.list.source.replace('\\1', '\\3') + '|')
18768 * GFM + Tables Block Grammar
18771 block.tables = merge({}, block.gfm, {
18772 nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,
18773 table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/
18780 var Lexer = function (options) {
18782 this.tokens.links = {};
18783 this.options = options || marked.defaults;
18784 this.rules = block.normal;
18786 if (this.options.gfm) {
18787 if (this.options.tables) {
18788 this.rules = block.tables;
18790 this.rules = block.gfm;
18796 * Expose Block Rules
18799 Lexer.rules = block;
18802 * Static Lex Method
18805 Lexer.lex = function(src, options) {
18806 var lexer = new Lexer(options);
18807 return lexer.lex(src);
18814 Lexer.prototype.lex = function(src) {
18816 .replace(/\r\n|\r/g, '\n')
18817 .replace(/\t/g, ' ')
18818 .replace(/\u00a0/g, ' ')
18819 .replace(/\u2424/g, '\n');
18821 return this.token(src, true);
18828 Lexer.prototype.token = function(src, top, bq) {
18829 var src = src.replace(/^ +$/gm, '')
18842 if (cap = this.rules.newline.exec(src)) {
18843 src = src.substring(cap[0].length);
18844 if (cap[0].length > 1) {
18852 if (cap = this.rules.code.exec(src)) {
18853 src = src.substring(cap[0].length);
18854 cap = cap[0].replace(/^ {4}/gm, '');
18857 text: !this.options.pedantic
18858 ? cap.replace(/\n+$/, '')
18865 if (cap = this.rules.fences.exec(src)) {
18866 src = src.substring(cap[0].length);
18876 if (cap = this.rules.heading.exec(src)) {
18877 src = src.substring(cap[0].length);
18880 depth: cap[1].length,
18886 // table no leading pipe (gfm)
18887 if (top && (cap = this.rules.nptable.exec(src))) {
18888 src = src.substring(cap[0].length);
18892 header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
18893 align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
18894 cells: cap[3].replace(/\n$/, '').split('\n')
18897 for (i = 0; i < item.align.length; i++) {
18898 if (/^ *-+: *$/.test(item.align[i])) {
18899 item.align[i] = 'right';
18900 } else if (/^ *:-+: *$/.test(item.align[i])) {
18901 item.align[i] = 'center';
18902 } else if (/^ *:-+ *$/.test(item.align[i])) {
18903 item.align[i] = 'left';
18905 item.align[i] = null;
18909 for (i = 0; i < item.cells.length; i++) {
18910 item.cells[i] = item.cells[i].split(/ *\| */);
18913 this.tokens.push(item);
18919 if (cap = this.rules.lheading.exec(src)) {
18920 src = src.substring(cap[0].length);
18923 depth: cap[2] === '=' ? 1 : 2,
18930 if (cap = this.rules.hr.exec(src)) {
18931 src = src.substring(cap[0].length);
18939 if (cap = this.rules.blockquote.exec(src)) {
18940 src = src.substring(cap[0].length);
18943 type: 'blockquote_start'
18946 cap = cap[0].replace(/^ *> ?/gm, '');
18948 // Pass `top` to keep the current
18949 // "toplevel" state. This is exactly
18950 // how markdown.pl works.
18951 this.token(cap, top, true);
18954 type: 'blockquote_end'
18961 if (cap = this.rules.list.exec(src)) {
18962 src = src.substring(cap[0].length);
18966 type: 'list_start',
18967 ordered: bull.length > 1
18970 // Get each top-level item.
18971 cap = cap[0].match(this.rules.item);
18977 for (; i < l; i++) {
18980 // Remove the list item's bullet
18981 // so it is seen as the next token.
18982 space = item.length;
18983 item = item.replace(/^ *([*+-]|\d+\.) +/, '');
18985 // Outdent whatever the
18986 // list item contains. Hacky.
18987 if (~item.indexOf('\n ')) {
18988 space -= item.length;
18989 item = !this.options.pedantic
18990 ? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '')
18991 : item.replace(/^ {1,4}/gm, '');
18994 // Determine whether the next list item belongs here.
18995 // Backpedal if it does not belong in this list.
18996 if (this.options.smartLists && i !== l - 1) {
18997 b = block.bullet.exec(cap[i + 1])[0];
18998 if (bull !== b && !(bull.length > 1 && b.length > 1)) {
18999 src = cap.slice(i + 1).join('\n') + src;
19004 // Determine whether item is loose or not.
19005 // Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/
19006 // for discount behavior.
19007 loose = next || /\n\n(?!\s*$)/.test(item);
19009 next = item.charAt(item.length - 1) === '\n';
19010 if (!loose) { loose = next; }
19015 ? 'loose_item_start'
19016 : 'list_item_start'
19020 this.token(item, false, bq);
19023 type: 'list_item_end'
19035 if (cap = this.rules.html.exec(src)) {
19036 src = src.substring(cap[0].length);
19038 type: this.options.sanitize
19041 pre: !this.options.sanitizer
19042 && (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'),
19049 if ((!bq && top) && (cap = this.rules.def.exec(src))) {
19050 src = src.substring(cap[0].length);
19051 this.tokens.links[cap[1].toLowerCase()] = {
19059 if (top && (cap = this.rules.table.exec(src))) {
19060 src = src.substring(cap[0].length);
19064 header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
19065 align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
19066 cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n')
19069 for (i = 0; i < item.align.length; i++) {
19070 if (/^ *-+: *$/.test(item.align[i])) {
19071 item.align[i] = 'right';
19072 } else if (/^ *:-+: *$/.test(item.align[i])) {
19073 item.align[i] = 'center';
19074 } else if (/^ *:-+ *$/.test(item.align[i])) {
19075 item.align[i] = 'left';
19077 item.align[i] = null;
19081 for (i = 0; i < item.cells.length; i++) {
19082 item.cells[i] = item.cells[i]
19083 .replace(/^ *\| *| *\| *$/g, '')
19087 this.tokens.push(item);
19092 // top-level paragraph
19093 if (top && (cap = this.rules.paragraph.exec(src))) {
19094 src = src.substring(cap[0].length);
19097 text: cap[1].charAt(cap[1].length - 1) === '\n'
19098 ? cap[1].slice(0, -1)
19105 if (cap = this.rules.text.exec(src)) {
19106 // Top-level should never reach here.
19107 src = src.substring(cap[0].length);
19117 Error('Infinite loop on byte: ' + src.charCodeAt(0));
19121 return this.tokens;
19125 * Inline-Level Grammar
19129 escape: /^\\([\\`*{}\[\]()#+\-.!_>])/,
19130 autolink: /^<([^ >]+(@|:\/)[^ >]+)>/,
19132 tag: /^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,
19133 link: /^!?\[(inside)\]\(href\)/,
19134 reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/,
19135 nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,
19136 strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,
19137 em: /^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,
19138 code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,
19139 br: /^ {2,}\n(?!\s*$)/,
19141 text: /^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/
19144 inline._inside = /(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/;
19145 inline._href = /\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/;
19147 inline.link = replace(inline.link)
19148 ('inside', inline._inside)
19149 ('href', inline._href)
19152 inline.reflink = replace(inline.reflink)
19153 ('inside', inline._inside)
19157 * Normal Inline Grammar
19160 inline.normal = merge({}, inline);
19163 * Pedantic Inline Grammar
19166 inline.pedantic = merge({}, inline.normal, {
19167 strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
19168 em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/
19172 * GFM Inline Grammar
19175 inline.gfm = merge({}, inline.normal, {
19176 escape: replace(inline.escape)('])', '~|])')(),
19177 url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,
19178 del: /^~~(?=\S)([\s\S]*?\S)~~/,
19179 text: replace(inline.text)
19181 ('|', '|https?://|')
19186 * GFM + Line Breaks Inline Grammar
19189 inline.breaks = merge({}, inline.gfm, {
19190 br: replace(inline.br)('{2,}', '*')(),
19191 text: replace(inline.gfm.text)('{2,}', '*')()
19195 * Inline Lexer & Compiler
19198 var InlineLexer = function (links, options) {
19199 this.options = options || marked.defaults;
19200 this.links = links;
19201 this.rules = inline.normal;
19202 this.renderer = this.options.renderer || new Renderer;
19203 this.renderer.options = this.options;
19207 Error('Tokens array requires a `links` property.');
19210 if (this.options.gfm) {
19211 if (this.options.breaks) {
19212 this.rules = inline.breaks;
19214 this.rules = inline.gfm;
19216 } else if (this.options.pedantic) {
19217 this.rules = inline.pedantic;
19222 * Expose Inline Rules
19225 InlineLexer.rules = inline;
19228 * Static Lexing/Compiling Method
19231 InlineLexer.output = function(src, links, options) {
19232 var inline = new InlineLexer(links, options);
19233 return inline.output(src);
19240 InlineLexer.prototype.output = function(src) {
19249 if (cap = this.rules.escape.exec(src)) {
19250 src = src.substring(cap[0].length);
19256 if (cap = this.rules.autolink.exec(src)) {
19257 src = src.substring(cap[0].length);
19258 if (cap[2] === '@') {
19259 text = cap[1].charAt(6) === ':'
19260 ? this.mangle(cap[1].substring(7))
19261 : this.mangle(cap[1]);
19262 href = this.mangle('mailto:') + text;
19264 text = escape(cap[1]);
19267 out += this.renderer.link(href, null, text);
19272 if (!this.inLink && (cap = this.rules.url.exec(src))) {
19273 src = src.substring(cap[0].length);
19274 text = escape(cap[1]);
19276 out += this.renderer.link(href, null, text);
19281 if (cap = this.rules.tag.exec(src)) {
19282 if (!this.inLink && /^<a /i.test(cap[0])) {
19283 this.inLink = true;
19284 } else if (this.inLink && /^<\/a>/i.test(cap[0])) {
19285 this.inLink = false;
19287 src = src.substring(cap[0].length);
19288 out += this.options.sanitize
19289 ? this.options.sanitizer
19290 ? this.options.sanitizer(cap[0])
19297 if (cap = this.rules.link.exec(src)) {
19298 src = src.substring(cap[0].length);
19299 this.inLink = true;
19300 out += this.outputLink(cap, {
19304 this.inLink = false;
19309 if ((cap = this.rules.reflink.exec(src))
19310 || (cap = this.rules.nolink.exec(src))) {
19311 src = src.substring(cap[0].length);
19312 link = (cap[2] || cap[1]).replace(/\s+/g, ' ');
19313 link = this.links[link.toLowerCase()];
19314 if (!link || !link.href) {
19315 out += cap[0].charAt(0);
19316 src = cap[0].substring(1) + src;
19319 this.inLink = true;
19320 out += this.outputLink(cap, link);
19321 this.inLink = false;
19326 if (cap = this.rules.strong.exec(src)) {
19327 src = src.substring(cap[0].length);
19328 out += this.renderer.strong(this.output(cap[2] || cap[1]));
19333 if (cap = this.rules.em.exec(src)) {
19334 src = src.substring(cap[0].length);
19335 out += this.renderer.em(this.output(cap[2] || cap[1]));
19340 if (cap = this.rules.code.exec(src)) {
19341 src = src.substring(cap[0].length);
19342 out += this.renderer.codespan(escape(cap[2], true));
19347 if (cap = this.rules.br.exec(src)) {
19348 src = src.substring(cap[0].length);
19349 out += this.renderer.br();
19354 if (cap = this.rules.del.exec(src)) {
19355 src = src.substring(cap[0].length);
19356 out += this.renderer.del(this.output(cap[1]));
19361 if (cap = this.rules.text.exec(src)) {
19362 src = src.substring(cap[0].length);
19363 out += this.renderer.text(escape(this.smartypants(cap[0])));
19369 Error('Infinite loop on byte: ' + src.charCodeAt(0));
19380 InlineLexer.prototype.outputLink = function(cap, link) {
19381 var href = escape(link.href)
19382 , title = link.title ? escape(link.title) : null;
19384 return cap[0].charAt(0) !== '!'
19385 ? this.renderer.link(href, title, this.output(cap[1]))
19386 : this.renderer.image(href, title, escape(cap[1]));
19390 * Smartypants Transformations
19393 InlineLexer.prototype.smartypants = function(text) {
19394 if (!this.options.smartypants) { return text; }
19397 .replace(/---/g, '\u2014')
19399 .replace(/--/g, '\u2013')
19401 .replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018')
19402 // closing singles & apostrophes
19403 .replace(/'/g, '\u2019')
19405 .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c')
19407 .replace(/"/g, '\u201d')
19409 .replace(/\.{3}/g, '\u2026');
19416 InlineLexer.prototype.mangle = function(text) {
19417 if (!this.options.mangle) { return text; }
19423 for (; i < l; i++) {
19424 ch = text.charCodeAt(i);
19425 if (Math.random() > 0.5) {
19426 ch = 'x' + ch.toString(16);
19428 out += '&#' + ch + ';';
19439 * eval:var:Renderer
19442 var Renderer = function (options) {
19443 this.options = options || {};
19446 Renderer.prototype.code = function(code, lang, escaped) {
19447 if (this.options.highlight) {
19448 var out = this.options.highlight(code, lang);
19449 if (out != null && out !== code) {
19454 // hack!!! - it's already escapeD?
19459 return '<pre><code>'
19460 + (escaped ? code : escape(code, true))
19461 + '\n</code></pre>';
19464 return '<pre><code class="'
19465 + this.options.langPrefix
19466 + escape(lang, true)
19468 + (escaped ? code : escape(code, true))
19469 + '\n</code></pre>\n';
19472 Renderer.prototype.blockquote = function(quote) {
19473 return '<blockquote>\n' + quote + '</blockquote>\n';
19476 Renderer.prototype.html = function(html) {
19480 Renderer.prototype.heading = function(text, level, raw) {
19484 + this.options.headerPrefix
19485 + raw.toLowerCase().replace(/[^\w]+/g, '-')
19493 Renderer.prototype.hr = function() {
19494 return this.options.xhtml ? '<hr/>\n' : '<hr>\n';
19497 Renderer.prototype.list = function(body, ordered) {
19498 var type = ordered ? 'ol' : 'ul';
19499 return '<' + type + '>\n' + body + '</' + type + '>\n';
19502 Renderer.prototype.listitem = function(text) {
19503 return '<li>' + text + '</li>\n';
19506 Renderer.prototype.paragraph = function(text) {
19507 return '<p>' + text + '</p>\n';
19510 Renderer.prototype.table = function(header, body) {
19511 return '<table class="table table-striped">\n'
19521 Renderer.prototype.tablerow = function(content) {
19522 return '<tr>\n' + content + '</tr>\n';
19525 Renderer.prototype.tablecell = function(content, flags) {
19526 var type = flags.header ? 'th' : 'td';
19527 var tag = flags.align
19528 ? '<' + type + ' style="text-align:' + flags.align + '">'
19529 : '<' + type + '>';
19530 return tag + content + '</' + type + '>\n';
19533 // span level renderer
19534 Renderer.prototype.strong = function(text) {
19535 return '<strong>' + text + '</strong>';
19538 Renderer.prototype.em = function(text) {
19539 return '<em>' + text + '</em>';
19542 Renderer.prototype.codespan = function(text) {
19543 return '<code>' + text + '</code>';
19546 Renderer.prototype.br = function() {
19547 return this.options.xhtml ? '<br/>' : '<br>';
19550 Renderer.prototype.del = function(text) {
19551 return '<del>' + text + '</del>';
19554 Renderer.prototype.link = function(href, title, text) {
19555 if (this.options.sanitize) {
19557 var prot = decodeURIComponent(unescape(href))
19558 .replace(/[^\w:]/g, '')
19563 if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0) {
19567 var out = '<a href="' + href + '"';
19569 out += ' title="' + title + '"';
19571 out += '>' + text + '</a>';
19575 Renderer.prototype.image = function(href, title, text) {
19576 var out = '<img src="' + href + '" alt="' + text + '"';
19578 out += ' title="' + title + '"';
19580 out += this.options.xhtml ? '/>' : '>';
19584 Renderer.prototype.text = function(text) {
19589 * Parsing & Compiling
19595 var Parser= function (options) {
19598 this.options = options || marked.defaults;
19599 this.options.renderer = this.options.renderer || new Renderer;
19600 this.renderer = this.options.renderer;
19601 this.renderer.options = this.options;
19605 * Static Parse Method
19608 Parser.parse = function(src, options, renderer) {
19609 var parser = new Parser(options, renderer);
19610 return parser.parse(src);
19617 Parser.prototype.parse = function(src) {
19618 this.inline = new InlineLexer(src.links, this.options, this.renderer);
19619 this.tokens = src.reverse();
19622 while (this.next()) {
19633 Parser.prototype.next = function() {
19634 return this.token = this.tokens.pop();
19638 * Preview Next Token
19641 Parser.prototype.peek = function() {
19642 return this.tokens[this.tokens.length - 1] || 0;
19646 * Parse Text Tokens
19649 Parser.prototype.parseText = function() {
19650 var body = this.token.text;
19652 while (this.peek().type === 'text') {
19653 body += '\n' + this.next().text;
19656 return this.inline.output(body);
19660 * Parse Current Token
19663 Parser.prototype.tok = function() {
19664 switch (this.token.type) {
19669 return this.renderer.hr();
19672 return this.renderer.heading(
19673 this.inline.output(this.token.text),
19678 return this.renderer.code(this.token.text,
19680 this.token.escaped);
19693 for (i = 0; i < this.token.header.length; i++) {
19694 flags = { header: true, align: this.token.align[i] };
19695 cell += this.renderer.tablecell(
19696 this.inline.output(this.token.header[i]),
19697 { header: true, align: this.token.align[i] }
19700 header += this.renderer.tablerow(cell);
19702 for (i = 0; i < this.token.cells.length; i++) {
19703 row = this.token.cells[i];
19706 for (j = 0; j < row.length; j++) {
19707 cell += this.renderer.tablecell(
19708 this.inline.output(row[j]),
19709 { header: false, align: this.token.align[j] }
19713 body += this.renderer.tablerow(cell);
19715 return this.renderer.table(header, body);
19717 case 'blockquote_start': {
19720 while (this.next().type !== 'blockquote_end') {
19721 body += this.tok();
19724 return this.renderer.blockquote(body);
19726 case 'list_start': {
19728 , ordered = this.token.ordered;
19730 while (this.next().type !== 'list_end') {
19731 body += this.tok();
19734 return this.renderer.list(body, ordered);
19736 case 'list_item_start': {
19739 while (this.next().type !== 'list_item_end') {
19740 body += this.token.type === 'text'
19745 return this.renderer.listitem(body);
19747 case 'loose_item_start': {
19750 while (this.next().type !== 'list_item_end') {
19751 body += this.tok();
19754 return this.renderer.listitem(body);
19757 var html = !this.token.pre && !this.options.pedantic
19758 ? this.inline.output(this.token.text)
19760 return this.renderer.html(html);
19762 case 'paragraph': {
19763 return this.renderer.paragraph(this.inline.output(this.token.text));
19766 return this.renderer.paragraph(this.parseText());
19778 var marked = function (src, opt, callback) {
19779 if (callback || typeof opt === 'function') {
19785 opt = merge({}, marked.defaults, opt || {});
19787 var highlight = opt.highlight
19793 tokens = Lexer.lex(src, opt)
19795 return callback(e);
19798 pending = tokens.length;
19802 var done = function(err) {
19804 opt.highlight = highlight;
19805 return callback(err);
19811 out = Parser.parse(tokens, opt);
19816 opt.highlight = highlight;
19820 : callback(null, out);
19823 if (!highlight || highlight.length < 3) {
19827 delete opt.highlight;
19829 if (!pending) { return done(); }
19831 for (; i < tokens.length; i++) {
19833 if (token.type !== 'code') {
19834 return --pending || done();
19836 return highlight(token.text, token.lang, function(err, code) {
19837 if (err) { return done(err); }
19838 if (code == null || code === token.text) {
19839 return --pending || done();
19842 token.escaped = true;
19843 --pending || done();
19851 if (opt) { opt = merge({}, marked.defaults, opt); }
19852 return Parser.parse(Lexer.lex(src, opt), opt);
19854 e.message += '\nPlease report this to https://github.com/chjj/marked.';
19855 if ((opt || marked.defaults).silent) {
19856 return '<p>An error occured:</p><pre>'
19857 + escape(e.message + '', true)
19869 marked.setOptions = function(opt) {
19870 merge(marked.defaults, opt);
19874 marked.defaults = {
19885 langPrefix: 'lang-',
19886 smartypants: false,
19888 renderer: new Renderer,
19896 marked.Parser = Parser;
19897 marked.parser = Parser.parse;
19899 marked.Renderer = Renderer;
19901 marked.Lexer = Lexer;
19902 marked.lexer = Lexer.lex;
19904 marked.InlineLexer = InlineLexer;
19905 marked.inlineLexer = InlineLexer.output;
19907 marked.parse = marked;
19909 Roo.Markdown.marked = marked;
19913 * Ext JS Library 1.1.1
19914 * Copyright(c) 2006-2007, Ext JS, LLC.
19916 * Originally Released Under LGPL - original licence link has changed is not relivant.
19919 * <script type="text/javascript">
19925 * These classes are derivatives of the similarly named classes in the YUI Library.
19926 * The original license:
19927 * Copyright (c) 2006, Yahoo! Inc. All rights reserved.
19928 * Code licensed under the BSD License:
19929 * http://developer.yahoo.net/yui/license.txt
19934 var Event=Roo.EventManager;
19935 var Dom=Roo.lib.Dom;
19938 * @class Roo.dd.DragDrop
19939 * @extends Roo.util.Observable
19940 * Defines the interface and base operation of items that that can be
19941 * dragged or can be drop targets. It was designed to be extended, overriding
19942 * the event handlers for startDrag, onDrag, onDragOver and onDragOut.
19943 * Up to three html elements can be associated with a DragDrop instance:
19945 * <li>linked element: the element that is passed into the constructor.
19946 * This is the element which defines the boundaries for interaction with
19947 * other DragDrop objects.</li>
19948 * <li>handle element(s): The drag operation only occurs if the element that
19949 * was clicked matches a handle element. By default this is the linked
19950 * element, but there are times that you will want only a portion of the
19951 * linked element to initiate the drag operation, and the setHandleElId()
19952 * method provides a way to define this.</li>
19953 * <li>drag element: this represents the element that would be moved along
19954 * with the cursor during a drag operation. By default, this is the linked
19955 * element itself as in {@link Roo.dd.DD}. setDragElId() lets you define
19956 * a separate element that would be moved, as in {@link Roo.dd.DDProxy}.
19959 * This class should not be instantiated until the onload event to ensure that
19960 * the associated elements are available.
19961 * The following would define a DragDrop obj that would interact with any
19962 * other DragDrop obj in the "group1" group:
19964 * dd = new Roo.dd.DragDrop("div1", "group1");
19966 * Since none of the event handlers have been implemented, nothing would
19967 * actually happen if you were to run the code above. Normally you would
19968 * override this class or one of the default implementations, but you can
19969 * also override the methods you want on an instance of the class...
19971 * dd.onDragDrop = function(e, id) {
19972 * alert("dd was dropped on " + id);
19976 * @param {String} id of the element that is linked to this instance
19977 * @param {String} sGroup the group of related DragDrop objects
19978 * @param {object} config an object containing configurable attributes
19979 * Valid properties for DragDrop:
19980 * padding, isTarget, maintainOffset, primaryButtonOnly
19982 Roo.dd.DragDrop = function(id, sGroup, config) {
19984 this.init(id, sGroup, config);
19989 Roo.extend(Roo.dd.DragDrop, Roo.util.Observable , {
19992 * The id of the element associated with this object. This is what we
19993 * refer to as the "linked element" because the size and position of
19994 * this element is used to determine when the drag and drop objects have
20002 * Configuration attributes passed into the constructor
20009 * The id of the element that will be dragged. By default this is same
20010 * as the linked element , but could be changed to another element. Ex:
20012 * @property dragElId
20019 * the id of the element that initiates the drag operation. By default
20020 * this is the linked element, but could be changed to be a child of this
20021 * element. This lets us do things like only starting the drag when the
20022 * header element within the linked html element is clicked.
20023 * @property handleElId
20030 * An associative array of HTML tags that will be ignored if clicked.
20031 * @property invalidHandleTypes
20032 * @type {string: string}
20034 invalidHandleTypes: null,
20037 * An associative array of ids for elements that will be ignored if clicked
20038 * @property invalidHandleIds
20039 * @type {string: string}
20041 invalidHandleIds: null,
20044 * An indexted array of css class names for elements that will be ignored
20046 * @property invalidHandleClasses
20049 invalidHandleClasses: null,
20052 * The linked element's absolute X position at the time the drag was
20054 * @property startPageX
20061 * The linked element's absolute X position at the time the drag was
20063 * @property startPageY
20070 * The group defines a logical collection of DragDrop objects that are
20071 * related. Instances only get events when interacting with other
20072 * DragDrop object in the same group. This lets us define multiple
20073 * groups using a single DragDrop subclass if we want.
20075 * @type {string: string}
20080 * Individual drag/drop instances can be locked. This will prevent
20081 * onmousedown start drag.
20089 * Lock this instance
20092 lock: function() { this.locked = true; },
20095 * Unlock this instace
20098 unlock: function() { this.locked = false; },
20101 * By default, all insances can be a drop target. This can be disabled by
20102 * setting isTarget to false.
20109 * The padding configured for this drag and drop object for calculating
20110 * the drop zone intersection with this object.
20117 * Cached reference to the linked element
20118 * @property _domRef
20124 * Internal typeof flag
20125 * @property __ygDragDrop
20128 __ygDragDrop: true,
20131 * Set to true when horizontal contraints are applied
20132 * @property constrainX
20139 * Set to true when vertical contraints are applied
20140 * @property constrainY
20147 * The left constraint
20155 * The right constraint
20163 * The up constraint
20172 * The down constraint
20180 * Maintain offsets when we resetconstraints. Set to true when you want
20181 * the position of the element relative to its parent to stay the same
20182 * when the page changes
20184 * @property maintainOffset
20187 maintainOffset: false,
20190 * Array of pixel locations the element will snap to if we specified a
20191 * horizontal graduation/interval. This array is generated automatically
20192 * when you define a tick interval.
20199 * Array of pixel locations the element will snap to if we specified a
20200 * vertical graduation/interval. This array is generated automatically
20201 * when you define a tick interval.
20208 * By default the drag and drop instance will only respond to the primary
20209 * button click (left button for a right-handed mouse). Set to true to
20210 * allow drag and drop to start with any mouse click that is propogated
20212 * @property primaryButtonOnly
20215 primaryButtonOnly: true,
20218 * The availabe property is false until the linked dom element is accessible.
20219 * @property available
20225 * By default, drags can only be initiated if the mousedown occurs in the
20226 * region the linked element is. This is done in part to work around a
20227 * bug in some browsers that mis-report the mousedown if the previous
20228 * mouseup happened outside of the window. This property is set to true
20229 * if outer handles are defined.
20231 * @property hasOuterHandles
20235 hasOuterHandles: false,
20238 * Code that executes immediately before the startDrag event
20239 * @method b4StartDrag
20242 b4StartDrag: function(x, y) { },
20245 * Abstract method called after a drag/drop object is clicked
20246 * and the drag or mousedown time thresholds have beeen met.
20247 * @method startDrag
20248 * @param {int} X click location
20249 * @param {int} Y click location
20251 startDrag: function(x, y) { /* override this */ },
20254 * Code that executes immediately before the onDrag event
20258 b4Drag: function(e) { },
20261 * Abstract method called during the onMouseMove event while dragging an
20264 * @param {Event} e the mousemove event
20266 onDrag: function(e) { /* override this */ },
20269 * Abstract method called when this element fist begins hovering over
20270 * another DragDrop obj
20271 * @method onDragEnter
20272 * @param {Event} e the mousemove event
20273 * @param {String|DragDrop[]} id In POINT mode, the element
20274 * id this is hovering over. In INTERSECT mode, an array of one or more
20275 * dragdrop items being hovered over.
20277 onDragEnter: function(e, id) { /* override this */ },
20280 * Code that executes immediately before the onDragOver event
20281 * @method b4DragOver
20284 b4DragOver: function(e) { },
20287 * Abstract method called when this element is hovering over another
20289 * @method onDragOver
20290 * @param {Event} e the mousemove event
20291 * @param {String|DragDrop[]} id In POINT mode, the element
20292 * id this is hovering over. In INTERSECT mode, an array of dd items
20293 * being hovered over.
20295 onDragOver: function(e, id) { /* override this */ },
20298 * Code that executes immediately before the onDragOut event
20299 * @method b4DragOut
20302 b4DragOut: function(e) { },
20305 * Abstract method called when we are no longer hovering over an element
20306 * @method onDragOut
20307 * @param {Event} e the mousemove event
20308 * @param {String|DragDrop[]} id In POINT mode, the element
20309 * id this was hovering over. In INTERSECT mode, an array of dd items
20310 * that the mouse is no longer over.
20312 onDragOut: function(e, id) { /* override this */ },
20315 * Code that executes immediately before the onDragDrop event
20316 * @method b4DragDrop
20319 b4DragDrop: function(e) { },
20322 * Abstract method called when this item is dropped on another DragDrop
20324 * @method onDragDrop
20325 * @param {Event} e the mouseup event
20326 * @param {String|DragDrop[]} id In POINT mode, the element
20327 * id this was dropped on. In INTERSECT mode, an array of dd items this
20330 onDragDrop: function(e, id) { /* override this */ },
20333 * Abstract method called when this item is dropped on an area with no
20335 * @method onInvalidDrop
20336 * @param {Event} e the mouseup event
20338 onInvalidDrop: function(e) { /* override this */ },
20341 * Code that executes immediately before the endDrag event
20342 * @method b4EndDrag
20345 b4EndDrag: function(e) { },
20348 * Fired when we are done dragging the object
20350 * @param {Event} e the mouseup event
20352 endDrag: function(e) { /* override this */ },
20355 * Code executed immediately before the onMouseDown event
20356 * @method b4MouseDown
20357 * @param {Event} e the mousedown event
20360 b4MouseDown: function(e) { },
20363 * Event handler that fires when a drag/drop obj gets a mousedown
20364 * @method onMouseDown
20365 * @param {Event} e the mousedown event
20367 onMouseDown: function(e) { /* override this */ },
20370 * Event handler that fires when a drag/drop obj gets a mouseup
20371 * @method onMouseUp
20372 * @param {Event} e the mouseup event
20374 onMouseUp: function(e) { /* override this */ },
20377 * Override the onAvailable method to do what is needed after the initial
20378 * position was determined.
20379 * @method onAvailable
20381 onAvailable: function () {
20385 * Provides default constraint padding to "constrainTo" elements (defaults to {left: 0, right:0, top:0, bottom:0}).
20388 defaultPadding : {left:0, right:0, top:0, bottom:0},
20391 * Initializes the drag drop object's constraints to restrict movement to a certain element.
20395 var dd = new Roo.dd.DDProxy("dragDiv1", "proxytest",
20396 { dragElId: "existingProxyDiv" });
20397 dd.startDrag = function(){
20398 this.constrainTo("parent-id");
20401 * Or you can initalize it using the {@link Roo.Element} object:
20403 Roo.get("dragDiv1").initDDProxy("proxytest", {dragElId: "existingProxyDiv"}, {
20404 startDrag : function(){
20405 this.constrainTo("parent-id");
20409 * @param {String/HTMLElement/Element} constrainTo The element to constrain to.
20410 * @param {Object/Number} pad (optional) Pad provides a way to specify "padding" of the constraints,
20411 * and can be either a number for symmetrical padding (4 would be equal to {left:4, right:4, top:4, bottom:4}) or
20412 * an object containing the sides to pad. For example: {right:10, bottom:10}
20413 * @param {Boolean} inContent (optional) Constrain the draggable in the content box of the element (inside padding and borders)
20415 constrainTo : function(constrainTo, pad, inContent){
20416 if(typeof pad == "number"){
20417 pad = {left: pad, right:pad, top:pad, bottom:pad};
20419 pad = pad || this.defaultPadding;
20420 var b = Roo.get(this.getEl()).getBox();
20421 var ce = Roo.get(constrainTo);
20422 var s = ce.getScroll();
20423 var c, cd = ce.dom;
20424 if(cd == document.body){
20425 c = { x: s.left, y: s.top, width: Roo.lib.Dom.getViewWidth(), height: Roo.lib.Dom.getViewHeight()};
20428 c = {x : xy[0]+s.left, y: xy[1]+s.top, width: cd.clientWidth, height: cd.clientHeight};
20432 var topSpace = b.y - c.y;
20433 var leftSpace = b.x - c.x;
20435 this.resetConstraints();
20436 this.setXConstraint(leftSpace - (pad.left||0), // left
20437 c.width - leftSpace - b.width - (pad.right||0) //right
20439 this.setYConstraint(topSpace - (pad.top||0), //top
20440 c.height - topSpace - b.height - (pad.bottom||0) //bottom
20445 * Returns a reference to the linked element
20447 * @return {HTMLElement} the html element
20449 getEl: function() {
20450 if (!this._domRef) {
20451 this._domRef = Roo.getDom(this.id);
20454 return this._domRef;
20458 * Returns a reference to the actual element to drag. By default this is
20459 * the same as the html element, but it can be assigned to another
20460 * element. An example of this can be found in Roo.dd.DDProxy
20461 * @method getDragEl
20462 * @return {HTMLElement} the html element
20464 getDragEl: function() {
20465 return Roo.getDom(this.dragElId);
20469 * Sets up the DragDrop object. Must be called in the constructor of any
20470 * Roo.dd.DragDrop subclass
20472 * @param id the id of the linked element
20473 * @param {String} sGroup the group of related items
20474 * @param {object} config configuration attributes
20476 init: function(id, sGroup, config) {
20477 this.initTarget(id, sGroup, config);
20478 if (!Roo.isTouch) {
20479 Event.on(this.id, "mousedown", this.handleMouseDown, this);
20481 Event.on(this.id, "touchstart", this.handleMouseDown, this);
20482 // Event.on(this.id, "selectstart", Event.preventDefault);
20486 * Initializes Targeting functionality only... the object does not
20487 * get a mousedown handler.
20488 * @method initTarget
20489 * @param id the id of the linked element
20490 * @param {String} sGroup the group of related items
20491 * @param {object} config configuration attributes
20493 initTarget: function(id, sGroup, config) {
20495 // configuration attributes
20496 this.config = config || {};
20498 // create a local reference to the drag and drop manager
20499 this.DDM = Roo.dd.DDM;
20500 // initialize the groups array
20503 // assume that we have an element reference instead of an id if the
20504 // parameter is not a string
20505 if (typeof id !== "string") {
20512 // add to an interaction group
20513 this.addToGroup((sGroup) ? sGroup : "default");
20515 // We don't want to register this as the handle with the manager
20516 // so we just set the id rather than calling the setter.
20517 this.handleElId = id;
20519 // the linked element is the element that gets dragged by default
20520 this.setDragElId(id);
20522 // by default, clicked anchors will not start drag operations.
20523 this.invalidHandleTypes = { A: "A" };
20524 this.invalidHandleIds = {};
20525 this.invalidHandleClasses = [];
20527 this.applyConfig();
20529 this.handleOnAvailable();
20533 * Applies the configuration parameters that were passed into the constructor.
20534 * This is supposed to happen at each level through the inheritance chain. So
20535 * a DDProxy implentation will execute apply config on DDProxy, DD, and
20536 * DragDrop in order to get all of the parameters that are available in
20538 * @method applyConfig
20540 applyConfig: function() {
20542 // configurable properties:
20543 // padding, isTarget, maintainOffset, primaryButtonOnly
20544 this.padding = this.config.padding || [0, 0, 0, 0];
20545 this.isTarget = (this.config.isTarget !== false);
20546 this.maintainOffset = (this.config.maintainOffset);
20547 this.primaryButtonOnly = (this.config.primaryButtonOnly !== false);
20552 * Executed when the linked element is available
20553 * @method handleOnAvailable
20556 handleOnAvailable: function() {
20557 this.available = true;
20558 this.resetConstraints();
20559 this.onAvailable();
20563 * Configures the padding for the target zone in px. Effectively expands
20564 * (or reduces) the virtual object size for targeting calculations.
20565 * Supports css-style shorthand; if only one parameter is passed, all sides
20566 * will have that padding, and if only two are passed, the top and bottom
20567 * will have the first param, the left and right the second.
20568 * @method setPadding
20569 * @param {int} iTop Top pad
20570 * @param {int} iRight Right pad
20571 * @param {int} iBot Bot pad
20572 * @param {int} iLeft Left pad
20574 setPadding: function(iTop, iRight, iBot, iLeft) {
20575 // this.padding = [iLeft, iRight, iTop, iBot];
20576 if (!iRight && 0 !== iRight) {
20577 this.padding = [iTop, iTop, iTop, iTop];
20578 } else if (!iBot && 0 !== iBot) {
20579 this.padding = [iTop, iRight, iTop, iRight];
20581 this.padding = [iTop, iRight, iBot, iLeft];
20586 * Stores the initial placement of the linked element.
20587 * @method setInitialPosition
20588 * @param {int} diffX the X offset, default 0
20589 * @param {int} diffY the Y offset, default 0
20591 setInitPosition: function(diffX, diffY) {
20592 var el = this.getEl();
20594 if (!this.DDM.verifyEl(el)) {
20598 var dx = diffX || 0;
20599 var dy = diffY || 0;
20601 var p = Dom.getXY( el );
20603 this.initPageX = p[0] - dx;
20604 this.initPageY = p[1] - dy;
20606 this.lastPageX = p[0];
20607 this.lastPageY = p[1];
20610 this.setStartPosition(p);
20614 * Sets the start position of the element. This is set when the obj
20615 * is initialized, the reset when a drag is started.
20616 * @method setStartPosition
20617 * @param pos current position (from previous lookup)
20620 setStartPosition: function(pos) {
20621 var p = pos || Dom.getXY( this.getEl() );
20622 this.deltaSetXY = null;
20624 this.startPageX = p[0];
20625 this.startPageY = p[1];
20629 * Add this instance to a group of related drag/drop objects. All
20630 * instances belong to at least one group, and can belong to as many
20631 * groups as needed.
20632 * @method addToGroup
20633 * @param sGroup {string} the name of the group
20635 addToGroup: function(sGroup) {
20636 this.groups[sGroup] = true;
20637 this.DDM.regDragDrop(this, sGroup);
20641 * Remove's this instance from the supplied interaction group
20642 * @method removeFromGroup
20643 * @param {string} sGroup The group to drop
20645 removeFromGroup: function(sGroup) {
20646 if (this.groups[sGroup]) {
20647 delete this.groups[sGroup];
20650 this.DDM.removeDDFromGroup(this, sGroup);
20654 * Allows you to specify that an element other than the linked element
20655 * will be moved with the cursor during a drag
20656 * @method setDragElId
20657 * @param id {string} the id of the element that will be used to initiate the drag
20659 setDragElId: function(id) {
20660 this.dragElId = id;
20664 * Allows you to specify a child of the linked element that should be
20665 * used to initiate the drag operation. An example of this would be if
20666 * you have a content div with text and links. Clicking anywhere in the
20667 * content area would normally start the drag operation. Use this method
20668 * to specify that an element inside of the content div is the element
20669 * that starts the drag operation.
20670 * @method setHandleElId
20671 * @param id {string} the id of the element that will be used to
20672 * initiate the drag.
20674 setHandleElId: function(id) {
20675 if (typeof id !== "string") {
20678 this.handleElId = id;
20679 this.DDM.regHandle(this.id, id);
20683 * Allows you to set an element outside of the linked element as a drag
20685 * @method setOuterHandleElId
20686 * @param id the id of the element that will be used to initiate the drag
20688 setOuterHandleElId: function(id) {
20689 if (typeof id !== "string") {
20692 Event.on(id, "mousedown",
20693 this.handleMouseDown, this);
20694 this.setHandleElId(id);
20696 this.hasOuterHandles = true;
20700 * Remove all drag and drop hooks for this element
20703 unreg: function() {
20704 Event.un(this.id, "mousedown",
20705 this.handleMouseDown);
20706 Event.un(this.id, "touchstart",
20707 this.handleMouseDown);
20708 this._domRef = null;
20709 this.DDM._remove(this);
20712 destroy : function(){
20717 * Returns true if this instance is locked, or the drag drop mgr is locked
20718 * (meaning that all drag/drop is disabled on the page.)
20720 * @return {boolean} true if this obj or all drag/drop is locked, else
20723 isLocked: function() {
20724 return (this.DDM.isLocked() || this.locked);
20728 * Fired when this object is clicked
20729 * @method handleMouseDown
20731 * @param {Roo.dd.DragDrop} oDD the clicked dd object (this dd obj)
20734 handleMouseDown: function(e, oDD){
20736 if (!Roo.isTouch && this.primaryButtonOnly && e.button != 0) {
20737 //Roo.log('not touch/ button !=0');
20740 if (e.browserEvent.touches && e.browserEvent.touches.length != 1) {
20741 return; // double touch..
20745 if (this.isLocked()) {
20746 //Roo.log('locked');
20750 this.DDM.refreshCache(this.groups);
20751 // Roo.log([Roo.lib.Event.getPageX(e), Roo.lib.Event.getPageY(e)]);
20752 var pt = new Roo.lib.Point(Roo.lib.Event.getPageX(e), Roo.lib.Event.getPageY(e));
20753 if (!this.hasOuterHandles && !this.DDM.isOverTarget(pt, this) ) {
20754 //Roo.log('no outer handes or not over target');
20757 // Roo.log('check validator');
20758 if (this.clickValidator(e)) {
20759 // Roo.log('validate success');
20760 // set the initial element position
20761 this.setStartPosition();
20764 this.b4MouseDown(e);
20765 this.onMouseDown(e);
20767 this.DDM.handleMouseDown(e, this);
20769 this.DDM.stopEvent(e);
20777 clickValidator: function(e) {
20778 var target = e.getTarget();
20779 return ( this.isValidHandleChild(target) &&
20780 (this.id == this.handleElId ||
20781 this.DDM.handleWasClicked(target, this.id)) );
20785 * Allows you to specify a tag name that should not start a drag operation
20786 * when clicked. This is designed to facilitate embedding links within a
20787 * drag handle that do something other than start the drag.
20788 * @method addInvalidHandleType
20789 * @param {string} tagName the type of element to exclude
20791 addInvalidHandleType: function(tagName) {
20792 var type = tagName.toUpperCase();
20793 this.invalidHandleTypes[type] = type;
20797 * Lets you to specify an element id for a child of a drag handle
20798 * that should not initiate a drag
20799 * @method addInvalidHandleId
20800 * @param {string} id the element id of the element you wish to ignore
20802 addInvalidHandleId: function(id) {
20803 if (typeof id !== "string") {
20806 this.invalidHandleIds[id] = id;
20810 * Lets you specify a css class of elements that will not initiate a drag
20811 * @method addInvalidHandleClass
20812 * @param {string} cssClass the class of the elements you wish to ignore
20814 addInvalidHandleClass: function(cssClass) {
20815 this.invalidHandleClasses.push(cssClass);
20819 * Unsets an excluded tag name set by addInvalidHandleType
20820 * @method removeInvalidHandleType
20821 * @param {string} tagName the type of element to unexclude
20823 removeInvalidHandleType: function(tagName) {
20824 var type = tagName.toUpperCase();
20825 // this.invalidHandleTypes[type] = null;
20826 delete this.invalidHandleTypes[type];
20830 * Unsets an invalid handle id
20831 * @method removeInvalidHandleId
20832 * @param {string} id the id of the element to re-enable
20834 removeInvalidHandleId: function(id) {
20835 if (typeof id !== "string") {
20838 delete this.invalidHandleIds[id];
20842 * Unsets an invalid css class
20843 * @method removeInvalidHandleClass
20844 * @param {string} cssClass the class of the element(s) you wish to
20847 removeInvalidHandleClass: function(cssClass) {
20848 for (var i=0, len=this.invalidHandleClasses.length; i<len; ++i) {
20849 if (this.invalidHandleClasses[i] == cssClass) {
20850 delete this.invalidHandleClasses[i];
20856 * Checks the tag exclusion list to see if this click should be ignored
20857 * @method isValidHandleChild
20858 * @param {HTMLElement} node the HTMLElement to evaluate
20859 * @return {boolean} true if this is a valid tag type, false if not
20861 isValidHandleChild: function(node) {
20864 // var n = (node.nodeName == "#text") ? node.parentNode : node;
20867 nodeName = node.nodeName.toUpperCase();
20869 nodeName = node.nodeName;
20871 valid = valid && !this.invalidHandleTypes[nodeName];
20872 valid = valid && !this.invalidHandleIds[node.id];
20874 for (var i=0, len=this.invalidHandleClasses.length; valid && i<len; ++i) {
20875 valid = !Dom.hasClass(node, this.invalidHandleClasses[i]);
20884 * Create the array of horizontal tick marks if an interval was specified
20885 * in setXConstraint().
20886 * @method setXTicks
20889 setXTicks: function(iStartX, iTickSize) {
20891 this.xTickSize = iTickSize;
20895 for (var i = this.initPageX; i >= this.minX; i = i - iTickSize) {
20897 this.xTicks[this.xTicks.length] = i;
20902 for (i = this.initPageX; i <= this.maxX; i = i + iTickSize) {
20904 this.xTicks[this.xTicks.length] = i;
20909 this.xTicks.sort(this.DDM.numericSort) ;
20913 * Create the array of vertical tick marks if an interval was specified in
20914 * setYConstraint().
20915 * @method setYTicks
20918 setYTicks: function(iStartY, iTickSize) {
20920 this.yTickSize = iTickSize;
20924 for (var i = this.initPageY; i >= this.minY; i = i - iTickSize) {
20926 this.yTicks[this.yTicks.length] = i;
20931 for (i = this.initPageY; i <= this.maxY; i = i + iTickSize) {
20933 this.yTicks[this.yTicks.length] = i;
20938 this.yTicks.sort(this.DDM.numericSort) ;
20942 * By default, the element can be dragged any place on the screen. Use
20943 * this method to limit the horizontal travel of the element. Pass in
20944 * 0,0 for the parameters if you want to lock the drag to the y axis.
20945 * @method setXConstraint
20946 * @param {int} iLeft the number of pixels the element can move to the left
20947 * @param {int} iRight the number of pixels the element can move to the
20949 * @param {int} iTickSize optional parameter for specifying that the
20951 * should move iTickSize pixels at a time.
20953 setXConstraint: function(iLeft, iRight, iTickSize) {
20954 this.leftConstraint = iLeft;
20955 this.rightConstraint = iRight;
20957 this.minX = this.initPageX - iLeft;
20958 this.maxX = this.initPageX + iRight;
20959 if (iTickSize) { this.setXTicks(this.initPageX, iTickSize); }
20961 this.constrainX = true;
20965 * Clears any constraints applied to this instance. Also clears ticks
20966 * since they can't exist independent of a constraint at this time.
20967 * @method clearConstraints
20969 clearConstraints: function() {
20970 this.constrainX = false;
20971 this.constrainY = false;
20976 * Clears any tick interval defined for this instance
20977 * @method clearTicks
20979 clearTicks: function() {
20980 this.xTicks = null;
20981 this.yTicks = null;
20982 this.xTickSize = 0;
20983 this.yTickSize = 0;
20987 * By default, the element can be dragged any place on the screen. Set
20988 * this to limit the vertical travel of the element. Pass in 0,0 for the
20989 * parameters if you want to lock the drag to the x axis.
20990 * @method setYConstraint
20991 * @param {int} iUp the number of pixels the element can move up
20992 * @param {int} iDown the number of pixels the element can move down
20993 * @param {int} iTickSize optional parameter for specifying that the
20994 * element should move iTickSize pixels at a time.
20996 setYConstraint: function(iUp, iDown, iTickSize) {
20997 this.topConstraint = iUp;
20998 this.bottomConstraint = iDown;
21000 this.minY = this.initPageY - iUp;
21001 this.maxY = this.initPageY + iDown;
21002 if (iTickSize) { this.setYTicks(this.initPageY, iTickSize); }
21004 this.constrainY = true;
21009 * resetConstraints must be called if you manually reposition a dd element.
21010 * @method resetConstraints
21011 * @param {boolean} maintainOffset
21013 resetConstraints: function() {
21016 // Maintain offsets if necessary
21017 if (this.initPageX || this.initPageX === 0) {
21018 // figure out how much this thing has moved
21019 var dx = (this.maintainOffset) ? this.lastPageX - this.initPageX : 0;
21020 var dy = (this.maintainOffset) ? this.lastPageY - this.initPageY : 0;
21022 this.setInitPosition(dx, dy);
21024 // This is the first time we have detected the element's position
21026 this.setInitPosition();
21029 if (this.constrainX) {
21030 this.setXConstraint( this.leftConstraint,
21031 this.rightConstraint,
21035 if (this.constrainY) {
21036 this.setYConstraint( this.topConstraint,
21037 this.bottomConstraint,
21043 * Normally the drag element is moved pixel by pixel, but we can specify
21044 * that it move a number of pixels at a time. This method resolves the
21045 * location when we have it set up like this.
21047 * @param {int} val where we want to place the object
21048 * @param {int[]} tickArray sorted array of valid points
21049 * @return {int} the closest tick
21052 getTick: function(val, tickArray) {
21055 // If tick interval is not defined, it is effectively 1 pixel,
21056 // so we return the value passed to us.
21058 } else if (tickArray[0] >= val) {
21059 // The value is lower than the first tick, so we return the first
21061 return tickArray[0];
21063 for (var i=0, len=tickArray.length; i<len; ++i) {
21065 if (tickArray[next] && tickArray[next] >= val) {
21066 var diff1 = val - tickArray[i];
21067 var diff2 = tickArray[next] - val;
21068 return (diff2 > diff1) ? tickArray[i] : tickArray[next];
21072 // The value is larger than the last tick, so we return the last
21074 return tickArray[tickArray.length - 1];
21081 * @return {string} string representation of the dd obj
21083 toString: function() {
21084 return ("DragDrop " + this.id);
21092 * Ext JS Library 1.1.1
21093 * Copyright(c) 2006-2007, Ext JS, LLC.
21095 * Originally Released Under LGPL - original licence link has changed is not relivant.
21098 * <script type="text/javascript">
21103 * The drag and drop utility provides a framework for building drag and drop
21104 * applications. In addition to enabling drag and drop for specific elements,
21105 * the drag and drop elements are tracked by the manager class, and the
21106 * interactions between the various elements are tracked during the drag and
21107 * the implementing code is notified about these important moments.
21110 // Only load the library once. Rewriting the manager class would orphan
21111 // existing drag and drop instances.
21112 if (!Roo.dd.DragDropMgr) {
21115 * @class Roo.dd.DragDropMgr
21116 * DragDropMgr is a singleton that tracks the element interaction for
21117 * all DragDrop items in the window. Generally, you will not call
21118 * this class directly, but it does have helper methods that could
21119 * be useful in your DragDrop implementations.
21122 Roo.dd.DragDropMgr = function() {
21124 var Event = Roo.EventManager;
21129 * Two dimensional Array of registered DragDrop objects. The first
21130 * dimension is the DragDrop item group, the second the DragDrop
21133 * @type {string: string}
21140 * Array of element ids defined as drag handles. Used to determine
21141 * if the element that generated the mousedown event is actually the
21142 * handle and not the html element itself.
21143 * @property handleIds
21144 * @type {string: string}
21151 * the DragDrop object that is currently being dragged
21152 * @property dragCurrent
21160 * the DragDrop object(s) that are being hovered over
21161 * @property dragOvers
21169 * the X distance between the cursor and the object being dragged
21178 * the Y distance between the cursor and the object being dragged
21187 * Flag to determine if we should prevent the default behavior of the
21188 * events we define. By default this is true, but this can be set to
21189 * false if you need the default behavior (not recommended)
21190 * @property preventDefault
21194 preventDefault: true,
21197 * Flag to determine if we should stop the propagation of the events
21198 * we generate. This is true by default but you may want to set it to
21199 * false if the html element contains other features that require the
21201 * @property stopPropagation
21205 stopPropagation: true,
21208 * Internal flag that is set to true when drag and drop has been
21210 * @property initialized
21217 * All drag and drop can be disabled.
21225 * Called the first time an element is registered.
21231 this.initialized = true;
21235 * In point mode, drag and drop interaction is defined by the
21236 * location of the cursor during the drag/drop
21244 * In intersect mode, drag and drop interactio nis defined by the
21245 * overlap of two or more drag and drop objects.
21246 * @property INTERSECT
21253 * The current drag and drop mode. Default: POINT
21261 * Runs method on all drag and drop objects
21262 * @method _execOnAll
21266 _execOnAll: function(sMethod, args) {
21267 for (var i in this.ids) {
21268 for (var j in this.ids[i]) {
21269 var oDD = this.ids[i][j];
21270 if (! this.isTypeOfDD(oDD)) {
21273 oDD[sMethod].apply(oDD, args);
21279 * Drag and drop initialization. Sets up the global event handlers
21284 _onLoad: function() {
21288 if (!Roo.isTouch) {
21289 Event.on(document, "mouseup", this.handleMouseUp, this, true);
21290 Event.on(document, "mousemove", this.handleMouseMove, this, true);
21292 Event.on(document, "touchend", this.handleMouseUp, this, true);
21293 Event.on(document, "touchmove", this.handleMouseMove, this, true);
21295 Event.on(window, "unload", this._onUnload, this, true);
21296 Event.on(window, "resize", this._onResize, this, true);
21297 // Event.on(window, "mouseout", this._test);
21302 * Reset constraints on all drag and drop objs
21303 * @method _onResize
21307 _onResize: function(e) {
21308 this._execOnAll("resetConstraints", []);
21312 * Lock all drag and drop functionality
21316 lock: function() { this.locked = true; },
21319 * Unlock all drag and drop functionality
21323 unlock: function() { this.locked = false; },
21326 * Is drag and drop locked?
21328 * @return {boolean} True if drag and drop is locked, false otherwise.
21331 isLocked: function() { return this.locked; },
21334 * Location cache that is set for all drag drop objects when a drag is
21335 * initiated, cleared when the drag is finished.
21336 * @property locationCache
21343 * Set useCache to false if you want to force object the lookup of each
21344 * drag and drop linked element constantly during a drag.
21345 * @property useCache
21352 * The number of pixels that the mouse needs to move after the
21353 * mousedown before the drag is initiated. Default=3;
21354 * @property clickPixelThresh
21358 clickPixelThresh: 3,
21361 * The number of milliseconds after the mousedown event to initiate the
21362 * drag if we don't get a mouseup event. Default=1000
21363 * @property clickTimeThresh
21367 clickTimeThresh: 350,
21370 * Flag that indicates that either the drag pixel threshold or the
21371 * mousdown time threshold has been met
21372 * @property dragThreshMet
21377 dragThreshMet: false,
21380 * Timeout used for the click time threshold
21381 * @property clickTimeout
21386 clickTimeout: null,
21389 * The X position of the mousedown event stored for later use when a
21390 * drag threshold is met.
21399 * The Y position of the mousedown event stored for later use when a
21400 * drag threshold is met.
21409 * Each DragDrop instance must be registered with the DragDropMgr.
21410 * This is executed in DragDrop.init()
21411 * @method regDragDrop
21412 * @param {DragDrop} oDD the DragDrop object to register
21413 * @param {String} sGroup the name of the group this element belongs to
21416 regDragDrop: function(oDD, sGroup) {
21417 if (!this.initialized) { this.init(); }
21419 if (!this.ids[sGroup]) {
21420 this.ids[sGroup] = {};
21422 this.ids[sGroup][oDD.id] = oDD;
21426 * Removes the supplied dd instance from the supplied group. Executed
21427 * by DragDrop.removeFromGroup, so don't call this function directly.
21428 * @method removeDDFromGroup
21432 removeDDFromGroup: function(oDD, sGroup) {
21433 if (!this.ids[sGroup]) {
21434 this.ids[sGroup] = {};
21437 var obj = this.ids[sGroup];
21438 if (obj && obj[oDD.id]) {
21439 delete obj[oDD.id];
21444 * Unregisters a drag and drop item. This is executed in
21445 * DragDrop.unreg, use that method instead of calling this directly.
21450 _remove: function(oDD) {
21451 for (var g in oDD.groups) {
21452 if (g && this.ids[g][oDD.id]) {
21453 delete this.ids[g][oDD.id];
21456 delete this.handleIds[oDD.id];
21460 * Each DragDrop handle element must be registered. This is done
21461 * automatically when executing DragDrop.setHandleElId()
21462 * @method regHandle
21463 * @param {String} sDDId the DragDrop id this element is a handle for
21464 * @param {String} sHandleId the id of the element that is the drag
21468 regHandle: function(sDDId, sHandleId) {
21469 if (!this.handleIds[sDDId]) {
21470 this.handleIds[sDDId] = {};
21472 this.handleIds[sDDId][sHandleId] = sHandleId;
21476 * Utility function to determine if a given element has been
21477 * registered as a drag drop item.
21478 * @method isDragDrop
21479 * @param {String} id the element id to check
21480 * @return {boolean} true if this element is a DragDrop item,
21484 isDragDrop: function(id) {
21485 return ( this.getDDById(id) ) ? true : false;
21489 * Returns the drag and drop instances that are in all groups the
21490 * passed in instance belongs to.
21491 * @method getRelated
21492 * @param {DragDrop} p_oDD the obj to get related data for
21493 * @param {boolean} bTargetsOnly if true, only return targetable objs
21494 * @return {DragDrop[]} the related instances
21497 getRelated: function(p_oDD, bTargetsOnly) {
21499 for (var i in p_oDD.groups) {
21500 for (j in this.ids[i]) {
21501 var dd = this.ids[i][j];
21502 if (! this.isTypeOfDD(dd)) {
21505 if (!bTargetsOnly || dd.isTarget) {
21506 oDDs[oDDs.length] = dd;
21515 * Returns true if the specified dd target is a legal target for
21516 * the specifice drag obj
21517 * @method isLegalTarget
21518 * @param {DragDrop} the drag obj
21519 * @param {DragDrop} the target
21520 * @return {boolean} true if the target is a legal target for the
21524 isLegalTarget: function (oDD, oTargetDD) {
21525 var targets = this.getRelated(oDD, true);
21526 for (var i=0, len=targets.length;i<len;++i) {
21527 if (targets[i].id == oTargetDD.id) {
21536 * My goal is to be able to transparently determine if an object is
21537 * typeof DragDrop, and the exact subclass of DragDrop. typeof
21538 * returns "object", oDD.constructor.toString() always returns
21539 * "DragDrop" and not the name of the subclass. So for now it just
21540 * evaluates a well-known variable in DragDrop.
21541 * @method isTypeOfDD
21542 * @param {Object} the object to evaluate
21543 * @return {boolean} true if typeof oDD = DragDrop
21546 isTypeOfDD: function (oDD) {
21547 return (oDD && oDD.__ygDragDrop);
21551 * Utility function to determine if a given element has been
21552 * registered as a drag drop handle for the given Drag Drop object.
21554 * @param {String} id the element id to check
21555 * @return {boolean} true if this element is a DragDrop handle, false
21559 isHandle: function(sDDId, sHandleId) {
21560 return ( this.handleIds[sDDId] &&
21561 this.handleIds[sDDId][sHandleId] );
21565 * Returns the DragDrop instance for a given id
21566 * @method getDDById
21567 * @param {String} id the id of the DragDrop object
21568 * @return {DragDrop} the drag drop object, null if it is not found
21571 getDDById: function(id) {
21572 for (var i in this.ids) {
21573 if (this.ids[i][id]) {
21574 return this.ids[i][id];
21581 * Fired after a registered DragDrop object gets the mousedown event.
21582 * Sets up the events required to track the object being dragged
21583 * @method handleMouseDown
21584 * @param {Event} e the event
21585 * @param oDD the DragDrop object being dragged
21589 handleMouseDown: function(e, oDD) {
21591 Roo.QuickTips.disable();
21593 this.currentTarget = e.getTarget();
21595 this.dragCurrent = oDD;
21597 var el = oDD.getEl();
21599 // track start position
21600 this.startX = e.getPageX();
21601 this.startY = e.getPageY();
21603 this.deltaX = this.startX - el.offsetLeft;
21604 this.deltaY = this.startY - el.offsetTop;
21606 this.dragThreshMet = false;
21608 this.clickTimeout = setTimeout(
21610 var DDM = Roo.dd.DDM;
21611 DDM.startDrag(DDM.startX, DDM.startY);
21613 this.clickTimeThresh );
21617 * Fired when either the drag pixel threshol or the mousedown hold
21618 * time threshold has been met.
21619 * @method startDrag
21620 * @param x {int} the X position of the original mousedown
21621 * @param y {int} the Y position of the original mousedown
21624 startDrag: function(x, y) {
21625 clearTimeout(this.clickTimeout);
21626 if (this.dragCurrent) {
21627 this.dragCurrent.b4StartDrag(x, y);
21628 this.dragCurrent.startDrag(x, y);
21630 this.dragThreshMet = true;
21634 * Internal function to handle the mouseup event. Will be invoked
21635 * from the context of the document.
21636 * @method handleMouseUp
21637 * @param {Event} e the event
21641 handleMouseUp: function(e) {
21644 Roo.QuickTips.enable();
21646 if (! this.dragCurrent) {
21650 clearTimeout(this.clickTimeout);
21652 if (this.dragThreshMet) {
21653 this.fireEvents(e, true);
21663 * Utility to stop event propagation and event default, if these
21664 * features are turned on.
21665 * @method stopEvent
21666 * @param {Event} e the event as returned by this.getEvent()
21669 stopEvent: function(e){
21670 if(this.stopPropagation) {
21671 e.stopPropagation();
21674 if (this.preventDefault) {
21675 e.preventDefault();
21680 * Internal function to clean up event handlers after the drag
21681 * operation is complete
21683 * @param {Event} e the event
21687 stopDrag: function(e) {
21688 // Fire the drag end event for the item that was dragged
21689 if (this.dragCurrent) {
21690 if (this.dragThreshMet) {
21691 this.dragCurrent.b4EndDrag(e);
21692 this.dragCurrent.endDrag(e);
21695 this.dragCurrent.onMouseUp(e);
21698 this.dragCurrent = null;
21699 this.dragOvers = {};
21703 * Internal function to handle the mousemove event. Will be invoked
21704 * from the context of the html element.
21706 * @TODO figure out what we can do about mouse events lost when the
21707 * user drags objects beyond the window boundary. Currently we can
21708 * detect this in internet explorer by verifying that the mouse is
21709 * down during the mousemove event. Firefox doesn't give us the
21710 * button state on the mousemove event.
21711 * @method handleMouseMove
21712 * @param {Event} e the event
21716 handleMouseMove: function(e) {
21717 if (! this.dragCurrent) {
21721 // var button = e.which || e.button;
21723 // check for IE mouseup outside of page boundary
21724 if (Roo.isIE && (e.button !== 0 && e.button !== 1 && e.button !== 2)) {
21726 return this.handleMouseUp(e);
21729 if (!this.dragThreshMet) {
21730 var diffX = Math.abs(this.startX - e.getPageX());
21731 var diffY = Math.abs(this.startY - e.getPageY());
21732 if (diffX > this.clickPixelThresh ||
21733 diffY > this.clickPixelThresh) {
21734 this.startDrag(this.startX, this.startY);
21738 if (this.dragThreshMet) {
21739 this.dragCurrent.b4Drag(e);
21740 this.dragCurrent.onDrag(e);
21741 if(!this.dragCurrent.moveOnly){
21742 this.fireEvents(e, false);
21752 * Iterates over all of the DragDrop elements to find ones we are
21753 * hovering over or dropping on
21754 * @method fireEvents
21755 * @param {Event} e the event
21756 * @param {boolean} isDrop is this a drop op or a mouseover op?
21760 fireEvents: function(e, isDrop) {
21761 var dc = this.dragCurrent;
21763 // If the user did the mouse up outside of the window, we could
21764 // get here even though we have ended the drag.
21765 if (!dc || dc.isLocked()) {
21769 var pt = e.getPoint();
21771 // cache the previous dragOver array
21777 var enterEvts = [];
21779 // Check to see if the object(s) we were hovering over is no longer
21780 // being hovered over so we can fire the onDragOut event
21781 for (var i in this.dragOvers) {
21783 var ddo = this.dragOvers[i];
21785 if (! this.isTypeOfDD(ddo)) {
21789 if (! this.isOverTarget(pt, ddo, this.mode)) {
21790 outEvts.push( ddo );
21793 oldOvers[i] = true;
21794 delete this.dragOvers[i];
21797 for (var sGroup in dc.groups) {
21799 if ("string" != typeof sGroup) {
21803 for (i in this.ids[sGroup]) {
21804 var oDD = this.ids[sGroup][i];
21805 if (! this.isTypeOfDD(oDD)) {
21809 if (oDD.isTarget && !oDD.isLocked() && oDD != dc) {
21810 if (this.isOverTarget(pt, oDD, this.mode)) {
21811 // look for drop interactions
21813 dropEvts.push( oDD );
21814 // look for drag enter and drag over interactions
21817 // initial drag over: dragEnter fires
21818 if (!oldOvers[oDD.id]) {
21819 enterEvts.push( oDD );
21820 // subsequent drag overs: dragOver fires
21822 overEvts.push( oDD );
21825 this.dragOvers[oDD.id] = oDD;
21833 if (outEvts.length) {
21834 dc.b4DragOut(e, outEvts);
21835 dc.onDragOut(e, outEvts);
21838 if (enterEvts.length) {
21839 dc.onDragEnter(e, enterEvts);
21842 if (overEvts.length) {
21843 dc.b4DragOver(e, overEvts);
21844 dc.onDragOver(e, overEvts);
21847 if (dropEvts.length) {
21848 dc.b4DragDrop(e, dropEvts);
21849 dc.onDragDrop(e, dropEvts);
21853 // fire dragout events
21855 for (i=0, len=outEvts.length; i<len; ++i) {
21856 dc.b4DragOut(e, outEvts[i].id);
21857 dc.onDragOut(e, outEvts[i].id);
21860 // fire enter events
21861 for (i=0,len=enterEvts.length; i<len; ++i) {
21862 // dc.b4DragEnter(e, oDD.id);
21863 dc.onDragEnter(e, enterEvts[i].id);
21866 // fire over events
21867 for (i=0,len=overEvts.length; i<len; ++i) {
21868 dc.b4DragOver(e, overEvts[i].id);
21869 dc.onDragOver(e, overEvts[i].id);
21872 // fire drop events
21873 for (i=0, len=dropEvts.length; i<len; ++i) {
21874 dc.b4DragDrop(e, dropEvts[i].id);
21875 dc.onDragDrop(e, dropEvts[i].id);
21880 // notify about a drop that did not find a target
21881 if (isDrop && !dropEvts.length) {
21882 dc.onInvalidDrop(e);
21888 * Helper function for getting the best match from the list of drag
21889 * and drop objects returned by the drag and drop events when we are
21890 * in INTERSECT mode. It returns either the first object that the
21891 * cursor is over, or the object that has the greatest overlap with
21892 * the dragged element.
21893 * @method getBestMatch
21894 * @param {DragDrop[]} dds The array of drag and drop objects
21896 * @return {DragDrop} The best single match
21899 getBestMatch: function(dds) {
21901 // Return null if the input is not what we expect
21902 //if (!dds || !dds.length || dds.length == 0) {
21904 // If there is only one item, it wins
21905 //} else if (dds.length == 1) {
21907 var len = dds.length;
21912 // Loop through the targeted items
21913 for (var i=0; i<len; ++i) {
21915 // If the cursor is over the object, it wins. If the
21916 // cursor is over multiple matches, the first one we come
21918 if (dd.cursorIsOver) {
21921 // Otherwise the object with the most overlap wins
21924 winner.overlap.getArea() < dd.overlap.getArea()) {
21935 * Refreshes the cache of the top-left and bottom-right points of the
21936 * drag and drop objects in the specified group(s). This is in the
21937 * format that is stored in the drag and drop instance, so typical
21940 * Roo.dd.DragDropMgr.refreshCache(ddinstance.groups);
21944 * Roo.dd.DragDropMgr.refreshCache({group1:true, group2:true});
21946 * @TODO this really should be an indexed array. Alternatively this
21947 * method could accept both.
21948 * @method refreshCache
21949 * @param {Object} groups an associative array of groups to refresh
21952 refreshCache: function(groups) {
21953 for (var sGroup in groups) {
21954 if ("string" != typeof sGroup) {
21957 for (var i in this.ids[sGroup]) {
21958 var oDD = this.ids[sGroup][i];
21960 if (this.isTypeOfDD(oDD)) {
21961 // if (this.isTypeOfDD(oDD) && oDD.isTarget) {
21962 var loc = this.getLocation(oDD);
21964 this.locationCache[oDD.id] = loc;
21966 delete this.locationCache[oDD.id];
21967 // this will unregister the drag and drop object if
21968 // the element is not in a usable state
21977 * This checks to make sure an element exists and is in the DOM. The
21978 * main purpose is to handle cases where innerHTML is used to remove
21979 * drag and drop objects from the DOM. IE provides an 'unspecified
21980 * error' when trying to access the offsetParent of such an element
21982 * @param {HTMLElement} el the element to check
21983 * @return {boolean} true if the element looks usable
21986 verifyEl: function(el) {
21991 parent = el.offsetParent;
21994 parent = el.offsetParent;
22005 * Returns a Region object containing the drag and drop element's position
22006 * and size, including the padding configured for it
22007 * @method getLocation
22008 * @param {DragDrop} oDD the drag and drop object to get the
22010 * @return {Roo.lib.Region} a Region object representing the total area
22011 * the element occupies, including any padding
22012 * the instance is configured for.
22015 getLocation: function(oDD) {
22016 if (! this.isTypeOfDD(oDD)) {
22020 var el = oDD.getEl(), pos, x1, x2, y1, y2, t, r, b, l;
22023 pos= Roo.lib.Dom.getXY(el);
22031 x2 = x1 + el.offsetWidth;
22033 y2 = y1 + el.offsetHeight;
22035 t = y1 - oDD.padding[0];
22036 r = x2 + oDD.padding[1];
22037 b = y2 + oDD.padding[2];
22038 l = x1 - oDD.padding[3];
22040 return new Roo.lib.Region( t, r, b, l );
22044 * Checks the cursor location to see if it over the target
22045 * @method isOverTarget
22046 * @param {Roo.lib.Point} pt The point to evaluate
22047 * @param {DragDrop} oTarget the DragDrop object we are inspecting
22048 * @return {boolean} true if the mouse is over the target
22052 isOverTarget: function(pt, oTarget, intersect) {
22053 // use cache if available
22054 var loc = this.locationCache[oTarget.id];
22055 if (!loc || !this.useCache) {
22056 loc = this.getLocation(oTarget);
22057 this.locationCache[oTarget.id] = loc;
22065 oTarget.cursorIsOver = loc.contains( pt );
22067 // DragDrop is using this as a sanity check for the initial mousedown
22068 // in this case we are done. In POINT mode, if the drag obj has no
22069 // contraints, we are also done. Otherwise we need to evaluate the
22070 // location of the target as related to the actual location of the
22071 // dragged element.
22072 var dc = this.dragCurrent;
22073 if (!dc || !dc.getTargetCoord ||
22074 (!intersect && !dc.constrainX && !dc.constrainY)) {
22075 return oTarget.cursorIsOver;
22078 oTarget.overlap = null;
22080 // Get the current location of the drag element, this is the
22081 // location of the mouse event less the delta that represents
22082 // where the original mousedown happened on the element. We
22083 // need to consider constraints and ticks as well.
22084 var pos = dc.getTargetCoord(pt.x, pt.y);
22086 var el = dc.getDragEl();
22087 var curRegion = new Roo.lib.Region( pos.y,
22088 pos.x + el.offsetWidth,
22089 pos.y + el.offsetHeight,
22092 var overlap = curRegion.intersect(loc);
22095 oTarget.overlap = overlap;
22096 return (intersect) ? true : oTarget.cursorIsOver;
22103 * unload event handler
22104 * @method _onUnload
22108 _onUnload: function(e, me) {
22109 Roo.dd.DragDropMgr.unregAll();
22113 * Cleans up the drag and drop events and objects.
22118 unregAll: function() {
22120 if (this.dragCurrent) {
22122 this.dragCurrent = null;
22125 this._execOnAll("unreg", []);
22127 for (i in this.elementCache) {
22128 delete this.elementCache[i];
22131 this.elementCache = {};
22136 * A cache of DOM elements
22137 * @property elementCache
22144 * Get the wrapper for the DOM element specified
22145 * @method getElWrapper
22146 * @param {String} id the id of the element to get
22147 * @return {Roo.dd.DDM.ElementWrapper} the wrapped element
22149 * @deprecated This wrapper isn't that useful
22152 getElWrapper: function(id) {
22153 var oWrapper = this.elementCache[id];
22154 if (!oWrapper || !oWrapper.el) {
22155 oWrapper = this.elementCache[id] =
22156 new this.ElementWrapper(Roo.getDom(id));
22162 * Returns the actual DOM element
22163 * @method getElement
22164 * @param {String} id the id of the elment to get
22165 * @return {Object} The element
22166 * @deprecated use Roo.getDom instead
22169 getElement: function(id) {
22170 return Roo.getDom(id);
22174 * Returns the style property for the DOM element (i.e.,
22175 * document.getElById(id).style)
22177 * @param {String} id the id of the elment to get
22178 * @return {Object} The style property of the element
22179 * @deprecated use Roo.getDom instead
22182 getCss: function(id) {
22183 var el = Roo.getDom(id);
22184 return (el) ? el.style : null;
22188 * Inner class for cached elements
22189 * @class DragDropMgr.ElementWrapper
22194 ElementWrapper: function(el) {
22199 this.el = el || null;
22204 this.id = this.el && el.id;
22206 * A reference to the style property
22209 this.css = this.el && el.style;
22213 * Returns the X position of an html element
22215 * @param el the element for which to get the position
22216 * @return {int} the X coordinate
22218 * @deprecated use Roo.lib.Dom.getX instead
22221 getPosX: function(el) {
22222 return Roo.lib.Dom.getX(el);
22226 * Returns the Y position of an html element
22228 * @param el the element for which to get the position
22229 * @return {int} the Y coordinate
22230 * @deprecated use Roo.lib.Dom.getY instead
22233 getPosY: function(el) {
22234 return Roo.lib.Dom.getY(el);
22238 * Swap two nodes. In IE, we use the native method, for others we
22239 * emulate the IE behavior
22241 * @param n1 the first node to swap
22242 * @param n2 the other node to swap
22245 swapNode: function(n1, n2) {
22249 var p = n2.parentNode;
22250 var s = n2.nextSibling;
22253 p.insertBefore(n1, n2);
22254 } else if (n2 == n1.nextSibling) {
22255 p.insertBefore(n2, n1);
22257 n1.parentNode.replaceChild(n2, n1);
22258 p.insertBefore(n1, s);
22264 * Returns the current scroll position
22265 * @method getScroll
22269 getScroll: function () {
22270 var t, l, dde=document.documentElement, db=document.body;
22271 if (dde && (dde.scrollTop || dde.scrollLeft)) {
22273 l = dde.scrollLeft;
22280 return { top: t, left: l };
22284 * Returns the specified element style property
22286 * @param {HTMLElement} el the element
22287 * @param {string} styleProp the style property
22288 * @return {string} The value of the style property
22289 * @deprecated use Roo.lib.Dom.getStyle
22292 getStyle: function(el, styleProp) {
22293 return Roo.fly(el).getStyle(styleProp);
22297 * Gets the scrollTop
22298 * @method getScrollTop
22299 * @return {int} the document's scrollTop
22302 getScrollTop: function () { return this.getScroll().top; },
22305 * Gets the scrollLeft
22306 * @method getScrollLeft
22307 * @return {int} the document's scrollTop
22310 getScrollLeft: function () { return this.getScroll().left; },
22313 * Sets the x/y position of an element to the location of the
22316 * @param {HTMLElement} moveEl The element to move
22317 * @param {HTMLElement} targetEl The position reference element
22320 moveToEl: function (moveEl, targetEl) {
22321 var aCoord = Roo.lib.Dom.getXY(targetEl);
22322 Roo.lib.Dom.setXY(moveEl, aCoord);
22326 * Numeric array sort function
22327 * @method numericSort
22330 numericSort: function(a, b) { return (a - b); },
22334 * @property _timeoutCount
22341 * Trying to make the load order less important. Without this we get
22342 * an error if this file is loaded before the Event Utility.
22343 * @method _addListeners
22347 _addListeners: function() {
22348 var DDM = Roo.dd.DDM;
22349 if ( Roo.lib.Event && document ) {
22352 if (DDM._timeoutCount > 2000) {
22354 setTimeout(DDM._addListeners, 10);
22355 if (document && document.body) {
22356 DDM._timeoutCount += 1;
22363 * Recursively searches the immediate parent and all child nodes for
22364 * the handle element in order to determine wheter or not it was
22366 * @method handleWasClicked
22367 * @param node the html element to inspect
22370 handleWasClicked: function(node, id) {
22371 if (this.isHandle(id, node.id)) {
22374 // check to see if this is a text node child of the one we want
22375 var p = node.parentNode;
22378 if (this.isHandle(id, p.id)) {
22393 // shorter alias, save a few bytes
22394 Roo.dd.DDM = Roo.dd.DragDropMgr;
22395 Roo.dd.DDM._addListeners();
22399 * Ext JS Library 1.1.1
22400 * Copyright(c) 2006-2007, Ext JS, LLC.
22402 * Originally Released Under LGPL - original licence link has changed is not relivant.
22405 * <script type="text/javascript">
22410 * A DragDrop implementation where the linked element follows the
22411 * mouse cursor during a drag.
22412 * @extends Roo.dd.DragDrop
22414 * @param {String} id the id of the linked element
22415 * @param {String} sGroup the group of related DragDrop items
22416 * @param {object} config an object containing configurable attributes
22417 * Valid properties for DD:
22420 Roo.dd.DD = function(id, sGroup, config) {
22422 this.init(id, sGroup, config);
22426 Roo.extend(Roo.dd.DD, Roo.dd.DragDrop, {
22429 * When set to true, the utility automatically tries to scroll the browser
22430 * window wehn a drag and drop element is dragged near the viewport boundary.
22431 * Defaults to true.
22438 * Sets the pointer offset to the distance between the linked element's top
22439 * left corner and the location the element was clicked
22440 * @method autoOffset
22441 * @param {int} iPageX the X coordinate of the click
22442 * @param {int} iPageY the Y coordinate of the click
22444 autoOffset: function(iPageX, iPageY) {
22445 var x = iPageX - this.startPageX;
22446 var y = iPageY - this.startPageY;
22447 this.setDelta(x, y);
22451 * Sets the pointer offset. You can call this directly to force the
22452 * offset to be in a particular location (e.g., pass in 0,0 to set it
22453 * to the center of the object)
22455 * @param {int} iDeltaX the distance from the left
22456 * @param {int} iDeltaY the distance from the top
22458 setDelta: function(iDeltaX, iDeltaY) {
22459 this.deltaX = iDeltaX;
22460 this.deltaY = iDeltaY;
22464 * Sets the drag element to the location of the mousedown or click event,
22465 * maintaining the cursor location relative to the location on the element
22466 * that was clicked. Override this if you want to place the element in a
22467 * location other than where the cursor is.
22468 * @method setDragElPos
22469 * @param {int} iPageX the X coordinate of the mousedown or drag event
22470 * @param {int} iPageY the Y coordinate of the mousedown or drag event
22472 setDragElPos: function(iPageX, iPageY) {
22473 // the first time we do this, we are going to check to make sure
22474 // the element has css positioning
22476 var el = this.getDragEl();
22477 this.alignElWithMouse(el, iPageX, iPageY);
22481 * Sets the element to the location of the mousedown or click event,
22482 * maintaining the cursor location relative to the location on the element
22483 * that was clicked. Override this if you want to place the element in a
22484 * location other than where the cursor is.
22485 * @method alignElWithMouse
22486 * @param {HTMLElement} el the element to move
22487 * @param {int} iPageX the X coordinate of the mousedown or drag event
22488 * @param {int} iPageY the Y coordinate of the mousedown or drag event
22490 alignElWithMouse: function(el, iPageX, iPageY) {
22491 var oCoord = this.getTargetCoord(iPageX, iPageY);
22492 var fly = el.dom ? el : Roo.fly(el);
22493 if (!this.deltaSetXY) {
22494 var aCoord = [oCoord.x, oCoord.y];
22496 var newLeft = fly.getLeft(true);
22497 var newTop = fly.getTop(true);
22498 this.deltaSetXY = [ newLeft - oCoord.x, newTop - oCoord.y ];
22500 fly.setLeftTop(oCoord.x + this.deltaSetXY[0], oCoord.y + this.deltaSetXY[1]);
22503 this.cachePosition(oCoord.x, oCoord.y);
22504 this.autoScroll(oCoord.x, oCoord.y, el.offsetHeight, el.offsetWidth);
22509 * Saves the most recent position so that we can reset the constraints and
22510 * tick marks on-demand. We need to know this so that we can calculate the
22511 * number of pixels the element is offset from its original position.
22512 * @method cachePosition
22513 * @param iPageX the current x position (optional, this just makes it so we
22514 * don't have to look it up again)
22515 * @param iPageY the current y position (optional, this just makes it so we
22516 * don't have to look it up again)
22518 cachePosition: function(iPageX, iPageY) {
22520 this.lastPageX = iPageX;
22521 this.lastPageY = iPageY;
22523 var aCoord = Roo.lib.Dom.getXY(this.getEl());
22524 this.lastPageX = aCoord[0];
22525 this.lastPageY = aCoord[1];
22530 * Auto-scroll the window if the dragged object has been moved beyond the
22531 * visible window boundary.
22532 * @method autoScroll
22533 * @param {int} x the drag element's x position
22534 * @param {int} y the drag element's y position
22535 * @param {int} h the height of the drag element
22536 * @param {int} w the width of the drag element
22539 autoScroll: function(x, y, h, w) {
22542 // The client height
22543 var clientH = Roo.lib.Dom.getViewWidth();
22545 // The client width
22546 var clientW = Roo.lib.Dom.getViewHeight();
22548 // The amt scrolled down
22549 var st = this.DDM.getScrollTop();
22551 // The amt scrolled right
22552 var sl = this.DDM.getScrollLeft();
22554 // Location of the bottom of the element
22557 // Location of the right of the element
22560 // The distance from the cursor to the bottom of the visible area,
22561 // adjusted so that we don't scroll if the cursor is beyond the
22562 // element drag constraints
22563 var toBot = (clientH + st - y - this.deltaY);
22565 // The distance from the cursor to the right of the visible area
22566 var toRight = (clientW + sl - x - this.deltaX);
22569 // How close to the edge the cursor must be before we scroll
22570 // var thresh = (document.all) ? 100 : 40;
22573 // How many pixels to scroll per autoscroll op. This helps to reduce
22574 // clunky scrolling. IE is more sensitive about this ... it needs this
22575 // value to be higher.
22576 var scrAmt = (document.all) ? 80 : 30;
22578 // Scroll down if we are near the bottom of the visible page and the
22579 // obj extends below the crease
22580 if ( bot > clientH && toBot < thresh ) {
22581 window.scrollTo(sl, st + scrAmt);
22584 // Scroll up if the window is scrolled down and the top of the object
22585 // goes above the top border
22586 if ( y < st && st > 0 && y - st < thresh ) {
22587 window.scrollTo(sl, st - scrAmt);
22590 // Scroll right if the obj is beyond the right border and the cursor is
22591 // near the border.
22592 if ( right > clientW && toRight < thresh ) {
22593 window.scrollTo(sl + scrAmt, st);
22596 // Scroll left if the window has been scrolled to the right and the obj
22597 // extends past the left border
22598 if ( x < sl && sl > 0 && x - sl < thresh ) {
22599 window.scrollTo(sl - scrAmt, st);
22605 * Finds the location the element should be placed if we want to move
22606 * it to where the mouse location less the click offset would place us.
22607 * @method getTargetCoord
22608 * @param {int} iPageX the X coordinate of the click
22609 * @param {int} iPageY the Y coordinate of the click
22610 * @return an object that contains the coordinates (Object.x and Object.y)
22613 getTargetCoord: function(iPageX, iPageY) {
22616 var x = iPageX - this.deltaX;
22617 var y = iPageY - this.deltaY;
22619 if (this.constrainX) {
22620 if (x < this.minX) { x = this.minX; }
22621 if (x > this.maxX) { x = this.maxX; }
22624 if (this.constrainY) {
22625 if (y < this.minY) { y = this.minY; }
22626 if (y > this.maxY) { y = this.maxY; }
22629 x = this.getTick(x, this.xTicks);
22630 y = this.getTick(y, this.yTicks);
22637 * Sets up config options specific to this class. Overrides
22638 * Roo.dd.DragDrop, but all versions of this method through the
22639 * inheritance chain are called
22641 applyConfig: function() {
22642 Roo.dd.DD.superclass.applyConfig.call(this);
22643 this.scroll = (this.config.scroll !== false);
22647 * Event that fires prior to the onMouseDown event. Overrides
22650 b4MouseDown: function(e) {
22651 // this.resetConstraints();
22652 this.autoOffset(e.getPageX(),
22657 * Event that fires prior to the onDrag event. Overrides
22660 b4Drag: function(e) {
22661 this.setDragElPos(e.getPageX(),
22665 toString: function() {
22666 return ("DD " + this.id);
22669 //////////////////////////////////////////////////////////////////////////
22670 // Debugging ygDragDrop events that can be overridden
22671 //////////////////////////////////////////////////////////////////////////
22673 startDrag: function(x, y) {
22676 onDrag: function(e) {
22679 onDragEnter: function(e, id) {
22682 onDragOver: function(e, id) {
22685 onDragOut: function(e, id) {
22688 onDragDrop: function(e, id) {
22691 endDrag: function(e) {
22698 * Ext JS Library 1.1.1
22699 * Copyright(c) 2006-2007, Ext JS, LLC.
22701 * Originally Released Under LGPL - original licence link has changed is not relivant.
22704 * <script type="text/javascript">
22708 * @class Roo.dd.DDProxy
22709 * A DragDrop implementation that inserts an empty, bordered div into
22710 * the document that follows the cursor during drag operations. At the time of
22711 * the click, the frame div is resized to the dimensions of the linked html
22712 * element, and moved to the exact location of the linked element.
22714 * References to the "frame" element refer to the single proxy element that
22715 * was created to be dragged in place of all DDProxy elements on the
22718 * @extends Roo.dd.DD
22720 * @param {String} id the id of the linked html element
22721 * @param {String} sGroup the group of related DragDrop objects
22722 * @param {object} config an object containing configurable attributes
22723 * Valid properties for DDProxy in addition to those in DragDrop:
22724 * resizeFrame, centerFrame, dragElId
22726 Roo.dd.DDProxy = function(id, sGroup, config) {
22728 this.init(id, sGroup, config);
22734 * The default drag frame div id
22735 * @property Roo.dd.DDProxy.dragElId
22739 Roo.dd.DDProxy.dragElId = "ygddfdiv";
22741 Roo.extend(Roo.dd.DDProxy, Roo.dd.DD, {
22744 * By default we resize the drag frame to be the same size as the element
22745 * we want to drag (this is to get the frame effect). We can turn it off
22746 * if we want a different behavior.
22747 * @property resizeFrame
22753 * By default the frame is positioned exactly where the drag element is, so
22754 * we use the cursor offset provided by Roo.dd.DD. Another option that works only if
22755 * you do not have constraints on the obj is to have the drag frame centered
22756 * around the cursor. Set centerFrame to true for this effect.
22757 * @property centerFrame
22760 centerFrame: false,
22763 * Creates the proxy element if it does not yet exist
22764 * @method createFrame
22766 createFrame: function() {
22768 var body = document.body;
22770 if (!body || !body.firstChild) {
22771 setTimeout( function() { self.createFrame(); }, 50 );
22775 var div = this.getDragEl();
22778 div = document.createElement("div");
22779 div.id = this.dragElId;
22782 s.position = "absolute";
22783 s.visibility = "hidden";
22785 s.border = "2px solid #aaa";
22788 // appendChild can blow up IE if invoked prior to the window load event
22789 // while rendering a table. It is possible there are other scenarios
22790 // that would cause this to happen as well.
22791 body.insertBefore(div, body.firstChild);
22796 * Initialization for the drag frame element. Must be called in the
22797 * constructor of all subclasses
22798 * @method initFrame
22800 initFrame: function() {
22801 this.createFrame();
22804 applyConfig: function() {
22805 Roo.dd.DDProxy.superclass.applyConfig.call(this);
22807 this.resizeFrame = (this.config.resizeFrame !== false);
22808 this.centerFrame = (this.config.centerFrame);
22809 this.setDragElId(this.config.dragElId || Roo.dd.DDProxy.dragElId);
22813 * Resizes the drag frame to the dimensions of the clicked object, positions
22814 * it over the object, and finally displays it
22815 * @method showFrame
22816 * @param {int} iPageX X click position
22817 * @param {int} iPageY Y click position
22820 showFrame: function(iPageX, iPageY) {
22821 var el = this.getEl();
22822 var dragEl = this.getDragEl();
22823 var s = dragEl.style;
22825 this._resizeProxy();
22827 if (this.centerFrame) {
22828 this.setDelta( Math.round(parseInt(s.width, 10)/2),
22829 Math.round(parseInt(s.height, 10)/2) );
22832 this.setDragElPos(iPageX, iPageY);
22834 Roo.fly(dragEl).show();
22838 * The proxy is automatically resized to the dimensions of the linked
22839 * element when a drag is initiated, unless resizeFrame is set to false
22840 * @method _resizeProxy
22843 _resizeProxy: function() {
22844 if (this.resizeFrame) {
22845 var el = this.getEl();
22846 Roo.fly(this.getDragEl()).setSize(el.offsetWidth, el.offsetHeight);
22850 // overrides Roo.dd.DragDrop
22851 b4MouseDown: function(e) {
22852 var x = e.getPageX();
22853 var y = e.getPageY();
22854 this.autoOffset(x, y);
22855 this.setDragElPos(x, y);
22858 // overrides Roo.dd.DragDrop
22859 b4StartDrag: function(x, y) {
22860 // show the drag frame
22861 this.showFrame(x, y);
22864 // overrides Roo.dd.DragDrop
22865 b4EndDrag: function(e) {
22866 Roo.fly(this.getDragEl()).hide();
22869 // overrides Roo.dd.DragDrop
22870 // By default we try to move the element to the last location of the frame.
22871 // This is so that the default behavior mirrors that of Roo.dd.DD.
22872 endDrag: function(e) {
22874 var lel = this.getEl();
22875 var del = this.getDragEl();
22877 // Show the drag frame briefly so we can get its position
22878 del.style.visibility = "";
22881 // Hide the linked element before the move to get around a Safari
22883 lel.style.visibility = "hidden";
22884 Roo.dd.DDM.moveToEl(lel, del);
22885 del.style.visibility = "hidden";
22886 lel.style.visibility = "";
22891 beforeMove : function(){
22895 afterDrag : function(){
22899 toString: function() {
22900 return ("DDProxy " + this.id);
22906 * Ext JS Library 1.1.1
22907 * Copyright(c) 2006-2007, Ext JS, LLC.
22909 * Originally Released Under LGPL - original licence link has changed is not relivant.
22912 * <script type="text/javascript">
22916 * @class Roo.dd.DDTarget
22917 * A DragDrop implementation that does not move, but can be a drop
22918 * target. You would get the same result by simply omitting implementation
22919 * for the event callbacks, but this way we reduce the processing cost of the
22920 * event listener and the callbacks.
22921 * @extends Roo.dd.DragDrop
22923 * @param {String} id the id of the element that is a drop target
22924 * @param {String} sGroup the group of related DragDrop objects
22925 * @param {object} config an object containing configurable attributes
22926 * Valid properties for DDTarget in addition to those in
22930 Roo.dd.DDTarget = function(id, sGroup, config) {
22932 this.initTarget(id, sGroup, config);
22934 if (config && (config.listeners || config.events)) {
22935 Roo.dd.DragDrop.superclass.constructor.call(this, {
22936 listeners : config.listeners || {},
22937 events : config.events || {}
22942 // Roo.dd.DDTarget.prototype = new Roo.dd.DragDrop();
22943 Roo.extend(Roo.dd.DDTarget, Roo.dd.DragDrop, {
22944 toString: function() {
22945 return ("DDTarget " + this.id);
22950 * Ext JS Library 1.1.1
22951 * Copyright(c) 2006-2007, Ext JS, LLC.
22953 * Originally Released Under LGPL - original licence link has changed is not relivant.
22956 * <script type="text/javascript">
22961 * @class Roo.dd.ScrollManager
22962 * Provides automatic scrolling of overflow regions in the page during drag operations.<br><br>
22963 * <b>Note: This class uses "Point Mode" and is untested in "Intersect Mode".</b>
22966 Roo.dd.ScrollManager = function(){
22967 var ddm = Roo.dd.DragDropMgr;
22974 var onStop = function(e){
22979 var triggerRefresh = function(){
22980 if(ddm.dragCurrent){
22981 ddm.refreshCache(ddm.dragCurrent.groups);
22985 var doScroll = function(){
22986 if(ddm.dragCurrent){
22987 var dds = Roo.dd.ScrollManager;
22989 if(proc.el.scroll(proc.dir, dds.increment)){
22993 proc.el.scroll(proc.dir, dds.increment, true, dds.animDuration, triggerRefresh);
22998 var clearProc = function(){
23000 clearInterval(proc.id);
23007 var startProc = function(el, dir){
23008 Roo.log('scroll startproc');
23012 proc.id = setInterval(doScroll, Roo.dd.ScrollManager.frequency);
23015 var onFire = function(e, isDrop){
23017 if(isDrop || !ddm.dragCurrent){ return; }
23018 var dds = Roo.dd.ScrollManager;
23019 if(!dragEl || dragEl != ddm.dragCurrent){
23020 dragEl = ddm.dragCurrent;
23021 // refresh regions on drag start
23022 dds.refreshCache();
23025 var xy = Roo.lib.Event.getXY(e);
23026 var pt = new Roo.lib.Point(xy[0], xy[1]);
23027 for(var id in els){
23028 var el = els[id], r = el._region;
23029 if(r && r.contains(pt) && el.isScrollable()){
23030 if(r.bottom - pt.y <= dds.thresh){
23032 startProc(el, "down");
23035 }else if(r.right - pt.x <= dds.thresh){
23037 startProc(el, "left");
23040 }else if(pt.y - r.top <= dds.thresh){
23042 startProc(el, "up");
23045 }else if(pt.x - r.left <= dds.thresh){
23047 startProc(el, "right");
23056 ddm.fireEvents = ddm.fireEvents.createSequence(onFire, ddm);
23057 ddm.stopDrag = ddm.stopDrag.createSequence(onStop, ddm);
23061 * Registers new overflow element(s) to auto scroll
23062 * @param {String/HTMLElement/Element/Array} el The id of or the element to be scrolled or an array of either
23064 register : function(el){
23065 if(el instanceof Array){
23066 for(var i = 0, len = el.length; i < len; i++) {
23067 this.register(el[i]);
23073 Roo.dd.ScrollManager.els = els;
23077 * Unregisters overflow element(s) so they are no longer scrolled
23078 * @param {String/HTMLElement/Element/Array} el The id of or the element to be removed or an array of either
23080 unregister : function(el){
23081 if(el instanceof Array){
23082 for(var i = 0, len = el.length; i < len; i++) {
23083 this.unregister(el[i]);
23092 * The number of pixels from the edge of a container the pointer needs to be to
23093 * trigger scrolling (defaults to 25)
23099 * The number of pixels to scroll in each scroll increment (defaults to 50)
23105 * The frequency of scrolls in milliseconds (defaults to 500)
23111 * True to animate the scroll (defaults to true)
23117 * The animation duration in seconds -
23118 * MUST BE less than Roo.dd.ScrollManager.frequency! (defaults to .4)
23124 * Manually trigger a cache refresh.
23126 refreshCache : function(){
23127 for(var id in els){
23128 if(typeof els[id] == 'object'){ // for people extending the object prototype
23129 els[id]._region = els[id].getRegion();
23136 * Ext JS Library 1.1.1
23137 * Copyright(c) 2006-2007, Ext JS, LLC.
23139 * Originally Released Under LGPL - original licence link has changed is not relivant.
23142 * <script type="text/javascript">
23147 * @class Roo.dd.Registry
23148 * Provides easy access to all drag drop components that are registered on a page. Items can be retrieved either
23149 * directly by DOM node id, or by passing in the drag drop event that occurred and looking up the event target.
23152 Roo.dd.Registry = function(){
23155 var autoIdSeed = 0;
23157 var getId = function(el, autogen){
23158 if(typeof el == "string"){
23162 if(!id && autogen !== false){
23163 id = "roodd-" + (++autoIdSeed);
23171 * Register a drag drop element
23172 * @param {String|HTMLElement} element The id or DOM node to register
23173 * @param {Object} data (optional) A custom data object that will be passed between the elements that are involved
23174 * in drag drop operations. You can populate this object with any arbitrary properties that your own code
23175 * knows how to interpret, plus there are some specific properties known to the Registry that should be
23176 * populated in the data object (if applicable):
23178 Value Description<br />
23179 --------- ------------------------------------------<br />
23180 handles Array of DOM nodes that trigger dragging<br />
23181 for the element being registered<br />
23182 isHandle True if the element passed in triggers<br />
23183 dragging itself, else false
23186 register : function(el, data){
23188 if(typeof el == "string"){
23189 el = document.getElementById(el);
23192 elements[getId(el)] = data;
23193 if(data.isHandle !== false){
23194 handles[data.ddel.id] = data;
23197 var hs = data.handles;
23198 for(var i = 0, len = hs.length; i < len; i++){
23199 handles[getId(hs[i])] = data;
23205 * Unregister a drag drop element
23206 * @param {String|HTMLElement} element The id or DOM node to unregister
23208 unregister : function(el){
23209 var id = getId(el, false);
23210 var data = elements[id];
23212 delete elements[id];
23214 var hs = data.handles;
23215 for(var i = 0, len = hs.length; i < len; i++){
23216 delete handles[getId(hs[i], false)];
23223 * Returns the handle registered for a DOM Node by id
23224 * @param {String|HTMLElement} id The DOM node or id to look up
23225 * @return {Object} handle The custom handle data
23227 getHandle : function(id){
23228 if(typeof id != "string"){ // must be element?
23231 return handles[id];
23235 * Returns the handle that is registered for the DOM node that is the target of the event
23236 * @param {Event} e The event
23237 * @return {Object} handle The custom handle data
23239 getHandleFromEvent : function(e){
23240 var t = Roo.lib.Event.getTarget(e);
23241 return t ? handles[t.id] : null;
23245 * Returns a custom data object that is registered for a DOM node by id
23246 * @param {String|HTMLElement} id The DOM node or id to look up
23247 * @return {Object} data The custom data
23249 getTarget : function(id){
23250 if(typeof id != "string"){ // must be element?
23253 return elements[id];
23257 * Returns a custom data object that is registered for the DOM node that is the target of the event
23258 * @param {Event} e The event
23259 * @return {Object} data The custom data
23261 getTargetFromEvent : function(e){
23262 var t = Roo.lib.Event.getTarget(e);
23263 return t ? elements[t.id] || handles[t.id] : null;
23268 * Ext JS Library 1.1.1
23269 * Copyright(c) 2006-2007, Ext JS, LLC.
23271 * Originally Released Under LGPL - original licence link has changed is not relivant.
23274 * <script type="text/javascript">
23279 * @class Roo.dd.StatusProxy
23280 * A specialized drag proxy that supports a drop status icon, {@link Roo.Layer} styles and auto-repair. This is the
23281 * default drag proxy used by all Roo.dd components.
23283 * @param {Object} config
23285 Roo.dd.StatusProxy = function(config){
23286 Roo.apply(this, config);
23287 this.id = this.id || Roo.id();
23288 this.el = new Roo.Layer({
23290 id: this.id, tag: "div", cls: "x-dd-drag-proxy "+this.dropNotAllowed, children: [
23291 {tag: "div", cls: "x-dd-drop-icon"},
23292 {tag: "div", cls: "x-dd-drag-ghost"}
23295 shadow: !config || config.shadow !== false
23297 this.ghost = Roo.get(this.el.dom.childNodes[1]);
23298 this.dropStatus = this.dropNotAllowed;
23301 Roo.dd.StatusProxy.prototype = {
23303 * @cfg {String} dropAllowed
23304 * The CSS class to apply to the status element when drop is allowed (defaults to "x-dd-drop-ok").
23306 dropAllowed : "x-dd-drop-ok",
23308 * @cfg {String} dropNotAllowed
23309 * The CSS class to apply to the status element when drop is not allowed (defaults to "x-dd-drop-nodrop").
23311 dropNotAllowed : "x-dd-drop-nodrop",
23314 * Updates the proxy's visual element to indicate the status of whether or not drop is allowed
23315 * over the current target element.
23316 * @param {String} cssClass The css class for the new drop status indicator image
23318 setStatus : function(cssClass){
23319 cssClass = cssClass || this.dropNotAllowed;
23320 if(this.dropStatus != cssClass){
23321 this.el.replaceClass(this.dropStatus, cssClass);
23322 this.dropStatus = cssClass;
23327 * Resets the status indicator to the default dropNotAllowed value
23328 * @param {Boolean} clearGhost True to also remove all content from the ghost, false to preserve it
23330 reset : function(clearGhost){
23331 this.el.dom.className = "x-dd-drag-proxy " + this.dropNotAllowed;
23332 this.dropStatus = this.dropNotAllowed;
23334 this.ghost.update("");
23339 * Updates the contents of the ghost element
23340 * @param {String} html The html that will replace the current innerHTML of the ghost element
23342 update : function(html){
23343 if(typeof html == "string"){
23344 this.ghost.update(html);
23346 this.ghost.update("");
23347 html.style.margin = "0";
23348 this.ghost.dom.appendChild(html);
23350 // ensure float = none set?? cant remember why though.
23351 var el = this.ghost.dom.firstChild;
23353 Roo.fly(el).setStyle('float', 'none');
23358 * Returns the underlying proxy {@link Roo.Layer}
23359 * @return {Roo.Layer} el
23361 getEl : function(){
23366 * Returns the ghost element
23367 * @return {Roo.Element} el
23369 getGhost : function(){
23375 * @param {Boolean} clear True to reset the status and clear the ghost contents, false to preserve them
23377 hide : function(clear){
23385 * Stops the repair animation if it's currently running
23388 if(this.anim && this.anim.isAnimated && this.anim.isAnimated()){
23394 * Displays this proxy
23401 * Force the Layer to sync its shadow and shim positions to the element
23408 * Causes the proxy to return to its position of origin via an animation. Should be called after an
23409 * invalid drop operation by the item being dragged.
23410 * @param {Array} xy The XY position of the element ([x, y])
23411 * @param {Function} callback The function to call after the repair is complete
23412 * @param {Object} scope The scope in which to execute the callback
23414 repair : function(xy, callback, scope){
23415 this.callback = callback;
23416 this.scope = scope;
23417 if(xy && this.animRepair !== false){
23418 this.el.addClass("x-dd-drag-repair");
23419 this.el.hideUnders(true);
23420 this.anim = this.el.shift({
23421 duration: this.repairDuration || .5,
23425 callback: this.afterRepair,
23429 this.afterRepair();
23434 afterRepair : function(){
23436 if(typeof this.callback == "function"){
23437 this.callback.call(this.scope || this);
23439 this.callback = null;
23444 * Ext JS Library 1.1.1
23445 * Copyright(c) 2006-2007, Ext JS, LLC.
23447 * Originally Released Under LGPL - original licence link has changed is not relivant.
23450 * <script type="text/javascript">
23454 * @class Roo.dd.DragSource
23455 * @extends Roo.dd.DDProxy
23456 * A simple class that provides the basic implementation needed to make any element draggable.
23458 * @param {String/HTMLElement/Element} el The container element
23459 * @param {Object} config
23461 Roo.dd.DragSource = function(el, config){
23462 this.el = Roo.get(el);
23463 this.dragData = {};
23465 Roo.apply(this, config);
23468 this.proxy = new Roo.dd.StatusProxy();
23471 Roo.dd.DragSource.superclass.constructor.call(this, this.el.dom, this.ddGroup || this.group,
23472 {dragElId : this.proxy.id, resizeFrame: false, isTarget: false, scroll: this.scroll === true});
23474 this.dragging = false;
23477 Roo.extend(Roo.dd.DragSource, Roo.dd.DDProxy, {
23479 * @cfg {String} dropAllowed
23480 * The CSS class returned to the drag source when drop is allowed (defaults to "x-dd-drop-ok").
23482 dropAllowed : "x-dd-drop-ok",
23484 * @cfg {String} dropNotAllowed
23485 * The CSS class returned to the drag source when drop is not allowed (defaults to "x-dd-drop-nodrop").
23487 dropNotAllowed : "x-dd-drop-nodrop",
23490 * Returns the data object associated with this drag source
23491 * @return {Object} data An object containing arbitrary data
23493 getDragData : function(e){
23494 return this.dragData;
23498 onDragEnter : function(e, id){
23499 var target = Roo.dd.DragDropMgr.getDDById(id);
23500 this.cachedTarget = target;
23501 if(this.beforeDragEnter(target, e, id) !== false){
23502 if(target.isNotifyTarget){
23503 var status = target.notifyEnter(this, e, this.dragData);
23504 this.proxy.setStatus(status);
23506 this.proxy.setStatus(this.dropAllowed);
23509 if(this.afterDragEnter){
23511 * An empty function by default, but provided so that you can perform a custom action
23512 * when the dragged item enters the drop target by providing an implementation.
23513 * @param {Roo.dd.DragDrop} target The drop target
23514 * @param {Event} e The event object
23515 * @param {String} id The id of the dragged element
23516 * @method afterDragEnter
23518 this.afterDragEnter(target, e, id);
23524 * An empty function by default, but provided so that you can perform a custom action
23525 * before the dragged item enters the drop target and optionally cancel the onDragEnter.
23526 * @param {Roo.dd.DragDrop} target The drop target
23527 * @param {Event} e The event object
23528 * @param {String} id The id of the dragged element
23529 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
23531 beforeDragEnter : function(target, e, id){
23536 alignElWithMouse: function() {
23537 Roo.dd.DragSource.superclass.alignElWithMouse.apply(this, arguments);
23542 onDragOver : function(e, id){
23543 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
23544 if(this.beforeDragOver(target, e, id) !== false){
23545 if(target.isNotifyTarget){
23546 var status = target.notifyOver(this, e, this.dragData);
23547 this.proxy.setStatus(status);
23550 if(this.afterDragOver){
23552 * An empty function by default, but provided so that you can perform a custom action
23553 * while the dragged item is over the drop target by providing an implementation.
23554 * @param {Roo.dd.DragDrop} target The drop target
23555 * @param {Event} e The event object
23556 * @param {String} id The id of the dragged element
23557 * @method afterDragOver
23559 this.afterDragOver(target, e, id);
23565 * An empty function by default, but provided so that you can perform a custom action
23566 * while the dragged item is over the drop target and optionally cancel the onDragOver.
23567 * @param {Roo.dd.DragDrop} target The drop target
23568 * @param {Event} e The event object
23569 * @param {String} id The id of the dragged element
23570 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
23572 beforeDragOver : function(target, e, id){
23577 onDragOut : function(e, id){
23578 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
23579 if(this.beforeDragOut(target, e, id) !== false){
23580 if(target.isNotifyTarget){
23581 target.notifyOut(this, e, this.dragData);
23583 this.proxy.reset();
23584 if(this.afterDragOut){
23586 * An empty function by default, but provided so that you can perform a custom action
23587 * after the dragged item is dragged out of the target without dropping.
23588 * @param {Roo.dd.DragDrop} target The drop target
23589 * @param {Event} e The event object
23590 * @param {String} id The id of the dragged element
23591 * @method afterDragOut
23593 this.afterDragOut(target, e, id);
23596 this.cachedTarget = null;
23600 * An empty function by default, but provided so that you can perform a custom action before the dragged
23601 * item is dragged out of the target without dropping, and optionally cancel the onDragOut.
23602 * @param {Roo.dd.DragDrop} target The drop target
23603 * @param {Event} e The event object
23604 * @param {String} id The id of the dragged element
23605 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
23607 beforeDragOut : function(target, e, id){
23612 onDragDrop : function(e, id){
23613 var target = this.cachedTarget || Roo.dd.DragDropMgr.getDDById(id);
23614 if(this.beforeDragDrop(target, e, id) !== false){
23615 if(target.isNotifyTarget){
23616 if(target.notifyDrop(this, e, this.dragData)){ // valid drop?
23617 this.onValidDrop(target, e, id);
23619 this.onInvalidDrop(target, e, id);
23622 this.onValidDrop(target, e, id);
23625 if(this.afterDragDrop){
23627 * An empty function by default, but provided so that you can perform a custom action
23628 * after a valid drag drop has occurred by providing an implementation.
23629 * @param {Roo.dd.DragDrop} target The drop target
23630 * @param {Event} e The event object
23631 * @param {String} id The id of the dropped element
23632 * @method afterDragDrop
23634 this.afterDragDrop(target, e, id);
23637 delete this.cachedTarget;
23641 * An empty function by default, but provided so that you can perform a custom action before the dragged
23642 * item is dropped onto the target and optionally cancel the onDragDrop.
23643 * @param {Roo.dd.DragDrop} target The drop target
23644 * @param {Event} e The event object
23645 * @param {String} id The id of the dragged element
23646 * @return {Boolean} isValid True if the drag drop event is valid, else false to cancel
23648 beforeDragDrop : function(target, e, id){
23653 onValidDrop : function(target, e, id){
23655 if(this.afterValidDrop){
23657 * An empty function by default, but provided so that you can perform a custom action
23658 * after a valid drop has occurred by providing an implementation.
23659 * @param {Object} target The target DD
23660 * @param {Event} e The event object
23661 * @param {String} id The id of the dropped element
23662 * @method afterInvalidDrop
23664 this.afterValidDrop(target, e, id);
23669 getRepairXY : function(e, data){
23670 return this.el.getXY();
23674 onInvalidDrop : function(target, e, id){
23675 this.beforeInvalidDrop(target, e, id);
23676 if(this.cachedTarget){
23677 if(this.cachedTarget.isNotifyTarget){
23678 this.cachedTarget.notifyOut(this, e, this.dragData);
23680 this.cacheTarget = null;
23682 this.proxy.repair(this.getRepairXY(e, this.dragData), this.afterRepair, this);
23684 if(this.afterInvalidDrop){
23686 * An empty function by default, but provided so that you can perform a custom action
23687 * after an invalid drop has occurred by providing an implementation.
23688 * @param {Event} e The event object
23689 * @param {String} id The id of the dropped element
23690 * @method afterInvalidDrop
23692 this.afterInvalidDrop(e, id);
23697 afterRepair : function(){
23699 this.el.highlight(this.hlColor || "c3daf9");
23701 this.dragging = false;
23705 * An empty function by default, but provided so that you can perform a custom action after an invalid
23706 * drop has occurred.
23707 * @param {Roo.dd.DragDrop} target The drop target
23708 * @param {Event} e The event object
23709 * @param {String} id The id of the dragged element
23710 * @return {Boolean} isValid True if the invalid drop should proceed, else false to cancel
23712 beforeInvalidDrop : function(target, e, id){
23717 handleMouseDown : function(e){
23718 if(this.dragging) {
23721 var data = this.getDragData(e);
23722 if(data && this.onBeforeDrag(data, e) !== false){
23723 this.dragData = data;
23725 Roo.dd.DragSource.superclass.handleMouseDown.apply(this, arguments);
23730 * An empty function by default, but provided so that you can perform a custom action before the initial
23731 * drag event begins and optionally cancel it.
23732 * @param {Object} data An object containing arbitrary data to be shared with drop targets
23733 * @param {Event} e The event object
23734 * @return {Boolean} isValid True if the drag event is valid, else false to cancel
23736 onBeforeDrag : function(data, e){
23741 * An empty function by default, but provided so that you can perform a custom action once the initial
23742 * drag event has begun. The drag cannot be canceled from this function.
23743 * @param {Number} x The x position of the click on the dragged object
23744 * @param {Number} y The y position of the click on the dragged object
23746 onStartDrag : Roo.emptyFn,
23748 // private - YUI override
23749 startDrag : function(x, y){
23750 this.proxy.reset();
23751 this.dragging = true;
23752 this.proxy.update("");
23753 this.onInitDrag(x, y);
23758 onInitDrag : function(x, y){
23759 var clone = this.el.dom.cloneNode(true);
23760 clone.id = Roo.id(); // prevent duplicate ids
23761 this.proxy.update(clone);
23762 this.onStartDrag(x, y);
23767 * Returns the drag source's underlying {@link Roo.dd.StatusProxy}
23768 * @return {Roo.dd.StatusProxy} proxy The StatusProxy
23770 getProxy : function(){
23775 * Hides the drag source's {@link Roo.dd.StatusProxy}
23777 hideProxy : function(){
23779 this.proxy.reset(true);
23780 this.dragging = false;
23784 triggerCacheRefresh : function(){
23785 Roo.dd.DDM.refreshCache(this.groups);
23788 // private - override to prevent hiding
23789 b4EndDrag: function(e) {
23792 // private - override to prevent moving
23793 endDrag : function(e){
23794 this.onEndDrag(this.dragData, e);
23798 onEndDrag : function(data, e){
23801 // private - pin to cursor
23802 autoOffset : function(x, y) {
23803 this.setDelta(-12, -20);
23807 * Ext JS Library 1.1.1
23808 * Copyright(c) 2006-2007, Ext JS, LLC.
23810 * Originally Released Under LGPL - original licence link has changed is not relivant.
23813 * <script type="text/javascript">
23818 * @class Roo.dd.DropTarget
23819 * @extends Roo.dd.DDTarget
23820 * A simple class that provides the basic implementation needed to make any element a drop target that can have
23821 * draggable items dropped onto it. The drop has no effect until an implementation of notifyDrop is provided.
23823 * @param {String/HTMLElement/Element} el The container element
23824 * @param {Object} config
23826 Roo.dd.DropTarget = function(el, config){
23827 this.el = Roo.get(el);
23829 var listeners = false; ;
23830 if (config && config.listeners) {
23831 listeners= config.listeners;
23832 delete config.listeners;
23834 Roo.apply(this, config);
23836 if(this.containerScroll){
23837 Roo.dd.ScrollManager.register(this.el);
23841 * @scope Roo.dd.DropTarget
23846 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the source is now over the
23847 * target. This default implementation adds the CSS class specified by overClass (if any) to the drop element
23848 * and returns the dropAllowed config value. This method should be overridden if drop validation is required.
23850 * IMPORTANT : it should set this.valid to true|false
23852 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
23853 * @param {Event} e The event
23854 * @param {Object} data An object containing arbitrary data supplied by the drag source
23860 * The function a {@link Roo.dd.DragSource} calls continuously while it is being dragged over the target.
23861 * This method will be called on every mouse movement while the drag source is over the drop target.
23862 * This default implementation simply returns the dropAllowed config value.
23864 * IMPORTANT : it should set this.valid to true|false
23866 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
23867 * @param {Event} e The event
23868 * @param {Object} data An object containing arbitrary data supplied by the drag source
23874 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the source has been dragged
23875 * out of the target without dropping. This default implementation simply removes the CSS class specified by
23876 * overClass (if any) from the drop element.
23879 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
23880 * @param {Event} e The event
23881 * @param {Object} data An object containing arbitrary data supplied by the drag source
23887 * The function a {@link Roo.dd.DragSource} calls once to notify this drop target that the dragged item has
23888 * been dropped on it. This method has no default implementation and returns false, so you must provide an
23889 * implementation that does something to process the drop event and returns true so that the drag source's
23890 * repair action does not run.
23892 * IMPORTANT : it should set this.success
23894 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
23895 * @param {Event} e The event
23896 * @param {Object} data An object containing arbitrary data supplied by the drag source
23902 Roo.dd.DropTarget.superclass.constructor.call( this,
23904 this.ddGroup || this.group,
23907 listeners : listeners || {}
23915 Roo.extend(Roo.dd.DropTarget, Roo.dd.DDTarget, {
23917 * @cfg {String} overClass
23918 * The CSS class applied to the drop target element while the drag source is over it (defaults to "").
23921 * @cfg {String} ddGroup
23922 * The drag drop group to handle drop events for
23926 * @cfg {String} dropAllowed
23927 * The CSS class returned to the drag source when drop is allowed (defaults to "x-dd-drop-ok").
23929 dropAllowed : "x-dd-drop-ok",
23931 * @cfg {String} dropNotAllowed
23932 * The CSS class returned to the drag source when drop is not allowed (defaults to "x-dd-drop-nodrop").
23934 dropNotAllowed : "x-dd-drop-nodrop",
23936 * @cfg {boolean} success
23937 * set this after drop listener..
23941 * @cfg {boolean|String} valid true/false or string (ok-add/ok-sub/ok/nodrop)
23942 * if the drop point is valid for over/enter..
23949 isNotifyTarget : true,
23954 notifyEnter : function(dd, e, data)
23957 this.fireEvent('enter', dd, e, data);
23958 if(this.overClass){
23959 this.el.addClass(this.overClass);
23961 return typeof(this.valid) == 'string' ? 'x-dd-drop-' + this.valid : (
23962 this.valid ? this.dropAllowed : this.dropNotAllowed
23969 notifyOver : function(dd, e, data)
23972 this.fireEvent('over', dd, e, data);
23973 return typeof(this.valid) == 'string' ? 'x-dd-drop-' + this.valid : (
23974 this.valid ? this.dropAllowed : this.dropNotAllowed
23981 notifyOut : function(dd, e, data)
23983 this.fireEvent('out', dd, e, data);
23984 if(this.overClass){
23985 this.el.removeClass(this.overClass);
23992 notifyDrop : function(dd, e, data)
23994 this.success = false;
23995 this.fireEvent('drop', dd, e, data);
23996 return this.success;
24000 * Ext JS Library 1.1.1
24001 * Copyright(c) 2006-2007, Ext JS, LLC.
24003 * Originally Released Under LGPL - original licence link has changed is not relivant.
24006 * <script type="text/javascript">
24011 * @class Roo.dd.DragZone
24012 * @extends Roo.dd.DragSource
24013 * This class provides a container DD instance that proxies for multiple child node sources.<br />
24014 * By default, this class requires that draggable child nodes are registered with {@link Roo.dd.Registry}.
24016 * @param {String/HTMLElement/Element} el The container element
24017 * @param {Object} config
24019 Roo.dd.DragZone = function(el, config){
24020 Roo.dd.DragZone.superclass.constructor.call(this, el, config);
24021 if(this.containerScroll){
24022 Roo.dd.ScrollManager.register(this.el);
24026 Roo.extend(Roo.dd.DragZone, Roo.dd.DragSource, {
24028 * @cfg {Boolean} containerScroll True to register this container with the Scrollmanager
24029 * for auto scrolling during drag operations.
24032 * @cfg {String} hlColor The color to use when visually highlighting the drag source in the afterRepair
24033 * method after a failed drop (defaults to "c3daf9" - light blue)
24037 * Called when a mousedown occurs in this container. Looks in {@link Roo.dd.Registry}
24038 * for a valid target to drag based on the mouse down. Override this method
24039 * to provide your own lookup logic (e.g. finding a child by class name). Make sure your returned
24040 * object has a "ddel" attribute (with an HTML Element) for other functions to work.
24041 * @param {EventObject} e The mouse down event
24042 * @return {Object} The dragData
24044 getDragData : function(e){
24045 return Roo.dd.Registry.getHandleFromEvent(e);
24049 * Called once drag threshold has been reached to initialize the proxy element. By default, it clones the
24050 * this.dragData.ddel
24051 * @param {Number} x The x position of the click on the dragged object
24052 * @param {Number} y The y position of the click on the dragged object
24053 * @return {Boolean} true to continue the drag, false to cancel
24055 onInitDrag : function(x, y){
24056 this.proxy.update(this.dragData.ddel.cloneNode(true));
24057 this.onStartDrag(x, y);
24062 * Called after a repair of an invalid drop. By default, highlights this.dragData.ddel
24064 afterRepair : function(){
24066 Roo.Element.fly(this.dragData.ddel).highlight(this.hlColor || "c3daf9");
24068 this.dragging = false;
24072 * Called before a repair of an invalid drop to get the XY to animate to. By default returns
24073 * the XY of this.dragData.ddel
24074 * @param {EventObject} e The mouse up event
24075 * @return {Array} The xy location (e.g. [100, 200])
24077 getRepairXY : function(e){
24078 return Roo.Element.fly(this.dragData.ddel).getXY();
24082 * Ext JS Library 1.1.1
24083 * Copyright(c) 2006-2007, Ext JS, LLC.
24085 * Originally Released Under LGPL - original licence link has changed is not relivant.
24088 * <script type="text/javascript">
24091 * @class Roo.dd.DropZone
24092 * @extends Roo.dd.DropTarget
24093 * This class provides a container DD instance that proxies for multiple child node targets.<br />
24094 * By default, this class requires that child nodes accepting drop are registered with {@link Roo.dd.Registry}.
24096 * @param {String/HTMLElement/Element} el The container element
24097 * @param {Object} config
24099 Roo.dd.DropZone = function(el, config){
24100 Roo.dd.DropZone.superclass.constructor.call(this, el, config);
24103 Roo.extend(Roo.dd.DropZone, Roo.dd.DropTarget, {
24105 * Returns a custom data object associated with the DOM node that is the target of the event. By default
24106 * this looks up the event target in the {@link Roo.dd.Registry}, although you can override this method to
24107 * provide your own custom lookup.
24108 * @param {Event} e The event
24109 * @return {Object} data The custom data
24111 getTargetFromEvent : function(e){
24112 return Roo.dd.Registry.getTargetFromEvent(e);
24116 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has entered a drop node
24117 * that it has registered. This method has no default implementation and should be overridden to provide
24118 * node-specific processing if necessary.
24119 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
24120 * {@link #getTargetFromEvent} for this node)
24121 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
24122 * @param {Event} e The event
24123 * @param {Object} data An object containing arbitrary data supplied by the drag source
24125 onNodeEnter : function(n, dd, e, data){
24130 * Called internally while the DropZone determines that a {@link Roo.dd.DragSource} is over a drop node
24131 * that it has registered. The default implementation returns this.dropNotAllowed, so it should be
24132 * overridden to provide the proper feedback.
24133 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
24134 * {@link #getTargetFromEvent} for this node)
24135 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
24136 * @param {Event} e The event
24137 * @param {Object} data An object containing arbitrary data supplied by the drag source
24138 * @return {String} status The CSS class that communicates the drop status back to the source so that the
24139 * underlying {@link Roo.dd.StatusProxy} can be updated
24141 onNodeOver : function(n, dd, e, data){
24142 return this.dropAllowed;
24146 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dragged out of
24147 * the drop node without dropping. This method has no default implementation and should be overridden to provide
24148 * node-specific processing if necessary.
24149 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
24150 * {@link #getTargetFromEvent} for this node)
24151 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
24152 * @param {Event} e The event
24153 * @param {Object} data An object containing arbitrary data supplied by the drag source
24155 onNodeOut : function(n, dd, e, data){
24160 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dropped onto
24161 * the drop node. The default implementation returns false, so it should be overridden to provide the
24162 * appropriate processing of the drop event and return true so that the drag source's repair action does not run.
24163 * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
24164 * {@link #getTargetFromEvent} for this node)
24165 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
24166 * @param {Event} e The event
24167 * @param {Object} data An object containing arbitrary data supplied by the drag source
24168 * @return {Boolean} True if the drop was valid, else false
24170 onNodeDrop : function(n, dd, e, data){
24175 * Called internally while the DropZone determines that a {@link Roo.dd.DragSource} is being dragged over it,
24176 * but not over any of its registered drop nodes. The default implementation returns this.dropNotAllowed, so
24177 * it should be overridden to provide the proper feedback if necessary.
24178 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
24179 * @param {Event} e The event
24180 * @param {Object} data An object containing arbitrary data supplied by the drag source
24181 * @return {String} status The CSS class that communicates the drop status back to the source so that the
24182 * underlying {@link Roo.dd.StatusProxy} can be updated
24184 onContainerOver : function(dd, e, data){
24185 return this.dropNotAllowed;
24189 * Called internally when the DropZone determines that a {@link Roo.dd.DragSource} has been dropped on it,
24190 * but not on any of its registered drop nodes. The default implementation returns false, so it should be
24191 * overridden to provide the appropriate processing of the drop event if you need the drop zone itself to
24192 * be able to accept drops. It should return true when valid so that the drag source's repair action does not run.
24193 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
24194 * @param {Event} e The event
24195 * @param {Object} data An object containing arbitrary data supplied by the drag source
24196 * @return {Boolean} True if the drop was valid, else false
24198 onContainerDrop : function(dd, e, data){
24203 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the source is now over
24204 * the zone. The default implementation returns this.dropNotAllowed and expects that only registered drop
24205 * nodes can process drag drop operations, so if you need the drop zone itself to be able to process drops
24206 * you should override this method and provide a custom implementation.
24207 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
24208 * @param {Event} e The event
24209 * @param {Object} data An object containing arbitrary data supplied by the drag source
24210 * @return {String} status The CSS class that communicates the drop status back to the source so that the
24211 * underlying {@link Roo.dd.StatusProxy} can be updated
24213 notifyEnter : function(dd, e, data){
24214 return this.dropNotAllowed;
24218 * The function a {@link Roo.dd.DragSource} calls continuously while it is being dragged over the drop zone.
24219 * This method will be called on every mouse movement while the drag source is over the drop zone.
24220 * It will call {@link #onNodeOver} while the drag source is over a registered node, and will also automatically
24221 * delegate to the appropriate node-specific methods as necessary when the drag source enters and exits
24222 * registered nodes ({@link #onNodeEnter}, {@link #onNodeOut}). If the drag source is not currently over a
24223 * registered node, it will call {@link #onContainerOver}.
24224 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
24225 * @param {Event} e The event
24226 * @param {Object} data An object containing arbitrary data supplied by the drag source
24227 * @return {String} status The CSS class that communicates the drop status back to the source so that the
24228 * underlying {@link Roo.dd.StatusProxy} can be updated
24230 notifyOver : function(dd, e, data){
24231 var n = this.getTargetFromEvent(e);
24232 if(!n){ // not over valid drop target
24233 if(this.lastOverNode){
24234 this.onNodeOut(this.lastOverNode, dd, e, data);
24235 this.lastOverNode = null;
24237 return this.onContainerOver(dd, e, data);
24239 if(this.lastOverNode != n){
24240 if(this.lastOverNode){
24241 this.onNodeOut(this.lastOverNode, dd, e, data);
24243 this.onNodeEnter(n, dd, e, data);
24244 this.lastOverNode = n;
24246 return this.onNodeOver(n, dd, e, data);
24250 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the source has been dragged
24251 * out of the zone without dropping. If the drag source is currently over a registered node, the notification
24252 * will be delegated to {@link #onNodeOut} for node-specific handling, otherwise it will be ignored.
24253 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop target
24254 * @param {Event} e The event
24255 * @param {Object} data An object containing arbitrary data supplied by the drag zone
24257 notifyOut : function(dd, e, data){
24258 if(this.lastOverNode){
24259 this.onNodeOut(this.lastOverNode, dd, e, data);
24260 this.lastOverNode = null;
24265 * The function a {@link Roo.dd.DragSource} calls once to notify this drop zone that the dragged item has
24266 * been dropped on it. The drag zone will look up the target node based on the event passed in, and if there
24267 * is a node registered for that event, it will delegate to {@link #onNodeDrop} for node-specific handling,
24268 * otherwise it will call {@link #onContainerDrop}.
24269 * @param {Roo.dd.DragSource} source The drag source that was dragged over this drop zone
24270 * @param {Event} e The event
24271 * @param {Object} data An object containing arbitrary data supplied by the drag source
24272 * @return {Boolean} True if the drop was valid, else false
24274 notifyDrop : function(dd, e, data){
24275 if(this.lastOverNode){
24276 this.onNodeOut(this.lastOverNode, dd, e, data);
24277 this.lastOverNode = null;
24279 var n = this.getTargetFromEvent(e);
24281 this.onNodeDrop(n, dd, e, data) :
24282 this.onContainerDrop(dd, e, data);
24286 triggerCacheRefresh : function(){
24287 Roo.dd.DDM.refreshCache(this.groups);